summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorGabriel Schneider <[email protected]>2026-11-06 00:02:06 -0300
committerGabriel Schneider <[email protected]>2026-11-06 01:21:34 -0300
commit423440f25b4b23b56162008bba35218d438767fe (patch)
treea7b06a88c7a55308e7e906ff49fa264a1fd147cf
parent94ca47f225632fefc8f688c0c0822d25d6a5db1e (diff)
downloadpardes-423440f25b4b23b56162008bba35218d438767fe.tar.gz
pardes-423440f25b4b23b56162008bba35218d438767fe.zip
kinds #2, a pane of a kind is one slot and image is a kind compiled in: src/kinds/pardes_addon.h is the kinds' C ABI (the cell, the window a kind paints, placements and the tag prefix it hands back, keys, the mouse, pa_api of six functions over the pane's arena, words, the head and pa_ops of paint and sixteen optional functions), translated once by the build into the core's records, never mirrored; src/Kind.zig is the core's side: the kinds this process has (a registry with the checks a load makes: the head's size and abi major, a paint, a name, words, leaders and extensions none else has), a pane's Slot (the kind's state and arena, its path, the art bytes Petscii, Palette and Ascii set, its tick deadline and jobs) and the addon arm at the sites: Look and the initial file by extension, draw (cells into the grid, placements keyed by serial and the kind's key), the tag prefix from a paint over no cells, nextWake and the step (ticks, jobs' answers landing on the loop), close, Recent, paneDir, /index's kind word; a dump writes a slot by hand (kind name and version, path, where, art, the kind's own record) and loads it through the kind's open and load, or as a placeholder that keeps the record when the kind is not here; image.zig's pane is now a static pa_ops (open refuses what it cannot read, the decode a job whose answer lands at a step instead of a thread polled by draw, one placement fitted by the frontend, its record the file's bytes), Pane.image is Pane.addon, and the three art words act on the slot; no golden changes (images.snap and tagbottomimage.snap pass, the tag prefix and the placement key are the same bytes); tests: the image dump test, the Petscii/Palette/Ascii ctl tests, the image tag-prefix test and fs_namespace's decode test rewritten on the slot (the decode now lands at the step after the open), plus a registry test; gates: core-test 960/960 on both, unit-test 1487/1488 tui and 1531/1532 gui, behaviour-test 244/244, pane-test 171/172, snap all ok, process-test 0 of 37 failed on both
Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_016Y9MNAtZenFv4weoMD3cge
-rw-r--r--build.zig6
-rw-r--r--src/Core.zig53
-rw-r--r--src/Effect.zig2
-rw-r--r--src/Kind.zig997
-rw-r--r--src/Output.zig4
-rw-r--r--src/Store.zig2
-rw-r--r--src/body_layer.zig2
-rw-r--r--src/builtins.zig20
-rw-r--r--src/draw.zig22
-rw-r--r--src/dump.zig2
-rw-r--r--src/edit.zig2
-rw-r--r--src/fs.zig2
-rw-r--r--src/image.zig238
-rw-r--r--src/keys.zig8
-rw-r--r--src/kinds/pardes_addon.h261
-rw-r--r--src/look.zig40
-rw-r--r--src/macos.zig2
-rw-r--r--src/main.zig2
-rw-r--r--src/ninep/ctl.zig36
-rw-r--r--src/ninep/pane.zig4
-rw-r--r--src/panes.zig14
-rw-r--r--src/pardes.zig1
-rw-r--r--src/tagline.zig2
-rw-r--r--test/fs_namespace.zig15
-rw-r--r--test/mode.zig4
-rw-r--r--test/panes.zig13
26 files changed, 1515 insertions, 239 deletions
diff --git a/build.zig b/build.zig
index e1544e74..7b1967c2 100644
--- a/build.zig
+++ b/build.zig
@@ -823,7 +823,11 @@ pub fn build(b: *std.Build) void {
// One call per module instead of one line per module per dependency, and
// BEFORE the fold below, which reads what these imports put in the table.
+ // The kinds' C ABI (src/kinds/pardes_addon.h), translated once: the core's
+ // records are the header's, never a mirror of it.
+ const kind_mod = b.addTranslateC(.{ .root_source_file = b.path("src/kinds/pardes_addon.h"), .target = target, .optimize = optimize }).createModule();
for (core_mods) |m| wireCore(m, .{
+ .kind = kind_mod,
.themes = themes_mod,
.tree_sitter = ts_mod,
.ts_libs = ts_libs.items,
@@ -1899,6 +1903,7 @@ fn vendoredThemes(b: *std.Build, io: std.Io) []const []const u8 {
}
fn wireCore(m: *std.Build.Module, d: struct {
+ kind: ?*std.Build.Module = null,
themes: ?*std.Build.Module = null,
tree_sitter: ?*std.Build.Module = null,
ts_libs: []const *std.Build.Step.Compile = &.{},
@@ -1913,6 +1918,7 @@ fn wireCore(m: *std.Build.Module, d: struct {
wuffs: ?*std.Build.Module = null,
xitdb: ?*std.Build.Module = null,
}) void {
+ if (d.kind) |x| m.addImport("pardes_addon", x);
if (d.themes) |x| m.addImport("generated_themes", x);
if (d.tree_sitter) |x| m.addImport("tree-sitter", x);
for (d.ts_libs) |lib| m.linkLibrary(lib);
diff --git a/src/Core.zig b/src/Core.zig
index 76f59247..54f0233e 100644
--- a/src/Core.zig
+++ b/src/Core.zig
@@ -508,8 +508,8 @@ fn initSession(gpa: std.mem.Allocator, opts: Options) !*Pardes {
const opened = initial_doc: {
if (comptime pdf_enabled) if (look.isPdfPath(path))
break :initial_doc pardes.panes.Pdf.openPane(p, 0, path, opts.file_line, .last);
- if (look.isImagePath(path))
- break :initial_doc pardes.panes.Image.create(p, 0, path, &.{});
+ if (pardes.Kind.forPath(path)) |kind|
+ break :initial_doc pardes.Kind.openFile(p, 0, kind, path);
break :initial_doc pardes.panes.File.open(p, 0, path, opts.file_line);
};
if (opened) |_| {} else |err| {
@@ -660,11 +660,11 @@ pub fn noteClosed(p: *Pardes, pane: *const Pane) void {
pub const RecentPlace = struct { path: []const u8, line: u32, col: u32, aline: u32 = 0, acol: u32 = 0 };
/// Where a pane is, as Recent keeps it: a file's dot, a PDF's page
-/// (`:page:1`), an image's path alone (line 0). Null for any other.
+/// (`:page:1`), a kind's pane's path alone (line 0). Null for any other.
pub fn recentPlace(pane: *const Pane) ?RecentPlace {
if (recentDot(pane)) |d| return .{ .path = d.path, .line = d.line, .col = d.col, .aline = d.aline, .acol = d.acol };
if (pane.pdfPath()) |path| return .{ .path = path, .line = @intCast(pane.pdfPage().? + 1), .col = 1 };
- if (pane.image) |iv| return .{ .path = iv.path, .line = 0, .col = 0 };
+ if (pane.addon) |k| if (k.path.len > 0) return .{ .path = k.path, .line = 0, .col = 0 };
return null;
}
@@ -1635,6 +1635,8 @@ pub fn update(p: *Pardes, ev: Event) void {
look.advanceLookHover(p);
},
}
+ // Each kind's pane whose time has come steps, and its jobs' answers land.
+ pardes.Kind.step(p);
// Each pane's places find a frame's more on a tick, and on any other
// step the ones an edit or a scroll left unfound in the view.
for (p.panes) |slot| if (slot) |pane| pane.places.settle(p, pane, ev == .tick);
@@ -1924,7 +1926,8 @@ pub fn nextWake(p: *const Pardes) ?u64 {
// Places still to find resume on the next frame; a picture being
// decoded is looked for.
for (p.panes) |slot| if (slot) |pane| if (pane.places.busy(pane)) return next;
- for (p.panes) |slot| if (slot) |pane| if (pane.image) |iv| if (iv.decoder != null) return next;
+ const kinds = pardes.Kind.wake(p);
+ if (kinds) |due| if (due <= next) return next;
// A PDF page being rendered on a lane lands on the frame after it is done.
if (comptime pdf_enabled) for (p.panes) |slot| if (slot) |pane| if (pane.pdf) |st| if (pardes.panes.Pdf.rendering(st)) return next;
// A markdown text's tables still being read from the top (Tables.zig).
@@ -1965,6 +1968,11 @@ pub fn nextWake(p: *const Pardes) ?u64 {
frames = if (frames) |soonest| @min(soonest, wait) else wait;
}
};
+ // A kind's next tick (Kind.zig).
+ if (kinds) |due| {
+ const wait = @max(1, (due -| p.clock.stepped_ns + frame_ns - 1) / frame_ns);
+ frames = if (frames) |soonest| @min(soonest, wait) else wait;
+ }
return if (frames) |n| p.clock.stepped_ns + n * frame_ns else null;
}
@@ -2461,7 +2469,7 @@ test "Filter is ordered after Del and toggles only its terminal or +Pager pane"
try testing.expect(!first.tty_filter);
const doc_id = p.freeSlot().?;
- const doc = try pardes.panes.Image.create(p, doc_id, "/tmp/filter-inert.ppm", &.{});
+ const doc = try pardes.Kind.open(p, doc_id, &image.kind, "/tmp/filter-inert.ppm", "");
try testing.expect(!doc.tty_filter);
try testing.expect(p.executeBuiltinLine(doc_id, "Filter"));
try testing.expect(!doc.tty_filter);
@@ -2631,8 +2639,7 @@ test "unknown Exec from a document runs as a command pane in its directory, type
// A terminal free at a prompt in the same directory is not borrowed.
p.setCwd(0, "/tmp/pardes-image-dir");
- const image_doc = try p.newDocPane(1);
- image_doc.image = .{ .path = try gpa.dupe(u8, "/tmp/pardes-image-dir/pic.ppm") };
+ const image_doc = try pardes.Kind.open(p, 1, &image.kind, "/tmp/pardes-image-dir/pic.ppm", null);
try std.testing.expectEqualStrings("/tmp/pardes-image-dir", Pardes.paneDir(image_doc));
const dst = exec.execute(p, 1, "echo image-fallback") orelse return error.ExecFoundNowhereToRun;
try std.testing.expect(dst != 0 and dst != 1);
@@ -2686,8 +2693,7 @@ test "a command of several lines keeps its tag one row, and its echo does not st
const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 100, .rows = 30 });
defer p.deinit();
while (p.nextEffect()) |_| {}
- const doc = try p.newDocPane(1);
- doc.image = .{ .path = try gpa.dupe(u8, "/tmp/pic.ppm") };
+ _ = try pardes.Kind.open(p, 1, &image.kind, "/tmp/pic.ppm", null);
const two = "def greet(name):\n return name\n\nprint(greet(\"x\"))\n";
const dst = exec.execute(p, 1, two) orelse return error.NoCommandPane;
while (p.nextEffect()) |_| {}
@@ -3035,8 +3041,7 @@ test "a command pane shows how its command ended, and the next command there run
defer p.deinit();
while (p.nextEffect()) |_| {}
p.setCwd(0, "/tmp/pardes-cmd");
- const doc = try p.newDocPane(1);
- doc.image = .{ .path = try gpa.dupe(u8, "/tmp/pardes-cmd/pic.ppm") };
+ _ = try pardes.Kind.open(p, 1, &image.kind, "/tmp/pardes-cmd/pic.ppm", null);
const dst = exec.execute(p, 1, "make -j8") orelse return error.NoCommandPane;
while (p.nextEffect()) |_| {}
@@ -3136,14 +3141,8 @@ test "image dump restores source bytes renderer choices and exact custom tail" {
p.panes[0] = null;
const source = "\x00embedded image bytes\xff";
- const raw = try p.image_gpa.dupe(u8, source);
- const pane = pardes.panes.Image.create(p, 0, "/missing/restored-image.ppm", raw) catch |err| {
- p.image_gpa.free(raw);
- return err;
- };
- pane.image.?.glyph_art = true;
- pane.image.?.pmode = .terminal;
- pane.image.?.ascii = false;
+ const pane = try pardes.Kind.open(p, 0, &image.kind, "/missing/restored-image.ppm", source);
+ pane.addon.?.art = .{ .glyph = true, .palette = .terminal, .ascii = false };
if (pane.tag.own) |own| p.gpa.free(own);
pane.tag.own = try p.gpa.dupe(u8, " Keep Del");
try dump.dumpState(p);
@@ -3151,18 +3150,22 @@ test "image dump restores source bytes renderer choices and exact custom tail" {
const restored = try dump.initFromDump(gpa, .{ .tty_only = true }, p.dump_out.?);
defer restored.deinit();
const restored_pane = restored.panes[0].?;
- try std.testing.expect(restored_pane.image.?.glyph_art);
- try std.testing.expectEqual(image.PaletteMode.terminal, restored_pane.image.?.pmode);
- try std.testing.expect(!restored_pane.image.?.ascii);
+ const art = restored_pane.addon.?.art;
+ try std.testing.expect(art.glyph);
+ try std.testing.expectEqual(image.PaletteMode.terminal, art.palette);
+ try std.testing.expect(!art.ascii);
try std.testing.expect(restored_pane.tag.own != null);
try std.testing.expectEqualStrings(" Keep Del", tagline.curTail(restored_pane));
- try std.testing.expectEqualSlices(u8, source, restored_pane.image.?.raw);
+ var kept: [64]u8 = undefined;
+ const slot = restored_pane.addon.?;
+ try std.testing.expectEqualSlices(u8, source, kept[0..image.kind.dump.?(slot.st, &kept, kept.len)]);
// And dumped again, its bytes still there.
try dump.dumpState(restored);
const again = try dump.load(gpa, .{ .tty_only = true }, restored.dump_out.?, null);
defer again.deinit();
- try std.testing.expectEqualSlices(u8, source, again.panes[0].?.image.?.raw);
+ const again_slot = again.panes[0].?.addon.?;
+ try std.testing.expectEqualSlices(u8, source, kept[0..image.kind.dump.?(again_slot.st, &kept, kept.len)]);
}
test "a terminal its program gave back takes command lines again" {
diff --git a/src/Effect.zig b/src/Effect.zig
index 51b7c645..ba8e5d60 100644
--- a/src/Effect.zig
+++ b/src/Effect.zig
@@ -603,7 +603,7 @@ test "Save reaches every tagline with text behind it and no other" {
// An image's bytes on disk already are what they are: nothing of the
// pane's own is unwritten, so the word is absent and inert.
const img_id = p.freeSlot().?;
- const img = try panes.Image.create(p, img_id, "/tmp/pardes-tag.ppm", &.{});
+ const img = try pardes.Kind.open(p, img_id, &panes.Image.kind, "/tmp/pardes-tag.ppm", "");
try std.testing.expectEqualStrings(" Term Collapse Del", tagline.curTail(img));
try std.testing.expect(p.executeBuiltinLine(img_id, "Save"));
try std.testing.expect(img.prompt != .save);
diff --git a/src/Kind.zig b/src/Kind.zig
new file mode 100644
index 00000000..24448aa5
--- /dev/null
+++ b/src/Kind.zig
@@ -0,0 +1,997 @@
+//! 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).
+//!
+//! 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.
+const std = @import("std");
+const builtin = @import("builtin");
+pub const c = @import("pardes_addon");
+const pardes = @import("pardes.zig");
+const walk = @import("walk.zig");
+const tape = @import("tape.zig");
+const surface = @import("surface.zig");
+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 kinds this process has ----
+
+/// A kind as /addons lists it: an addon's loaded, one compiled in, or an
+/// addon refused and why.
+pub const Listed = 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,
+ path: Buf(256) = .{},
+ why: Buf(128) = .{},
+
+ pub fn nameOf(l: *const Listed) []const u8 {
+ return std.mem.sliceTo(&l.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 std.mem.eql(u8, l.nameOf(), name)) return l.ops;
+ return 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;
+ 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;
+ 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) 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;
+ }
+ 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 {
+ if (nlisted == max_kinds) return "refused: no room for another kind";
+ const l = &listed[nlisted];
+ l.* = .{ .lib = lib };
+ 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;
+ 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;
+ }
+ l.why.set(if (lib == null) "static" else "loaded");
+ nlisted += 1;
+ return null;
+ };
+ 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();
+}
+
+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.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) });
+ }
+ 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];
+ 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;
+ std.mem.copyForwards(Listed, listed[at .. nlisted - 1], listed[at + 1 .. nlisted]);
+ nlisted -= 1;
+ return gone;
+}
+
+/// 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;
+}
+
+/// 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: `name version abi state [path]` a line.
+pub fn list(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');
+ }
+}
+
+// ---- 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.
+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,
+ st: ?*anyopaque = null,
+ /// What the slot's memory comes from; 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,
+ path: []u8 = &.{},
+ /// Petscii, Palette and Ascii: how a frontend shows its placements.
+ art: Placement.Art = .{},
+ /// When `tick` asked to be called next; 0, never.
+ next_tick: u64 = 0,
+ 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.
+ refused: Buf(96) = .{},
+
+ pub fn nameOf(s: *const Slot) []const u8 {
+ return std.mem.sliceTo(&s.name, 0);
+ }
+
+ pub fn is(s: *const Slot, name: []const u8) bool {
+ 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)});
+ }
+
+ /// 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,
+ };
+
+ 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 owned: ?[]u8 = null;
+ defer if (owned) |o| gpa.free(o);
+ if (s.ops) |ops| {
+ const prev = enter(null, 0, @constCast(s));
+ 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);
+ 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;
+ };
+ s.arena.deinit();
+ s.gpa.free(s.path);
+ if (s.record) |r| s.gpa.free(r);
+ s.* = undefined;
+ }
+};
+
+/// 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);
+ 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));
+ };
+ s.ops = ops;
+ s.st = st;
+ s.version = ops.head.version;
+ 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;
+}
+
+/// 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;
+ }
+ }
+ 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;
+ };
+}
+
+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;
+}
+
+/// A new pane of kind `ops` in slot `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 {
+ const gpa = p.image_gpa;
+ 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;
+ errdefer {
+ s.free();
+ gpa.destroy(s);
+ }
+ s.path = try gpa.dupe(u8, path orelse "");
+ const pane = try p.newDocPane(id);
+ pane.addon = s;
+ const prev = enter(p, id, s);
+ 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);
+ 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 {
+ 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 "");
+}
+
+/// 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);
+ defer leave(prev);
+ f(s.st);
+ };
+ const gpa = s.gpa;
+ s.free();
+ gpa.destroy(s);
+ pane.addon = null;
+}
+
+/// 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.
+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 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(cells, std.mem.zeroInit(c.pa_cell, .{ .fg = c.PA_DEFAULT, .bg = c.PA_DEFAULT, .flags = c.PA_UNPAINTED }));
+ 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);
+ 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;
+ 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| {
+ 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 },
+ .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)),
+ .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 {
+ 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),
+ });
+}
+
+fn styleOf(cell: *const c.pa_cell, fg: surface.Color, bg: surface.Color) surface.CellStyle {
+ const a = cell.attrs;
+ return .{
+ .fg = colorOf(cell.fg, fg),
+ .bg = colorOf(cell.bg, bg),
+ .bold = a & c.PA_BOLD != 0,
+ .dim = a & c.PA_DIM != 0,
+ .italic = a & c.PA_ITALIC != 0,
+ .reverse = a & c.PA_REVERSE != 0,
+ .ul = if (a & c.PA_UNDERLINE != 0) .single else .off,
+ };
+}
+
+fn colorOf(v: u32, default: surface.Color) surface.Color {
+ return switch (v & 0xff000000) {
+ c.PA_DEFAULT => default,
+ 0x02000000 => .{ .index = @truncate(v) },
+ else => .{ .rgb = .{ @truncate(v >> 16), @truncate(v >> 8), @truncate(v) } },
+ };
+}
+
+/// 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).
+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);
+ 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)]);
+}
+
+/// 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).
+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 (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);
+ defer leave(prev);
+ return f(slot.st, &pk) != 0;
+}
+
+/// 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 (authorityOnly("the mouse in a kind's pane")) return true;
+ const pm: c.pa_mouse = .{
+ .button = switch (m.button) {
+ .left => c.PA_LEFT,
+ .middle => c.PA_MIDDLE,
+ .right => c.PA_RIGHT,
+ .wheel_up => c.PA_WHEEL_UP,
+ .wheel_down => c.PA_WHEEL_DOWN,
+ else => 255,
+ },
+ .action = switch (m.kind) {
+ .press => c.PA_PRESS,
+ .release => c.PA_RELEASE,
+ .motion => c.PA_MOTION,
+ .drag => c.PA_DRAG,
+ },
+ .ctrl = @intFromBool(m.ctrl),
+ .shift = @intFromBool(m.shift),
+ .alt = @intFromBool(m.alt),
+ .pad = 0,
+ .col = col,
+ .row = row,
+ };
+ const prev = enter(p, id, slot);
+ defer leave(prev);
+ return f(slot.st, &pm) != 0;
+}
+
+/// A step of the session's clock: each kind whose time has come ticks,
+/// and each job's answer lands.
+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);
+ 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);
+ slot.next_tick = f(slot.st, now);
+ leave(prev);
+ p.needs_frame = true;
+ };
+ };
+}
+
+/// When the kinds next want a step: `0` a frame from now (a job under
+/// way), a time, 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);
+ };
+ 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);
+ defer leave(prev);
+ const n: usize = @intCast(@min(len_f(slot.st), 64 << 20));
+ const buf = try gpa.alloc(u8, n);
+ var off: usize = 0;
+ while (off < n) {
+ const got = read(slot.st, off, buf[off..].ptr, @intCast(@min(n - off, 1 << 20)));
+ if (got == 0) break;
+ off += got;
+ }
+ return buf[0..off];
+}
+
+/// 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 "";
+ const ops = slot.ops orelse return slot.where_text.slice();
+ const f = ops.where orelse return "";
+ const prev = enter(null, 0, slot);
+ defer leave(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);
+ 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 (authorityOnly("a kind's word")) return null;
+ const prev = enter(p, id, slot);
+ defer leave(prev);
+ @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";
+}
+
+/// 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);
+ defer leave(prev);
+ return buf[0..@min(buf.len, f(slot.st, buf.ptr, @intCast(buf.len)))];
+}
+
+fn authorityOnly(comptime why: []const u8) bool {
+ if (!tape.speculating()) return false;
+ tape.poison(why);
+ return true;
+}
+
+// ---- what the core does for a kind (pa_api) ----
+
+/// The pane a call into a kind is for: what `api` acts on.
+const Current = struct {
+ p: ?*Pardes,
+ id: usize,
+ slot: *Slot,
+ painting: bool = false,
+ /// In `open`: an error said refuses the pane.
+ opening: bool = false,
+ look: Buf(256) = .{},
+};
+var current: ?Current = null;
+
+fn enter(p: ?*Pardes, id: usize, slot: *Slot) ?Current {
+ const prev = current;
+ current = .{ .p = p, .id = id, .slot = slot };
+ return prev;
+}
+
+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());
+}
+
+pub const api: c.pa_api = .{
+ .size = @sizeOf(c.pa_api),
+ .alloc = apiAlloc,
+ .free = apiFree,
+ .job = apiJob,
+ .look = apiLook,
+ .say = apiSay,
+ .text = apiText,
+};
+
+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;
+ };
+ const history = pardes.panes.File.History.create(p.gpa) catch {
+ p.gpa.free(path);
+ p.gpa.free(content);
+ return 0;
+ };
+ const pane = p.newDocPane(free) catch {
+ p.gpa.destroy(history);
+ p.gpa.free(path);
+ p.gpa.free(content);
+ return 0;
+ };
+ 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);
+ }
+};
+
+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 (comptime !builtin.is_test) {
+ if (std.Thread.spawn(.{}, Job.work, .{job})) |t| job.thread = t else |_| job.work();
+ } else job.work();
+ free_at.* = job;
+ return job.token;
+}
+
+// ---- small things ----
+
+pub fn Buf(comptime n: usize) type {
+ return struct {
+ bytes: [n]u8 = undefined,
+ len: std.math.IntFittingRange(0, n) = 0,
+
+ const Self = @This();
+ pub fn set(b: *Self, s: []const u8) void {
+ const k = @min(s.len, n);
+ std.mem.copyForwards(u8, b.bytes[0..k], s[0..k]);
+ b.len = @intCast(k);
+ }
+ pub fn slice(b: *const Self) []const u8 {
+ return b.bytes[0..b.len];
+ }
+ pub fn print(b: *Self, comptime fmt: []const u8, args: anytype) []const u8 {
+ const s = std.fmt.bufPrint(&b.bytes, fmt, args) catch &b.bytes;
+ b.len = @intCast(s.len);
+ return b.slice();
+ }
+ };
+}
+
+test "a kind's head is checked before it is taken" {
+ 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("");
+ 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);
+}
diff --git a/src/Output.zig b/src/Output.zig
index d53ad968..bd8c79c0 100644
--- a/src/Output.zig
+++ b/src/Output.zig
@@ -648,8 +648,8 @@ pub fn openJumps(p: *Pardes, id: usize) !void {
std.fmt.bufPrint(&idbuf, config.pane_addr ++ "{d}", .{jp.serial}) catch unreachable;
const what: []const u8 = if (jp.file) |f|
std.mem.trim(u8, modal.lineSlice(f.content, j.line -| 1), " \t\r")
- else if (jp.image) |iv|
- iv.path
+ else if (jp.addon) |k|
+ k.path
else if (pdf_path) |path|
path
else
diff --git a/src/Store.zig b/src/Store.zig
index 9267dc3b..970fe85e 100644
--- a/src/Store.zig
+++ b/src/Store.zig
@@ -106,7 +106,7 @@ pub fn keep(s: *Store, p: *Pardes, id: usize) ?Kept {
gpa.free(owned);
return null;
}
- const what: []const u8 = if (pane.file) |f| f.path else if (pane.pdfPath()) |pdf| pdf else if (pane.image) |iv| iv.path else if (pane.command) |c| c else pane.cwdSlice();
+ const what: []const u8 = if (pane.file) |f| f.path else if (pane.pdfPath()) |pdf| pdf else if (pane.addon) |k| k.path else if (pane.command) |c| c else pane.cwdSlice();
var name = gpa.alloc(u8, @min(what.len, 4096)) catch {
gpa.free(owned);
return null;
diff --git a/src/body_layer.zig b/src/body_layer.zig
index bd9e065b..dc5e51bf 100644
--- a/src/body_layer.zig
+++ b/src/body_layer.zig
@@ -476,7 +476,7 @@ pub fn renderBody(p: *Pardes, s: *Surface, arena: std.mem.Allocator, pane: *Pane
}
pub fn bodyText(p: *Pardes, arena: std.mem.Allocator, pane: *Pane) ![]const u8 {
- if (pane.image != null) {
+ if (pane.addon != null) {
const buf = try arena.alloc(u8, pane.rows -| 1);
@memset(buf, '\n');
return buf;
diff --git a/src/builtins.zig b/src/builtins.zig
index 4c6fc367..92df2645 100644
--- a/src/builtins.zig
+++ b/src/builtins.zig
@@ -73,8 +73,8 @@ pub const PaneKind = enum {
return switch (kind) {
.terminal => pane.isTerminal(),
.pdf => pane.hasPdf(),
- .image => pane.image != null,
- .picture => pane.image != null or pane.isTerminal(),
+ .image => pane.addon != null,
+ .picture => pane.addon != null or pane.isTerminal(),
.program_colors => pane.isTerminal() or (pane.file != null and pane.file.?.pager),
.diff => if (pane.file) |f| pane.colorAlgo() == .diff or
(f.output != null and std.meta.eql(f.output.?.from, panes.Output.Origin{ .cmd = .Diff })) else false,
@@ -996,12 +996,12 @@ pub const Petscii = struct {
pub const takes_arg = true;
pub fn run(c: Ctx) void {
// `on|off` sets it, as the tag's `petscii:on` reads; none flips it.
- const now = if (c.pane.image) |state| state.glyph_art else panes.terminal.petscii(c.pane) orelse false;
+ const now = if (c.pane.addon) |k| k.art.glyph else panes.terminal.petscii(c.pane) orelse false;
if (c.arg != null) {
const want = stateArg(c, OnOff, "Petscii", "on or off") orelse return;
if ((want == .on) == now) return;
}
- if (c.pane.image) |*state| state.glyph_art = !state.glyph_art;
+ if (c.pane.addon) |k| k.art.glyph = !k.art.glyph;
panes.terminal.togglePetscii(c.pane);
}
};
@@ -1011,12 +1011,12 @@ pub const Palette = struct {
pub const needs: PaneKind = .image;
pub const takes_arg = true;
pub fn run(c: Ctx) void {
- const state = &(c.pane.image orelse return);
+ const art = &(c.pane.addon orelse return).art;
if (c.arg != null) {
const want = stateArg(c, panes.Image.PaletteMode, "Palette", "commodore or terminal") orelse return;
- if (want == state.pmode) return;
+ if (want == art.palette) return;
}
- state.pmode = if (state.pmode == .commodore) .terminal else .commodore;
+ art.palette = if (art.palette == .commodore) .terminal else .commodore;
}
};
@@ -1025,12 +1025,12 @@ pub const Ascii = struct {
pub const needs: PaneKind = .image;
pub const takes_arg = true;
pub fn run(c: Ctx) void {
- const state = &(c.pane.image orelse return);
+ const art = &(c.pane.addon orelse return).art;
if (c.arg != null) {
const want = stateArg(c, OnOff, "Ascii", "on or off") orelse return;
- if ((want == .on) == state.ascii) return;
+ if ((want == .on) == art.ascii) return;
}
- state.ascii = !state.ascii;
+ art.ascii = !art.ascii;
}
};
diff --git a/src/draw.zig b/src/draw.zig
index b63f61d8..4c476914 100644
--- a/src/draw.zig
+++ b/src/draw.zig
@@ -68,7 +68,7 @@ pub fn place(p: *Pardes, s: *Surface) void {
var rail: Region = .{ .kind = .rail, .owner = owner, .serial = pane.serial, .active = active, .rect = .{ .x = r.x, .y = body_y, .w = config.GUTTER, .h = body_h } };
// An image's rail has no thumb; a native PDF's is measured as its
// pages are placed (Pdf.draw); every other pane's is here.
- if (pane.image == null and body_h > 0) {
+ if (pane.addon == null and body_h > 0) {
const sb: struct { total: usize, offset: usize, len: usize } = if (pane.file) |*f| .{
.total = panes.File.nlines(p.gpa, f),
.offset = f.scroll,
@@ -91,7 +91,7 @@ pub fn place(p: *Pardes, s: *Surface) void {
rail.thumb_span = @as(f32, @floatFromInt(@max(1, sb.len))) / @as(f32, @floatFromInt(total));
}
s.addRegion(rail);
- if (body_h > 0 and pane.image == null) pane.places.addTicks(p, pane, s, owner);
+ if (body_h > 0 and pane.addon == null) pane.places.addTicks(p, pane, s, owner);
// Each notice a chip at the right edge, one to a row in the order
// collectNotices chose, as wide as its own message and no wider, so
// the text beneath the rest of the row keeps reading as the file.
@@ -436,13 +436,13 @@ fn renderPane(p: *Pardes, s: *Surface, arena: std.mem.Allocator, pane: *Pane, r:
if (comptime pdf_enabled)
if (pane.hasPdf() and panes.Pdf.draw(p, s, pane, r, id, tx, tw, rail)) return;
- if (pane.image) |*iv| {
+ if (pane.addon != null) {
// Below the notice chips: a picture is drawn after the cells (the
// GUI's image pass, kitty's z-order), so a chip over it would be
- // painted out. Text gets the overlay; a picture gives up the rows.
+ // painted out. Text gets the overlay; a kind's pane gives up the rows.
const shown = pane.notices.span();
- const image_h = (r.h -| pane.tag_rows) -| shown;
- panes.Image.draw(p, iv, @intCast(id), pane.serial, tx, body_y + shown, tw, image_h);
+ const body_h = (r.h -| pane.tag_rows) -| shown;
+ pardes.Kind.draw(p, s, arena, pane, id, tx, body_y + shown, tw, body_h);
// thumbless, but the same one column as the real scrollbar below —
// that is the whole point of drawing it, and like that one it runs
// past the notice bands so the gutter has no notch in it
@@ -557,10 +557,12 @@ fn tagTintRange(pane: *const Pane, tag: []const u8, prefix_len: usize) ?struct {
var start: usize = 0;
const name = if (pane.file) |file|
if (pane.prompt == .name) pane.input.own orelse file.path else file.path
- else if (pane.image) |state| blk: {
- // Image tags put renderer controls before the path.
- start = std.mem.lastIndexOf(u8, tag[0..@min(prefix_len, tag.len)], state.path) orelse return null;
- break :blk state.path;
+ else if (pane.addon) |k| blk: {
+ // A kind's tag may put its words before the path (an image's
+ // renderer controls).
+ if (k.path.len == 0) return null;
+ start = std.mem.lastIndexOf(u8, tag[0..@min(prefix_len, tag.len)], k.path) orelse return null;
+ break :blk k.path;
} else if (comptime pdf_enabled) blk: {
break :blk if (pane.pdf) |state| state.path else return null;
} else return null;
diff --git a/src/dump.zig b/src/dump.zig
index 976344b6..3c5decdd 100644
--- a/src/dump.zig
+++ b/src/dump.zig
@@ -420,7 +420,7 @@ fn loadImage(gpa: std.mem.Allocator, opts: Options, bytes: []const u8, notes: ?*
/// A pane that is none of its kinds (a terminal kept slim, or one another
/// build's dump could not give): a terminal, a new emulator for its shell.
fn ensureKind(p: *Pardes, pane: *pardes.panes.Pane) !void {
- if (pane.terminal != null or pane.file != null or pane.image != null or pane.hasPdf()) return;
+ if (pane.terminal != null or pane.file != null or pane.addon != null or pane.hasPdf()) return;
const fresh = try pardes.panes.terminal.create(p.gpa, @max(1, pane.cols), @max(1, pane.rows));
pane.terminal = fresh.terminal;
fresh.terminal = null;
diff --git a/src/edit.zig b/src/edit.zig
index 8691633c..5adb94e3 100644
--- a/src/edit.zig
+++ b/src/edit.zig
@@ -463,7 +463,7 @@ fn editText(p: *Pardes, t: *Text, lo: i32, hi: i32, col: i32) ?panes.EditText {
if (t.what != .body) return .{ .text = t.own orelse &.{}, .row0 = 0 };
const pane = t.pane() orelse return null;
if (pane.file) |f| return .{ .text = f.content, .row0 = 0 };
- if (pane.image != null or pane.hasPdf()) return null;
+ if (pane.addon != null or pane.hasPdf()) return null;
return panes.terminal.editText(p, pane, lo, hi, col);
}
diff --git a/src/fs.zig b/src/fs.zig
index 4afc17bd..d79b8cb3 100644
--- a/src/fs.zig
+++ b/src/fs.zig
@@ -1465,7 +1465,7 @@ pub fn unmount(p: *Pardes, name: []const u8) !void {
const paths = [_][]const u8{
if (pane.file) |file| file.path else "",
if (comptime pardes.pdf_enabled) (if (pane.pdf) |pdf| pdf.path else "") else "",
- if (pane.image) |image| image.path else "",
+ if (pane.addon) |k| k.path else "",
Pardes.paneDir(pane),
};
for (paths) |path| if (std.mem.startsWith(u8, path, prefix) and
diff --git a/src/image.zig b/src/image.zig
index 215bfc25..80261d91 100644
--- a/src/image.zig
+++ b/src/image.zig
@@ -4,6 +4,7 @@ const builtin = @import("builtin");
const zstbi = @import("zstbi");
const pdf_enabled = @import("pardes_config").mupdf;
const pardes = @import("pardes.zig");
+const Kind = @import("Kind.zig");
const config = @import("config.zig");
const filesystem = @import("fs.zig");
/// cap the longest side before keeping/transmitting: a pane is at most a
@@ -245,13 +246,18 @@ test "native geometry is total at extreme accepted aspect ratios" {
/// call once at startup / exit (stb_image's allocator shim)
pub fn start(io: std.Io, gpa: std.mem.Allocator) void {
zstbi.init(io, gpa);
+ decode_gpa = gpa;
started = true;
}
pub fn stop() void {
started = false;
+ decode_gpa = null;
zstbi.deinit();
}
+/// What a decode allocates from: the image region `start` was given.
+var decode_gpa: ?std.mem.Allocator = null;
+
/// stb_image has its allocator (`start`): before, nothing of it may run.
var started = false;
@@ -427,132 +433,132 @@ test "PNG and JPEG decode through wuffs, sized from their headers first; other f
try std.testing.expect(decode(gpa, "\xff\xd8\xff\xe0\x00\x10JFIF") == null);
}
-// ---- the image pane ----
+// ---- the image kind (kinds/pardes_addon.h), compiled in ----
-pub const State = struct {
- /// What the replay digest leaves out (src/walk.zig): the picture as
- /// decoded from its bytes, off the loop as the render first wants it.
- pub const replica = .{ .derived = .{ "tried", "rgba", "iw", "ih", "decoder", "decoded", "answer" } };
- path: []u8,
- /// Petscii, Palette and Ascii: how a frontend draws the picture as
- /// glyph art (`Placement.Art`), which the core never does.
- glyph_art: bool = false,
- pmode: PaletteMode = .commodore,
- ascii: bool = true,
- tried: bool = false,
- rgba: []u8 = &.{},
- iw: usize = 0,
- ih: usize = 0,
- /// Dump-loaded bytes, decoded lazily by the same path as a disk image.
- raw: []u8 = &.{},
- /// The decode under way off the loop (ensureDecoded), and its answer.
- decoder: ?std.Thread = null,
- decoded: std.atomic.Value(bool) = .init(false),
- answer: ?Decoded = null,
+/// A picture: its file's bytes decoded on a job, shown as one placement
+/// over the body that a frontend fits (or draws as glyph art).
+pub const kind: Kind.Ops = std.mem.zeroInit(Kind.Ops, .{
+ .head = std.mem.zeroInit(Kind.c.pa_head, .{
+ .size = @sizeOf(Kind.c.pa_head),
+ .abi = Kind.abi,
+ .name = "image".* ++ @as([11]u8, @splat(0)),
+ .version = 1,
+ .exts = exts,
+ }),
+ .open = open,
+ .paint = paint,
+ .job_run = jobRun,
+ .job_done = jobDone,
+ .dump = dump,
+ .load = load,
+});
- pub fn deinit(state: *State, gpa: std.mem.Allocator) void {
- if (state.decoder) |t| t.join();
- if (state.answer) |a| gpa.free(a.rgba);
- gpa.free(state.path);
- if (state.rgba.len > 0) gpa.free(state.rgba);
- if (state.raw.len > 0) gpa.free(state.raw);
- state.* = undefined;
- }
+const exts = blk: {
+ var all: []const u8 = "";
+ for (config.image_exts, 0..) |e, i| all = all ++ (if (i == 0) "" else " ") ++ e;
+ break :blk all ++ "";
};
-/// Construct an image pane from a path and optionally transferred dump bytes.
-/// `raw` must be image_gpa-owned and ownership transfers only on success.
-/// Without them the file is read here, not at the first draw: a draw
-/// must not go out into the host (`pardes.turn`), and the path may be a
-/// mount this editor serves. A file that cannot be read draws blank.
-pub fn create(p: *pardes.Pardes, id: usize, path: []const u8, raw: []u8) !*pardes.Pane {
- var bytes = raw;
- var read_here = false;
- if (bytes.len == 0) {
- // The slot stays ours across the read: another request may
- // make a pane meanwhile.
- p.reserved_slots[id] = true;
- defer p.reserved_slots[id] = false;
- if (filesystem.read(p, path)) |from_disk| {
- defer p.gpa.free(from_disk);
- bytes = try p.image_gpa.dupe(u8, from_disk);
- read_here = true;
- } else |_| {}
- }
- errdefer if (read_here) p.image_gpa.free(bytes);
- const path_copy = try p.image_gpa.dupe(u8, path);
- errdefer p.image_gpa.free(path_copy);
- const pane = try p.newDocPane(id);
- pane.image = .{ .path = path_copy, .raw = bytes };
- return pane;
-}
+const State = struct {
+ path: []const u8,
+ /// The file's bytes, as a dump keeps them.
+ raw: []const u8 = &.{},
+ rgba: []const u8 = &.{},
+ w: u32 = 0,
+ h: u32 = 0,
+};
-/// Image renderer choices are pane-local, not global Config values. Keep them
-/// queryable where they apply: the live tag beside the image's path.
-/// `glyphs`: whether the picture is drawn as glyph art, which a terminal
-/// with no graphics does whatever `glyph_art` says.
-pub fn tagPrefix(arena: std.mem.Allocator, state: *const State, glyphs: bool) ![]u8 {
- return std.fmt.allocPrint(
- arena,
- "{s} petscii:{s} palette:{s} ascii:{s} {s}",
- .{
- config.tag_image,
- if (glyphs) "on" else "off",
- @tagName(state.pmode),
- if (state.ascii) "on" else "off",
- state.path,
- },
- );
+fn alloc(comptime T: type, n: usize) ?[]T {
+ const mem = Kind.api.alloc.?(n * @sizeOf(T)) orelse return null;
+ return @as([*]T, @ptrCast(@alignCast(mem)))[0..n];
}
-/// The picture decoded off the loop: the first draw starts a thread and
-/// draws the pane without it (its tag and frame at once); the frames after
-/// it look (Pardes.nextWake asks for them) and the picture lands on the
-/// first one after the decode (80 ms in ReleaseSafe, 290 in Debug, for the
-/// docs' screenshot: all of it once on the frame before).
-/// ponytail: a thread a picture; a pool if many open at once.
-fn ensureDecoded(p: *pardes.Pardes, state: *State) void {
- if (state.decoder) |t| {
- if (!state.decoded.load(.acquire)) return;
- t.join();
- state.decoder = null;
- }
- if (state.answer) |decoded| {
- state.answer = null;
- state.rgba = decoded.rgba;
- state.iw = decoded.w;
- state.ih = decoded.h;
- }
- if (state.tried) return;
- state.tried = true;
- if (state.raw.len == 0) return; // nothing was readable at open
- const Work = struct {
- fn run(gpa: std.mem.Allocator, st: *State) void {
- st.answer = decode(gpa, st.raw);
- st.decoded.store(true, .release);
+fn open(path: [*c]const u8, bytes: [*c]const u8, len: u64) callconv(.c) ?*anyopaque {
+ const st = &(alloc(State, 1) orelse return null)[0];
+ const p = if (path == null) "" else std.mem.span(path);
+ const kept = alloc(u8, p.len) orelse return null;
+ @memcpy(kept, p);
+ st.* = .{ .path = kept };
+ if (bytes != null) {
+ const raw = bytes[0..@intCast(len)];
+ // One it cannot read (corrupt, truncated, not what its name says)
+ // is refused, rather than shown as a blank pane.
+ if (!readable(raw)) {
+ const why = "not an image pardes can read";
+ Kind.api.say.?(why, why.len, 1);
+ return st;
}
- };
- if (comptime !builtin.is_test) {
- if (std.Thread.spawn(.{}, Work.run, .{ p.image_gpa, state })) |t| {
- state.decoder = t;
- return;
- } else |_| {}
+ keep(st, raw);
}
- Work.run(p.image_gpa, state);
- ensureDecoded(p, state);
+ return st;
+}
+
+/// The file's bytes kept, and decoded on a job.
+fn keep(st: *State, raw: []const u8) void {
+ const copy = alloc(u8, raw.len) orelse return;
+ @memcpy(copy, raw);
+ st.raw = copy;
+ if (raw.len > 0) _ = Kind.api.job.?(copy.ptr, @intCast(copy.len));
}
-/// The picture over the body's cells, left for the frontend to fit (or
-/// to draw as glyph art).
-pub fn draw(p: *pardes.Pardes, state: *State, pane_id: u8, serial: u32, x: u16, y: u16, cols: u16, rows: u16) void {
- ensureDecoded(p, state);
- if (state.rgba.len == 0 or cols == 0 or rows == 0) return;
- _ = p.appendPlacement(.{
- .pane = pane_id,
- .raster = .of(state.rgba, state.iw, state.ih),
- .src = .{ .w = @intCast(state.iw), .h = @intCast(state.ih) },
- .dst = .{ .x = x, .y = y, .w = cols, .h = rows },
- .key = pardes.Placement.keyOf(serial, 0, 0),
- .art = .{ .glyph = state.glyph_art, .palette = state.pmode, .ascii = state.ascii },
+fn paint(ctx: ?*anyopaque, win: [*c]const Kind.c.pa_window, out: [*c]Kind.c.pa_paint) callconv(.c) void {
+ const st: *const State = @ptrCast(@alignCast(ctx orelse return));
+ const w = win.*;
+ const o = &out.*;
+ const prefix = std.fmt.bufPrint(&o.prefix, "{s} petscii:{s} palette:{s} ascii:{s} {s}", .{
+ config.tag_image,
+ if (w.glyphs != 0) "on" else "off",
+ if (w.palette == 0) "commodore" else "terminal",
+ if (w.ascii != 0) "on" else "off",
+ st.path,
+ }) catch &o.prefix;
+ o.prefix_len = @intCast(prefix.len);
+ if (st.rgba.len == 0 or o.cap == 0) return;
+ o.placements[0] = std.mem.zeroInit(Kind.c.pa_placement, .{
+ .rgba = st.rgba.ptr,
+ .w = st.w,
+ .h = st.h,
+ .stride = st.w * 4,
+ .src = .{ .x = 0, .y = 0, .w = st.w, .h = st.h },
+ .dst = .{ .x = 0, .y = 0, .w = w.cols, .h = w.rows },
});
+ o.n = 1;
+}
+
+/// Off the loop (80 ms in ReleaseSafe, 290 in Debug, for the docs'
+/// screenshot): width and height, then the RGBA.
+fn jobRun(in: [*c]const u8, n: u32, out: [*c]Kind.c.pa_out) callconv(.c) u32 {
+ const got = decode(decode_gpa orelse return 0, in[0..n]) orelse return 0;
+ defer decode_gpa.?.free(got.rgba);
+ const len = 8 + got.rgba.len;
+ const buf: [*]u8 = @ptrCast(out.*.alloc.?(out, len) orelse return 0);
+ std.mem.writeInt(u32, buf[0..4], @intCast(got.w), .little);
+ std.mem.writeInt(u32, buf[4..8], @intCast(got.h), .little);
+ @memcpy(buf[8..len], got.rgba);
+ return @intCast(len);
+}
+
+fn jobDone(ctx: ?*anyopaque, _: u32, out: [*c]const u8, n: u32) callconv(.c) void {
+ const st: *State = @ptrCast(@alignCast(ctx orelse return));
+ if (n < 8) return;
+ const w = std.mem.readInt(u32, out[0..4], .little);
+ const h = std.mem.readInt(u32, out[4..8], .little);
+ if (@as(u64, w) * h * 4 != n - 8) return;
+ const rgba = alloc(u8, n - 8) orelse return;
+ @memcpy(rgba, out[8..n]);
+ st.rgba = rgba;
+ st.w = w;
+ st.h = h;
+}
+
+fn dump(ctx: ?*anyopaque, buf: [*c]u8, n: u32) callconv(.c) u32 {
+ const st: *const State = @ptrCast(@alignCast(ctx orelse return 0));
+ if (st.raw.len <= n) @memcpy(buf[0..st.raw.len], st.raw);
+ return @intCast(st.raw.len);
+}
+
+fn load(ctx: ?*anyopaque, buf: [*c]const u8, n: u32, _: u32) callconv(.c) c_int {
+ const st: *State = @ptrCast(@alignCast(ctx orelse return 1));
+ keep(st, buf[0..n]);
+ return 0;
}
diff --git a/src/keys.zig b/src/keys.zig
index 9496d37a..1329de0b 100644
--- a/src/keys.zig
+++ b/src/keys.zig
@@ -424,6 +424,14 @@ pub fn handleKey(p: *Pardes, key: Key) void {
}
}
+/// Whether a leader path `keys` is the core's, or begins one of its
+/// paths or is begun by one: a kind's word may not have it (Kind.zig).
+pub fn leaderTaken(keys: []const u8) bool {
+ for (config.leader_args) |la| if (std.mem.startsWith(u8, la.path, keys) or std.mem.startsWith(u8, keys, la.path)) return true;
+ for (builtin_rows) |row| if (row.path) |path| if (std.mem.startsWith(u8, path, keys) or std.mem.startsWith(u8, keys, path)) return true;
+ return keys.len > 0 and keys[0] == config.leader_help;
+}
+
fn leaderKey(p: *Pardes, key: Key) void {
p.prefix = .none; // only "still a prefix" below re-arms it
if (key.ctrl or key.alt or key.cp < 0x20 or key.cp > 0x7e) return;
diff --git a/src/kinds/pardes_addon.h b/src/kinds/pardes_addon.h
new file mode 100644
index 00000000..8a95d6d7
--- /dev/null
+++ b/src/kinds/pardes_addon.h
@@ -0,0 +1,261 @@
+/* pardes_addon.h: an addon, a shared library that brings pardes one
+ * kind of pane (a picture, a game, a plot).
+ *
+ * An addon exports one symbol, `pardes_addon`, a `pa_ops` whose `head`
+ * names its kind. pardes calls it on its own thread, one call at a time;
+ * it keeps no pointer pardes hands it past the call (but its `pa_api`),
+ * starts no threads (it has jobs), and reads no file, clock or
+ * environment (it is handed bytes and the time). Every function but
+ * `paint` is optional: leave it NULL and pardes does the default the
+ * comment beside it says.
+ *
+ * cc -shared -fPIC -o game.so game.c
+ * echo 'Addon load ./game.so' > $PARDES_MOUNT/ctl
+ * pardes --addon-test ./game.so game.script a test, as a script
+ *
+ * addons/fake/fake.c implements every function; it is the template.
+ */
+#ifndef PARDES_ADDON_H
+#define PARDES_ADDON_H
+
+#include <stddef.h>
+#include <stdint.h>
+
+/* Major in the high half: an addon of another major is refused. */
+#define PA_ABI_MAJOR 1u
+#define PA_ABI_MINOR 0u
+#define PA_ABI ((PA_ABI_MAJOR << 16) | PA_ABI_MINOR)
+
+/* ---- the picture ---- */
+
+/* A cell's colour: the theme's own, one of its 256, or RGB. */
+#define PA_DEFAULT 0x01000000u
+#define PA_INDEX(n) (0x02000000u | (uint8_t)(n))
+#define PA_RGB(r, g, b) (((uint32_t)(uint8_t)(r) << 16) | ((uint32_t)(uint8_t)(g) << 8) | (uint32_t)(uint8_t)(b))
+
+#define PA_BOLD 0x01u
+#define PA_DIM 0x02u
+#define PA_ITALIC 0x04u
+#define PA_REVERSE 0x10u
+#define PA_UNDERLINE 0x100u
+
+/* A cell: one character, `len` bytes of UTF-8 (at most 7). */
+#define PA_UNPAINTED 0x01u /* flags: the pane's background, nothing drawn */
+typedef struct pa_cell {
+ uint8_t text[8];
+ uint32_t fg, bg;
+ uint16_t attrs;
+ uint8_t len;
+ uint8_t flags;
+} pa_cell;
+
+/* The pane's body, which `paint` writes: `rows` rows of `cols` cells,
+ * `stride` cells apart, every one PA_UNPAINTED when the call begins. */
+typedef struct pa_window {
+ pa_cell *cells;
+ uint32_t stride;
+ uint16_t rows, cols;
+ /* A cell's size in pixels, as the frontend draws it. */
+ uint16_t cell_w, cell_h;
+ /* The pane has the keyboard. */
+ uint8_t focused;
+ /* How the frontend shows this pane's placements, which the core words
+ * Petscii, Palette and Ascii set: as glyph art (Petscii on, or a frontend
+ * with no pixels), in the commodore (0) or the terminal's (1) palette,
+ * with letters among the glyphs. An addon may say so in its prefix. */
+ uint8_t glyphs, palette, ascii;
+} pa_window;
+
+typedef struct pa_rect { uint32_t x, y, w, h; } pa_rect; /* pixels */
+typedef struct pa_cells { uint16_t x, y, w, h; } pa_cells; /* cells of the window */
+
+/* A picture over the cells: the `src` part of an RGBA raster (straight
+ * alpha, `stride` bytes a row), over the `dst` cells; at `at` pixels in
+ * them, or fitted there (no larger than it is) when `at.w` is 0. The
+ * raster is the addon's and must stay as it is until the pane's next paint
+ * or close. `key` is the pixels' identity in the pane: one key, one
+ * picture, so a frontend keeps what it uploaded under it. */
+typedef struct pa_placement {
+ const uint8_t *rgba;
+ uint32_t w, h, stride;
+ pa_rect src;
+ pa_cells dst;
+ pa_rect at;
+ uint64_t key;
+} pa_placement;
+
+/* What `paint` hands back beside the cells: placements (room for `cap`,
+ * lowest first) and the start of the pane's tag (empty: the pane's path). */
+typedef struct pa_paint {
+ pa_placement *placements;
+ uint32_t cap, n;
+ char prefix[96];
+ uint32_t prefix_len;
+} pa_paint;
+
+/* ---- input ---- */
+
+/* A key: a codepoint, or one of these. */
+#define PA_KEY_ENTER 0x0Du
+#define PA_KEY_TAB 0x09u
+#define PA_KEY_BACKSPACE 0x7Fu
+#define PA_KEY_UP 0xF0001u
+#define PA_KEY_DOWN 0xF0002u
+#define PA_KEY_LEFT 0xF0003u
+#define PA_KEY_RIGHT 0xF0004u
+#define PA_KEY_HOME 0xF0005u
+#define PA_KEY_END 0xF0006u
+#define PA_KEY_PAGE_UP 0xF0007u
+#define PA_KEY_PAGE_DOWN 0xF0008u
+#define PA_KEY_DELETE 0xF0009u
+typedef struct pa_key {
+ uint32_t cp;
+ uint8_t ctrl, alt, shift, pad;
+} pa_key;
+
+#define PA_LEFT 0
+#define PA_MIDDLE 1
+#define PA_RIGHT 2
+#define PA_WHEEL_UP 3
+#define PA_WHEEL_DOWN 4
+#define PA_PRESS 0
+#define PA_RELEASE 1
+#define PA_MOTION 2
+#define PA_DRAG 3
+/* A pointer event in the window's cells. */
+typedef struct pa_mouse {
+ uint8_t button, action, ctrl, shift, alt, pad;
+ uint16_t col, row;
+} pa_mouse;
+
+/* ---- what pardes does for an addon ---- */
+
+/* Valid during any call pardes makes for a pane, and about that pane. */
+typedef struct pa_api {
+ uint32_t size;
+ /* Zeroed memory from the pane's arena, which pardes frees at its close;
+ * NULL when the arena is full. */
+ void *(*alloc)(size_t n);
+ void (*free)(void *ptr, size_t n);
+ /* `job_run` over a copy of `in` on a worker; its answer comes to
+ * `job_done` with the token returned here (0: refused). */
+ uint32_t (*job)(const void *in, uint32_t n);
+ /* Look at `text` as a click would: a URL, `file:12`, a word. */
+ void (*look)(const char *text, uint32_t n);
+ /* A message on the pane, or an error (`err` 1: also refuses an `open`). */
+ void (*say)(const char *text, uint32_t n, int err);
+ /* A new text pane named `name` holding `bytes`; its serial, 0 if none. */
+ uint32_t (*text)(const char *name, uint32_t name_len, const char *bytes, uint32_t n);
+} pa_api;
+
+/* A job's answer buffer: `alloc` it once, write it, return its length. */
+typedef struct pa_out {
+ void *(*alloc)(struct pa_out *out, size_t n);
+ void *ctx;
+} pa_out;
+
+/* ---- the addon ---- */
+
+#define PA_ARG_NONE 0
+#define PA_ARG_OPTIONAL 1
+#define PA_ARG_REQUIRED 2
+
+/* A word the addon brings. Written to a pane of its kind, it goes to `ctl`;
+ * one that `opens` it, run anywhere else, opens a pane of the kind
+ * (`open` with its argument as the path, or none). */
+typedef struct pa_word {
+ uint32_t size;
+ const char *name;
+ /* The keys after the leader (Space) that run it, "ng" for SPC n g, or NULL. */
+ const char *leader;
+ uint8_t arg, opens, pad[2];
+ const char *doc;
+} pa_word;
+
+typedef struct pa_head {
+ uint32_t size, abi;
+ /* The pane's kind word in /index, NUL-padded. */
+ char name[16];
+ uint32_t version;
+ /* The extensions it opens, space-separated (".png .jpg"), or "". */
+ const char *exts;
+ const pa_word *words;
+ uint32_t nwords;
+} pa_head;
+
+typedef struct pa_ops {
+ pa_head head;
+ /* Once, at load: nonzero refuses the addon. */
+ int (*init)(const pa_api *api);
+ /* A new pane (path and bytes NULL for one a word opened): its state,
+ * which every call below is handed. NULL with nothing said is a pane
+ * with no state; `say` an error to refuse it. */
+ void *(*open)(const char *path, const uint8_t *bytes, uint64_t len);
+ /* The pane closes; its arena is freed after. */
+ void (*close)(void *st);
+ /* Time has come to `now_ns`: step, and say when next (0: never). Absent,
+ * the pane repaints when the core repaints. */
+ uint64_t (*tick)(void *st, uint64_t now_ns);
+ /* Required. Pure: the same state paints the same, and changes nothing. */
+ void (*paint)(void *st, const pa_window *win, pa_paint *out);
+ /* Every key but Esc, which leaves; nonzero if taken. Absent: no keys. */
+ int (*key)(void *st, const pa_key *k);
+ /* Nonzero if taken. Absent: a click focuses the pane. */
+ int (*mouse)(void *st, const pa_mouse *m);
+ /* The pane's body as text (9P `body`). Absent: empty. */
+ uint64_t (*body_len)(void *st);
+ uint32_t (*body)(void *st, uint64_t off, char *buf, uint32_t n);
+ /* Go to `text` (`:12`, `12:0.33`); nonzero if it is a place here. And
+ * where the pane is now, as such a text (jumps, Recent, a Restore). */
+ int (*address)(void *st, const char *text, uint32_t n);
+ uint32_t (*where)(void *st, char *buf, uint32_t n);
+ /* One of the addon's words, as written (`Fit width`): 0 taken, else
+ * refused with `reply`. Required with words. */
+ int (*ctl)(void *st, const char *line, uint32_t n, char *reply, uint32_t cap);
+ /* What the pane's ctl file reads after the core's fields. */
+ uint32_t (*ctl_read)(void *st, char *buf, uint32_t n);
+ /* On a worker thread, pure over `in`: the answer's length. */
+ uint32_t (*job_run)(const uint8_t *in, uint32_t n, pa_out *out);
+ /* Back on pardes's thread; `out` is gone after the call. */
+ void (*job_done)(void *st, uint32_t token, const uint8_t *out, uint32_t n);
+ /* The pane's record for a dump (its length; at most `n`), and back. With
+ * none, a Restore reopens the pane from its path and its `where`. */
+ uint32_t (*dump)(void *st, uint8_t *buf, uint32_t n);
+ int (*load)(void *st, const uint8_t *buf, uint32_t n, uint32_t version);
+} pa_ops;
+
+/* ---- helpers ---- */
+
+static inline pa_cell *pa_at(const pa_window *w, unsigned row, unsigned col) {
+ return row < w->rows && col < w->cols ? &w->cells[row * w->stride + col] : 0;
+}
+
+/* `text` (UTF-8) from (row, col) on, a character a cell, cut at the edge;
+ * the cells written. */
+static inline unsigned pa_put(const pa_window *w, unsigned row, unsigned col, const char *text, uint32_t fg, uint32_t bg) {
+ unsigned n = 0;
+ while (*text) {
+ pa_cell *c = pa_at(w, row, col + n);
+ unsigned len = 1;
+ while (len < 7 && (text[len] & 0xC0) == 0x80) len++;
+ if (c) {
+ for (unsigned i = 0; i < 8; i++) c->text[i] = i < len ? (uint8_t)text[i] : 0;
+ c->len = (uint8_t)len;
+ c->fg = fg;
+ c->bg = bg;
+ c->attrs = 0;
+ c->flags = 0;
+ n++;
+ }
+ text += len;
+ if (!c) break;
+ }
+ return n;
+}
+
+/* An addon's head, its size and ABI filled:
+ * const pa_ops pardes_addon = { .head = PA_ADDON("game", 1, "", words, 1), .paint = paint }; */
+#define PA_ADDON(nm, ver, ex, ws, nws) \
+ { .size = sizeof(pa_head), .abi = PA_ABI, .name = nm, .version = (ver), .exts = (ex), .words = (ws), .nwords = (nws) }
+
+#endif
diff --git a/src/look.zig b/src/look.zig
index ab1407ee..870209a3 100644
--- a/src/look.zig
+++ b/src/look.zig
@@ -1,4 +1,5 @@
const std = @import("std");
+const Kind = @import("Kind.zig");
const builtin = @import("builtin");
const libc = std.c;
const pardes = @import("pardes.zig");
@@ -185,18 +186,12 @@ pub const Target = union(enum) {
none,
dir: []const u8, // resolved absolute path, in caller's buf
file: FileTarget,
- image: struct { path: []const u8 },
+ /// A file a kind opens (Kind.forPath): a picture.
+ kind: struct { path: []const u8, ops: *const Kind.Ops },
url: []const u8,
pane: struct { id: usize, at: Spot },
};
-pub fn isImagePath(path: []const u8) bool {
- for (config.image_exts) |ext| {
- if (std.ascii.endsWithIgnoreCase(path, ext)) return true;
- }
- return false;
-}
-
pub fn isPdfPath(path: []const u8) bool {
if (comptime !pdf_enabled) return false;
return std.ascii.endsWithIgnoreCase(path, ".pdf");
@@ -279,7 +274,7 @@ pub fn lineSpan(p: ?*pardes.Pardes, line: []const u8, cwd: []const u8, realbuf:
while (b > a and std.mem.indexOfScalar(u8, trail_trim, line[b - 1]) != null) b -= 1;
const cand = line[a..b];
if (cand.len > 0 and parsePathLine(cand).end == cand.len) switch (resolve(p, cand, cwd, realbuf)) {
- .dir, .file, .image => return .{ .start = a, .end = b },
+ .dir, .file, .kind => return .{ .start = a, .end = b },
.url, .pane => if (std.mem.indexOfAny(u8, cand, " \t") == null)
return .{ .start = a, .end = b },
.none => {},
@@ -376,7 +371,7 @@ pub fn resolve(p: ?*pardes.Pardes, word_raw: []const u8, cwd: []const u8, realbu
.at = pl.at,
.kind = .pdf,
} };
- if (isImagePath(found.path)) return .{ .image = .{ .path = found.path } };
+ if (Kind.forPath(found.path)) |ops| return .{ .kind = .{ .path = found.path, .ops = ops } };
return .{ .file = .{ .path = found.path, .at = pl.at } };
}
@@ -1038,7 +1033,7 @@ fn selectSpan(p: *Pardes, pane: *Pane, at: Spot) void {
fn openPaneTarget(p: *const Pardes, path: []const u8, at: Spot) ?Target {
for (p.panes, 0..) |slot, i| {
const tt = slot orelse continue;
- if (tt.image) |iv| if (std.mem.eql(u8, iv.path, path)) {
+ if (tt.addon) |k| if (std.mem.eql(u8, k.path, path)) {
return .{ .pane = .{ .id = i, .at = .{} } };
};
if (comptime pdf_enabled) if (tt.pdf) |pv| if (std.mem.eql(u8, pv.path, path)) {
@@ -1137,14 +1132,14 @@ fn canonicalLookLocation(p: *Pardes, id: usize, text: []const u8) ?[]const u8 {
return p.scratch.allocator().dupe(u8, url) catch null;
},
.file => |file| return locationText(p, file.path, file.at),
- .image => |iv| return locationText(p, iv.path, .{}),
+ .kind => |k| return locationText(p, k.path, .{}),
.dir => |dir| return locationText(p, dir, .{}),
.pane => |target| {
if (target.id >= p.panes.len) return null;
const pane = p.panes[target.id] orelse return null;
if (pane.file) |file| return locationText(p, file.path, target.at);
if (comptime pdf_enabled) if (pane.pdf) |doc| return locationText(p, doc.path, target.at);
- if (pane.image) |iv| return locationText(p, iv.path, target.at);
+ if (pane.addon) |k| if (k.path.len > 0) return locationText(p, k.path, target.at);
var path: [32]u8 = undefined;
return locationText(p, std.fmt.bufPrint(&path, config.pane_addr ++ "{d}", .{pane.serial}) catch return null, target.at);
},
@@ -1380,7 +1375,7 @@ fn lookUnresolved(p: *Pardes, id: usize, pane: *Pane, trimmed: []const u8, text:
}
// A raw terminal's clicks are its program's; a look written over
// 9P is no keyboard input, and searches whatever the key mode.
- if (pane.image != null or (pane.body.mode == .tty and !p.fs.serving)) return;
+ if (pane.addon != null or (pane.body.mode == .tty and !p.fs.serving)) return;
if (text.len == 0) return;
if (lookCommit(p, id, pane, trimmed)) return;
if (pane.file != null) return lookWord(p, id, pane, text);
@@ -1485,7 +1480,7 @@ fn lookAddress(p: *Pardes, id: usize, path: []const u8, expr: []const u8) void {
if ((by_serial or path.len == 0) and pane.isTerminal()) return lookTerminalAddress(p, id, target, expr);
// Named as the pane is, the bare `:addr` (path empty) included.
var serial_name: [32]u8 = undefined;
- const subject = if (pane.image) |iv| iv.path else if (path.len > 0) path else std.fmt.bufPrint(&serial_name, config.pane_addr ++ "{d}", .{pane.serial}) catch "the pane";
+ const subject = if (pane.addon) |k| k.path else if (path.len > 0) path else std.fmt.bufPrint(&serial_name, config.pane_addr ++ "{d}", .{pane.serial}) catch "the pane";
var cut: [miss_path_cap + "…".len]u8 = undefined;
return missed(p, id, "{s} is no text to address", .{missText(subject, &cut)});
};
@@ -1882,20 +1877,21 @@ pub fn lookAt(p: *Pardes, id: usize, operand_raw: []const u8) void {
}
settleLine(p, id, target.path, target.at, before, opened);
},
- .image => |target| {
+ .kind => |target| {
if (focusPaneByPath(p, target.path, .{})) return;
const free = p.freeSlot() orelse return p.reportError(id, "look", error.NoPaneSlots);
- const made = panes.Image.create(p, free, target.path, &.{}) catch |err|
+ const made = Kind.openFile(p, free, target.ops, target.path) catch |err|
return lookOpenFailed(p, id, target.path, err);
- // One it cannot read (corrupt, truncated, not what its name says)
- // is said, a failure, rather than shown as a blank pane.
- if (!@import("image.zig").readable(made.image.?.raw)) {
+ // One its kind refuses (an image corrupt, truncated, not what
+ // its name says) is said, a failure, rather than shown blank.
+ if (made.addon.?.refused.len > 0) {
made.vweight = 0;
p.unplaced.set(free);
- var said: [miss_path_cap + 64]u8 = undefined;
+ var said: [miss_path_cap + 160]u8 = undefined;
var cut: [miss_path_cap + "…".len]u8 = undefined;
- return p.reportFailure(id, std.fmt.bufPrint(&said, "look: {s}: not an image pardes can read", .{missText(target.path, &cut)}) catch "look: not an image pardes can read");
+ return p.reportFailure(id, std.fmt.bufPrint(&said, "look: {s}: {s}", .{ missText(target.path, &cut), made.addon.?.refused.slice() }) catch "look: refused");
}
+ Kind.startTicking(p, made);
exec.placeNew(p, id, id, free, .doc);
},
}
diff --git a/src/macos.zig b/src/macos.zig
index 17b1bf35..96ef4f1e 100644
--- a/src/macos.zig
+++ b/src/macos.zig
@@ -2093,7 +2093,7 @@ fn activeFilePath(st: *State) ?[]const u8 {
const pane = st.core.panes[st.core.active] orelse return null;
if (pane.file) |*f| return if (f.output == null) f.path else null;
if (comptime pardes.pdf_enabled) if (pane.pdfPath()) |path| return path;
- if (pane.image) |*iv| return iv.path;
+ if (pane.addon) |k| return k.path;
return null;
}
diff --git a/src/main.zig b/src/main.zig
index be66e8e2..aaa27031 100644
--- a/src/main.zig
+++ b/src/main.zig
@@ -721,7 +721,7 @@ fn nativeMain(std_init: std.process.Init) !void {
opts.file = try arena.dupe(u8, t.path);
opts.file_line = t.at.line;
},
- .image => |t| opts.file = try arena.dupe(u8, t.path),
+ .kind => |t| opts.file = try arena.dupe(u8, t.path),
.none => opts.missing = .{
.word = try arena.dupe(u8, a),
.dir = try arena.dupe(u8, std.mem.span(@as([*:0]u8, @ptrCast(cwd)))),
diff --git a/src/ninep/ctl.zig b/src/ninep/ctl.zig
index 81ccd6ea..68fefbc5 100644
--- a/src/ninep/ctl.zig
+++ b/src/ninep/ctl.zig
@@ -1521,8 +1521,7 @@ test "an address looked at in an image pane names the image, never an empty subj
const p = try withFile(testing.allocator, "x\n");
defer p.deinit();
const id = p.freeSlot().?;
- const doc = try p.newDocPane(id);
- doc.image = .{ .path = try p.gpa.dupe(u8, "/tmp/pardes-pic.ppm") };
+ const doc = try pardes.Kind.open(p, id, &pardes.image.kind, "/tmp/pardes-pic.ppm", null);
_ = wr(p, Node.of(doc.serial, .look), ":/x/\n");
try testing.expect(th.logHas(p, "look: /tmp/pardes-pic.ppm is no text to address"));
}
@@ -1531,8 +1530,7 @@ test "Save and Save path on an image pane are refused with why, never a silent s
const p = try withFile(testing.allocator, "x\n");
defer p.deinit();
const id = p.freeSlot().?;
- const doc = try p.newDocPane(id);
- doc.image = .{ .path = try p.gpa.dupe(u8, "/tmp/pardes-pic.ppm") };
+ const doc = try pardes.Kind.open(p, id, &pardes.image.kind, "/tmp/pardes-pic.ppm", null);
for ([_][]const u8{ "Save\n", "Save /tmp/pardes-copy.ppm\n" }) |line| {
const r = wr(p, Node.of(doc.serial, .ctl), line);
try testing.expectEqual(Status.err, r.reply.status);
@@ -1562,17 +1560,16 @@ test "a builtin for one kind of pane is refused on another, and still acts on it
try testing.expectEqual(Status.err, wr(p, Node.of(serial, .ctl), line).reply.status);
};
const id = p.freeSlot().?;
- const doc = try p.newDocPane(id);
- doc.image = .{ .path = try p.gpa.dupe(u8, "/tmp/pardes-pic.ppm") };
+ const doc = try pardes.Kind.open(p, id, &pardes.image.kind, "/tmp/pardes-pic.ppm", null);
const r = wr(p, Node.of(doc.serial, .ctl), "Mode\n");
try testing.expectEqualStrings("Mode: only a text or terminal pane has modes", r.reply.ename);
- const glyphs = doc.image.?.glyph_art;
+ const glyphs = doc.addon.?.art.glyph;
try testing.expectEqual(Status.ok, wr(p, Node.of(doc.serial, .ctl), "Petscii\n").reply.status);
- try testing.expect(doc.image.?.glyph_art != glyphs);
+ try testing.expect(doc.addon.?.art.glyph != glyphs);
// Its tag says what is drawn: with no graphics, glyph art whatever
// Petscii chose; with them, what it chose.
for ([_]bool{ false, true }) |art| {
- doc.image.?.glyph_art = art;
+ doc.addon.?.art.glyph = art;
p.frontend.native_images = false;
try testing.expect(std.mem.indexOf(u8, try pardes.tagline.tagPrefix(p, doc), " petscii:on ") != null);
p.frontend.native_images = true;
@@ -2137,7 +2134,7 @@ test "a language server question that finds nothing, cannot be answered, or is a
try testing.expectEqual(@as(u16, 0), p.fs.late_failure_len);
// An image's body takes no write.
const slot = p.freeSlot().?;
- const img = try pardes.panes.Image.create(p, slot, "/tmp/pardes-no-such.png", try p.image_gpa.dupe(u8, "not a png"));
+ const img = try pardes.Kind.open(p, slot, &pardes.image.kind, "/tmp/pardes-no-such.png", "not a png");
try testing.expectEqual(E.INVAL, wr(p, Node.of(img.serial, .body), "text\n").errno());
}
@@ -2779,8 +2776,7 @@ test "a Save whose directory is missing because one above refuses says permissio
test "a body write to an image pane says its body takes none, not that terminals have no text" {
const p = try withFile(testing.allocator, "x\n");
defer p.deinit();
- const doc = try p.newDocPane(p.freeSlot().?);
- doc.image = .{ .path = try p.gpa.dupe(u8, "/tmp/pardes-pic.ppm") };
+ const doc = try pardes.Kind.open(p, p.freeSlot().?, &pardes.image.kind, "/tmp/pardes-pic.ppm", null);
try testing.expectEqualStrings(pane_files.e_no_body, wr(p, Node.of(doc.serial, .body), "x").reply.ename);
}
@@ -2810,8 +2806,7 @@ test "a Rename that reaches other files previews them, says so, and is the pane
test "Edit on an image pane is refused as a data write there is, EINVAL, before it runs" {
const p = try withFile(testing.allocator, "x\n");
defer p.deinit();
- const doc = try p.newDocPane(p.freeSlot().?);
- doc.image = .{ .path = try p.gpa.dupe(u8, "/tmp/pardes-pic.ppm") };
+ const doc = try pardes.Kind.open(p, p.freeSlot().?, &pardes.image.kind, "/tmp/pardes-pic.ppm", null);
const edit = wr(p, Node.of(doc.serial, .ctl), "Edit ,d\n");
const data = wr(p, Node.of(doc.serial, .data), "x");
try testing.expectEqual(E.INVAL, edit.errno());
@@ -2822,24 +2817,23 @@ test "Edit on an image pane is refused as a data write there is, EINVAL, before
test "Petscii, Palette and Ascii take the state their tag word names, set rather than flipped" {
const p = try withFile(testing.allocator, "x\n");
defer p.deinit();
- const doc = try p.newDocPane(p.freeSlot().?);
- doc.image = .{ .path = try p.gpa.dupe(u8, "/tmp/pardes-pic.ppm") };
+ const doc = try pardes.Kind.open(p, p.freeSlot().?, &pardes.image.kind, "/tmp/pardes-pic.ppm", null);
const ctl_node = Node.of(doc.serial, .ctl);
for ([_][]const u8{ "Petscii on\n", "Petscii on\n" }) |line| {
try testing.expectEqual(Status.ok, wr(p, ctl_node, line).reply.status);
- try testing.expect(doc.image.?.glyph_art);
+ try testing.expect(doc.addon.?.art.glyph);
}
_ = wr(p, ctl_node, "Petscii off\n");
- try testing.expect(!doc.image.?.glyph_art);
+ try testing.expect(!doc.addon.?.art.glyph);
_ = wr(p, ctl_node, "Palette terminal\n");
_ = wr(p, ctl_node, "Palette terminal\n");
- try testing.expectEqual(pardes.panes.Image.PaletteMode.terminal, doc.image.?.pmode);
+ try testing.expectEqual(pardes.panes.Image.PaletteMode.terminal, doc.addon.?.art.palette);
_ = wr(p, ctl_node, "Ascii off\n");
_ = wr(p, ctl_node, "Ascii off\n");
- try testing.expect(!doc.image.?.ascii);
+ try testing.expect(!doc.addon.?.art.ascii);
// Bare, each still flips.
_ = wr(p, ctl_node, "Ascii\n");
- try testing.expect(doc.image.?.ascii);
+ try testing.expect(doc.addon.?.art.ascii);
_ = wr(p, ctl_node, "Petscii maybe\n");
try testing.expect(th.logHas(p, "Petscii takes on or off"));
}
diff --git a/src/ninep/pane.zig b/src/ninep/pane.zig
index 4595d02d..49fa46c6 100644
--- a/src/ninep/pane.zig
+++ b/src/ninep/pane.zig
@@ -146,7 +146,7 @@ pub fn dirtyOf(pane: *const Pane) bool {
pub fn nameOf(p: *Pardes, pane: *const Pane) []const u8 {
if (pane.file) |*f| return f.path;
if (pane.pdfPath()) |path| return path;
- if (pane.image) |state| return state.path;
+ if (pane.addon) |k| if (k.path.len > 0) return k.path;
const cwd = pane.cwdSlice();
// A shell given no directory was started in the session's, and is
// named by it until it says where it is (a `new` then, not a rename).
@@ -156,7 +156,7 @@ pub fn nameOf(p: *Pardes, pane: *const Pane) []const u8 {
pub fn kindOf(pane: *const Pane) []const u8 {
if (pane.file != null) return "text";
if (pane.pdfPath() != null) return "pdf";
- if (pane.image != null) return "image";
+ if (pane.addon) |k| return k.nameOf();
// A command's pane is no shell to type into: a script choosing a
// terminal by kind must not pick one.
if (pane.command != null) return "cmd";
diff --git a/src/panes.zig b/src/panes.zig
index c4a32413..9f1ce036 100644
--- a/src/panes.zig
+++ b/src/panes.zig
@@ -37,7 +37,7 @@ pub const Pane = struct {
.len = .{ .{ "msg", "msg_len" }, .{ "msg_older", "msg_older_len" }, .{ "question", "question_len" }, .{ "shell_tail", "shell_tail_len" }, .{ "sel_snap", "nsel_snap" } },
// A picture's and a PDF's memory is their own allocators' (a dump
// loaded makes it there).
- .alloc = .{ .{ "image", "image" }, .{ "pdf", "pdf" }, .{ "terminal", "terminal" } },
+ .alloc = .{ .{ "addon", "image" }, .{ "pdf", "pdf" }, .{ "terminal", "terminal" } },
};
/// The words that throw unsaved text away (builtins.zig warnModified).
pub const Discarding = enum { Exit, Restore, get, Del, Delcol };
@@ -201,7 +201,8 @@ pub const Pane = struct {
/// (builtins.zig warnModified).
discard_warned: ?struct { revision: u32, by: Discarding } = null,
file: ?File.State = null,
- image: ?Image.State = null,
+ /// A pane of a kind (Kind.zig): a picture, or one a library brought.
+ addon: ?*@import("Kind.zig").Slot = null,
pdf: PdfSlot = if (Pdf.enabled) null else {},
prompt: Prompt = .none,
/// The text an open prompt answers for: `s`/`S` select in it and `|`
@@ -502,7 +503,7 @@ pub const Pane = struct {
pub fn isTerminal(pane: *const Pane) bool {
const no_pdf = if (comptime Pdf.enabled) pane.pdf == null else true;
- return pane.file == null and pane.image == null and no_pdf;
+ return pane.file == null and pane.addon == null and no_pdf;
}
/// The one coloring choice keyed on what a pane IS, so the highlight
@@ -736,6 +737,7 @@ test {
_ = Dir;
_ = mini;
_ = Image;
+ _ = @import("Kind.zig");
_ = Pdf;
_ = terminal;
}
@@ -803,9 +805,7 @@ pub fn teardownPane(p: *Pardes, pane: *Pane) void {
panes.terminal.deinitPendingCommand(pane);
if (pane.command) |line| p.gpa.free(line);
if (pane.shell) |bin| p.gpa.free(bin);
- if (pane.image) |*iv| {
- iv.deinit(p.image_gpa);
- }
+ @import("Kind.zig").close(p, pane);
if (comptime pdf_enabled) if (pane.pdf) |pv| panes.Pdf.deinitPane(p, pane, pv);
if (pane.file) |*file| panes.File.deinit(p, pane, file);
if (pane.ovl) |o| p.gpa.free(o.text);
@@ -1000,7 +1000,7 @@ pub fn paneDir(pane: *const Pane) []const u8 {
if (pane.file) |f| return panes.Dir.ofName(f.path);
if (comptime pdf_enabled) if (pane.pdf) |pv|
return std.fs.path.dirname(pv.path) orelse "/";
- if (pane.image) |iv| return std.fs.path.dirname(iv.path) orelse "/";
+ if (pane.addon) |k| if (k.path.len > 0) return std.fs.path.dirname(k.path) orelse "/";
return pane.cwdSlice();
}
diff --git a/src/pardes.zig b/src/pardes.zig
index 05dc42ef..ab2e706f 100644
--- a/src/pardes.zig
+++ b/src/pardes.zig
@@ -78,6 +78,7 @@ pub const rollback = @import("rollback.zig");
pub const replica = @import("replica.zig");
pub const echo = @import("echo.zig");
pub const image = @import("image.zig");
+pub const Kind = @import("Kind.zig");
pub const dump = @import("dump.zig");
pub const lsp = @import("lsp/lsp.zig");
pub const host_io = @import("host_io.zig");
diff --git a/src/tagline.zig b/src/tagline.zig
index 8d65f8c6..5cfb9f50 100644
--- a/src/tagline.zig
+++ b/src/tagline.zig
@@ -117,7 +117,7 @@ pub fn pathPrefix(p: *const Pardes, arena: std.mem.Allocator, pane: *Pane) ![]co
if (comptime pdf_enabled) if (pane.pdf) |pv|
return std.fmt.allocPrint(arena, "{s} [{d}/{d}]", .{ pv.path, pv.page + 1, pv.page_count });
// What is drawn: with no graphics, glyph art whatever `Petscii` says.
- if (pane.image) |*state| return panes.Image.tagPrefix(arena, state, state.glyph_art or !p.frontend.native_images);
+ if (pane.addon != null) return pardes.Kind.prefix(p, arena, pane);
// A command pane: its directory, the line it runs, and how that went.
// Its first line only, cut to 48 bytes at a character's start: a tag's
// first row is where the prefix ends, and a line that ran over to a
diff --git a/test/fs_namespace.zig b/test/fs_namespace.zig
index d54eb9a2..ac638e41 100644
--- a/test/fs_namespace.zig
+++ b/test/fs_namespace.zig
@@ -1,5 +1,6 @@
const std = @import("std");
const pardes = @import("pardes");
+const image = pardes.image;
const filesystem = pardes.filesystem;
test "runtime Mount and Unmount copy command arguments and change Look resolution" {
@@ -302,14 +303,18 @@ test "images decode through explicit filesystem mounts, and a dump reads one on
defer p.deinit();
var arena = std.heap.ArenaAllocator.init(gpa);
defer arena.deinit();
+ // Its decode lands at the step after it (a job, run here at once).
+ p.update(.tick);
_ = try p.render(arena.allocator());
- const pane = p.panes[0].?;
- const state = pane.image.?;
- try std.testing.expectEqual(@as(usize, 1), state.iw);
- try std.testing.expectEqual(@as(usize, 1), state.ih);
+ const shown = p.surface.placements.items;
+ try std.testing.expectEqual(@as(usize, 1), shown.len);
+ try std.testing.expectEqual(@as(u32, 1), shown[0].raster.w);
+ try std.testing.expectEqual(@as(u32, 1), shown[0].raster.h);
// The picture's bytes are in the dump: it comes back as it was shown.
try pardes.dump.dumpState(p);
const restored = try pardes.dump.initFromDump(gpa, .{ .tty_only = true }, p.dump_out.?);
defer restored.deinit();
- try std.testing.expectEqualStrings(bytes, restored.panes[0].?.image.?.raw);
+ const slot = restored.panes[0].?.addon.?;
+ var kept: [64]u8 = undefined;
+ try std.testing.expectEqualStrings(bytes, kept[0..image.kind.dump.?(slot.st, &kept, kept.len)]);
}
diff --git a/test/mode.zig b/test/mode.zig
index 6141d898..86de0488 100644
--- a/test/mode.zig
+++ b/test/mode.zig
@@ -92,9 +92,9 @@ test "Mode from actual tag Exec preserves parked file and output insert transact
test "Mode leaves image and PDF document modes unchanged" {
const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true });
defer p.deinit();
- const picture = try panes.Image.create(p, 1, "/mode-test.png", &.{});
+ const picture = try pardes.Kind.open(p, 1, &panes.Image.kind, "/mode-test.png", "");
try mode(p, 1, .normal);
- try std.testing.expect(picture.image != null);
+ try std.testing.expect(picture.addon != null);
if (comptime panes.Pdf.enabled) {
var tmp = std.testing.tmpDir(.{});
defer tmp.cleanup();
diff --git a/test/panes.zig b/test/panes.zig
index a6b6aecd..f51c2b27 100644
--- a/test/panes.zig
+++ b/test/panes.zig
@@ -2247,19 +2247,16 @@ const OutputTests = struct {
};
const ImageTests = struct {
- const State = panes.Image.State;
- const tagPrefix = panes.Image.tagPrefix;
-
test "pane-local renderer choices are visible in the image tag" {
- const state: State = .{ .path = @constCast("/tmp/picture.ppm"), .glyph_art = true, .pmode = .terminal, .ascii = false };
- const tag = try tagPrefix(std.testing.allocator, &state, state.glyph_art);
- defer std.testing.allocator.free(tag);
+ const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true });
+ defer p.deinit();
+ const pane = try pardes.Kind.open(p, p.freeSlot().?, &image.kind, "/tmp/picture.ppm", null);
+ pane.addon.?.art = .{ .glyph = true, .palette = .terminal, .ascii = false };
try std.testing.expectEqualStrings(
config.tag_image ++ " petscii:on palette:terminal ascii:off /tmp/picture.ppm",
- tag,
+ try pardes.tagline.tagPrefix(p, pane),
);
}
-
};
const PdfTests = struct {