From 3f8f66643a1e4840e1cbf0d7a4c5aa8580360ac7 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Wed, 18 Nov 2026 05:32:59 -0300 Subject: kinds: a draw (pa_api.draw, ABI 3.2), a kind's job whose answer feeds its pictures alone: job_run over a copy of its input on a worker of the process that shows the pane (the frontend's workers through Kind.drawer, else at once), its answer to job_done with a PA_DRAWN token at the pane's next paint (Kind.deliver), never an event, on the tape, in the digest or sent to another process, each process asking its own from the same call; the header says what a kind promises by it (what job_done keeps of it paint alone reads; never a plain kind's block, nor its token; Debug checks the block is as it was) and addon.zig has draw; a client's pane of a plain kind closed in a speculation leaves its kind's own memory be (its rollback brings the pane back); the window client takes its queue's draws; the addon ABI tests expect 3.2; tui core-test 819/958 (139 skipped), shell-test 993/996, behaviour-test 273/273 (the four addon tests the base failed on its ABI string run again and pass), --replay 20 seeds 0 failures, pane-test 180/181, replicas pass, addon-test 1/1 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T --- src/Kind.zig | 90 +++++++++++++++++++++++++++++++++++++++++++++--- src/gui/gui.zig | 29 +++++++++++++++- src/host_io.zig | 16 +++++++-- src/kinds/addon.zig | 14 ++++++-- src/kinds/pardes_addon.h | 20 +++++++++-- src/tui/tui.zig | 16 +++++++++ 6 files changed, 171 insertions(+), 14 deletions(-) (limited to 'src') diff --git a/src/Kind.zig b/src/Kind.zig index 42205518..47384227 100644 --- a/src/Kind.zig +++ b/src/Kind.zig @@ -24,6 +24,7 @@ const tape = @import("tape.zig"); const surface = @import("surface.zig"); const views = @import("views.zig"); const Addon = @import("Addon.zig"); +const host_io = @import("host_io.zig"); pub const Loaded = Addon.Loaded; pub const LoadedWord = Addon.LoadedWord; pub const loadedOf = Addon.loadedOf; @@ -41,7 +42,7 @@ comptime { if (@sizeOf(usize) == 8) for (.{ .{ c.pa_cell, 20 }, .{ c.pa_window, 24 }, .{ c.pa_rect, 16 }, .{ c.pa_cells, 8 }, .{ c.pa_placement, 80 }, .{ c.pa_paint, 48 }, .{ c.pa_key, 8 }, .{ c.pa_mouse, 16 }, - .{ c.pa_api, 112 }, .{ c.pa_out, 16 }, .{ c.pa_word, 32 }, .{ c.pa_head, 56 }, + .{ c.pa_api, 120 }, .{ c.pa_out, 16 }, .{ c.pa_word, 32 }, .{ c.pa_head, 56 }, .{ c.pa_ops, 208 }, .{ c.pa_view, 32 }, .{ c.pa_tick, 128 }, }) |r| if (@sizeOf(r[0]) != r[1]) @compileError(std.fmt.comptimePrint("{s} is {d} bytes, the header says {d}", .{ @typeName(r[0]), @sizeOf(r[0]), r[1] })); } @@ -384,13 +385,22 @@ pub fn fileChanged(p: *Pardes, id: usize, _: []const u8) bool { /// 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| { + // A client's pane of a plain kind closed in a speculation: its kind's + // own memory (its pictures) is left be, as the rollback brings the pane + // back; the session's order closes it. + const kept = s.plain != null and s.ops != null and s.ops.?.close != null and tape.authorityOnly("a kind's close"); + if (!kept) { + var i: usize = 0; + while (i < ready.items.len) if (ready.items[i].draw == p and ready.items[i].serial == pane.serial) ready.orderedRemove(i).drop() else { + i += 1; + }; + } + if (s.ops) |ops| if (ops.close) |f| if (!kept) { var cl: Call = .{ .p = null, .id = 0, .slot = s, .quiet = true }; const prev = cl.begin("close"); f(s.st); _ = cl.end(prev); }; - _ = p; const gpa = s.gpa; s.free(); gpa.destroy(s); @@ -422,7 +432,10 @@ pub fn draw(p: *Pardes, s: *surface.Surface, arena: std.mem.Allocator, pane: *Pa const text = if (p.kinds.byName(slot.nameOf()) != null) why else 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; - } else frame.cells = (paint(p, slot, id, arena, cols, rows, &frame) orelse return); + } else { + if (ready.items.len > 0) deliver(p, slot, pane, id); + frame.cells = (paint(p, slot, id, arena, cols, rows, &frame) orelse return); + } if (frame.gpu.len != 0) s.gpu_frames[id] = .{ .bytes = frame.gpu, .serial = pane.serial, .dst = .{ .x = x, .y = y, .w = cols, .h = rows } }; for (0..@min(rows, frame.rows)) |r| for (0..@min(cols, frame.cols)) |col| { const cell = &frame.cells[r * frame.cols + col]; @@ -469,7 +482,7 @@ pub fn paint(p: *const Pardes, slot: *Slot, id: usize, arena: std.mem.Allocator, var out: c.pa_paint = std.mem.zeroInit(c.pa_paint, .{ .placements = &frame.buf, .cap = frame.buf.len, .gpu = GpuPaint.emit, .gpu_ctx = &gpu }); const px = p.view().cell_pixels; const win = std.mem.zeroInit(c.pa_window, .{ .cells = cells.ptr, .stride = cols, .rows = rows, .cols = cols, .cell_w = px.w, .cell_h = px.h, .focused = @intFromBool(focusedAnywhere(p, id)), .view = p.live + 1, .glyphs = @intFromBool(!p.view().frontend.native_images) }); - var cl: Call = .{ .p = null, .id = 0, .slot = slot, .quiet = true }; + var cl: Call = .{ .p = null, .id = id, .slot = slot, .quiet = true, .core = p }; const prev = cl.begin("paint"); const before = if (checked) usedHash(slot) else {}; ops.paint.?(slot.st, &win, &out); @@ -914,6 +927,9 @@ const Call = struct { opening: bool = false, /// An address's: what it says of a miss is the Look's to say. missing: ?*Buf(160) = null, + /// Paint's core (its `p` is null: it asks nothing of the step), whose + /// pane `id` a draw is for. + core: ?*const Pardes = null, name: []const u8 = "", ret: i64 = 0, refused: Buf(160) = .{}, @@ -1167,6 +1183,31 @@ pub const api: c.pa_api = .{ cl.cancels[free] = token; } }.f, + .draw = struct { + /// A picture's job, of this process alone: on the frontend's + /// workers (`drawer`), else here at once; its answer to job_done at + /// the pane's next paint (`deliver`), never through the step. + fn f(in: ?*const anyopaque, n: u32) callconv(.c) u32 { + const cl = current orelse return 0; + const p: *const Pardes = cl.p orelse cl.core orelse return 0; + const pane = p.panes[cl.id] orelse return 0; + const ops = cl.slot.ops orelse return 0; + if (ops.job_run == null or ops.job_done == null) return 0; + const copy = heap.dupe(u8, if (in) |b| @as([*]const u8, @ptrCast(b))[0..n] else "") catch return 0; + const j = heap.create(host_io.KindJob) catch { + heap.free(copy); + return 0; + }; + draw_tokens = (draw_tokens +% 1) & ~c.PA_DRAWN; + const token = c.PA_DRAWN | draw_tokens; + j.* = .{ .gpa = heap, .pane = @intCast(cl.id), .serial = pane.serial, .token = token, .gen = cl.slot.gen, .ops = ops, .in = copy, .arena = .init(heap), .draw = p }; + Addon.holdJob(ops, true); + if (drawer) |d| if (d.go(d.ctx, j)) return token; + j.run(); + ready.append(heap, j) catch j.drop(); + return token; + } + }.f, .found = struct { /// Gathered in the call: the search's answer, or onto its +Search after. fn f(rows: [*c]const u8, n: u32) callconv(.c) void { @@ -1178,6 +1219,45 @@ pub const api: c.pa_api = .{ }.f, }; +/// Where this process's draws run (api.draw): its frontend's workers, +/// which post each back to its loop to land (host_io.KindJob.land); false, +/// or none (a test's core), and it runs here at once. +pub var drawer: ?struct { ctx: ?*anyopaque, go: *const fn (ctx: ?*anyopaque, j: *host_io.KindJob) bool } = null; +var draw_tokens: u32 = 0; +/// Draws done, each kept for its pane's next paint (the loop's alone). +var ready: std.ArrayListUnmanaged(*host_io.KindJob) = .empty; + +/// A draw done on a worker, back on the loop: kept for its pane's next +/// paint, a frame owed. One of another core's (a client joined again +/// since) is dropped: the new core's pane asked its own. +pub fn landDraw(p: *Pardes, j: *host_io.KindJob) void { + if (j.draw != p) return j.drop(); + ready.append(heap, j) catch return j.drop(); + p.needs_frame = true; +} + +/// The draws done for pane `id`, to its kind's job_done before it paints: +/// pictures only, so a plain kind's block is as it was (Debug checks). +fn deliver(p: *const Pardes, slot: *Slot, pane: *const Pane, id: usize) void { + var i: usize = 0; + while (i < ready.items.len) { + const j = ready.items[i]; + if (j.draw != p or j.pane != id) { + i += 1; + continue; + } + _ = ready.orderedRemove(i); + defer j.drop(); + if (pane.serial != j.serial or slot.gen != j.gen or slot.ops != j.ops) continue; + var cl: Call = .{ .p = null, .id = id, .slot = slot, .quiet = true, .core = p }; + const prev = cl.begin("job_done"); + const before = if (checked) usedHash(slot); + j.ops.job_done.?(slot.st, j.token, j.out.ptr, @intCast(j.out.len)); + if (checked and slot.plain != null and usedHash(slot) != before) std.debug.panic("addon {s}: a draw's answer changed its state (a draw is pictures alone)", .{slot.nameOf()}); + _ = cl.end(prev); + } +} + /// What `api.heap` hands out: memory that outlives a call, from any /// thread (a document a kind keeps, its pixels, MuPDF's own). A host sets /// it to its region for kinds (memory.zig); the C heap otherwise. diff --git a/src/gui/gui.zig b/src/gui/gui.zig index 65e3088c..3af66b12 100644 --- a/src/gui/gui.zig +++ b/src/gui/gui.zig @@ -1117,6 +1117,8 @@ fn localSession( frame_capture_dir = if (std.c.getenv("PARDES_FRAMES_CAPTURE")) |dir| std.mem.span(dir) else null; const host = shell.host(); core.host = host; + pardes.Kind.drawer = .{ .ctx = &shell, .go = kindDraw }; + defer pardes.Kind.drawer = null; shell.peers = .{ .gpa = gpa, .io = io, .name = daemon.name(), .wake = sdlWake, .detached = detached }; defer shell.peers.deinit(); // Before the core goes: each client sees its link end. @@ -1383,7 +1385,7 @@ fn clientSession(init: std.process.Init, g: *Gui, opts_in: pardes.Options, test_ // empty ones, there for what draws. var ptys: [pardes.MAX_PANES]?Pty = @splat(null); var gens: [pardes.MAX_PANES]u32 = @splat(0); - var queue: Queue = .{ .io = io, .gpa = gpa, .lsp_allocator = allocs.lsp }; + var queue: Queue = .{ .io = io, .gpa = gpa, .lsp_allocator = allocs.lsp, .wake_fn = sdlWake }; defer queue.deinit(); var pipe_tasks: PipeTasks = .{}; var watches: file_watch.Table = @splat(null); @@ -1404,6 +1406,9 @@ fn clientSession(init: std.process.Init, g: *Gui, opts_in: pardes.Options, test_ .test_mode = test_mode, .client = &client, }; + pardes.Kind.drawer = .{ .ctx = &shell, .go = kindDraw }; + defer pardes.Kind.drawer = null; + defer shell.job_tasks.cancelAll(io); g.no_blink = test_mode; defer g.hit_core = null; _ = c.SDL_StartTextInput(g.window); @@ -1481,6 +1486,8 @@ fn clientSession(init: std.process.Init, g: *Gui, opts_in: pardes.Options, test_ if (link.quit) break; } client.takeSaid(); + // Its draws done (api.draw: this window's own pictures). + if (shell.takeDraws()) link.dirty = true; r.settle(); if (titled and link.notice_len == 0) { titled = false; @@ -2688,6 +2695,20 @@ const Shell = struct { s.closePty(@intCast(id)); } + /// A client's queue holds its draws alone: each landed for its pane's + /// next paint. Whether any came. + fn takeDraws(s: *Shell) bool { + s.queue.takeInto(&s.batch); + for (s.batch.slice()) |m| switch (m) { + .kind_job => |j| { + s.job_tasks.finish(s.io, j.id); + j.land(s.core); + }, + else => m.deinit(s.gpa, s.lsp_allocator), + }; + return s.batch.slice().len > 0; + } + fn drainQueue(s: *Shell) void { s.reconcilePtys(); // After this batch's output, which an exit is told behind. @@ -3451,6 +3472,12 @@ fn pipe(ctx: ?*anyopaque, id: u32) void { s.core.reportError(s.core.view().active, "pipe", error.WorkersUnavailable); } +/// A draw (api.draw) on a worker, as a job is. +fn kindDraw(ctx: ?*anyopaque, j: *host_io.KindJob) bool { + const s = shellOf(ctx); + return (s.threads_ok or s.client != null) and host_io.KindJob.go(s.io, &s.job_tasks, j, s.queue, Queue.pushJob); +} + fn kindJob(ctx: ?*anyopaque, pane: u8, serial: u32, token: u32) void { const s = shellOf(ctx); if (s.threads_ok) return host_io.KindJob.start(s.io, s.core, &s.job_tasks, pane, serial, token, s.queue, Queue.pushJob); diff --git a/src/host_io.zig b/src/host_io.zig index b086b5fe..d199c839 100644 --- a/src/host_io.zig +++ b/src/host_io.zig @@ -80,6 +80,8 @@ pub const Host = struct { /// A kind's job (Effect.job), taken off its pane: its input, its kind's /// `job_run` and generation; run on a worker (or here), its answer the /// core's `job` event. Its library is held until it lands (Addon.holdJob). +/// A draw (api.draw, `draw`) is one of this process's alone: never an +/// event, its answer kept for the pane's next paint (Kind.landDraw). pub const KindJob = struct { gpa: std.mem.Allocator, pane: u8, @@ -92,6 +94,8 @@ pub const KindJob = struct { arena: std.heap.ArenaAllocator, out: []u8 = &.{}, id: u32 = 0, + /// A draw's: the core it was asked in. + draw: ?*const pardes.Pardes = null, pub fn take(p: *pardes.Pardes, pane: u8, serial: u32, token: u32) ?*KindJob { const pn = p.panes[pane] orelse return null; @@ -123,6 +127,7 @@ pub const KindJob = struct { /// Its answer to the core, and it gone. pub fn land(j: *KindJob, p: *pardes.Pardes) void { + if (j.draw != null) return pardes.Kind.landDraw(p, j); p.update(.{ .job = .{ .pane = j.pane, .serial = j.serial, .token = j.token, .gen = j.gen, .bytes = j.out } }); j.drop(); } @@ -137,6 +142,12 @@ pub const KindJob = struct { /// On a worker of `io`, posting itself to `sink` done: a host's `job`. pub fn start(io: std.Io, p: *pardes.Pardes, tasks: *selection_pipe.Tasks, pane: u8, serial: u32, token: u32, ctx: ?*anyopaque, sink: *const fn (?*anyopaque, *KindJob) void) void { const j = take(p, pane, serial, token) orelse return; + if (!go(io, tasks, j, ctx, sink)) here(j, p); + } + + /// `j` on a worker of `io`, posting itself to `sink` done; false when + /// none could take it. + pub fn go(io: std.Io, tasks: *selection_pipe.Tasks, j: *KindJob, ctx: ?*anyopaque, sink: *const fn (?*anyopaque, *KindJob) void) bool { next_id +%= 1; j.id = next_id | 0x8000_0000; const work = struct { @@ -145,9 +156,10 @@ pub const KindJob = struct { s(c, job); } }.work; - if (tasks.full()) return here(j, p); - const future = io.concurrent(work, .{ j, ctx, sink }) catch return here(j, p); + if (tasks.full()) return false; + const future = io.concurrent(work, .{ j, ctx, sink }) catch return false; _ = tasks.add(.{ .id = j.id, .future = future }); + return true; } var next_id: u32 = 0; diff --git a/src/kinds/addon.zig b/src/kinds/addon.zig index 557547f6..1fa2279a 100644 --- a/src/kinds/addon.zig +++ b/src/kinds/addon.zig @@ -19,7 +19,7 @@ //! dump(s, buf) usize load(s, bytes, version) bool search(s, pat) void //! //! and pardes's side (pa_api) as the functions below: `arena` and `heap` -//! as Allocators, `seed`, `say`, `job`, `cancel`, `look`, `text`, `exec`, +//! as Allocators, `seed`, `say`, `job`, `draw`, `cancel`, `look`, `text`, `exec`, //! `select` and `found`. A body written is at most `body_max` bytes. //! //! pub const pardes_addon = addon.ops(Snake); @@ -36,9 +36,9 @@ pub const c = @import("pardes_addon"); const Allocator = std.mem.Allocator; /// The ABI this file speaks: a header of another needs it brought along. -pub const abi = 0x30001; +pub const abi = 0x30002; comptime { - if (c.PA_ABI != abi) @compileError("addon.zig speaks ABI 3.1 and the header another"); + if (c.PA_ABI != abi) @compileError("addon.zig speaks ABI 3.2 and the header another"); } /// A word the kind brings: `opens` a pane of it, else goes to the pane's @@ -87,6 +87,14 @@ pub fn say(text_: []const u8, how: enum { note, err }) void { pub fn job(in: []const u8) u32 { return api.job.?(in.ptr, @intCast(in.len)); } +/// A picture's job (pa_api.draw): `jobRun` over a copy of `in` on a worker +/// of the process that shows the pane, its answer to `jobDone` there alone +/// (`token & drawn`), which keeps it for `paint` only. 0 when refused. +pub fn draw(in: []const u8) u32 { + if (api.size < @sizeOf(c.pa_api)) return 0; + return api.draw.?(in.ptr, @intCast(in.len)); +} +pub const drawn = c.PA_DRAWN; /// A job's answer not yet come dropped. pub fn cancel(token: u32) void { api.cancel.?(token); diff --git a/src/kinds/pardes_addon.h b/src/kinds/pardes_addon.h index 586b03d3..11dcec38 100644 --- a/src/kinds/pardes_addon.h +++ b/src/kinds/pardes_addon.h @@ -37,7 +37,7 @@ /* Major in the high half: an addon of another major is refused. */ #define PA_ABI_MAJOR 3u -#define PA_ABI_MINOR 1u +#define PA_ABI_MINOR 2u #define PA_ABI ((PA_ABI_MAJOR << 16) | PA_ABI_MINOR) #define PA_OK 0 #define PA_RASTER_MAX (32u << 20) /* a placement's w*h*4 above this is dropped, said once */ @@ -225,7 +225,18 @@ typedef struct pa_api { void (*found)(const char *rows, uint32_t n); /* The core's PA_ABI. */ uint32_t abi, pad; + /* Since 3.2 (check api->size): a picture's job, made where the pane is + * shown. `job_run` over a copy of `in` on a worker of this process, its + * answer to `job_done` here alone, its token PA_DRAWN: never on the tape, + * in the digest or sent to another process (each that shows the pane + * asks its own, from the same call). A draw's answer changes pixels + * only: what job_done keeps of it (memory of its own, api->heap: never a + * PA_PLAIN kind's block, nor its token) `paint` alone reads; no other + * call reads it, or anything made from it. 0: refused. */ + uint32_t (*draw)(const void *in, uint32_t n); } pa_api; +/* A token of api->draw's. */ +#define PA_DRAWN 0x80000000u /* What a job allocates from, on its worker (pa_api is not there): as often * as it needs, all of it freed after its job_done. The last it allocates @@ -287,7 +298,10 @@ typedef struct pa_tick { * from the session's very bytes, its keys at once * and its pictures its own, and a client without the addon shows a line. * A kind that breaks the promise is caught: the client's state is not the - * session's, and it joins again without the kind. */ + * session's, and it joins again without the kind. Its pictures are each + * process's own (api->draw), kept outside the block (api->heap), found by + * the block's address; a pane with a file is opened in a client from the + * file's bytes as the session's was. */ #define PA_PLAIN 0x2u typedef struct pa_head { @@ -376,7 +390,7 @@ _Static_assert(sizeof(pa_rect) == 16 && sizeof(pa_cells) == 8, "pa_rect"); _Static_assert(sizeof(pa_placement) == 80, "pa_placement"); _Static_assert(sizeof(pa_paint) == 48 && sizeof(pa_view) == 32 && sizeof(pa_tick) == 128, "pa_paint"); _Static_assert(sizeof(pa_key) == 8 && sizeof(pa_mouse) == 16, "pa_key"); -_Static_assert(sizeof(pa_api) == 112 && sizeof(pa_out) == 16, "pa_api"); +_Static_assert(sizeof(pa_api) == 120 && sizeof(pa_out) == 16, "pa_api"); _Static_assert(sizeof(pa_word) == 32 && sizeof(pa_head) == 56, "pa_head"); _Static_assert(sizeof(pa_ops) == 208, "pa_ops"); #endif diff --git a/src/tui/tui.zig b/src/tui/tui.zig index 919eeded..3938c854 100644 --- a/src/tui/tui.zig +++ b/src/tui/tui.zig @@ -737,6 +737,8 @@ pub fn runClient(init: std.process.Init, opts: pardes.Options, path: []const u8, .client = &client_link, }; + pardes.Kind.drawer = .{ .ctx = &sh, .go = Shell.draw }; + defer pardes.Kind.drawer = null; try startInput(&loop, &screen); defer stopInput(io, &screen.thread); (try std.Thread.spawn(.{}, winchWatch, .{&loop})).detach(); @@ -1073,6 +1075,8 @@ fn localSession( const host = sh.host(); core.host = host; + pardes.Kind.drawer = .{ .ctx = &sh, .go = Shell.draw }; + defer pardes.Kind.drawer = null; // An upgraded session's terminals, its own again. if (comptime !builtin.is_test) if (upgrade.resumed) |*rec| sh.resumeTerminals(rec); // Nobody to see it, and nobody to size it: `size` sets it (ctl.zig). @@ -1831,6 +1835,8 @@ const Shell = struct { .kind_job => |j| { s.job_tasks.finish(s.io, j.id); j.land(core); + // A client's draw done: its frame is its own to draw again. + if (s.client) |cl| cl.link.dirty = true; }, } return false; @@ -2202,6 +2208,16 @@ const Shell = struct { pardes.Stream.runHere(s.core, gen); } + /// A draw (api.draw) on a worker, as a job is. + fn draw(ctx: ?*anyopaque, j: *host_io.KindJob) bool { + const s = of(ctx); + return (s.threads_ok or s.client != null) and host_io.KindJob.go(s.io, &s.job_tasks, j, s, struct { + fn deliver(c: ?*anyopaque, k: *host_io.KindJob) void { + of(c).loop.postEvent(.{ .kind_job = k }) catch k.drop(); + } + }.deliver); + } + fn job(ctx: ?*anyopaque, pane: u8, serial: u32, token: u32) void { const s = of(ctx); if (!s.threads_ok) return host_io.KindJob.runHere(s.core, pane, serial, token); -- cgit v1.3 From 3350156db428656fa8e583d1971663e1c4a215b0 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Wed, 18 Nov 2026 05:48:27 -0300 Subject: image: the image kind runs where its pane is shown (PA_PLAIN): its block is the file's size as it says, the same bytes in every process, and each process decodes the file on a draw of its own and keeps the RGBA beside the block (by its address) for its paint alone, so a client draws the picture itself and the session sends nothing for the pane (no Shadow, no decoded pixels in a job's answer on the tape); a plain kind's code is loaded in a client at its first pane, not at the join (Addon.need; a client with no picture or game maps no addon library); a client that joins late opens a plain kind's pane from its file, which the join's dump carries, read from the disk then (SlotRecord.file: paid only at a join), and one it cannot open shows the line; a client's join with a picture and a PDF open reads 10.70 MB -> 7.36 MB, its picture the session's pixel for pixel, its memory 269.1 -> 272.5 MB RSS (184.2 -> 187.6 PSS); with no client perf --only medium 2,279.68M -> 2,279.60M instructions:u, pdf-scroll-bench 18,392-18,399M -> 18,397-18,402M (its visual hashes the same), start to the first frame 53.6M (terminal) and 392-411M (window) as before; tui core-test 819/958 (139 skipped), shell-test 993/996, behaviour-test 273/273, --replay 20 seeds 0 failures, pane-test 180/181 (the picture's tag test steps the core, as no job's event does now), replicas pass, addon-test 1/1, process-test 2 of 144 failed (lspcomplete and lspcompletemoved, the base's), image-harness passes, test/daemon.py, --far, --games (keys stopped 0 and 0 of 453 and 452) and --window-clients pass; gui unit-test 1586/1590 (4 skipped; the perf check's BaselineBuildMismatch, the base's), the frame corpus 77/77 against mbase, pdf-harness CaptureColorMissing as on the base Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T --- addons/image/image.zig | 64 ++++++++++++++++++++++++++++++++++++-------------- src/Addon.zig | 10 ++++++-- src/Kind.zig | 6 ++++- src/dump.zig | 19 ++++++++++++++- src/replica.zig | 14 ++++++----- test/panes.zig | 3 ++- 6 files changed, 87 insertions(+), 29 deletions(-) (limited to 'src') diff --git a/addons/image/image.zig b/addons/image/image.zig index 09b17ca7..f2303433 100644 --- a/addons/image/image.zig +++ b/addons/image/image.zig @@ -1,7 +1,9 @@ //! image.zig: pictures as a pardes addon (.png .jpg .gif .bmp .ppm .pgm .tga). -//! A pane decodes its file's bytes on a job with stb_image (stb.c), at most -//! max_dim pixels a side; the core shows the RGBA fitted to the pane (or as -//! glyph art, its Petscii word). It has no record: a Restore reads the file. +//! A pane's state is its file's size (PA_PLAIN: a client runs it as the +//! session does); each process that shows it decodes the file's bytes on a +//! draw (api.draw) with stb_image (stb.c), at most max_dim pixels a side, +//! and keeps the RGBA for its paint alone. The core shows it fitted to the +//! pane (or as glyph art, its Petscii word). const std = @import("std"); const addon = @import("addon"); @@ -12,10 +14,10 @@ extern fn pa_image_info(bytes: [*]const u8, n: c_int, w: *c_int, h: *c_int) c_in extern fn pa_image_load(bytes: [*]const u8, n: c_int, w: *c_int, h: *c_int) ?[*]const u8; extern fn pa_image_resize(in: [*]const u8, w: c_int, h: c_int, out: [*]u8, nw: c_int, nh: c_int) c_int; -/// stb's memory (stb.c): the job's on a worker, else the pane's arena. +/// stb's memory (stb.c): an arena of the call's (a draw's, or `info`'s). threadlocal var job: ?std.mem.Allocator = null; export fn pa_image_mem(n: usize) ?*anyopaque { - return ((job orelse addon.arena).alignedAlloc(u8, .@"16", n) catch return null).ptr; + return ((job orelse return null).alignedAlloc(u8, .@"16", n) catch return null).ptr; } export fn pa_image_remem(p: ?*anyopaque, old: usize, n: usize) ?*anyopaque { const q: [*]u8 = @ptrCast(pa_image_mem(n) orelse return null); @@ -25,24 +27,44 @@ export fn pa_image_remem(p: ?*anyopaque, old: usize, n: usize) ?*anyopaque { /// Its width and height, if stb can read it. fn info(bytes: []const u8) ?[2]u32 { + var arena: std.heap.ArenaAllocator = .init(addon.heap); + defer arena.deinit(); + job = arena.allocator(); + defer job = null; var w: c_int, var h: c_int = .{ 0, 0 }; if (bytes.len == 0 or bytes.len > std.math.maxInt(c_int) or pa_image_info(bytes.ptr, @intCast(bytes.len), &w, &h) == 0) return null; return .{ @intCast(w), @intCast(h) }; } -pub const Image = struct { +/// Each pane's pixels in this process, by its block's address: a draw's +/// answer, which paint alone reads. +const Picture = struct { of: ?*const Image = null, w: u32 = 0, h: u32 = 0, rgba: []u8 = &.{} }; +var pictures: [64]Picture = @splat(.{}); + +fn pictureOf(im: *const Image) ?*Picture { + for (&pictures) |*p| if (p.of == im) return p; + return null; +} + +pub const Image = extern struct { + /// The file's size, as it says (the block: the same in every process). w: u32 = 0, h: u32 = 0, - rgba: ?[]const u8 = null, // w x h, once its job is done - pub const head: addon.Head = .{ .name = "image", .version = 1, .exts = ".png .jpg .jpeg .gif .bmp .ppm .pgm .tga", .pictures = true }; + pub const head: addon.Head = .{ .name = "image", .version = 1, .exts = ".png .jpg .jpeg .gif .bmp .ppm .pgm .tga", .pictures = true, .plain = true }; - /// Decoded on a job; one it cannot read (corrupt, truncated, not what + /// Decoded on a draw; one it cannot read (corrupt, truncated, not what /// its name says) is refused, rather than shown as a blank pane. - pub fn open(_: *Image, _: ?[]const u8, bytes: ?[]const u8) void { + pub fn open(im: *Image, _: ?[]const u8, bytes: ?[]const u8) void { const b = bytes orelse return; - if (info(b) == null) return addon.say("not an image pardes can read", .err); - _ = addon.job(b); + im.w, im.h = info(b) orelse return addon.say("not an image pardes can read", .err); + _ = addon.draw(b); + } + + pub fn close(im: *Image) void { + const p = pictureOf(im) orelse return; + addon.heap.free(p.rgba); + p.* = .{}; } /// The core follows it with its art words and the path. @@ -51,17 +73,18 @@ pub const Image = struct { } pub fn paint(im: *const Image, w: addon.Window, out: addon.Paint) void { - const rgba = im.rgba orelse return; - out.place(.{ .rgba = rgba.ptr, .w = im.w, .h = im.h, .src = .{ .w = im.w, .h = im.h }, .dst = .{ .w = w.cols, .h = w.rows } }); + const p = pictureOf(im) orelse return; + out.place(.{ .rgba = p.rgba.ptr, .w = p.w, .h = p.h, .src = .{ .w = p.w, .h = p.h }, .dst = .{ .w = w.cols, .h = w.rows } }); } /// On a worker: width and height (little endian), then the RGBA. pub fn jobRun(in: []const u8, gpa: std.mem.Allocator) ?[]u8 { job = gpa; defer job = null; - const wh = info(in) orelse return null; - if (@as(u64, wh[0]) * wh[1] > max_pixels) return null; var w: c_int, var h: c_int = .{ 0, 0 }; + if (in.len == 0 or in.len > std.math.maxInt(c_int) or pa_image_info(in.ptr, @intCast(in.len), &w, &h) == 0) return null; + const wh: [2]u32 = .{ @intCast(w), @intCast(h) }; + if (@as(u64, wh[0]) * wh[1] > max_pixels) return null; var px = pa_image_load(in.ptr, @intCast(in.len), &w, &h) orelse return null; const longest: u64 = @max(wh[0], wh[1]); var nw, var nh = wh; @@ -79,13 +102,18 @@ pub const Image = struct { return a; } + /// A draw's answer: this process's pixels, the block untouched. pub fn jobDone(im: *Image, _: u32, out: []const u8) void { if (out.len < 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 != out.len - 8) return; - im.rgba = addon.arena.dupe(u8, out[8..]) catch return; - im.w, im.h = .{ w, h }; + const p = pictureOf(im) orelse for (&pictures) |*free| { + if (free.of == null) break free; + } else return; + const rgba = addon.heap.dupe(u8, out[8..]) catch return; + addon.heap.free(p.rgba); + p.* = .{ .of = im, .w = w, .h = h, .rgba = rgba }; } }; diff --git a/src/Addon.zig b/src/Addon.zig index 16c38758..398ec415 100644 --- a/src/Addon.zig +++ b/src/Addon.zig @@ -343,7 +343,12 @@ fn listed(data: []const u8, path: []const u8, n: usize, why: *Why) Loaded { /// library loaded at the first pane of its kind, from the file the start /// listed it from (`listed`); null, and why, when it will not load. pub fn need(r: *Kind.Registry, k: u8, why: *Why) ?*const Kind.Ops { - if (r.ops[k] != null or tape.replaying()) return r.ops[k]; + if (r.ops[k] != null) return r.ops[k]; + // A client's: its own code for a plain kind, loaded at its first pane. + if (tape.replaying()) { + r.ops[k] = plainOps(&r.kinds[k]); + return r.ops[k]; + } const e = &r.kinds[k]; for (found[0..nfound], 0..) |*l, i| if (l.why.len == 0 and std.mem.eql(u8, &l.hash, &e.hash) and std.mem.eql(u8, l.path, e.path.slice())) { if (l.ops == 0) l.ops = loadListed(i, why) orelse return null; @@ -617,7 +622,8 @@ pub fn take(r: *Kind.Registry, l: Loaded, except: []const u8) ?[]const u8 { } e.why.set("loaded"); // A client's: its own code for a plain kind, or none (the session's). - r.ops[r.n] = if (tape.replaying()) plainOps(e) else @ptrFromInt(l.ops); + // A client's code for a plain kind is loaded at its first pane (`need`). + r.ops[r.n] = if (tape.replaying()) null else @ptrFromInt(l.ops); for (l.words) |w| { r.words[r.nwords] = .{ .kind = r.n, .arg = w.arg, .opens = w.opens }; r.words[r.nwords].name.set(w.name); diff --git a/src/Kind.zig b/src/Kind.zig index 47384227..374a2d81 100644 --- a/src/Kind.zig +++ b/src/Kind.zig @@ -138,7 +138,7 @@ pub const Slot = struct { // jobs' inputs, its file's hash, a placeholder's record), and what // a frame makes (the thumb, the pointer, whether one was drawn: a // view's, never a step's). - .local = .{ "ops", "st", "gpa", "arena", "plain", "opened", "reloads", "jobs", "tokens", "record", "thumb_at", "thumb_span", "pointer", "painted", "over", "shadow", "used" }, + .local = .{ "ops", "st", "gpa", "arena", "plain", "file", "opened", "reloads", "jobs", "tokens", "record", "thumb_at", "thumb_span", "pointer", "painted", "over", "shadow", "used" }, }; /// Its kind's code here; null in a placeholder (`live` false: its kind /// not in the registry, its record kept for the day it comes) or a @@ -213,6 +213,9 @@ pub const Slot = struct { tail: Buf(160) = .{}, /// A replica's frame of it, as the authority painted it. shadow: ?*Shadow = null, + /// A client's join: its plain kind's file, until the pane is opened + /// from it (dump.plainHere). + file: ?[]u8 = null, /// Debug: the kind's allocations, which paint must leave as they are /// (the list the page allocator's: a region's first is slow in Debug). used: if (checked) std.ArrayList([]u8) else void = if (checked) .empty else {}, @@ -240,6 +243,7 @@ pub const Slot = struct { s.arena.deinit(); s.gpa.free(s.path); if (s.record) |r| s.gpa.free(r); + if (s.file) |f| s.gpa.free(f); s.* = undefined; } }; diff --git a/src/dump.zig b/src/dump.zig index 971a4d26..c5e2953b 100644 --- a/src/dump.zig +++ b/src/dump.zig @@ -263,11 +263,15 @@ pub fn image(p: *Pardes, name: []const u8) ![]u8 { pub fn dumpJoin(p: *Pardes, deferred: *std.ArrayListUnmanaged(walk.Deferred)) ![]u8 { slim_terminals = true; defer slim_terminals = false; + join_files = true; + defer join_files = false; return dumpWith(p, deferred); } /// `dumpJoin`'s and `dumpExit`'s: a terminal dumps its size, not its emulator. pub var slim_terminals = false; +/// `dumpJoin`'s: a plain kind's pane carries its file (SlotRecord.file). +var join_files = false; fn dumpWith(p: *Pardes, deferred: ?*std.ArrayListUnmanaged(walk.Deferred)) ![]u8 { var d = try Session.init(p.gpa); @@ -782,6 +786,9 @@ const SlotRecord = struct { selection: []const u8 = "", /// A plain kind's block's hash (Kind.Slot.state). state: u64 = 0, + /// A client's join (`dumpJoin`): a plain kind's file, as the disk has + /// it now, which the client opens the pane from (plainHere). + file: ?[]const u8 = null, }; pub fn slotWrite(s: *const Kind.Slot, gpa: std.mem.Allocator, w: *std.Io.Writer) !void { @@ -795,6 +802,15 @@ pub fn slotWrite(s: *const Kind.Slot, gpa: std.mem.Allocator, w: *std.Io.Writer) owned = if (s.plain) |b| (if (b.len > 0) try s.gpa.dupe(u8, b) else null) else try slotRecord(@constCast(s)); r.record = owned; } + // Paid only at a client's join: the session keeps no file's bytes. + var file: ?[]u8 = null; + defer if (file) |f| s.gpa.free(f); + if (join_files and s.plain != null and s.ops != null) if (filesystem.localPath(s.path)) |path| { + const z = try s.gpa.dupeSentinel(u8, path, 0); + defer s.gpa.free(z); + file = filesystem.readHost(s.gpa, z, pardes.memory.limits.max_file_bytes) catch null; + r.file = file; + }; const bytes = try walk.save(SlotRecord, gpa, &r); defer gpa.free(bytes); try w.writeAll(bytes); @@ -830,6 +846,7 @@ pub fn slotRead(out: *Kind.Slot, gpa: std.mem.Allocator, bytes: []const u8) !voi out.values.set(r.values); out.selection = try gpa.dupe(u8, r.selection); if (r.record) |rec| out.record = try gpa.dupe(u8, rec); + if (r.file) |f| out.file = try gpa.dupe(u8, f); } pub fn slotFree(s: *Kind.Slot, gpa: std.mem.Allocator) void { @@ -883,7 +900,7 @@ pub fn plainHere(p: *Pardes, id: usize, old: *Kind.Slot, ops: *const Kind.Ops) ! s.path = try p.gpa.dupe(u8, old.path); s.selection = try p.gpa.dupe(u8, old.selection); const kept = .{ old.next_tick, old.views, old.focused, old.state }; - if (!Kind.reopen(p, id, s, null)) return error.KindRefused; + if (!Kind.reopen(p, id, s, old.file)) return error.KindRefused; // Its block the session's, byte for byte (its record), never through // the kind's load, which may tidy it. const block = s.plain orelse return error.KindRefused; diff --git a/src/replica.zig b/src/replica.zig index f84e61e8..b1b0514c 100644 --- a/src/replica.zig +++ b/src/replica.zig @@ -762,12 +762,14 @@ pub const Replica = struct { const c = try pardes.dump.load(epoch, o, bytes, null); // The chrome's colours are local, never dumped: the restored theme's. pardes.colors.finishThemeInitialization(c); - // It runs a plain kind's code of its own (Addon.plainOps), each pane - // of one opened here from its record; another's panes are Shadows. - for (c.kinds.kinds[0..c.kinds.n], c.kinds.ops[0..c.kinds.n]) |*e, *ops| ops.* = pardes.Addon.plainOps(e); - @memset(c.kinds.ops[c.kinds.n..], null); - for (c.panes, 0..) |pslot, at| if (pslot) |pane| if (pane.addon) |s| if (c.kinds.byName(s.nameOf())) |k| if (c.kinds.ops[k]) |ops| { - pane.addon = try pardes.dump.plainHere(c, at, s, ops); + // It runs a plain kind's code of its own (Addon.plainOps), loaded + // at its first pane, each opened here from its record; another's + // panes are Shadows. + c.kinds.ops = @splat(null); + for (c.panes, 0..) |pslot, at| if (pslot) |pane| if (pane.addon) |s| if (c.kinds.byName(s.nameOf())) |k| { + if (c.kinds.ops[k] == null) c.kinds.ops[k] = pardes.Addon.plainOps(&c.kinds.kinds[k]); + // Refused (its file not here): the line saying it does not run here. + if (c.kinds.ops[k]) |ops| pane.addon = pardes.dump.plainHere(c, at, s, ops) catch s; }; // What loading queued (a watch, a theme asked for) is the // authority's errand, done there already: the session was dumped diff --git a/test/panes.zig b/test/panes.zig index 2082c3ad..d47136a5 100644 --- a/test/panes.zig +++ b/test/panes.zig @@ -2259,7 +2259,8 @@ const ImageTests = struct { // art words after the kind's `img`, then its path. const id = p.freeSlot().?; const pane = try pardes.Kind.open(p, id, load(p), "/tmp/picture.ppm", "P6\n1 1\n255\n\x01\x02\x03"); - while (p.nextEffect()) |e| p.perform(e); + // Its tick after the open (its decode a draw: no job's event steps it). + pardes.Kind.step(p, true); pardes.layout.placeNew(p, 0, 0, id, .doc); _ = try p.render(p.scratch.allocator()); pane.addon.?.art = .{ .glyph = true, .palette = .terminal, .ascii = false }; -- cgit v1.3