summaryrefslogtreecommitdiff
path: root/src/detached/wire.zig
diff options
context:
space:
mode:
authorGabriel Schneider <[email protected]>2026-10-29 10:48:56 -0300
committerGabriel Schneider <[email protected]>2026-10-29 12:01:27 -0300
commit5c23bd8b1bbdbbacd99b11e75d38f7ce1801cd8a (patch)
tree0b5fae621797c2ae243fea4073dc0e1594289ee8 /src/detached/wire.zig
parent4ffe5c93b3087f245f5b57a822ab0ecf41cc085c (diff)
downloadpardes-5c23bd8b1bbdbbacd99b11e75d38f7ce1801cd8a.tar.gz
pardes-5c23bd8b1bbdbbacd99b11e75d38f7ce1801cd8a.zip
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 <[email protected]>
Diffstat (limited to 'src/detached/wire.zig')
-rw-r--r--src/detached/wire.zig1296
1 files changed, 17 insertions, 1279 deletions
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
// ---------------------------------------------------------------------------
@@ -491,367 +199,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) {
@@ -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, &regions, &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, &regions, &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, &regions, &chrome);
- try std.testing.expectEqual(@as(u16, 0), decoded[0].rows);
}