diff options
Diffstat (limited to 'src/detached/wire.zig')
| -rw-r--r-- | src/detached/wire.zig | 1096 |
1 files changed, 603 insertions, 493 deletions
diff --git a/src/detached/wire.zig b/src/detached/wire.zig index 245bc9f4..0e141686 100644 --- a/src/detached/wire.zig +++ b/src/detached/wire.zig @@ -3,10 +3,35 @@ const std = @import("std"); const pardes = @import("../pardes.zig"); const limits = @import("../memory.zig").limits; +const ShaderBuild = @import("../ShaderBuild.zig"); +const Scene = pardes.config.Runtime.Scene; +const ShaderAnimation = pardes.config.Runtime.ShaderAnimation; -pub const version: u16 = 6; +/// 7: tag layers gained the `.notice` kind, so a frame can carry a tag value +/// an older frontend would reject mid-session. The greeting is where that has +/// to be refused, which is what this number is for. +/// 8: one layer type: a tag band carries all its rows (not a layer per +/// line), and a frame carries the core's placed regions after its layers. +pub const version: u16 = 12; -pub const Error = error{ Truncated, Overlong, BadTag, BadValue, Trailing, NoSpace }; +/// The Chrome palette is carried field by field as its declaration lists +/// them, so any change to it changes the wire: bump `version`, then this. +const chrome_layout: u64 = 0xbe608bed776ff502; +comptime { + @setEvalBranchQuota(10_000); + var hash = std.hash.Fnv1a_64.init(); + const info = @typeInfo(pardes.Chrome).@"struct"; + for (info.field_names, info.field_types) |name, T| { + hash.update(name); + hash.update(@typeName(T)); + } + if (hash.final() != chrome_layout) @compileError(std.fmt.comptimePrint("pardes.Chrome changed (layout 0x{x}): bump wire.version, then chrome_layout", .{hash.final()})); +} + +/// EndOfStream: the message ends early; WriteFailed: no room for it. +/// ReadFailed is in only because std.Io.Reader says so: a fixed one never +/// fails a read. +pub const Error = error{ EndOfStream, ReadFailed, Overlong, BadTag, BadValue, Trailing, WriteFailed }; pub const max_cols: u16 = 512; pub const max_rows: u16 = 128; @@ -37,6 +62,7 @@ pub const ClientTag = enum(u8) { pinch = 0x1b, touch_scroll = 0x1c, pointer_leave = 0x1d, + focus = 0x1e, }; // Session control precedes display-local effects. @@ -55,6 +81,9 @@ pub const ServerTag = enum(u8) { set_clipboard = 0x10, read_clipboard = 0x11, open_link = 0x12, + /// The post chain this frontend draws its frames through: sent on + /// attach and whenever it or a file's SPIR-V changes. + post = 0x13, }; /// Why the server hung up on a connect. Sent as a `refuse` and followed by a @@ -133,8 +162,8 @@ pub const Hello = struct { /// An error rather than a zero on a payload shorter than two bytes, so a /// truncated hello stays diagnosable too instead of reading as version 0. pub fn helloVersion(payload: []const u8) Error!u16 { - var r: Reader = .init(payload); - return r.getU16(); + var r: std.Io.Reader = .fixed(payload); + return r.takeInt(u16, .little); } pub const Welcome = struct { @@ -164,7 +193,9 @@ pub const Frame = struct { nruns: u32, runs: []const u8, - pub fn applyLayers(f: Frame, gpa: std.mem.Allocator, layers: *[pardes.MAX_PANES]pardes.BodyLayer, tags: *[pardes.MAX_TAG_LAYERS]pardes.TagLayer) !void { + pub fn applyLayers(f: Frame, gpa: std.mem.Allocator, layers: *[pardes.MAX_PANES]pardes.Layer, tags: *[pardes.MAX_TAG_LAYERS]pardes.Layer, regions: *std.ArrayListUnmanaged(pardes.Region), chrome: *pardes.Chrome) !void { + regions.clearRetainingCapacity(); + chrome.* = .{}; for (layers) |*layer| { gpa.free(layer.cells); layer.* = .{}; @@ -182,52 +213,105 @@ pub const Frame = struct { gpa.free(layer.cells); layer.* = .{}; } + regions.clearRetainingCapacity(); + chrome.* = .{}; } if (f.layers.len == 0) return; - var r: Reader = .init(f.layers); - const count = try r.getU16(); + var r: std.Io.Reader = .fixed(f.layers); + const count = try r.takeInt(u16, .little); if (count > layers.len) return error.Overlong; for (layers[0..count]) |*layer| { - layer.pane = try r.getU16(); - layer.serial = try r.getU32(); - layer.viewport = .{ .x = try r.getU16(), .y = try r.getU16(), .w = try r.getU16(), .h = try r.getU16() }; - layer.cols = try r.getU16(); - layer.rows = try r.getU16(); - layer.context_rows = try r.getU16(); - if (layer.pane >= pardes.MAX_PANES or layer.cols == 0 or layer.cols > f.cols or + layer.kind = .body; + layer.id = try r.takeInt(u16, .little); + layer.serial = try r.takeInt(u32, .little); + layer.viewport = .{ .x = try r.takeInt(u16, .little), .y = try r.takeInt(u16, .little), .w = try r.takeInt(u16, .little), .h = try r.takeInt(u16, .little) }; + layer.cols = try r.takeInt(u16, .little); + layer.rows = try r.takeInt(u16, .little); + layer.context_rows = try r.takeInt(u16, .little); + if (layer.id >= pardes.MAX_PANES or layer.cols == 0 or layer.cols > f.cols or layer.rows == 0 or layer.rows > 2 * max_rows or layer.context_rows > layer.rows or layer.context_rows > limits.wrap_rows or layer.viewport.x > f.cols or layer.viewport.w > f.cols - layer.viewport.x or layer.viewport.y > f.rows or layer.viewport.h > f.rows - layer.viewport.y) return error.BadValue; for (0..layer.context_rows) |row| { - if (try r.getBool()) layer.context_separators.set(row); + if (try getBool(&r)) layer.context_separators.set(row); } const cursor = try getCursor(&r, layer.cols, layer.rows); layer.cursor = if (cursor) |c| .{ .x = c.x, .y = c.y, .bar = c.bar } else null; layer.cells = try gpa.alloc(pardes.Cell, @as(usize, layer.cols) * layer.rows); for (layer.cells) |*cell| cell.* = try decodeCell(&r); } - const tag_count = try r.getU16(); + const tag_count = try r.takeInt(u16, .little); if (tag_count > tags.len) return error.Overlong; for (tags[0..tag_count]) |*layer| { - layer.kind = try r.getTag(pardes.TagKind); - layer.id = try r.getU16(); - layer.serial = try r.getU32(); - layer.viewport = .{ .x = try r.getU16(), .y = try r.getU16(), .w = try r.getU16(), .h = try r.getU16() }; - layer.cols = try r.getU16(); - for (&layer.bg) |*channel| channel.* = try r.getByte(); - if (layer.cols == 0 or layer.viewport.w == 0 or layer.viewport.h != 1 or + layer.kind = try getTag(&r, pardes.TagKind); + layer.id = try r.takeInt(u16, .little); + layer.serial = try r.takeInt(u32, .little); + layer.viewport = .{ .x = try r.takeInt(u16, .little), .y = try r.takeInt(u16, .little), .w = try r.takeInt(u16, .little), .h = try r.takeInt(u16, .little) }; + layer.cols = try r.takeInt(u16, .little); + layer.rows = try r.takeInt(u16, .little); + for (&layer.bg) |*channel| channel.* = try r.takeByte(); + if (layer.cols == 0 or layer.viewport.w == 0 or layer.rows == 0 or layer.rows > pardes.MAX_TAG_ROWS or + layer.viewport.h != layer.rows or layer.viewport.x > f.cols or layer.viewport.w > f.cols - layer.viewport.x or - layer.viewport.y >= f.rows or (switch (layer.kind) { + layer.viewport.y >= f.rows or layer.viewport.h > f.rows - layer.viewport.y or (switch (layer.kind) { .workspace => layer.id != 0, .column => layer.id >= pardes.MAX_COLS, - .pane => layer.id >= pardes.MAX_PANES, + .pane, .notice => layer.id >= pardes.MAX_PANES, + .body => true, })) return error.BadValue; - const cursor = try getCursor(&r, layer.cols, 1); - layer.cursor = if (cursor) |c| .{ .col = c.x, .bar = c.bar } else null; - layer.cells = try gpa.alloc(pardes.Cell, layer.cols); + const cursor = try getCursor(&r, layer.cols, layer.rows); + layer.cursor = if (cursor) |c| .{ .x = c.x, .y = c.y, .bar = c.bar } else null; + layer.cells = try gpa.alloc(pardes.Cell, @as(usize, layer.cols) * layer.rows); for (layer.cells) |*cell| cell.* = try decodeCell(&r); } - try r.end(); + const region_count = try r.takeInt(u16, .little); + if (region_count > pardes.MAX_REGIONS) return error.Overlong; + try regions.ensureTotalCapacity(gpa, region_count); + for (0..region_count) |_| { + var region: pardes.Region = .{ .kind = try getTag(&r, pardes.Region.Kind), .rect = undefined }; + region.owner = try r.takeByte(); + region.serial = try r.takeInt(u32, .little); + region.rect = .{ .x = try r.takeInt(u16, .little), .y = try r.takeInt(u16, .little), .w = try r.takeInt(u16, .little), .h = try r.takeInt(u16, .little) }; + const flags = try r.takeByte(); + if (flags > 3) return error.BadValue; + region.active = flags & 1 != 0; + region.dirty = flags & 2 != 0; + region.thumb_y = try r.takeInt(u16, .little); + region.thumb_h = try r.takeInt(u16, .little); + region.notice = try r.takeByte(); + region.clip = try r.takeInt(u16, .little); + region.lift = @bitCast(try r.takeInt(u32, .little)); + region.line = @bitCast(try r.takeInt(u32, .little)); + // A springy flavour overshoots, and a wind-up dips below. + if (!(region.lift >= -1 and region.lift <= 2)) return error.BadValue; + if (region.rect.x > f.cols or region.rect.w > f.cols - region.rect.x or + region.rect.y > f.rows or region.rect.h > f.rows - region.rect.y or + region.clip > region.rect.w or region.thumb_y > region.rect.h or region.thumb_h > region.rect.h - region.thumb_y) return error.BadValue; + regions.appendAssumeCapacity(region); + } + const info = @typeInfo(pardes.Chrome).@"struct"; + inline for (info.field_names, info.field_types) |name, T| { + const rgb = &@field(chrome, name); + if (T == ?[3]u8) { + if (try getBool(&r)) { + rgb.* = .{ 0, 0, 0 }; + for (&rgb.*.?) |*channel| channel.* = try r.takeByte(); + } + } else if (T == u8) { + rgb.* = try r.takeByte(); + } else if (T == u32) { + rgb.* = try r.takeInt(u32, .little); + } else if (T == f32) { + rgb.* = @bitCast(try r.takeInt(u32, .little)); + if (!std.math.isFinite(rgb.*)) return error.BadValue; + } else if (T == [8]f32) { + for (rgb) |*value| { + value.* = @bitCast(try r.takeInt(u32, .little)); + if (!std.math.isFinite(value.*)) return error.BadValue; + } + } else for (rgb) |*channel| channel.* = try r.takeByte(); + } + try end(&r); } /// Paint this frame into `grid`, which must be exactly `cols * rows` cells @@ -239,12 +323,12 @@ pub const Frame = struct { pub fn apply(f: Frame, grid: []pardes.Cell) Error!void { if (grid.len != @as(usize, f.cols) * @as(usize, f.rows)) return error.BadValue; if (f.kind == .full) @memset(grid, .{}); - var r: Reader = .init(f.runs); + var r: std.Io.Reader = .fixed(f.runs); var i: u32 = 0; while (i < f.nruns) : (i += 1) { - const start = try r.getU32(); - const count = try r.getU16(); - // A zero-length run is not something `encodeFrame` emits, and + const start = try r.takeInt(u32, .little); + const count = try r.takeInt(u16, .little); + // A zero-length run is not something `encodeFrameLayers` emits, and // accepting one would let a peer spend the run budget saying // nothing. if (count == 0) return error.BadValue; @@ -254,7 +338,7 @@ pub const Frame = struct { if (start > grid.len or count > grid.len - start) return error.Overlong; for (grid[start..][0..count]) |*c| c.* = try decodeCell(&r); } - try r.end(); + try end(&r); } }; @@ -281,175 +365,115 @@ pub const ServerMsg = union(enum) { set_clipboard: []const u8, read_clipboard, open_link: []const u8, + post: Post, }; -// --------------------------------------------------------------------------- -// primitives -// --------------------------------------------------------------------------- - -pub const Writer = struct { - buf: []u8, - n: usize = 0, - - pub fn init(buf: []u8) Writer { - return .{ .buf = buf }; - } - - pub fn written(w: *const Writer) []const u8 { - return w.buf[0..w.n]; - } - - fn room(w: *Writer, k: usize) Error![]u8 { - if (w.buf.len - w.n < k) return error.NoSpace; - defer w.n += k; - return w.buf[w.n..][0..k]; - } - - fn putByte(w: *Writer, v: u8) Error!void { - (try w.room(1))[0] = v; - } - - fn putU16(w: *Writer, v: u16) Error!void { - std.mem.writeInt(u16, (try w.room(2))[0..2], v, .little); - } - - fn putU32(w: *Writer, v: u32) Error!void { - std.mem.writeInt(u32, (try w.room(4))[0..4], v, .little); - } - - /// One byte, 0 or 1, never "nonzero". `getBool` refuses anything else. - fn putBool(w: *Writer, v: bool) Error!void { - try w.putByte(@intFromBool(v)); - } - - /// IEEE-754 binary32, as its bit pattern in an explicit u32. A scalar - /// bitcast and not a struct blit: the format is the one thing a riscv32 - /// and an x86_64 do agree about. - fn putF32(w: *Writer, v: f32) Error!void { - try w.putU32(@bitCast(v)); - } - - fn putBytes(w: *Writer, v: []const u8) Error!void { - @memcpy(try w.room(v.len), v); - } - - /// Length-prefixed, u16: paths, command lines, a key's text. Nothing here - /// is legitimately longer than 64 KiB and a u16 says so on the wire. - fn putSlice16(w: *Writer, v: []const u8) Error!void { - if (v.len > std.math.maxInt(u16)) return error.Overlong; - try w.putU16(@intCast(v.len)); - try w.putBytes(v); - } +/// The session's post chain, as a GUI attached to it draws it: its passes in +/// order, each a bundled scene at its level or a Shadertoy file's SPIR-V +/// (compiled by the session, ShaderBuild.zig: a frontend reads no disk and +/// runs no program), and when it animates on its own. Slices borrow the +/// payload. +pub const Post = struct { + animation: ShaderAnimation = .on, + passes: [ShaderBuild.max]ShaderBuild.Pass = @splat(.{}), + len: u8 = 0, - /// ...and u32 for the ones that are: pty output, a paste, a file. - fn putSlice32(w: *Writer, v: []const u8) Error!void { - if (v.len > max_payload) return error.Overlong; - try w.putU32(@intCast(v.len)); - try w.putBytes(v); + pub fn list(p: *const Post) []const ShaderBuild.Pass { + return p.passes[0..p.len]; } }; -pub const Reader = struct { - bytes: []const u8, - i: usize = 0, - - pub fn init(bytes: []const u8) Reader { - return .{ .bytes = bytes }; - } - - /// `i <= bytes.len` is the invariant every getter below preserves, which is - /// what makes the subtraction here safe. - fn take(r: *Reader, n: usize) Error![]const u8 { - if (r.bytes.len - r.i < n) return error.Truncated; - defer r.i += n; - return r.bytes[r.i..][0..n]; - } - - fn getByte(r: *Reader) Error!u8 { - return (try r.take(1))[0]; - } - - fn getU16(r: *Reader) Error!u16 { - return std.mem.readInt(u16, (try r.take(2))[0..2], .little); - } +// --------------------------------------------------------------------------- +// primitives +// --------------------------------------------------------------------------- - fn getU32(r: *Reader) Error!u32 { - return std.mem.readInt(u32, (try r.take(4))[0..4], .little); - } +/// Length-prefixed, u16: paths, command lines, a key's text. Nothing here +/// is legitimately longer than 64 KiB and a u16 says so on the wire. +fn putSlice16(w: *std.Io.Writer, v: []const u8) Error!void { + if (v.len > std.math.maxInt(u16)) return error.Overlong; + try w.writeInt(u16, @intCast(v.len), .little); + try w.writeAll(v); +} - fn getBool(r: *Reader) Error!bool { - return switch (try r.getByte()) { - 0 => false, - 1 => true, - else => error.BadValue, - }; - } +/// ...and u32 for the ones that are: pty output, a paste, a file. +fn putSlice32(w: *std.Io.Writer, v: []const u8) Error!void { + if (v.len > max_payload) return error.Overlong; + try w.writeInt(u32, @intCast(v.len), .little); + try w.writeAll(v); +} - fn getF32(r: *Reader) Error!f32 { - const v: f32 = @bitCast(try r.getU32()); - // A NaN or an infinity here is not a scroll distance. `pinch` in - // particular multiplies into a zoom factor the pane keeps, so one bad - // value poisons that pane for the rest of the session. - if (!std.math.isFinite(v)) return error.BadValue; - return v; - } +/// One byte, 0 or 1, never "nonzero": the writer's `@intFromBool`. +fn getBool(r: *std.Io.Reader) Error!bool { + return switch (try r.takeByte()) { + 0 => false, + 1 => true, + else => error.BadValue, + }; +} - fn getSlice16(r: *Reader) Error![]const u8 { - return r.take(try r.getU16()); - } +/// IEEE-754 binary32, as its bit pattern in an explicit u32. A scalar +/// bitcast and not a struct blit: the format is the one thing a riscv32 +/// and an x86_64 do agree about. +fn getF32(r: *std.Io.Reader) Error!f32 { + const v: f32 = @bitCast(try r.takeInt(u32, .little)); + // A NaN or an infinity here is not a scroll distance. `pinch` in + // particular multiplies into a zoom factor the pane keeps, so one bad + // value poisons that pane for the rest of the session. + if (!std.math.isFinite(v)) return error.BadValue; + return v; +} - fn getSlice32(r: *Reader) Error![]const u8 { - const n = try r.getU32(); - if (n > max_payload) return error.Overlong; - return r.take(n); - } +fn getSlice32(r: *std.Io.Reader) Error![]const u8 { + const n = try r.takeInt(u32, .little); + if (n > max_payload) return error.Overlong; + return r.take(n); +} - /// A pane id the core can actually index. `Event.output{ .pane = 200 }` - /// would reach `p.panes[200]`. - fn getPane(r: *Reader) Error!u8 { - const pane = try r.getByte(); - if (pane >= pardes.MAX_PANES) return error.BadValue; - return pane; - } +/// A pane id the core can actually index. `Event.output{ .pane = 200 }` +/// would reach `p.panes[200]`. +fn getPane(r: *std.Io.Reader) Error!u8 { + const pane = try r.takeByte(); + if (pane >= pardes.MAX_PANES) return error.BadValue; + return pane; +} - /// A grid the core can render into. Zero is refused rather than clamped: a - /// frontend that has not been sized yet must not be allowed to collapse a - /// shared session to nothing (see server.zig `geometry`). - fn getCols(r: *Reader) Error!u16 { - const v = try r.getU16(); - if (v == 0 or v > max_cols) return error.BadValue; - return v; - } +/// A grid the core can render into. Zero is refused rather than clamped: a +/// frontend that has not been sized yet must not be allowed to collapse a +/// shared session to nothing (see server.zig `geometry`). +fn getCols(r: *std.Io.Reader) Error!u16 { + const v = try r.takeInt(u16, .little); + if (v == 0 or v > max_cols) return error.BadValue; + return v; +} - fn getRows(r: *Reader) Error!u16 { - const v = try r.getU16(); - if (v == 0 or v > max_rows) return error.BadValue; - return v; - } +fn getRows(r: *std.Io.Reader) Error!u16 { + const v = try r.takeInt(u16, .little); + if (v == 0 or v > max_rows) return error.BadValue; + return v; +} - fn getTag(r: *Reader, comptime T: type) Error!T { - return std.enums.fromInt(T, try r.getByte()) orelse error.BadTag; - } +fn getTag(r: *std.Io.Reader, comptime T: type) Error!T { + return std.enums.fromInt(T, try r.takeByte()) orelse error.BadTag; +} - fn end(r: *Reader) Error!void { - if (r.i != r.bytes.len) return error.Trailing; - } -}; +fn end(r: *std.Io.Reader) Error!void { + if (r.seek != r.end) return error.Trailing; +} /// Reserve a message header; `finishMessage` back-patches the length. Two /// passes would mean walking a frame's runs twice to find out how long they /// are, and the walk is the expensive half. -fn beginMessage(w: *Writer, tag: u8) Error!usize { - const at = w.n; - try w.putByte(tag); - try w.putU32(0); +fn beginMessage(w: *std.Io.Writer, tag: u8) Error!usize { + const at = w.end; + try w.writeByte(tag); + try w.writeInt(u32, 0, .little); return at; } -fn finishMessage(w: *Writer, at: usize) Error!void { - const len = w.n - at - header_len; +fn finishMessage(w: *std.Io.Writer, at: usize) Error!void { + const len = w.end - at - header_len; if (len > max_payload) return error.Overlong; - std.mem.writeInt(u32, w.buf[at + 1 ..][0..4], @intCast(len), .little); + std.mem.writeInt(u32, w.buffer[at + 1 ..][0..4], @intCast(len), .little); } /// One complete message at the front of a stream buffer, or null when the rest @@ -470,24 +494,24 @@ pub fn framed(buf: []const u8) Error!?Framed { // cells // --------------------------------------------------------------------------- -fn putColor(w: *Writer, c: pardes.Color) Error!void { +fn putColor(w: *std.Io.Writer, c: pardes.Color) Error!void { switch (c) { - .default => try w.putByte(@intFromEnum(ColorTag.default)), + .default => try w.writeByte(@backingInt(ColorTag.default)), .index => |i| { - try w.putByte(@intFromEnum(ColorTag.index)); - try w.putByte(i); + try w.writeByte(@backingInt(ColorTag.index)); + try w.writeByte(i); }, .rgb => |v| { - try w.putByte(@intFromEnum(ColorTag.rgb)); - try w.putBytes(&v); + try w.writeByte(@backingInt(ColorTag.rgb)); + try w.writeAll(&v); }, } } -fn getColor(r: *Reader) Error!pardes.Color { - return switch (try r.getTag(ColorTag)) { +fn getColor(r: *std.Io.Reader) Error!pardes.Color { + return switch (try getTag(r, ColorTag)) { .default => .default, - .index => .{ .index = try r.getByte() }, + .index => .{ .index = try r.takeByte() }, .rgb => .{ .rgb = (try r.take(3))[0..3].* }, }; } @@ -506,32 +530,32 @@ const Ul = @FieldType(pardes.CellStyle, "ul"); /// which is the whole property the six hand-written switches this replaced /// existed for, in a form that cannot fall out of step. A variant that has to /// travel under a DIFFERENT name than the core's gets an arm of its own before -/// the `inline else`, exactly as `clientTag` keeps `.fs_req`. -fn putUl(w: *Writer, u: Ul) Error!void { - try w.putByte(switch (u) { - inline else => |t| @intFromEnum(@field(UlTag, @tagName(t))), +/// the `inline else`, exactly as `clientTag` keeps the machine-local reports. +fn putUl(w: *std.Io.Writer, u: Ul) Error!void { + try w.writeByte(switch (u) { + inline else => |t| @backingInt(@field(UlTag, @tagName(t))), }); } -fn getUl(r: *Reader) Error!Ul { - return switch (try r.getTag(UlTag)) { +fn getUl(r: *std.Io.Reader) Error!Ul { + return switch (try getTag(r, UlTag)) { inline else => |t| @field(Ul, @tagName(t)), }; } -fn putFont(w: *Writer, f: pardes.FontRole) Error!void { - try w.putByte(switch (f) { - inline else => |t| @intFromEnum(@field(FontTag, @tagName(t))), +fn putFont(w: *std.Io.Writer, f: pardes.FontRole) Error!void { + try w.writeByte(switch (f) { + inline else => |t| @backingInt(@field(FontTag, @tagName(t))), }); } -fn getFont(r: *Reader) Error!pardes.FontRole { - return switch (try r.getTag(FontTag)) { +fn getFont(r: *std.Io.Reader) Error!pardes.FontRole { + return switch (try getTag(r, FontTag)) { inline else => |t| @field(pardes.FontRole, @tagName(t)), }; } -/// How many bytes `putCell` will write. Exact, because `encodeFrame` weighs it +/// How many bytes `putCell` will write. Exact, because `encodeFrameLayers` weighs it /// against `run_header` to decide whether to coalesce a run across it. fn cellSize(c: *const pardes.Cell) usize { if (c.default) return 1; @@ -547,13 +571,13 @@ fn colorSize(c: pardes.Color) usize { } /// An unpainted cell is ONE byte: `default` means "the shell renders the -/// terminal's default cell" (pardes.zig `Cell`), so its text and style are not +/// terminal's default cell" (surface.zig `Cell`), so its text and style are not /// merely equal to the defaults, they are not part of the frame at all. -fn putCell(w: *Writer, c: *const pardes.Cell) Error!void { - try w.putBool(c.default); +fn putCell(w: *std.Io.Writer, c: *const pardes.Cell) Error!void { + try w.writeByte(@intFromBool(c.default)); if (c.default) return; - try w.putByte(c.len); - try w.putBytes(c.grapheme()); + try w.writeByte(c.len); + try w.writeAll(c.grapheme()); const s = c.style; try putColor(w, s.fg); try putColor(w, s.bg); @@ -565,15 +589,15 @@ fn putCell(w: *Writer, c: *const pardes.Cell) Error!void { if (s.reverse) attrs |= attr_reverse; if (s.invisible) attrs |= attr_invisible; if (s.strikethrough) attrs |= attr_strikethrough; - try w.putByte(attrs); + try w.writeByte(attrs); try putUl(w, s.ul); try putFont(w, s.font_role); } -fn decodeCell(r: *Reader) Error!pardes.Cell { - if (try r.getBool()) return .{}; +fn decodeCell(r: *std.Io.Reader) Error!pardes.Cell { + if (try getBool(r)) return .{}; var c: pardes.Cell = .{ .default = false }; - const len = try r.getByte(); + const len = try r.takeByte(); // `Cell.text` is 7 bytes and `grapheme()` slices to `len`. A zero-length // grapheme is a cell with nothing to draw and no way to advance a column. if (len == 0 or len > c.text.len) return error.BadValue; @@ -581,7 +605,7 @@ fn decodeCell(r: *Reader) Error!pardes.Cell { @memcpy(c.text[0..len], try r.take(len)); c.style.fg = try getColor(r); c.style.bg = try getColor(r); - const attrs = try r.getByte(); + const attrs = try r.takeByte(); if (attrs & attr_reserved != 0) return error.BadValue; c.style.bold = attrs & attr_bold != 0; c.style.dim = attrs & attr_dim != 0; @@ -599,24 +623,24 @@ fn decodeCell(r: *Reader) Error!pardes.Cell { // frames // --------------------------------------------------------------------------- -fn putCursor(w: *Writer, cursor: ?Cursor, cols: u16, rows: u16) Error!void { +fn putCursor(w: *std.Io.Writer, cursor: ?Cursor, cols: u16, rows: u16) Error!void { // Fixed six bytes whether or not there is a cursor. An optional field // would save five bytes on a message that is already hundreds, and cost a // branch on both sides of the wire. - try w.putBool(cursor != null); + try w.writeByte(@intFromBool(cursor != null)); const c = cursor orelse Cursor{ .x = 0, .y = 0, .bar = false }; // Refused here as well as on decode, so this side cannot build a frame its // own decoder rejects: a dropped frame (sendFrame logs it) leaves a stale // screen, and a refused one takes the frontend's connection with it. if (c.x >= cols or c.y >= rows) return error.BadValue; - try w.putU16(c.x); - try w.putU16(c.y); - try w.putBool(c.bar); + try w.writeInt(u16, c.x, .little); + try w.writeInt(u16, c.y, .little); + try w.writeByte(@intFromBool(c.bar)); } -fn getCursor(r: *Reader, cols: u16, rows: u16) Error!?Cursor { - const present = try r.getBool(); - const c: Cursor = .{ .x = try r.getU16(), .y = try r.getU16(), .bar = try r.getBool() }; +fn getCursor(r: *std.Io.Reader, cols: u16, rows: u16) Error!?Cursor { + const present = try getBool(r); + const c: Cursor = .{ .x = try r.takeInt(u16, .little), .y = try r.takeInt(u16, .little), .bar = try getBool(r) }; // THE cursor bounds check. Every other field of a frame is checked against // the grid and these two were not, and they are the two a frontend indexes // with directly — `Surface.at(cursor.x, cursor.y)` on a grid this frame @@ -628,6 +652,22 @@ fn getCursor(r: *Reader, cols: u16, rows: u16) Error!?Cursor { return if (present) c else null; } +pub fn layersBound(layers: []const pardes.Layer, tags: []const pardes.Layer, regions: []const pardes.Region) usize { + var n: usize = 6; + for (layers) |layer| if (layer.rows != 0) { + n += 26 + layer.context_rows + layer.cells.len * cell_max; + }; + for (tags) |layer| if (layer.rows != 0) { + n += 28 + layer.cells.len * cell_max; + }; + return n + regions.len * region_len + chrome_len; +} + +const region_len = 1 + 1 + 4 + 8 + 1 + 2 + 2 + 1 + 2 + 4 + 4; +/// The palette: each colour three bytes, a theme's optional ones a flag +/// before them. +const chrome_len = @typeInfo(pardes.Chrome).@"struct".field_names.len * 4 + 8 * 4; + /// Encode one frame of `cells`, as a DIFF against `prev` when `prev` is the /// same grid this receiver last acknowledged, and as a FULL frame otherwise. /// @@ -649,41 +689,7 @@ fn getCursor(r: *Reader, cols: u16, rows: u16) Error!?Cursor { /// own 56x14 grid with uncoloured cells, where it is exact: 6298 against 56. /// This transport exists for a frontend on the far end of a slow link, and /// shipping the Surface every frame would be 3 MiB/s at the animation tick. -pub fn encodeFrame( - out: []u8, - cols: u16, - rows: u16, - cursor: ?Cursor, - cells: []const pardes.Cell, - prev: []const pardes.Cell, -) Error![]const u8 { - return encodeFramePointer(out, cols, rows, cursor, .arrow, cells, prev); -} - -pub fn encodeFramePointer( - out: []u8, - cols: u16, - rows: u16, - cursor: ?Cursor, - pointer_shape: pardes.Surface.PointerShape, - cells: []const pardes.Cell, - prev: []const pardes.Cell, -) Error![]const u8 { - return encodeFrameLayers(out, cols, rows, cursor, pointer_shape, cells, prev, &.{}, &.{}); -} - -pub fn layersBound(layers: []const pardes.BodyLayer, tags: []const pardes.TagLayer) usize { - var n: usize = 4; - for (layers) |layer| if (layer.rows != 0) { - n += 26 + layer.context_rows + layer.cells.len * cell_max; - }; - for (tags) |layer| if (layer.cols != 0) { - n += 26 + layer.cells.len * cell_max; - }; - return n; -} - -pub fn encodeFrameLayers(out: []u8, cols: u16, rows: u16, cursor: ?Cursor, pointer_shape: pardes.Surface.PointerShape, cells: []const pardes.Cell, prev: []const pardes.Cell, layers: []const pardes.BodyLayer, tags: []const pardes.TagLayer) Error![]const u8 { +pub fn encodeFrameLayers(out: []u8, cols: u16, rows: u16, cursor: ?Cursor, pointer_shape: pardes.Surface.PointerShape, cells: []const pardes.Cell, prev: []const pardes.Cell, layers: []const pardes.Layer, tags: []const pardes.Layer, regions: []const pardes.Region, chrome: pardes.Chrome) Error![]const u8 { // The protocol's ceiling, enforced by the ENCODER too, and BEFORE the // assert below so a caller can be told rather than tripped. `max_payload` // is derived from these two, so a larger grid is a frame this decoder @@ -692,65 +698,99 @@ pub fn encodeFrameLayers(out: []u8, cols: u16, rows: u16, cursor: ?Cursor, point if (cols == 0 or cols > max_cols or rows == 0 or rows > max_rows) return error.Overlong; std.debug.assert(cells.len == @as(usize, cols) * @as(usize, rows)); const full = prev.len != cells.len; - var w: Writer = .init(out); - const at = try beginMessage(&w, @intFromEnum(ServerTag.frame)); + var w: std.Io.Writer = .fixed(out); + const at = try beginMessage(&w, @backingInt(ServerTag.frame)); const header: FrameHeader = if (pointer_shape == .link) (if (full) .full_link else .diff_link) else (if (full) .full else .diff); - try w.putByte(@intFromEnum(header)); - try w.putU16(cols); - try w.putU16(rows); + try w.writeByte(@backingInt(header)); + try w.writeInt(u16, cols, .little); + try w.writeInt(u16, rows, .little); try putCursor(&w, cursor, cols, rows); - const layers_len_at = w.n; - try w.putU32(0); - const layers_start = w.n; - if (layers.len != 0 or tags.len != 0) { + const layers_len_at = w.end; + try w.writeInt(u32, 0, .little); + const layers_start = w.end; + if (layers.len != 0 or tags.len != 0 or regions.len != 0) { var count: u16 = 0; for (layers) |layer| if (layer.rows != 0) { count += 1; }; - try w.putU16(count); + try w.writeInt(u16, count, .little); for (layers) |layer| { if (layer.rows == 0) continue; if (layer.context_rows > limits.wrap_rows or layer.context_rows > layer.rows) return error.BadValue; - try w.putU16(layer.pane); - try w.putU32(layer.serial); - try w.putU16(layer.viewport.x); - try w.putU16(layer.viewport.y); - try w.putU16(layer.viewport.w); - try w.putU16(layer.viewport.h); - try w.putU16(layer.cols); - try w.putU16(layer.rows); - try w.putU16(layer.context_rows); - for (0..layer.context_rows) |row| try w.putBool(layer.context_separators.isSet(row)); + try w.writeInt(u16, layer.id, .little); + try w.writeInt(u32, layer.serial, .little); + try w.writeInt(u16, layer.viewport.x, .little); + try w.writeInt(u16, layer.viewport.y, .little); + try w.writeInt(u16, layer.viewport.w, .little); + try w.writeInt(u16, layer.viewport.h, .little); + try w.writeInt(u16, layer.cols, .little); + try w.writeInt(u16, layer.rows, .little); + try w.writeInt(u16, layer.context_rows, .little); + for (0..layer.context_rows) |row| try w.writeByte(@intFromBool(layer.context_separators.isSet(row))); try putCursor(&w, if (layer.cursor) |c| .{ .x = c.x, .y = c.y, .bar = c.bar } else null, layer.cols, layer.rows); for (layer.cells) |*cell| try putCell(&w, cell); } var tag_count: u16 = 0; - for (tags) |layer| if (layer.cols != 0) { + for (tags) |layer| if (layer.rows != 0) { tag_count += 1; }; - try w.putU16(tag_count); + try w.writeInt(u16, tag_count, .little); for (tags) |layer| { - if (layer.cols == 0) continue; - if (layer.cells.len != layer.cols) return error.BadValue; - try w.putByte(@intFromEnum(layer.kind)); - try w.putU16(layer.id); - try w.putU32(layer.serial); - try w.putU16(layer.viewport.x); - try w.putU16(layer.viewport.y); - try w.putU16(layer.viewport.w); - try w.putU16(layer.viewport.h); - try w.putU16(layer.cols); - for (layer.bg) |channel| try w.putByte(channel); - try putCursor(&w, if (layer.cursor) |c| .{ .x = c.col, .y = 0, .bar = c.bar } else null, layer.cols, 1); + if (layer.rows == 0) continue; + if (layer.cells.len != @as(usize, layer.cols) * layer.rows) return error.BadValue; + try w.writeByte(@backingInt(layer.kind)); + try w.writeInt(u16, layer.id, .little); + try w.writeInt(u32, layer.serial, .little); + try w.writeInt(u16, layer.viewport.x, .little); + try w.writeInt(u16, layer.viewport.y, .little); + try w.writeInt(u16, layer.viewport.w, .little); + try w.writeInt(u16, layer.viewport.h, .little); + try w.writeInt(u16, layer.cols, .little); + try w.writeInt(u16, layer.rows, .little); + for (layer.bg) |channel| try w.writeByte(channel); + try putCursor(&w, if (layer.cursor) |c| .{ .x = c.x, .y = c.y, .bar = c.bar } else null, layer.cols, layer.rows); for (layer.cells) |*cell| try putCell(&w, cell); } + try w.writeInt(u16, @intCast(regions.len), .little); + for (regions) |region| { + try w.writeByte(@backingInt(region.kind)); + try w.writeByte(region.owner); + try w.writeInt(u32, region.serial, .little); + try w.writeInt(u16, region.rect.x, .little); + try w.writeInt(u16, region.rect.y, .little); + try w.writeInt(u16, region.rect.w, .little); + try w.writeInt(u16, region.rect.h, .little); + try w.writeByte(@as(u8, @intFromBool(region.active)) | @as(u8, @intFromBool(region.dirty)) << 1); + try w.writeInt(u16, region.thumb_y, .little); + try w.writeInt(u16, region.thumb_h, .little); + try w.writeByte(region.notice); + try w.writeInt(u16, region.clip, .little); + try w.writeInt(u32, @bitCast(region.lift), .little); + try w.writeInt(u32, @bitCast(region.line), .little); + } + const info = @typeInfo(pardes.Chrome).@"struct"; + inline for (info.field_names, info.field_types) |name, T| { + const rgb = @field(chrome, name); + if (T == ?[3]u8) { + try w.writeByte(@intFromBool(rgb != null)); + if (rgb) |value| for (value) |channel| try w.writeByte(channel); + } else if (T == u8) { + try w.writeByte(rgb); + } else if (T == u32) { + try w.writeInt(u32, rgb, .little); + } else if (T == f32) { + try w.writeInt(u32, @bitCast(rgb), .little); + } else if (T == [8]f32) { + for (rgb) |value| try w.writeInt(u32, @bitCast(value), .little); + } else for (rgb) |channel| try w.writeByte(channel); + } } - std.mem.writeInt(u32, w.buf[layers_len_at..][0..4], @intCast(w.n - layers_start), .little); - const nruns_at = w.n; - try w.putU32(0); + std.mem.writeInt(u32, w.buffer[layers_len_at..][0..4], @intCast(w.end - layers_start), .little); + const nruns_at = w.end; + try w.writeInt(u32, 0, .little); var nruns: u32 = 0; var i: usize = 0; @@ -787,15 +827,15 @@ pub fn encodeFrameLayers(out: []u8, cols: u16, rows: u16, cursor: ?Cursor, point if (j >= cells.len or gap >= run_header) break; i = j; } - try w.putU32(@intCast(start)); - try w.putU16(@intCast(run_end - start)); + try w.writeInt(u32, @intCast(start), .little); + try w.writeInt(u16, @intCast(run_end - start), .little); for (cells[start..run_end]) |*c| try putCell(&w, c); nruns += 1; i = run_end; } - std.mem.writeInt(u32, w.buf[nruns_at..][0..4], nruns, .little); + std.mem.writeInt(u32, w.buffer[nruns_at..][0..4], nruns, .little); try finishMessage(&w, at); - return w.written(); + return w.buffered(); } fn sendCell(cells: []const pardes.Cell, prev: []const pardes.Cell, full: bool, i: usize) bool { @@ -816,7 +856,7 @@ fn clientTag(msg: ClientMsg) ClientTag { return switch (msg) { .event => |ev| switch (ev) { // Machine-local reports and 9P requests belong to the session owner. - .output, .eof, .lsp_resp, .pipe_resp, .file_changed, .tick, .fs_req => unreachable, + .output, .eof, .exited, .lsp_resp, .pipe_resp, .search, .file_changed, .handed, .tick => unreachable, inline else => |_, t| @field(ClientTag, @tagName(t)), }, inline else => |_, t| @field(ClientTag, @tagName(t)), @@ -828,64 +868,64 @@ fn clientTag(msg: ClientMsg) ClientTag { /// WIRE is not. const has_cell_pixels = @hasField(pardes.CellPixels, "w"); -fn putMetrics(w: *Writer, metrics: ?pardes.RowMetrics) Error!void { - try w.putBool(metrics != null); +fn putMetrics(w: *std.Io.Writer, metrics: ?pardes.RowMetrics) Error!void { + try w.writeByte(@intFromBool(metrics != null)); if (metrics) |m| { - try w.putU16(m.body_w); - try w.putU16(m.body_h); - try w.putU16(m.tagline_w); - try w.putU16(m.tagline_h); + try w.writeInt(u16, m.body_w, .little); + try w.writeInt(u16, m.body_h, .little); + try w.writeInt(u16, m.tagline_w, .little); + try w.writeInt(u16, m.tagline_h, .little); } } -fn getMetrics(r: *Reader) Error!?pardes.RowMetrics { - if (!try r.getBool()) return null; - const m: pardes.RowMetrics = .{ .body_w = try r.getU16(), .body_h = try r.getU16(), .tagline_w = try r.getU16(), .tagline_h = try r.getU16() }; +fn getMetrics(r: *std.Io.Reader) Error!?pardes.RowMetrics { + if (!try getBool(r)) return null; + const m: pardes.RowMetrics = .{ .body_w = try r.takeInt(u16, .little), .body_h = try r.takeInt(u16, .little), .tagline_w = try r.takeInt(u16, .little), .tagline_h = try r.takeInt(u16, .little) }; if (m.body_w == 0 or m.body_h == 0 or m.tagline_w == 0 or m.tagline_h == 0) return error.BadValue; return m; } -fn putBodyHit(w: *Writer, hit: ?pardes.Mouse.BodyHit) Error!void { - try w.putBool(hit != null); +fn putBodyHit(w: *std.Io.Writer, hit: ?pardes.Mouse.BodyHit) Error!void { + try w.writeByte(@intFromBool(hit != null)); if (hit) |h| { - try w.putU32(h.serial); - try w.putU16(h.row); - try w.putU16(h.col); - try w.putF32(h.pixel_x); - try w.putF32(h.pixel_y); + try w.writeInt(u32, h.serial, .little); + try w.writeInt(u16, h.row, .little); + try w.writeInt(u16, h.col, .little); + try w.writeInt(u32, @bitCast(h.pixel_x), .little); + try w.writeInt(u32, @bitCast(h.pixel_y), .little); try putMetrics(w, h.metrics); } } -fn getBodyHit(r: *Reader) Error!?pardes.Mouse.BodyHit { - if (!try r.getBool()) return null; - const hit: pardes.Mouse.BodyHit = .{ .serial = try r.getU32(), .row = try r.getU16(), .col = try r.getU16(), .pixel_x = try r.getF32(), .pixel_y = try r.getF32(), .metrics = (try getMetrics(r)) orelse return error.BadValue }; +fn getBodyHit(r: *std.Io.Reader) Error!?pardes.Mouse.BodyHit { + if (!try getBool(r)) return null; + const hit: pardes.Mouse.BodyHit = .{ .serial = try r.takeInt(u32, .little), .row = try r.takeInt(u16, .little), .col = try r.takeInt(u16, .little), .pixel_x = try getF32(r), .pixel_y = try getF32(r), .metrics = (try getMetrics(r)) orelse return error.BadValue }; if (!std.math.isFinite(hit.pixel_x) or !std.math.isFinite(hit.pixel_y)) return error.BadValue; return hit; } -fn putTagHit(w: *Writer, hit: ?pardes.TagHit) Error!void { - try w.putBool(hit != null); +fn putTagHit(w: *std.Io.Writer, hit: ?pardes.TagHit) Error!void { + try w.writeByte(@intFromBool(hit != null)); if (hit) |h| { - try w.putByte(@intFromEnum(h.kind)); - try w.putU16(h.id); - try w.putU32(h.serial); - try w.putU16(h.col); - try w.putF32(h.pixel_x); - try w.putF32(h.pixel_y); + try w.writeByte(@backingInt(h.kind)); + try w.writeInt(u16, h.id, .little); + try w.writeInt(u32, h.serial, .little); + try w.writeInt(u16, h.col, .little); + try w.writeInt(u32, @bitCast(h.pixel_x), .little); + try w.writeInt(u32, @bitCast(h.pixel_y), .little); try putMetrics(w, h.metrics); } } -fn getTagHit(r: *Reader) Error!?pardes.TagHit { - if (!try r.getBool()) return null; +fn getTagHit(r: *std.Io.Reader) Error!?pardes.TagHit { + if (!try getBool(r)) return null; const hit: pardes.TagHit = .{ - .kind = try r.getTag(pardes.TagKind), - .id = try r.getU16(), - .serial = try r.getU32(), - .col = try r.getU16(), - .pixel_x = try r.getF32(), - .pixel_y = try r.getF32(), + .kind = try getTag(r, pardes.TagKind), + .id = try r.takeInt(u16, .little), + .serial = try r.takeInt(u32, .little), + .col = try r.takeInt(u16, .little), + .pixel_x = try getF32(r), + .pixel_y = try getF32(r), .metrics = (try getMetrics(r)) orelse return error.BadValue, }; if (!std.math.isFinite(hit.pixel_x) or !std.math.isFinite(hit.pixel_y)) return error.BadValue; @@ -893,117 +933,124 @@ fn getTagHit(r: *Reader) Error!?pardes.TagHit { } pub fn encodeClient(out: []u8, msg: ClientMsg) Error![]const u8 { - var w: Writer = .init(out); - const at = try beginMessage(&w, @intFromEnum(clientTag(msg))); + var w: std.Io.Writer = .fixed(out); + const at = try beginMessage(&w, @backingInt(clientTag(msg))); switch (msg) { .hello => |h| { - try w.putU16(h.version); - try w.putU16(h.cols); - try w.putU16(h.rows); + try w.writeInt(u16, h.version, .little); + try w.writeInt(u16, h.cols, .little); + try w.writeInt(u16, h.rows, .little); }, .bye => {}, .event => |ev| switch (ev) { .key => |k| { - try w.putU32(k.cp); - try w.putSlice16(k.text); - try w.putBool(k.ctrl); - try w.putBool(k.alt); - try w.putBool(k.shift); + try w.writeInt(u32, k.cp, .little); + try putSlice16(&w, k.text); + try w.writeByte(@intFromBool(k.ctrl)); + try w.writeByte(@intFromBool(k.alt)); + try w.writeByte(@intFromBool(k.shift)); }, .mouse => |m| { - try w.putByte(switch (m.button) { - inline else => |t| @intFromEnum(@field(ButtonTag, @tagName(t))), + try w.writeByte(switch (m.button) { + inline else => |t| @backingInt(@field(ButtonTag, @tagName(t))), }); - try w.putByte(switch (m.kind) { - inline else => |t| @intFromEnum(@field(KindTag, @tagName(t))), + try w.writeByte(switch (m.kind) { + inline else => |t| @backingInt(@field(KindTag, @tagName(t))), }); - try w.putU16(m.col); - try w.putU16(m.row); - try w.putBool(m.ctrl); + try w.writeInt(u16, m.col, .little); + try w.writeInt(u16, m.row, .little); + try w.writeByte(@intFromBool(m.ctrl)); + try w.writeByte(@intFromBool(m.shift)); + try w.writeByte(@intFromBool(m.alt)); try putBodyHit(&w, m.body_hit); try putTagHit(&w, m.tag_hit); }, .resize => |rs| { - try w.putU16(rs.cols); - try w.putU16(rs.rows); + try w.writeInt(u16, rs.cols, .little); + try w.writeInt(u16, rs.rows, .little); // The conventional 1:2 cell aspect when this build has no // pixels of its own, which is the same default the field // carries where it exists. - try w.putU16(if (comptime has_cell_pixels) rs.cell_pixels.w else 8); - try w.putU16(if (comptime has_cell_pixels) rs.cell_pixels.h else 16); + try w.writeInt(u16, if (comptime has_cell_pixels) rs.cell_pixels.w else 8, .little); + try w.writeInt(u16, if (comptime has_cell_pixels) rs.cell_pixels.h else 16, .little); try putMetrics(&w, rs.row_metrics); }, - .paste => |b| try w.putSlice32(b), - .command => |line| try w.putSlice16(line), + .paste => |b| try putSlice32(&w, b), + .command => |line| try putSlice16(&w, line), .pdf_scroll => |s| { - try w.putByte(s.pane); - try w.putF32(s.delta_pixels); + try w.writeByte(s.pane); + try w.writeInt(u32, @bitCast(s.delta_pixels), .little); + try w.writeByte(@intFromBool(s.glide)); }, - .pinch => |v| try w.putF32(v), - .touch_scroll => |v| try w.putF32(v), + .pinch => |v| try w.writeInt(u32, @bitCast(v), .little), + .touch_scroll => |v| try w.writeInt(u32, @bitCast(v), .little), .pointer_leave => {}, + .focus => |focused| try w.writeByte(@intFromBool(focused)), // See `clientTag`: no tag, so nothing to encode. - .output, .eof, .lsp_resp, .pipe_resp, .file_changed, .tick, .fs_req => unreachable, + .output, .eof, .exited, .lsp_resp, .pipe_resp, .search, .file_changed, .handed, .tick => unreachable, }, } try finishMessage(&w, at); - return w.written(); + return w.buffered(); } pub fn decodeClient(tag: u8, payload: []const u8) Error!ClientMsg { - var r: Reader = .init(payload); + var r: std.Io.Reader = .fixed(payload); const msg: ClientMsg = switch (std.enums.fromInt(ClientTag, tag) orelse return error.BadTag) { .hello => .{ .hello = .{ - .version = try r.getU16(), - .cols = try r.getCols(), - .rows = try r.getRows(), + .version = try r.takeInt(u16, .little), + .cols = try getCols(&r), + .rows = try getRows(&r), } }, .bye => .bye, .key => blk: { - const cp = try r.getU32(); + const cp = try r.takeInt(u32, .little); // `Key.cp` is a u21, and the specials live in the private-use // plane below this bound. A larger number is not a codepoint and // @intCast of it would panic in a release build's own decoder. if (cp > 0x10FFFF) return error.BadValue; break :blk .{ .event = .{ .key = .{ .cp = @intCast(cp), - .text = try r.getSlice16(), - .ctrl = try r.getBool(), - .alt = try r.getBool(), - .shift = try r.getBool(), + .text = try r.take(try r.takeInt(u16, .little)), + .ctrl = try getBool(&r), + .alt = try getBool(&r), + .shift = try getBool(&r), } } }; }, .mouse => .{ .event = .{ .mouse = .{ - .button = switch (try r.getTag(ButtonTag)) { + .button = switch (try getTag(&r, ButtonTag)) { inline else => |t| @field(pardes.Mouse.Button, @tagName(t)), }, - .kind = switch (try r.getTag(KindTag)) { + .kind = switch (try getTag(&r, KindTag)) { inline else => |t| @field(pardes.Mouse.Kind, @tagName(t)), }, - .col = try r.getU16(), - .row = try r.getU16(), - .ctrl = try r.getBool(), + .col = try r.takeInt(u16, .little), + .row = try r.takeInt(u16, .little), + .ctrl = try getBool(&r), + .shift = try getBool(&r), + .alt = try getBool(&r), .body_hit = try getBodyHit(&r), .tag_hit = try getTagHit(&r), } } }, .resize => blk: { - var ev: pardes.Event = .{ .resize = .{ .cols = try r.getCols(), .rows = try r.getRows() } }; - const px_w = try r.getU16(); - const px_h = try r.getU16(); + var ev: pardes.Event = .{ .resize = .{ .cols = try getCols(&r), .rows = try getRows(&r) } }; + const px_w = try r.takeInt(u16, .little); + const px_h = try r.takeInt(u16, .little); // Read either way — the bytes are on the wire — and kept only by a // build that has somewhere to keep them. if (comptime has_cell_pixels) ev.resize.cell_pixels = .{ .w = px_w, .h = px_h }; ev.resize.row_metrics = try getMetrics(&r); break :blk .{ .event = ev }; }, - .paste => .{ .event = .{ .paste = try r.getSlice32() } }, - .command => .{ .event = .{ .command = try r.getSlice16() } }, - .pdf_scroll => .{ .event = .{ .pdf_scroll = .{ .pane = try r.getPane(), .delta_pixels = try r.getF32() } } }, - .pinch => .{ .event = .{ .pinch = try r.getF32() } }, - .touch_scroll => .{ .event = .{ .touch_scroll = try r.getF32() } }, + .paste => .{ .event = .{ .paste = try getSlice32(&r) } }, + .command => .{ .event = .{ .command = try r.take(try r.takeInt(u16, .little)) } }, + .pdf_scroll => .{ .event = .{ .pdf_scroll = .{ .pane = try getPane(&r), .delta_pixels = try getF32(&r), .glide = try getBool(&r) } } }, + .pinch => .{ .event = .{ .pinch = try getF32(&r) } }, + .touch_scroll => .{ .event = .{ .touch_scroll = try getF32(&r) } }, .pointer_leave => .{ .event = .pointer_leave }, + .focus => .{ .event = .{ .focus = try getBool(&r) } }, }; - try r.end(); + try end(&r); return msg; } @@ -1019,29 +1066,42 @@ fn serverTag(msg: ServerMsg) ServerTag { } /// Every server message EXCEPT a frame, which has its own encoder because its -/// payload is a walk of two grids rather than a value (see `encodeFrame`). +/// payload is a walk of two grids rather than a value (see `encodeFrameLayers`). pub fn encodeServer(out: []u8, msg: ServerMsg) Error![]const u8 { - var w: Writer = .init(out); - const at = try beginMessage(&w, @intFromEnum(serverTag(msg))); + var w: std.Io.Writer = .fixed(out); + const at = try beginMessage(&w, @backingInt(serverTag(msg))); switch (msg) { .welcome => |v| { - try w.putU16(v.version); - try w.putByte(v.slot); - try w.putU16(v.cols); - try w.putU16(v.rows); + try w.writeInt(u16, v.version, .little); + try w.writeByte(v.slot); + try w.writeInt(u16, v.cols, .little); + try w.writeInt(u16, v.rows, .little); }, - .refuse => |why| try w.putByte(@intFromEnum(why)), + .refuse => |why| try w.writeByte(@backingInt(why)), // A frame's runs are not a value this union can hold; the server calls - // encodeFrame directly and this arm exists so the switch stays + // encodeFrameLayers directly and this arm exists so the switch stays // exhaustive over ServerMsg. .frame => return error.BadValue, .quit, .detach => {}, - .set_clipboard => |t| try w.putSlice32(t), + .set_clipboard => |t| try putSlice32(&w, t), .read_clipboard => {}, - .open_link => |u| try w.putSlice16(u), + .open_link => |u| try putSlice16(&w, u), + .post => |p| { + try w.writeByte(@backingInt(p.animation)); + try w.writeByte(p.len); + for (p.list()) |pass| { + // 0 a file, else a bundled scene and one. + try w.writeByte(if (pass.scene) |scene| @as(u8, @backingInt(scene)) + 1 else 0); + try w.writeByte(pass.level); + try w.writeByte(@intFromBool(pass.animated)); + try w.writeInt(u32, pass.revision, .little); + try putSlice16(&w, pass.path); + try putSlice32(&w, pass.spirv); + } + }, } try finishMessage(&w, at); - return w.written(); + return w.buffered(); } /// Slack over a message's variable payload, covering every fixed field any @@ -1060,6 +1120,11 @@ pub fn serverBound(msg: ServerMsg) usize { .frame => |f| frameBound(f.cols, f.rows), .set_clipboard => |t| t.len, .open_link => |u| u.len, + .post => |p| blk: { + var n: usize = 0; + for (p.list()) |pass| n += 13 + pass.path.len + pass.spirv.len; + break :blk n; + }, }; } @@ -1068,44 +1133,44 @@ pub fn clientBound(msg: ClientMsg) usize { return msg_slack + switch (msg) { .hello, .bye => 0, .event => |ev| switch (ev) { - .mouse, .resize, .pdf_scroll, .pinch, .touch_scroll, .pointer_leave => 0, + .mouse, .resize, .pdf_scroll, .pinch, .touch_scroll, .pointer_leave, .focus => 0, .key => |k| k.text.len, .paste => |b| b.len, .command => |line| line.len, // See `clientTag`: not on this wire in this direction. - .output, .eof, .lsp_resp, .pipe_resp, .file_changed, .tick, .fs_req => unreachable, + .output, .eof, .exited, .lsp_resp, .pipe_resp, .search, .file_changed, .handed, .tick => unreachable, }, }; } pub fn decodeServer(tag: u8, payload: []const u8) Error!ServerMsg { - var r: Reader = .init(payload); + var r: std.Io.Reader = .fixed(payload); const msg: ServerMsg = switch (std.enums.fromInt(ServerTag, tag) orelse return error.BadTag) { .welcome => .{ .welcome = .{ - .version = try r.getU16(), - .slot = try r.getByte(), - .cols = try r.getCols(), - .rows = try r.getRows(), + .version = try r.takeInt(u16, .little), + .slot = try r.takeByte(), + .cols = try getCols(&r), + .rows = try getRows(&r), } }, - .refuse => .{ .refuse = try r.getTag(Refusal) }, + .refuse => .{ .refuse = try getTag(&r, Refusal) }, .frame => blk: { - const header = try r.getTag(FrameHeader); + const header = try getTag(&r, FrameHeader); const kind: FrameKind = switch (header) { .full, .full_link => .full, .diff, .diff_link => .diff, }; - const cols = try r.getCols(); - const rows = try r.getRows(); + const cols = try getCols(&r); + const rows = try getRows(&r); const cursor = try getCursor(&r, cols, rows); - const layers = try r.getSlice32(); - const nruns = try r.getU32(); + const layers = try getSlice32(&r); + const nruns = try r.takeInt(u32, .little); // One run per cell is the worst an encoder emits, so a bigger // count cannot be describing this grid. Checked HERE rather than // in `apply`'s loop so the number is refused before it is used to // bound anything. if (nruns > @as(u32, cols) * @as(u32, rows)) return error.Overlong; - const runs = r.bytes[r.i..]; - r.i = r.bytes.len; + const runs = r.buffered(); + r.tossBuffered(); break :blk .{ .frame = .{ .layers = layers, .kind = kind, @@ -1119,11 +1184,32 @@ pub fn decodeServer(tag: u8, payload: []const u8) Error!ServerMsg { }, .quit => .quit, .detach => .detach, - .set_clipboard => .{ .set_clipboard = try r.getSlice32() }, + .set_clipboard => .{ .set_clipboard = try getSlice32(&r) }, .read_clipboard => .read_clipboard, - .open_link => .{ .open_link = try r.getSlice16() }, + .open_link => .{ .open_link = try r.take(try r.takeInt(u16, .little)) }, + .post => blk: { + var p: Post = .{ .animation = try getTag(&r, ShaderAnimation) }; + p.len = try r.takeByte(); + if (p.len > ShaderBuild.max) return error.Overlong; + for (p.passes[0..p.len]) |*pass| { + const kind = try r.takeByte(); + pass.* = .{ + .scene = if (kind == 0) null else std.enums.fromInt(Scene, kind - 1) orelse return error.BadValue, + .level = try r.takeByte(), + .animated = switch (try r.takeByte()) { + 0 => false, + 1 => true, + else => return error.BadValue, + }, + .revision = try r.takeInt(u32, .little), + .path = try r.take(try r.takeInt(u16, .little)), + .spirv = try getSlice32(&r), + }; + } + break :blk .{ .post = p }; + }, }; - try r.end(); + try end(&r); return msg; } @@ -1160,9 +1246,9 @@ test "detached wire: every Event variant round-trips" { // The tag space is the protocol's own, so assert the numbers themselves: // a renumbering here breaks every deployed frontend and must be a diff // somebody reads, not a silent change. - try testing.expectEqual(@as(u8, 0x01), @intFromEnum(ClientTag.hello)); - try testing.expectEqual(@as(u8, 0x10), @intFromEnum(ClientTag.key)); - try testing.expectEqual(@as(u8, 0x1d), @intFromEnum(ClientTag.pointer_leave)); + try testing.expectEqual(@as(u8, 0x01), @backingInt(ClientTag.hello)); + try testing.expectEqual(@as(u8, 0x10), @backingInt(ClientTag.key)); + try testing.expectEqual(@as(u8, 0x1d), @backingInt(ClientTag.pointer_leave)); { const got = try roundClient(&buf, .{ .hello = .{ .cols = 80, .rows = 24 } }); @@ -1186,13 +1272,15 @@ test "detached wire: every Event variant round-trips" { // the only place a value can be mistranslated and still decode. for (std.enums.values(pardes.Mouse.Button)) |button| { for (std.enums.values(pardes.Mouse.Kind)) |kind| { - const m: pardes.Mouse = .{ .button = button, .kind = kind, .col = 4200, .row = 7, .ctrl = true }; + const m: pardes.Mouse = .{ .button = button, .kind = kind, .col = 4200, .row = 7, .ctrl = true, .shift = true, .alt = true }; const got = (try roundClient(&buf, .{ .event = .{ .mouse = m } })).event.mouse; try testing.expectEqual(m.button, got.button); try testing.expectEqual(m.kind, got.kind); try testing.expectEqual(m.col, got.col); try testing.expectEqual(m.row, got.row); try testing.expectEqual(m.ctrl, got.ctrl); + try testing.expectEqual(m.shift, got.shift); + try testing.expectEqual(m.alt, got.alt); } } } @@ -1210,9 +1298,10 @@ test "detached wire: every Event variant round-trips" { try testing.expectEqualStrings("clip", (try roundClient(&buf, .{ .event = .{ .paste = "clip" } })).event.paste); try testing.expectEqualStrings("Look /x", (try roundClient(&buf, .{ .event = .{ .command = "Look /x" } })).event.command); { - const got = (try roundClient(&buf, .{ .event = .{ .pdf_scroll = .{ .pane = 2, .delta_pixels = -12.5 } } })).event.pdf_scroll; + const got = (try roundClient(&buf, .{ .event = .{ .pdf_scroll = .{ .pane = 2, .delta_pixels = -12.5, .glide = false } } })).event.pdf_scroll; try testing.expectEqual(@as(u8, 2), got.pane); try testing.expectEqual(@as(f32, -12.5), got.delta_pixels); + try testing.expect(!got.glide); } try testing.expectEqual(@as(f32, 1.25), (try roundClient(&buf, .{ .event = .{ .pinch = 1.25 } })).event.pinch); try testing.expectEqual(@as(f32, -0.75), (try roundClient(&buf, .{ .event = .{ .touch_scroll = -0.75 } })).event.touch_scroll); @@ -1239,6 +1328,19 @@ test "detached wire: every server message round-trips" { try testing.expectEqualStrings("yank", (try roundServer(&buf, .{ .set_clipboard = "yank" })).set_clipboard); try testing.expectEqual(ServerMsg.read_clipboard, try roundServer(&buf, .read_clipboard)); try testing.expectEqualStrings("https://x", (try roundServer(&buf, .{ .open_link = "https://x" })).open_link); + var chain: Post = .{ .animation = .always, .len = 2 }; + chain.passes[0] = .{ .scene = .bloom, .level = 3 }; + chain.passes[1] = .{ .path = "~/wave.glsl", .spirv = "\x03\x02\x23\x07spirv", .revision = 7, .animated = true }; + const back = (try roundServer(&buf, .{ .post = chain })).post; + try testing.expectEqual(ShaderAnimation.always, back.animation); + try testing.expectEqual(@as(u8, 2), back.len); + try testing.expectEqual(Scene.bloom, back.passes[0].scene.?); + try testing.expectEqual(@as(u8, 3), back.passes[0].level); + try testing.expect(back.passes[1].scene == null); + try testing.expectEqualStrings("~/wave.glsl", back.passes[1].path); + try testing.expectEqualStrings("\x03\x02\x23\x07spirv", back.passes[1].spirv); + try testing.expectEqual(@as(u32, 7), back.passes[1].revision); + try testing.expect(back.passes[1].animated and !back.passes[0].animated); } test "detached wire: only the display's own effects are on the wire" { @@ -1247,9 +1349,9 @@ test "detached wire: only the display's own effects are on the wire" { // is the direction that matters: it would hand a frontend work that must // outlive it. The count fails if one of the three is dropped, which would // silently leave a clipboard or a link unanswered on every frontend. - try testing.expectEqual(@as(usize, 8), std.enums.values(ServerTag).len); + try testing.expectEqual(@as(usize, 9), std.enums.values(ServerTag).len); for (std.enums.values(ServerTag)) |t| switch (t) { - .welcome, .refuse, .frame, .quit, .detach, .set_clipboard, .read_clipboard, .open_link => {}, + .welcome, .refuse, .frame, .quit, .detach, .set_clipboard, .read_clipboard, .open_link, .post => {}, }; } @@ -1265,7 +1367,7 @@ test "detached wire: a session is never told to do a frontend's remembering" { // Adding a name here is meant to be an ARGUMENT, not a formality, and the // bar is one sentence: A HUMAN DID IT. A keystroke, a click, a pinch, a // window resized, a paste, a command line executed, a pointer leaving the - // window — plus the two session words that say who is speaking. A pty's + // window, the window's focus — plus the two session words that say who is speaking. A pty's // output, a worker's answer, a watched file's new bytes and an animation // tick all fail that bar the same way: nobody did them, a machine reported // them, and the machine that reports them is the one already holding the @@ -1278,7 +1380,7 @@ test "detached wire: a session is never told to do a frontend's remembering" { "resize", "paste", "command", "pdf_scroll", "pinch", "touch_scroll", - "pointer_leave", + "pointer_leave", "focus", }; // One: the tag set is exactly that, named rather than counted, so @@ -1302,7 +1404,7 @@ test "detached wire: a session is never told to do a frontend's remembering" { for (0..256) |i| { const tag: u8 = @intCast(i); // Empty payloads on purpose: what is asked is whether the TAG is known. - // A known one fails later (`Truncated`) or succeeds, never with + // A known one fails later (`EndOfStream`) or succeeds, never with // `BadTag`. if (decodeClient(tag, &.{})) |_| accepted += 1 else |err| switch (err) { error.BadTag => continue, @@ -1310,7 +1412,7 @@ test "detached wire: a session is never told to do a frontend's remembering" { } const named = for (allowed) |ok| { const want = std.meta.stringToEnum(ClientTag, ok).?; - if (@intFromEnum(want) == tag) break true; + if (@backingInt(want) == tag) break true; } else false; if (!named) { std.debug.print("tag 0x{x:0>2} is decodable by a session and is not something a human did\n", .{tag}); @@ -1382,7 +1484,7 @@ test "detached wire: a full frame carries the grid, a diff carries the change" { // FULL: nothing on the far side is comparable, which is the late joiner // and the resize both. - const full_bytes = try encodeFrame(buf, cols, rows, .{ .x = 3, .y = 4, .bar = true }, cells, &.{}); + const full_bytes = try encodeFrameLayers(buf, cols, rows, .{ .x = 3, .y = 4, .bar = true }, .arrow, cells, &.{}, &.{}, &.{}, &.{}, .{}); { const f = (try framed(full_bytes)).?; const msg = (try decodeServer(f.tag, f.payload)).frame; @@ -1402,7 +1504,7 @@ test "detached wire: a full frame carries the grid, a diff carries the change" { defer gpa.free(before); cells[100] = .{ .text = "q".* ++ @as([6]u8, @splat(0)), .len = 1, .default = false }; cells[0] = .{}; // ...and one goes back to unpainted, which a diff must say - const diff_bytes = try encodeFrame(buf, cols, rows, null, cells, before); + const diff_bytes = try encodeFrameLayers(buf, cols, rows, null, .arrow, cells, before, &.{}, &.{}, &.{}, .{}); { const f = (try framed(diff_bytes)).?; const msg = (try decodeServer(f.tag, f.payload)).frame; @@ -1416,7 +1518,7 @@ test "detached wire: a full frame carries the grid, a diff carries the change" { // An unchanged frame is the head and nothing else: no runs, and the // receiver keeps what it has. This is what makes an idle session silent. { - const idle = try encodeFrame(buf, cols, rows, null, cells, cells); + const idle = try encodeFrameLayers(buf, cols, rows, null, .arrow, cells, cells, &.{}, &.{}, &.{}, .{}); try testing.expectEqual(@as(usize, header_len + frame_head), idle.len); const f = (try framed(idle)).?; const msg = (try decodeServer(f.tag, f.payload)).frame; @@ -1452,7 +1554,7 @@ test "detached wire: the largest grid is one cell past a run, and survives it" { for (cells) |*c| c.* = .{ .text = "a".* ++ @as([6]u8, @splat(0)), .len = 1, .default = false }; @memset(mirror, .{}); - const bytes = try encodeFrame(buf, cols, rows, null, cells, &.{}); + const bytes = try encodeFrameLayers(buf, cols, rows, null, .arrow, cells, &.{}, &.{}, &.{}, &.{}, .{}); const f = (try framed(bytes)).?; const msg = (try decodeServer(f.tag, f.payload)).frame; try testing.expectEqual(FrameKind.full, msg.kind); @@ -1462,7 +1564,7 @@ test "detached wire: the largest grid is one cell past a run, and survives it" { try expectGridEqual(cells, mirror); // ...at exactly the two headers the split costs and not one byte more. // `bytes.len <= frameBound(...)` would prove nothing here — the buffer IS - // `frameBound` bytes, so an over-run is `NoSpace` above, not a false + // `frameBound` bytes, so an over-run is `WriteFailed` above, not a false // assertion here — and what wants pinning is that the second run is the // whole of the cost. try testing.expectEqual( @@ -1472,7 +1574,7 @@ test "detached wire: the largest grid is one cell past a run, and survives it" { } test "detached wire: the diff is worth having, in bytes, on the board's grid" { - // The numbers quoted in `encodeFrame`'s comment, asserted so the claim + // The numbers quoted in `encodeFrameLayers`'s comment, asserted so the claim // cannot rot. 56x14 is the ESP32-P4 board's default grid (esp32p4.zig). const cols: u16 = 56; const rows: u16 = 14; @@ -1487,7 +1589,7 @@ test "detached wire: the diff is worth having, in bytes, on the board's grid" { // Every cell painted with a plain ASCII glyph and default colors, which is // what a pardes frame overwhelmingly is: eight bytes a cell. for (cells) |*c| c.* = .{ .text = "a".* ++ @as([6]u8, @splat(0)), .len = 1, .default = false }; - const full = (try encodeFrame(buf, cols, rows, null, cells, &.{})).len; + const full = (try encodeFrameLayers(buf, cols, rows, null, .arrow, cells, &.{}, &.{}, &.{}, &.{}, .{})).len; try testing.expectEqual(@as(usize, header_len + frame_head + run_header + n * 8), full); try testing.expectEqual(@as(usize, 6302), full); @@ -1498,7 +1600,7 @@ test "detached wire: the diff is worth having, in bytes, on the board's grid" { cells[300] = .{ .text = "b".* ++ @as([6]u8, @splat(0)), .len = 1, .default = false }; cells[301] = .{ .text = "c".* ++ @as([6]u8, @splat(0)), .len = 1, .default = false }; cells[500] = .{ .text = "d".* ++ @as([6]u8, @splat(0)), .len = 1, .default = false }; - const diff = (try encodeFrame(buf, cols, rows, null, cells, before)).len; + const diff = (try encodeFrameLayers(buf, cols, rows, null, .arrow, cells, before, &.{}, &.{}, &.{}, .{})).len; try testing.expectEqual(@as(usize, header_len + frame_head + 2 * run_header + 3 * 8), diff); try testing.expectEqual(@as(usize, 60), diff); // The whole reason this codec exists rather than shipping the Surface. @@ -1517,7 +1619,7 @@ test "detached wire: a run is coalesced across a gap only when that is cheaper" cells[0] = .{ .text = "a".* ++ @as([6]u8, @splat(0)), .len = 1, .default = false }; cells[4] = .{ .text = "b".* ++ @as([6]u8, @splat(0)), .len = 1, .default = false }; { - const f = (try framed(try encodeFrame(&buf, cols, rows, null, &cells, &prev))).?; + const f = (try framed(try encodeFrameLayers(&buf, cols, rows, null, .arrow, &cells, &prev, &.{}, &.{}, &.{}, .{}))).?; try testing.expectEqual(@as(u32, 1), (try decodeServer(f.tag, f.payload)).frame.nruns); } // Now put a PAINTED cell in the gap that both sides already agree about. @@ -1526,12 +1628,12 @@ test "detached wire: a run is coalesced across a gap only when that is cheaper" cells[2] = painted; prev[2] = painted; { - const f = (try framed(try encodeFrame(&buf, cols, rows, null, &cells, &prev))).?; + const f = (try framed(try encodeFrameLayers(&buf, cols, rows, null, .arrow, &cells, &prev, &.{}, &.{}, &.{}, .{}))).?; try testing.expectEqual(@as(u32, 2), (try decodeServer(f.tag, f.payload)).frame.nruns); } // Whichever it chose, the receiver ends up with the same grid. var mirror: [8]pardes.Cell = prev; - const f = (try framed(try encodeFrame(&buf, cols, rows, null, &cells, &prev))).?; + const f = (try framed(try encodeFrameLayers(&buf, cols, rows, null, .arrow, &cells, &prev, &.{}, &.{}, &.{}, .{}))).?; try (try decodeServer(f.tag, f.payload)).frame.apply(&mirror); try expectGridEqual(&cells, &mirror); } @@ -1550,14 +1652,14 @@ test "detached wire: a truncated frame is refused at every length" { // ...and the same bytes handed to the decoder with the header's length // left claiming the whole message, which is how a decoder is walked // off the end of its buffer. - try testing.expectError(error.Truncated, decodeClient(copy[0], copy[header_len..cut])); + try testing.expectError(error.EndOfStream, decodeClient(copy[0], copy[header_len..cut])); } // Shorter than the header itself is not yet a message at all. for (0..header_len + 1) |cut| try testing.expectEqual(@as(?Framed, null), try framed(copy[0..cut])); // A payload with bytes LEFT OVER is refused too: it is not this message. - try testing.expectError(error.Trailing, decodeClient(@intFromEnum(ClientTag.pointer_leave), "x")); - try testing.expectError(error.Trailing, decodeServer(@intFromEnum(ServerTag.quit), "x")); + try testing.expectError(error.Trailing, decodeClient(@backingInt(ClientTag.pointer_leave), "x")); + try testing.expectError(error.Trailing, decodeServer(@backingInt(ServerTag.quit), "x")); } test "detached wire: an unknown tag is refused, never guessed" { @@ -1569,9 +1671,9 @@ test "detached wire: an unknown tag is refused, never guessed" { } // A tag NESTED in a payload gets the same treatment: a color, an // underline style, a mouse button, a refusal reason. - try testing.expectError(error.BadTag, decodeServer(@intFromEnum(ServerTag.refuse), &.{0x7f})); + try testing.expectError(error.BadTag, decodeServer(@backingInt(ServerTag.refuse), &.{0x7f})); try testing.expectError(error.BadTag, decodeClient( - @intFromEnum(ClientTag.mouse), + @backingInt(ClientTag.mouse), &.{ 0xff, 0x00, 0, 0, 0, 0, 0 }, )); } @@ -1579,7 +1681,7 @@ test "detached wire: an unknown tag is refused, never guessed" { test "detached wire: an over-long length prefix is refused before it is believed" { // The prefix a hostile or corrupt peer sends to make the receiver allocate // or index by it. `framed` must refuse rather than wait for 4 GiB. - var head: [header_len]u8 = .{ @intFromEnum(ClientTag.paste), 0, 0, 0, 0 }; + var head: [header_len]u8 = .{ @backingInt(ClientTag.paste), 0, 0, 0, 0 }; std.mem.writeInt(u32, head[1..5], max_payload + 1, .little); try testing.expectError(error.Overlong, framed(&head)); std.mem.writeInt(u32, head[1..5], std.math.maxInt(u32), .little); @@ -1593,10 +1695,10 @@ test "detached wire: an over-long length prefix is refused before it is believed var paste: [8]u8 = undefined; std.mem.writeInt(u32, paste[0..4], 4096, .little); @memcpy(paste[4..8], "abcd"); - try testing.expectError(error.Truncated, decodeClient(@intFromEnum(ClientTag.paste), &paste)); + try testing.expectError(error.EndOfStream, decodeClient(@backingInt(ClientTag.paste), &paste)); // ...and past the cap, which is refused rather than read. std.mem.writeInt(u32, paste[0..4], max_payload + 1, .little); - try testing.expectError(error.Overlong, decodeClient(@intFromEnum(ClientTag.paste), &paste)); + try testing.expectError(error.Overlong, decodeClient(@backingInt(ClientTag.paste), &paste)); } test "detached wire: a frame that lies about its runs cannot walk out of the grid" { @@ -1640,14 +1742,14 @@ test "detached wire: a frame that lies about its runs cannot walk out of the gri // A run count larger than the grid has cells is refused at DECODE, before // it is used to bound the walk. var head: [frame_head]u8 = undefined; - var w: Writer = .init(&head); - try w.putByte(@intFromEnum(FrameKind.diff)); - try w.putU16(cols); - try w.putU16(rows); + var w: std.Io.Writer = .fixed(&head); + try w.writeByte(@backingInt(FrameKind.diff)); + try w.writeInt(u16, cols, .little); + try w.writeInt(u16, rows, .little); try putCursor(&w, null, cols, rows); - try w.putU32(0); // no body layers - try w.putU32(9); - try testing.expectError(error.Overlong, decodeServer(@intFromEnum(ServerTag.frame), w.written())); + try w.writeInt(u32, 0, .little); // no body layers + try w.writeInt(u32, 9, .little); + try testing.expectError(error.Overlong, decodeServer(@backingInt(ServerTag.frame), w.buffered())); // ...and a grid of the wrong size is the receiver's own bug, not a frame // it should paint half of. @@ -1667,7 +1769,7 @@ test "detached wire: link pointer survives full and unchanged grid frames" { var buffer: [256]u8 = undefined; for ([_]pardes.Surface.PointerShape{ .link, .arrow, .link }) |shape| { for ([_]bool{ true, false }) |full| { - const bytes = try encodeFramePointer(&buffer, 1, 1, null, shape, &cells, if (full) &.{} else &cells); + const bytes = try encodeFrameLayers(&buffer, 1, 1, null, shape, &cells, if (full) &.{} else &cells, &.{}, &.{}, &.{}, .{}); const packet = (try framed(bytes)).?; const frame = (try decodeServer(packet.tag, packet.payload)).frame; try std.testing.expectEqual(shape, frame.pointer_shape); @@ -1688,32 +1790,32 @@ test "detached wire: a cursor outside the grid is refused, not painted" { const rows: u16 = 2; var head: [frame_head]u8 = undefined; for ([_][2]u16{ .{ cols, 0 }, .{ 0, rows }, .{ 0xffff, 0xffff } }) |xy| { - var w: Writer = .init(&head); - try w.putByte(@intFromEnum(FrameKind.diff)); - try w.putU16(cols); - try w.putU16(rows); + var w: std.Io.Writer = .fixed(&head); + try w.writeByte(@backingInt(FrameKind.diff)); + try w.writeInt(u16, cols, .little); + try w.writeInt(u16, rows, .little); // Written by hand: `putCursor` now refuses this too, which is the // other half of the same fix and is asserted below. - try w.putBool(true); - try w.putU16(xy[0]); - try w.putU16(xy[1]); - try w.putBool(false); - try w.putU32(0); + try w.writeByte(@intFromBool(true)); + try w.writeInt(u16, xy[0], .little); + try w.writeInt(u16, xy[1], .little); + try w.writeByte(@intFromBool(false)); + try w.writeInt(u32, 0, .little); try testing.expectError( error.BadValue, - decodeServer(@intFromEnum(ServerTag.frame), w.written()), + decodeServer(@backingInt(ServerTag.frame), w.buffered()), ); } // The last cell IS in the grid, and a frame carrying it decodes. { - var w: Writer = .init(&head); - try w.putByte(@intFromEnum(FrameKind.diff)); - try w.putU16(cols); - try w.putU16(rows); + var w: std.Io.Writer = .fixed(&head); + try w.writeByte(@backingInt(FrameKind.diff)); + try w.writeInt(u16, cols, .little); + try w.writeInt(u16, rows, .little); try putCursor(&w, .{ .x = cols - 1, .y = rows - 1, .bar = true }, cols, rows); - try w.putU32(0); // no body layers - try w.putU32(0); - const got = (try decodeServer(@intFromEnum(ServerTag.frame), w.written())).frame; + try w.writeInt(u32, 0, .little); // no body layers + try w.writeInt(u32, 0, .little); + const got = (try decodeServer(@backingInt(ServerTag.frame), w.buffered())).frame; try testing.expectEqual(@as(u16, cols - 1), got.cursor.?.x); try testing.expectEqual(@as(u16, rows - 1), got.cursor.?.y); } @@ -1723,13 +1825,13 @@ test "detached wire: a cursor outside the grid is refused, not painted" { var buf: [512]u8 = undefined; try testing.expectError( error.BadValue, - encodeFrame(&buf, cols, rows, .{ .x = cols, .y = 0, .bar = false }, &cells, &.{}), + encodeFrameLayers(&buf, cols, rows, .{ .x = cols, .y = 0, .bar = false }, .arrow, &cells, &.{}, &.{}, &.{}, &.{}, .{}), ); // A grid past the protocol's own ceiling is refused by the encoder for the // same reason: `max_payload` is derived from it, so the decoder would. try testing.expectError( error.Overlong, - encodeFrame(&buf, max_cols + 1, 1, null, cells[0..0], &.{}), + encodeFrameLayers(&buf, max_cols + 1, 1, null, .arrow, cells[0..0], &.{}, &.{}, &.{}, &.{}, .{}), ); } @@ -1737,25 +1839,25 @@ test "detached wire: values a field cannot mean are refused" { // A bool is 0 or 1. `2` used to be "true" in every hand-written codec that // ever silently accepted a corrupt stream. try testing.expectError(error.BadValue, decodeClient( - @intFromEnum(ClientTag.key), + @backingInt(ClientTag.key), &.{ 'a', 0, 0, 0, 0, 0, 2, 0, 0 }, )); // A codepoint past Unicode's last: @intCast into Key.cp's u21 would panic. try testing.expectError(error.BadValue, decodeClient( - @intFromEnum(ClientTag.key), + @backingInt(ClientTag.key), &.{ 0x00, 0x00, 0x11, 0x00, 0, 0, 0, 0, 0 }, )); // A pane the core cannot index. `pdf_scroll` reads its pane byte before the // f32 that follows, so a one-byte payload reaches the check this is about - // rather than tripping `Truncated` first. + // rather than tripping `EndOfStream` first. try testing.expectError(error.BadValue, decodeClient( - @intFromEnum(ClientTag.pdf_scroll), + @backingInt(ClientTag.pdf_scroll), &.{pardes.MAX_PANES}, )); // A zero-column grid would collapse a shared session; an over-wide one is // past what this protocol carries. try testing.expectError(error.BadValue, decodeClient( - @intFromEnum(ClientTag.hello), + @backingInt(ClientTag.hello), &.{ 1, 0, 0, 0, 24, 0 }, )); { @@ -1763,15 +1865,15 @@ test "detached wire: values a field cannot mean are refused" { std.mem.writeInt(u16, hello[0..2], version, .little); std.mem.writeInt(u16, hello[2..4], max_cols + 1, .little); std.mem.writeInt(u16, hello[4..6], 24, .little); - try testing.expectError(error.BadValue, decodeClient(@intFromEnum(ClientTag.hello), &hello)); + try testing.expectError(error.BadValue, decodeClient(@backingInt(ClientTag.hello), &hello)); } // A NaN scroll distance. `pinch` multiplies into a zoom the pane keeps. { var pinch: [4]u8 = undefined; std.mem.writeInt(u32, &pinch, @bitCast(std.math.nan(f32)), .little); - try testing.expectError(error.BadValue, decodeClient(@intFromEnum(ClientTag.pinch), &pinch)); + try testing.expectError(error.BadValue, decodeClient(@backingInt(ClientTag.pinch), &pinch)); std.mem.writeInt(u32, &pinch, @bitCast(std.math.inf(f32)), .little); - try testing.expectError(error.BadValue, decodeClient(@intFromEnum(ClientTag.touch_scroll), &pinch)); + try testing.expectError(error.BadValue, decodeClient(@backingInt(ClientTag.touch_scroll), &pinch)); } // A cell with the reserved attribute bit set, and one with an impossible // grapheme length. Both are bytes this protocol has no meaning for. @@ -1806,10 +1908,10 @@ test "detached wire: max_payload bounds every message this protocol can build" { const room = try gpa.alloc(u8, huge.len + header_len + 2); defer gpa.free(room); try testing.expectError(error.Overlong, encodeClient(room, .{ .event = .{ .command = huge } })); - // ...and a buffer the caller sized too small is NoSpace, which is the + // ...and a buffer the caller sized too small is WriteFailed, which is the // server's signal to drop that one message rather than the client. var small: [8]u8 = undefined; - try testing.expectError(error.NoSpace, encodeClient(&small, .{ .event = .{ .paste = "0123456789" } })); + try testing.expectError(error.WriteFailed, encodeClient(&small, .{ .event = .{ .paste = "0123456789" } })); } test "detached wire carries compact body rows and exact pointer metrics" { @@ -1817,22 +1919,29 @@ test "detached wire carries compact body rows and exact pointer metrics" { var cells: [8]pardes.Cell = @splat(.{}); var logical: [12]pardes.Cell = @splat(.{}); logical[10] = .{ .text = "z".* ++ @as([6]u8, @splat(0)), .len = 1, .default = false }; - var layer: pardes.BodyLayer = .{ .pane = 0, .serial = 42, .viewport = .{ .x = 0, .y = 0, .w = 2, .h = 4 }, .cols = 2, .rows = 6, .context_rows = 2, .cells = &logical, .cursor = .{ .x = 0, .y = 5, .bar = true } }; + var layer: pardes.Layer = .{ .id = 0, .serial = 42, .viewport = .{ .x = 0, .y = 0, .w = 2, .h = 4 }, .cols = 2, .rows = 6, .context_rows = 2, .cells = &logical, .cursor = .{ .x = 0, .y = 5, .bar = true } }; layer.context_separators.set(0); var tag_cells: [3]pardes.Cell = @splat(.{}); tag_cells[2] = logical[10]; - const tag: pardes.TagLayer = .{ .kind = .column, .id = 1, .viewport = .{ .x = 0, .y = 0, .w = 2, .h = 1 }, .cols = 3, .bg = .{ 11, 22, 33 }, .cells = &tag_cells, .cursor = .{ .col = 2, .bar = true } }; - const out = try gpa.alloc(u8, frameBound(2, 4) + layersBound(&.{layer}, &.{tag})); + const tag: pardes.Layer = .{ .kind = .column, .id = 1, .viewport = .{ .x = 0, .y = 0, .w = 2, .h = 1 }, .cols = 3, .rows = 1, .bg = .{ 11, 22, 33 }, .cells = &tag_cells, .cursor = .{ .x = 2, .y = 0, .bar = true } }; + const placed = [_]pardes.Region{.{ .kind = .rail, .owner = 3, .serial = 42, .rect = .{ .x = 0, .y = 1, .w = 2, .h = 3 }, .active = true, .dirty = true, .thumb_y = 1, .thumb_h = 2, .clip = 1, .lift = 0.5 }}; + const out = try gpa.alloc(u8, frameBound(2, 4) + layersBound(&.{layer}, &.{tag}, &placed)); defer gpa.free(out); - const encoded = try encodeFrameLayers(out, 2, 4, null, .link, &cells, &cells, &.{layer}, &.{tag}); + const palette: pardes.Chrome = .{ .page = .{ 1, 2, 3 }, .border = .{ 4, 5, 6 }, .tag_focus_bg = .{ 7, 8, 9 }, .scroll_thumb = .{ 10, 11, 12 }, .rule_px = 3, .tag_rule = .{ 13, 14, 15 }, .rail_px = 12, .grip_border = .{ 16, 17, 18 }, .grip_focus_ring = .{ 19, 20, 21 }, .grip_dirty = .{ 22, 23, 24 }, .lift_style = 2, .cursor_glide = 3, .cursor_alpha = 0.5, .cursor_idle_ms = 1234, .cursor_quad = .{ 1, 2, 3.5, 2, 3.5, 3, 1, 3 } }; + const encoded = try encodeFrameLayers(out, 2, 4, null, .link, &cells, &cells, &.{layer}, &.{tag}, &placed, palette); const packet = (try framed(encoded)).?; const frame = (try decodeServer(packet.tag, packet.payload)).frame; - var decoded: [pardes.MAX_PANES]pardes.BodyLayer = @splat(.{}); - var tags: [pardes.MAX_TAG_LAYERS]pardes.TagLayer = @splat(.{}); + var decoded: [pardes.MAX_PANES]pardes.Layer = @splat(.{}); + var tags: [pardes.MAX_TAG_LAYERS]pardes.Layer = @splat(.{}); defer for (&tags) |*item| gpa.free(item.cells); defer for (&decoded) |*item| gpa.free(item.cells); try frame.apply(&cells); - try frame.applyLayers(gpa, &decoded, &tags); + var regions: std.ArrayListUnmanaged(pardes.Region) = .empty; + defer regions.deinit(gpa); + var chrome: pardes.Chrome = .{}; + try frame.applyLayers(gpa, &decoded, &tags, ®ions, &chrome); + try std.testing.expectEqualDeep(placed[0..], regions.items); + try std.testing.expectEqualDeep(palette, chrome); try std.testing.expectEqual(@as(u16, 6), decoded[0].rows); try std.testing.expect(decoded[0].context_separators.isSet(0)); try std.testing.expect(!decoded[0].context_separators.isSet(1)); @@ -1844,10 +1953,10 @@ test "detached wire carries compact body rows and exact pointer metrics" { try std.testing.expectEqual(tag.id, tags[0].id); try std.testing.expectEqual(tag.bg, tags[0].bg); try std.testing.expectEqual(tag.cols, tags[0].cols); - try std.testing.expectEqual(@as(u16, 2), tags[0].cursor.?.col); + try std.testing.expectEqual(@as(u16, 2), tags[0].cursor.?.x); try std.testing.expectEqualStrings("z", tags[0].cells[2].grapheme()); - const pointer = layer.hitAt(4, 27, 8, 16, 6, 8).?; - const tag_pointer = tag.hitAt(11, 8, 8, 16, 4, 8).?; + const pointer = layer.bodyHit(4, 27, 8, 16, 6, 8).?; + const tag_pointer = tag.tagHit(11, 8, 8, 16, 4, 8).?; const message: ClientMsg = .{ .event = .{ .mouse = .{ .col = 0, .row = 1, .button = .left, .kind = .press, .body_hit = pointer, .tag_hit = tag_pointer } } }; var mouse_bytes: [256]u8 = undefined; const mouse_encoded = try encodeClient(&mouse_bytes, message); @@ -1858,19 +1967,20 @@ test "detached wire carries compact body rows and exact pointer metrics" { try std.testing.expect(mouse_encoded.len <= clientBound(message)); var truncated = frame; truncated.layers = frame.layers[0 .. frame.layers.len - 1]; - try std.testing.expectError(error.Truncated, truncated.applyLayers(gpa, &decoded, &tags)); + try std.testing.expectError(error.EndOfStream, truncated.applyLayers(gpa, &decoded, &tags, ®ions, &chrome)); for (decoded) |item| { try std.testing.expectEqual(@as(u16, 0), item.rows); try std.testing.expectEqual(@as(usize, 0), item.cells.len); try std.testing.expectEqual(@as(usize, 0), item.context_separators.count()); } for (tags) |item| { - try std.testing.expectEqual(@as(u16, 0), item.cols); + try std.testing.expectEqual(@as(u16, 0), item.rows); try std.testing.expectEqual(@as(usize, 0), item.cells.len); } - const no_layers = try encodeFramePointer(out, 2, 4, null, .arrow, &cells, &cells); + try std.testing.expectEqual(@as(usize, 0), regions.items.len); + const no_layers = try encodeFrameLayers(out, 2, 4, null, .arrow, &cells, &cells, &.{}, &.{}, &.{}, .{}); const cleared_packet = (try framed(no_layers)).?; const cleared = (try decodeServer(cleared_packet.tag, cleared_packet.payload)).frame; - try cleared.applyLayers(gpa, &decoded, &tags); + try cleared.applyLayers(gpa, &decoded, &tags, ®ions, &chrome); try std.testing.expectEqual(@as(u16, 0), decoded[0].rows); } |
