diff options
| author | Gabriel Schneider <[email protected]> | 2026-10-30 17:35:06 -0300 |
|---|---|---|
| committer | Gabriel Schneider <[email protected]> | 2026-10-30 17:35:06 -0300 |
| commit | 6d8da8721141284cf33bb901168b26135893eb86 (patch) | |
| tree | 791d63401d4e85fbca1d597a8ce0326e70efd545 /src/detached | |
| parent | efd43a3a2cf03bb741366331158b368abf9ac583 (diff) | |
| parent | bf6810a8f9d6cc82050e7d9c0cfb06358301b574 (diff) | |
| download | pardes-6d8da8721141284cf33bb901168b26135893eb86.tar.gz pardes-6d8da8721141284cf33bb901168b26135893eb86.zip | |
Merge latest upstream into the macOS branch for Zig 0.17
Retain the macOS branch history and local Acme selection color while adopting upstream's current core and platform changes. Pin Zig and ZLS to 0.17.0, and fetch the existing zstbi compatibility commit through upstream after its original fork was removed.
Diffstat (limited to 'src/detached')
| -rw-r--r-- | src/detached/client.zig | 121 | ||||
| -rw-r--r-- | src/detached/server.zig | 645 | ||||
| -rw-r--r-- | src/detached/wire.zig | 1096 |
3 files changed, 1089 insertions, 773 deletions
diff --git a/src/detached/client.zig b/src/detached/client.zig index 9481cd54..617ae342 100644 --- a/src/detached/client.zig +++ b/src/detached/client.zig @@ -59,6 +59,7 @@ const std = @import("std"); const libc = std.c; const pardes = @import("../pardes.zig"); +const dump = @import("../dump.zig"); const server = @import("server.zig"); const wire = @import("wire.zig"); @@ -102,8 +103,16 @@ pub const Client = struct { grid: std.ArrayListUnmanaged(pardes.Cell) = .empty, cursor: ?wire.Cursor = null, pointer_shape: pardes.Surface.PointerShape = .arrow, - body_layers: [pardes.MAX_PANES]pardes.BodyLayer = @splat(.{}), - tag_layers: [pardes.MAX_TAG_LAYERS]pardes.TagLayer = @splat(.{}), + body_layers: [pardes.MAX_PANES]pardes.Layer = @splat(.{}), + tag_layers: [pardes.MAX_TAG_LAYERS]pardes.Layer = @splat(.{}), + /// The session's placed regions, as its last frame gave them. + regions: std.ArrayListUnmanaged(pardes.Region) = .empty, + /// The palette its chrome is drawn in, as its last frame gave it. + chrome: pardes.Chrome = .{}, + /// The post chain its frames are drawn through, as the session last + /// sent it; its paths and SPIR-V owned here. `post_key` moves with it. + post: wire.Post = .{}, + post_key: u32 = 0, in: std.ArrayListUnmanaged(u8) = .empty, out: std.ArrayListUnmanaged(u8) = .empty, /// Bytes of `in` belonging to the message `next` returned last. Compacted at @@ -156,7 +165,7 @@ pub const Client = struct { _ = libc.close(fd); return error.NoSession; } - server.setNonblock(fd); + _ = server.setNonblock(fd); var c: Client = .{ .gpa = gpa, .fd = fd }; errdefer c.deinit(); try c.send(.{ .hello = .{ @@ -181,6 +190,8 @@ pub const Client = struct { layer.* = .{}; } for (&c.tag_layers) |*layer| c.gpa.free(layer.cells); + c.regions.deinit(c.gpa); + c.freePost(); c.in.deinit(c.gpa); c.out.deinit(c.gpa); } @@ -214,7 +225,7 @@ pub const Client = struct { // next flush: the session decodes it as a message, refuses it, and // drops a frontend whose only mistake was a message this protocol // cannot carry (an `Event.command` past 64 KiB is `Overlong`, and a - // caller that mis-sized the queue is `NoSpace`). + // caller that mis-sized the queue is `WriteFailed`). c.out.items.len = at; return err; }; @@ -318,7 +329,7 @@ pub const Client = struct { try c.reshape(f.cols, f.rows); } try f.apply(c.grid.items); - f.applyLayers(c.gpa, &c.body_layers, &c.tag_layers) catch |err| return switch (err) { + f.applyLayers(c.gpa, &c.body_layers, &c.tag_layers, &c.regions, &c.chrome) catch |err| return switch (err) { error.OutOfMemory => error.Closed, else => @as(wire.Error, @errorCast(err)), }; @@ -350,10 +361,30 @@ pub const Client = struct { // open a URI on this display or read this display's selection back // over the socket. `Ungreeted` is the same refusal a frame gets. .set_clipboard, .read_clipboard, .open_link => if (!c.attached()) return error.Ungreeted, + // Kept, like the chrome: the frames that follow are drawn + // through it. + .post => |chain| { + if (!c.attached()) return error.Ungreeted; + c.freePost(); + c.post = chain; + for (c.post.passes[0..c.post.len]) |*pass| { + pass.path = c.gpa.dupe(u8, pass.path) catch return error.Closed; + pass.spirv = c.gpa.dupe(u8, pass.spirv) catch return error.Closed; + } + c.post_key +%= 1; + }, } return msg; } + fn freePost(c: *Client) void { + for (c.post.passes[0..c.post.len]) |pass| { + c.gpa.free(pass.path); + c.gpa.free(pass.spirv); + } + c.post = .{}; + } + // ---- internals -------------------------------------------------------- fn reshape(c: *Client, cols: u16, rows: u16) (Error || wire.Error)!void { @@ -837,24 +868,25 @@ test "detached Restore keeps attached frontends and follows queued frames with a const fd = h.session.clients[c.slot].fd; try testing.expectError(error.BadDumpMagic, h.session.restore( ".{ .magic = \"not-a-pardes-dump\", .theme = \"dark\", .screen = .{ .cols = 60, .rows = 16 } }", + "test", )); try testing.expectEqual(before, h.session.core); try testing.expectEqual(fd, h.session.clients[c.slot].fd); try testing.expect(h.session.clients[c.slot].attached); - try h.core.dumpState(); + try dump.dumpState(h.core); const saved = try testing.allocator.dupe(u8, h.core.dump_out.?); defer testing.allocator.free(saved); while (h.core.nextEffect()) |_| {} _ = try h.core.setTestFile("changed after dump\n"); - try h.session.restore(saved); + try h.session.restore(saved, "test"); h.core = h.session.core; try testing.expect(h.core != before); try testing.expectEqual(fd, h.session.clients[c.slot].fd); try testing.expect(h.session.clients[c.slot].attached); try testing.expectEqualStrings("saved body\n", h.core.panes[0].?.file.?.content); try testing.expect(h.session.clients[c.slot].need_full); - var wake = [_]libc.pollfd{.{ .fd = h.session.mailbox.wake[0], .events = poll_in, .revents = 0 }}; + var wake = [_]libc.pollfd{.{ .fd = h.session.wake[0], .events = poll_in, .revents = 0 }}; try testing.expectEqual(@as(c_int, 1), libc.poll(&wake, wake.len, 0)); for (0..Harness.rounds) |_| { if ((try h.pumpUntil(&c, .frame)).frame.kind == .full) break; @@ -867,9 +899,9 @@ test "detached selection pipe runs off the loop and returns through the attached try h.init(60, 16); defer h.deinit(); const pane = try h.core.setTestFile("one\ntwo\n"); - pane.cur_row = 0; - pane.cur_col = 2; - pane.vsel = .{ .active = true, .row = 0, .col = 0, .explicit = true }; + pane.body.cur_row = 0; + pane.body.cur_col = 2; + pane.body.vsel = .{ .active = true, .row = 0, .col = 0, .explicit = true }; var client = try h.attach(60, 16); defer client.deinit(); _ = try h.pumpUntil(&client, .frame); @@ -883,7 +915,7 @@ test "detached selection pipe runs off the loop and returns through the attached while (try client.next()) |_| {} if (std.mem.eql(u8, pane.file.?.content, "ONE\ntwo\n")) break; } else return error.PipeDidNotComplete; - try testing.expect(h.core.pipe_wait == null); + try testing.expect(h.core.pipe.wait == null); try testing.expectEqual(@as(usize, 0), h.session.pipe_tasks.len); try h.pumpUntilShowsCore(&client); } @@ -994,6 +1026,12 @@ test "detached session: a frontend that dies takes nothing with it" { } test "detached session: a frontend speaking another protocol is refused, loudly" { + // The protocol before this one (v7 carried one-row tags and no regions) + // and the one after. + for ([_]u16{ wire.version - 1, wire.version + 1 }) |claimed| try refusedHello(claimed); +} + +fn refusedHello(claimed: u16) !void { var h: Harness = undefined; try h.init(60, 16); defer h.deinit(); @@ -1005,7 +1043,7 @@ test "detached session: a frontend speaking another protocol is refused, loudly" defer _ = libc.close(fd); var buf: [64]u8 = undefined; const hello = try wire.encodeClient(&buf, .{ - .hello = .{ .version = wire.version + 1, .cols = 60, .rows = 16 }, + .hello = .{ .version = claimed, .cols = 60, .rows = 16 }, }); try testing.expectEqual(@as(isize, @intCast(hello.len)), libc.send(fd, hello.ptr, hello.len, nosignal)); @@ -1023,6 +1061,17 @@ test "detached session: a frontend speaking another protocol is refused, loudly" try testing.expect(!h.core.quit); } +test "detached frontend: a session speaking another protocol is not attached to" { + for ([_]u16{ wire.version - 1, wire.version + 1 }) |claimed| { + var c: Client = .{ .gpa = testing.allocator }; + defer c.deinit(); + var buf: [64]u8 = undefined; + try c.in.appendSlice(testing.allocator, try wire.encodeServer(&buf, .{ .welcome = .{ .version = claimed, .slot = 0, .cols = 60, .rows = 16 } })); + try testing.expectError(error.Ungreeted, c.next()); + try testing.expect(!c.attached()); + } +} + test "detached session: a peer that sends garbage is dropped, not obeyed" { var h: Harness = undefined; try h.init(60, 16); @@ -1107,7 +1156,7 @@ test "detached session: the seam's own routing rules, per surviving effect" { test "detached session: a frontend is never asked to fork, write, or watch" { // THE INVARIANT OF THE WHOLE DETACHED DESIGN, pinned as a property of the // protocol rather than of one code path: a frontend is input and screen, so - // the set of messages that can reach it is exactly the eight below. If a + // the set of messages that can reach it is exactly the nine below. If a // machine-local effect is ever put back on the wire, a frontend becomes the // process that owns a pane's shell again — and a pane whose shell belongs to // a frontend dies when that frontend leaves, which is the bug this replaced. @@ -1125,16 +1174,20 @@ test "detached session: a frontend is never asked to fork, write, or watch" { // The three that need THIS human's display and cannot be done by a // daemon nobody is looking at. "set_clipboard", "read_clipboard", "open_link", + // Display state, like a frame's chrome: the passes this display + // draws its frames through. A file's SPIR-V arrives compiled, so the + // frontend still reads no disk and runs no program. + "post", }; // One: the union a frontend decodes into has no other variant. Named // rather than counted, so re-adding `spawn` fails with the name in it. - const fields = @typeInfo(wire.ServerMsg).@"union".fields; - inline for (fields) |f| { + const fields = @typeInfo(wire.ServerMsg).@"union".field_names; + inline for (fields) |name| { for (allowed) |ok| { - if (std.mem.eql(u8, f.name, ok)) break; + if (std.mem.eql(u8, name, ok)) break; } else { - std.debug.print("ServerMsg.{s} is not an effect a frontend may perform\n", .{f.name}); + std.debug.print("ServerMsg.{s} is not an effect a frontend may perform\n", .{name}); return error.MachineLocalEffectOnTheWire; } } @@ -1148,7 +1201,7 @@ test "detached session: a frontend is never asked to fork, write, or watch" { for (0..256) |i| { const tag: u8 = @intCast(i); // Payloads are deliberately empty: what is asked is whether the TAG is - // known, and every known tag fails later (`Truncated`) or succeeds, but + // known, and every known tag fails later (`EndOfStream`) or succeeds, but // never with `BadTag`. if (wire.decodeServer(tag, &.{})) |_| accepted += 1 else |err| switch (err) { error.BadTag => continue, @@ -1156,10 +1209,10 @@ test "detached session: a frontend is never asked to fork, write, or watch" { } const named = for (allowed) |ok| { const want = std.meta.stringToEnum(wire.ServerTag, ok).?; - if (@intFromEnum(want) == tag) break true; + if (@backingInt(want) == tag) break true; } else false; if (!named) { - std.debug.print("tag 0x{x:0>2} is decodable by a frontend and is not one of the seven\n", .{tag}); + std.debug.print("tag 0x{x:0>2} is decodable by a frontend and is not one of the nine\n", .{tag}); return error.MachineLocalEffectOnTheWire; } } @@ -1266,8 +1319,32 @@ test "detached session: a frontend that stops reading is dropped, not waited for // for, which is the whole claim: one slow peer costs its own slot. try testing.expect(h.session.clients[0].attached); try testing.expect(!h.core.quit); + // A message is a tagline band now, not a grid run, so "still being drawn + // for" is checked on the layers the frontend decoded rather than on nruns. try good.send(.{ .event = .{ .command = "Msg still here" } }); - try testing.expect((try h.pumpUntilChange(&good)).nruns > 0); + try testing.expect(try pumpUntilNotice(&h, &good, "still here")); +} + +/// Pump until this client has a notice band carrying `want`. +fn pumpUntilNotice(h: *Harness, c: *Client, want: []const u8) !bool { + var line: [256]u8 = undefined; + for (0..Harness.rounds) |_| { + try h.pump(); + try c.wait(5); + while (try c.next()) |_| {} + for (&c.tag_layers) |*layer| { + if (layer.rows == 0 or layer.kind != .notice) continue; + var n: usize = 0; + for (layer.cells[0..layer.cols]) |cell| { + const g = cell.grapheme(); + if (n + g.len > line.len) break; + @memcpy(line[n..][0..g.len], g); + n += g.len; + } + if (std.mem.indexOf(u8, line[0..n], want) != null) return true; + } + } + return false; } /// A connected socket with nothing said on it yet, for the tests whose peer is diff --git a/src/detached/server.zig b/src/detached/server.zig index ac9af2ee..d7dda6ba 100644 --- a/src/detached/server.zig +++ b/src/detached/server.zig @@ -4,18 +4,20 @@ const builtin = @import("builtin"); const libc = std.c; const posix = std.posix; const pardes = @import("../pardes.zig"); +const dump = @import("../dump.zig"); const wire = @import("wire.zig"); const host_io = @import("../host_io.zig"); const selection_pipe = @import("../selection_pipe.zig"); const file_watch = @import("../file_watch.zig"); +const ShaderBuild = @import("../ShaderBuild.zig"); const ninep_io = @import("../9p_io.zig"); const look = @import("../look.zig"); -const message = pardes.Pardes.Message; +const message = pardes.Messages.Message; const TIOCSWINSZ: c_int = @bitCast(@as(u32, if (@hasDecl(posix.T, "IOCSWINSZ")) posix.T.IOCSWINSZ else 0x80087467)); @@ -62,6 +64,8 @@ const Client = struct { mirror: std.ArrayListUnmanaged(pardes.Cell) = .empty, need_full: bool = true, accepted_ms: i64 = 0, + /// The post chain last sent (Session.sendPost); null: none yet. + post_sent: ?u64 = null, }; const Pty = struct { @@ -69,61 +73,18 @@ const Pty = struct { pid: posix.pid_t = 0, kill_at: i64 = 0, out: std.ArrayListUnmanaged(u8) = .empty, + /// A command pane's child, watched to its exit (host_io.watchExit); + /// the pty stays open, unpolled after its end of file, until both its + /// end of file and its exit. + cmd: host_io.CommandWatch = .{}, }; -const RetiredShell = struct { pid: posix.pid_t = 0, kill_at: i64 = 0 }; - -const Completion = union(enum) { - lsp: struct { id: u32, rows: ?[]u8 }, - pipe: selection_pipe.Response, - - fn deinit(completion: *Completion, gpa: std.mem.Allocator) void { - switch (completion.*) { - .lsp => |result| if (result.rows) |rows| gpa.free(rows), - .pipe => |*result| result.deinit(gpa), - } - } -}; - -const Mailbox = struct { - const capacity = selection_pipe.Tasks.capacity + 1; - const Batch = struct { - items: [capacity]Completion = undefined, - len: usize = 0, - status: ?[]u8 = null, - }; - - mutex: std.atomic.Mutex = .unlocked, - batch: Batch = .{}, - wake: [2]c_int = .{ -1, -1 }, - - fn post(box: *Mailbox, completion: Completion) void { - while (!box.mutex.tryLock()) std.atomic.spinLoopHint(); - // Tasks retain their slot until the owner consumes their one completion. - std.debug.assert(box.batch.len < capacity); - box.batch.items[box.batch.len] = completion; - box.batch.len += 1; - box.mutex.unlock(); - box.signal(); - } - - fn signal(box: *Mailbox) void { - while (libc.send(box.wake[1], "w", 1, nosignal) < 0) { - if (libc.errno(-1) != .INTR) break; - } - } +/// A watched child exited, or a worker finished: wake the loop. +fn wakeForExit(ctx: ?*anyopaque) void { + Session.signal(@ptrCast(@alignCast(ctx.?))); +} - fn take(box: *Mailbox) Batch { - var bytes: [128]u8 = undefined; - while (libc.recv(box.wake[0], &bytes, bytes.len, 0) > 0) {} - while (!box.mutex.tryLock()) std.atomic.spinLoopHint(); - defer box.mutex.unlock(); - const batch = box.batch; - box.batch.len = 0; - box.batch.status = null; - return batch; - } -}; +const RetiredShell = struct { pid: posix.pid_t = 0, kill_at: i64 = 0 }; const Source = union(enum) { listener, @@ -139,6 +100,8 @@ pub const Session = struct { worker_gpa: std.mem.Allocator, io: std.Io, core: *pardes.Pardes, + /// PARDES_TEST_CLOCK's virtual time (host_io.testClock). + test_clock: ?u64 = null, listener: c_int = -1, path_buf: [sun_path_len]u8 = undefined, path_len: usize = 0, @@ -149,16 +112,21 @@ pub const Session = struct { scratch: std.ArrayListUnmanaged(u8) = .empty, ptys: [pardes.MAX_PANES]Pty = @splat(.{}), retired_shells: [pardes.MAX_PANES]RetiredShell = @splat(.{}), - mailbox: Mailbox = .{}, - lsp_task: ?host_io.Lsp.Task = null, + /// The workers' answers (initAsync sets it up); `wake` is what wakes + /// the loop's poll for them, and for a watched child's exit. + inbox: host_io.Inbox = undefined, + wake: [2]c_int = .{ -1, -1 }, pipe_tasks: selection_pipe.Tasks = .{}, prompt_rcs: host_io.Shell.PromptFiles = .{}, inotify_fd: c_int = -1, ninep: ?*ninep_io.Listener = null, ninep_pending: bool = false, - /// Set by the 9P runner's tasks: a request waits for `tick`. + /// A 9P request changed the core since the wake byte was last drained: + /// the next poll returns at once, to draw it. ninep_wake: std.atomic.Value(bool) = .init(false), watches: file_watch.Table = @splat(null), + /// The post chain's files, compiled here for the GUIs attached. + shaders: ShaderBuild = .{}, check_files: bool = false, in_loop: bool = false, greet_deadline_ms: u32 = greet_deadline_default_ms, @@ -172,42 +140,50 @@ pub const Session = struct { }; for (pair) |fd| { if (libc.fcntl(fd, libc.F.SETFD, @as(c_int, 1)) < 0) return error.SocketOptionFailed; - const flags = libc.fcntl(fd, libc.F.GETFL, @as(c_int, 0)); - if (flags < 0) return error.SocketOptionFailed; - var options: libc.O = @bitCast(@as(u32, @bitCast(flags))); - options.NONBLOCK = true; - if (libc.fcntl(fd, libc.F.SETFL, @as(c_int, @bitCast(@as(u32, @bitCast(options))))) < 0) - return error.SocketOptionFailed; + if (!setNonblock(fd)) return error.SocketOptionFailed; if (comptime darwin) { const on: c_int = 1; if (libc.setsockopt(fd, libc.SOL.SOCKET, libc.SO.NOSIGPIPE, &on, @sizeOf(c_int)) != 0) return error.SocketOptionFailed; } } - s.mailbox.wake = pair; - pardes.lsp.setStatusSink(s, lspStatus); + s.wake = pair; + s.inbox = .{ .gpa = s.worker_gpa, .lsp_allocator = s.worker_gpa, .io = s.io, .wake_fn = wakeForExit, .wake_ctx = s }; + pardes.lsp.setStatusSink(&s.inbox, host_io.Inbox.lspStatus); + host_io.setExitWake(s, wakeForExit); + } + + fn signal(s: *Session) void { + while (libc.send(s.wake[1], "w", 1, nosignal) < 0) { + if (libc.errno(-1) != .INTR) break; + } } fn cancelWorkers(s: *Session) void { - if (s.lsp_task) |*task| { - task.future.cancel(s.io) catch {}; - s.lsp_task = null; + if (s.wake[0] < 0) return; // no initAsync: no workers + if (s.inbox.lsp_task) |*task| { + task.future.cancel(s.io); + s.inbox.lsp_task = null; } s.pipe_tasks.cancelAll(s.io); + // Its worker may be waiting on the inbox for room. + s.core.stream.cancelTask(); _ = s.drainCompletions(false); } fn drainCompletions(s: *Session, apply_results: bool) bool { - var batch = s.mailbox.take(); - for (batch.items[0..batch.len]) |*completion| { - defer completion.deinit(s.worker_gpa); + var bytes: [128]u8 = undefined; + while (libc.recv(s.wake[0], &bytes, bytes.len, 0) > 0) {} + var batch = s.inbox.take(); + for (batch.slice()) |msg| { + defer msg.deinit(s.worker_gpa, s.worker_gpa); if (!apply_results) continue; - switch (completion.*) { + switch (msg) { .lsp => |result| { s.core.update(.{ .lsp_resp = .{ .id = result.id, .rows = result.rows } }); - if (s.lsp_task) |*task| if (task.id == result.id) { - task.future.await(s.io) catch {}; - s.lsp_task = null; + if (s.inbox.lsp_task) |*task| if (task.id == result.id) { + task.future.await(s.io); + s.inbox.lsp_task = null; }; }, .pipe => |result| { @@ -219,28 +195,31 @@ pub const Session = struct { } }); s.pipe_tasks.finish(s.io, result.id); }, + .lsp_status => |status| { + var buf: [256]u8 = undefined; + s.core.setStatus(s.core.active, message.stamp(&buf, "lsp", status)); + }, + .search => |b| s.core.update(.{ .search = b }), + // Ptys are read in the loop's own poll, not through the inbox. + // No hand_over host entry here (a session with no window): none comes. + .output, .eof, .files_changed, .fs_ready, .handed => {}, } } - if (batch.status) |status| { - defer s.worker_gpa.free(status); - if (apply_results) { - var buf: [256]u8 = undefined; - s.core.setStatus(s.core.active, message.stamp(&buf, "lsp", status)); - } - } - return batch.len != 0 or batch.status != null; + return batch.len != 0; } - pub fn restore(s: *Session, bytes: []const u8) !void { - const replacement = try s.core.restore(bytes); + pub fn restore(s: *Session, bytes: []const u8, from: []const u8) !void { + const replacement = try dump.restore(s.core, bytes, from); s.cancelWorkers(); for (0..s.ptys.len) |pane| s.closePty(@intCast(pane)); s.harvest(); for (0..pardes.MAX_PANES) |pane| file_watch.watchPane(s.inotify_fd, &s.watches, @intCast(pane), null, 0, .{ .text = 0 }); _ = file_watch.applyThemeEffect(s.core, s.gpa, s.inotify_fd, &s.watches, 0, false, false); + // The new core's chain generations are its own. + s.shaders.generation = null; s.check_files = false; - if (s.ninep) |listener| listener.reset(s.core); + if (s.ninep) |listener| listener.reset(replacement); s.ninep_pending = false; replacement.host = s.host(); s.core.deinit(); @@ -248,16 +227,20 @@ pub const Session = struct { for (&s.clients) |*client| if (client.attached) { client.need_full = true; }; - s.mailbox.signal(); + s.signal(); } pub fn deinit(s: *Session) void { - if (s.mailbox.wake[0] >= 0) pardes.lsp.setStatusSink(null, null); + // First: its compile thread wakes the loop, whose socket closes below. + s.shaders.deinit(s.gpa, s.inotify_fd, &s.watches); + if (s.wake[0] >= 0) pardes.lsp.setStatusSink(null, null); + if (s.wake[0] >= 0) host_io.setExitWake(null, null); s.cancelWorkers(); - for (s.mailbox.wake) |fd| if (fd >= 0) { + if (s.wake[0] >= 0) s.inbox.close(); + for (s.wake) |fd| if (fd >= 0) { _ = libc.close(fd); }; - s.mailbox.wake = .{ -1, -1 }; + s.wake = .{ -1, -1 }; if (s.ninep) |l| { l.deinit(s.gpa); s.ninep = null; @@ -317,7 +300,7 @@ pub const Session = struct { _ = libc.close(fd); return false; } - setNonblock(fd); + _ = setNonblock(fd); s.listener = fd; s.path_len = path.len; return true; @@ -341,15 +324,25 @@ pub const Session = struct { return @ptrCast(@alignCast(ctx.?)); } + fn clockNow(ctx: ?*anyopaque) u64 { + const s = of(ctx); + return s.test_clock orelse @intCast(std.Io.Clock.awake.now(s.io).nanoseconds); + } + const vtable: host_io.Host.VTable = .{ .wait_input = waitInput, + .now = clockNow, .present = present, .poll_frame = pollFrame, + .watched = watched, .spawn = spawn, .pty_write = ptyWrite, .pty_resize = ptyResize, .pty_signal = ptySignal, + .close_pty = closePaneShell, .tty_taken = ttyTaken, + .fg_name = fgName, + .kill_job = killJob, .write_file = writeFile, .write_dump = writeDump, .watch_file = watchFile, @@ -361,70 +354,25 @@ pub const Session = struct { .detach = detach, .lsp = lspRequest, .pipe = pipeRequest, + .search = searchRequest, }; - fn lspRequest(ctx: ?*anyopaque, request: host_io.Lsp.Request) void { + fn searchRequest(ctx: ?*anyopaque, gen: u32) void { const s = of(ctx); - _ = s.drainCompletions(true); - if (s.lsp_task) |*task| { - task.future.cancel(s.io) catch {}; - s.lsp_task = null; - _ = s.drainCompletions(true); - } - const job = host_io.Lsp.snapshot(s.worker_gpa, s.core, request) catch |err| { - s.core.update(.{ .lsp_resp = .{ .id = request.id, .rows = null } }); - return s.core.reportError(request.pane, "lsp", err); - }; - const future = s.io.concurrent(lspWorker, .{ s.worker_gpa, job, &s.mailbox }) catch |err| { - job.free(s.worker_gpa); - s.core.update(.{ .lsp_resp = .{ .id = request.id, .rows = null } }); - return s.core.reportError(request.pane, "lsp", err); - }; - s.lsp_task = .{ .id = request.id, .future = future }; - } - - fn lspWorker(gpa: std.mem.Allocator, job: *host_io.Lsp.Job, box: *Mailbox) anyerror!void { - host_io.Lsp.work(gpa, job, box, deliverLspRows); + if (s.wake[0] < 0) return pardes.Stream.runHere(s.core, gen); + pardes.Stream.start(s.io, s.worker_gpa, s.core, gen, &s.inbox, host_io.Inbox.pushSearch); } - fn deliverLspRows(ctx: ?*anyopaque, id: u32, rows: ?[]u8) void { - const box: *Mailbox = @ptrCast(@alignCast(ctx.?)); - box.post(.{ .lsp = .{ .id = id, .rows = rows } }); - } - - fn lspStatus(ctx: ?*anyopaque, text: []const u8) void { + fn lspRequest(ctx: ?*anyopaque, request: host_io.Lsp.Request) void { const s = of(ctx); - const copy = s.worker_gpa.dupe(u8, text) catch return; - while (!s.mailbox.mutex.tryLock()) std.atomic.spinLoopHint(); - if (s.mailbox.batch.status) |old| s.worker_gpa.free(old); - s.mailbox.batch.status = copy; - s.mailbox.mutex.unlock(); - s.mailbox.signal(); + _ = s.drainCompletions(true); + s.inbox.startLsp(s.core, request); } fn pipeRequest(ctx: ?*anyopaque, id: u32) void { const s = of(ctx); _ = s.drainCompletions(true); - if (s.pipe_tasks.full()) { - s.core.update(.{ .pipe_resp = .{ .id = id, .success = false, .outputs = &.{} } }); - return; - } - const request = s.core.pipeRequest(id) orelse return; - const job = selection_pipe.Job.copy(s.worker_gpa, request) catch |err| { - s.core.update(.{ .pipe_resp = .{ .id = id, .success = false, .outputs = &.{} } }); - return s.core.reportError(s.core.active, "pipe", err); - }; - const future = s.io.concurrent(pipeWorker, .{ s.io, s.worker_gpa, job, &s.mailbox }) catch |err| { - job.deinit(s.worker_gpa); - s.core.update(.{ .pipe_resp = .{ .id = id, .success = false, .outputs = &.{} } }); - return s.core.reportError(s.core.active, "pipe", err); - }; - std.debug.assert(s.pipe_tasks.add(.{ .id = id, .future = future })); - } - - fn pipeWorker(io: std.Io, gpa: std.mem.Allocator, job: *selection_pipe.Job, box: *Mailbox) anyerror!void { - defer job.deinit(gpa); - box.post(.{ .pipe = selection_pipe.runJob(gpa, io, job) }); + selection_pipe.start(s.io, s.worker_gpa, s.core, &s.pipe_tasks, id, &s.inbox, host_io.Inbox.pushPipe); } fn primary(s: *Session) ?*Client { @@ -451,9 +399,11 @@ pub const Session = struct { fn spawn(ctx: ?*anyopaque, pane: u8, cwd: []const u8) void { const s = of(ctx); if (pane >= s.ptys.len) return; // the core indexes its own panes - s.closePty(pane); s.harvest(); - if (s.ptys[pane].pid != 0) return s.core.reportError(pane, "shell", error.ShellClosing); + // The new shell starts before a running one goes: one that cannot + // start leaves the running one be (pty/ctl's exec). + const running = s.ptys[pane].fd >= 0; + if (!running and s.ptys[pane].pid != 0) return s.core.reportError(pane, "shell", error.ShellClosing); for (s.retired_shells) |shell| { if (shell.pid == 0) break; } else return s.core.reportError(pane, "shell", error.ShellClosing); @@ -466,11 +416,25 @@ pub const Session = struct { s.core.screen_h, s.core.screen_w, s.ninep, - ) catch |err| return s.core.reportError(pane, "shell", err); - s.ptys[pane] = .{ .fd = child.file.handle, .pid = child.pid }; - setNonblock(child.file.handle); + ) catch |err| { + if (running) return s.core.restartFailed(pane, err); + return s.core.shellFailed(pane, err); + }; + s.closePty(pane); + s.harvest(); + if (s.ptys[pane].pid != 0) { + _ = libc.close(child.file.handle); + host_io.retireShell(child.pid); + return s.core.reportError(pane, "shell", error.ShellClosing); + } + const command = if (s.core.panes[pane]) |pn| pn.command != null else false; + s.ptys[pane] = .{ .fd = child.file.handle, .pid = child.pid, .cmd = .{ .watched = command and host_io.watchExit(child.pid), .fd = child.file.handle } }; + _ = setNonblock(child.file.handle); var lbuf: [pardes.memory.limits.host_path_cap + 1]u8 = undefined; - if (host_io.shellCwd(child.pid, &lbuf)) |wd| s.core.setCwd(pane, wd); + // Only a shell given no directory is asked where it is: one given a + // directory is named by it already (newShell), and asked now, before + // its chdir, it would answer this process's, a rename to undo. + if (cwd.len == 0) if (host_io.shellCwd(child.pid, &lbuf)) |wd| s.core.setCwd(pane, wd); } fn ptyWrite(ctx: ?*anyopaque, pane: u8, bytes: []const u8) void { @@ -478,7 +442,8 @@ pub const Session = struct { if (pane >= s.ptys.len) return; const pt = &s.ptys[pane]; if (pt.fd < 0) return; - if (pt.out.items.len > pty_backlog) { + // The bound holds with this write in: queued and new together. + if (pt.out.items.len + bytes.len > pty_backlog) { var mbuf: [256]u8 = undefined; const text = std.fmt.bufPrint( &mbuf, @@ -498,7 +463,9 @@ pub const Session = struct { if (pane >= s.ptys.len) return; const fd = s.ptys[pane].fd; if (fd < 0) return; - const ws: posix.winsize = .{ .row = rows, .col = cols, .xpixel = 0, .ypixel = 0 }; + // In pixels too, at the last frontend's cell size (8x16 before + // one attached): a program sizes its kitty graphics by them. + const ws = host_io.ptyWinsize(s.core, cols, rows); _ = posix.system.ioctl(fd, TIOCSWINSZ, @intFromPtr(&ws)); } @@ -506,8 +473,9 @@ pub const Session = struct { const s = of(ctx); if (pane >= s.ptys.len) return; const pt = s.ptys[pane]; - if (pt.fd < 0) return; - host_io.signalTty(pt.pid, pt.fd, sig); + // A command whose exit is recorded is reaped: its group may be another's. + if (pt.fd < 0 or pt.cmd.exited) return; + host_io.signalTty(pt.pid, pt.fd, sig, pt.cmd.watched); } fn ttyTaken(ctx: ?*anyopaque, pane: u8) bool { @@ -518,26 +486,29 @@ pub const Session = struct { return host_io.ttyTaken(pt.pid, pt.fd); } + fn fgName(ctx: ?*anyopaque, pane: u8, buf: []u8) ?[]const u8 { + const s = of(ctx); + if (pane >= s.ptys.len) return null; + const pt = s.ptys[pane]; + if (pt.fd < 0) return null; + return host_io.foregroundName(pt.pid, pt.fd, buf); + } + + fn killJob(ctx: ?*anyopaque, pane: u8) bool { + const s = of(ctx); + if (pane >= s.ptys.len) return false; + const pt = s.ptys[pane]; + if (pt.fd < 0) return false; + return host_io.killJob(pt.pid, pt.fd); + } + fn writeFile(ctx: ?*anyopaque, pane: u8, path: []const u8, bytes: []const u8) void { const s = of(ctx); - filesystem.write(s.core, path, bytes) catch |err| - return s.core.saveFailed(pane, "save", err); - if (s.core.panes[pane]) |pn| if (pn.file) |f| if (std.mem.eql(u8, f.path, path)) { - if (s.watches[pane]) |*w| if (w.serial == pn.serial) switch (w.generation) { - .text => w.generation = .{ .text = std.hash.Wyhash.hash(0, bytes) }, - .pdf => {}, - }; - }; - var mbuf: [256]u8 = undefined; - s.core.setMessage(pane, message.stamp(&mbuf, "saved", path)); + host_io.writeFile(s.core, &s.watches, pane, path, bytes); } fn writeDump(ctx: ?*anyopaque, bytes: []const u8) void { - const s = of(ctx); - var pbuf: [1024:0]u8 = undefined; - const path = pardes.dump.outPath(&pbuf) orelse return; - filesystem.write(s.core, path, bytes) catch |err| return s.core.reportError(0, "dump", err); - s.core.setLastDump(path); + host_io.writeDump(of(ctx).core, bytes); } fn watchFile(ctx: ?*anyopaque, pane: u8, _: []const u8, on: bool, mode: pardes.WatchMode) void { @@ -554,14 +525,7 @@ pub const Session = struct { fn dumpThemes(ctx: ?*anyopaque, pane: u8) void { const s = of(ctx); - const config_dir = s.core.opts.config_dir orelse return; - const out_dir = pardes.config.User.dumpThemes(s.io, s.gpa, config_dir, pardes.themes) catch |err| { - s.core.reportError(pane, "dump themes", err); - return; - }; - defer s.gpa.free(out_dir); - var mbuf: [256]u8 = undefined; - s.core.setMessage(pane, message.stamp(&mbuf, "dumped themes", out_dir)); + host_io.dumpThemes(s.core, s.io, s.gpa, pane); } fn setClipboard(ctx: ?*anyopaque, text: []const u8) void { @@ -579,7 +543,11 @@ pub const Session = struct { fn openLink(ctx: ?*anyopaque, url: []const u8) void { const s = of(ctx); if (s.origins()) |c| return s.send(c, .{ .open_link = url }); + // No frontend: the session's own desktop is nobody's to open a + // browser on. Kept, and said, so a script sees the look land. s.core.fallback.setLink(url); + var said: [320]u8 = undefined; + s.core.setMessage(s.core.active, std.fmt.bufPrint(&said, "look: {s}: no frontend attached to open it in a browser", .{url}) catch "look: no frontend attached to open a link"); } fn detach(ctx: ?*anyopaque) void { @@ -587,23 +555,34 @@ pub const Session = struct { if (s.origins()) |c| s.send(c, .detach); } - /// The 9P runner has a request for `tick`: wake the poll loop. + /// A 9P request changed the core: wake the poll loop to draw it. fn wakeNinep(ctx: ?*anyopaque) void { const s = of(ctx); s.ninep_wake.store(true, .release); - s.mailbox.signal(); + s.signal(); + } + + fn watched(ctx: ?*anyopaque) bool { + const s = of(ctx); + for (&s.clients) |*c| if (c.attached) return true; + return false; } fn pollFrame(ctx: ?*anyopaque) void { const s = of(ctx); - if (s.ninep) |l| s.ninep_pending = l.tick(s.core).pending; + if (s.ninep) |l| s.ninep_pending = l.tick().pending; for (&s.ptys, 0..) |*pt, pane| { if (pt.fd < 0) continue; var lbuf: [pardes.memory.limits.host_path_cap + 1]u8 = undefined; - if (host_io.shellCwd(pt.pid, &lbuf)) |cwd| s.core.setCwd(pane, cwd); + if (host_io.ttyCwd(pt.pid, pt.fd, s.core.settings.shell.effective.get(), &lbuf)) |cwd| s.core.setCwd(pane, cwd); } } + fn closePaneShell(ctx: ?*anyopaque, pane: u8) void { + const s = of(ctx); + if (pane < s.ptys.len) s.closePty(pane); + } + fn closePty(s: *Session, pane: u8) void { const pt = &s.ptys[pane]; if (pt.fd < 0) return; @@ -613,7 +592,7 @@ pub const Session = struct { pt.out = .empty; if (pt.pid == 0) return; _ = libc.kill(pt.pid, libc.SIG.HUP); - pt.kill_at = monotonicMs() + 100; + pt.kill_at = std.Io.Clock.awake.now(s.io).toMilliseconds() + 100; s.harvest(); if (pt.pid == 0) return; for (&s.retired_shells) |*shell| if (shell.pid == 0) { @@ -662,27 +641,35 @@ pub const Session = struct { } fn paneEof(s: *Session, pane: u8) void { + const pt = &s.ptys[pane]; + // A command's pty stays open until its child has exited: closing + // it would hang up one that runs on without it. + // Its exit, if it came first, is told now its output is in. + if (pt.cmd.watched) return host_io.commandEof(s.core, &s.ptys, pane, s, closeWatched); + // Unwatched, a command's exit is read here, as its end, and a + // shell's, for a run waiting on it and the log. + const unwatched = if (s.core.panes[pane]) |pn| pn.command != null else false; + const status = host_io.exitStatus(pt.pid, 100); + if (status != null) pt.pid = 0; // reaped: no shell to retire s.closePty(pane); s.harvest(); + if (unwatched or status != null) s.core.update(.{ .exited = .{ .pane = pane, .status = status } }); s.core.update(.{ .eof = .{ .pane = pane } }); } - fn harvest(s: *Session) void { - const now = monotonicMs(); - for (&s.retired_shells) |*shell| reapShell(&shell.pid, &shell.kill_at, now); - for (&s.ptys) |*pty| if (pty.fd < 0) reapShell(&pty.pid, &pty.kill_at, now); + /// The command panes' exits, told once their output is in (host_io). + fn takeExits(s: *Session) void { + host_io.takeExits(s.core, &s.ptys, s, closeWatched); } - fn reapShell(pid: *posix.pid_t, kill_at: *i64, now: i64) void { - if (pid.* == 0) return; - const result = libc.waitpid(pid.*, null, libc.W.NOHANG); - if (result > 0 or (result < 0 and libc.errno(result) == .CHILD)) { - pid.* = 0; - kill_at.* = 0; - } else if (kill_at.* != 0 and now >= kill_at.*) { - _ = libc.kill(pid.*, libc.SIG.KILL); - kill_at.* = 0; - } + fn closeWatched(s: *Session, id: usize) void { + s.closePty(@intCast(id)); + } + + fn harvest(s: *Session) void { + const now = std.Io.Clock.awake.now(s.io).toMilliseconds(); + for (&s.retired_shells) |*shell| host_io.reapRetired(&shell.pid, &shell.kill_at, now); + for (&s.ptys) |*pty| if (pty.fd < 0) host_io.reapRetired(&pty.pid, &pty.kill_at, now); } fn inotify(s: *Session) c_int { @@ -698,6 +685,7 @@ pub const Session = struct { fn reloadWatched(s: *Session) void { if (!s.check_files) return; s.check_files = false; + s.shaders.recheck(); for (0..reload_retries) |_| { if (!file_watch.reloadChanged(s.core, s.io, s.gpa, &s.watches)) return; } @@ -714,7 +702,7 @@ pub const Session = struct { fn sendFrame(s: *Session, c: *Client, surface: *const pardes.Surface) void { const cells = surface.cells; - const want = wire.frameBound(surface.cols, surface.rows) + wire.layersBound(&surface.body_layers, &surface.tag_layers); + const want = wire.frameBound(surface.cols, surface.rows) + wire.layersBound(&surface.body_layers, &surface.tag_layers, surface.regionList()); s.scratch.ensureTotalCapacity(s.gpa, want) catch return s.close(c, .oom); const prev: []const pardes.Cell = if (c.need_full or c.mirror.items.len != cells.len) &.{} @@ -734,6 +722,8 @@ pub const Session = struct { prev, &surface.body_layers, &surface.tag_layers, + surface.regionList(), + surface.chrome, ) catch |err| { log.debug("frame {d}x{d} not encodable: {t}", .{ surface.cols, surface.rows, err }); return; @@ -753,13 +743,19 @@ pub const Session = struct { const completed = s.ninep_wake.swap(false, .acq_rel) or drained; for (&s.clients) |*c| if (c.fd >= 0) s.flush(c); const regridded = s.reconcile(); + // After the greeting reconcile sends: a chain before it is refused. + const compiled = s.sendPost(); + // Nobody attached, nobody to dismiss a message: the loop expires + // them itself, between the editor's steps (expireUnattended). + s.core.unattended = s.primary() == null; + pardes.Messages.expireUnattended(s.core); - const now = monotonicMs(); + const now = std.Io.Clock.awake.now(s.io).toMilliseconds(); var fds: [poll_slots]libc.pollfd = undefined; var src: [poll_slots]Source = undefined; var n: usize = 0; - if (s.mailbox.wake[0] >= 0) { - fds[n] = .{ .fd = s.mailbox.wake[0], .events = poll_in, .revents = 0 }; + if (s.wake[0] >= 0) { + fds[n] = .{ .fd = s.wake[0], .events = poll_in, .revents = 0 }; src[n] = .completion; n += 1; } @@ -780,7 +776,7 @@ pub const Session = struct { n += 1; } for (&s.ptys, 0..) |*pt, pane| { - if (pt.fd < 0) continue; + if (pt.fd < 0 or pt.cmd.eof) continue; fds[n] = .{ .fd = pt.fd, .events = if (pt.out.items.len != 0) poll_in | poll_out else poll_in, @@ -796,7 +792,7 @@ pub const Session = struct { } if (s.ninep) |l| { // Unix and TCP connections run on cloud9's runner, which wakes - // this loop through the mailbox; only QUIC is polled here. + // this loop through `wake`; only QUIC is polled here. if (comptime ninep_io.quic_enabled) { if (l.quic) |*listener| { fds[n] = listener.poll(); @@ -805,14 +801,30 @@ pub const Session = struct { } } } - if (n == 0) return nap(if (timeout_ms == 0) 16 else timeout_ms); + // The wait is the 9P connections' turn with the core. + if (n == 0) { + pardes.turn.rest(); + s.io.sleep(.fromMilliseconds(if (timeout_ms == 0) 16 else timeout_ms), .awake) catch {}; + pardes.turn.wake(); + if (timeout_ms != 0) if (s.test_clock) |*virtual| { + virtual.* = @max(virtual.*, s.core.nextWake() orelse virtual.*); + }; + return; + } var timeout: c_int = if (timeout_ms == 0) -1 else @intCast(@min(timeout_ms, std.math.maxInt(c_int))); if (s.nextWake(now)) |due| timeout = if (timeout < 0) due else @min(timeout, due); - if (completed or s.check_files or regridded or s.ninep_pending) timeout = 0; + if (completed or compiled or s.check_files or regridded or s.ninep_pending) timeout = 0; + pardes.turn.rest(); const ready = libc.poll(&fds, @intCast(n), timeout); + pardes.turn.wake(); if (ready > 0) s.dispatch(fds[0..n], src[0..n]); + // The core's wake ran out; the pump advances it from `now`. + if (timeout_ms != 0 and std.Io.Clock.awake.now(s.io).toMilliseconds() -| now >= timeout_ms) if (s.test_clock) |*virtual| { + virtual.* = @max(virtual.*, s.core.nextWake() orelse virtual.*); + }; _ = s.drainCompletions(true); - s.expire(monotonicMs()); + s.takeExits(); + s.expire(std.Io.Clock.awake.now(s.io).toMilliseconds()); s.harvest(); s.reloadWatched(); _ = s.reconcile(); @@ -849,7 +861,6 @@ pub const Session = struct { } fn nextWake(s: *const Session, now: i64) ?c_int { - if (now == 0) return null; // no clock; see `monotonicMs` var due: ?i64 = null; for (s.retired_shells) |shell| if (shell.pid != 0) { due = now + 10; @@ -872,6 +883,11 @@ pub const Session = struct { due = if (due) |d| @min(d, at9) else at9; } } + // Unattended messages go on the clock: look again in a while. + if (s.core.unattended) for (s.core.panes) |slot| if (slot) |pane| if (pane.msg_len > 0) { + due = if (due) |d| @min(d, now + 100) else now + 100; + break; + }; const at = due orelse return null; return @intCast(@max(0, @min(at - now, std.math.maxInt(c_int)))); } @@ -891,13 +907,13 @@ pub const Session = struct { switch (libc.errno(fd)) { .AGAIN, .INTR, .CONNABORTED => return, else => { - s.accept_paused_ms = monotonicMs() + accept_pause_ms; + s.accept_paused_ms = std.Io.Clock.awake.now(s.io).toMilliseconds() + accept_pause_ms; return; }, } } ninep_io.setCloexec(fd); - setNonblock(fd); + _ = setNonblock(fd); if (comptime darwin) { const on: c_int = 1; _ = libc.setsockopt(fd, libc.SOL.SOCKET, libc.SO.NOSIGPIPE, &on, @sizeOf(c_int)); @@ -909,7 +925,7 @@ pub const Session = struct { _ = libc.close(fd); continue; }; - s.clients[slot] = .{ .fd = fd, .accepted_ms = monotonicMs() }; + s.clients[slot] = .{ .fd = fd, .accepted_ms = std.Io.Clock.awake.now(s.io).toMilliseconds() }; } } @@ -946,7 +962,7 @@ pub const Session = struct { } fn apply(s: *Session, c: *Client, slot: u8, tag: u8, payload: []const u8) wire.Error!void { - if (tag == @intFromEnum(wire.ClientTag.hello)) { + if (tag == @backingInt(wire.ClientTag.hello)) { if (c.attached) return error.BadValue; const claimed = try wire.helloVersion(payload); if (claimed != wire.version) { @@ -962,6 +978,9 @@ pub const Session = struct { c.attached = true; c.need_full = true; c.greet = true; + // Unwatched until now, it may have drawn nothing: a frame + // for the one attaching (watched). + s.core.needs_frame = true; }, .bye => s.close(c, .bye), .event => |ev| { @@ -990,7 +1009,9 @@ pub const Session = struct { rows = if (rows == 0) c.rows else @min(rows, c.rows); } var regridded = false; - if (cols != 0 and (cols != s.cols or rows != s.rows)) { + // Against the core's size too: a root ctl `size` may have set it + // while nobody was attached. + if (cols != 0 and (cols != s.cols or rows != s.rows or cols != s.core.screen_w or rows != s.core.screen_h)) { s.cols = cols; s.rows = rows; for (&s.clients) |*c| c.need_full = true; @@ -1005,6 +1026,28 @@ pub const Session = struct { return regridded; } + /// Compiles the post chain's files (a finished compile wakes the loop + /// through `wake`) and sends each attached frontend the chain it + /// has not seen: on attach, and when it or a file's SPIR-V changes. True + /// when a compile was taken in, so the loop draws what it said. + /// ponytail: a terminal frontend is sent it too and drops it; a hello + /// saying which frontend it is would spare those bytes. + fn sendPost(s: *Session) bool { + const files = for (s.core.settings.post.list()) |entry| { + if (entry.scene == null) break true; + } else false; + const compiled = s.shaders.sync(s.gpa, s.io, s.core, if (files) s.inotify() else s.inotify_fd, &s.watches, .{ .ctx = s, .call = wakeForExit }); + const key = @as(u64, s.shaders.revision) << 8 | @backingInt(s.core.settings.shader_animation); + var chain: wire.Post = .{ .animation = s.core.settings.shader_animation, .len = s.core.settings.post.len }; + _ = s.shaders.view(&s.core.settings.post, &chain.passes); + for (&s.clients) |*c| { + if (!c.attached or c.greet or c.post_sent == key) continue; + c.post_sent = key; + s.send(c, .{ .post = chain }); + } + return compiled; + } + fn send(s: *Session, c: *Client, msg: wire.ServerMsg) void { const want = wire.serverBound(msg); s.scratch.ensureTotalCapacity(s.gpa, want) catch return s.close(c, .oom); @@ -1015,6 +1058,9 @@ pub const Session = struct { s.queue(c, bytes); } + /// A client's queued output is at most `out_backlog + wire.max_payload`: + /// past the backlog it is closed, and one frame lands on top of it first + /// (a frame bigger than the backlog must still go out whole). fn queue(s: *Session, c: *Client, bytes: []const u8) void { if (c.out.items.len > out_backlog) return s.close(c, .backlog); s.account(); @@ -1068,6 +1114,7 @@ pub const Session = struct { fn refuseFd(_: *Session, fd: c_int, why: wire.Refusal) void { var buf: [wire.header_len + 1]u8 = undefined; + // unreachable: a refusal is a header and one byte, which buf is sized to const bytes = wire.encodeServer(&buf, .{ .refuse = why }) catch unreachable; var off: usize = 0; while (off < bytes.len) { @@ -1093,11 +1140,43 @@ pub const Session = struct { } }; +/// SIGTERM, SIGINT or SIGHUP: quit as Exit does, through the loop, so its +/// sockets are unlinked on the way out rather than left for the next +/// session to trip on. The handler only sets the flag and wakes the loop. +var quit_signalled = std.atomic.Value(bool).init(false); +var quit_wake: c_int = -1; + +fn onQuitSignal(_: std.posix.SIG) callconv(.c) void { + quit_signalled.store(true, .release); + if (quit_wake >= 0) _ = libc.send(quit_wake, "q", 1, nosignal); +} + +/// The screen of a detached session no frontend has sized. +pub const detached_cols = 160; +pub const detached_rows = 50; + pub fn run(init: std.process.Init, opts: pardes.Options, name: []const u8) !void { + // A name a live session holds: said, exit 1, before anything is made + // (no error trace, no second session racing the first for the socket). + if (comptime supported) { + var path_buf: [path_max]u8 = undefined; + if (sessionPath(&path_buf, name)) |path| if (ninep_io.statNoFollow(path) != null and alive(path)) { + var said: [path_max + 64]u8 = undefined; + const text = std.fmt.bufPrint(&said, "pardes: a session named {s} is already running\n", .{name}) catch "pardes: a session of that name is already running\n"; + std.Io.File.stderr().writeStreamingAll(init.io, text) catch {}; + std.process.exit(1); + }; + } const gpa = init.gpa; const allocs = pardes.memory.init(gpa); defer pardes.memory.deinit(); var options = opts; + // No frontend yet, so no size to take: one roomy enough for a script's + // panes (80x24 left pane/new refused after a few); `size` sets another, + // and an attaching frontend its own. + options.cols = detached_cols; + options.rows = detached_rows; + options.detached_session = true; options.image_allocator = allocs.image; options.pdf_allocator = allocs.pdf; options.tree_sitter_allocator = allocs.tree_sitter; @@ -1115,7 +1194,7 @@ pub fn run(init: std.process.Init, opts: pardes.Options, name: []const u8) !void const core = if (options.load_path) |lp| blk: { const bytes = try filesystem.readFile(gpa, lp); defer gpa.free(bytes); - break :blk try pardes.Pardes.initFromDump(allocs.pardes, options, bytes); + break :blk try pardes.dump.initFromDump(allocs.pardes, options, bytes); } else try pardes.Pardes.init(allocs.pardes, options); var session: Session = .{ .gpa = gpa, @@ -1125,40 +1204,62 @@ pub fn run(init: std.process.Init, opts: pardes.Options, name: []const u8) !void .cols = options.cols, .rows = options.rows, .prompt_rcs = host_io.Shell.prepare(), + .test_clock = host_io.testClock(), }; defer session.core.deinit(); defer session.deinit(); try session.initAsync(); if (!session.listen(name)) { try std.Io.File.stderr().writeStreamingAll(init.io, "pardes: could not bind a detached session socket\n"); - return error.NoSocket; + std.process.exit(1); } - session.ninep = ninep_io.listen(init.io, gpa, opts.ninep_name, name, opts.ninep_tcp, opts.ninep_quic); + session.ninep = ninep_io.listen(init.io, gpa, core, opts.ninep_name, name, opts.ninep_tcp, opts.ninep_quic); if (session.ninep == null) return error.ListenFailed; - session.ninep.?.setWake(&session, Session.wakeNinep); - core.fs.socket_path = session.ninep.?.path(); - core.fs.tcp_address = session.ninep.?.tcp_address; - core.fs.quic_address = session.ninep.?.quic_address; + session.ninep.?.wake_ctx = &session; + session.ninep.?.wake = Session.wakeNinep; const h = session.host(); core.host = h; while (core.nextEffect()) |effect| core.perform(effect); session.in_loop = true; - while (!session.core.quit) { + quit_wake = session.wake[1]; + const on_quit: std.posix.Sigaction = .{ .handler = .{ .handler = onQuitSignal }, .mask = std.posix.sigemptyset(), .flags = 0 }; + for ([_]std.posix.SIG{ .HUP, .INT, .TERM }) |sig| std.posix.sigaction(sig, &on_quit, null); + defer quit_wake = -1; + while (!session.core.quit and !quit_signalled.load(.acquire)) { + pardes.turn.bump(&pardes.turn.restores); try session.core.pump(h); if (session.core.quit) break; if (session.core.takeRestore()) |path| restore: { - const bytes = filesystem.readRestore(gpa, path) catch |err| { + const bytes = filesystem.readRestore(gpa, path, session.core.settings.dump_dir.get()) catch |err| { session.core.reportError(session.core.active, "Restore", err); break :restore; }; defer gpa.free(bytes); - session.restore(bytes) catch |err| session.core.reportError(session.core.active, "Restore", err); + session.restore(bytes, path) catch |err| session.core.reportError(session.core.active, "Restore", err); } } } +test "a link looked at with no frontend attached opens no browser, and says so" { + const gpa = std.testing.allocator; + var s: Session = .{ + .gpa = gpa, + .worker_gpa = gpa, + .io = std.testing.io, + .core = try pardes.Pardes.init(gpa, .{ .tty_only = true, .cols = 40, .rows = 12 }), + .cols = 40, + .rows = 12, + }; + defer s.core.deinit(); + defer s.deinit(); + Session.openLink(&s, "https://example.com/x"); + try std.testing.expectEqualStrings("https://example.com/x", s.core.fallback.link.items); + const pane = s.core.panes[s.core.active].?; + try std.testing.expectEqualStrings("look: https://example.com/x: no frontend attached to open it in a browser", pane.msg[0..pane.msg_len]); +} + test "detached queued results preserve current requests and are discarded before Restore" { const gpa = std.testing.allocator; var s: Session = .{ @@ -1178,24 +1279,27 @@ test "detached queued results preserve current requests and are discarded before const old_id = s.core.lsp_wait.?.id; s.core.lspRequest(0, .status, ""); const current_id = s.core.lsp_wait.?.id; - s.lsp_task = .{ .id = current_id, .future = .{ .any_future = null, .result = {} } }; - s.mailbox.post(.{ .lsp = .{ .id = old_id, .rows = try gpa.dupe(u8, "old result\n") } }); - try std.testing.expect(s.drainCompletions(true)); - try std.testing.expectEqual(current_id, s.lsp_task.?.id); + s.inbox.lsp_id = current_id; + s.inbox.lsp_task = .{ .id = current_id, .future = .{ .any_future = null, .result = {} } }; + // The inbox turns the superseded answer away. + s.inbox.push(.{ .lsp = .{ .id = old_id, .rows = try gpa.dupe(u8, "old result\n") } }); + try std.testing.expectEqual(@as(usize, 0), s.inbox.completion_len); + _ = s.drainCompletions(true); + try std.testing.expectEqual(current_id, s.inbox.lsp_task.?.id); try std.testing.expectEqual(current_id, s.core.lsp_wait.?.id); - try s.core.dumpState(); + try dump.dumpState(s.core); const saved = try gpa.dupe(u8, s.core.dump_out.?); defer gpa.free(saved); while (s.core.nextEffect()) |_| {} - s.mailbox.post(.{ .lsp = .{ .id = current_id, .rows = try gpa.dupe(u8, "queued before restore\n") } }); + s.inbox.push(.{ .lsp = .{ .id = current_id, .rows = try gpa.dupe(u8, "queued before restore\n") } }); const outputs = try gpa.alloc([]u8, 1); outputs[0] = try gpa.dupe(u8, "old filter output\n"); try std.testing.expect(s.pipe_tasks.add(.{ .id = 77, .future = .{ .any_future = null, .result = {} } })); - s.mailbox.post(.{ .pipe = .{ .id = 77, .success = true, .outputs = outputs } }); - Session.lspStatus(&s, "old status"); - try s.restore(saved); - try std.testing.expect(s.lsp_task == null); + s.inbox.push(.{ .pipe = .{ .id = 77, .success = true, .outputs = outputs } }); + host_io.Inbox.lspStatus(&s.inbox, "old status"); + try s.restore(saved, "test"); + try std.testing.expect(s.inbox.lsp_task == null); try std.testing.expectEqual(@as(usize, 0), s.pipe_tasks.len); try std.testing.expect(!s.drainCompletions(true)); try std.testing.expectEqualStrings("saved body\n", s.core.panes[0].?.file.?.content); @@ -1203,18 +1307,57 @@ test "detached queued results preserve current requests and are discarded before s.core.lspRequest(0, .status, ""); const restored_id = s.core.lsp_wait.?.id; try std.testing.expect(restored_id > current_id); - s.lsp_task = .{ .id = restored_id, .future = .{ .any_future = null, .result = {} } }; - s.mailbox.post(.{ .lsp = .{ .id = current_id, .rows = try gpa.dupe(u8, "late old result\n") } }); + s.inbox.lsp_id = restored_id; + s.inbox.lsp_task = .{ .id = restored_id, .future = .{ .any_future = null, .result = {} } }; + s.inbox.push(.{ .lsp = .{ .id = current_id, .rows = try gpa.dupe(u8, "late old result\n") } }); _ = s.drainCompletions(true); - try std.testing.expectEqual(restored_id, s.lsp_task.?.id); + try std.testing.expectEqual(restored_id, s.inbox.lsp_task.?.id); try std.testing.expectEqual(restored_id, s.core.lsp_wait.?.id); - s.mailbox.post(.{ .lsp = .{ .id = restored_id, .rows = &.{} } }); + s.inbox.push(.{ .lsp = .{ .id = restored_id, .rows = &.{} } }); const host = s.host(); host.vtable.wait_input.?(host.ctx, 1); - try std.testing.expect(s.lsp_task == null); + try std.testing.expect(s.inbox.lsp_task == null); try std.testing.expect(s.core.lsp_wait == null); } +test "a detached session's terminal pane takes its shell with it when it closes" { + const gpa = std.testing.allocator; + var s: Session = .{ + .gpa = gpa, + .worker_gpa = gpa, + .io = std.testing.io, + .core = try pardes.Pardes.init(gpa, .{ .tty_only = true, .cols = 40, .rows = 12 }), + .cols = 40, + .rows = 12, + }; + defer s.core.deinit(); + defer s.deinit(); + // A stand-in shell: it waits for a signal, and a hangup ends it. + const pid = libc.fork(); + if (pid == 0) while (true) { + _ = libc.poll(&[0]libc.pollfd{}, 0, -1); + }; + try std.testing.expect(pid > 0); + var fds: [2]c_int = undefined; + try std.testing.expectEqual(@as(c_int, 0), libc.pipe(&fds)); + defer _ = libc.close(fds[1]); + s.ptys[3] = .{ .fd = fds[0], .pid = pid }; + const host = s.host(); + host.vtable.close_pty.?(host.ctx, 3); + try std.testing.expect(s.ptys[3].fd < 0); + const deadline = std.Io.Clock.awake.now(std.testing.io).toMilliseconds() + 2000; + while (std.Io.Clock.awake.now(std.testing.io).toMilliseconds() < deadline) { + s.harvest(); + const running = s.ptys[3].pid != 0 or for (s.retired_shells) |shell| { + if (shell.pid == pid) break true; + } else false; + if (!running) break; + _ = libc.poll(&[0]libc.pollfd{}, 0, 5); + } + try std.testing.expect(s.ptys[3].pid == 0); + for (s.retired_shells) |shell| try std.testing.expect(shell.pid != pid); +} + test "detached worker setup failure completes requests without changing document bytes" { const gpa = std.testing.allocator; var failing = std.testing.FailingAllocator.init(gpa, .{ .fail_index = 0 }); @@ -1235,16 +1378,16 @@ test "detached worker setup failure completes requests without changing document s.core.lspRequest(0, .status, ""); while (s.core.nextEffect()) |effect| s.core.perform(effect); try std.testing.expect(s.core.lsp_wait == null); - try std.testing.expect(s.lsp_task == null); + try std.testing.expect(s.inbox.lsp_task == null); - pane.cur_col = 2; - pane.vsel = .{ .active = true, .row = 0, .col = 0, .explicit = true }; + pane.body.cur_col = 2; + pane.body.vsel = .{ .active = true, .row = 0, .col = 0, .explicit = true }; s.core.update(.{ .key = .{ .cp = '|' } }); s.core.update(.{ .key = .{ .cp = 't', .text = "tr a-z A-Z" } }); s.core.update(.{ .key = .{ .cp = pardes.Key.enter } }); - try std.testing.expect(s.core.pipe_wait != null); + try std.testing.expect(s.core.pipe.wait != null); while (s.core.nextEffect()) |effect| s.core.perform(effect); - try std.testing.expect(s.core.pipe_wait == null); + try std.testing.expect(s.core.pipe.wait == null); try std.testing.expectEqual(@as(usize, 0), s.pipe_tasks.len); try std.testing.expectEqualStrings("one\n", pane.file.?.content); try std.testing.expect(failing.has_induced_failure); @@ -1252,12 +1395,12 @@ test "detached worker setup failure completes requests without changing document pub const setCloexec = ninep_io.setCloexec; -pub fn setNonblock(fd: c_int) void { +pub fn setNonblock(fd: c_int) bool { const flags = libc.fcntl(fd, libc.F.GETFL, @as(c_int, 0)); - if (flags < 0) return; + if (flags < 0) return false; var o: libc.O = @bitCast(@as(u32, @bitCast(flags))); o.NONBLOCK = true; - _ = libc.fcntl(fd, libc.F.SETFL, @as(c_int, @bitCast(@as(u32, @bitCast(o))))); + return libc.fcntl(fd, libc.F.SETFL, @as(c_int, @bitCast(@as(u32, @bitCast(o))))) >= 0; } pub const nosignal: u32 = if (darwin) 0 else libc.MSG.NOSIGNAL; @@ -1273,20 +1416,6 @@ fn retire(gpa: std.mem.Allocator, list: *std.ArrayListUnmanaged(u8)) void { list.clearAndFree(gpa); } -pub fn monotonicMs() i64 { - var ts: libc.timespec = undefined; - if (libc.clock_gettime(.MONOTONIC, &ts) != 0) return 0; - return @as(i64, ts.sec) * std.time.ms_per_s + @divTrunc(ts.nsec, std.time.ns_per_ms); -} - -fn nap(ms: u32) void { - var ts: libc.timespec = .{ - .sec = @intCast(ms / 1000), - .nsec = @intCast((ms % 1000) * std.time.ns_per_ms), - }; - _ = libc.nanosleep(&ts, null); -} - pub fn socketPath(buf: *[sun_path_len]u8, dir: []const u8, name: []const u8) ?[:0]const u8 { if (name.len == 0) return null; if (std.mem.indexOfAny(u8, name, "/\x00") != null) return null; @@ -1330,7 +1459,7 @@ fn alive(path: [:0]const u8) bool { if (fd < 0) return true; defer _ = libc.close(fd); ninep_io.setCloexec(fd); - setNonblock(fd); + _ = setNonblock(fd); const rc = libc.connect(fd, @ptrCast(&addr), @sizeOf(@TypeOf(addr))); if (rc == 0) return true; return libc.errno(rc) != .CONNREFUSED; diff --git a/src/detached/wire.zig b/src/detached/wire.zig index 245bc9f4..0e141686 100644 --- a/src/detached/wire.zig +++ b/src/detached/wire.zig @@ -3,10 +3,35 @@ const std = @import("std"); const pardes = @import("../pardes.zig"); const limits = @import("../memory.zig").limits; +const ShaderBuild = @import("../ShaderBuild.zig"); +const Scene = pardes.config.Runtime.Scene; +const ShaderAnimation = pardes.config.Runtime.ShaderAnimation; -pub const version: u16 = 6; +/// 7: tag layers gained the `.notice` kind, so a frame can carry a tag value +/// an older frontend would reject mid-session. The greeting is where that has +/// to be refused, which is what this number is for. +/// 8: one layer type: a tag band carries all its rows (not a layer per +/// line), and a frame carries the core's placed regions after its layers. +pub const version: u16 = 12; -pub const Error = error{ Truncated, Overlong, BadTag, BadValue, Trailing, NoSpace }; +/// The Chrome palette is carried field by field as its declaration lists +/// them, so any change to it changes the wire: bump `version`, then this. +const chrome_layout: u64 = 0xbe608bed776ff502; +comptime { + @setEvalBranchQuota(10_000); + var hash = std.hash.Fnv1a_64.init(); + const info = @typeInfo(pardes.Chrome).@"struct"; + for (info.field_names, info.field_types) |name, T| { + hash.update(name); + hash.update(@typeName(T)); + } + if (hash.final() != chrome_layout) @compileError(std.fmt.comptimePrint("pardes.Chrome changed (layout 0x{x}): bump wire.version, then chrome_layout", .{hash.final()})); +} + +/// EndOfStream: the message ends early; WriteFailed: no room for it. +/// ReadFailed is in only because std.Io.Reader says so: a fixed one never +/// fails a read. +pub const Error = error{ EndOfStream, ReadFailed, Overlong, BadTag, BadValue, Trailing, WriteFailed }; pub const max_cols: u16 = 512; pub const max_rows: u16 = 128; @@ -37,6 +62,7 @@ pub const ClientTag = enum(u8) { pinch = 0x1b, touch_scroll = 0x1c, pointer_leave = 0x1d, + focus = 0x1e, }; // Session control precedes display-local effects. @@ -55,6 +81,9 @@ pub const ServerTag = enum(u8) { set_clipboard = 0x10, read_clipboard = 0x11, open_link = 0x12, + /// The post chain this frontend draws its frames through: sent on + /// attach and whenever it or a file's SPIR-V changes. + post = 0x13, }; /// Why the server hung up on a connect. Sent as a `refuse` and followed by a @@ -133,8 +162,8 @@ pub const Hello = struct { /// An error rather than a zero on a payload shorter than two bytes, so a /// truncated hello stays diagnosable too instead of reading as version 0. pub fn helloVersion(payload: []const u8) Error!u16 { - var r: Reader = .init(payload); - return r.getU16(); + var r: std.Io.Reader = .fixed(payload); + return r.takeInt(u16, .little); } pub const Welcome = struct { @@ -164,7 +193,9 @@ pub const Frame = struct { nruns: u32, runs: []const u8, - pub fn applyLayers(f: Frame, gpa: std.mem.Allocator, layers: *[pardes.MAX_PANES]pardes.BodyLayer, tags: *[pardes.MAX_TAG_LAYERS]pardes.TagLayer) !void { + pub fn applyLayers(f: Frame, gpa: std.mem.Allocator, layers: *[pardes.MAX_PANES]pardes.Layer, tags: *[pardes.MAX_TAG_LAYERS]pardes.Layer, regions: *std.ArrayListUnmanaged(pardes.Region), chrome: *pardes.Chrome) !void { + regions.clearRetainingCapacity(); + chrome.* = .{}; for (layers) |*layer| { gpa.free(layer.cells); layer.* = .{}; @@ -182,52 +213,105 @@ pub const Frame = struct { gpa.free(layer.cells); layer.* = .{}; } + regions.clearRetainingCapacity(); + chrome.* = .{}; } if (f.layers.len == 0) return; - var r: Reader = .init(f.layers); - const count = try r.getU16(); + var r: std.Io.Reader = .fixed(f.layers); + const count = try r.takeInt(u16, .little); if (count > layers.len) return error.Overlong; for (layers[0..count]) |*layer| { - layer.pane = try r.getU16(); - layer.serial = try r.getU32(); - layer.viewport = .{ .x = try r.getU16(), .y = try r.getU16(), .w = try r.getU16(), .h = try r.getU16() }; - layer.cols = try r.getU16(); - layer.rows = try r.getU16(); - layer.context_rows = try r.getU16(); - if (layer.pane >= pardes.MAX_PANES or layer.cols == 0 or layer.cols > f.cols or + layer.kind = .body; + layer.id = try r.takeInt(u16, .little); + layer.serial = try r.takeInt(u32, .little); + layer.viewport = .{ .x = try r.takeInt(u16, .little), .y = try r.takeInt(u16, .little), .w = try r.takeInt(u16, .little), .h = try r.takeInt(u16, .little) }; + layer.cols = try r.takeInt(u16, .little); + layer.rows = try r.takeInt(u16, .little); + layer.context_rows = try r.takeInt(u16, .little); + if (layer.id >= pardes.MAX_PANES or layer.cols == 0 or layer.cols > f.cols or layer.rows == 0 or layer.rows > 2 * max_rows or layer.context_rows > layer.rows or layer.context_rows > limits.wrap_rows or layer.viewport.x > f.cols or layer.viewport.w > f.cols - layer.viewport.x or layer.viewport.y > f.rows or layer.viewport.h > f.rows - layer.viewport.y) return error.BadValue; for (0..layer.context_rows) |row| { - if (try r.getBool()) layer.context_separators.set(row); + if (try getBool(&r)) layer.context_separators.set(row); } const cursor = try getCursor(&r, layer.cols, layer.rows); layer.cursor = if (cursor) |c| .{ .x = c.x, .y = c.y, .bar = c.bar } else null; layer.cells = try gpa.alloc(pardes.Cell, @as(usize, layer.cols) * layer.rows); for (layer.cells) |*cell| cell.* = try decodeCell(&r); } - const tag_count = try r.getU16(); + const tag_count = try r.takeInt(u16, .little); if (tag_count > tags.len) return error.Overlong; for (tags[0..tag_count]) |*layer| { - layer.kind = try r.getTag(pardes.TagKind); - layer.id = try r.getU16(); - layer.serial = try r.getU32(); - layer.viewport = .{ .x = try r.getU16(), .y = try r.getU16(), .w = try r.getU16(), .h = try r.getU16() }; - layer.cols = try r.getU16(); - for (&layer.bg) |*channel| channel.* = try r.getByte(); - if (layer.cols == 0 or layer.viewport.w == 0 or layer.viewport.h != 1 or + layer.kind = try getTag(&r, pardes.TagKind); + layer.id = try r.takeInt(u16, .little); + layer.serial = try r.takeInt(u32, .little); + layer.viewport = .{ .x = try r.takeInt(u16, .little), .y = try r.takeInt(u16, .little), .w = try r.takeInt(u16, .little), .h = try r.takeInt(u16, .little) }; + layer.cols = try r.takeInt(u16, .little); + layer.rows = try r.takeInt(u16, .little); + for (&layer.bg) |*channel| channel.* = try r.takeByte(); + if (layer.cols == 0 or layer.viewport.w == 0 or layer.rows == 0 or layer.rows > pardes.MAX_TAG_ROWS or + layer.viewport.h != layer.rows or layer.viewport.x > f.cols or layer.viewport.w > f.cols - layer.viewport.x or - layer.viewport.y >= f.rows or (switch (layer.kind) { + layer.viewport.y >= f.rows or layer.viewport.h > f.rows - layer.viewport.y or (switch (layer.kind) { .workspace => layer.id != 0, .column => layer.id >= pardes.MAX_COLS, - .pane => layer.id >= pardes.MAX_PANES, + .pane, .notice => layer.id >= pardes.MAX_PANES, + .body => true, })) return error.BadValue; - const cursor = try getCursor(&r, layer.cols, 1); - layer.cursor = if (cursor) |c| .{ .col = c.x, .bar = c.bar } else null; - layer.cells = try gpa.alloc(pardes.Cell, layer.cols); + const cursor = try getCursor(&r, layer.cols, layer.rows); + layer.cursor = if (cursor) |c| .{ .x = c.x, .y = c.y, .bar = c.bar } else null; + layer.cells = try gpa.alloc(pardes.Cell, @as(usize, layer.cols) * layer.rows); for (layer.cells) |*cell| cell.* = try decodeCell(&r); } - try r.end(); + const region_count = try r.takeInt(u16, .little); + if (region_count > pardes.MAX_REGIONS) return error.Overlong; + try regions.ensureTotalCapacity(gpa, region_count); + for (0..region_count) |_| { + var region: pardes.Region = .{ .kind = try getTag(&r, pardes.Region.Kind), .rect = undefined }; + region.owner = try r.takeByte(); + region.serial = try r.takeInt(u32, .little); + region.rect = .{ .x = try r.takeInt(u16, .little), .y = try r.takeInt(u16, .little), .w = try r.takeInt(u16, .little), .h = try r.takeInt(u16, .little) }; + const flags = try r.takeByte(); + if (flags > 3) return error.BadValue; + region.active = flags & 1 != 0; + region.dirty = flags & 2 != 0; + region.thumb_y = try r.takeInt(u16, .little); + region.thumb_h = try r.takeInt(u16, .little); + region.notice = try r.takeByte(); + region.clip = try r.takeInt(u16, .little); + region.lift = @bitCast(try r.takeInt(u32, .little)); + region.line = @bitCast(try r.takeInt(u32, .little)); + // A springy flavour overshoots, and a wind-up dips below. + if (!(region.lift >= -1 and region.lift <= 2)) return error.BadValue; + if (region.rect.x > f.cols or region.rect.w > f.cols - region.rect.x or + region.rect.y > f.rows or region.rect.h > f.rows - region.rect.y or + region.clip > region.rect.w or region.thumb_y > region.rect.h or region.thumb_h > region.rect.h - region.thumb_y) return error.BadValue; + regions.appendAssumeCapacity(region); + } + const info = @typeInfo(pardes.Chrome).@"struct"; + inline for (info.field_names, info.field_types) |name, T| { + const rgb = &@field(chrome, name); + if (T == ?[3]u8) { + if (try getBool(&r)) { + rgb.* = .{ 0, 0, 0 }; + for (&rgb.*.?) |*channel| channel.* = try r.takeByte(); + } + } else if (T == u8) { + rgb.* = try r.takeByte(); + } else if (T == u32) { + rgb.* = try r.takeInt(u32, .little); + } else if (T == f32) { + rgb.* = @bitCast(try r.takeInt(u32, .little)); + if (!std.math.isFinite(rgb.*)) return error.BadValue; + } else if (T == [8]f32) { + for (rgb) |*value| { + value.* = @bitCast(try r.takeInt(u32, .little)); + if (!std.math.isFinite(value.*)) return error.BadValue; + } + } else for (rgb) |*channel| channel.* = try r.takeByte(); + } + try end(&r); } /// Paint this frame into `grid`, which must be exactly `cols * rows` cells @@ -239,12 +323,12 @@ pub const Frame = struct { pub fn apply(f: Frame, grid: []pardes.Cell) Error!void { if (grid.len != @as(usize, f.cols) * @as(usize, f.rows)) return error.BadValue; if (f.kind == .full) @memset(grid, .{}); - var r: Reader = .init(f.runs); + var r: std.Io.Reader = .fixed(f.runs); var i: u32 = 0; while (i < f.nruns) : (i += 1) { - const start = try r.getU32(); - const count = try r.getU16(); - // A zero-length run is not something `encodeFrame` emits, and + const start = try r.takeInt(u32, .little); + const count = try r.takeInt(u16, .little); + // A zero-length run is not something `encodeFrameLayers` emits, and // accepting one would let a peer spend the run budget saying // nothing. if (count == 0) return error.BadValue; @@ -254,7 +338,7 @@ pub const Frame = struct { if (start > grid.len or count > grid.len - start) return error.Overlong; for (grid[start..][0..count]) |*c| c.* = try decodeCell(&r); } - try r.end(); + try end(&r); } }; @@ -281,175 +365,115 @@ pub const ServerMsg = union(enum) { set_clipboard: []const u8, read_clipboard, open_link: []const u8, + post: Post, }; -// --------------------------------------------------------------------------- -// primitives -// --------------------------------------------------------------------------- - -pub const Writer = struct { - buf: []u8, - n: usize = 0, - - pub fn init(buf: []u8) Writer { - return .{ .buf = buf }; - } - - pub fn written(w: *const Writer) []const u8 { - return w.buf[0..w.n]; - } - - fn room(w: *Writer, k: usize) Error![]u8 { - if (w.buf.len - w.n < k) return error.NoSpace; - defer w.n += k; - return w.buf[w.n..][0..k]; - } - - fn putByte(w: *Writer, v: u8) Error!void { - (try w.room(1))[0] = v; - } - - fn putU16(w: *Writer, v: u16) Error!void { - std.mem.writeInt(u16, (try w.room(2))[0..2], v, .little); - } - - fn putU32(w: *Writer, v: u32) Error!void { - std.mem.writeInt(u32, (try w.room(4))[0..4], v, .little); - } - - /// One byte, 0 or 1, never "nonzero". `getBool` refuses anything else. - fn putBool(w: *Writer, v: bool) Error!void { - try w.putByte(@intFromBool(v)); - } - - /// IEEE-754 binary32, as its bit pattern in an explicit u32. A scalar - /// bitcast and not a struct blit: the format is the one thing a riscv32 - /// and an x86_64 do agree about. - fn putF32(w: *Writer, v: f32) Error!void { - try w.putU32(@bitCast(v)); - } - - fn putBytes(w: *Writer, v: []const u8) Error!void { - @memcpy(try w.room(v.len), v); - } - - /// Length-prefixed, u16: paths, command lines, a key's text. Nothing here - /// is legitimately longer than 64 KiB and a u16 says so on the wire. - fn putSlice16(w: *Writer, v: []const u8) Error!void { - if (v.len > std.math.maxInt(u16)) return error.Overlong; - try w.putU16(@intCast(v.len)); - try w.putBytes(v); - } +/// The session's post chain, as a GUI attached to it draws it: its passes in +/// order, each a bundled scene at its level or a Shadertoy file's SPIR-V +/// (compiled by the session, ShaderBuild.zig: a frontend reads no disk and +/// runs no program), and when it animates on its own. Slices borrow the +/// payload. +pub const Post = struct { + animation: ShaderAnimation = .on, + passes: [ShaderBuild.max]ShaderBuild.Pass = @splat(.{}), + len: u8 = 0, - /// ...and u32 for the ones that are: pty output, a paste, a file. - fn putSlice32(w: *Writer, v: []const u8) Error!void { - if (v.len > max_payload) return error.Overlong; - try w.putU32(@intCast(v.len)); - try w.putBytes(v); + pub fn list(p: *const Post) []const ShaderBuild.Pass { + return p.passes[0..p.len]; } }; -pub const Reader = struct { - bytes: []const u8, - i: usize = 0, - - pub fn init(bytes: []const u8) Reader { - return .{ .bytes = bytes }; - } - - /// `i <= bytes.len` is the invariant every getter below preserves, which is - /// what makes the subtraction here safe. - fn take(r: *Reader, n: usize) Error![]const u8 { - if (r.bytes.len - r.i < n) return error.Truncated; - defer r.i += n; - return r.bytes[r.i..][0..n]; - } - - fn getByte(r: *Reader) Error!u8 { - return (try r.take(1))[0]; - } - - fn getU16(r: *Reader) Error!u16 { - return std.mem.readInt(u16, (try r.take(2))[0..2], .little); - } +// --------------------------------------------------------------------------- +// primitives +// --------------------------------------------------------------------------- - fn getU32(r: *Reader) Error!u32 { - return std.mem.readInt(u32, (try r.take(4))[0..4], .little); - } +/// Length-prefixed, u16: paths, command lines, a key's text. Nothing here +/// is legitimately longer than 64 KiB and a u16 says so on the wire. +fn putSlice16(w: *std.Io.Writer, v: []const u8) Error!void { + if (v.len > std.math.maxInt(u16)) return error.Overlong; + try w.writeInt(u16, @intCast(v.len), .little); + try w.writeAll(v); +} - fn getBool(r: *Reader) Error!bool { - return switch (try r.getByte()) { - 0 => false, - 1 => true, - else => error.BadValue, - }; - } +/// ...and u32 for the ones that are: pty output, a paste, a file. +fn putSlice32(w: *std.Io.Writer, v: []const u8) Error!void { + if (v.len > max_payload) return error.Overlong; + try w.writeInt(u32, @intCast(v.len), .little); + try w.writeAll(v); +} - fn getF32(r: *Reader) Error!f32 { - const v: f32 = @bitCast(try r.getU32()); - // A NaN or an infinity here is not a scroll distance. `pinch` in - // particular multiplies into a zoom factor the pane keeps, so one bad - // value poisons that pane for the rest of the session. - if (!std.math.isFinite(v)) return error.BadValue; - return v; - } +/// One byte, 0 or 1, never "nonzero": the writer's `@intFromBool`. +fn getBool(r: *std.Io.Reader) Error!bool { + return switch (try r.takeByte()) { + 0 => false, + 1 => true, + else => error.BadValue, + }; +} - fn getSlice16(r: *Reader) Error![]const u8 { - return r.take(try r.getU16()); - } +/// IEEE-754 binary32, as its bit pattern in an explicit u32. A scalar +/// bitcast and not a struct blit: the format is the one thing a riscv32 +/// and an x86_64 do agree about. +fn getF32(r: *std.Io.Reader) Error!f32 { + const v: f32 = @bitCast(try r.takeInt(u32, .little)); + // A NaN or an infinity here is not a scroll distance. `pinch` in + // particular multiplies into a zoom factor the pane keeps, so one bad + // value poisons that pane for the rest of the session. + if (!std.math.isFinite(v)) return error.BadValue; + return v; +} - fn getSlice32(r: *Reader) Error![]const u8 { - const n = try r.getU32(); - if (n > max_payload) return error.Overlong; - return r.take(n); - } +fn getSlice32(r: *std.Io.Reader) Error![]const u8 { + const n = try r.takeInt(u32, .little); + if (n > max_payload) return error.Overlong; + return r.take(n); +} - /// A pane id the core can actually index. `Event.output{ .pane = 200 }` - /// would reach `p.panes[200]`. - fn getPane(r: *Reader) Error!u8 { - const pane = try r.getByte(); - if (pane >= pardes.MAX_PANES) return error.BadValue; - return pane; - } +/// A pane id the core can actually index. `Event.output{ .pane = 200 }` +/// would reach `p.panes[200]`. +fn getPane(r: *std.Io.Reader) Error!u8 { + const pane = try r.takeByte(); + if (pane >= pardes.MAX_PANES) return error.BadValue; + return pane; +} - /// A grid the core can render into. Zero is refused rather than clamped: a - /// frontend that has not been sized yet must not be allowed to collapse a - /// shared session to nothing (see server.zig `geometry`). - fn getCols(r: *Reader) Error!u16 { - const v = try r.getU16(); - if (v == 0 or v > max_cols) return error.BadValue; - return v; - } +/// A grid the core can render into. Zero is refused rather than clamped: a +/// frontend that has not been sized yet must not be allowed to collapse a +/// shared session to nothing (see server.zig `geometry`). +fn getCols(r: *std.Io.Reader) Error!u16 { + const v = try r.takeInt(u16, .little); + if (v == 0 or v > max_cols) return error.BadValue; + return v; +} - fn getRows(r: *Reader) Error!u16 { - const v = try r.getU16(); - if (v == 0 or v > max_rows) return error.BadValue; - return v; - } +fn getRows(r: *std.Io.Reader) Error!u16 { + const v = try r.takeInt(u16, .little); + if (v == 0 or v > max_rows) return error.BadValue; + return v; +} - fn getTag(r: *Reader, comptime T: type) Error!T { - return std.enums.fromInt(T, try r.getByte()) orelse error.BadTag; - } +fn getTag(r: *std.Io.Reader, comptime T: type) Error!T { + return std.enums.fromInt(T, try r.takeByte()) orelse error.BadTag; +} - fn end(r: *Reader) Error!void { - if (r.i != r.bytes.len) return error.Trailing; - } -}; +fn end(r: *std.Io.Reader) Error!void { + if (r.seek != r.end) return error.Trailing; +} /// Reserve a message header; `finishMessage` back-patches the length. Two /// passes would mean walking a frame's runs twice to find out how long they /// are, and the walk is the expensive half. -fn beginMessage(w: *Writer, tag: u8) Error!usize { - const at = w.n; - try w.putByte(tag); - try w.putU32(0); +fn beginMessage(w: *std.Io.Writer, tag: u8) Error!usize { + const at = w.end; + try w.writeByte(tag); + try w.writeInt(u32, 0, .little); return at; } -fn finishMessage(w: *Writer, at: usize) Error!void { - const len = w.n - at - header_len; +fn finishMessage(w: *std.Io.Writer, at: usize) Error!void { + const len = w.end - at - header_len; if (len > max_payload) return error.Overlong; - std.mem.writeInt(u32, w.buf[at + 1 ..][0..4], @intCast(len), .little); + std.mem.writeInt(u32, w.buffer[at + 1 ..][0..4], @intCast(len), .little); } /// One complete message at the front of a stream buffer, or null when the rest @@ -470,24 +494,24 @@ pub fn framed(buf: []const u8) Error!?Framed { // cells // --------------------------------------------------------------------------- -fn putColor(w: *Writer, c: pardes.Color) Error!void { +fn putColor(w: *std.Io.Writer, c: pardes.Color) Error!void { switch (c) { - .default => try w.putByte(@intFromEnum(ColorTag.default)), + .default => try w.writeByte(@backingInt(ColorTag.default)), .index => |i| { - try w.putByte(@intFromEnum(ColorTag.index)); - try w.putByte(i); + try w.writeByte(@backingInt(ColorTag.index)); + try w.writeByte(i); }, .rgb => |v| { - try w.putByte(@intFromEnum(ColorTag.rgb)); - try w.putBytes(&v); + try w.writeByte(@backingInt(ColorTag.rgb)); + try w.writeAll(&v); }, } } -fn getColor(r: *Reader) Error!pardes.Color { - return switch (try r.getTag(ColorTag)) { +fn getColor(r: *std.Io.Reader) Error!pardes.Color { + return switch (try getTag(r, ColorTag)) { .default => .default, - .index => .{ .index = try r.getByte() }, + .index => .{ .index = try r.takeByte() }, .rgb => .{ .rgb = (try r.take(3))[0..3].* }, }; } @@ -506,32 +530,32 @@ const Ul = @FieldType(pardes.CellStyle, "ul"); /// which is the whole property the six hand-written switches this replaced /// existed for, in a form that cannot fall out of step. A variant that has to /// travel under a DIFFERENT name than the core's gets an arm of its own before -/// the `inline else`, exactly as `clientTag` keeps `.fs_req`. -fn putUl(w: *Writer, u: Ul) Error!void { - try w.putByte(switch (u) { - inline else => |t| @intFromEnum(@field(UlTag, @tagName(t))), +/// the `inline else`, exactly as `clientTag` keeps the machine-local reports. +fn putUl(w: *std.Io.Writer, u: Ul) Error!void { + try w.writeByte(switch (u) { + inline else => |t| @backingInt(@field(UlTag, @tagName(t))), }); } -fn getUl(r: *Reader) Error!Ul { - return switch (try r.getTag(UlTag)) { +fn getUl(r: *std.Io.Reader) Error!Ul { + return switch (try getTag(r, UlTag)) { inline else => |t| @field(Ul, @tagName(t)), }; } -fn putFont(w: *Writer, f: pardes.FontRole) Error!void { - try w.putByte(switch (f) { - inline else => |t| @intFromEnum(@field(FontTag, @tagName(t))), +fn putFont(w: *std.Io.Writer, f: pardes.FontRole) Error!void { + try w.writeByte(switch (f) { + inline else => |t| @backingInt(@field(FontTag, @tagName(t))), }); } -fn getFont(r: *Reader) Error!pardes.FontRole { - return switch (try r.getTag(FontTag)) { +fn getFont(r: *std.Io.Reader) Error!pardes.FontRole { + return switch (try getTag(r, FontTag)) { inline else => |t| @field(pardes.FontRole, @tagName(t)), }; } -/// How many bytes `putCell` will write. Exact, because `encodeFrame` weighs it +/// How many bytes `putCell` will write. Exact, because `encodeFrameLayers` weighs it /// against `run_header` to decide whether to coalesce a run across it. fn cellSize(c: *const pardes.Cell) usize { if (c.default) return 1; @@ -547,13 +571,13 @@ fn colorSize(c: pardes.Color) usize { } /// An unpainted cell is ONE byte: `default` means "the shell renders the -/// terminal's default cell" (pardes.zig `Cell`), so its text and style are not +/// terminal's default cell" (surface.zig `Cell`), so its text and style are not /// merely equal to the defaults, they are not part of the frame at all. -fn putCell(w: *Writer, c: *const pardes.Cell) Error!void { - try w.putBool(c.default); +fn putCell(w: *std.Io.Writer, c: *const pardes.Cell) Error!void { + try w.writeByte(@intFromBool(c.default)); if (c.default) return; - try w.putByte(c.len); - try w.putBytes(c.grapheme()); + try w.writeByte(c.len); + try w.writeAll(c.grapheme()); const s = c.style; try putColor(w, s.fg); try putColor(w, s.bg); @@ -565,15 +589,15 @@ fn putCell(w: *Writer, c: *const pardes.Cell) Error!void { if (s.reverse) attrs |= attr_reverse; if (s.invisible) attrs |= attr_invisible; if (s.strikethrough) attrs |= attr_strikethrough; - try w.putByte(attrs); + try w.writeByte(attrs); try putUl(w, s.ul); try putFont(w, s.font_role); } -fn decodeCell(r: *Reader) Error!pardes.Cell { - if (try r.getBool()) return .{}; +fn decodeCell(r: *std.Io.Reader) Error!pardes.Cell { + if (try getBool(r)) return .{}; var c: pardes.Cell = .{ .default = false }; - const len = try r.getByte(); + const len = try r.takeByte(); // `Cell.text` is 7 bytes and `grapheme()` slices to `len`. A zero-length // grapheme is a cell with nothing to draw and no way to advance a column. if (len == 0 or len > c.text.len) return error.BadValue; @@ -581,7 +605,7 @@ fn decodeCell(r: *Reader) Error!pardes.Cell { @memcpy(c.text[0..len], try r.take(len)); c.style.fg = try getColor(r); c.style.bg = try getColor(r); - const attrs = try r.getByte(); + const attrs = try r.takeByte(); if (attrs & attr_reserved != 0) return error.BadValue; c.style.bold = attrs & attr_bold != 0; c.style.dim = attrs & attr_dim != 0; @@ -599,24 +623,24 @@ fn decodeCell(r: *Reader) Error!pardes.Cell { // frames // --------------------------------------------------------------------------- -fn putCursor(w: *Writer, cursor: ?Cursor, cols: u16, rows: u16) Error!void { +fn putCursor(w: *std.Io.Writer, cursor: ?Cursor, cols: u16, rows: u16) Error!void { // Fixed six bytes whether or not there is a cursor. An optional field // would save five bytes on a message that is already hundreds, and cost a // branch on both sides of the wire. - try w.putBool(cursor != null); + try w.writeByte(@intFromBool(cursor != null)); const c = cursor orelse Cursor{ .x = 0, .y = 0, .bar = false }; // Refused here as well as on decode, so this side cannot build a frame its // own decoder rejects: a dropped frame (sendFrame logs it) leaves a stale // screen, and a refused one takes the frontend's connection with it. if (c.x >= cols or c.y >= rows) return error.BadValue; - try w.putU16(c.x); - try w.putU16(c.y); - try w.putBool(c.bar); + try w.writeInt(u16, c.x, .little); + try w.writeInt(u16, c.y, .little); + try w.writeByte(@intFromBool(c.bar)); } -fn getCursor(r: *Reader, cols: u16, rows: u16) Error!?Cursor { - const present = try r.getBool(); - const c: Cursor = .{ .x = try r.getU16(), .y = try r.getU16(), .bar = try r.getBool() }; +fn getCursor(r: *std.Io.Reader, cols: u16, rows: u16) Error!?Cursor { + const present = try getBool(r); + const c: Cursor = .{ .x = try r.takeInt(u16, .little), .y = try r.takeInt(u16, .little), .bar = try getBool(r) }; // THE cursor bounds check. Every other field of a frame is checked against // the grid and these two were not, and they are the two a frontend indexes // with directly — `Surface.at(cursor.x, cursor.y)` on a grid this frame @@ -628,6 +652,22 @@ fn getCursor(r: *Reader, cols: u16, rows: u16) Error!?Cursor { return if (present) c else null; } +pub fn layersBound(layers: []const pardes.Layer, tags: []const pardes.Layer, regions: []const pardes.Region) usize { + var n: usize = 6; + for (layers) |layer| if (layer.rows != 0) { + n += 26 + layer.context_rows + layer.cells.len * cell_max; + }; + for (tags) |layer| if (layer.rows != 0) { + n += 28 + layer.cells.len * cell_max; + }; + return n + regions.len * region_len + chrome_len; +} + +const region_len = 1 + 1 + 4 + 8 + 1 + 2 + 2 + 1 + 2 + 4 + 4; +/// The palette: each colour three bytes, a theme's optional ones a flag +/// before them. +const chrome_len = @typeInfo(pardes.Chrome).@"struct".field_names.len * 4 + 8 * 4; + /// Encode one frame of `cells`, as a DIFF against `prev` when `prev` is the /// same grid this receiver last acknowledged, and as a FULL frame otherwise. /// @@ -649,41 +689,7 @@ fn getCursor(r: *Reader, cols: u16, rows: u16) Error!?Cursor { /// own 56x14 grid with uncoloured cells, where it is exact: 6298 against 56. /// This transport exists for a frontend on the far end of a slow link, and /// shipping the Surface every frame would be 3 MiB/s at the animation tick. -pub fn encodeFrame( - out: []u8, - cols: u16, - rows: u16, - cursor: ?Cursor, - cells: []const pardes.Cell, - prev: []const pardes.Cell, -) Error![]const u8 { - return encodeFramePointer(out, cols, rows, cursor, .arrow, cells, prev); -} - -pub fn encodeFramePointer( - out: []u8, - cols: u16, - rows: u16, - cursor: ?Cursor, - pointer_shape: pardes.Surface.PointerShape, - cells: []const pardes.Cell, - prev: []const pardes.Cell, -) Error![]const u8 { - return encodeFrameLayers(out, cols, rows, cursor, pointer_shape, cells, prev, &.{}, &.{}); -} - -pub fn layersBound(layers: []const pardes.BodyLayer, tags: []const pardes.TagLayer) usize { - var n: usize = 4; - for (layers) |layer| if (layer.rows != 0) { - n += 26 + layer.context_rows + layer.cells.len * cell_max; - }; - for (tags) |layer| if (layer.cols != 0) { - n += 26 + layer.cells.len * cell_max; - }; - return n; -} - -pub fn encodeFrameLayers(out: []u8, cols: u16, rows: u16, cursor: ?Cursor, pointer_shape: pardes.Surface.PointerShape, cells: []const pardes.Cell, prev: []const pardes.Cell, layers: []const pardes.BodyLayer, tags: []const pardes.TagLayer) Error![]const u8 { +pub fn encodeFrameLayers(out: []u8, cols: u16, rows: u16, cursor: ?Cursor, pointer_shape: pardes.Surface.PointerShape, cells: []const pardes.Cell, prev: []const pardes.Cell, layers: []const pardes.Layer, tags: []const pardes.Layer, regions: []const pardes.Region, chrome: pardes.Chrome) Error![]const u8 { // The protocol's ceiling, enforced by the ENCODER too, and BEFORE the // assert below so a caller can be told rather than tripped. `max_payload` // is derived from these two, so a larger grid is a frame this decoder @@ -692,65 +698,99 @@ pub fn encodeFrameLayers(out: []u8, cols: u16, rows: u16, cursor: ?Cursor, point if (cols == 0 or cols > max_cols or rows == 0 or rows > max_rows) return error.Overlong; std.debug.assert(cells.len == @as(usize, cols) * @as(usize, rows)); const full = prev.len != cells.len; - var w: Writer = .init(out); - const at = try beginMessage(&w, @intFromEnum(ServerTag.frame)); + var w: std.Io.Writer = .fixed(out); + const at = try beginMessage(&w, @backingInt(ServerTag.frame)); const header: FrameHeader = if (pointer_shape == .link) (if (full) .full_link else .diff_link) else (if (full) .full else .diff); - try w.putByte(@intFromEnum(header)); - try w.putU16(cols); - try w.putU16(rows); + try w.writeByte(@backingInt(header)); + try w.writeInt(u16, cols, .little); + try w.writeInt(u16, rows, .little); try putCursor(&w, cursor, cols, rows); - const layers_len_at = w.n; - try w.putU32(0); - const layers_start = w.n; - if (layers.len != 0 or tags.len != 0) { + const layers_len_at = w.end; + try w.writeInt(u32, 0, .little); + const layers_start = w.end; + if (layers.len != 0 or tags.len != 0 or regions.len != 0) { var count: u16 = 0; for (layers) |layer| if (layer.rows != 0) { count += 1; }; - try w.putU16(count); + try w.writeInt(u16, count, .little); for (layers) |layer| { if (layer.rows == 0) continue; if (layer.context_rows > limits.wrap_rows or layer.context_rows > layer.rows) return error.BadValue; - try w.putU16(layer.pane); - try w.putU32(layer.serial); - try w.putU16(layer.viewport.x); - try w.putU16(layer.viewport.y); - try w.putU16(layer.viewport.w); - try w.putU16(layer.viewport.h); - try w.putU16(layer.cols); - try w.putU16(layer.rows); - try w.putU16(layer.context_rows); - for (0..layer.context_rows) |row| try w.putBool(layer.context_separators.isSet(row)); + try w.writeInt(u16, layer.id, .little); + try w.writeInt(u32, layer.serial, .little); + try w.writeInt(u16, layer.viewport.x, .little); + try w.writeInt(u16, layer.viewport.y, .little); + try w.writeInt(u16, layer.viewport.w, .little); + try w.writeInt(u16, layer.viewport.h, .little); + try w.writeInt(u16, layer.cols, .little); + try w.writeInt(u16, layer.rows, .little); + try w.writeInt(u16, layer.context_rows, .little); + for (0..layer.context_rows) |row| try w.writeByte(@intFromBool(layer.context_separators.isSet(row))); try putCursor(&w, if (layer.cursor) |c| .{ .x = c.x, .y = c.y, .bar = c.bar } else null, layer.cols, layer.rows); for (layer.cells) |*cell| try putCell(&w, cell); } var tag_count: u16 = 0; - for (tags) |layer| if (layer.cols != 0) { + for (tags) |layer| if (layer.rows != 0) { tag_count += 1; }; - try w.putU16(tag_count); + try w.writeInt(u16, tag_count, .little); for (tags) |layer| { - if (layer.cols == 0) continue; - if (layer.cells.len != layer.cols) return error.BadValue; - try w.putByte(@intFromEnum(layer.kind)); - try w.putU16(layer.id); - try w.putU32(layer.serial); - try w.putU16(layer.viewport.x); - try w.putU16(layer.viewport.y); - try w.putU16(layer.viewport.w); - try w.putU16(layer.viewport.h); - try w.putU16(layer.cols); - for (layer.bg) |channel| try w.putByte(channel); - try putCursor(&w, if (layer.cursor) |c| .{ .x = c.col, .y = 0, .bar = c.bar } else null, layer.cols, 1); + if (layer.rows == 0) continue; + if (layer.cells.len != @as(usize, layer.cols) * layer.rows) return error.BadValue; + try w.writeByte(@backingInt(layer.kind)); + try w.writeInt(u16, layer.id, .little); + try w.writeInt(u32, layer.serial, .little); + try w.writeInt(u16, layer.viewport.x, .little); + try w.writeInt(u16, layer.viewport.y, .little); + try w.writeInt(u16, layer.viewport.w, .little); + try w.writeInt(u16, layer.viewport.h, .little); + try w.writeInt(u16, layer.cols, .little); + try w.writeInt(u16, layer.rows, .little); + for (layer.bg) |channel| try w.writeByte(channel); + try putCursor(&w, if (layer.cursor) |c| .{ .x = c.x, .y = c.y, .bar = c.bar } else null, layer.cols, layer.rows); for (layer.cells) |*cell| try putCell(&w, cell); } + try w.writeInt(u16, @intCast(regions.len), .little); + for (regions) |region| { + try w.writeByte(@backingInt(region.kind)); + try w.writeByte(region.owner); + try w.writeInt(u32, region.serial, .little); + try w.writeInt(u16, region.rect.x, .little); + try w.writeInt(u16, region.rect.y, .little); + try w.writeInt(u16, region.rect.w, .little); + try w.writeInt(u16, region.rect.h, .little); + try w.writeByte(@as(u8, @intFromBool(region.active)) | @as(u8, @intFromBool(region.dirty)) << 1); + try w.writeInt(u16, region.thumb_y, .little); + try w.writeInt(u16, region.thumb_h, .little); + try w.writeByte(region.notice); + try w.writeInt(u16, region.clip, .little); + try w.writeInt(u32, @bitCast(region.lift), .little); + try w.writeInt(u32, @bitCast(region.line), .little); + } + const info = @typeInfo(pardes.Chrome).@"struct"; + inline for (info.field_names, info.field_types) |name, T| { + const rgb = @field(chrome, name); + if (T == ?[3]u8) { + try w.writeByte(@intFromBool(rgb != null)); + if (rgb) |value| for (value) |channel| try w.writeByte(channel); + } else if (T == u8) { + try w.writeByte(rgb); + } else if (T == u32) { + try w.writeInt(u32, rgb, .little); + } else if (T == f32) { + try w.writeInt(u32, @bitCast(rgb), .little); + } else if (T == [8]f32) { + for (rgb) |value| try w.writeInt(u32, @bitCast(value), .little); + } else for (rgb) |channel| try w.writeByte(channel); + } } - std.mem.writeInt(u32, w.buf[layers_len_at..][0..4], @intCast(w.n - layers_start), .little); - const nruns_at = w.n; - try w.putU32(0); + std.mem.writeInt(u32, w.buffer[layers_len_at..][0..4], @intCast(w.end - layers_start), .little); + const nruns_at = w.end; + try w.writeInt(u32, 0, .little); var nruns: u32 = 0; var i: usize = 0; @@ -787,15 +827,15 @@ pub fn encodeFrameLayers(out: []u8, cols: u16, rows: u16, cursor: ?Cursor, point if (j >= cells.len or gap >= run_header) break; i = j; } - try w.putU32(@intCast(start)); - try w.putU16(@intCast(run_end - start)); + try w.writeInt(u32, @intCast(start), .little); + try w.writeInt(u16, @intCast(run_end - start), .little); for (cells[start..run_end]) |*c| try putCell(&w, c); nruns += 1; i = run_end; } - std.mem.writeInt(u32, w.buf[nruns_at..][0..4], nruns, .little); + std.mem.writeInt(u32, w.buffer[nruns_at..][0..4], nruns, .little); try finishMessage(&w, at); - return w.written(); + return w.buffered(); } fn sendCell(cells: []const pardes.Cell, prev: []const pardes.Cell, full: bool, i: usize) bool { @@ -816,7 +856,7 @@ fn clientTag(msg: ClientMsg) ClientTag { return switch (msg) { .event => |ev| switch (ev) { // Machine-local reports and 9P requests belong to the session owner. - .output, .eof, .lsp_resp, .pipe_resp, .file_changed, .tick, .fs_req => unreachable, + .output, .eof, .exited, .lsp_resp, .pipe_resp, .search, .file_changed, .handed, .tick => unreachable, inline else => |_, t| @field(ClientTag, @tagName(t)), }, inline else => |_, t| @field(ClientTag, @tagName(t)), @@ -828,64 +868,64 @@ fn clientTag(msg: ClientMsg) ClientTag { /// WIRE is not. const has_cell_pixels = @hasField(pardes.CellPixels, "w"); -fn putMetrics(w: *Writer, metrics: ?pardes.RowMetrics) Error!void { - try w.putBool(metrics != null); +fn putMetrics(w: *std.Io.Writer, metrics: ?pardes.RowMetrics) Error!void { + try w.writeByte(@intFromBool(metrics != null)); if (metrics) |m| { - try w.putU16(m.body_w); - try w.putU16(m.body_h); - try w.putU16(m.tagline_w); - try w.putU16(m.tagline_h); + try w.writeInt(u16, m.body_w, .little); + try w.writeInt(u16, m.body_h, .little); + try w.writeInt(u16, m.tagline_w, .little); + try w.writeInt(u16, m.tagline_h, .little); } } -fn getMetrics(r: *Reader) Error!?pardes.RowMetrics { - if (!try r.getBool()) return null; - const m: pardes.RowMetrics = .{ .body_w = try r.getU16(), .body_h = try r.getU16(), .tagline_w = try r.getU16(), .tagline_h = try r.getU16() }; +fn getMetrics(r: *std.Io.Reader) Error!?pardes.RowMetrics { + if (!try getBool(r)) return null; + const m: pardes.RowMetrics = .{ .body_w = try r.takeInt(u16, .little), .body_h = try r.takeInt(u16, .little), .tagline_w = try r.takeInt(u16, .little), .tagline_h = try r.takeInt(u16, .little) }; if (m.body_w == 0 or m.body_h == 0 or m.tagline_w == 0 or m.tagline_h == 0) return error.BadValue; return m; } -fn putBodyHit(w: *Writer, hit: ?pardes.Mouse.BodyHit) Error!void { - try w.putBool(hit != null); +fn putBodyHit(w: *std.Io.Writer, hit: ?pardes.Mouse.BodyHit) Error!void { + try w.writeByte(@intFromBool(hit != null)); if (hit) |h| { - try w.putU32(h.serial); - try w.putU16(h.row); - try w.putU16(h.col); - try w.putF32(h.pixel_x); - try w.putF32(h.pixel_y); + try w.writeInt(u32, h.serial, .little); + try w.writeInt(u16, h.row, .little); + try w.writeInt(u16, h.col, .little); + try w.writeInt(u32, @bitCast(h.pixel_x), .little); + try w.writeInt(u32, @bitCast(h.pixel_y), .little); try putMetrics(w, h.metrics); } } -fn getBodyHit(r: *Reader) Error!?pardes.Mouse.BodyHit { - if (!try r.getBool()) return null; - const hit: pardes.Mouse.BodyHit = .{ .serial = try r.getU32(), .row = try r.getU16(), .col = try r.getU16(), .pixel_x = try r.getF32(), .pixel_y = try r.getF32(), .metrics = (try getMetrics(r)) orelse return error.BadValue }; +fn getBodyHit(r: *std.Io.Reader) Error!?pardes.Mouse.BodyHit { + if (!try getBool(r)) return null; + const hit: pardes.Mouse.BodyHit = .{ .serial = try r.takeInt(u32, .little), .row = try r.takeInt(u16, .little), .col = try r.takeInt(u16, .little), .pixel_x = try getF32(r), .pixel_y = try getF32(r), .metrics = (try getMetrics(r)) orelse return error.BadValue }; if (!std.math.isFinite(hit.pixel_x) or !std.math.isFinite(hit.pixel_y)) return error.BadValue; return hit; } -fn putTagHit(w: *Writer, hit: ?pardes.TagHit) Error!void { - try w.putBool(hit != null); +fn putTagHit(w: *std.Io.Writer, hit: ?pardes.TagHit) Error!void { + try w.writeByte(@intFromBool(hit != null)); if (hit) |h| { - try w.putByte(@intFromEnum(h.kind)); - try w.putU16(h.id); - try w.putU32(h.serial); - try w.putU16(h.col); - try w.putF32(h.pixel_x); - try w.putF32(h.pixel_y); + try w.writeByte(@backingInt(h.kind)); + try w.writeInt(u16, h.id, .little); + try w.writeInt(u32, h.serial, .little); + try w.writeInt(u16, h.col, .little); + try w.writeInt(u32, @bitCast(h.pixel_x), .little); + try w.writeInt(u32, @bitCast(h.pixel_y), .little); try putMetrics(w, h.metrics); } } -fn getTagHit(r: *Reader) Error!?pardes.TagHit { - if (!try r.getBool()) return null; +fn getTagHit(r: *std.Io.Reader) Error!?pardes.TagHit { + if (!try getBool(r)) return null; const hit: pardes.TagHit = .{ - .kind = try r.getTag(pardes.TagKind), - .id = try r.getU16(), - .serial = try r.getU32(), - .col = try r.getU16(), - .pixel_x = try r.getF32(), - .pixel_y = try r.getF32(), + .kind = try getTag(r, pardes.TagKind), + .id = try r.takeInt(u16, .little), + .serial = try r.takeInt(u32, .little), + .col = try r.takeInt(u16, .little), + .pixel_x = try getF32(r), + .pixel_y = try getF32(r), .metrics = (try getMetrics(r)) orelse return error.BadValue, }; if (!std.math.isFinite(hit.pixel_x) or !std.math.isFinite(hit.pixel_y)) return error.BadValue; @@ -893,117 +933,124 @@ fn getTagHit(r: *Reader) Error!?pardes.TagHit { } pub fn encodeClient(out: []u8, msg: ClientMsg) Error![]const u8 { - var w: Writer = .init(out); - const at = try beginMessage(&w, @intFromEnum(clientTag(msg))); + var w: std.Io.Writer = .fixed(out); + const at = try beginMessage(&w, @backingInt(clientTag(msg))); switch (msg) { .hello => |h| { - try w.putU16(h.version); - try w.putU16(h.cols); - try w.putU16(h.rows); + try w.writeInt(u16, h.version, .little); + try w.writeInt(u16, h.cols, .little); + try w.writeInt(u16, h.rows, .little); }, .bye => {}, .event => |ev| switch (ev) { .key => |k| { - try w.putU32(k.cp); - try w.putSlice16(k.text); - try w.putBool(k.ctrl); - try w.putBool(k.alt); - try w.putBool(k.shift); + try w.writeInt(u32, k.cp, .little); + try putSlice16(&w, k.text); + try w.writeByte(@intFromBool(k.ctrl)); + try w.writeByte(@intFromBool(k.alt)); + try w.writeByte(@intFromBool(k.shift)); }, .mouse => |m| { - try w.putByte(switch (m.button) { - inline else => |t| @intFromEnum(@field(ButtonTag, @tagName(t))), + try w.writeByte(switch (m.button) { + inline else => |t| @backingInt(@field(ButtonTag, @tagName(t))), }); - try w.putByte(switch (m.kind) { - inline else => |t| @intFromEnum(@field(KindTag, @tagName(t))), + try w.writeByte(switch (m.kind) { + inline else => |t| @backingInt(@field(KindTag, @tagName(t))), }); - try w.putU16(m.col); - try w.putU16(m.row); - try w.putBool(m.ctrl); + try w.writeInt(u16, m.col, .little); + try w.writeInt(u16, m.row, .little); + try w.writeByte(@intFromBool(m.ctrl)); + try w.writeByte(@intFromBool(m.shift)); + try w.writeByte(@intFromBool(m.alt)); try putBodyHit(&w, m.body_hit); try putTagHit(&w, m.tag_hit); }, .resize => |rs| { - try w.putU16(rs.cols); - try w.putU16(rs.rows); + try w.writeInt(u16, rs.cols, .little); + try w.writeInt(u16, rs.rows, .little); // The conventional 1:2 cell aspect when this build has no // pixels of its own, which is the same default the field // carries where it exists. - try w.putU16(if (comptime has_cell_pixels) rs.cell_pixels.w else 8); - try w.putU16(if (comptime has_cell_pixels) rs.cell_pixels.h else 16); + try w.writeInt(u16, if (comptime has_cell_pixels) rs.cell_pixels.w else 8, .little); + try w.writeInt(u16, if (comptime has_cell_pixels) rs.cell_pixels.h else 16, .little); try putMetrics(&w, rs.row_metrics); }, - .paste => |b| try w.putSlice32(b), - .command => |line| try w.putSlice16(line), + .paste => |b| try putSlice32(&w, b), + .command => |line| try putSlice16(&w, line), .pdf_scroll => |s| { - try w.putByte(s.pane); - try w.putF32(s.delta_pixels); + try w.writeByte(s.pane); + try w.writeInt(u32, @bitCast(s.delta_pixels), .little); + try w.writeByte(@intFromBool(s.glide)); }, - .pinch => |v| try w.putF32(v), - .touch_scroll => |v| try w.putF32(v), + .pinch => |v| try w.writeInt(u32, @bitCast(v), .little), + .touch_scroll => |v| try w.writeInt(u32, @bitCast(v), .little), .pointer_leave => {}, + .focus => |focused| try w.writeByte(@intFromBool(focused)), // See `clientTag`: no tag, so nothing to encode. - .output, .eof, .lsp_resp, .pipe_resp, .file_changed, .tick, .fs_req => unreachable, + .output, .eof, .exited, .lsp_resp, .pipe_resp, .search, .file_changed, .handed, .tick => unreachable, }, } try finishMessage(&w, at); - return w.written(); + return w.buffered(); } pub fn decodeClient(tag: u8, payload: []const u8) Error!ClientMsg { - var r: Reader = .init(payload); + var r: std.Io.Reader = .fixed(payload); const msg: ClientMsg = switch (std.enums.fromInt(ClientTag, tag) orelse return error.BadTag) { .hello => .{ .hello = .{ - .version = try r.getU16(), - .cols = try r.getCols(), - .rows = try r.getRows(), + .version = try r.takeInt(u16, .little), + .cols = try getCols(&r), + .rows = try getRows(&r), } }, .bye => .bye, .key => blk: { - const cp = try r.getU32(); + const cp = try r.takeInt(u32, .little); // `Key.cp` is a u21, and the specials live in the private-use // plane below this bound. A larger number is not a codepoint and // @intCast of it would panic in a release build's own decoder. if (cp > 0x10FFFF) return error.BadValue; break :blk .{ .event = .{ .key = .{ .cp = @intCast(cp), - .text = try r.getSlice16(), - .ctrl = try r.getBool(), - .alt = try r.getBool(), - .shift = try r.getBool(), + .text = try r.take(try r.takeInt(u16, .little)), + .ctrl = try getBool(&r), + .alt = try getBool(&r), + .shift = try getBool(&r), } } }; }, .mouse => .{ .event = .{ .mouse = .{ - .button = switch (try r.getTag(ButtonTag)) { + .button = switch (try getTag(&r, ButtonTag)) { inline else => |t| @field(pardes.Mouse.Button, @tagName(t)), }, - .kind = switch (try r.getTag(KindTag)) { + .kind = switch (try getTag(&r, KindTag)) { inline else => |t| @field(pardes.Mouse.Kind, @tagName(t)), }, - .col = try r.getU16(), - .row = try r.getU16(), - .ctrl = try r.getBool(), + .col = try r.takeInt(u16, .little), + .row = try r.takeInt(u16, .little), + .ctrl = try getBool(&r), + .shift = try getBool(&r), + .alt = try getBool(&r), .body_hit = try getBodyHit(&r), .tag_hit = try getTagHit(&r), } } }, .resize => blk: { - var ev: pardes.Event = .{ .resize = .{ .cols = try r.getCols(), .rows = try r.getRows() } }; - const px_w = try r.getU16(); - const px_h = try r.getU16(); + var ev: pardes.Event = .{ .resize = .{ .cols = try getCols(&r), .rows = try getRows(&r) } }; + const px_w = try r.takeInt(u16, .little); + const px_h = try r.takeInt(u16, .little); // Read either way — the bytes are on the wire — and kept only by a // build that has somewhere to keep them. if (comptime has_cell_pixels) ev.resize.cell_pixels = .{ .w = px_w, .h = px_h }; ev.resize.row_metrics = try getMetrics(&r); break :blk .{ .event = ev }; }, - .paste => .{ .event = .{ .paste = try r.getSlice32() } }, - .command => .{ .event = .{ .command = try r.getSlice16() } }, - .pdf_scroll => .{ .event = .{ .pdf_scroll = .{ .pane = try r.getPane(), .delta_pixels = try r.getF32() } } }, - .pinch => .{ .event = .{ .pinch = try r.getF32() } }, - .touch_scroll => .{ .event = .{ .touch_scroll = try r.getF32() } }, + .paste => .{ .event = .{ .paste = try getSlice32(&r) } }, + .command => .{ .event = .{ .command = try r.take(try r.takeInt(u16, .little)) } }, + .pdf_scroll => .{ .event = .{ .pdf_scroll = .{ .pane = try getPane(&r), .delta_pixels = try getF32(&r), .glide = try getBool(&r) } } }, + .pinch => .{ .event = .{ .pinch = try getF32(&r) } }, + .touch_scroll => .{ .event = .{ .touch_scroll = try getF32(&r) } }, .pointer_leave => .{ .event = .pointer_leave }, + .focus => .{ .event = .{ .focus = try getBool(&r) } }, }; - try r.end(); + try end(&r); return msg; } @@ -1019,29 +1066,42 @@ fn serverTag(msg: ServerMsg) ServerTag { } /// Every server message EXCEPT a frame, which has its own encoder because its -/// payload is a walk of two grids rather than a value (see `encodeFrame`). +/// payload is a walk of two grids rather than a value (see `encodeFrameLayers`). pub fn encodeServer(out: []u8, msg: ServerMsg) Error![]const u8 { - var w: Writer = .init(out); - const at = try beginMessage(&w, @intFromEnum(serverTag(msg))); + var w: std.Io.Writer = .fixed(out); + const at = try beginMessage(&w, @backingInt(serverTag(msg))); switch (msg) { .welcome => |v| { - try w.putU16(v.version); - try w.putByte(v.slot); - try w.putU16(v.cols); - try w.putU16(v.rows); + try w.writeInt(u16, v.version, .little); + try w.writeByte(v.slot); + try w.writeInt(u16, v.cols, .little); + try w.writeInt(u16, v.rows, .little); }, - .refuse => |why| try w.putByte(@intFromEnum(why)), + .refuse => |why| try w.writeByte(@backingInt(why)), // A frame's runs are not a value this union can hold; the server calls - // encodeFrame directly and this arm exists so the switch stays + // encodeFrameLayers directly and this arm exists so the switch stays // exhaustive over ServerMsg. .frame => return error.BadValue, .quit, .detach => {}, - .set_clipboard => |t| try w.putSlice32(t), + .set_clipboard => |t| try putSlice32(&w, t), .read_clipboard => {}, - .open_link => |u| try w.putSlice16(u), + .open_link => |u| try putSlice16(&w, u), + .post => |p| { + try w.writeByte(@backingInt(p.animation)); + try w.writeByte(p.len); + for (p.list()) |pass| { + // 0 a file, else a bundled scene and one. + try w.writeByte(if (pass.scene) |scene| @as(u8, @backingInt(scene)) + 1 else 0); + try w.writeByte(pass.level); + try w.writeByte(@intFromBool(pass.animated)); + try w.writeInt(u32, pass.revision, .little); + try putSlice16(&w, pass.path); + try putSlice32(&w, pass.spirv); + } + }, } try finishMessage(&w, at); - return w.written(); + return w.buffered(); } /// Slack over a message's variable payload, covering every fixed field any @@ -1060,6 +1120,11 @@ pub fn serverBound(msg: ServerMsg) usize { .frame => |f| frameBound(f.cols, f.rows), .set_clipboard => |t| t.len, .open_link => |u| u.len, + .post => |p| blk: { + var n: usize = 0; + for (p.list()) |pass| n += 13 + pass.path.len + pass.spirv.len; + break :blk n; + }, }; } @@ -1068,44 +1133,44 @@ pub fn clientBound(msg: ClientMsg) usize { return msg_slack + switch (msg) { .hello, .bye => 0, .event => |ev| switch (ev) { - .mouse, .resize, .pdf_scroll, .pinch, .touch_scroll, .pointer_leave => 0, + .mouse, .resize, .pdf_scroll, .pinch, .touch_scroll, .pointer_leave, .focus => 0, .key => |k| k.text.len, .paste => |b| b.len, .command => |line| line.len, // See `clientTag`: not on this wire in this direction. - .output, .eof, .lsp_resp, .pipe_resp, .file_changed, .tick, .fs_req => unreachable, + .output, .eof, .exited, .lsp_resp, .pipe_resp, .search, .file_changed, .handed, .tick => unreachable, }, }; } pub fn decodeServer(tag: u8, payload: []const u8) Error!ServerMsg { - var r: Reader = .init(payload); + var r: std.Io.Reader = .fixed(payload); const msg: ServerMsg = switch (std.enums.fromInt(ServerTag, tag) orelse return error.BadTag) { .welcome => .{ .welcome = .{ - .version = try r.getU16(), - .slot = try r.getByte(), - .cols = try r.getCols(), - .rows = try r.getRows(), + .version = try r.takeInt(u16, .little), + .slot = try r.takeByte(), + .cols = try getCols(&r), + .rows = try getRows(&r), } }, - .refuse => .{ .refuse = try r.getTag(Refusal) }, + .refuse => .{ .refuse = try getTag(&r, Refusal) }, .frame => blk: { - const header = try r.getTag(FrameHeader); + const header = try getTag(&r, FrameHeader); const kind: FrameKind = switch (header) { .full, .full_link => .full, .diff, .diff_link => .diff, }; - const cols = try r.getCols(); - const rows = try r.getRows(); + const cols = try getCols(&r); + const rows = try getRows(&r); const cursor = try getCursor(&r, cols, rows); - const layers = try r.getSlice32(); - const nruns = try r.getU32(); + const layers = try getSlice32(&r); + const nruns = try r.takeInt(u32, .little); // One run per cell is the worst an encoder emits, so a bigger // count cannot be describing this grid. Checked HERE rather than // in `apply`'s loop so the number is refused before it is used to // bound anything. if (nruns > @as(u32, cols) * @as(u32, rows)) return error.Overlong; - const runs = r.bytes[r.i..]; - r.i = r.bytes.len; + const runs = r.buffered(); + r.tossBuffered(); break :blk .{ .frame = .{ .layers = layers, .kind = kind, @@ -1119,11 +1184,32 @@ pub fn decodeServer(tag: u8, payload: []const u8) Error!ServerMsg { }, .quit => .quit, .detach => .detach, - .set_clipboard => .{ .set_clipboard = try r.getSlice32() }, + .set_clipboard => .{ .set_clipboard = try getSlice32(&r) }, .read_clipboard => .read_clipboard, - .open_link => .{ .open_link = try r.getSlice16() }, + .open_link => .{ .open_link = try r.take(try r.takeInt(u16, .little)) }, + .post => blk: { + var p: Post = .{ .animation = try getTag(&r, ShaderAnimation) }; + p.len = try r.takeByte(); + if (p.len > ShaderBuild.max) return error.Overlong; + for (p.passes[0..p.len]) |*pass| { + const kind = try r.takeByte(); + pass.* = .{ + .scene = if (kind == 0) null else std.enums.fromInt(Scene, kind - 1) orelse return error.BadValue, + .level = try r.takeByte(), + .animated = switch (try r.takeByte()) { + 0 => false, + 1 => true, + else => return error.BadValue, + }, + .revision = try r.takeInt(u32, .little), + .path = try r.take(try r.takeInt(u16, .little)), + .spirv = try getSlice32(&r), + }; + } + break :blk .{ .post = p }; + }, }; - try r.end(); + try end(&r); return msg; } @@ -1160,9 +1246,9 @@ test "detached wire: every Event variant round-trips" { // The tag space is the protocol's own, so assert the numbers themselves: // a renumbering here breaks every deployed frontend and must be a diff // somebody reads, not a silent change. - try testing.expectEqual(@as(u8, 0x01), @intFromEnum(ClientTag.hello)); - try testing.expectEqual(@as(u8, 0x10), @intFromEnum(ClientTag.key)); - try testing.expectEqual(@as(u8, 0x1d), @intFromEnum(ClientTag.pointer_leave)); + try testing.expectEqual(@as(u8, 0x01), @backingInt(ClientTag.hello)); + try testing.expectEqual(@as(u8, 0x10), @backingInt(ClientTag.key)); + try testing.expectEqual(@as(u8, 0x1d), @backingInt(ClientTag.pointer_leave)); { const got = try roundClient(&buf, .{ .hello = .{ .cols = 80, .rows = 24 } }); @@ -1186,13 +1272,15 @@ test "detached wire: every Event variant round-trips" { // the only place a value can be mistranslated and still decode. for (std.enums.values(pardes.Mouse.Button)) |button| { for (std.enums.values(pardes.Mouse.Kind)) |kind| { - const m: pardes.Mouse = .{ .button = button, .kind = kind, .col = 4200, .row = 7, .ctrl = true }; + const m: pardes.Mouse = .{ .button = button, .kind = kind, .col = 4200, .row = 7, .ctrl = true, .shift = true, .alt = true }; const got = (try roundClient(&buf, .{ .event = .{ .mouse = m } })).event.mouse; try testing.expectEqual(m.button, got.button); try testing.expectEqual(m.kind, got.kind); try testing.expectEqual(m.col, got.col); try testing.expectEqual(m.row, got.row); try testing.expectEqual(m.ctrl, got.ctrl); + try testing.expectEqual(m.shift, got.shift); + try testing.expectEqual(m.alt, got.alt); } } } @@ -1210,9 +1298,10 @@ test "detached wire: every Event variant round-trips" { try testing.expectEqualStrings("clip", (try roundClient(&buf, .{ .event = .{ .paste = "clip" } })).event.paste); try testing.expectEqualStrings("Look /x", (try roundClient(&buf, .{ .event = .{ .command = "Look /x" } })).event.command); { - const got = (try roundClient(&buf, .{ .event = .{ .pdf_scroll = .{ .pane = 2, .delta_pixels = -12.5 } } })).event.pdf_scroll; + const got = (try roundClient(&buf, .{ .event = .{ .pdf_scroll = .{ .pane = 2, .delta_pixels = -12.5, .glide = false } } })).event.pdf_scroll; try testing.expectEqual(@as(u8, 2), got.pane); try testing.expectEqual(@as(f32, -12.5), got.delta_pixels); + try testing.expect(!got.glide); } try testing.expectEqual(@as(f32, 1.25), (try roundClient(&buf, .{ .event = .{ .pinch = 1.25 } })).event.pinch); try testing.expectEqual(@as(f32, -0.75), (try roundClient(&buf, .{ .event = .{ .touch_scroll = -0.75 } })).event.touch_scroll); @@ -1239,6 +1328,19 @@ test "detached wire: every server message round-trips" { try testing.expectEqualStrings("yank", (try roundServer(&buf, .{ .set_clipboard = "yank" })).set_clipboard); try testing.expectEqual(ServerMsg.read_clipboard, try roundServer(&buf, .read_clipboard)); try testing.expectEqualStrings("https://x", (try roundServer(&buf, .{ .open_link = "https://x" })).open_link); + var chain: Post = .{ .animation = .always, .len = 2 }; + chain.passes[0] = .{ .scene = .bloom, .level = 3 }; + chain.passes[1] = .{ .path = "~/wave.glsl", .spirv = "\x03\x02\x23\x07spirv", .revision = 7, .animated = true }; + const back = (try roundServer(&buf, .{ .post = chain })).post; + try testing.expectEqual(ShaderAnimation.always, back.animation); + try testing.expectEqual(@as(u8, 2), back.len); + try testing.expectEqual(Scene.bloom, back.passes[0].scene.?); + try testing.expectEqual(@as(u8, 3), back.passes[0].level); + try testing.expect(back.passes[1].scene == null); + try testing.expectEqualStrings("~/wave.glsl", back.passes[1].path); + try testing.expectEqualStrings("\x03\x02\x23\x07spirv", back.passes[1].spirv); + try testing.expectEqual(@as(u32, 7), back.passes[1].revision); + try testing.expect(back.passes[1].animated and !back.passes[0].animated); } test "detached wire: only the display's own effects are on the wire" { @@ -1247,9 +1349,9 @@ test "detached wire: only the display's own effects are on the wire" { // is the direction that matters: it would hand a frontend work that must // outlive it. The count fails if one of the three is dropped, which would // silently leave a clipboard or a link unanswered on every frontend. - try testing.expectEqual(@as(usize, 8), std.enums.values(ServerTag).len); + try testing.expectEqual(@as(usize, 9), std.enums.values(ServerTag).len); for (std.enums.values(ServerTag)) |t| switch (t) { - .welcome, .refuse, .frame, .quit, .detach, .set_clipboard, .read_clipboard, .open_link => {}, + .welcome, .refuse, .frame, .quit, .detach, .set_clipboard, .read_clipboard, .open_link, .post => {}, }; } @@ -1265,7 +1367,7 @@ test "detached wire: a session is never told to do a frontend's remembering" { // Adding a name here is meant to be an ARGUMENT, not a formality, and the // bar is one sentence: A HUMAN DID IT. A keystroke, a click, a pinch, a // window resized, a paste, a command line executed, a pointer leaving the - // window — plus the two session words that say who is speaking. A pty's + // window, the window's focus — plus the two session words that say who is speaking. A pty's // output, a worker's answer, a watched file's new bytes and an animation // tick all fail that bar the same way: nobody did them, a machine reported // them, and the machine that reports them is the one already holding the @@ -1278,7 +1380,7 @@ test "detached wire: a session is never told to do a frontend's remembering" { "resize", "paste", "command", "pdf_scroll", "pinch", "touch_scroll", - "pointer_leave", + "pointer_leave", "focus", }; // One: the tag set is exactly that, named rather than counted, so @@ -1302,7 +1404,7 @@ test "detached wire: a session is never told to do a frontend's remembering" { for (0..256) |i| { const tag: u8 = @intCast(i); // Empty payloads on purpose: what is asked is whether the TAG is known. - // A known one fails later (`Truncated`) or succeeds, never with + // A known one fails later (`EndOfStream`) or succeeds, never with // `BadTag`. if (decodeClient(tag, &.{})) |_| accepted += 1 else |err| switch (err) { error.BadTag => continue, @@ -1310,7 +1412,7 @@ test "detached wire: a session is never told to do a frontend's remembering" { } const named = for (allowed) |ok| { const want = std.meta.stringToEnum(ClientTag, ok).?; - if (@intFromEnum(want) == tag) break true; + if (@backingInt(want) == tag) break true; } else false; if (!named) { std.debug.print("tag 0x{x:0>2} is decodable by a session and is not something a human did\n", .{tag}); @@ -1382,7 +1484,7 @@ test "detached wire: a full frame carries the grid, a diff carries the change" { // FULL: nothing on the far side is comparable, which is the late joiner // and the resize both. - const full_bytes = try encodeFrame(buf, cols, rows, .{ .x = 3, .y = 4, .bar = true }, cells, &.{}); + const full_bytes = try encodeFrameLayers(buf, cols, rows, .{ .x = 3, .y = 4, .bar = true }, .arrow, cells, &.{}, &.{}, &.{}, &.{}, .{}); { const f = (try framed(full_bytes)).?; const msg = (try decodeServer(f.tag, f.payload)).frame; @@ -1402,7 +1504,7 @@ test "detached wire: a full frame carries the grid, a diff carries the change" { defer gpa.free(before); cells[100] = .{ .text = "q".* ++ @as([6]u8, @splat(0)), .len = 1, .default = false }; cells[0] = .{}; // ...and one goes back to unpainted, which a diff must say - const diff_bytes = try encodeFrame(buf, cols, rows, null, cells, before); + const diff_bytes = try encodeFrameLayers(buf, cols, rows, null, .arrow, cells, before, &.{}, &.{}, &.{}, .{}); { const f = (try framed(diff_bytes)).?; const msg = (try decodeServer(f.tag, f.payload)).frame; @@ -1416,7 +1518,7 @@ test "detached wire: a full frame carries the grid, a diff carries the change" { // An unchanged frame is the head and nothing else: no runs, and the // receiver keeps what it has. This is what makes an idle session silent. { - const idle = try encodeFrame(buf, cols, rows, null, cells, cells); + const idle = try encodeFrameLayers(buf, cols, rows, null, .arrow, cells, cells, &.{}, &.{}, &.{}, .{}); try testing.expectEqual(@as(usize, header_len + frame_head), idle.len); const f = (try framed(idle)).?; const msg = (try decodeServer(f.tag, f.payload)).frame; @@ -1452,7 +1554,7 @@ test "detached wire: the largest grid is one cell past a run, and survives it" { for (cells) |*c| c.* = .{ .text = "a".* ++ @as([6]u8, @splat(0)), .len = 1, .default = false }; @memset(mirror, .{}); - const bytes = try encodeFrame(buf, cols, rows, null, cells, &.{}); + const bytes = try encodeFrameLayers(buf, cols, rows, null, .arrow, cells, &.{}, &.{}, &.{}, &.{}, .{}); const f = (try framed(bytes)).?; const msg = (try decodeServer(f.tag, f.payload)).frame; try testing.expectEqual(FrameKind.full, msg.kind); @@ -1462,7 +1564,7 @@ test "detached wire: the largest grid is one cell past a run, and survives it" { try expectGridEqual(cells, mirror); // ...at exactly the two headers the split costs and not one byte more. // `bytes.len <= frameBound(...)` would prove nothing here — the buffer IS - // `frameBound` bytes, so an over-run is `NoSpace` above, not a false + // `frameBound` bytes, so an over-run is `WriteFailed` above, not a false // assertion here — and what wants pinning is that the second run is the // whole of the cost. try testing.expectEqual( @@ -1472,7 +1574,7 @@ test "detached wire: the largest grid is one cell past a run, and survives it" { } test "detached wire: the diff is worth having, in bytes, on the board's grid" { - // The numbers quoted in `encodeFrame`'s comment, asserted so the claim + // The numbers quoted in `encodeFrameLayers`'s comment, asserted so the claim // cannot rot. 56x14 is the ESP32-P4 board's default grid (esp32p4.zig). const cols: u16 = 56; const rows: u16 = 14; @@ -1487,7 +1589,7 @@ test "detached wire: the diff is worth having, in bytes, on the board's grid" { // Every cell painted with a plain ASCII glyph and default colors, which is // what a pardes frame overwhelmingly is: eight bytes a cell. for (cells) |*c| c.* = .{ .text = "a".* ++ @as([6]u8, @splat(0)), .len = 1, .default = false }; - const full = (try encodeFrame(buf, cols, rows, null, cells, &.{})).len; + const full = (try encodeFrameLayers(buf, cols, rows, null, .arrow, cells, &.{}, &.{}, &.{}, &.{}, .{})).len; try testing.expectEqual(@as(usize, header_len + frame_head + run_header + n * 8), full); try testing.expectEqual(@as(usize, 6302), full); @@ -1498,7 +1600,7 @@ test "detached wire: the diff is worth having, in bytes, on the board's grid" { cells[300] = .{ .text = "b".* ++ @as([6]u8, @splat(0)), .len = 1, .default = false }; cells[301] = .{ .text = "c".* ++ @as([6]u8, @splat(0)), .len = 1, .default = false }; cells[500] = .{ .text = "d".* ++ @as([6]u8, @splat(0)), .len = 1, .default = false }; - const diff = (try encodeFrame(buf, cols, rows, null, cells, before)).len; + const diff = (try encodeFrameLayers(buf, cols, rows, null, .arrow, cells, before, &.{}, &.{}, &.{}, .{})).len; try testing.expectEqual(@as(usize, header_len + frame_head + 2 * run_header + 3 * 8), diff); try testing.expectEqual(@as(usize, 60), diff); // The whole reason this codec exists rather than shipping the Surface. @@ -1517,7 +1619,7 @@ test "detached wire: a run is coalesced across a gap only when that is cheaper" cells[0] = .{ .text = "a".* ++ @as([6]u8, @splat(0)), .len = 1, .default = false }; cells[4] = .{ .text = "b".* ++ @as([6]u8, @splat(0)), .len = 1, .default = false }; { - const f = (try framed(try encodeFrame(&buf, cols, rows, null, &cells, &prev))).?; + const f = (try framed(try encodeFrameLayers(&buf, cols, rows, null, .arrow, &cells, &prev, &.{}, &.{}, &.{}, .{}))).?; try testing.expectEqual(@as(u32, 1), (try decodeServer(f.tag, f.payload)).frame.nruns); } // Now put a PAINTED cell in the gap that both sides already agree about. @@ -1526,12 +1628,12 @@ test "detached wire: a run is coalesced across a gap only when that is cheaper" cells[2] = painted; prev[2] = painted; { - const f = (try framed(try encodeFrame(&buf, cols, rows, null, &cells, &prev))).?; + const f = (try framed(try encodeFrameLayers(&buf, cols, rows, null, .arrow, &cells, &prev, &.{}, &.{}, &.{}, .{}))).?; try testing.expectEqual(@as(u32, 2), (try decodeServer(f.tag, f.payload)).frame.nruns); } // Whichever it chose, the receiver ends up with the same grid. var mirror: [8]pardes.Cell = prev; - const f = (try framed(try encodeFrame(&buf, cols, rows, null, &cells, &prev))).?; + const f = (try framed(try encodeFrameLayers(&buf, cols, rows, null, .arrow, &cells, &prev, &.{}, &.{}, &.{}, .{}))).?; try (try decodeServer(f.tag, f.payload)).frame.apply(&mirror); try expectGridEqual(&cells, &mirror); } @@ -1550,14 +1652,14 @@ test "detached wire: a truncated frame is refused at every length" { // ...and the same bytes handed to the decoder with the header's length // left claiming the whole message, which is how a decoder is walked // off the end of its buffer. - try testing.expectError(error.Truncated, decodeClient(copy[0], copy[header_len..cut])); + try testing.expectError(error.EndOfStream, decodeClient(copy[0], copy[header_len..cut])); } // Shorter than the header itself is not yet a message at all. for (0..header_len + 1) |cut| try testing.expectEqual(@as(?Framed, null), try framed(copy[0..cut])); // A payload with bytes LEFT OVER is refused too: it is not this message. - try testing.expectError(error.Trailing, decodeClient(@intFromEnum(ClientTag.pointer_leave), "x")); - try testing.expectError(error.Trailing, decodeServer(@intFromEnum(ServerTag.quit), "x")); + try testing.expectError(error.Trailing, decodeClient(@backingInt(ClientTag.pointer_leave), "x")); + try testing.expectError(error.Trailing, decodeServer(@backingInt(ServerTag.quit), "x")); } test "detached wire: an unknown tag is refused, never guessed" { @@ -1569,9 +1671,9 @@ test "detached wire: an unknown tag is refused, never guessed" { } // A tag NESTED in a payload gets the same treatment: a color, an // underline style, a mouse button, a refusal reason. - try testing.expectError(error.BadTag, decodeServer(@intFromEnum(ServerTag.refuse), &.{0x7f})); + try testing.expectError(error.BadTag, decodeServer(@backingInt(ServerTag.refuse), &.{0x7f})); try testing.expectError(error.BadTag, decodeClient( - @intFromEnum(ClientTag.mouse), + @backingInt(ClientTag.mouse), &.{ 0xff, 0x00, 0, 0, 0, 0, 0 }, )); } @@ -1579,7 +1681,7 @@ test "detached wire: an unknown tag is refused, never guessed" { test "detached wire: an over-long length prefix is refused before it is believed" { // The prefix a hostile or corrupt peer sends to make the receiver allocate // or index by it. `framed` must refuse rather than wait for 4 GiB. - var head: [header_len]u8 = .{ @intFromEnum(ClientTag.paste), 0, 0, 0, 0 }; + var head: [header_len]u8 = .{ @backingInt(ClientTag.paste), 0, 0, 0, 0 }; std.mem.writeInt(u32, head[1..5], max_payload + 1, .little); try testing.expectError(error.Overlong, framed(&head)); std.mem.writeInt(u32, head[1..5], std.math.maxInt(u32), .little); @@ -1593,10 +1695,10 @@ test "detached wire: an over-long length prefix is refused before it is believed var paste: [8]u8 = undefined; std.mem.writeInt(u32, paste[0..4], 4096, .little); @memcpy(paste[4..8], "abcd"); - try testing.expectError(error.Truncated, decodeClient(@intFromEnum(ClientTag.paste), &paste)); + try testing.expectError(error.EndOfStream, decodeClient(@backingInt(ClientTag.paste), &paste)); // ...and past the cap, which is refused rather than read. std.mem.writeInt(u32, paste[0..4], max_payload + 1, .little); - try testing.expectError(error.Overlong, decodeClient(@intFromEnum(ClientTag.paste), &paste)); + try testing.expectError(error.Overlong, decodeClient(@backingInt(ClientTag.paste), &paste)); } test "detached wire: a frame that lies about its runs cannot walk out of the grid" { @@ -1640,14 +1742,14 @@ test "detached wire: a frame that lies about its runs cannot walk out of the gri // A run count larger than the grid has cells is refused at DECODE, before // it is used to bound the walk. var head: [frame_head]u8 = undefined; - var w: Writer = .init(&head); - try w.putByte(@intFromEnum(FrameKind.diff)); - try w.putU16(cols); - try w.putU16(rows); + var w: std.Io.Writer = .fixed(&head); + try w.writeByte(@backingInt(FrameKind.diff)); + try w.writeInt(u16, cols, .little); + try w.writeInt(u16, rows, .little); try putCursor(&w, null, cols, rows); - try w.putU32(0); // no body layers - try w.putU32(9); - try testing.expectError(error.Overlong, decodeServer(@intFromEnum(ServerTag.frame), w.written())); + try w.writeInt(u32, 0, .little); // no body layers + try w.writeInt(u32, 9, .little); + try testing.expectError(error.Overlong, decodeServer(@backingInt(ServerTag.frame), w.buffered())); // ...and a grid of the wrong size is the receiver's own bug, not a frame // it should paint half of. @@ -1667,7 +1769,7 @@ test "detached wire: link pointer survives full and unchanged grid frames" { var buffer: [256]u8 = undefined; for ([_]pardes.Surface.PointerShape{ .link, .arrow, .link }) |shape| { for ([_]bool{ true, false }) |full| { - const bytes = try encodeFramePointer(&buffer, 1, 1, null, shape, &cells, if (full) &.{} else &cells); + const bytes = try encodeFrameLayers(&buffer, 1, 1, null, shape, &cells, if (full) &.{} else &cells, &.{}, &.{}, &.{}, .{}); const packet = (try framed(bytes)).?; const frame = (try decodeServer(packet.tag, packet.payload)).frame; try std.testing.expectEqual(shape, frame.pointer_shape); @@ -1688,32 +1790,32 @@ test "detached wire: a cursor outside the grid is refused, not painted" { const rows: u16 = 2; var head: [frame_head]u8 = undefined; for ([_][2]u16{ .{ cols, 0 }, .{ 0, rows }, .{ 0xffff, 0xffff } }) |xy| { - var w: Writer = .init(&head); - try w.putByte(@intFromEnum(FrameKind.diff)); - try w.putU16(cols); - try w.putU16(rows); + var w: std.Io.Writer = .fixed(&head); + try w.writeByte(@backingInt(FrameKind.diff)); + try w.writeInt(u16, cols, .little); + try w.writeInt(u16, rows, .little); // Written by hand: `putCursor` now refuses this too, which is the // other half of the same fix and is asserted below. - try w.putBool(true); - try w.putU16(xy[0]); - try w.putU16(xy[1]); - try w.putBool(false); - try w.putU32(0); + try w.writeByte(@intFromBool(true)); + try w.writeInt(u16, xy[0], .little); + try w.writeInt(u16, xy[1], .little); + try w.writeByte(@intFromBool(false)); + try w.writeInt(u32, 0, .little); try testing.expectError( error.BadValue, - decodeServer(@intFromEnum(ServerTag.frame), w.written()), + decodeServer(@backingInt(ServerTag.frame), w.buffered()), ); } // The last cell IS in the grid, and a frame carrying it decodes. { - var w: Writer = .init(&head); - try w.putByte(@intFromEnum(FrameKind.diff)); - try w.putU16(cols); - try w.putU16(rows); + var w: std.Io.Writer = .fixed(&head); + try w.writeByte(@backingInt(FrameKind.diff)); + try w.writeInt(u16, cols, .little); + try w.writeInt(u16, rows, .little); try putCursor(&w, .{ .x = cols - 1, .y = rows - 1, .bar = true }, cols, rows); - try w.putU32(0); // no body layers - try w.putU32(0); - const got = (try decodeServer(@intFromEnum(ServerTag.frame), w.written())).frame; + try w.writeInt(u32, 0, .little); // no body layers + try w.writeInt(u32, 0, .little); + const got = (try decodeServer(@backingInt(ServerTag.frame), w.buffered())).frame; try testing.expectEqual(@as(u16, cols - 1), got.cursor.?.x); try testing.expectEqual(@as(u16, rows - 1), got.cursor.?.y); } @@ -1723,13 +1825,13 @@ test "detached wire: a cursor outside the grid is refused, not painted" { var buf: [512]u8 = undefined; try testing.expectError( error.BadValue, - encodeFrame(&buf, cols, rows, .{ .x = cols, .y = 0, .bar = false }, &cells, &.{}), + encodeFrameLayers(&buf, cols, rows, .{ .x = cols, .y = 0, .bar = false }, .arrow, &cells, &.{}, &.{}, &.{}, &.{}, .{}), ); // A grid past the protocol's own ceiling is refused by the encoder for the // same reason: `max_payload` is derived from it, so the decoder would. try testing.expectError( error.Overlong, - encodeFrame(&buf, max_cols + 1, 1, null, cells[0..0], &.{}), + encodeFrameLayers(&buf, max_cols + 1, 1, null, .arrow, cells[0..0], &.{}, &.{}, &.{}, &.{}, .{}), ); } @@ -1737,25 +1839,25 @@ test "detached wire: values a field cannot mean are refused" { // A bool is 0 or 1. `2` used to be "true" in every hand-written codec that // ever silently accepted a corrupt stream. try testing.expectError(error.BadValue, decodeClient( - @intFromEnum(ClientTag.key), + @backingInt(ClientTag.key), &.{ 'a', 0, 0, 0, 0, 0, 2, 0, 0 }, )); // A codepoint past Unicode's last: @intCast into Key.cp's u21 would panic. try testing.expectError(error.BadValue, decodeClient( - @intFromEnum(ClientTag.key), + @backingInt(ClientTag.key), &.{ 0x00, 0x00, 0x11, 0x00, 0, 0, 0, 0, 0 }, )); // A pane the core cannot index. `pdf_scroll` reads its pane byte before the // f32 that follows, so a one-byte payload reaches the check this is about - // rather than tripping `Truncated` first. + // rather than tripping `EndOfStream` first. try testing.expectError(error.BadValue, decodeClient( - @intFromEnum(ClientTag.pdf_scroll), + @backingInt(ClientTag.pdf_scroll), &.{pardes.MAX_PANES}, )); // A zero-column grid would collapse a shared session; an over-wide one is // past what this protocol carries. try testing.expectError(error.BadValue, decodeClient( - @intFromEnum(ClientTag.hello), + @backingInt(ClientTag.hello), &.{ 1, 0, 0, 0, 24, 0 }, )); { @@ -1763,15 +1865,15 @@ test "detached wire: values a field cannot mean are refused" { std.mem.writeInt(u16, hello[0..2], version, .little); std.mem.writeInt(u16, hello[2..4], max_cols + 1, .little); std.mem.writeInt(u16, hello[4..6], 24, .little); - try testing.expectError(error.BadValue, decodeClient(@intFromEnum(ClientTag.hello), &hello)); + try testing.expectError(error.BadValue, decodeClient(@backingInt(ClientTag.hello), &hello)); } // A NaN scroll distance. `pinch` multiplies into a zoom the pane keeps. { var pinch: [4]u8 = undefined; std.mem.writeInt(u32, &pinch, @bitCast(std.math.nan(f32)), .little); - try testing.expectError(error.BadValue, decodeClient(@intFromEnum(ClientTag.pinch), &pinch)); + try testing.expectError(error.BadValue, decodeClient(@backingInt(ClientTag.pinch), &pinch)); std.mem.writeInt(u32, &pinch, @bitCast(std.math.inf(f32)), .little); - try testing.expectError(error.BadValue, decodeClient(@intFromEnum(ClientTag.touch_scroll), &pinch)); + try testing.expectError(error.BadValue, decodeClient(@backingInt(ClientTag.touch_scroll), &pinch)); } // A cell with the reserved attribute bit set, and one with an impossible // grapheme length. Both are bytes this protocol has no meaning for. @@ -1806,10 +1908,10 @@ test "detached wire: max_payload bounds every message this protocol can build" { const room = try gpa.alloc(u8, huge.len + header_len + 2); defer gpa.free(room); try testing.expectError(error.Overlong, encodeClient(room, .{ .event = .{ .command = huge } })); - // ...and a buffer the caller sized too small is NoSpace, which is the + // ...and a buffer the caller sized too small is WriteFailed, which is the // server's signal to drop that one message rather than the client. var small: [8]u8 = undefined; - try testing.expectError(error.NoSpace, encodeClient(&small, .{ .event = .{ .paste = "0123456789" } })); + try testing.expectError(error.WriteFailed, encodeClient(&small, .{ .event = .{ .paste = "0123456789" } })); } test "detached wire carries compact body rows and exact pointer metrics" { @@ -1817,22 +1919,29 @@ test "detached wire carries compact body rows and exact pointer metrics" { var cells: [8]pardes.Cell = @splat(.{}); var logical: [12]pardes.Cell = @splat(.{}); logical[10] = .{ .text = "z".* ++ @as([6]u8, @splat(0)), .len = 1, .default = false }; - var layer: pardes.BodyLayer = .{ .pane = 0, .serial = 42, .viewport = .{ .x = 0, .y = 0, .w = 2, .h = 4 }, .cols = 2, .rows = 6, .context_rows = 2, .cells = &logical, .cursor = .{ .x = 0, .y = 5, .bar = true } }; + var layer: pardes.Layer = .{ .id = 0, .serial = 42, .viewport = .{ .x = 0, .y = 0, .w = 2, .h = 4 }, .cols = 2, .rows = 6, .context_rows = 2, .cells = &logical, .cursor = .{ .x = 0, .y = 5, .bar = true } }; layer.context_separators.set(0); var tag_cells: [3]pardes.Cell = @splat(.{}); tag_cells[2] = logical[10]; - const tag: pardes.TagLayer = .{ .kind = .column, .id = 1, .viewport = .{ .x = 0, .y = 0, .w = 2, .h = 1 }, .cols = 3, .bg = .{ 11, 22, 33 }, .cells = &tag_cells, .cursor = .{ .col = 2, .bar = true } }; - const out = try gpa.alloc(u8, frameBound(2, 4) + layersBound(&.{layer}, &.{tag})); + const tag: pardes.Layer = .{ .kind = .column, .id = 1, .viewport = .{ .x = 0, .y = 0, .w = 2, .h = 1 }, .cols = 3, .rows = 1, .bg = .{ 11, 22, 33 }, .cells = &tag_cells, .cursor = .{ .x = 2, .y = 0, .bar = true } }; + const placed = [_]pardes.Region{.{ .kind = .rail, .owner = 3, .serial = 42, .rect = .{ .x = 0, .y = 1, .w = 2, .h = 3 }, .active = true, .dirty = true, .thumb_y = 1, .thumb_h = 2, .clip = 1, .lift = 0.5 }}; + const out = try gpa.alloc(u8, frameBound(2, 4) + layersBound(&.{layer}, &.{tag}, &placed)); defer gpa.free(out); - const encoded = try encodeFrameLayers(out, 2, 4, null, .link, &cells, &cells, &.{layer}, &.{tag}); + const palette: pardes.Chrome = .{ .page = .{ 1, 2, 3 }, .border = .{ 4, 5, 6 }, .tag_focus_bg = .{ 7, 8, 9 }, .scroll_thumb = .{ 10, 11, 12 }, .rule_px = 3, .tag_rule = .{ 13, 14, 15 }, .rail_px = 12, .grip_border = .{ 16, 17, 18 }, .grip_focus_ring = .{ 19, 20, 21 }, .grip_dirty = .{ 22, 23, 24 }, .lift_style = 2, .cursor_glide = 3, .cursor_alpha = 0.5, .cursor_idle_ms = 1234, .cursor_quad = .{ 1, 2, 3.5, 2, 3.5, 3, 1, 3 } }; + const encoded = try encodeFrameLayers(out, 2, 4, null, .link, &cells, &cells, &.{layer}, &.{tag}, &placed, palette); const packet = (try framed(encoded)).?; const frame = (try decodeServer(packet.tag, packet.payload)).frame; - var decoded: [pardes.MAX_PANES]pardes.BodyLayer = @splat(.{}); - var tags: [pardes.MAX_TAG_LAYERS]pardes.TagLayer = @splat(.{}); + var decoded: [pardes.MAX_PANES]pardes.Layer = @splat(.{}); + var tags: [pardes.MAX_TAG_LAYERS]pardes.Layer = @splat(.{}); defer for (&tags) |*item| gpa.free(item.cells); defer for (&decoded) |*item| gpa.free(item.cells); try frame.apply(&cells); - try frame.applyLayers(gpa, &decoded, &tags); + var regions: std.ArrayListUnmanaged(pardes.Region) = .empty; + defer regions.deinit(gpa); + var chrome: pardes.Chrome = .{}; + try frame.applyLayers(gpa, &decoded, &tags, ®ions, &chrome); + try std.testing.expectEqualDeep(placed[0..], regions.items); + try std.testing.expectEqualDeep(palette, chrome); try std.testing.expectEqual(@as(u16, 6), decoded[0].rows); try std.testing.expect(decoded[0].context_separators.isSet(0)); try std.testing.expect(!decoded[0].context_separators.isSet(1)); @@ -1844,10 +1953,10 @@ test "detached wire carries compact body rows and exact pointer metrics" { try std.testing.expectEqual(tag.id, tags[0].id); try std.testing.expectEqual(tag.bg, tags[0].bg); try std.testing.expectEqual(tag.cols, tags[0].cols); - try std.testing.expectEqual(@as(u16, 2), tags[0].cursor.?.col); + try std.testing.expectEqual(@as(u16, 2), tags[0].cursor.?.x); try std.testing.expectEqualStrings("z", tags[0].cells[2].grapheme()); - const pointer = layer.hitAt(4, 27, 8, 16, 6, 8).?; - const tag_pointer = tag.hitAt(11, 8, 8, 16, 4, 8).?; + const pointer = layer.bodyHit(4, 27, 8, 16, 6, 8).?; + const tag_pointer = tag.tagHit(11, 8, 8, 16, 4, 8).?; const message: ClientMsg = .{ .event = .{ .mouse = .{ .col = 0, .row = 1, .button = .left, .kind = .press, .body_hit = pointer, .tag_hit = tag_pointer } } }; var mouse_bytes: [256]u8 = undefined; const mouse_encoded = try encodeClient(&mouse_bytes, message); @@ -1858,19 +1967,20 @@ test "detached wire carries compact body rows and exact pointer metrics" { try std.testing.expect(mouse_encoded.len <= clientBound(message)); var truncated = frame; truncated.layers = frame.layers[0 .. frame.layers.len - 1]; - try std.testing.expectError(error.Truncated, truncated.applyLayers(gpa, &decoded, &tags)); + try std.testing.expectError(error.EndOfStream, truncated.applyLayers(gpa, &decoded, &tags, ®ions, &chrome)); for (decoded) |item| { try std.testing.expectEqual(@as(u16, 0), item.rows); try std.testing.expectEqual(@as(usize, 0), item.cells.len); try std.testing.expectEqual(@as(usize, 0), item.context_separators.count()); } for (tags) |item| { - try std.testing.expectEqual(@as(u16, 0), item.cols); + try std.testing.expectEqual(@as(u16, 0), item.rows); try std.testing.expectEqual(@as(usize, 0), item.cells.len); } - const no_layers = try encodeFramePointer(out, 2, 4, null, .arrow, &cells, &cells); + try std.testing.expectEqual(@as(usize, 0), regions.items.len); + const no_layers = try encodeFrameLayers(out, 2, 4, null, .arrow, &cells, &cells, &.{}, &.{}, &.{}, .{}); const cleared_packet = (try framed(no_layers)).?; const cleared = (try decodeServer(cleared_packet.tag, cleared_packet.payload)).frame; - try cleared.applyLayers(gpa, &decoded, &tags); + try cleared.applyLayers(gpa, &decoded, &tags, ®ions, &chrome); try std.testing.expectEqual(@as(u16, 0), decoded[0].rows); } |
