diff options
| author | Gabriel Schneider <[email protected]> | 2026-10-31 06:28:48 -0300 |
|---|---|---|
| committer | Gabriel Schneider <[email protected]> | 2026-10-31 06:28:48 -0300 |
| commit | a479792a1ab2b593642d7f648194bfa23ce01dba (patch) | |
| tree | 96ddee7d879a9084daa07db43b0b7910b072a785 /src/detached/wire.zig | |
| parent | e179cc44fe5060c76a5b00c41e53f11209f5acd9 (diff) | |
| parent | 4c761893e5b3fdae422622cfa02104ab36633045 (diff) | |
| download | pardes-a479792a1ab2b593642d7f648194bfa23ce01dba.tar.gz pardes-a479792a1ab2b593642d7f648194bfa23ce01dba.zip | |
Merge the upstream daemon and replicated client/server refactor
Diffstat (limited to 'src/detached/wire.zig')
| -rw-r--r-- | src/detached/wire.zig | 1618 |
1 files changed, 308 insertions, 1310 deletions
diff --git a/src/detached/wire.zig b/src/detached/wire.zig index 0e141686..337211b7 100644 --- a/src/detached/wire.zig +++ b/src/detached/wire.zig @@ -1,32 +1,67 @@ -//! Detached input and frames use fixed-width little-endian fields and explicit tags. -//! Native struct layout never reaches the wire. +//! The framed stream a replica speaks (docs/next-daemon.md, phase 5), on +//! the daemon's `pardes-replica.sock` and then its session's: fixed-width +//! little-endian fields and explicit tags, the hello and its version, a +//! ping, 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 builtin = @import("builtin"); 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; +const config = @import("pardes_config"); -/// 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; +/// 19: a client joining again names the view it had in its hello, and a +/// bye says whether it joins again for it (views.away); +/// 18: a replica's input is stamped with its guess of the session's +/// clocks, the time its step reads (phase 6's instant interaction notes); +/// 17: a pointer's hit carries the place it was made on (Layer.Place) and +/// a tag hit its line, which the step resolves it by, not by its frame; +/// 16: a far client says so, the session sends it its blobs' hashes before +/// the rest and only the blobs it asks for, all of it in zstd (phase 6's +/// content cache and zstd notes), and a client says its frontend (a window +/// or a terminal) as its first input, a window replicating a terminal's +/// session and back (phase 6's GUI replica notes); 15: the session streams +/// a replica its dump and units, and terminal deltas both ways (phase 5 +/// part B); 14: the hello names a session and +/// carries the semantics hash, and a ping is answered (phase 5's +/// groundwork); 13: the frames went (phase 3). +pub const version: u16 = 19; -/// 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()})); -} +/// The terminal's build and the window's step alike (`semantics`). +const family = switch (config.platform) { + .tty, .gui => "desktop", + else => @tagName(config.platform), +}; + +/// What makes two cores step differently, hashed: a replica's hello carries +/// its own, and one of another build is refused. The protocol, the release +/// and commit, the platform and build options, every dependency's content +/// hash (grammars, ghostty, Unicode), the walker codec's assumptions +/// (pointer width, byte order) and the tape's shape (tape.shape: what each +/// input and each answer of the host's is laid out as). Not the OS: a Linux +/// client of a FreeBSD session is the main case, and what differs there is +/// the host's, taped, in a shape every OS shares (an error by its name, a +/// stat as fs.OsStat). Nor the build mode: a Debug build steps as a +/// release one does (regexp.zig's one budget). +/// Nor the terminal's build against the window's: their cores step alike, +/// the GUI's own words by the view's frontend (builtins.zig `here`), so a +/// window replicates a terminal's session and a terminal a window's. +/// ponytail: an unstamped build (Debug with -Dplatform, every test build) +/// has no commit, so two dev trees of one release are told apart only by +/// their options and dependencies; -Dstamp-commit stamps one. +pub const semantics: u64 = blk: { + @setEvalBranchQuota(1_000_000); + break :blk std.hash.Wyhash.hash(0, std.fmt.comptimePrint( + "wire {d}\npardes {s} {s}\n{s} grammars {} {} {} {} mupdf {} themes {} workspace_tag {} sources {} board {d}x{d}\nusize {d} {t}\n{s}\n{s}", + .{ + version, config.version, config.commit orelse "unstamped", + family, config.syntax_highlighting, config.syntax_zig_grammar, + config.syntax_minimal_grammars, config.syntax_full_grammars, config.mupdf, + config.theme_animation, config.workspace_tag, config.embed_sources, + config.esp32p4_cols, config.esp32p4_rows, @sizeOf(usize), + builtin.cpu.arch.endian(), config.deps, pardes.tape.shape, + }, + )); +}; /// 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,20 +73,26 @@ 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, bye = 0x02, + ping = 0x03, + /// A replica's word about a terminal's state (src/screen_state.zig): the + /// delta it holds, or rows it asks for. Opaque here. + screen_ack = 0x04, + /// What is the session's digest, in stream order (a replica checks + /// itself against it once quiet). + check = 0x05, + /// A client's first word after its hello: whether it is far (through + /// ssh), so that it holds blobs by their hash and reads zstd. + far = 0x06, + /// The join's blobs a far client lacks, a bit each in `blobs` order. + want = 0x07, + /// The session's clocks (realtime and monotonic, ns) as the client + /// guessed them for the input that follows: its time, which the step + /// reads (src/replica.zig). + stamp = 0x08, key = 0x10, mouse = 0x11, @@ -63,45 +104,10 @@ pub const ClientTag = enum(u8) { touch_scroll = 0x1c, pointer_leave = 0x1d, focus = 0x1e, + /// Which frontend the client is: a window, or a terminal. + frontend = 0x20, }; -// 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 +122,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,12 +131,126 @@ 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. - cols: u16, - rows: u16, + /// The client's `semantics`: the daemon refuses it unless the session's + /// is the same. + semantics: u64 = semantics, + /// Which session (its 9P name, as `--attach=` names it). + session: []const u8, + /// The view it had, joining again for it (a divergence's rejoin, an + /// Upgrade's): the daemon hands it on with the connection. 0xff: none. + view: ?u8 = null, +}; + +/// A session's name on the wire, as the daemon keeps it. +pub const max_name = 128; +/// The longest hello there is, header and all. +pub const hello_max = header_len + 2 + 8 + 2 + max_name + 1; + +/// Daemon or session -> client. +pub const ServerTag = enum(u8) { + /// The hello is accepted and the connection is the session's now: its pid + /// and name. + welcome = 0x01, + /// Refused, said in words; the connection ends. + refused = 0x02, + /// A ping's value back. + pong = 0x03, + /// A piece of the join's dump (src/dump.zig): the welcome says how long + /// it is whole. + dump = 0x04, + /// A unit of the authority's stream (src/replica.zig): its origin, seq, + /// clocks and tape. + unit = 0x05, + /// A terminal's delta, or rows asked for (src/screen_state.zig), applied + /// before the next unit. Opaque here. + screen = 0x06, + /// The session's digest (u64le), after every unit before it. + check = 0x07, + /// Part of the join's list of blobs, to a far client: each one's place + /// in the state, its length and its BLAKE3 hash (src/replica.zig). + blobs = 0x08, + /// A piece of a far client's stream from here on, zstd-compressed: the + /// messages in it are framed as these are. Opaque here. + zstd = 0x09, +}; + +pub const ServerMsg = union(ServerTag) { + /// Who the client is now (its id and view in the session), how long the + /// dump that follows is, and the session's offset from UTC (a replica + /// guesses the session's time of day). A far client is told how many + /// blobs the dump holds (`blobs`). + welcome: struct { pid: u32, session: []const u8, client: u16 = 0, view: u8 = 0, dump_len: u64 = 0, gmtoff: i32 = 0, digest: u64 = 0, semantics: u64 = 0, blobs: u32 = 0 }, + refused: []const u8, + pong: u64, + dump: []const u8, + unit: []const u8, + screen: []const u8, + check: u64, + blobs: []const u8, + zstd: []const u8, }; +/// A message's header, for a payload sent on its own (a unit, a dump's +/// piece): no copy of it into a message buffer. +pub fn header(tag: u8, len: usize) [header_len]u8 { + var h: [header_len]u8 = undefined; + h[0] = tag; + std.mem.writeInt(u32, h[1..5], @intCast(len), .little); + return h; +} + +/// The other way: what a client is told, its slices borrowing `payload`. +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 = .{ + .pid = try r.takeInt(u32, .little), + .session = try r.take(try r.takeInt(u16, .little)), + .client = try r.takeInt(u16, .little), + .view = try r.takeByte(), + .dump_len = try r.takeInt(u64, .little), + .gmtoff = try r.takeInt(i32, .little), + .digest = try r.takeInt(u64, .little), + .semantics = try r.takeInt(u64, .little), + .blobs = try r.takeInt(u32, .little), + } }, + .refused => .{ .refused = try r.take(try r.takeInt(u16, .little)) }, + .pong => .{ .pong = try r.takeInt(u64, .little) }, + .dump => return .{ .dump = payload }, + .unit => return .{ .unit = payload }, + .screen => return .{ .screen = payload }, + .check => .{ .check = try r.takeInt(u64, .little) }, + .blobs => return .{ .blobs = payload }, + .zstd => return .{ .zstd = payload }, + }; + try end(&r); + return msg; +} + +pub fn encodeServer(out: []u8, msg: ServerMsg) Error![]const u8 { + var w: std.Io.Writer = .fixed(out); + const at = try beginMessage(&w, @backingInt(std.meta.activeTag(msg))); + switch (msg) { + .welcome => |h| { + try w.writeInt(u32, h.pid, .little); + try putSlice16(&w, h.session); + try w.writeInt(u16, h.client, .little); + try w.writeByte(h.view); + try w.writeInt(u64, h.dump_len, .little); + try w.writeInt(i32, h.gmtoff, .little); + try w.writeInt(u64, h.digest, .little); + try w.writeInt(u64, h.semantics, .little); + try w.writeInt(u32, h.blobs, .little); + }, + .refused => |words| try putSlice16(&w, words), + .pong => |v| try w.writeInt(u64, v, .little), + .dump, .unit, .screen, .blobs, .zstd => |bytes| try w.writeAll(bytes), + .check => |v| try w.writeInt(u64, v, .little), + } + try finishMessage(&w, at); + return w.buffered(); +} + /// `Hello.version` alone, read out of the still-undecoded payload. /// /// Separate from `decodeClient` because of the guarantee the fixed offset above @@ -166,223 +268,23 @@ 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. pub const ClientMsg = union(enum) { hello: Hello, - bye, + /// The client's end: `again`, it joins again for its view at once. + bye: struct { again: bool = false }, + /// A round trip's probe, answered `pong` with the same value. + ping: u64, + screen_ack: []const u8, + check, + far: bool, + want: []const u8, + stamp: [2]i64, 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 // --------------------------------------------------------------------------- @@ -491,367 +393,12 @@ pub fn framed(buf: []const u8) Error!?Framed { } // --------------------------------------------------------------------------- -// 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) { @@ -885,6 +432,17 @@ fn getMetrics(r: *std.Io.Reader) Error!?pardes.RowMetrics { return m; } +fn putPlace(w: *std.Io.Writer, at: pardes.Layer.Place) Error!void { + for ([_]u16{ at.viewport.x, at.viewport.y, at.viewport.w, at.viewport.h, at.cols, at.rows, at.context_rows }) |n| try w.writeInt(u16, n, .little); +} + +fn getPlace(r: *std.Io.Reader) Error!pardes.Layer.Place { + var n: [7]u16 = undefined; + for (&n) |*x| x.* = try r.takeInt(u16, .little); + if (n[6] > n[5]) return error.BadValue; + return .{ .viewport = .{ .x = n[0], .y = n[1], .w = n[2], .h = n[3] }, .cols = n[4], .rows = n[5], .context_rows = n[6] }; +} + fn putBodyHit(w: *std.Io.Writer, hit: ?pardes.Mouse.BodyHit) Error!void { try w.writeByte(@intFromBool(hit != null)); if (hit) |h| { @@ -894,12 +452,13 @@ fn putBodyHit(w: *std.Io.Writer, hit: ?pardes.Mouse.BodyHit) Error!void { try w.writeInt(u32, @bitCast(h.pixel_x), .little); try w.writeInt(u32, @bitCast(h.pixel_y), .little); try putMetrics(w, h.metrics); + try putPlace(w, h.place); } } fn getBodyHit(r: *std.Io.Reader) Error!?pardes.Mouse.BodyHit { if (!try getBool(r)) return null; - const hit: pardes.Mouse.BodyHit = .{ .serial = try r.takeInt(u32, .little), .row = try r.takeInt(u16, .little), .col = try r.takeInt(u16, .little), .pixel_x = try getF32(r), .pixel_y = try getF32(r), .metrics = (try getMetrics(r)) orelse return error.BadValue }; + const hit: pardes.Mouse.BodyHit = .{ .serial = try r.takeInt(u32, .little), .row = try r.takeInt(u16, .little), .col = try r.takeInt(u16, .little), .pixel_x = try getF32(r), .pixel_y = try getF32(r), .metrics = (try getMetrics(r)) orelse return error.BadValue, .place = try getPlace(r) }; if (!std.math.isFinite(hit.pixel_x) or !std.math.isFinite(hit.pixel_y)) return error.BadValue; return hit; } @@ -911,9 +470,11 @@ fn putTagHit(w: *std.Io.Writer, hit: ?pardes.TagHit) Error!void { try w.writeInt(u16, h.id, .little); try w.writeInt(u32, h.serial, .little); try w.writeInt(u16, h.col, .little); + try w.writeInt(u16, h.line, .little); try w.writeInt(u32, @bitCast(h.pixel_x), .little); try w.writeInt(u32, @bitCast(h.pixel_y), .little); try putMetrics(w, h.metrics); + try putPlace(w, h.place); } } @@ -924,9 +485,11 @@ fn getTagHit(r: *std.Io.Reader) Error!?pardes.TagHit { .id = try r.takeInt(u16, .little), .serial = try r.takeInt(u32, .little), .col = try r.takeInt(u16, .little), + .line = try r.takeInt(u16, .little), .pixel_x = try getF32(r), .pixel_y = try getF32(r), .metrics = (try getMetrics(r)) orelse return error.BadValue, + .place = try getPlace(r), }; if (!std.math.isFinite(hit.pixel_x) or !std.math.isFinite(hit.pixel_y)) return error.BadValue; return hit; @@ -938,10 +501,17 @@ pub fn encodeClient(out: []u8, msg: ClientMsg) Error![]const u8 { switch (msg) { .hello => |h| { try w.writeInt(u16, h.version, .little); - try w.writeInt(u16, h.cols, .little); - try w.writeInt(u16, h.rows, .little); + try w.writeInt(u64, h.semantics, .little); + if (h.session.len > max_name) return error.Overlong; + try putSlice16(&w, h.session); + try w.writeByte(h.view orelse 0xff); }, - .bye => {}, + .bye => |b| try w.writeByte(@intFromBool(b.again)), + .ping => |v| try w.writeInt(u64, v, .little), + .screen_ack, .want => |bytes| try w.writeAll(bytes), + .check => {}, + .far => |far| try w.writeByte(@intFromBool(far)), + .stamp => |s| for (s) |v| try w.writeInt(i64, v, .little), .event => |ev| switch (ev) { .key => |k| { try w.writeInt(u32, k.cp, .little); @@ -986,6 +556,11 @@ pub fn encodeClient(out: []u8, msg: ClientMsg) Error![]const u8 { .touch_scroll => |v| try w.writeInt(u32, @bitCast(v), .little), .pointer_leave => {}, .focus => |focused| try w.writeByte(@intFromBool(focused)), + .frontend => |f| { + try w.writeByte(@intFromBool(f.windowed)); + try w.writeByte(@intFromBool(f.native_images)); + try w.writeByte(@intFromBool(f.native_image_patches)); + }, // See `clientTag`: no tag, so nothing to encode. .output, .eof, .exited, .lsp_resp, .pipe_resp, .search, .file_changed, .handed, .tick => unreachable, }, @@ -999,10 +574,24 @@ pub fn decodeClient(tag: u8, payload: []const u8) Error!ClientMsg { const msg: ClientMsg = switch (std.enums.fromInt(ClientTag, tag) orelse return error.BadTag) { .hello => .{ .hello = .{ .version = try r.takeInt(u16, .little), - .cols = try getCols(&r), - .rows = try getRows(&r), + .semantics = try r.takeInt(u64, .little), + .session = blk: { + const n = try r.takeInt(u16, .little); + if (n > max_name) return error.BadValue; + break :blk try r.take(n); + }, + .view = switch (try r.takeByte()) { + 0xff => null, + else => |k| k, + }, } }, - .bye => .bye, + .bye => .{ .bye = .{ .again = try getBool(&r) } }, + .ping => .{ .ping = try r.takeInt(u64, .little) }, + .screen_ack => return .{ .screen_ack = payload }, + .check => .check, + .far => .{ .far = try getBool(&r) }, + .want => return .{ .want = payload }, + .stamp => .{ .stamp = .{ try r.takeInt(i64, .little), try r.takeInt(i64, .little) } }, .key => blk: { const cp = try r.takeInt(u32, .little); // `Key.cp` is a u21, and the specials live in the private-use @@ -1049,91 +638,27 @@ pub fn decodeClient(tag: u8, payload: []const u8) Error!ClientMsg { .touch_scroll => .{ .event = .{ .touch_scroll = try getF32(&r) } }, .pointer_leave => .{ .event = .pointer_leave }, .focus => .{ .event = .{ .focus = try getBool(&r) } }, + .frontend => .{ .event = .{ .frontend = .{ .windowed = try getBool(&r), .native_images = try getBool(&r), .native_image_patches = try getBool(&r) } } }, }; try end(&r); 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, + .hello => |h| h.session.len, + .bye, .ping, .check, .far, .stamp => 0, + .screen_ack, .want => |bytes| bytes.len, .event => |ev| switch (ev) { - .mouse, .resize, .pdf_scroll, .pinch, .touch_scroll, .pointer_leave, .focus => 0, + // Its hits' places (14 bytes each) past the slack. + .mouse => 28, + .resize, .pdf_scroll, .pinch, .touch_scroll, .pointer_leave, .focus, .frontend => 0, .key => |k| k.text.len, .paste => |b| b.len, .command => |line| line.len, @@ -1143,76 +668,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 +688,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; @@ -1251,12 +699,25 @@ test "detached wire: every Event variant round-trips" { try testing.expectEqual(@as(u8, 0x1d), @backingInt(ClientTag.pointer_leave)); { - const got = try roundClient(&buf, .{ .hello = .{ .cols = 80, .rows = 24 } }); + const got = try roundClient(&buf, .{ .hello = .{ .session = "work" } }); try testing.expectEqual(version, got.hello.version); - try testing.expectEqual(@as(u16, 80), got.hello.cols); - try testing.expectEqual(@as(u16, 24), got.hello.rows); + try testing.expectEqual(semantics, got.hello.semantics); + try testing.expectEqualStrings("work", got.hello.session); + } + try testing.expect((try roundClient(&buf, .{ .bye = .{ .again = true } })).bye.again); + try testing.expectEqual(@as(?u8, 2), (try roundClient(&buf, .{ .hello = .{ .session = "work", .view = 2 } })).hello.view); + try testing.expectEqual(@as(u64, 0xfeed_beef_0000_0001), (try roundClient(&buf, .{ .ping = 0xfeed_beef_0000_0001 })).ping); + { + // The other way: framed the same, its tag the ServerTag's number. + const bytes = try encodeServer(&buf, .{ .welcome = .{ .pid = 42, .session = "work" } }); + const f = (try framed(bytes)).?; + try testing.expectEqual(@as(u8, 0x01), f.tag); + try testing.expectEqualSlices(u8, &.{ 42, 0, 0, 0, 4, 0, 'w', 'o', 'r', 'k', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, f.payload); + const back = (try decodeServer(f.tag, f.payload)).welcome; + try testing.expectEqualStrings("work", back.session); + try testing.expectEqual(@as(u32, 42), back.pid); + try testing.expectEqual(@as(u8, 0x03), (try framed(try encodeServer(&buf, .{ .pong = 7 }))).?.tag); } - try testing.expectEqual(ClientMsg.bye, try roundClient(&buf, .bye)); { const key: pardes.Key = .{ .cp = pardes.Key.page_down, .text = "ü", .ctrl = true, .alt = false, .shift = true }; @@ -1311,50 +772,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; @@ -1367,20 +784,27 @@ test "detached wire: a session is never told to do a frontend's remembering" { // Adding a name here is meant to be an ARGUMENT, not a formality, and the // bar is one sentence: A HUMAN DID IT. A keystroke, a click, a pinch, a // window resized, a paste, a command line executed, a pointer leaving the - // window, the window's focus — plus the two session words that say who is speaking. A pty's + // window, the window's focus — plus the session words that say who is speaking, time the link and end it. A pty's // output, a worker's answer, a watched file's new bytes and an animation // tick all fail that bar the same way: nobody did them, a machine reported // them, and the machine that reports them is the one already holding the // core. const allowed = [_][]const u8{ - // Who this connection is, and that it is finished. - "hello", "bye", + // Who this connection is, its round trip, and that it is finished, + // and which terminal state its replica holds (a protocol's word, + // as a ping is). + "hello", "bye", "ping", "screen_ack", "check", + // ...and how far it is, and which of the join's blobs it lacks. + "far", "want", + // ...and when its next input was, by the session's clocks. + "stamp", // ...and everything a person can do to a window. - "key", "mouse", - "resize", "paste", - "command", "pdf_scroll", - "pinch", "touch_scroll", + "key", "mouse", "resize", + "paste", "command", "pdf_scroll", "pinch", "touch_scroll", "pointer_leave", "focus", + // ...and which of its frontends the person sits at: a window, or a + // terminal (what the view draws, and the words it takes). + "frontend", }; // One: the tag set is exactly that, named rather than counted, so @@ -1422,223 +846,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 +867,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 +874,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 +905,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. @@ -1854,18 +924,17 @@ test "detached wire: values a field cannot mean are refused" { @backingInt(ClientTag.pdf_scroll), &.{pardes.MAX_PANES}, )); - // A zero-column grid would collapse a shared session; an over-wide one is - // past what this protocol carries. - try testing.expectError(error.BadValue, decodeClient( - @backingInt(ClientTag.hello), - &.{ 1, 0, 0, 0, 24, 0 }, - )); + // A session name longer than the daemon keeps one: refused, never cut + // to another session's name. { - var hello: [6]u8 = undefined; + var hello: [12 + max_name + 1]u8 = @splat('x'); std.mem.writeInt(u16, hello[0..2], version, .little); - std.mem.writeInt(u16, hello[2..4], max_cols + 1, .little); - std.mem.writeInt(u16, hello[4..6], 24, .little); + std.mem.writeInt(u16, hello[10..12], max_name + 1, .little); try testing.expectError(error.BadValue, decodeClient(@backingInt(ClientTag.hello), &hello)); + std.mem.writeInt(u16, hello[10..12], max_name, .little); + hello[hello.len - 1] = 0xff; + try testing.expectEqual(@as(usize, max_name), (try decodeClient(@backingInt(ClientTag.hello), &hello)).hello.session.len); + try testing.expect(header_len + hello.len == hello_max); } // A NaN scroll distance. `pinch` multiplies into a zoom the pane keeps. { @@ -1875,28 +944,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 +965,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 +981,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); } |
