From 5c23bd8b1bbdbbacd99b11e75d38f7ce1801cd8a Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Thu, 29 Oct 2026 10:48:56 -0300 Subject: the frame wire goes: detached/server.zig, client.zig and the cell frames of wire.zig Nothing draws a session's screen from frames any more: a session is always an in-process authority with its terminal or window, and remote clients come back as replicas (docs/next-daemon.md, phase 5). server.zig, the third host and its frontend socket, the smallest-common-grid rule and its 32 frontends; client.zig, the frontend half; wire.zig's frames, cell and layer codecs, server messages and the post chain on the wire. wire.zig keeps the framing, the hello and its version (now 13) and the input events, with their tests, for phase 5. Co-Authored-By: Claude Opus 5.5 --- src/detached/client.zig | 1406 -------------------------------------------- src/detached/server.zig | 1478 ----------------------------------------------- src/detached/wire.zig | 1296 +---------------------------------------- 3 files changed, 17 insertions(+), 4163 deletions(-) delete mode 100644 src/detached/client.zig delete mode 100644 src/detached/server.zig (limited to 'src') diff --git a/src/detached/client.zig b/src/detached/client.zig deleted file mode 100644 index 617ae342..00000000 --- a/src/detached/client.zig +++ /dev/null @@ -1,1406 +0,0 @@ -//! THE FRONTEND SIDE of a detached session: a socket, a grid, and no core. -//! -//! A FRONTEND IS INPUT AND SCREEN, and that is the whole of it. Keystrokes, -//! mouse, window size go out; frames come back and get painted. This is the -//! shape the ESP32-P4 serial console has always had — a panel and a keypad on -//! the far end of a wire, performing no effects of its own — and after the -//! machine-local IO moved into the daemon it is the shape EVERY frontend has, -//! terminal and window alike. -//! -//! THIS SIDE DOES NOT OWN A `Pardes`. There is no `update`, no `postEvent` and -//! no `Host` in this file. The core lives in the detached process (server.zig), -//! which is also where every `Host.VTable` call now lands: forking a pane's -//! shell, writing a file, watching a path and reading the theme directory are -//! all done BY THE DAEMON, against the same machine's kernel it shares with -//! this frontend over an AF_UNIX socket. NO FORK HAPPENS IN A FRONTEND ANY -//! MORE. That is not a simplification of this file, it is the fix: a pane's -//! shell used to be a child of whichever frontend forked it, so leaving killed -//! the shells of a session whose entire promise is outliving frontends. -//! -//! `Client` is NOT a renderer either. It owns `grid` and `cursor`: the cells the -//! session is showing, kept current by applying frames as they arrive. Whoever -//! owns a terminal (or a window, or an ESP32-P4 panel) reads those and paints. -//! The split is deliberate — pardes already has terminal frontends, and a second -//! one living in here would be a second convention for a job that has one. -//! -//! THE ATTACH IS NOT A BLOCKING HANDSHAKE. `open` connects and writes the -//! `hello`; the `welcome` (or the `refuse`) arrives through the ordinary -//! `wait`/`next` loop like everything else. A frontend therefore has one loop -//! and one place it sleeps, instead of a startup path that can hang for two -//! seconds before its terminal is even in raw mode. `attached()` says whether -//! the session has greeted us; `refusal` says why it did not. -//! -//! WHAT ARRIVES. `next` hands back one decoded `wire.ServerMsg` at a time, and -//! there are exactly seven of them: -//! * `welcome` and `frame` have already been applied to `slot`/`cols`/`rows`/ -//! `grid`/`cursor` by the time you see them. They are returned so a frontend -//! knows the screen moved. -//! * `set_clipboard`, `read_clipboard` and `open_link` are the only effects -//! still on the wire, and they are here because each needs THIS HUMAN'S -//! DISPLAY: a daemon nobody is looking at has no clipboard and no browser. -//! The answer to `read_clipboard` is not a reply message: it is an ordinary -//! `Event.paste` sent back through `send`, which is the same asynchronous -//! shape `read_clipboard` already has in-process. -//! * `refuse` is followed by the session closing the connection, and `quit` -//! means the session itself has ended. -//! The switch in `next` is exhaustive over that set on purpose: putting a -//! machine-local effect back on the wire is a compile error here, and the test -//! at the bottom of this file says so in the other direction too. -//! -//! GEOMETRY. `cols`/`rows` are the SESSION's grid, which with several frontends -//! attached is the smallest common one and can be smaller than this frontend's -//! window. Tell the session about the window with `resize`; do not assume the -//! next frame will agree with it. -//! -//! BORROWED BYTES. Every slice in a returned `ServerMsg` points into this -//! client's receive buffer and is valid until the next call to `next` or -//! `wait`. A frontend that needs a payload for longer copies it — the same rule -//! the core's own `Event.output` bytes have. -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"); - -const read_chunk = 16 * 1024; - -pub const Error = error{ - /// No `$XDG_RUNTIME_DIR` and no `$HOME`, or a name that is not one path - /// component — there is no socket path to try. - NoSessionPath, - /// Nothing is listening there: the name is wrong, or that session ended. - /// Its socket file, if it is still lying about, is unlinked by the sweep the - /// next detached session runs. - NoSession, - /// The socket is there and this frontend will not talk to it: the directory - /// or the socket is not a private one of ours (server.zig `vetted`). A - /// planted socket at a derivable path collects every keystroke typed into - /// the frontend that trusts it, so this is refused rather than reported as - /// "no session" — the two need different answers from a human. - NotPrivate, - /// The session hung up, or the connection failed under us. Every read and - /// write path funnels here: a frontend's answer to all of them is the same - /// (report and exit), so distinguishing them would be a distinction nobody - /// acts on. - Closed, - /// The session said something before it said `welcome`. - Ungreeted, -}; - -pub const Client = struct { - gpa: std.mem.Allocator, - fd: c_int = -1, - /// Which client slot the session gave this connection. Diagnostics only, - /// and it exists so both sides print the same number. - slot: u8 = 0, - /// Set by a `refuse`, and the reason a frontend prints before exiting. - refusal: ?wire.Refusal = null, - /// The SESSION's grid, not this frontend's window. Zero until the welcome. - cols: u16 = 0, - rows: u16 = 0, - /// `cols * rows` cells: what the session is showing right now. - grid: std.ArrayListUnmanaged(pardes.Cell) = .empty, - cursor: ?wire.Cursor = null, - pointer_shape: pardes.Surface.PointerShape = .arrow, - 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 - /// the top of the next call, which is exactly what makes that message's - /// borrowed slices valid until then and no longer. - held: usize = 0, - - /// Connect to the session called `name` and say hello, telling it this - /// frontend's window. Does not wait: the greeting arrives through `next`. - pub fn open(gpa: std.mem.Allocator, name: []const u8, cols: u16, rows: u16) (Error || wire.Error)!Client { - var path_buf: [server.path_max]u8 = undefined; - const path = server.sessionPath(&path_buf, name) orelse return error.NoSessionPath; - // `vetted` is one predicate over two different failures, and a human is - // owed different words for them: `NotPrivate` promises, in its own doc - // above, that the socket IS there. So ask the cheap question first, - // because the commonest failure of all is a mistyped session name — - // until this, `Attach nosuchsession` put "attach: NotPrivate" on the - // message row, which reads as an accusation rather than a typo. Spelled - // with the `access` this file already uses in `resolve`. - const F_OK: c_int = 0; - if (libc.access(path, F_OK) != 0) return error.NoSession; - // Both ends vet, and this is this end's half: the session refuses a - // directory or a socket anyone else can reach before it binds, and until - // this a frontend connected to whatever it found at the path it derived. - // See server.zig `vetted` for what is asked and why it is asked there. - if (!server.vetted(path)) return error.NotPrivate; - var addr: libc.sockaddr.un = .{ .path = @splat(0) }; - @memcpy(addr.path[0 .. path.len + 1], path[0 .. path.len + 1]); - const fd = libc.socket(libc.AF.UNIX, libc.SOCK.STREAM, 0); - if (fd < 0) return error.NoSession; - // CLOEXEC anyway, even though a frontend no longer forks pane shells: - // `open_link` runs this display's browser, and a `xdg-open` inheriting - // this socket would keep the session believing a frontend is attached - // long after this process left. - server.setCloexec(fd); - if (comptime server.darwin) { - // linux says MSG_NOSIGNAL per write and darwin says it once per - // socket, which is what `nosignal` being 0 on darwin MEANS — so - // this call is the whole of that platform's protection and the - // comment on `nosignal` used to say `open` made it without `open` - // making it. A session that ends mid-write must not take the - // frontend down with SIGPIPE. server.zig `accept` is the mirror. - const on: c_int = 1; - _ = libc.setsockopt(fd, libc.SOL.SOCKET, libc.SO.NOSIGPIPE, &on, @sizeOf(c_int)); - } - // Still blocking for the connect itself, which on AF_UNIX either lands - // in the listener's backlog immediately or is refused; there is no - // in-progress state to poll for. - if (libc.connect(fd, @ptrCast(&addr), @sizeOf(@TypeOf(addr))) != 0) { - _ = libc.close(fd); - return error.NoSession; - } - _ = server.setNonblock(fd); - var c: Client = .{ .gpa = gpa, .fd = fd }; - errdefer c.deinit(); - try c.send(.{ .hello = .{ - .cols = @min(cols, wire.max_cols), - .rows = @min(rows, wire.max_rows), - } }); - return c; - } - - /// Has the session greeted us? Until it has, `grid` is empty and nothing - /// has been drawn. - pub fn attached(c: *const Client) bool { - return c.cols != 0; - } - - pub fn deinit(c: *Client) void { - if (c.fd >= 0) _ = libc.close(c.fd); - c.fd = -1; - c.grid.deinit(c.gpa); - for (&c.body_layers) |*layer| { - c.gpa.free(layer.cells); - 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); - } - - /// Leave without ending the session. The `bye` is a courtesy — the session - /// handles a frontend that simply dies, and proving it does is what that - /// test is for — but it turns "the peer vanished" into "the peer left" in - /// the session's log, which is worth seven bytes. - pub fn detach(c: *Client) void { - c.send(.bye) catch {}; - c.deinit(); - } - - /// One message on its way to the core. Everything a frontend collects goes - /// through here, and after the IO moved into the daemon that is a short - /// list: keys, the mouse, a window resize, and the paste that answers a - /// `read_clipboard`. `ClientMsg.output`/`.eof` still exist on the wire but - /// no frontend sends them any more — pty bytes are read by the process that - /// forked the shell, which is the daemon. - pub fn send(c: *Client, msg: wire.ClientMsg) (Error || wire.Error)!void { - const want = wire.clientBound(msg); - c.out.ensureUnusedCapacity(c.gpa, want) catch return error.Closed; - const at = c.out.items.len; - // Encoded straight into the queue's tail rather than through a scratch - // buffer: a paste is four megabytes and copying it twice is two copies. - c.out.items.len += want; - const bytes = wire.encodeClient(c.out.items[at..], msg) catch |err| { - // AND THE QUEUE GOES BACK. `want` bytes of it are uninitialised - // right now, and leaving them there — which is what a bare `try` - // did — puts that much stack-shaped garbage on the socket at the - // 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 `WriteFailed`). - c.out.items.len = at; - return err; - }; - c.out.items.len = at + bytes.len; - return c.flush(); - } - - /// Tell the session this frontend's window changed. Not a promise about the - /// next frame: with other frontends attached the session grid is the - /// smallest common one. - /// - /// Clamped, like the hello in `open`: a window past `max_cols`/`max_rows` - /// is a geometry the protocol cannot carry, and the decoder on the far end - /// answers one with `BadValue` — which `apply` turns into `close(.protocol)` - /// with no `refuse` behind it, so the frontend was told only that the - /// session "hung up on the connect". A 4K display at a small font is - /// already past `max_rows`, which made an ordinary big screen unable to - /// attach at all. Asking for the largest grid the wire carries is what this - /// file's GEOMETRY note already promises a frontend gets: the session is - /// drawn at ITS size wherever the window is bigger, exactly as it is when - /// another frontend is the smaller one. - /// - /// A ZERO is dropped rather than clamped, and that asymmetry is the whole - /// point of `getCols` refusing zero in the first place: the session grid is - /// the smallest common one, so a frontend that reported 1 would collapse - /// every other frontend to a single cell. `TIOCGWINSZ` answers 0x0 while a - /// terminal is being torn down and tty.zig forwards a `winsize` verbatim - /// (its ATTACH path already refuses a zero one, its resize path did not), - /// so this is reachable without a hostile peer — and it reached the session - /// as the same mute `close(.protocol)` the oversize geometry did. Keeping - /// the last real window is what a momentary zero means. - pub fn resize(c: *Client, cols: u16, rows: u16) (Error || wire.Error)!void { - if (cols == 0 or rows == 0) return; - return c.send(.{ .event = .{ .resize = .{ - .cols = @min(cols, wire.max_cols), - .rows = @min(rows, wire.max_rows), - } } }); - } - - /// Wait up to `timeout_ms` for the session to say something, and push - /// whatever we still owe it. Zero blocks. This is the frontend's one - /// sleeping place FOR THE SOCKET; the terminal it draws on is polled by - /// whoever owns that, which is why this takes a timeout rather than a second - /// descriptor. - pub fn wait(c: *Client, timeout_ms: u32) (Error || wire.Error)!void { - if (c.fd < 0) return error.Closed; - try c.flush(); - var fds: [1]libc.pollfd = .{.{ - .fd = c.fd, - .events = if (c.out.items.len != 0) poll_in | poll_out else poll_in, - .revents = 0, - }}; - const timeout: c_int = if (timeout_ms == 0) -1 else @intCast(@min(timeout_ms, std.math.maxInt(c_int))); - if (libc.poll(&fds, 1, timeout) <= 0) return; // a timeout, or EINTR - if (fds[0].revents & poll_out != 0) try c.flush(); - // POLLIN wins over POLLHUP: a session that wrote a `quit` and then - // closed has bytes worth reading. - if (fds[0].revents & poll_in != 0) return c.fill(); - if (fds[0].revents & (poll_hup | poll_err | poll_nval) != 0) return error.Closed; - } - - /// The next complete message, or null when the buffer holds only part of - /// one. `welcome` and `frame` have already been applied to this client's - /// own state; every slice in the result borrows the receive buffer until the - /// next call here or to `wait`. - pub fn next(c: *Client) (Error || wire.Error)!?wire.ServerMsg { - // Retire the message returned last, now that its borrow window is over. - if (c.held != 0) { - if (c.held == c.in.items.len) { - c.in.clearRetainingCapacity(); - } else { - std.mem.copyForwards(u8, c.in.items, c.in.items[c.held..]); - c.in.items.len -= c.held; - } - c.held = 0; - } - const found = (try wire.framed(c.in.items)) orelse return null; - const msg = try wire.decodeServer(found.tag, found.payload); - c.held = found.total; - switch (msg) { - .welcome => |v| { - // Both sides check the version. This side checks it too because - // a session speaking something else may not have recognised our - // hello as one either, and a frontend must not paint a frame it - // decoded by a layout the other end does not use. - if (v.version != wire.version) return error.Ungreeted; - c.slot = v.slot; - try c.reshape(v.cols, v.rows); - }, - .refuse => |why| c.refusal = why, - .frame => |f| { - // A frame before the greeting would be the session drawing for a - // connection it never accepted. - if (!c.attached()) return error.Ungreeted; - // A geometry change and a late attach are the same case on this - // side too: reshape, and require the FULL frame the session - // promises for it. Applying a diff to a grid we just cleared - // would leave every untouched cell blank. - if (f.cols != c.cols or f.rows != c.rows) { - if (f.kind != .full) return error.BadValue; - try c.reshape(f.cols, f.rows); - } - try f.apply(c.grid.items); - 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)), - }; - c.cursor = f.cursor; - c.pointer_shape = f.pointer_shape; - }, - // The session has ended. Left for the caller to act on, and the - // descriptor stays open so `deinit` is the only place that closes. - .quit => {}, - // THIS frontend is done and the session is not. Same shape as - // `quit` and the same non-answer here — the caller leaves its loop - // — but the opposite meaning about what survives, so a frontend - // must not collapse the two: `quit` is the session ending and - // `detach` is success. Guarded, because a peer that has not greeted - // us has no standing to dismiss us either. - .detach => if (!c.attached()) return error.Ungreeted, - // The three display effects need this process's clipboard and this - // process's browser, so they are the caller's to perform and there - // is nothing for a `Client` to update. Listed rather than swept up - // by an `else`: an `else` here would silently accept a - // machine-local effect returning to the wire, and the point of the - // rewrite is that it cannot. - // - // Guarded like `.frame`, and for a stronger reason than drawing: - // these reach the human's clipboard and the human's browser. The - // protocol version is checked in the `.welcome` arm above and - // nowhere else, so a peer that simply never greets us has had its - // version checked by nobody — and until it does, it does not get to - // 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 { - c.grid.resize(c.gpa, @as(usize, cols) * @as(usize, rows)) catch return error.Closed; - // Unpainted, which a frontend draws as the terminal's own default cell. - // The full frame that follows paints over it. - @memset(c.grid.items, .{}); - c.cols = cols; - c.rows = rows; - c.cursor = null; - c.pointer_shape = .arrow; - } - - /// Take everything the kernel is holding, not one chunk of it. The server - /// deliberately reads its clients ONE chunk per round, because it is - /// dividing a loop between thirty-two of them; a frontend has exactly one - /// peer, and reading one 16 KiB slice per poll would leave it a full frame - /// behind on every large one — and the session drops a frontend whose queue - /// it cannot drain (server.zig `out_backlog`). - fn fill(c: *Client) (Error || wire.Error)!void { - var buf: [read_chunk]u8 = undefined; - while (true) { - const got = libc.read(c.fd, &buf, buf.len); - if (got == 0) return error.Closed; - if (got < 0) return switch (libc.errno(got)) { - .INTR => continue, - // Nothing more is ready; what we have is what there was. - .AGAIN => {}, - else => error.Closed, - }; - c.in.appendSlice(c.gpa, buf[0..@intCast(got)]) catch return error.Closed; - } - } - - fn flush(c: *Client) Error!void { - if (c.fd < 0) return error.Closed; - var off: usize = 0; - while (off < c.out.items.len) { - const n = libc.send(c.fd, c.out.items.ptr + off, c.out.items.len - off, nosignal); - if (n < 0) switch (libc.errno(n)) { - .INTR => continue, - // The session is not draining us. The rest waits for POLLOUT; - // the queue is bounded in practice because a frontend's output - // is keystrokes and pty chunks, never frames. - .AGAIN => break, - else => return error.Closed, - }; - if (n == 0) break; - off += @intCast(n); - } - if (off == 0) return; - if (off == c.out.items.len) return c.out.clearRetainingCapacity(); - std.mem.copyForwards(u8, c.out.items, c.out.items[off..]); - c.out.items.len -= off; - } -}; - -// The socket primitives are server.zig's, which is the file that owns this -// transport's conventions and both ends of it — see its `setNonblock`, -// `nosignal` and `poll_*`. There was a third copy of all of them here. -const nosignal = server.nosignal; -const poll_in = server.poll_in; -const poll_out = server.poll_out; -const poll_hup = server.poll_hup; -const poll_err = server.poll_err; -const poll_nval = server.poll_nval; - -/// Which session an attach meant, answered before a frontend opens its window. -/// -/// `--attach=` is taken at its word beyond one `access` on the socket -/// file, because the connect is the real authority on whether anything is -/// listening — and a typo is the one failure worth catching earlier, since the -/// alternative is a full-screen flash on the way to a one-line message. Bare -/// `--attach`, and the bare `Attach` word, is THE session: bare `--detach` -/// names itself by its own pid, and nobody can be expected to read a pid out -/// of `$XDG_RUNTIME_DIR`. With exactly one listening, that is the one meant; -/// with none or several this says WHICH case it is instead of picking one. -/// -/// Both the directory and the filename convention come off ONE probe through -/// `server.sessionPath` rather than being re-derived here, for the reason that -/// function exists at all: the side that binds and the side that looks must -/// never be able to disagree about where a session lives. -/// -/// It lives in this file, rather than in either shell, because BOTH frontends -/// now ask the same question — a terminal for `--attach` and the SDL window -/// for the `Attach` word — and a second copy of a directory scan is exactly -/// how the two of them would start disagreeing. -pub const Resolved = union(enum) { - /// The session to open. Borrows `requested` when it was named, and `buf` - /// when it had to be scanned for. - name: []const u8, - /// No socket of that name, or no session at all. The caller knows which it - /// asked for, so it owns the wording. - none, - /// Several are listening, and choosing between them is not ours to do. - ambiguous: usize, -}; - -pub fn resolve(buf: *[server.path_max]u8, requested: []const u8) Resolved { - if (requested.len != 0) { - var one_buf: [server.path_max]u8 = undefined; - const one = server.sessionPath(&one_buf, requested) orelse return .none; - const F_OK: c_int = 0; - if (libc.access(one, F_OK) != 0) return .none; - return .{ .name = requested }; - } - const probe_name = "0"; - var probe_buf: [server.path_max]u8 = undefined; - const probe = server.sessionPath(&probe_buf, probe_name) orelse return .none; - const base = std.fs.path.basename(probe); - const cut = std.mem.lastIndexOf(u8, base, probe_name).?; - const prefix = base[0..cut]; - const suffix = base[cut + probe_name.len ..]; - var dir_buf: [server.path_max:0]u8 = undefined; - const dir = std.fs.path.dirname(probe) orelse ""; - if (dir.len == 0 or dir.len >= dir_buf.len) return .none; - @memcpy(dir_buf[0..dir.len], dir); - dir_buf[dir.len] = 0; - const d = libc.opendir(dir_buf[0..dir.len :0]) orelse return .none; - defer _ = libc.closedir(d); - var found: usize = 0; - var len: usize = 0; - while (libc.readdir(d)) |ent| { - const entry = std.mem.sliceTo(&ent.name, 0); - if (entry.len <= prefix.len + suffix.len) continue; - if (!std.mem.startsWith(u8, entry, prefix) or !std.mem.endsWith(u8, entry, suffix)) continue; - const name = entry[prefix.len .. entry.len - suffix.len]; - if (name.len > buf.len) continue; - found += 1; - @memcpy(buf[0..name.len], name); - len = name.len; - } - // A socket file whose session is gone still counts here: the sweep that - // unlinks corpses runs when the NEXT session binds (server.zig `sweep`), - // and probing every candidate with a connect would put a phantom frontend - // into a live session's slot table just to count it. One stale file - // therefore fails at `open` with "no such session", which is the truth. - if (found != 1) return if (found == 0) .none else .{ .ambiguous = found }; - return .{ .name = buf[0..len] }; -} - -// Input arrives through frontend queues, so attached clients bound socket waits to half a frame. -pub const poll_ms: u32 = 8; - -/// One round of waiting for the greeting, and how many of them. The COUNT is -/// derived from `server.greet_deadline_default_ms` rather than written down -/// again, so the two ends of the handshake give each other the same grace out -/// of one number instead of two that can drift apart. -/// -/// Rounds rather than a clock, and that is sound rather than lazy: the only -/// message a session may legally send before its `welcome` is a `refuse`. -/// Everything else is refused by `next` as `Ungreeted` — a frame because it -/// would be drawing for a connection that was never accepted, and the three -/// display effects because a peer whose version nobody has checked does not get -/// to open a URI or read a clipboard. So a peer that is silent costs one whole -/// timeout per round, which makes the round count a real wall-clock bound; and -/// a peer that is NOISY but ungreeted fails on its first message rather than -/// spending the budget. -const greet_round_ms: u32 = 250; -const greet_rounds: u32 = server.greet_deadline_default_ms / greet_round_ms; - -/// What came of trying to attach. A VALUE and not an error union, because four -/// of the six outcomes are ordinary answers a human needs different words for, -/// and because the two frontends report them by different mechanisms — a -/// terminal prints a sentence and exits, a window logs and unwinds. `resolve` -/// above returns a union for the same reason. -pub const Attempt = union(enum) { - /// Resolved, connected, AND greeted. The caller owns it. - greeted: Client, - /// No socket of that name, or nothing detached at all. The caller knows - /// which it asked for, so the wording is the caller's. - no_session, - /// Several are listening and choosing is not ours to do. - ambiguous: usize, - /// The session said no, and said why. - refused: wire.Refusal, - /// It accepted and then never greeted us inside the deadline. - silent, - /// Everything else, already reported by the errno it came from. - lost: anyerror, -}; - -/// Wait for welcome before the caller replaces its session; connect alone can -/// still lead to a version refusal. Every non-greeted result owns no resources. -pub fn attempt(gpa: std.mem.Allocator, requested: []const u8, cols: u16, rows: u16) Attempt { - var buf: [server.path_max]u8 = undefined; - const name = switch (resolve(&buf, requested)) { - .name => |n| n, - .none => return .no_session, - .ambiguous => |n| return .{ .ambiguous = n }, - }; - var c = Client.open(gpa, name, cols, rows) catch |err| return switch (err) { - // `open`'s own two ways of saying "there is nothing there" collapse - // into the one the caller has wording for. - error.NoSession, error.NoSessionPath => .no_session, - else => .{ .lost = err }, - }; - var rounds: u32 = 0; - while (rounds < greet_rounds) : (rounds += 1) { - c.wait(greet_round_ms) catch |err| return give(&c, err); - // Drain whatever landed. `next` is what applies the welcome, so the - // loop below is not discarding anything it needs — the state it wants - // is in `c` afterwards. - while (true) { - const msg = c.next() catch |err| return give(&c, err); - if (msg == null) break; - } - if (c.attached()) return .{ .greeted = c }; - if (c.refusal) |why| { - c.deinit(); - return .{ .refused = why }; - } - } - c.deinit(); - return .silent; -} - -/// Close, and say what the failure actually was. A session that refuses us -/// writes its reason and closes in the same pass (server.zig `refuseFd`), so a -/// read error here is usually the far side hanging up on a refusal we have -/// already decoded — reporting that as a lost connection would throw away the -/// one sentence worth telling the human. -fn give(c: *Client, err: anyerror) Attempt { - const why = c.refusal; - c.deinit(); - if (why) |w| return .{ .refused = w }; - return .{ .lost = err }; -} - -// --------------------------------------------------------------------------- -// tests -// --------------------------------------------------------------------------- -// -// One real core, one real unix socket, real frontends. The harness runs the -// server's vtable in the order `Pardes.pump` runs it, so what these exercise is -// the transport as the core actually drives it rather than a mock of it. - -const testing = std.testing; - -extern "c" fn setenv(name: [*:0]const u8, value: [*:0]const u8, overwrite: c_int) c_int; -extern "c" fn unsetenv(name: [*:0]const u8) c_int; - -/// A session on a socket of its own under `.zig-cache/tmp`, so a test never -/// collides with a real session in `$XDG_RUNTIME_DIR` and never depends on that -/// variable being set at all. It is process-wide, so it is saved and restored. -const Harness = struct { - tmp: std.testing.TmpDir, - saved: ?[:0]const u8, - saved_buf: [4096:0]u8 = undefined, - core: *pardes.Pardes, - session: server.Session, - arena: std.heap.ArenaAllocator, - name_buf: [32]u8 = undefined, - name: []const u8 = &.{}, - - fn init(h: *Harness, cols: u16, rows: u16) !void { - h.tmp = std.testing.tmpDir(.{}); - errdefer h.tmp.cleanup(); - h.saved = if (libc.getenv("XDG_RUNTIME_DIR")) |v| - try std.fmt.bufPrintSentinel(&h.saved_buf, "{s}", .{std.mem.span(v)}, 0) - else - null; - errdefer h.restoreEnv(); - var dir_buf: [4096:0]u8 = undefined; - const dir = try std.fmt.bufPrintSentinel(&dir_buf, ".zig-cache/tmp/{s}", .{h.tmp.sub_path}, 0); - // `ensureSocketDir` refuses anything with a bit granted to group or - // other, which is the whole point of it; a tmpDir arrives 0755. - try testing.expectEqual(@as(c_int, 0), libc.chmod(dir, 0o700)); - _ = setenv("XDG_RUNTIME_DIR", dir.ptr, 1); - h.core = try pardes.Pardes.init(testing.allocator, .{ .tty_only = true, .cols = cols, .rows = rows }); - errdefer h.core.deinit(); - h.arena = .init(testing.allocator); - errdefer h.arena.deinit(); - // `io` is not optional on `Session`: the daemon does the file watching - // and the theme scan itself now, and both of those take a `std.Io`. - h.session = .{ - .gpa = testing.allocator, - .worker_gpa = testing.allocator, - .io = std.testing.io, - .core = h.core, - .cols = cols, - .rows = rows, - }; - try h.session.initAsync(); - errdefer h.session.deinit(); - h.name = "s"; - try testing.expect(h.session.listen(h.name)); - // The pre-loop drain tty.zig has, for its reason: the startup spawns are - // already queued and a session must not open its socket with panes that - // have not been created. These now fork IN THIS PROCESS, because the - // daemon is the thing that owns pane shells — which is exactly the - // property under test, and the reason no frontend below is ever asked - // to fork anything. - h.core.host = h.session.host(); - while (h.core.nextEffect()) |e| h.core.perform(e); - } - - fn restoreEnv(h: *Harness) void { - if (h.saved) |v| { - _ = setenv("XDG_RUNTIME_DIR", v.ptr, 1); - } else _ = unsetenv("XDG_RUNTIME_DIR"); - } - - fn deinit(h: *Harness) void { - h.session.deinit(); - h.core.deinit(); - h.arena.deinit(); - h.restoreEnv(); - h.tmp.cleanup(); - } - - /// `Pardes.pump`, with the one substitution a single-threaded test needs: a - /// bounded wait, so a frontend that says nothing cannot hang the suite - /// where the real session would sleep until it spoke. The queued-input - /// drain `pump` does between the two is absent because this host has no - /// queue: it calls `update` directly (borrowed bytes), and `postEvent` is - /// for hosts whose worker threads post from off the loop. - fn pump(h: *Harness) !void { - const host = h.session.host(); - host.vtable.wait_input.?(host.ctx, 20); - while (h.core.nextEffect()) |e| h.core.perform(e); - if (h.core.quit) return; - _ = h.arena.reset(.retain_capacity); - const surface = try h.core.render(h.arena.allocator()); - host.vtable.present.?(host.ctx, surface); - } - - /// The round budget every `pumpUntil*` below shares. A round moves at most - /// one socket buffer, because nothing here is concurrent: the session - /// flushes until `EAGAIN`, and only then does the client read. That buffer - /// is 8 KiB on darwin (`net.local.stream.sendspace`) against linux's 208 - /// KiB, which is the same asymmetry the slow-frontend test at the bottom of - /// this file already had to say out loud — and a full frame of the largest - /// grid the protocol carries is near a megabyte, so 64 rounds is a linux- - /// only number. High enough for that frame on the smaller buffer, and still - /// a bound: a broken transport fails a test rather than hanging the suite. - const rounds = 256; - - /// Pump until this client has the message we are waiting for. - fn pumpUntil(h: *Harness, c: *Client, comptime want: std.meta.Tag(wire.ServerMsg)) !wire.ServerMsg { - for (0..rounds) |_| { - try h.pump(); - try c.wait(5); - while (try c.next()) |msg| if (std.meta.activeTag(msg) == want) return msg; - } - return error.NeverArrived; - } - - /// Pump until this client is sent a frame that CHANGES something. The first - /// frame after an input is not always the one carrying it — an effect the - /// input queued (a `Look` on a directory emits a spawn) lands a frame - /// later, and the frame in between legitimately says nothing. - fn pumpUntilChange(h: *Harness, c: *Client) !wire.Frame { - for (0..rounds) |_| { - const msg = try h.pumpUntil(c, .frame); - if (msg.frame.nruns > 0) return msg.frame; - } - return error.NothingChanged; - } - - /// Pump until this client's grid is this shape, draining everything that - /// arrives. A test waits for the STATE rather than for the n-th message - /// because a resize is announced when the session settles it, which may be - /// one empty frame after the pump that caused it. - fn pumpUntilGrid(h: *Harness, c: *Client, cols: u16, rows: u16) !void { - for (0..rounds) |_| { - try h.pump(); - try c.wait(5); - while (try c.next()) |_| {} - if (c.cols == cols and c.rows == rows) return; - } - return error.NeverResized; - } - - /// Pump until two frontends are showing the same screen, draining both on - /// every pass. One pump sends every attached frontend a frame, so a test - /// that drains only one of them is comparing two different instants — and - /// what a shared session promises is that they CONVERGE, which is what this - /// waits for. - fn pumpUntilSameScreen(h: *Harness, a: *Client, b: *Client) !void { - for (0..rounds) |_| { - try h.pump(); - try a.wait(5); - try b.wait(5); - while (try a.next()) |_| {} - while (try b.next()) |_| {} - if (sameScreen(a.grid.items, b.grid.items)) return; - } - return error.NeverConverged; - } - - /// Pump until THIS frontend is showing the core's own screen, draining - /// everything that arrives on every pass. `pumpUntilSameScreen`'s reason, - /// with one frontend instead of two, and a second reason of its own: - /// `pumpUntil` returns the instant it decodes the message it was waiting - /// for and leaves the rest of that burst in the socket, so a client can sit - /// one whole frame behind for the rest of a test. Comparing once against - /// that grid compares the core's NOW with the frontend's THEN — which is - /// nothing at all until the pane shell's prompt lands in the frame nobody - /// read, and then it is a cell that differs. - /// - /// Checked BEFORE the first pump, so a test already in sync spends nothing - /// and no extra frame is manufactured to make one appear. Out of rounds it - /// hands the last comparison to `expectSameScreen`, which names the cell: - /// a transport that really does drop one must fail as a wrong screen, not - /// as a timeout. - fn pumpUntilShowsCore(h: *Harness, c: *Client) !void { - for (0..rounds) |_| { - _ = h.arena.reset(.retain_capacity); - if (sameScreen((try h.core.render(h.arena.allocator())).cells, c.grid.items)) return; - try h.pump(); - try c.wait(5); - while (try c.next()) |_| {} - } - _ = h.arena.reset(.retain_capacity); - return expectSameScreen((try h.core.render(h.arena.allocator())).cells, c.grid.items); - } - - /// Attach a frontend and get it greeted: `open` writes the hello into the - /// listener's backlog, one pump accepts and answers it. Nothing blocks, - /// which is the whole reason the handshake is not a blocking call. - fn attach(h: *Harness, cols: u16, rows: u16) !Client { - var c = try Client.open(testing.allocator, h.name, cols, rows); - errdefer c.deinit(); - _ = try h.pumpUntil(&c, .welcome); - return c; - } -}; - -test "detached session: a frontend attaches, is greeted, and is sent the screen" { - var h: Harness = undefined; - try h.init(60, 16); - defer h.deinit(); - - var c = try h.attach(60, 16); - defer c.deinit(); - try testing.expectEqual(@as(u8, 0), c.slot); - try testing.expectEqual(@as(u16, 60), c.cols); - try testing.expectEqual(@as(u16, 16), c.rows); - - const frame = (try h.pumpUntil(&c, .frame)).frame; - // The first frame a frontend gets must be full: it has nothing to diff - // against. - try testing.expectEqual(wire.FrameKind.full, frame.kind); - try testing.expectEqual(@as(usize, 60 * 16), c.grid.items.len); - // ...and it must be the core's own frame, cell for cell. This is the whole - // claim of the transport — asserted once the frontend has read everything - // the session sent, which `pumpUntil` above deliberately did not do. - try h.pumpUntilShowsCore(&c); -} - -test "detached session: input from a frontend reaches the core and comes back as a diff" { - var h: Harness = undefined; - try h.init(60, 16); - defer h.deinit(); - var c = try h.attach(60, 16); - defer c.deinit(); - _ = try h.pumpUntil(&c, .frame); - - // A builtin line is the cheapest input with a guaranteed visible effect, - // and it travels the same `Event` path a keystroke does. - try c.send(.{ .event = .{ .command = "Look /" } }); - const frame = try h.pumpUntilChange(&c); - // The change arrived as a DIFF: this frontend was already in sync, so - // nothing it already had was re-sent. - try testing.expectEqual(wire.FrameKind.diff, frame.kind); - try h.pumpUntilShowsCore(&c); -} - -test "detached Restore keeps attached frontends and follows queued frames with a full replacement" { - var h: Harness = undefined; - try h.init(60, 16); - defer h.deinit(); - _ = try h.core.setTestFile("saved body\n"); - var c = try h.attach(60, 16); - defer c.deinit(); - _ = try h.pumpUntil(&c, .frame); - try h.pumpUntilShowsCore(&c); - - const before = h.core; - 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 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, "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.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; - } else return error.NoFullReplacement; - try h.pumpUntilShowsCore(&c); -} - -test "detached selection pipe runs off the loop and returns through the attached frontend" { - var h: Harness = undefined; - try h.init(60, 16); - defer h.deinit(); - const pane = try h.core.setTestFile("one\ntwo\n"); - 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); - - try client.send(.{ .event = .{ .key = .{ .cp = '|' } } }); - try client.send(.{ .event = .{ .key = .{ .cp = 't', .text = "tr a-z A-Z" } } }); - try client.send(.{ .event = .{ .key = .{ .cp = pardes.Key.enter } } }); - for (0..Harness.rounds) |_| { - try h.pump(); - try client.wait(5); - 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.expectEqual(@as(usize, 0), h.session.pipe_tasks.len); - try h.pumpUntilShowsCore(&client); -} - -test "detached session: two frontends share one screen at the smallest common grid" { - var h: Harness = undefined; - try h.init(80, 24); - defer h.deinit(); - var a = try h.attach(80, 24); - defer a.deinit(); - _ = try h.pumpUntil(&a, .frame); - - // A second, smaller frontend. tmux's rule: the session shrinks to what both - // can show, because two people looking at different screens is the point of - // a shared session lost. - var b = try h.attach(50, 12); - defer b.deinit(); - try testing.expectEqual(@as(u8, 1), b.slot); - try testing.expectEqual(@as(u16, 50), b.cols); - try testing.expectEqual(@as(u16, 12), b.rows); - - // Both are now on the 50x12 grid — and getting there IS the proof that the - // reshape was sent as a FULL frame: `next` refuses a diff whose geometry - // does not match the grid it holds, so a client whose shape moved can only - // have been reshaped by a full one. - try h.pumpUntilGrid(&a, 50, 12); - try h.pumpUntilGrid(&b, 50, 12); - try testing.expectEqual(@as(usize, 50 * 12), a.grid.items.len); - // CONVERGENCE, not a snapshot. `pumpUntilGrid(&b, ...)` pumped the session - // while draining only `b`, and the daemon owns the pane shells now: a - // prompt arriving on a pty moves the screen between pumps, so `a` can be - // holding an undrained frame and comparing the two grids here would compare - // two instants. What a shared session promises is that they agree, which is - // what this waits for. - try h.pumpUntilSameScreen(&a, &b); - - // ...and input from EITHER moves that one screen. Both are drained on every - // pump before they are compared: one pump sends every attached frontend a - // frame, so a test that drains only one is comparing two instants. - try b.send(.{ .event = .{ .command = "Look /" } }); - _ = try h.pumpUntilChange(&a); - try h.pumpUntilSameScreen(&a, &b); -} - -test "detached session: a window past the protocol attaches at the largest grid it carries" { - var h: Harness = undefined; - try h.init(80, 24); - defer h.deinit(); - - // A 4K display at a small font is already past `max_rows`, and until the - // clamp in `open` that hello was a geometry the session's decoder refused: - // `apply` answered `BadValue` with `close(.protocol)` and no `refuse` - // behind it, so a frontend on a big screen was told the session "hung up on - // the connect" — at a session with every slot free. It attaches now, at the - // biggest grid the wire has. - var c = try h.attach(wire.max_cols + 400, wire.max_rows + 70); - defer c.deinit(); - try testing.expectEqual(wire.max_cols, c.cols); - try testing.expectEqual(wire.max_rows, c.rows); - - // ...and the full frame that follows is the 65536-cell one whose single run - // does not fit a u16 count (wire.zig `run_max`), which is the half of this - // the clamp alone would have made universal rather than fixed. - const frame = (try h.pumpUntil(&c, .frame)).frame; - try testing.expectEqual(wire.FrameKind.full, frame.kind); - try testing.expectEqual(@as(usize, @as(usize, wire.max_cols) * wire.max_rows), c.grid.items.len); - // TWO runs and not one, which is the assertion that fails first if the - // encoder's bound goes: this grid's full frame is 65536 painted cells and - // a run counts to 65535. - try testing.expectEqual(@as(u32, 2), frame.nruns); - try h.pumpUntilShowsCore(&c); -} - -test "detached session: a frontend that dies takes nothing with it" { - var h: Harness = undefined; - try h.init(60, 16); - defer h.deinit(); - var a = try h.attach(60, 16); - defer a.deinit(); - var b = try h.attach(60, 16); - _ = try h.pumpUntil(&a, .frame); - _ = try h.pumpUntil(&b, .frame); - try testing.expect(h.session.clients[0].attached); - try testing.expect(h.session.clients[1].attached); - - // Not a `bye`: the socket goes away under the session's feet, which is what - // a frontend crashing or being killed looks like from here. - b.deinit(); - _ = try h.pumpUntil(&a, .frame); - try testing.expect(!h.session.clients[1].attached); - try testing.expectEqual(@as(c_int, -1), h.session.clients[1].fd); - // The survivor is still served and the core is still running. - try testing.expect(h.session.clients[0].attached); - try testing.expect(!h.core.quit); - try a.send(.{ .event = .{ .command = "Look /" } }); - try testing.expect((try h.pumpUntilChange(&a)).nruns > 0); - - // The freed slot takes the next frontend, and the screen comes with it. - var d = try h.attach(60, 16); - defer d.deinit(); - try testing.expectEqual(@as(u8, 1), d.slot); - try testing.expectEqual(wire.FrameKind.full, (try h.pumpUntil(&d, .frame)).frame.kind); - // ...and it is the SAME screen the survivor is looking at. Waited for - // rather than snapshotted, for the reason above: `pumpUntil(&d, ...)` - // drained only `d`, and pane output means the screen does not stand still - // between pumps. - try h.pumpUntilSameScreen(&a, &d); -} - -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(); - - // A raw socket rather than a `Client`, because the whole point is a peer - // that does not agree with `wire.version` — and `open` would already have - // sent a perfectly good hello. - const fd = try rawConnect(&h); - defer _ = libc.close(fd); - var buf: [64]u8 = undefined; - const hello = try wire.encodeClient(&buf, .{ - .hello = .{ .version = claimed, .cols = 60, .rows = 16 }, - }); - try testing.expectEqual(@as(isize, @intCast(hello.len)), libc.send(fd, hello.ptr, hello.len, nosignal)); - - // Two pumps: one to accept the connection, one to read the hello and - // answer it. - try h.pump(); - try h.pump(); - var got: [64]u8 = undefined; - const n = libc.read(fd, &got, got.len); - try testing.expect(n > 0); - const f = (try wire.framed(got[0..@intCast(n)])).?; - try testing.expectEqual(wire.Refusal.version, (try wire.decodeServer(f.tag, f.payload)).refuse); - // Refused means refused: the slot went back and no frame was ever sent. - for (&h.session.clients) |*slot| try testing.expect(!slot.attached); - 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); - defer h.deinit(); - var c = try h.attach(60, 16); - defer c.deinit(); - _ = try h.pumpUntil(&c, .frame); - - // A well-formed frame around a tag this protocol has never defined. The - // session must close the connection rather than guess at it. - const junk = [_]u8{ 0xfe, 0x00, 0x00, 0x00, 0x00 }; - try testing.expectEqual(@as(isize, junk.len), libc.send(c.fd, &junk, junk.len, nosignal)); - for (0..8) |_| { - try h.pump(); - if (!h.session.clients[0].attached) break; - } - try testing.expect(!h.session.clients[0].attached); - // The session is untouched: a hostile frontend costs a slot, not a session. - try testing.expect(!h.core.quit); -} - -test "detached session: the session outlives every frontend and keeps its grid" { - var h: Harness = undefined; - try h.init(72, 20); - defer h.deinit(); - { - var c = try h.attach(40, 10); - defer c.detach(); - _ = try h.pumpUntil(&c, .frame); - try testing.expectEqual(@as(u16, 40), h.session.cols); - } - // Nobody attached. The grid stays where the last frontend left it rather - // than collapsing: a detached session is one nobody is looking at, not one - // of no size. - try h.pump(); - try testing.expectEqual(@as(u16, 40), h.session.cols); - try testing.expectEqual(@as(u16, 10), h.session.rows); - try testing.expect(!h.core.quit); - // ...and the next frontend takes the grid over: with one attachment the - // smallest common grid IS that frontend's, so the session follows it up to - // 90x30 rather than pinning the departed one's 40x10 forever. - var again = try h.attach(90, 30); - defer again.deinit(); - try testing.expectEqual(@as(u16, 90), again.cols); - try testing.expectEqual(@as(u16, 30), again.rows); - try h.pumpUntilGrid(&again, 90, 30); - try testing.expectEqual(@as(usize, 90 * 30), again.grid.items.len); -} - -test "detached session: the seam's own routing rules, per surviving effect" { - var h: Harness = undefined; - try h.init(60, 16); - defer h.deinit(); - var a = try h.attach(60, 16); - defer a.deinit(); - var b = try h.attach(60, 16); - defer b.deinit(); - _ = try h.pumpUntil(&a, .frame); - _ = try h.pumpUntil(&b, .frame); - - const host = h.session.host(); - // BROADCAST: the yank register is a fact about the session, so every - // display it is being watched on gets it. - host.vtable.set_clipboard.?(host.ctx, "yank"); - try expectBoth(&h, &a, &b, .set_clipboard); - - // Ask one frontend: two clipboard answers would paste twice. - h.session.origin = 1; - host.vtable.read_clipboard.?(host.ctx); - try expectOnly(&h, &b, &a, .read_clipboard); - // `open_link` follows the same origin: the browser that opens is the one on - // the display of the human who clicked, not the oldest attachment's. - host.vtable.open_link.?(host.ctx, "https://x"); - try expectOnly(&h, &b, &a, .open_link); - // ...and with no origin it falls back to the primary, which is what a link - // opened by something other than a keystroke gets. - h.session.origin = 0; - host.vtable.open_link.?(host.ctx, "https://y"); - try expectOnly(&h, &a, &b, .open_link); -} - -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 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. - // - // Adding a name here is meant to be an ARGUMENT, not a formality. The bar is - // the one `quit` and `detach` clear and `spawn` cannot: it needs this - // human's screen, keyboard, clipboard or browser, or it is the session - // telling this frontend about its own membership. Anything that touches a - // disk or a process table fails that bar by construction. - const allowed = [_][]const u8{ - // Session control: who this connection is, and whether it is still one. - // `detach` is this frontend leaving and `quit` is the session ending — - // opposite meanings, same shape, and neither is an effect. - "welcome", "refuse", "frame", "quit", "detach", - // 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".field_names; - inline for (fields) |name| { - for (allowed) |ok| { - if (std.mem.eql(u8, name, ok)) break; - } else { - std.debug.print("ServerMsg.{s} is not an effect a frontend may perform\n", .{name}); - return error.MachineLocalEffectOnTheWire; - } - } - try testing.expectEqual(allowed.len, fields.len); - - // Two: and no TAG BYTE outside them decodes either — the check above is - // about this build's union, this one is about the bytes on the socket. Every - // other byte must be `BadTag`, including the eight that used to be defined: - // a session built before this change cannot talk a frontend into forking. - var accepted: usize = 0; - 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 (`EndOfStream`) or succeeds, but - // never with `BadTag`. - if (wire.decodeServer(tag, &.{})) |_| accepted += 1 else |err| switch (err) { - error.BadTag => continue, - else => accepted += 1, - } - const named = for (allowed) |ok| { - const want = std.meta.stringToEnum(wire.ServerTag, ok).?; - 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 nine\n", .{tag}); - return error.MachineLocalEffectOnTheWire; - } - } - try testing.expectEqual(allowed.len, accepted); -} - -test "detached session: the client table is a refusal, not a queue" { - // A small grid on purpose: these thirty-two peers never read, and a full - // frame of 80x24 each would push them into the backlog rule that the next - // test is about. 20x5 keeps every queue in the kernel's own buffer. - var h: Harness = undefined; - try h.init(20, 5); - defer h.deinit(); - - var fds: [server.max_clients]c_int = @splat(-1); - defer for (fds) |fd| if (fd >= 0) { - _ = libc.close(fd); - }; - var buf: [64]u8 = undefined; - const hello = try wire.encodeClient(&buf, .{ .hello = .{ .cols = 20, .rows = 5 } }); - for (&fds) |*fd| { - fd.* = try rawConnect(&h); - try testing.expectEqual(@as(isize, @intCast(hello.len)), libc.send(fd.*, hello.ptr, hello.len, nosignal)); - } - // The listener's backlog is `max_clients` deep, so this takes a few rounds: - // `accept` drains what is there each time it is woken. - for (0..16) |_| { - try h.pump(); - var attached: usize = 0; - for (&h.session.clients) |*slot| if (slot.attached) { - attached += 1; - }; - if (attached == server.max_clients) break; - } - for (&h.session.clients) |*slot| try testing.expect(slot.attached); - - // The thirty-third is TOLD it does not fit, and told promptly: the - // alternative — leaving it in the backlog — makes a level-triggered poll - // report the listener ready forever and spins the core. - const extra = try rawConnect(&h); - defer _ = libc.close(extra); - try testing.expectEqual(@as(isize, @intCast(hello.len)), libc.send(extra, hello.ptr, hello.len, nosignal)); - var got: [64]u8 = undefined; - const refusal = for (0..8) |_| { - try h.pump(); - const n = libc.read(extra, &got, got.len); - if (n > 0) break got[0..@intCast(n)]; - } else return error.NeverRefused; - const f = (try wire.framed(refusal)).?; - try testing.expectEqual(wire.Refusal.full, (try wire.decodeServer(f.tag, f.payload)).refuse); - // ...and the thirty-two it does serve are untouched. - for (&h.session.clients) |*slot| try testing.expect(slot.attached); - try testing.expect(!h.core.quit); -} - -test "detached session: a frontend that stops reading is dropped, not waited for" { - var h: Harness = undefined; - try h.init(40, 10); - defer h.deinit(); - var good = try h.attach(40, 10); - defer good.deinit(); - - // A peer that says hello and then never reads a byte again — a frontend - // stopped in a debugger, or one whose terminal is blocked. - const mute = try rawConnect(&h); - defer _ = libc.close(mute); - var buf: [64]u8 = undefined; - const hello = try wire.encodeClient(&buf, .{ .hello = .{ .cols = 40, .rows = 10 } }); - try testing.expectEqual(@as(isize, @intCast(hello.len)), libc.send(mute, hello.ptr, hello.len, nosignal)); - for (0..8) |_| { - try h.pump(); - if (h.session.clients[1].attached) break; - } - try testing.expect(h.session.clients[1].attached); - - // Clipboard updates broadcast to every frontend. - const text = try testing.allocator.alloc(u8, 256 * 1024); - defer testing.allocator.free(text); - @memset(text, 'y'); - const host = h.session.host(); - for (0..24) |_| { - if (!h.session.clients[1].attached) break; - host.vtable.set_clipboard.?(host.ctx, text); - // Read `good` back to EMPTY before the next mirror, rather than - // pumping once and taking whatever one write fitted. One pump moves at - // most one socket buffer, and that buffer is 8 KiB here - // (`net.local.stream.sendspace` on Darwin) against Linux's 208 KiB — - // so a single pump per 256 KiB mirror leaves the READING frontend - // falling behind by a quarter megabyte a round and closes it for a - // backlog it never caused. The claim under test is that a frontend - // that reads survives, so it has to actually finish reading. - for (0..256) |_| { - try h.pump(); - try good.wait(5); - while (try good.next()) |_| {} - if (h.session.clients[0].out.items.len == 0) break; - } - } - // Dropped rather than queued without bound, and rather than the core - // blocking on it. - try testing.expect(!h.session.clients[1].attached); - try testing.expectEqual(@as(c_int, -1), h.session.clients[1].fd); - // The frontend that WAS reading is still attached and still being drawn - // 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 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 -/// deliberately not a `Client`: one that speaks another protocol, thirty-two -/// that fill the table, one that never reads. -fn rawConnect(h: *Harness) !c_int { - var path_buf: [server.path_max]u8 = undefined; - const path = server.sessionPath(&path_buf, h.name).?; - var addr: libc.sockaddr.un = .{ .path = @splat(0) }; - @memcpy(addr.path[0 .. path.len + 1], path[0 .. path.len + 1]); - const fd = libc.socket(libc.AF.UNIX, libc.SOCK.STREAM, 0); - if (fd < 0) return error.NoSocket; - errdefer _ = libc.close(fd); - if (libc.connect(fd, @ptrCast(&addr), @sizeOf(@TypeOf(addr))) != 0) return error.NoSession; - return fd; -} - -/// `want` reached `to` and nothing reached `other`. -fn expectOnly( - h: *Harness, - to: *Client, - other: *Client, - comptime want: std.meta.Tag(wire.ServerMsg), -) !void { - _ = try h.pumpUntil(to, want); - try other.wait(5); - while (try other.next()) |msg| if (std.meta.activeTag(msg) == want) { - std.debug.print("{t} reached a frontend it was not routed to\n", .{want}); - return error.Misrouted; - }; -} - -fn expectBoth( - h: *Harness, - a: *Client, - b: *Client, - comptime want: std.meta.Tag(wire.ServerMsg), -) !void { - _ = try h.pumpUntil(a, want); - _ = try h.pumpUntil(b, want); -} - -/// Are these two grids showing the same thing? `visuallyEqual` and not -/// `std.meta.eql`, because `Cell.text` past `len` is scratch the decoder does -/// not invent — pardes.zig says in as many words that it must never -/// manufacture a difference. -fn sameScreen(want: []const pardes.Cell, have: []const pardes.Cell) bool { - if (want.len != have.len) return false; - for (want, have) |*x, *y| if (!x.visuallyEqual(y)) return false; - return true; -} - -fn expectSameScreen(want: []const pardes.Cell, have: []const pardes.Cell) !void { - try testing.expectEqual(want.len, have.len); - for (want, have, 0..) |*x, *y, i| if (!x.visuallyEqual(y)) { - std.debug.print("cell {d} differs\n", .{i}); - return error.CellMismatch; - }; -} diff --git a/src/detached/server.zig b/src/detached/server.zig deleted file mode 100644 index d7dda6ba..00000000 --- a/src/detached/server.zig +++ /dev/null @@ -1,1478 +0,0 @@ -const filesystem = @import("../fs.zig"); -const std = @import("std"); -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.Messages.Message; - -const TIOCSWINSZ: c_int = @bitCast(@as(u32, if (@hasDecl(posix.T, "IOCSWINSZ")) posix.T.IOCSWINSZ else 0x80087467)); - -const log = std.log.scoped(.detached); - -pub const darwin = ninep_io.darwin; - -const supported = ninep_io.supported; - -const sun_path_len = ninep_io.sun_path_len; - -pub const max_clients = 32; - -const out_backlog = 1 << 20; - -const read_chunk = 16 * 1024; - -const pty_chunk = 64 * 1024; - -const poll_slots = 2 + max_clients + pardes.MAX_PANES + 2 + @as(usize, @intFromBool(ninep_io.quic_enabled)); - -const reload_retries = 4; - -const session_backlog = 2 * @as(usize, wire.max_payload); - -const pty_backlog = 1 << 20; - -pub const greet_deadline_default_ms: u32 = 5_000; - -const idle_retain = read_chunk; - -const accept_pause_ms = 100; - -const Closed = enum { bye, peer, protocol, backlog, silent, write, read, oom, refused, quitting }; - -const Client = struct { - fd: c_int = -1, - attached: bool = false, - greet: bool = false, - cols: u16 = 0, - rows: u16 = 0, - in: std.ArrayListUnmanaged(u8) = .empty, - out: std.ArrayListUnmanaged(u8) = .empty, - 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 { - fd: c_int = -1, - 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 = .{}, -}; - -/// A watched child exited, or a worker finished: wake the loop. -fn wakeForExit(ctx: ?*anyopaque) void { - Session.signal(@ptrCast(@alignCast(ctx.?))); -} - -const RetiredShell = struct { pid: posix.pid_t = 0, kill_at: i64 = 0 }; - -const Source = union(enum) { - listener, - completion, - client: u8, - pty: u8, - inotify, - ninep_quic, -}; - -pub const Session = struct { - gpa: std.mem.Allocator, - 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, - clients: [max_clients]Client = @splat(.{}), - cols: u16, - rows: u16, - origin: ?u8 = null, - scratch: std.ArrayListUnmanaged(u8) = .empty, - ptys: [pardes.MAX_PANES]Pty = @splat(.{}), - retired_shells: [pardes.MAX_PANES]RetiredShell = @splat(.{}), - /// 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, - /// 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, - accept_paused_ms: i64 = 0, - - pub fn initAsync(s: *Session) !void { - var pair: [2]c_int = undefined; - if (libc.socketpair(libc.AF.UNIX, libc.SOCK.STREAM, 0, &pair) != 0) return error.SocketFailed; - errdefer for (pair) |fd| { - _ = libc.close(fd); - }; - for (pair) |fd| { - if (libc.fcntl(fd, libc.F.SETFD, @as(c_int, 1)) < 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.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.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 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 (msg) { - .lsp => |result| { - s.core.update(.{ .lsp_resp = .{ .id = result.id, .rows = result.rows } }); - if (s.inbox.lsp_task) |*task| if (task.id == result.id) { - task.future.await(s.io); - s.inbox.lsp_task = null; - }; - }, - .pipe => |result| { - s.core.update(.{ .pipe_resp = .{ - .id = result.id, - .success = result.success, - .outputs = result.outputs, - .failure = result.failure, - } }); - 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 => {}, - } - } - return batch.len != 0; - } - - 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(replacement); - s.ninep_pending = false; - replacement.host = s.host(); - s.core.deinit(); - s.core = replacement; - for (&s.clients) |*client| if (client.attached) { - client.need_full = true; - }; - s.signal(); - } - - pub fn deinit(s: *Session) void { - // 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(); - if (s.wake[0] >= 0) s.inbox.close(); - for (s.wake) |fd| if (fd >= 0) { - _ = libc.close(fd); - }; - s.wake = .{ -1, -1 }; - if (s.ninep) |l| { - l.deinit(s.gpa); - s.ninep = null; - } - for (&s.clients) |*c| if (c.attached) s.send(c, .quit); - for (&s.clients) |*c| if (c.fd >= 0) s.close(c, .quitting); - s.unlisten(); - s.scratch.deinit(s.gpa); - for (0..s.ptys.len) |pane| s.closePty(@intCast(pane)); - for (s.retired_shells) |shell| if (shell.pid > 0) { - _ = libc.kill(shell.pid, libc.SIG.KILL); - }; - for (s.ptys) |pty| if (pty.pid > 0) { - _ = libc.kill(pty.pid, libc.SIG.KILL); - }; - for (&s.retired_shells) |*shell| if (shell.pid > 0) { - while (libc.waitpid(shell.pid, null, 0) < 0 and libc.errno(-1) == .INTR) {} - shell.* = .{}; - }; - for (&s.ptys) |*pty| if (pty.pid > 0) { - while (libc.waitpid(pty.pid, null, 0) < 0 and libc.errno(-1) == .INTR) {} - pty.pid = 0; - }; - if (s.inotify_fd >= 0) { - _ = libc.close(s.inotify_fd); - s.inotify_fd = -1; - } - s.prompt_rcs.deinit(); - } - - pub fn listen(s: *Session, name: []const u8) bool { - if (comptime !supported) return false; - var dir_buf: [sun_path_len:0]u8 = undefined; - const dir = ninep_io.socketDir(&dir_buf) orelse return false; - if (!ninep_io.ensureSocketDir(dir)) return false; - sweep(dir); - const path = socketPath(&s.path_buf, dir, name) orelse return false; - var addr: libc.sockaddr.un = .{ .path = @splat(0) }; - @memcpy(addr.path[0 .. path.len + 1], path[0 .. path.len + 1]); - const fd = libc.socket(libc.AF.UNIX, libc.SOCK.STREAM, 0); - if (fd < 0) return false; - ninep_io.setCloexec(fd); - if (libc.bind(fd, @ptrCast(&addr), @sizeOf(@TypeOf(addr))) != 0) { - if (alive(path)) { - log.debug("a detached session is already listening on {s}", .{path}); - _ = libc.close(fd); - return false; - } - _ = libc.unlink(path); - if (libc.bind(fd, @ptrCast(&addr), @sizeOf(@TypeOf(addr))) != 0) { - _ = libc.close(fd); - return false; - } - } - _ = libc.chmod(path, 0o600); - if (libc.listen(fd, max_clients) != 0) { - _ = libc.close(fd); - return false; - } - _ = setNonblock(fd); - s.listener = fd; - s.path_len = path.len; - return true; - } - - fn unlisten(s: *Session) void { - if (s.listener < 0) return; - _ = libc.close(s.listener); - s.listener = -1; - var z: [sun_path_len:0]u8 = undefined; - @memcpy(z[0..s.path_len], s.path_buf[0..s.path_len]); - z[s.path_len] = 0; - _ = libc.unlink(z[0..s.path_len :0]); - } - - pub fn host(s: *Session) host_io.Host { - return .{ .ctx = s, .vtable = &vtable }; - } - - fn of(ctx: ?*anyopaque) *Session { - 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, - .watch_theme = watchTheme, - .dump_themes = dumpThemes, - .set_clipboard = setClipboard, - .read_clipboard = readClipboard, - .open_link = openLink, - .detach = detach, - .lsp = lspRequest, - .pipe = pipeRequest, - .search = searchRequest, - }; - - fn searchRequest(ctx: ?*anyopaque, gen: u32) void { - const s = of(ctx); - 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 lspRequest(ctx: ?*anyopaque, request: host_io.Lsp.Request) void { - const s = of(ctx); - _ = s.drainCompletions(true); - s.inbox.startLsp(s.core, request); - } - - fn pipeRequest(ctx: ?*anyopaque, id: u32) void { - const s = of(ctx); - _ = s.drainCompletions(true); - 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 { - for (&s.clients) |*c| if (c.attached) return c; - return null; - } - - fn origins(s: *Session) ?*Client { - if (s.origin) |i| { - const c = &s.clients[i]; - if (c.attached) return c; - } - return s.primary(); - } - - fn slotOf(s: *Session, c: *const Client) u8 { - return @intCast(@divExact(@intFromPtr(c) - @intFromPtr(&s.clients[0]), @sizeOf(Client))); - } - - fn broadcast(s: *Session, msg: wire.ServerMsg) void { - for (&s.clients) |*c| if (c.attached) s.send(c, msg); - } - - 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.harvest(); - // 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); - const child = host_io.forkShell( - s.core, - pane, - &s.prompt_rcs, - s.core.shellBin(), - cwd, - s.core.screen_h, - s.core.screen_w, - s.ninep, - ) 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; - // 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 { - const s = of(ctx); - if (pane >= s.ptys.len) return; - const pt = &s.ptys[pane]; - if (pt.fd < 0) return; - // 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, - "input refused: pane not reading ({d} bytes queued)", - .{pt.out.items.len}, - ) catch "input refused: pane not reading"; - return s.core.setMessage(pane, text); - } - pt.out.appendSlice(s.gpa, bytes) catch { - return s.core.setMessage(pane, "input refused: out of memory"); - }; - s.flushPty(pane); - } - - fn ptyResize(ctx: ?*anyopaque, pane: u8, cols: u16, rows: u16) void { - const s = of(ctx); - if (pane >= s.ptys.len) return; - const fd = s.ptys[pane].fd; - if (fd < 0) return; - // 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)); - } - - fn ptySignal(ctx: ?*anyopaque, pane: u8, sig: pardes.PtySignal) void { - const s = of(ctx); - if (pane >= s.ptys.len) return; - const pt = s.ptys[pane]; - // 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 { - 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.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); - host_io.writeFile(s.core, &s.watches, pane, path, bytes); - } - - fn writeDump(ctx: ?*anyopaque, bytes: []const u8) void { - host_io.writeDump(of(ctx).core, bytes); - } - - fn watchFile(ctx: ?*anyopaque, pane: u8, _: []const u8, on: bool, mode: pardes.WatchMode) void { - const s = of(ctx); - if (file_watch.applyEffect(s.core, s.io, s.inotify(), &s.watches, pane, on, mode)) - s.check_files = true; - } - - fn watchTheme(ctx: ?*anyopaque, generation: u32, on: bool) void { - const s = of(ctx); - if (file_watch.applyThemeEffect(s.core, s.gpa, s.inotify(), &s.watches, generation, on, s.in_loop)) - s.check_files = true; - } - - fn dumpThemes(ctx: ?*anyopaque, pane: u8) void { - const s = of(ctx); - host_io.dumpThemes(s.core, s.io, s.gpa, pane); - } - - fn setClipboard(ctx: ?*anyopaque, text: []const u8) void { - const s = of(ctx); - s.core.fallback.setClipboard(text); - s.broadcast(.{ .set_clipboard = text }); - } - - fn readClipboard(ctx: ?*anyopaque) void { - const s = of(ctx); - if (s.origins()) |c| return s.send(c, .read_clipboard); - s.core.update(.{ .paste = s.core.fallback.clipboard.items }); - } - - 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 { - const s = of(ctx); - if (s.origins()) |c| s.send(c, .detach); - } - - /// 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.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().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.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; - _ = libc.close(pt.fd); - pt.fd = -1; - pt.out.deinit(s.gpa); - pt.out = .empty; - if (pt.pid == 0) return; - _ = libc.kill(pt.pid, libc.SIG.HUP); - 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) { - shell.* = .{ .pid = pt.pid, .kill_at = pt.kill_at }; - pt.pid = 0; - pt.kill_at = 0; - return; - }; - } - - fn flushPty(s: *Session, pane: u8) void { - const pt = &s.ptys[pane]; - var off: usize = 0; - while (off < pt.out.items.len) { - const n = libc.write(pt.fd, pt.out.items.ptr + off, pt.out.items.len - off); - if (n < 0) switch (libc.errno(n)) { - .INTR => continue, - .AGAIN => break, - else => { - s.readPty(pane); - if (s.ptys[pane].fd >= 0) s.paneEof(pane); - return; - }, - }; - if (n == 0) break; - off += @intCast(n); - } - if (off == 0) return; - if (off == pt.out.items.len) { - pt.out.clearRetainingCapacity(); - return retire(s.gpa, &pt.out); - } - std.mem.copyForwards(u8, pt.out.items, pt.out.items[off..]); - pt.out.items.len -= off; - } - - fn readPty(s: *Session, pane: u8) void { - var buf: [pty_chunk]u8 = undefined; - const got = libc.read(s.ptys[pane].fd, &buf, buf.len); - if (got == 0) return s.paneEof(pane); - if (got < 0) return switch (libc.errno(got)) { - .INTR, .AGAIN => {}, - else => s.paneEof(pane), - }; - s.core.update(.{ .output = .{ .pane = pane, .bytes = buf[0..@intCast(got)] } }); - } - - 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 } }); - } - - /// 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 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 { - if (s.inotify_fd >= 0) return s.inotify_fd; - s.inotify_fd = file_watch.init(true); - return s.inotify_fd; - } - - fn drainInotify(s: *Session) void { - if (file_watch.drain(s.inotify_fd)) s.check_files = true; - } - - 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; - } - } - - fn present(ctx: ?*anyopaque, surface: *const pardes.Surface) void { - const s = of(ctx); - for (&s.clients) |*c| { - if (!c.attached) continue; - if (c.out.items.len != 0) continue; - s.sendFrame(c, surface); - } - } - - 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, 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) - &.{} - else - c.mirror.items; - const cursor: ?wire.Cursor = if (surface.cursor) |cur| - .{ .x = cur.x, .y = cur.y, .bar = cur.bar } - else - null; - const bytes = wire.encodeFrameLayers( - s.scratch.allocatedSlice()[0..want], - surface.cols, - surface.rows, - cursor, - surface.pointer_shape, - cells, - 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; - }; - s.queue(c, bytes); - if (c.fd < 0) return; // the queue closed it; the mirror went with it - c.mirror.resize(s.gpa, cells.len) catch return s.close(c, .oom); - @memcpy(c.mirror.items, cells); - c.need_full = false; - } - - fn waitInput(ctx: ?*anyopaque, timeout_ms: u32) void { - const s = of(ctx); - // Both before the poll: a wake that landed since the last frame has - // had its byte drained here and must not be waited for again. - const drained = s.drainCompletions(true); - 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 = 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.wake[0] >= 0) { - fds[n] = .{ .fd = s.wake[0], .events = poll_in, .revents = 0 }; - src[n] = .completion; - n += 1; - } - const watching_listener = s.listener >= 0 and now >= s.accept_paused_ms; - if (watching_listener) { - fds[n] = .{ .fd = s.listener, .events = poll_in, .revents = 0 }; - src[n] = .listener; - n += 1; - } - for (&s.clients, 0..) |*c, i| { - if (c.fd < 0) continue; - fds[n] = .{ - .fd = c.fd, - .events = if (c.out.items.len != 0) poll_in | poll_out else poll_in, - .revents = 0, - }; - src[n] = .{ .client = @intCast(i) }; - n += 1; - } - for (&s.ptys, 0..) |*pt, pane| { - 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, - .revents = 0, - }; - src[n] = .{ .pty = @intCast(pane) }; - n += 1; - } - if (s.inotify_fd >= 0) { - fds[n] = .{ .fd = s.inotify_fd, .events = poll_in, .revents = 0 }; - src[n] = .inotify; - n += 1; - } - if (s.ninep) |l| { - // Unix and TCP connections run on cloud9's runner, which wakes - // this loop through `wake`; only QUIC is polled here. - if (comptime ninep_io.quic_enabled) { - if (l.quic) |*listener| { - fds[n] = listener.poll(); - src[n] = .ninep_quic; - n += 1; - } - } - } - // 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 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.takeExits(); - s.expire(std.Io.Clock.awake.now(s.io).toMilliseconds()); - s.harvest(); - s.reloadWatched(); - _ = s.reconcile(); - } - - fn dispatch(s: *Session, fds: []const libc.pollfd, src: []const Source) void { - for (fds, src) |pfd, source| switch (source) { - .listener => if (pfd.revents != 0) s.accept(), - .completion => {}, - .client => |i| { - const c = &s.clients[i]; - if (c.fd < 0) continue; - if (pfd.revents & poll_out != 0) s.flush(c); - if (c.fd < 0) continue; - if (pfd.revents & poll_in != 0) { - s.receive(c, i); - } else if (pfd.revents & (poll_hup | poll_err | poll_nval) != 0) { - s.close(c, .peer); - } - }, - .pty => |pane| { - if (s.ptys[pane].fd < 0) continue; - if (pfd.revents & poll_out != 0) s.flushPty(pane); - if (s.ptys[pane].fd < 0) continue; - if (pfd.revents & poll_in != 0) { - s.readPty(pane); - } else if (pfd.revents & (poll_hup | poll_err | poll_nval) != 0) { - s.paneEof(pane); - } - }, - .inotify => if (pfd.revents & poll_in != 0) s.drainInotify(), - .ninep_quic => {}, - }; - } - - fn nextWake(s: *const Session, now: i64) ?c_int { - var due: ?i64 = null; - for (s.retired_shells) |shell| if (shell.pid != 0) { - due = now + 10; - break; - }; - for (s.ptys) |pty| if (pty.fd < 0 and pty.pid != 0) { - due = now + 10; - break; - }; - for (&s.clients) |*c| { - if (c.fd < 0 or c.attached) continue; - const at = c.accepted_ms + @as(i64, s.greet_deadline_ms); - due = if (due) |d| @min(d, at) else at; - } - if (s.listener >= 0 and s.accept_paused_ms > now) - due = if (due) |d| @min(d, s.accept_paused_ms) else s.accept_paused_ms; - if (s.ninep) |l| { - if (l.nextDue()) |ms| { - const at9 = now + ms; - 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)))); - } - - fn expire(s: *Session, now: i64) void { - if (now == 0) return; // no clock: enforce nothing rather than everything - for (&s.clients) |*c| { - if (c.fd < 0 or c.attached) continue; - if (now - c.accepted_ms >= s.greet_deadline_ms) s.close(c, .silent); - } - } - - fn accept(s: *Session) void { - for (0..max_clients + 1) |_| { - const fd = libc.accept(s.listener, null, null); - if (fd < 0) { - switch (libc.errno(fd)) { - .AGAIN, .INTR, .CONNABORTED => return, - else => { - s.accept_paused_ms = std.Io.Clock.awake.now(s.io).toMilliseconds() + accept_pause_ms; - return; - }, - } - } - ninep_io.setCloexec(fd); - _ = setNonblock(fd); - if (comptime darwin) { - const on: c_int = 1; - _ = libc.setsockopt(fd, libc.SOL.SOCKET, libc.SO.NOSIGPIPE, &on, @sizeOf(c_int)); - } - const slot = for (&s.clients, 0..) |*c, i| { - if (c.fd < 0) break i; - } else { - s.refuseFd(fd, .full); - _ = libc.close(fd); - continue; - }; - s.clients[slot] = .{ .fd = fd, .accepted_ms = std.Io.Clock.awake.now(s.io).toMilliseconds() }; - } - } - - fn receive(s: *Session, c: *Client, slot: u8) void { - var buf: [read_chunk]u8 = undefined; - const got = libc.read(c.fd, &buf, buf.len); - if (got == 0) return s.close(c, .peer); // clean EOF: the frontend left - if (got < 0) return switch (libc.errno(got)) { - .INTR, .AGAIN => {}, - else => s.close(c, .read), - }; - c.in.appendSlice(s.gpa, buf[0..@intCast(got)]) catch return s.close(c, .oom); - s.account(); - if (c.fd < 0) return; // it was this one - s.consume(c, slot); - } - - fn consume(s: *Session, c: *Client, slot: u8) void { - var off: usize = 0; - while (true) { - const found = wire.framed(c.in.items[off..]) catch return s.close(c, .protocol); - const msg = found orelse break; - s.apply(c, slot, msg.tag, msg.payload) catch return s.close(c, .protocol); - if (c.fd < 0) return; // apply closed it, buffers and all - off += msg.total; - } - if (off == 0) return; - if (off == c.in.items.len) { - c.in.clearRetainingCapacity(); - return retire(s.gpa, &c.in); - } - std.mem.copyForwards(u8, c.in.items, c.in.items[off..]); - c.in.items.len -= off; - } - - fn apply(s: *Session, c: *Client, slot: u8, tag: u8, payload: []const u8) wire.Error!void { - if (tag == @backingInt(wire.ClientTag.hello)) { - if (c.attached) return error.BadValue; - const claimed = try wire.helloVersion(payload); - if (claimed != wire.version) { - log.debug("frontend speaks protocol {d}, this session speaks {d}", .{ claimed, wire.version }); - return s.refuse(c, .version); - } - } - switch (try wire.decodeClient(tag, payload)) { - .hello => |h| { - if (s.core.quit) return s.refuse(c, .quitting); - c.cols = h.cols; - c.rows = h.rows; - 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| { - if (!c.attached) return error.BadValue; - switch (ev) { - .resize => |r| { - c.cols = r.cols; - c.rows = r.rows; - if (r.row_metrics) |metrics| s.core.row_metrics = metrics; - }, - else => { - s.origin = slot; - s.core.update(ev); - }, - } - }, - } - } - - fn reconcile(s: *Session) bool { - var cols: u16 = 0; - var rows: u16 = 0; - for (&s.clients) |*c| { - if (!c.attached) continue; - cols = if (cols == 0) c.cols else @min(cols, c.cols); - rows = if (rows == 0) c.rows else @min(rows, c.rows); - } - var regridded = false; - // 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; - s.core.update(.{ .resize = .{ .cols = cols, .rows = rows } }); - regridded = true; - } - for (&s.clients, 0..) |*c, i| { - if (!c.greet) continue; - c.greet = false; - s.send(c, .{ .welcome = .{ .slot = @intCast(i), .cols = s.cols, .rows = s.rows } }); - } - 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); - const bytes = wire.encodeServer(s.scratch.allocatedSlice()[0..want], msg) catch |err| { - log.debug("message {t} not encodable: {t}", .{ msg, err }); - return; - }; - 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(); - if (c.fd < 0) return; // the fattest peer was this one - c.out.appendSlice(s.gpa, bytes) catch return s.close(c, .oom); - s.flush(c); - } - - fn account(s: *Session) void { - var total: usize = 0; - var worst: ?*Client = null; - var worst_bytes: usize = 0; - for (&s.clients) |*c| { - if (c.fd < 0) continue; - const held = c.in.items.len + c.out.items.len; - total += held; - if (held > worst_bytes) { - worst_bytes = held; - worst = c; - } - } - if (total <= session_backlog) return; - if (worst) |c| s.close(c, .backlog); - } - - fn flush(s: *Session, c: *Client) void { - var off: usize = 0; - while (off < c.out.items.len) { - const n = libc.send(c.fd, c.out.items.ptr + off, c.out.items.len - off, nosignal); - if (n < 0) switch (libc.errno(n)) { - .INTR => continue, - .AGAIN => break, - else => return s.close(c, .write), - }; - if (n == 0) break; - off += @intCast(n); - } - if (off == 0) return; - if (off == c.out.items.len) { - c.out.clearRetainingCapacity(); - return retire(s.gpa, &c.out); - } - std.mem.copyForwards(u8, c.out.items, c.out.items[off..]); - c.out.items.len -= off; - } - - fn refuse(s: *Session, c: *Client, why: wire.Refusal) void { - s.refuseFd(c.fd, why); - s.close(c, .refused); - } - - 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) { - const n = libc.send(fd, bytes.ptr + off, bytes.len - off, nosignal); - if (n < 0 and libc.errno(n) == .INTR) continue; - if (n <= 0) break; // it left before hearing why; nothing to do - off += @intCast(n); - } - } - - fn close(s: *Session, c: *Client, why: Closed) void { - if (c.fd < 0) return; - log.debug("frontend detached: {t}", .{why}); - _ = libc.close(c.fd); - c.in.deinit(s.gpa); - c.out.deinit(s.gpa); - c.mirror.deinit(s.gpa); - const gone = s.slotOf(c); - if (s.origin) |i| if (i == gone) { - s.origin = null; - }; - c.* = .{}; - } -}; - -/// 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; - options.frame_allocator = allocs.frame; - - pardes.image.start(init.io, allocs.image); - if (comptime pardes.pdf_enabled) pardes.pdf.start(allocs.pdf); - pardes.syntax.start(allocs.tree_sitter); - defer { - pardes.image.stop(); - if (comptime pardes.pdf_enabled) pardes.pdf.stop(); - pardes.syntax.stop(); - } - - const core = if (options.load_path) |lp| blk: { - const bytes = try filesystem.readFile(gpa, lp); - defer gpa.free(bytes); - break :blk try pardes.dump.initFromDump(allocs.pardes, options, bytes); - } else try pardes.Pardes.init(allocs.pardes, options); - var session: Session = .{ - .gpa = gpa, - .worker_gpa = allocs.lsp, - .io = init.io, - .core = core, - .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"); - std.process.exit(1); - } - - 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.?.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; - 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, 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, 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 = .{ - .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(); - try s.initAsync(); - while (s.core.nextEffect()) |_| {} - _ = try s.core.setTestFile("saved body\n"); - s.core.lspRequest(0, .status, ""); - const old_id = s.core.lsp_wait.?.id; - s.core.lspRequest(0, .status, ""); - const current_id = s.core.lsp_wait.?.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 dump.dumpState(s.core); - const saved = try gpa.dupe(u8, s.core.dump_out.?); - defer gpa.free(saved); - while (s.core.nextEffect()) |_| {} - 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.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); - - s.core.lspRequest(0, .status, ""); - const restored_id = s.core.lsp_wait.?.id; - try std.testing.expect(restored_id > current_id); - 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.inbox.lsp_task.?.id); - try std.testing.expectEqual(restored_id, s.core.lsp_wait.?.id); - s.inbox.push(.{ .lsp = .{ .id = restored_id, .rows = &.{} } }); - const host = s.host(); - host.vtable.wait_input.?(host.ctx, 1); - 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 }); - var s: Session = .{ - .gpa = gpa, - .worker_gpa = failing.allocator(), - .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(); - try s.initAsync(); - while (s.core.nextEffect()) |_| {} - const pane = try s.core.setTestFile("one\n"); - s.core.host = s.host(); - 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.inbox.lsp_task == null); - - 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); - while (s.core.nextEffect()) |effect| s.core.perform(effect); - 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); -} - -pub const setCloexec = ninep_io.setCloexec; - -pub fn setNonblock(fd: c_int) bool { - const flags = libc.fcntl(fd, libc.F.GETFL, @as(c_int, 0)); - if (flags < 0) return false; - var o: libc.O = @bitCast(@as(u32, @bitCast(flags))); - o.NONBLOCK = true; - 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; - -pub const poll_in: i16 = @intCast(libc.POLL.IN); -pub const poll_out: i16 = @intCast(libc.POLL.OUT); -pub const poll_hup: i16 = @intCast(libc.POLL.HUP); -pub const poll_err: i16 = @intCast(libc.POLL.ERR); -pub const poll_nval: i16 = @intCast(libc.POLL.NVAL); - -fn retire(gpa: std.mem.Allocator, list: *std.ArrayListUnmanaged(u8)) void { - if (list.items.len != 0 or list.capacity <= idle_retain) return; - list.clearAndFree(gpa); -} - -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; - return std.fmt.bufPrintSentinel(buf, "{s}/" ++ prefix ++ "{s}.sock", .{ dir, name }, 0) catch null; -} - -const prefix = "pardes-detached-"; - -pub const path_max = sun_path_len; - -pub fn sessionPath(buf: *[path_max]u8, name: []const u8) ?[:0]const u8 { - if (comptime !supported) return null; - var dir_buf: [sun_path_len:0]u8 = undefined; - const dir = ninep_io.socketDir(&dir_buf) orelse return null; - return socketPath(buf, dir, name); -} - -pub fn vetted(path: [:0]const u8) bool { - if (comptime !supported) return false; - var dir_buf: [sun_path_len:0]u8 = undefined; - const dir = ninep_io.socketDir(&dir_buf) orelse return false; - if (!ours(ninep_io.statNoFollow(dir) orelse return false, s_ifdir)) return false; - return ours(ninep_io.statNoFollow(path) orelse return false, s_ifsock); -} - -const s_ifmt: u32 = 0o170000; -const s_ifdir: u32 = 0o040000; -const s_ifsock: u32 = 0o140000; - -fn ours(st: ninep_io.FileFacts, kind: u32) bool { - if (st.mode & s_ifmt != kind) return false; - if (st.uid != libc.getuid()) return false; - return st.mode & 0o077 == 0; -} - -fn alive(path: [:0]const u8) bool { - var addr: libc.sockaddr.un = .{ .path = @splat(0) }; - if (path.len + 1 > addr.path.len) return true; - @memcpy(addr.path[0 .. path.len + 1], path[0 .. path.len + 1]); - const fd = libc.socket(libc.AF.UNIX, libc.SOCK.STREAM, 0); - if (fd < 0) return true; - defer _ = libc.close(fd); - ninep_io.setCloexec(fd); - _ = setNonblock(fd); - const rc = libc.connect(fd, @ptrCast(&addr), @sizeOf(@TypeOf(addr))); - if (rc == 0) return true; - return libc.errno(rc) != .CONNREFUSED; -} - -fn sweep(dir: [:0]const u8) void { - const d = libc.opendir(dir) orelse return; - defer _ = libc.closedir(d); - while (libc.readdir(d)) |ent| { - const name = std.mem.sliceTo(&ent.name, 0); - if (!std.mem.startsWith(u8, name, prefix) or !std.mem.endsWith(u8, name, ".sock")) continue; - var path_buf: [sun_path_len:0]u8 = undefined; - const path = std.fmt.bufPrintSentinel(&path_buf, "{s}/{s}", .{ dir, name }, 0) catch continue; - if (!alive(path)) _ = libc.unlink(path); - } -} diff --git a/src/detached/wire.zig b/src/detached/wire.zig index 0e141686..20d75274 100644 --- a/src/detached/wire.zig +++ b/src/detached/wire.zig @@ -1,32 +1,13 @@ -//! Detached input and frames use fixed-width little-endian fields and explicit tags. -//! Native struct layout never reaches the wire. +//! The framed stream a remote client will speak (docs/next-daemon.md, +//! phase 5): fixed-width little-endian fields and explicit tags, the hello +//! and its version, and the input Events. Native struct layout never reaches +//! the wire. The cell frames that went the other way, and the frontends that +//! drew them, went with phase 3. 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; -/// 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; - -/// 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()})); -} +/// 13: the frames, and every message a session sent, are gone (phase 3). +pub const version: u16 = 13; /// EndOfStream: the message ends early; WriteFailed: no room for it. /// ReadFailed is in only because std.Io.Reader says so: a fixed one never @@ -38,16 +19,6 @@ pub const max_rows: u16 = 128; pub const max_payload: u32 = 16 << 20; pub const header_len = 5; // tag:u8, payload length:u32le -const cell_max = 1 + 1 + 7 + 4 + 4 + 1 + 1 + 1; -const run_header = 4 + 2; // start:u32, count:u16 -const run_max = std.math.maxInt(u16); -const frame_head = 1 + 2 + 2 + 6 + 4 + 4; - -// Worst case: every cell changed, each in its own run. -pub fn frameBound(cols: u16, rows: u16) usize { - return header_len + frame_head + @as(usize, cols) * @as(usize, rows) * (run_header + cell_max); -} - // Stable wire numbers; gaps are retired tags. Unknown tags are rejected by the decoder. pub const ClientTag = enum(u8) { hello = 0x01, @@ -65,43 +36,6 @@ pub const ClientTag = enum(u8) { focus = 0x1e, }; -// Session control precedes display-local effects. -pub const ServerTag = enum(u8) { - welcome = 0x01, - refuse = 0x02, - frame = 0x03, - quit = 0x04, - /// One frontend is done, and the session is NOT over. The `Detach` word, - /// routed back to the frontend whose keystroke ran it (server.zig ORIGIN, - /// ELSE PRIMARY, the same rule `read_clipboard` takes and for the same - /// reason). Every other frontend, the core and the pane shells are - /// untouched, so leaving is success rather than a failure to report. - detach = 0x05, - - 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 -/// close, so a frontend can say something specific instead of "connection -/// closed". -pub const Refusal = enum(u8) { - /// `Hello.version` is not `version`. The frontend and the core are two - /// builds of pardes. - version = 0x01, - /// Every client slot is taken (see server.zig `max_clients`). - full = 0x02, - /// The core has already quit; this session is ending. - quitting = 0x03, -}; - -const ColorTag = enum(u8) { default = 0x00, index = 0x01, rgb = 0x02 }; -const UlTag = enum(u8) { off = 0x00, single = 0x01, double = 0x02, curly = 0x03, dotted = 0x04, dashed = 0x05 }; -const FontTag = enum(u8) { body = 0x00, tagline = 0x01 }; const ButtonTag = enum(u8) { left = 0x00, middle = 0x01, @@ -116,24 +50,6 @@ const ButtonTag = enum(u8) { }; const KindTag = enum(u8) { press = 0x00, release = 0x01, motion = 0x02, drag = 0x03 }; -/// A full frame resets the receiver's grid to unpainted cells and then applies -/// its runs; a diff applies its runs on top of what is already there. One bit -/// of semantics and one code path, and it is what makes a full frame of a -/// mostly-empty grid cheap. -pub const FrameKind = enum(u8) { full = 0x01, diff = 0x02 }; -const FrameHeader = enum(u8) { full = 0x01, diff = 0x02, full_link = 0x03, diff_link = 0x04 }; - -/// Bit per `CellStyle` bool, packed into one byte. Bit 7 is unassigned and a -/// set bit 7 is a decode error: it is a byte this protocol cannot mean. -const attr_bold: u8 = 1 << 0; -const attr_dim: u8 = 1 << 1; -const attr_italic: u8 = 1 << 2; -const attr_blink: u8 = 1 << 3; -const attr_reverse: u8 = 1 << 4; -const attr_invisible: u8 = 1 << 5; -const attr_strikethrough: u8 = 1 << 6; -const attr_reserved: u8 = 1 << 7; - // --------------------------------------------------------------------------- // messages // --------------------------------------------------------------------------- @@ -143,8 +59,8 @@ const attr_reserved: u8 = 1 << 7; /// when the rest of the layout is the part that changed. pub const Hello = struct { version: u16 = version, - /// This frontend's grid. Never zero — see `Cursor` for why zero is refused - /// rather than clamped. + /// This client's grid. Never zero: a client not sized yet must not + /// collapse a shared session (getCols). cols: u16, rows: u16, }; @@ -166,182 +82,6 @@ pub fn helloVersion(payload: []const u8) Error!u16 { return r.takeInt(u16, .little); } -pub const Welcome = struct { - version: u16 = version, - /// Which client slot this connection got. Carried because it is what the - /// server's own diagnostics name, so both sides say the same number. - slot: u8, - /// The session's grid as of this attach — the smallest common one, which - /// may be smaller than the `Hello` asked for. See server.zig `geometry`. - cols: u16, - rows: u16, -}; - -pub const Cursor = struct { x: u16, y: u16, bar: bool }; - -/// One frame, head decoded and runs left encoded. The runs are NOT expanded -/// into a slice of cells here: a frame of the largest grid is 1.6 MiB, this -/// union is passed by value, and the receiver already owns the grid the runs -/// belong in. `apply` is the bounds-checked walk. -pub const Frame = struct { - layers: []const u8 = &.{}, - pointer_shape: pardes.Surface.PointerShape = .arrow, - kind: FrameKind, - cols: u16, - rows: u16, - cursor: ?Cursor, - nruns: u32, - runs: []const u8, - - 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.* = .{}; - } - for (tags) |*layer| { - gpa.free(layer.cells); - layer.* = .{}; - } - errdefer { - for (layers) |*layer| { - gpa.free(layer.cells); - layer.* = .{}; - } - for (tags) |*layer| { - gpa.free(layer.cells); - layer.* = .{}; - } - regions.clearRetainingCapacity(); - chrome.* = .{}; - } - if (f.layers.len == 0) return; - 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.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 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.takeInt(u16, .little); - if (tag_count > tags.len) return error.Overlong; - for (tags[0..tag_count]) |*layer| { - 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 layer.viewport.h > f.rows - layer.viewport.y or (switch (layer.kind) { - .workspace => layer.id != 0, - .column => layer.id >= pardes.MAX_COLS, - .pane, .notice => layer.id >= pardes.MAX_PANES, - .body => true, - })) return error.BadValue; - 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 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 - /// — the receiver resizes on a geometry change before applying, and a grid - /// of the wrong size is a receiver bug, not a wire condition. - /// - /// Every run is range-checked against the grid before a single cell is - /// written, so a run claiming to start past the end writes nothing. - 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: std.Io.Reader = .fixed(f.runs); - var i: u32 = 0; - while (i < f.nruns) : (i += 1) { - 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; - // THE bounds check. Written as `count > len - start` rather than - // `start + count > len` because the sum of two attacker-chosen - // 32-bit numbers is the classic way this check is bypassed. - if (start > grid.len or count > grid.len - start) return error.Overlong; - for (grid[start..][0..count]) |*c| c.* = try decodeCell(&r); - } - try end(&r); - } -}; - /// Frontend -> core, decoded. The `Event`'s slices BORROW the payload buffer, /// exactly like the pty chunks the tty host hands to `update`: valid for that /// one call and no longer. @@ -351,38 +91,6 @@ pub const ClientMsg = union(enum) { event: pardes.Event, }; -/// Core -> frontend, decoded. Slices borrow the payload buffer the same way. -pub const ServerMsg = union(enum) { - welcome: Welcome, - refuse: Refusal, - frame: Frame, - /// The session is over. Sent before the listener closes so a frontend can - /// exit rather than report a broken pipe. - quit, - /// One frontend is done, and the session is NOT over — see `ServerTag`. - detach, - - set_clipboard: []const u8, - read_clipboard, - open_link: []const u8, - post: Post, -}; - -/// 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, - - pub fn list(p: *const Post) []const ShaderBuild.Pass { - return p.passes[0..p.len]; - } -}; - // --------------------------------------------------------------------------- // primitives // --------------------------------------------------------------------------- @@ -490,368 +198,13 @@ pub fn framed(buf: []const u8) Error!?Framed { return .{ .tag = buf[0], .payload = buf[header_len..][0..len], .total = header_len + len }; } -// --------------------------------------------------------------------------- -// cells -// --------------------------------------------------------------------------- - -fn putColor(w: *std.Io.Writer, c: pardes.Color) Error!void { - switch (c) { - .default => try w.writeByte(@backingInt(ColorTag.default)), - .index => |i| { - try w.writeByte(@backingInt(ColorTag.index)); - try w.writeByte(i); - }, - .rgb => |v| { - try w.writeByte(@backingInt(ColorTag.rgb)); - try w.writeAll(&v); - }, - } -} - -fn getColor(r: *std.Io.Reader) Error!pardes.Color { - return switch (try getTag(r, ColorTag)) { - .default => .default, - .index => .{ .index = try r.takeByte() }, - .rgb => .{ .rgb = (try r.take(3))[0..3].* }, - }; -} - -const Ul = @FieldType(pardes.CellStyle, "ul"); - -/// The four enum mappings — underline, font role, mouse button, mouse kind — -/// and `clientTag`/`serverTag` further down all have one shape: the WIRE -/// member of the same NAME. So the byte on the socket is still `@intFromEnum` -/// of an explicitly numbered enum in THIS file and never of a core type — -/// reordering `CellStyle.ul` changes nothing — and adding a variant to the -/// core without adding one here does not compile: -/// -/// error: enum 'wire.UlTag' has no member named 'wavy' -/// -/// 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 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: *std.Io.Reader) Error!Ul { - return switch (try getTag(r, UlTag)) { - inline else => |t| @field(Ul, @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: *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 `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; - return 1 + 1 + c.len + colorSize(c.style.fg) + colorSize(c.style.bg) + 1 + 1 + 1; -} - -fn colorSize(c: pardes.Color) usize { - return switch (c) { - .default => 1, - .index => 2, - .rgb => 4, - }; -} - -/// An unpainted cell is ONE byte: `default` means "the shell renders the -/// 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: *std.Io.Writer, c: *const pardes.Cell) Error!void { - try w.writeByte(@intFromBool(c.default)); - if (c.default) return; - try w.writeByte(c.len); - try w.writeAll(c.grapheme()); - const s = c.style; - try putColor(w, s.fg); - try putColor(w, s.bg); - var attrs: u8 = 0; - if (s.bold) attrs |= attr_bold; - if (s.dim) attrs |= attr_dim; - if (s.italic) attrs |= attr_italic; - if (s.blink) attrs |= attr_blink; - if (s.reverse) attrs |= attr_reverse; - if (s.invisible) attrs |= attr_invisible; - if (s.strikethrough) attrs |= attr_strikethrough; - try w.writeByte(attrs); - try putUl(w, s.ul); - try putFont(w, s.font_role); -} - -fn decodeCell(r: *std.Io.Reader) Error!pardes.Cell { - if (try getBool(r)) return .{}; - var c: pardes.Cell = .{ .default = false }; - 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; - c.len = len; - @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.takeByte(); - if (attrs & attr_reserved != 0) return error.BadValue; - c.style.bold = attrs & attr_bold != 0; - c.style.dim = attrs & attr_dim != 0; - c.style.italic = attrs & attr_italic != 0; - c.style.blink = attrs & attr_blink != 0; - c.style.reverse = attrs & attr_reverse != 0; - c.style.invisible = attrs & attr_invisible != 0; - c.style.strikethrough = attrs & attr_strikethrough != 0; - c.style.ul = try getUl(r); - c.style.font_role = try getFont(r); - return c; -} - -// --------------------------------------------------------------------------- -// frames -// --------------------------------------------------------------------------- - -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.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.writeInt(u16, c.x, .little); - try w.writeInt(u16, c.y, .little); - try w.writeByte(@intFromBool(c.bar)); -} - -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 - // says is 4x2 is an out-of-bounds write in EVERY frontend, not a wrong - // glyph. Checked whether or not the cursor is present, because the absent - // case is six bytes of padding this encoder writes as zero and a peer that - // fills them with anything else is not speaking this protocol. - if (c.x >= cols or c.y >= rows) return error.BadValue; - 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. -/// -/// A late joiner and a resize are the same case and are handled by the same -/// test: nothing on the far side is comparable to this grid, so `prev` is -/// empty or a different length and the frame becomes full. -/// -/// Why a diff at all. Measured against a real `pardes --detach` at 80x24 with -/// the default theme, which paints every cell and gives most of them an rgb -/// pair (14 bytes a cell rather than the 8 an uncoloured one costs): -/// * a full frame is 21965-26699 bytes, depending on what is on screen, -/// * a frame that changes nothing is 20 — the head, and no runs at all, -/// * a one-row change (`Msg hi`) is 54 bytes in one run, and a wordier one -/// 166, -/// * and an IDLE session sends nothing whatever, because the core is asleep -/// in `poll(2)` and produces no frame until something happens. -/// So the diff is worth roughly 500x on the traffic a session actually -/// generates. The byte-count test below asserts the arithmetic on the board's -/// 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 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 - // refuses as Overlong — and sendFrame's log line already claims that this - // is the error it is catching, which was true of nothing until here. - 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: 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.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.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.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.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.rows != 0) { - tag_count += 1; - }; - try w.writeInt(u16, tag_count, .little); - for (tags) |layer| { - 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.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; - while (i < cells.len) { - if (!sendCell(cells, prev, full, i)) { - i += 1; - continue; - } - const start = i; - var run_end = i + 1; - i += 1; - // `i - start` and not `run_end - start`, because the gap lookahead - // below moves `i` ahead of `run_end` by up to `run_header - 1` before - // the next iteration adopts it: bounding the cursor bounds the run, - // and bounding the run afterwards would not. - while (i < cells.len and i - start < run_max) { - if (sendCell(cells, prev, full, i)) { - run_end = i + 1; - i += 1; - continue; - } - // A gap. Re-sending cells the far side already has is cheaper than - // a second run header whenever their encoded size adds up to less - // than one — true for short stretches of unpainted cells at a byte - // each, and false as soon as one painted cell (eight bytes at its - // smallest) is in the way. So the lookahead can never need to pass - // `run_header - 1` cells. - var gap: usize = 0; - var j = i; - while (j < cells.len and gap < run_header) : (j += 1) { - if (sendCell(cells, prev, full, j)) break; - gap += cellSize(&cells[j]); - } - if (j >= cells.len or gap >= run_header) break; - i = j; - } - 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.buffer[nruns_at..][0..4], nruns, .little); - try finishMessage(&w, at); - return w.buffered(); -} - -fn sendCell(cells: []const pardes.Cell, prev: []const pardes.Cell, full: bool, i: usize) bool { - // Full: the receiver reset the grid, so unpainted cells are already right. - // Diff: anything the receiver cannot already be showing. - if (full) return !cells[i].default; - return !cells[i].visuallyEqual(&prev[i]); -} - // --------------------------------------------------------------------------- // frontend -> core // --------------------------------------------------------------------------- /// Which tag a message travels under: the `ClientTag` of the same NAME, so a -/// new `Event` variant does not compile until it has a number here. See -/// `putUl` for the error it produces and why this is not a written-out table. +/// new `Event` variant does not compile until it has a number here, rather +/// than a written-out table that can drift. fn clientTag(msg: ClientMsg) ClientTag { return switch (msg) { .event => |ev| switch (ev) { @@ -1054,81 +407,12 @@ pub fn decodeClient(tag: u8, payload: []const u8) Error!ClientMsg { return msg; } -// --------------------------------------------------------------------------- -// core -> frontend -// --------------------------------------------------------------------------- - -/// ...and the same rule in the same shape: the `ServerTag` of the same name. -fn serverTag(msg: ServerMsg) ServerTag { - return switch (msg) { - inline else => |_, t| @field(ServerTag, @tagName(t)), - }; -} - -/// 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 `encodeFrameLayers`). -pub fn encodeServer(out: []u8, msg: ServerMsg) Error![]const u8 { - var w: std.Io.Writer = .fixed(out); - const at = try beginMessage(&w, @backingInt(serverTag(msg))); - switch (msg) { - .welcome => |v| { - 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.writeByte(@backingInt(why)), - // A frame's runs are not a value this union can hold; the server calls - // encodeFrameLayers directly and this arm exists so the switch stays - // exhaustive over ServerMsg. - .frame => return error.BadValue, - .quit, .detach => {}, - .set_clipboard => |t| try putSlice32(&w, t), - .read_clipboard => {}, - .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.buffered(); -} - /// Slack over a message's variable payload, covering every fixed field any -/// message here has plus its own header. One loose constant rather than a -/// field-by-field count: a bound that is 32 bytes generous costs one `memcpy` -/// worth of nothing, and a bound that is one byte tight is a bug that only -/// shows up on the message nobody tested. +/// message here has plus its own header. const msg_slack = header_len + 64; -/// An upper bound on `encodeServer`'s output, so a caller sizes its buffer +/// An upper bound on `encodeClient`'s output, so a caller sizes its buffer /// once instead of guessing and retrying. -pub fn serverBound(msg: ServerMsg) usize { - return msg_slack + switch (msg) { - .welcome, .refuse, .quit, .detach, .read_clipboard => 0, - // A frame is bounded by its grid, not by this: see `frameBound`. - .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; - }, - }; -} - -/// ...and the same for the frontend's side of the wire. pub fn clientBound(msg: ClientMsg) usize { return msg_slack + switch (msg) { .hello, .bye => 0, @@ -1143,76 +427,6 @@ pub fn clientBound(msg: ClientMsg) usize { }; } -pub fn decodeServer(tag: u8, payload: []const u8) Error!ServerMsg { - 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.takeInt(u16, .little), - .slot = try r.takeByte(), - .cols = try getCols(&r), - .rows = try getRows(&r), - } }, - .refuse => .{ .refuse = try getTag(&r, Refusal) }, - .frame => blk: { - const header = try getTag(&r, FrameHeader); - const kind: FrameKind = switch (header) { - .full, .full_link => .full, - .diff, .diff_link => .diff, - }; - const cols = try getCols(&r); - const rows = try getRows(&r); - const cursor = try getCursor(&r, cols, rows); - 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.buffered(); - r.tossBuffered(); - break :blk .{ .frame = .{ - .layers = layers, - .kind = kind, - .pointer_shape = if (header == .full_link or header == .diff_link) .link else .arrow, - .cols = cols, - .rows = rows, - .cursor = cursor, - .nruns = nruns, - .runs = runs, - } }; - }, - .quit => .quit, - .detach => .detach, - .set_clipboard => .{ .set_clipboard = try getSlice32(&r) }, - .read_clipboard => .read_clipboard, - .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 end(&r); - return msg; -} - // --------------------------------------------------------------------------- // tests // --------------------------------------------------------------------------- @@ -1233,13 +447,6 @@ fn roundClient(buf: []u8, msg: ClientMsg) !ClientMsg { return decodeClient(f.tag, f.payload); } -fn roundServer(buf: []u8, msg: ServerMsg) !ServerMsg { - const bytes = try encodeServer(buf, msg); - const f = (try framed(bytes)).?; - try testing.expectEqual(bytes.len, f.total); - return decodeServer(f.tag, f.payload); -} - test "detached wire: every Event variant round-trips" { var buf: [4096]u8 = undefined; @@ -1311,50 +518,6 @@ test "detached wire: every Event variant round-trips" { ); } -test "detached wire: every server message round-trips" { - var buf: [4096]u8 = undefined; - - { - const got = (try roundServer(&buf, .{ .welcome = .{ .slot = 2, .cols = 56, .rows = 14 } })).welcome; - try testing.expectEqual(version, got.version); - try testing.expectEqual(@as(u8, 2), got.slot); - try testing.expectEqual(@as(u16, 56), got.cols); - try testing.expectEqual(@as(u16, 14), got.rows); - } - for (std.enums.values(Refusal)) |why| - try testing.expectEqual(why, (try roundServer(&buf, .{ .refuse = why })).refuse); - try testing.expectEqual(ServerMsg.quit, try roundServer(&buf, .quit)); - try testing.expectEqual(ServerMsg.detach, try roundServer(&buf, .detach)); - 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" { - // Two guards, because the mistake has two directions. The exhaustive - // switch fails to COMPILE if a machine-local effect is added back, which - // 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, 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, .post => {}, - }; -} - test "detached wire: a session is never told to do a frontend's remembering" { // The mirror of the test above, and of client.zig's "a frontend is never // asked to fork, write, or watch". That one pins what may reach a FRONTEND; @@ -1422,223 +585,7 @@ test "detached wire: a session is never told to do a frontend's remembering" { try testing.expectEqual(allowed.len, accepted); } -/// A grid with something in every corner: a default cell, a plain ASCII cell, -/// an indexed pair, an rgb pair with every attribute on, and a multi-byte -/// grapheme — the five shapes `putCell` branches on. -fn sampleGrid(cells: []pardes.Cell) void { - @memset(cells, .{}); - cells[0] = .{ .text = "x".* ++ @as([6]u8, @splat(0)), .len = 1, .default = false }; - cells[1] = .{ - .text = "y".* ++ @as([6]u8, @splat(0)), - .len = 1, - .default = false, - .style = .{ .fg = .{ .index = 3 }, .bg = .{ .index = 250 }, .bold = true, .ul = .curly }, - }; - cells[2] = .{ - .text = "→".* ++ @as([4]u8, @splat(0)), - .len = 3, - .default = false, - .style = .{ - .fg = .{ .rgb = .{ 1, 2, 3 } }, - .bg = .{ .rgb = .{ 250, 251, 252 } }, - .bold = true, - .dim = true, - .italic = true, - .blink = true, - .reverse = true, - .invisible = true, - .strikethrough = true, - .ul = .dashed, - .font_role = .tagline, - }, - }; - cells[cells.len - 1] = .{ .text = "z".* ++ @as([6]u8, @splat(0)), .len = 1, .default = false }; -} - -fn expectGridEqual(want: []const pardes.Cell, have: []const pardes.Cell) !void { - try testing.expectEqual(want.len, have.len); - // `visuallyEqual` and not `std.meta.eql`: `Cell.text` past `len` is - // scratch left by an earlier grapheme, the decoder does not invent it, and - // pardes.zig says in as many words that it must never manufacture a diff. - for (want, have, 0..) |*a, *b, i| if (!a.visuallyEqual(b)) { - std.debug.print("cell {d} differs: {any} vs {any}\n", .{ i, a.*, b.* }); - return error.CellMismatch; - }; -} - -test "detached wire: a full frame carries the grid, a diff carries the change" { - const cols: u16 = 56; - const rows: u16 = 14; - const n = @as(usize, cols) * rows; - const gpa = testing.allocator; - - const cells = try gpa.alloc(pardes.Cell, n); - defer gpa.free(cells); - const mirror = try gpa.alloc(pardes.Cell, n); - defer gpa.free(mirror); - const buf = try gpa.alloc(u8, frameBound(cols, rows)); - defer gpa.free(buf); - - sampleGrid(cells); - @memset(mirror, .{}); - - // FULL: nothing on the far side is comparable, which is the late joiner - // and the resize both. - 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; - try testing.expectEqual(FrameKind.full, msg.kind); - try testing.expectEqual(cols, msg.cols); - try testing.expectEqual(rows, msg.rows); - try testing.expectEqual(@as(u16, 3), msg.cursor.?.x); - try testing.expectEqual(@as(u16, 4), msg.cursor.?.y); - try testing.expect(msg.cursor.?.bar); - try msg.apply(mirror); - try expectGridEqual(cells, mirror); - } - - // DIFF: two cells move. The mirror is already in sync, so this is what a - // steady-state frame looks like. - const before = try gpa.dupe(pardes.Cell, cells); - 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 encodeFrameLayers(buf, cols, rows, null, .arrow, cells, before, &.{}, &.{}, &.{}, .{}); - { - const f = (try framed(diff_bytes)).?; - const msg = (try decodeServer(f.tag, f.payload)).frame; - try testing.expectEqual(FrameKind.diff, msg.kind); - try testing.expectEqual(@as(?Cursor, null), msg.cursor); - try testing.expectEqual(@as(u32, 2), msg.nruns); - try msg.apply(mirror); - try expectGridEqual(cells, mirror); - } - - // 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 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; - try testing.expectEqual(@as(u32, 0), msg.nruns); - try msg.apply(mirror); - try expectGridEqual(cells, mirror); - } -} - -test "detached wire: the largest grid is one cell past a run, and survives it" { - // `max_cols * max_rows` is 65536 and a run's `count` is a u16, so THE ONE - // grid this protocol calls legal at both bounds is the one grid whose full - // frame cannot be described by a single run. It reached nobody while a - // frontend sent its window raw — a display that big had its hello refused - // before any frame was composed — and it is the ordinary case now that a - // frontend clamps to exactly this. In a safe build the `@intCast` panicked - // and took the session down; in a fast one it wrote a zero-length run the - // frontend answered with `BadValue`. - const cols = max_cols; - const rows = max_rows; - const n = @as(usize, cols) * rows; - const gpa = testing.allocator; - - const cells = try gpa.alloc(pardes.Cell, n); - defer gpa.free(cells); - const mirror = try gpa.alloc(pardes.Cell, n); - defer gpa.free(mirror); - const buf = try gpa.alloc(u8, frameBound(cols, rows)); - defer gpa.free(buf); - - // Every cell painted, which is what `render` produces and therefore what a - // full frame always is: one run, if a run could be that long. - for (cells) |*c| c.* = .{ .text = "a".* ++ @as([6]u8, @splat(0)), .len = 1, .default = false }; - @memset(mirror, .{}); - - 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); - // Split, and split as late as it can be: 65535 cells then 1. - try testing.expectEqual(@as(u32, 2), msg.nruns); - try msg.apply(mirror); - 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 `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( - @as(usize, header_len + frame_head + 2 * run_header + n * 8), - bytes.len, - ); -} - -test "detached wire: the diff is worth having, in bytes, on the board's grid" { - // 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; - const n = @as(usize, cols) * rows; - const gpa = testing.allocator; - - const cells = try gpa.alloc(pardes.Cell, n); - defer gpa.free(cells); - const buf = try gpa.alloc(u8, frameBound(cols, rows)); - defer gpa.free(buf); - - // 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 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); - - const before = try gpa.dupe(pardes.Cell, cells); - defer gpa.free(before); - // A keystroke: one glyph replaced, and the cursor's old and new cells - // repainted. Three cells, adjacent enough to coalesce into two runs. - 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 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. - try testing.expect(full / diff > 100); -} - -test "detached wire: a run is coalesced across a gap only when that is cheaper" { - const cols: u16 = 8; - const rows: u16 = 1; - var cells: [8]pardes.Cell = @splat(.{}); - var prev: [8]pardes.Cell = @splat(.{}); - var buf: [512]u8 = undefined; - - // Two changes with three UNPAINTED cells between them. Re-sending those is - // three bytes; a second run header is six. One run. - 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 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. - // Eight bytes to re-send against six for a header: two runs. - const painted: pardes.Cell = .{ .text = "-".* ++ @as([6]u8, @splat(0)), .len = 1, .default = false }; - cells[2] = painted; - prev[2] = painted; - { - 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 encodeFrameLayers(&buf, cols, rows, null, .arrow, &cells, &prev, &.{}, &.{}, &.{}, .{}))).?; - try (try decodeServer(f.tag, f.payload)).frame.apply(&mirror); - try expectGridEqual(&cells, &mirror); -} - -test "detached wire: a truncated frame is refused at every length" { +test "detached wire: a truncated message is refused at every length" { var buf: [4096]u8 = undefined; // Every prefix of a real message. The framing must say "not yet" for the @@ -1659,7 +606,6 @@ test "detached wire: a truncated frame is refused at every length" { 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(@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" { @@ -1667,11 +613,8 @@ test "detached wire: an unknown tag is refused, never guessed" { // the session tags and the input tags. All three are the same answer. for ([_]u8{ 0x00, 0x0f, 0x1f, 0xff }) |tag| { try testing.expectError(error.BadTag, decodeClient(tag, "")); - try testing.expectError(error.BadTag, decodeServer(tag, "")); } - // 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(@backingInt(ServerTag.refuse), &.{0x7f})); + // A tag NESTED in a payload gets the same treatment: a mouse button. try testing.expectError(error.BadTag, decodeClient( @backingInt(ClientTag.mouse), &.{ 0xff, 0x00, 0, 0, 0, 0, 0 }, @@ -1701,140 +644,6 @@ test "detached wire: an over-long length prefix is refused before it is believed 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" { - const cols: u16 = 4; - const rows: u16 = 2; - var grid: [8]pardes.Cell = @splat(.{}); - - // start = 6, count = 4 on an 8-cell grid: the check that matters, and the - // one an `start + count > len` spelling would miss on overflow. - var runs: [10]u8 = undefined; - std.mem.writeInt(u32, runs[0..4], 6, .little); - std.mem.writeInt(u16, runs[4..6], 4, .little); - runs[6] = 1; - const f: Frame = .{ .kind = .diff, .cols = cols, .rows = rows, .cursor = null, .nruns = 1, .runs = runs[0..7] }; - try testing.expectError(error.Overlong, f.apply(&grid)); - - // A start past the end entirely, and the 32-bit wrap. - std.mem.writeInt(u32, runs[0..4], std.math.maxInt(u32) - 1, .little); - std.mem.writeInt(u16, runs[4..6], 4, .little); - try testing.expectError(error.Overlong, (Frame{ - .kind = .diff, - .cols = cols, - .rows = rows, - .cursor = null, - .nruns = 1, - .runs = runs[0..7], - }).apply(&grid)); - - // A zero-length run says nothing and is not something the encoder emits. - std.mem.writeInt(u32, runs[0..4], 0, .little); - std.mem.writeInt(u16, runs[4..6], 0, .little); - try testing.expectError(error.BadValue, (Frame{ - .kind = .diff, - .cols = cols, - .rows = rows, - .cursor = null, - .nruns = 1, - .runs = runs[0..6], - }).apply(&grid)); - - // 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: 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.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. - var small: [4]pardes.Cell = @splat(.{}); - try testing.expectError(error.BadValue, (Frame{ - .kind = .full, - .cols = cols, - .rows = rows, - .cursor = null, - .nruns = 0, - .runs = "", - }).apply(&small)); -} - -test "detached wire: link pointer survives full and unchanged grid frames" { - const cells = [_]pardes.Cell{.{}}; - var buffer: [256]u8 = undefined; - for ([_]pardes.Surface.PointerShape{ .link, .arrow, .link }) |shape| { - for ([_]bool{ true, false }) |full| { - 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); - try std.testing.expectEqual(if (full) FrameKind.full else FrameKind.diff, frame.kind); - if (!full) try std.testing.expectEqual(@as(u32, 0), frame.nruns); - } - } -} - -test "detached wire: a cursor outside the grid is refused, not painted" { - // The one field of a frame a frontend indexes with rather than copies: - // tty.zig moves the terminal's own cursor to `cursor.x`/`cursor.y`, and - // the ESP32-P4 panel writes the cell there. A frame that says 4x2 and puts - // the cursor at (9,0) is an out-of-bounds write in every frontend, so it - // has to be a decode error and not a clamp — a clamped cursor is a wrong - // screen that nobody reports. - const cols: u16 = 4; - const rows: u16 = 2; - var head: [frame_head]u8 = undefined; - for ([_][2]u16{ .{ cols, 0 }, .{ 0, rows }, .{ 0xffff, 0xffff } }) |xy| { - 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.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(@backingInt(ServerTag.frame), w.buffered()), - ); - } - // The last cell IS in the grid, and a frame carrying it decodes. - { - 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.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); - } - // ...and the ENCODER refuses to build one, so a core bug is a dropped - // frame with a log line rather than a frame every frontend hangs up over. - var cells: [8]pardes.Cell = @splat(.{}); - var buf: [512]u8 = undefined; - try testing.expectError( - error.BadValue, - 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, - encodeFrameLayers(&buf, max_cols + 1, 1, null, .arrow, cells[0..0], &.{}, &.{}, &.{}, &.{}, .{}), - ); -} - 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. @@ -1875,28 +684,10 @@ test "detached wire: values a field cannot mean are refused" { std.mem.writeInt(u32, &pinch, @bitCast(std.math.inf(f32)), .little); 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. - { - var grid: [1]pardes.Cell = @splat(.{}); - // default=0, len=1, 'x', fg default, bg default, attrs=0x80, ul, font - var runs = [_]u8{ 0, 0, 0, 0, 1, 0, 0, 1, 'x', 0, 0, 0x80, 0, 0 }; - const f: Frame = .{ .kind = .diff, .cols = 1, .rows = 1, .cursor = null, .nruns = 1, .runs = &runs }; - try testing.expectError(error.BadValue, f.apply(&grid)); - runs[11] = 0; - runs[7] = 8; // len past Cell.text - try testing.expectError(error.BadValue, f.apply(&grid)); - runs[7] = 0; // ...and a grapheme of no bytes at all - try testing.expectError(error.BadValue, f.apply(&grid)); - } } test "detached wire: max_payload bounds every message this protocol can build" { - // The derivation in `max_payload`'s comment, asserted: the worst frame - // this protocol admits fits, so a receiver sized for max_payload can - // always hold one. - try testing.expect(frameBound(max_cols, max_rows) <= max_payload); - // ...and a 4 MiB paste, which is the tty frontend's own cap. + // A 4 MiB paste, which is the tty's own cap, fits. try testing.expect((4 << 20) + header_len + 4 <= max_payload); // A slice past the width of its own length prefix is refused by the // ENCODER, rather than written and rejected at the far end. A command line @@ -1914,47 +705,12 @@ test "detached wire: max_payload bounds every message this protocol can build" { try testing.expectError(error.WriteFailed, encodeClient(&small, .{ .event = .{ .paste = "0123456789" } })); } -test "detached wire carries compact body rows and exact pointer metrics" { - const gpa = std.testing.allocator; - var cells: [8]pardes.Cell = @splat(.{}); +test "detached wire carries exact pointer metrics" { var logical: [12]pardes.Cell = @splat(.{}); - logical[10] = .{ .text = "z".* ++ @as([6]u8, @splat(0)), .len = 1, .default = false }; 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.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 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.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); - 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)); - try std.testing.expect(decoded[0].hasContextBorderAfter(0)); - try std.testing.expect(decoded[0].hasContextBorderAfter(1)); - try std.testing.expectEqualStrings("z", decoded[0].cells[10].grapheme()); - try std.testing.expectEqual(@as(u16, 5), decoded[0].cursor.?.y); - try std.testing.expectEqual(tag.kind, tags[0].kind); - 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.?.x); - try std.testing.expectEqualStrings("z", tags[0].cells[2].grapheme()); 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 } } }; @@ -1965,22 +721,4 @@ test "detached wire carries compact body rows and exact pointer metrics" { try std.testing.expectEqualDeep(pointer, mouse.body_hit.?); try std.testing.expectEqualDeep(tag_pointer, mouse.tag_hit.?); 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.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.rows); - try std.testing.expectEqual(@as(usize, 0), item.cells.len); - } - 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, ®ions, &chrome); - try std.testing.expectEqual(@as(u16, 0), decoded[0].rows); } -- cgit v1.3