diff options
| -rw-r--r-- | src/CHANGELOG.md | 7 | ||||
| -rw-r--r-- | src/Core.zig | 8 | ||||
| -rw-r--r-- | src/File.zig | 9 | ||||
| -rw-r--r-- | src/Kind.zig | 373 | ||||
| -rw-r--r-- | src/Term.zig | 62 | ||||
| -rw-r--r-- | src/body_layer.zig | 4 | ||||
| -rw-r--r-- | src/builtins.zig | 4 | ||||
| -rw-r--r-- | src/colors.zig | 2 | ||||
| -rw-r--r-- | src/dump.zig | 6 | ||||
| -rw-r--r-- | src/exec.zig | 2 | ||||
| -rw-r--r-- | src/gui/gui.zig | 2 | ||||
| -rw-r--r-- | src/keys.zig | 6 | ||||
| -rw-r--r-- | src/ninep/pty.zig | 4 | ||||
| -rw-r--r-- | src/panes.zig | 5 | ||||
| -rw-r--r-- | src/pardes.zig | 4 | ||||
| -rw-r--r-- | src/replica.zig | 51 | ||||
| -rw-r--r-- | src/tagline.zig | 4 | ||||
| -rw-r--r-- | src/tape.zig | 1 | ||||
| -rw-r--r-- | src/term/echo.zig | 2 | ||||
| -rw-r--r-- | src/term/screen_state.zig | 370 | ||||
| -rw-r--r-- | src/term/terminal.zig | 91 | ||||
| -rw-r--r-- | src/wire.zig | 2 | ||||
| -rw-r--r-- | test/replicas.zig | 10 |
23 files changed, 573 insertions, 456 deletions
diff --git a/src/CHANGELOG.md b/src/CHANGELOG.md index 5a8947e8..5aa8141c 100644 --- a/src/CHANGELOG.md +++ b/src/CHANGELOG.md @@ -2,6 +2,13 @@ ## Unreleased +- The terminal is reached through one interface, `src/Term.zig`, and its + own files (the emulator, its screen state for replicas, predicted echo, + kitty images, the pager's parse) sit behind it in `src/term/`: the + first step of taking the terminal out of the core + (docs/next-terminal.md). Editing a terminal's text is the core's, on a + copy of its rows, as before; nothing a session does changes. + - The 256-colour palette Petscii art and the window draw a palette colour with is pardes's own (`colors.xterm`), ghostty-vt's default to the entry. diff --git a/src/Core.zig b/src/Core.zig index 4d24dcc7..5516265e 100644 --- a/src/Core.zig +++ b/src/Core.zig @@ -245,7 +245,7 @@ session_dir_len: ?u16 = null, settings: config.Runtime = .{ .font = .{ .tagline_percent = config.gui_tagline_font_percent } }, locations_config: locations.Config = .{}, locations_cache: locations.Cache = .{}, -tty_filter_palette: pardes.panes.terminal.FilterPalette = .{}, +tty_filter_palette: pardes.Term.FilterPalette = .{}, font_request_taken: bool = false, custom_theme: ?Theme = null, /// bodyChrome's: the theme it was worked out for, and it. @@ -364,7 +364,7 @@ surface: Surface = .{}, /// A replica's predicted echo (src/term/echo.zig), drawn over its terminals: /// presentation, its own, in no digest and no rollback copy. Null on a /// session's own core. -echo: ?*pardes.echo.Echo = null, +echo: ?*pardes.Term.Echo = null, /// The live view, `views[live]` (`view()`): whose input the session /// takes now, and whose share of the panes is in their own fields /// (views.zig). `views_open` says which views there are, one a window @@ -3244,9 +3244,9 @@ test "a host with no methods at all is a complete in-process pardes" { // the absent child is SILENT: the bytes are dropped, and nothing appears // on the pane's screen to suggest a program answered - const before = p.panes[0].?.terminal.?.vt.screens.active.cursor.y; + const before = pardes.Term.grid(p.panes[0].?.terminal).cursor_y; p.perform(.{ .write = .{ .pane = 0, .bytes = .from("ls\r") } }); - try std.testing.expectEqual(before, p.panes[0].?.terminal.?.vt.screens.active.cursor.y); + try std.testing.expectEqual(before, pardes.Term.grid(p.panes[0].?.terminal).cursor_y); // the clipboard round-trips through the in-process one try p.registers.put(gpa, '+', "copied", 0, 1, true); diff --git a/src/File.zig b/src/File.zig index f33d0f1b..2a7d5b40 100644 --- a/src/File.zig +++ b/src/File.zig @@ -21,7 +21,6 @@ const Stream = @import("Stream.zig"); const Pane = panes.Pane; const Output = panes.Output; const Mini = panes.mini; -const terminal = panes.terminal; const Text = panes.Text; const SYNTAX_CONTEXT_AFTER_ROWS: usize = 2; @@ -1865,8 +1864,8 @@ pub fn recolorSyntax(p: *Pardes, s: *Surface, pane: *Pane, f: *State, r: pardes. const algo = pane.colorAlgo(); const tints: ?DiffTints = if ((algo == .diff or algo == .locations) and highlights.len > 0) DiffTints.of(p) else null; const row_tint = algo == .diff; - var filtered_storage: terminal.FilteredColors = undefined; - const filtered: ?*terminal.FilteredColors = if (pane.tty_filter and spans.len > 0) blk: { + var filtered_storage: pardes.Term.Filter = undefined; + const filtered: ?*pardes.Term.Filter = if (pane.tty_filter and spans.len > 0) blk: { filtered_storage = .init(p, null); break :blk &filtered_storage; } else null; @@ -1993,8 +1992,8 @@ pub fn recolorSyntax(p: *Pardes, s: *Surface, pane: *Pane, f: *State, r: pardes. if (st.fg != .default) cell.style.fg = colors.spanColor(st.fg, false); if (st.bg != .default) cell.style.bg = colors.spanColor(st.bg, true); } else { - if (st.fg != .default) cell.style.fg = if (st.fg == .index) terminal.palColor(p, st.fg.index) else st.fg; - if (st.bg != .default) cell.style.bg = if (st.bg == .index) terminal.palColor(p, st.bg.index) else st.bg; + if (st.fg != .default) cell.style.fg = if (st.fg == .index) pardes.Term.palColor(p, st.fg.index) else st.fg; + if (st.bg != .default) cell.style.bg = if (st.bg == .index) pardes.Term.palColor(p, st.bg.index) else st.bg; } cell.style.bold = cell.style.bold or st.bold; cell.style.dim = st.dim; diff --git a/src/Kind.zig b/src/Kind.zig index 055b17f9..04db2579 100644 --- a/src/Kind.zig +++ b/src/Kind.zig @@ -199,7 +199,7 @@ pub const Slot = struct { /// Collapse Del. tail: Buf(160) = .{}, /// A replica's frame of it, as the authority painted it. - shadow: ?*@import("term/screen_state.zig").Shadow = null, + shadow: ?*Shadow = null, /// Debug: the kind's allocations, which paint must leave as they are /// (the list the page allocator's: a region's first is slow in Debug). used: if (checked) std.ArrayList([]u8) else void = if (checked) .empty else {}, @@ -1186,6 +1186,283 @@ pub fn Buf(comptime n: usize) type { }; } +// ---- a pane of a kind, as a Shadow (architecture §16.5) ---- +// +// A replica's core has no code for a library's kind: such a pane is drawn +// from the authority's frame of it, painted at the size the peer's view +// gives it. A frame crosses as its size and the pointer it asks for, each +// row by its hash (with its cells when the peer's row there is another), +// then each placement by its key; its raster's pixels cross before it, as +// strips of rows (`raster` messages, `encodeStrip`), those over its `src` +// the peer was not sent with the frame before. The stream is ordered and +// loses nothing, so what the authority last sent a peer is what the peer +// holds, but for a raster its `Blobs` let go, which it asks for again. + +const ShadowCell = c.pa_cell; +const Place = c.pa_placement; +/// A row's or a frame's content address, as a terminal's rows have one. +const Hash = u64; + +/// A replica's frame of a pane of a kind: what Kind.draw draws for it, its +/// placements' pixels its peer's `Blobs`. +pub const Shadow = struct { + gpu: []const u8 = &.{}, + cols: u16 = 0, + rows: u16 = 0, + cells: []ShadowCell = &.{}, + hashes: []Hash = &.{}, + places: std.ArrayList(Place) = .empty, + pointer: u8 = 0, + /// The raster it last asked for again (`apply`'s): asked once. + wanted: u64 = 0, + + pub fn deinit(sh: *Shadow, gpa: std.mem.Allocator) void { + gpa.free(sh.gpu); + gpa.free(sh.cells); + gpa.free(sh.hashes); + sh.places.deinit(gpa); + gpa.destroy(sh); + } + + /// A frame message applied (`encodeShadow`'s), of the pane `serial`, + /// each placement's pixels from `blobs`: one it lacks is not shown, and + /// its name is what to ask for (once), else 0. + pub fn apply(sh: *Shadow, gpa: std.mem.Allocator, bytes: []const u8, serial: u32, blobs: *Blobs) !u64 { + var r: std.Io.Reader = .fixed(bytes); + const cols = try r.takeInt(u16, .little); + const rows = try r.takeInt(u16, .little); + if (cols != sh.cols or rows != sh.rows) { + gpa.free(sh.cells); + gpa.free(sh.hashes); + sh.cells = try gpa.alloc(ShadowCell, @as(usize, cols) * rows); + sh.hashes = try gpa.alloc(Hash, rows); + @memset(std.mem.sliceAsBytes(sh.cells), 0); + @memset(sh.hashes, 0); + sh.cols = cols; + sh.rows = rows; + } + sh.pointer = try r.takeByte(); + for (0..rows) |y| { + sh.hashes[y] = try r.takeInt(u64, .little); + if (try r.takeByte() == 0) continue; + for (sh.cells[y * cols ..][0..cols]) |*cell| { + @memcpy(&cell.text, try r.take(8)); + cell.fg = try r.takeInt(u32, .little); + cell.bg = try r.takeInt(u32, .little); + cell.attrs = try r.takeInt(u16, .little); + cell.len = try r.takeByte(); + cell.flags = try r.takeByte(); + } + } + sh.places.clearRetainingCapacity(); + var lacking: u64 = 0; + for (0..try r.takeByte()) |_| { + var pl = std.mem.zeroes(Place); + pl.w = try r.takeInt(u32, .little); + pl.h = try r.takeInt(u32, .little); + inline for (.{ &pl.src.x, &pl.src.y, &pl.src.w, &pl.src.h, &pl.at.x, &pl.at.y, &pl.at.w, &pl.at.h }) |f| f.* = try r.takeInt(u32, .little); + inline for (.{ &pl.dst.x, &pl.dst.y, &pl.dst.w, &pl.dst.h }) |f| f.* = try r.takeInt(u16, .little); + pl.key = try r.takeInt(u64, .little); + const name = std.hash.Wyhash.hash(serial, std.mem.asBytes(&pl.key)); + pl.rgba = (blobs.shows(name, &pl) orelse { + lacking = name; + continue; + }).ptr; + try sh.places.append(gpa, pl); + } + // Older frames have no optional GPU tail. + const n = if (r.seek < r.end) try r.takeInt(u32, .little) else 0; + if (n > 4 << 20) return error.BadGpuFrame; + const gpu = try gpa.dupe(u8, try r.take(n)); + gpa.free(sh.gpu); + sh.gpu = gpu; + if (lacking == sh.wanted) return 0; + sh.wanted = lacking; + return lacking; + } +}; + +/// A raster's strip: at most this many bytes of its rows (17.3). +pub const strip_max = 4 << 20; + +/// How many of a `w`-pixel raster's rows a strip holds. +pub fn stripRows(w: u32) u32 { + return @max(1, strip_max / (@as(u32, @max(w, 1)) * 4)); +} + +/// The strips of `pl`'s raster over its `src` rows, a bit each. +fn stripsOver(pl: *const Place) u64 { + const per = stripRows(pl.w); + const lo = @min(pl.src.y, pl.h) / per; + const hi = (@min(pl.src.y +| pl.src.h, pl.h) + per - 1) / per; + var bits: u64 = 0; + for (lo..@min(hi, 64)) |i| bits |= @as(u64, 1) << @intCast(i); + return bits; +} + +/// Strip `i` of `pl`'s raster, a `raster` message's payload: its key, its +/// size, its first row, and its rows' bytes. +pub fn encodeStrip(pl: *const Place, i: u32, w: *std.Io.Writer) !void { + const y0 = i * stripRows(pl.w); + const row = @as(usize, pl.w) * 4; + try w.writeInt(u64, pl.key, .little); + try w.writeInt(u32, pl.w, .little); + try w.writeInt(u32, pl.h, .little); + try w.writeInt(u32, y0, .little); + try w.writeAll(pl.rgba[y0 * row .. @min(pl.h, y0 + stripRows(pl.w)) * row]); +} + +/// A peer's rasters of the panes of a kind, made from their strips by +/// name (the key with its pane's serial), kept to `max` bytes by least +/// recent use but for those a Shadow shows (17.3). +pub const Blobs = struct { + list: std.ArrayList(Blob) = .empty, + clock: u64 = 0, + + pub const max = 64 << 20; + const Blob = struct { name: u64, w: u32, h: u32, bytes: []u8, have: u64 = 0, used: u64 = 0 }; + + pub fn deinit(b: *Blobs, gpa: std.mem.Allocator) void { + for (b.list.items) |x| gpa.free(x.bytes); + b.list.deinit(gpa); + } + + /// A `raster` message's payload (`encodeStrip`'s) into raster `name`, + /// made at its first strip; `shown`, the pixels Shadows show now. + pub fn strip(b: *Blobs, gpa: std.mem.Allocator, name: u64, payload: []const u8, shown: []const [*]const u8) !void { + var r: std.Io.Reader = .fixed(payload); + _ = try r.takeInt(u64, .little); + const w = try r.takeInt(u32, .little); + const h = try r.takeInt(u32, .little); + const y0 = try r.takeInt(u32, .little); + const rows = r.buffered(); + const row = @as(usize, w) * 4; + if (row == 0 or rows.len % row != 0 or y0 % stripRows(w) != 0 or y0 + rows.len / row > h) return error.BadShadow; + const x = for (b.list.items) |*x| { + if (x.name == name) break x; + } else made: { + var held: usize = row * h; + for (b.list.items) |x| held += x.bytes.len; + while (held > max) { + var old: ?usize = null; + for (b.list.items, 0..) |x, i| if (std.mem.indexOfScalar([*]const u8, shown, x.bytes.ptr) == null and (old == null or x.used < b.list.items[old.?].used)) { + old = i; + }; + const i = old orelse break; + held -= b.list.items[i].bytes.len; + gpa.free(b.list.swapRemove(i).bytes); + } + const bytes = try gpa.alloc(u8, row * h); + errdefer gpa.free(bytes); + try b.list.append(gpa, .{ .name = name, .w = w, .h = h, .bytes = bytes }); + break :made &b.list.items[b.list.items.len - 1]; + }; + if (x.w != w or x.h != h) return error.BadShadow; + @memcpy(x.bytes[y0 * row ..][0..rows.len], rows); + x.have |= @as(u64, 1) << @intCast(@min(63, y0 / stripRows(w))); + b.clock += 1; + x.used = b.clock; + } + + /// Raster `name`'s pixels when it has every strip `pl` shows. + fn shows(b: *Blobs, name: u64, pl: *const Place) ?[]u8 { + for (b.list.items) |*x| if (x.name == name and x.w == pl.w and x.h == pl.h and stripsOver(pl) & ~x.have == 0) { + b.clock += 1; + x.used = b.clock; + return x.bytes; + }; + return null; + } +}; + +/// What the authority last sent one peer of a pane of a kind: its rows' +/// hashes, its placements, and which strips of each raster it holds. +pub const ShadowSent = struct { + serial: u32 = 0, + cols: u16 = 0, + hashes: std.ArrayList(Hash) = .empty, + places: Hash = 0, + keys: std.ArrayList(struct { key: u64, have: u64 }) = .empty, + + pub fn deinit(s: *ShadowSent, gpa: std.mem.Allocator) void { + s.hashes.deinit(gpa); + s.keys.deinit(gpa); + s.* = .{}; + } + + /// The strips of `pl`'s raster over its `src` the peer lacks (a bit + /// each, `encodeStrip`'s `i`), counted sent now. + pub fn owed(s: *ShadowSent, gpa: std.mem.Allocator, pl: *const Place) !u64 { + const need = stripsOver(pl); + for (s.keys.items) |*k| if (k.key == pl.key) { + defer k.have |= need; + return need & ~k.have; + }; + try s.keys.append(gpa, .{ .key = pl.key, .have = need }); + return need; + } +}; + +/// Frame `f` of a pane (the pointer its paint asked for) for a peer that +/// was last sent `sent`: false, and nothing written, when it holds this +/// frame already. Its placements cross by key, their pixels as strips +/// before it (`ShadowSent.owed`), so a frame is small whatever it shows. +pub fn encodeShadow(gpa: std.mem.Allocator, sent: *ShadowSent, f: *const Frame, pointer: u8, w: *std.Io.Writer) !bool { + var hashes: std.ArrayList(Hash) = .empty; + errdefer hashes.deinit(gpa); + for (0..f.rows) |y| try hashes.append(gpa, std.hash.Wyhash.hash(0, std.mem.sliceAsBytes(f.cells[y * f.cols ..][0..f.cols]))); + const places = f.places[0..@min(f.n, 64)]; + var ph = std.hash.Wyhash.init(pointer); + for (places) |*pl| inline for (.{ pl.w, pl.h, pl.src, pl.at, pl.dst, pl.key }) |v| ph.update(std.mem.asBytes(&v)); + if (f.gpu.len != 0) ph.update(f.gpu); + const places_hash = ph.final(); + if (sent.cols == f.cols and std.mem.eql(Hash, sent.hashes.items, hashes.items) and sent.places == places_hash) { + hashes.deinit(gpa); + return false; + } + try w.writeInt(u16, f.cols, .little); + try w.writeInt(u16, f.rows, .little); + try w.writeByte(pointer); + for (hashes.items, 0..) |h, y| { + try w.writeInt(u64, h, .little); + // Held only at the same size: a peer's Shadow of another starts afresh. + const held = sent.cols == f.cols and sent.hashes.items.len == f.rows and sent.hashes.items[y] == h; + try w.writeByte(@intFromBool(!held)); + if (!held) for (f.cells[y * f.cols ..][0..f.cols]) |*cell| { + try w.writeAll(&cell.text); + try w.writeInt(u32, cell.fg, .little); + try w.writeInt(u32, cell.bg, .little); + try w.writeInt(u16, cell.attrs, .little); + try w.writeByte(cell.len); + try w.writeByte(cell.flags); + }; + } + try w.writeByte(@intCast(places.len)); + for (places) |pl| { + try w.writeInt(u32, pl.w, .little); + try w.writeInt(u32, pl.h, .little); + inline for (.{ pl.src.x, pl.src.y, pl.src.w, pl.src.h, pl.at.x, pl.at.y, pl.at.w, pl.at.h }) |v| try w.writeInt(u32, v, .little); + inline for (.{ pl.dst.x, pl.dst.y, pl.dst.w, pl.dst.h }) |v| try w.writeInt(u16, v, .little); + try w.writeInt(u64, pl.key, .little); + } + if (f.gpu.len > 4 << 20) return error.BadGpuFrame; + try w.writeInt(u32, @intCast(f.gpu.len), .little); + try w.writeAll(f.gpu); + sent.hashes.deinit(gpa); + sent.hashes = hashes; + sent.cols = f.cols; + sent.places = places_hash; + // The strips of the rasters this frame shows: a key gone is sent whole again. + var i: usize = 0; + while (i < sent.keys.items.len) { + const kept = for (places) |pl| { + if (pl.key == sent.keys.items[i].key) break true; + } else false; + if (kept) i += 1 else _ = sent.keys.swapRemove(i); + } + return true; +} + test "a kind's head is checked before a core takes it, and a core's kinds are its own" { const Fake = struct { fn paint(_: ?*anyopaque, _: [*c]const c.pa_window, _: [*c]c.pa_paint) callconv(.c) void {} @@ -1213,3 +1490,97 @@ const GpuPaint = struct { return 0; } }; + +test "a pane of a kind's frame a row taller or shorter is drawn whole at its peer, never a row it let go" { + const gpa = std.testing.allocator; + var cells: [2 * 3]ShadowCell = @splat(std.mem.zeroes(ShadowCell)); + cells[0] = .{ .text = "a".* ++ @as([7]u8, @splat(0)), .fg = 1, .bg = 2, .attrs = 0, .len = 1, .flags = c.PA_PAINTED }; + var f: Frame = .{ .cells = &cells, .cols = 2, .rows = 2 }; + var sent: ShadowSent = .{}; + defer sent.deinit(gpa); + var blobs: Blobs = .{}; + const sh = try gpa.create(Shadow); + sh.* = .{}; + defer sh.deinit(gpa); + var out: std.Io.Writer.Allocating = .init(gpa); + defer out.deinit(); + for ([_]u16{ 2, 3, 2 }) |rows| { + f.rows = rows; + out.clearRetainingCapacity(); + try std.testing.expect(try encodeShadow(gpa, &sent, &f, 0, &out.writer)); + _ = try sh.apply(gpa, out.written(), 1, &blobs); + try std.testing.expectEqualStrings("a", sh.cells[0].text[0..1]); + } +} + +test "a pane of a kind crosses as its frame, a row the peer holds as its hash, a raster by key after its strips over what it shows" { + const gpa = std.testing.allocator; + var cells: [3 * 2]ShadowCell = @splat(std.mem.zeroes(ShadowCell)); + cells[0] = .{ .text = "a".* ++ @as([7]u8, @splat(0)), .fg = 1, .bg = 2, .attrs = 0, .len = 1, .flags = c.PA_PAINTED }; + // A raster of three strips (4 MiB a strip at 1,024 px), of which it shows the second. + const w: u32 = 1024; + const per = stripRows(w); + const pixels = try gpa.alloc(u8, @as(usize, w) * per * 3 * 4); + defer gpa.free(pixels); + @memset(pixels, 5); + var f: Frame = .{ .cells = &cells, .cols = 3, .rows = 2, .n = 1 }; + f.buf[0] = std.mem.zeroInit(Place, .{ .rgba = pixels.ptr, .w = w, .h = per * 3, .src = .{ .x = 0, .y = per + 1, .w = w, .h = 10 }, .key = 9 }); + f.places = &f.buf; + var sent: ShadowSent = .{}; + defer sent.deinit(gpa); + var blobs: Blobs = .{}; + defer blobs.deinit(gpa); + const sh = try gpa.create(Shadow); + sh.* = .{}; + defer sh.deinit(gpa); + var out: std.Io.Writer.Allocating = .init(gpa); + defer out.deinit(); + const name = std.hash.Wyhash.hash(1, std.mem.asBytes(&f.buf[0].key)); + try std.testing.expectEqual(@as(u64, 0b010), try sent.owed(gpa, &f.buf[0])); + try encodeStrip(&f.buf[0], 1, &out.writer); + try std.testing.expect(out.written().len <= strip_max + 20); + try blobs.strip(gpa, name, out.written(), &.{}); + out.clearRetainingCapacity(); + try std.testing.expect(try encodeShadow(gpa, &sent, &f, 0, &out.writer)); + try std.testing.expectEqual(@as(u64, 0), try sh.apply(gpa, out.written(), 1, &blobs)); + try std.testing.expectEqualStrings("a", sh.cells[0].text[0..1]); + try std.testing.expectEqual(@as(u8, 5), sh.places.items[0].rgba[per * w * 4]); + // The same frame again: nothing to send, no strip owed. + out.clearRetainingCapacity(); + try std.testing.expect(!try encodeShadow(gpa, &sent, &f, 0, &out.writer)); + try std.testing.expectEqual(@as(u64, 0), try sent.owed(gpa, &f.buf[0])); + // Its src moves into the third strip: that one is owed, and a peer + // without it does not show the raster and asks for it, once. + f.buf[0].src.y = 2 * per + 1; + try std.testing.expectEqual(@as(u64, 0b100), try sent.owed(gpa, &f.buf[0])); + out.clearRetainingCapacity(); + try std.testing.expect(try encodeShadow(gpa, &sent, &f, 0, &out.writer)); + try std.testing.expect(out.written().len < 4 + 1 + 2 * 9 + 60 + 8); + try std.testing.expectEqual(name, try sh.apply(gpa, out.written(), 1, &blobs)); + try std.testing.expectEqual(@as(usize, 0), sh.places.items.len); + try std.testing.expectEqual(@as(u64, 0), try sh.apply(gpa, out.written(), 1, &blobs)); +} + +test "optional GPU frames cross shadows, change independently, and disappear" { + const gpa = std.testing.allocator; + var sent: ShadowSent = .{}; + defer sent.deinit(gpa); + const shadow = try gpa.create(Shadow); + shadow.* = .{}; + defer shadow.deinit(gpa); + var blobs: Blobs = .{}; + defer blobs.deinit(gpa); + var cell = std.mem.zeroes(ShadowCell); + var frame: Frame = .{ .cols = 1, .rows = 1, .cells = @as([*]ShadowCell, @ptrCast(&cell))[0..1], .gpu = "first scene" }; + var out: std.Io.Writer.Allocating = .init(gpa); + defer out.deinit(); + for ([_][]const u8{ "first scene", "second scene", "" }) |bytes| { + frame.gpu = bytes; + out.clearRetainingCapacity(); + try std.testing.expect(try encodeShadow(gpa, &sent, &frame, 0, &out.writer)); + _ = try shadow.apply(gpa, out.written(), 1, &blobs); + try std.testing.expectEqualStrings(bytes, shadow.gpu); + out.clearRetainingCapacity(); + try std.testing.expect(!try encodeShadow(gpa, &sent, &frame, 0, &out.writer)); + } +} diff --git a/src/Term.zig b/src/Term.zig index 6c9bd4e3..a21c3d97 100644 --- a/src/Term.zig +++ b/src/Term.zig @@ -8,6 +8,11 @@ const std = @import("std"); const terminal = @import("term/terminal.zig"); const pager = @import("term/pager.zig"); +const echo = @import("term/echo.zig"); +/// The screen state replicas are sent (its encoder, a terminal's versions, +/// what a peer holds, a replica's side), and its streams and soak for the +/// replica tests outside src/. +pub const screen_state = @import("term/screen_state.zig"); /// A terminal pane's emulator, its parse and what pardes keeps beside it. pub const State = terminal.State; @@ -208,6 +213,63 @@ pub const Page = pager.Page; /// Bytes `start..end` of a page's text, drawn in `style`. pub const Span = pager.Span; +// ---- draw ---- +// +// ponytail: not yet narrowed to plain data (docs/next-terminal.md's draw +// row): these still take the core's Pardes, Surface and Pane, read the +// pane's edit copy and write the surface's cells and placements +// themselves. Phase 1 needs them as a cell hand-over (`paint`) and a +// placement list (`images`) first. + +/// Its program's colours over the body's rows, through the theme's +/// filter when the pane has it on. +pub const recolor = terminal.recolorAnsi; +/// Its kitty graphics over the body's rows, as placements. +pub const images = terminal.drawImages; +/// The Petscii builtin on it: its kitty graphics as glyph art, or back to +/// pixels; null for none. +pub const petscii = terminal.petscii; +pub const togglePetscii = terminal.togglePetscii; +/// Whether the screen showing holds any kitty graphics image. +pub const hasImages = terminal.hasImages; +/// A program's colours mapped to the theme (Filter): a terminal's cells +/// or a +Pager's spans (`spanColor`). +pub const Filter = terminal.FilteredColors; +/// The theme's 256 colours as the filter maps onto them, kept while the +/// theme is the same (`Pardes.tty_filter_palette`). +pub const FilterPalette = terminal.FilterPalette; +/// A palette index as the theme draws it: its own sixteen, else the index. +pub const palColor = terminal.palColor; + +// ---- its replicas ---- + +/// What a peer is owed of it, a delta against what the peer was sent. +pub const encode = terminal.encode; +/// Rows of it a replica holds as holes. +pub const encodeRows = terminal.encodeRows; +/// A peer's track of it let go. +pub const untrack = terminal.untrack; +/// Whether a step read its rows since `clearRead`. +pub const wasRead = terminal.wasRead; +pub const clearRead = terminal.clearRead; +/// A replica's side: a delta applied, rows applied, the rows its view +/// shows, rows blank until they come. +pub const apply = terminal.apply; +pub const applyRows = terminal.applyRows; +pub const shown = terminal.shown; +pub const blank = terminal.blank; +pub const dumpScreen = terminal.dumpScreen; +pub const Encoder = screen_state.Encoder; +pub const Track = screen_state.Track; +pub const Peer = screen_state.Peer; +pub const Replica = screen_state.Replica; +/// A replica's keys into a terminal drawn at once, before its authority +/// says (predicted echo). +pub const Echo = echo.Echo; + test { + _ = terminal; _ = pager; + _ = echo; + _ = screen_state; } diff --git a/src/body_layer.zig b/src/body_layer.zig index 2df619ba..942d7895 100644 --- a/src/body_layer.zig +++ b/src/body_layer.zig @@ -344,11 +344,11 @@ pub fn renderBody(p: *Pardes, s: *Surface, arena: std.mem.Allocator, pane: *Pane pane.places.paint(p, s, pane, r, body_h); panes.Query.paint(p, s, pane, r, body_h); } else if (pane.isTerminal()) { - panes.terminal.recolorAnsi(p, s, pane, r, tx, tw, body_h, body); + panes.Term.recolor(p, s, pane, r, tx, tw, body_h, body); panes.File.recolorDiffOutput(p, s, pane, r, tx, tw, body_h, body); } tz_color.end(); - if (pane.isTerminal()) panes.terminal.drawImages(p, s, pane, id, tx, tw, body_y, body_h); + if (pane.isTerminal()) panes.Term.images(p, s, pane, id, tx, tw, body_y, body_h); const sel_btn = buttonTints(th); if (p.look_hover_preview) |preview| { diff --git a/src/builtins.zig b/src/builtins.zig index 5a1c3061..b2690920 100644 --- a/src/builtins.zig +++ b/src/builtins.zig @@ -753,13 +753,13 @@ pub const Petscii = struct { pub const takes_arg = true; pub fn run(c: Ctx) void { // `on|off` sets it, as the tag's `petscii:on` reads; none flips it. - const now = if (c.pane.addon) |k| k.art.glyph else panes.terminal.petscii(c.pane) orelse false; + const now = if (c.pane.addon) |k| k.art.glyph else panes.Term.petscii(c.pane.terminal) orelse false; if (c.arg != null) { const want = stateArg(c, OnOff, "Petscii", "on or off") orelse return; if ((want == .on) == now) return; } if (c.pane.addon) |k| k.art.glyph = !k.art.glyph; - panes.terminal.togglePetscii(c.pane); + if (c.pane.terminal) |state| panes.Term.togglePetscii(state); } }; diff --git a/src/colors.zig b/src/colors.zig index 1713ba24..fab1b95d 100644 --- a/src/colors.zig +++ b/src/colors.zig @@ -12,7 +12,7 @@ const MAX_PANES = pardes.MAX_PANES; const BOX_H = pardes.BOX_H; const Pardes = pardes.Pardes; -/// The 256-colour palette a terminal starts from (ghostty-vt's default): +/// The 256-colour palette a terminal starts from (its emulator's default): /// sixteen named colours, a 6x6x6 cube at xterm's levels (0, then 95 to /// 255 by 40) and a ramp of 24 greys from 8 by 10. pub const xterm: [256][3]u8 = blk: { diff --git a/src/dump.zig b/src/dump.zig index 38be263d..31765836 100644 --- a/src/dump.zig +++ b/src/dump.zig @@ -74,7 +74,7 @@ pub var terminal_gpa: ?std.mem.Allocator = null; // // A dump is everything the session is but what is the host's, the frame's // or worked out again: its panes with their text and undo, terminals with -// their screens, history and kitty images (ghostty's snapshot), registers, +// their screens, history and kitty images (the emulator's snapshot), registers, // places, tags, layout and settings. It crosses builds: its fields are // matched by name. It is an image (Db.zig): a database in memory the walk // writes by name (walk.Put), which the state file keeps under a label, @@ -1037,13 +1037,13 @@ test "an upgraded session's dump keeps its views and its running terminal as the const was = pardes.Term.grid(p.panes[0].?.terminal); const is = pardes.Term.grid(q.panes[0].?.terminal); try std.testing.expectEqual([2]u16{ was.cursor_x, was.cursor_y }, [2]u16{ is.cursor_x, is.cursor_y }); - try std.testing.expect(q.panes[0].?.terminal.?.vt.screens.active_key == .alternate); + try std.testing.expect(pardes.Term.modes(q.panes[0].?.terminal).alternate); while (q.nextEffect()) |e| try std.testing.expect(e != .spawn); // Not kept, the same terminal is a new shell's under its history. kept[0] = false; const r = try resumeFromDump(gpa, .{ .tty_only = true, .cols = 40, .rows = 12 }, bytes, &kept); defer r.deinit(); - try std.testing.expect(r.panes[0].?.terminal.?.vt.screens.active_key == .primary); + try std.testing.expect(!pardes.Term.modes(r.panes[0].?.terminal).alternate); } test "a loaded session asks its host for its font again: a new process has only its built-in face" { diff --git a/src/exec.zig b/src/exec.zig index 315f4eee..3593bb72 100644 --- a/src/exec.zig +++ b/src/exec.zig @@ -781,7 +781,7 @@ fn runCommand(p: *Pardes, from: usize, line: []const u8) ?usize { // What the last program left the emulator in goes first: the // alternate screen left (only if it is there: leaving restores a // saved cursor), mouse reports and bracketed paste off, the cursor - // shown, colours reset. (Not DECSTR: ghostty's stream does not + // shown, colours reset. (Not DECSTR: the emulator's stream does not // implement it.) if (panes.Term.modes(pane.terminal).alternate) pane.feedOutput(p, "\x1b[?1049l"); pane.feedOutput(p, "\x1b[?1000l\x1b[?1002l\x1b[?1003l\x1b[?1006l\x1b[?2004l\x1b[?25h\x1b[0m"); diff --git a/src/gui/gui.zig b/src/gui/gui.zig index 4b956f52..c2a4ad15 100644 --- a/src/gui/gui.zig +++ b/src/gui/gui.zig @@ -7402,7 +7402,7 @@ test "the window's function and editing keys reach a terminal as its cursor keys .{ .modes = "\x1b[?1l\x1b[>7u", .sym = 'c', .mod = c.SDL_KMOD_LCTRL, .sent = "\x1b[99;5u" }, .{ .modes = "", .sym = 'a', .mod = c.SDL_KMOD_LALT, .sent = "\x1b[97;3u" }, // With event types asked for (2), an arrow says it is a press, as - // ghostty says it. + // the emulator's encoder says it. .{ .modes = "", .sym = c.SDLK_UP, .sent = "\x1b[1;1:1A" }, }; for (cases) |case| { diff --git a/src/keys.zig b/src/keys.zig index c4651be7..bdf8a454 100644 --- a/src/keys.zig +++ b/src/keys.zig @@ -549,7 +549,7 @@ test "Esc back into a tty leaves its view at the prompt" { p.update(.{ .output = .{ .pane = @intCast(shell), .bytes = std.fmt.bufPrint(&buf, "line {d}\r\n", .{i}) catch unreachable } }); } p.sync(); - const live = sp.terminal.?.vt.screens.active.pages.scrollbar().offset; + const live = pardes.Term.grid(sp.terminal).offset; try std.testing.expect(live > 0); p.update(.{ .key = .{ .cp = Key.escape } }); // shell-prompt heuristic: out to the doc @@ -558,7 +558,7 @@ test "Esc back into a tty leaves its view at the prompt" { p.sync(); try std.testing.expectEqual(shell, p.view().active); - try std.testing.expectEqual(live, sp.terminal.?.vt.screens.active.pages.scrollbar().offset); + try std.testing.expectEqual(live, pardes.Term.grid(sp.terminal).offset); } test "Del from a key asks which neighbour takes the rows; nothing else asks" { @@ -803,7 +803,7 @@ test "raw tty forwards Ctrl letters and former global shortcuts to the child" { } p.update(.{ .key = .{ .cp = Key.up } }); try std.testing.expectEqualStrings("\x1b[A", test_api.ptyBytes(p, null, &buf)); - p.panes[0].?.terminal.?.vt.modes.set(.cursor_keys, true); + _ = pardes.Term.feed(p.panes[0].?.terminal.?, "\x1b[?1h", &.{}, &.{}, &.{}); // DECCKM p.update(.{ .key = .{ .cp = Key.up } }); try std.testing.expectEqualStrings("\x1bOA", test_api.ptyBytes(p, null, &buf)); p.update(.{ .key = .{ .cp = Key.left, .ctrl = true } }); diff --git a/src/ninep/pty.zig b/src/ninep/pty.zig index bd090dfc..40ae179c 100644 --- a/src/ninep/pty.zig +++ b/src/ninep/pty.zig @@ -235,7 +235,7 @@ pub fn writeRun(p: *Pardes, req: Req, id: usize, pane: *Pane) Reply { // Something is running or someone has typed at the prompt: sending // now would type into the middle of it. The phase is pardes's own // marks: a nested shell's prompt (ssh, a shell with its own - // integration) looks like an empty prompt to ghostty but is not the + // integration) looks like an empty prompt to the emulator but is not the // shell this run knows. // Naming what runs, where the host can tell (Linux). var name: [64]u8 = undefined; @@ -365,7 +365,7 @@ pub fn noteMarks(p: *Pardes, id: usize, pane: *Pane) void { fn finish(p: *Pardes, slot: *Run, pane: *Pane, status_code: ?i32) void { // As the authority's emulator has it (taped): a screen-state replica's // is its deltas', which a lagging client's can be states behind, its - // pins in pages it never had (ghostty's leftWrap overflowed on one). + // pins in pages it never had (the emulator's leftWrap overflowed on one). const printed = pardes.tape.value(.prompt, printedBy, .{ pane, p.scratch.allocator() }) orelse return answer(p, slot, "error out of memory", .{}); // Keep the tail, cut at a line start so the first line kept is whole. diff --git a/src/panes.zig b/src/panes.zig index 4f9ac6fc..77246653 100644 --- a/src/panes.zig +++ b/src/panes.zig @@ -1088,8 +1088,6 @@ pub const Dir = @import("Dir.zig"); pub const mini = @import("mini.zig"); -pub const terminal = @import("term/terminal.zig"); - pub const Term = @import("Term.zig"); /// What a pane says when a position kept over its terminal's rows could @@ -1558,7 +1556,6 @@ test { _ = Dir; _ = mini; _ = @import("Kind.zig"); - _ = terminal; } test "owned cwd preserves long paths aliases and failed updates" { @@ -1712,7 +1709,7 @@ test "owned cwd EOF failure retains the pane and Del retries its close" { } test "owned cwd restore either copies the directory or preserves the old core" { - // No terminal: ghostty 1.4's snapshot decode leaks when an allocation + // No terminal: the emulator's (1.4) snapshot decode leaks when an allocation // inside it fails, and this fails every allocation of a Restore in turn // (what pardes's own load made is freed, src/walk.zig rollback). var allocator = std.testing.FailingAllocator.init(std.testing.allocator, .{}); diff --git a/src/pardes.zig b/src/pardes.zig index f8f49fb3..2b956882 100644 --- a/src/pardes.zig +++ b/src/pardes.zig @@ -71,11 +71,9 @@ pub const config = @import("config.zig"); pub const memory = @import("memory.zig"); pub const tape = @import("tape.zig"); pub const walk = @import("walk.zig"); -pub const screen_state = @import("term/screen_state.zig"); pub const views = @import("views.zig"); pub const rollback = @import("rollback.zig"); pub const replica = @import("replica.zig"); -pub const echo = @import("term/echo.zig"); pub const Kind = @import("Kind.zig"); /// The terminal, as the core calls it (src/term/ behind it). pub const Term = @import("Term.zig"); @@ -392,7 +390,6 @@ test { _ = @import("Effect.zig"); _ = @import("tape.zig"); _ = @import("replica.zig"); - _ = @import("term/echo.zig"); _ = Term; _ = @import("modal.zig"); _ = @import("tagline.zig"); @@ -429,6 +426,5 @@ test { _ = @import("Tables.zig"); _ = @import("Handover.zig"); _ = @import("walk.zig"); - _ = screen_state; _ = @import("views.zig"); } diff --git a/src/replica.zig b/src/replica.zig index fa6cfadb..b746ddb6 100644 --- a/src/replica.zig +++ b/src/replica.zig @@ -30,9 +30,8 @@ const walk = @import("walk.zig"); const wire = @import("wire.zig"); const daemon = @import("daemon.zig"); const writeAll = daemon.writeAll; -const screen_state = @import("term/screen_state.zig"); const c_heap = @import("c_heap"); -const terminal = pardes.panes.terminal; +const Term = pardes.Term; const Allocator = std.mem.Allocator; const Pardes = pardes.Pardes; @@ -330,7 +329,7 @@ fn writeScreenHead(out: *std.ArrayListUnmanaged(u8), gpa: Allocator, pane: u8, s /// pane, and what each peer was sent of it. pub const Screens = struct { gpa: Allocator, - enc: screen_state.Encoder, + enc: Term.Encoder, tracks: [pardes.MAX_PANES]?Tracked = @splat(null), peers: std.ArrayListUnmanaged(*[pardes.MAX_PANES]PeerOf) = .empty, free_peers: std.ArrayListUnmanaged(u16) = .empty, @@ -338,8 +337,8 @@ pub const Screens = struct { /// Nanoseconds: what each flush spent encoding, for every peer. encode_ns: u64 = 0, - const Tracked = struct { serial: u32, state: *terminal.State, track: screen_state.Track }; - const PeerOf = struct { serial: u32 = 0, peer: screen_state.Peer = .{}, shadow: screen_state.ShadowSent = .{} }; + const Tracked = struct { serial: u32, state: *Term.State, track: Term.Track }; + const PeerOf = struct { serial: u32 = 0, peer: Term.Peer = .{}, shadow: pardes.Kind.ShadowSent = .{} }; pub fn init(gpa: Allocator) Screens { return .{ .gpa = gpa, .enc = .init(gpa) }; @@ -347,7 +346,7 @@ pub const Screens = struct { /// `core` is the session's, its terminals still there. pub fn deinit(s: *Screens, core: *Pardes) void { - for (&s.tracks, 0..) |*slot, id| if (slot.*) |*tr| tr.track.deinit(s.gpa, if (s.live(core, id, tr)) &tr.state.vt else null); + for (&s.tracks, 0..) |*slot, id| if (slot.*) |*tr| Term.untrack(&tr.track, s.gpa, if (s.live(core, id, tr)) tr.state else null); for (s.peers.items) |p| { for (p) |*pp| { pp.peer.deinit(s.gpa); @@ -402,12 +401,11 @@ pub const Screens = struct { pp.peer.reset(); pp.serial = pane.serial; } - var marks: [terminal.marks_len]u8 = undefined; s.out.clearRetainingCapacity(); try writeScreenHead(&s.out, s.gpa, @intCast(id), pane.serial, kind_delta); var w: std.Io.Writer.Allocating = .fromArrayList(s.gpa, &s.out); defer s.out = w.toArrayList(); - if (!try screen_state.encode(&s.enc, &tr.track, &pp.peer, &state.vt, state.changes, terminal.marksOf(state, &marks), &w.writer)) continue; + if (!try Term.encode(state, &s.enc, &tr.track, &pp.peer, &w.writer)) continue; try out.append(s.gpa, try s.gpa.dupe(u8, w.written())); } } @@ -440,14 +438,14 @@ pub const Screens = struct { // lacks, each a message before the frame naming them. for (frame.places[0..@min(frame.n, 64)]) |*pl| { // A row past a strip's bound cannot cross: not shown there. - if (@as(usize, pl.w) * 4 > screen_state.strip_max) continue; + if (@as(usize, pl.w) * 4 > pardes.Kind.strip_max) continue; var owed = try pp.shadow.owed(x.s.gpa, pl); while (owed != 0) : (owed &= owed - 1) { x.s.out.clearRetainingCapacity(); try writeScreenHead(&x.s.out, x.s.gpa, @intCast(id), pane.serial, kind_raster); var w: std.Io.Writer.Allocating = .fromArrayList(x.s.gpa, &x.s.out); defer x.s.out = w.toArrayList(); - try screen_state.encodeStrip(pl, @ctz(owed), &w.writer); + try pardes.Kind.encodeStrip(pl, @ctz(owed), &w.writer); try x.out.append(x.s.gpa, try x.s.gpa.dupe(u8, w.written())); } } @@ -455,7 +453,7 @@ pub const Screens = struct { try writeScreenHead(&x.s.out, x.s.gpa, @intCast(id), pane.serial, kind_shadow); var w: std.Io.Writer.Allocating = .fromArrayList(x.s.gpa, &x.s.out); defer x.s.out = w.toArrayList(); - if (!try screen_state.encodeShadow(x.s.gpa, &pp.shadow, &frame, k.pointer, &w.writer)) continue; + if (!try pardes.Kind.encodeShadow(x.s.gpa, &pp.shadow, &frame, k.pointer, &w.writer)) continue; try x.out.append(x.s.gpa, try x.s.gpa.dupe(u8, w.written())); }; } @@ -473,7 +471,7 @@ pub const Screens = struct { for (core.panes, 0..) |slot, id| { const pane = slot orelse continue; const state = pane.terminal orelse continue; - if (!state.read) continue; + if (!Term.wasRead(state)) continue; const pp = &s.peers.items[peer][id]; if (pp.serial != pane.serial or pp.peer.holes.items.len == 0) continue; const tr = try s.track(core, id); @@ -485,7 +483,7 @@ pub const Screens = struct { try writeScreenHead(&s.out, s.gpa, @intCast(id), pane.serial, kind_rows); var w: std.Io.Writer.Allocating = .fromArrayList(s.gpa, &s.out); defer s.out = w.toArrayList(); - try screen_state.encodeRows(&s.enc, &tr.track, &state.vt, lo, hi, &w.writer); + try Term.encodeRows(state, &s.enc, &tr.track, lo, hi, &w.writer); try out.append(s.gpa, try s.gpa.dupe(u8, w.written())); lo = hi; } @@ -497,7 +495,7 @@ pub const Screens = struct { /// Every peer is filled: the steps' reads are forgotten. pub fn filled(_: *Screens, core: *Pardes) void { for (core.panes) |slot| if (slot) |pane| if (pane.terminal) |state| { - state.read = false; + Term.clearRead(state); }; } @@ -506,7 +504,7 @@ pub const Screens = struct { if (s.tracks[id]) |*tr| { if (s.live(core, id, tr)) return tr; // Its pane closed (its emulator, the pin with it, gone). - tr.track.deinit(s.gpa, null); + Term.untrack(&tr.track, s.gpa, null); } s.tracks[id] = .{ .serial = pane.serial, .state = pane.terminal.?, .track = .init(s.gpa) }; return &s.tracks[id].?; @@ -533,7 +531,7 @@ pub const Screens = struct { try writeScreenHead(&s.out, s.gpa, m.pane, m.serial, kind_rows); var w: std.Io.Writer.Allocating = .fromArrayList(s.gpa, &s.out); defer s.out = w.toArrayList(); - try screen_state.encodeRows(&s.enc, &tr.track, &state.vt, std.mem.readInt(u64, m.payload[0..8], .little), std.mem.readInt(u64, m.payload[8..16], .little), &w.writer); + try Term.encodeRows(state, &s.enc, &tr.track, std.mem.readInt(u64, m.payload[0..8], .little), std.mem.readInt(u64, m.payload[8..16], .little), &w.writer); return try s.gpa.dupe(u8, w.written()); }, else => {}, @@ -679,14 +677,14 @@ pub const Replica = struct { views: [pardes.MAX_PANES]View = @splat(.{}), screen_out: std.ArrayListUnmanaged(u8) = .empty, /// Its Shadows' rasters, from the session's strips (17.3). - blobs: screen_state.Blobs = .{}, + blobs: pardes.Kind.Blobs = .{}, /// Its predicted echo (src/term/echo.zig), drawn over its core's terminals: /// fed by its keys, its units and its deltas here, and by `echoFrame`. - echo: pardes.echo.Echo = .{}, + echo: Term.Echo = .{}, const ScreenOf = struct { serial: u32, - rep: screen_state.Replica = .{}, + rep: Term.Replica = .{}, /// A delta was refused, and a reset asked for: those in flight /// before it are refused unasked. refused: bool = false, @@ -1144,7 +1142,7 @@ pub const Replica = struct { // A pane of a kind: the authority's frame of it, drawn as it is. if (m.kind == kind_shadow) if (pane.addon) |k| { const sh = k.shadow orelse sh: { - const made = k.gpa.create(screen_state.Shadow) catch return null; + const made = k.gpa.create(pardes.Kind.Shadow) catch return null; made.* = .{}; k.shadow = made; break :sh made; @@ -1168,7 +1166,7 @@ pub const Replica = struct { switch (m.kind) { kind_delta => { const t0 = nowNs(); - const applied = sc.rep.apply(state.gpa, terminal.terminalIo(), &state.vt, m.payload) catch |err| { + const applied = Term.apply(state, &sc.rep, m.payload) catch |err| { if (err != error.BaseMismatch) r.fail("a terminal's delta did not apply"); if (sc.refused) return null; sc.refused = true; @@ -1176,7 +1174,6 @@ pub const Replica = struct { }; if (r.stats.samples) r.stats.apply_ns.append(r.gpa, nowNs() - t0) catch {}; sc.refused = false; - terminal.takeMarks(state, applied.extra); r.echo.delta(c, m.pane, sc.rep.top); // Its rows as the core keeps them read are another grid's. c.shell_rows.markStale(pane); @@ -1190,7 +1187,7 @@ pub const Replica = struct { }, kind_rows => { sc.asked = null; - sc.rep.applyRows(state.gpa, &state.vt, m.payload) catch r.fail("a terminal's rows did not apply"); + Term.applyRows(state, &sc.rep, m.payload) catch r.fail("a terminal's rows did not apply"); c.shell_rows.markStale(pane); r.overTerminals(); return null; @@ -1225,13 +1222,13 @@ pub const Replica = struct { const pane = c.panes[id] orelse continue; if (pane.serial != sc.serial) continue; const state = pane.terminal orelse continue; - const shown = sc.rep.shown(&state.vt); + const shown = Term.shown(state, &sc.rep); var holes: std.ArrayList([2]u64) = .empty; defer holes.deinit(r.gpa); sc.rep.missing(shown[0], shown[1], &holes, r.gpa) catch return null; if (holes.items.len == 0) continue; const want: [2]u64 = .{ holes.items[0][0], holes.items[holes.items.len - 1][1] }; - sc.rep.blank(&state.vt, want[0], want[1]); + Term.blank(state, &sc.rep, want[0], want[1]); sc.asked = want; var range: [16]u8 = undefined; std.mem.writeInt(u64, range[0..8], want[0], .little); @@ -3460,8 +3457,8 @@ test "a delta applied under a speculation outlives its rollback: the terminal st defer dump_a.deinit(); var dump_r: std.Io.Writer.Allocating = .init(gpa); defer dump_r.deinit(); - try screen_state.dumpScreen(&a.core.panes[shell].?.terminal.?.vt, &dump_a.writer); - try screen_state.dumpScreen(&r.core().panes[shell].?.terminal.?.vt, &dump_r.writer); + try Term.dumpScreen(a.core.panes[shell].?.terminal.?, &dump_a.writer); + try Term.dumpScreen(r.core().panes[shell].?.terminal.?, &dump_r.writer); try std.testing.expectEqualStrings(dump_a.written(), dump_r.written()); const rows_a = try pardes.edit.shellRows(a.core, a.core.panes[shell].?); const rows_r = try pardes.edit.shellRows(r.core(), r.core().panes[shell].?); diff --git a/src/tagline.zig b/src/tagline.zig index fa5246c4..1bb4dc85 100644 --- a/src/tagline.zig +++ b/src/tagline.zig @@ -157,9 +157,9 @@ pub fn pathPrefix(p: *const Pardes, arena: std.mem.Allocator, pane: *Pane) ![]co if (pane.file) |f| return if (pane.prompt == .name) pane.input.own orelse f.path else f.path; // A terminal showing kitty graphics says how it draws them, as an image // pane does, and so does one drawing them as glyph art by choice. - if (panes.terminal.petscii(pane)) |chosen| { + if (panes.Term.petscii(pane.terminal)) |chosen| { const on = chosen or !p.view().frontend.native_images; - if (chosen or panes.terminal.hasImages(pane)) + if (chosen or panes.Term.hasImages(pane.terminal)) return std.fmt.allocPrint(arena, "{s} petscii:{s}", .{ (try shownDir(arena, pane)), if (on) "on" else "off" }); } return (try shownDir(arena, pane)); diff --git a/src/tape.zig b/src/tape.zig index 9c3730f0..fd5b4b85 100644 --- a/src/tape.zig +++ b/src/tape.zig @@ -21,7 +21,6 @@ const std = @import("std"); const pardes = @import("pardes.zig"); const walk = @import("walk.zig"); const host_io = @import("host_io.zig"); -const terminal = @import("term/terminal.zig"); const Pardes = pardes.Pardes; const VTable = pardes.Host.VTable; const libc = std.c; diff --git a/src/term/echo.zig b/src/term/echo.zig index 9ea13111..a5c65f7e 100644 --- a/src/term/echo.zig +++ b/src/term/echo.zig @@ -29,7 +29,7 @@ //! there is ever shown. const std = @import("std"); const pardes = @import("../pardes.zig"); -const terminal = pardes.panes.terminal; +const terminal = @import("terminal.zig"); const Pardes = pardes.Pardes; const Pane = pardes.Pane; const Surface = pardes.Surface; diff --git a/src/term/screen_state.zig b/src/term/screen_state.zig index bbb7f959..43eae542 100644 --- a/src/term/screen_state.zig +++ b/src/term/screen_state.zig @@ -1135,282 +1135,6 @@ pub fn yesStream(gpa: std.mem.Allocator, lines: usize) ![]u8 { return out; } -// ---- a pane of a kind, as a Shadow (architecture §16.5) ---- -// -// A replica's core has no code for a library's kind: such a pane is drawn -// from the authority's frame of it, painted at the size the peer's view -// gives it. A frame crosses as its size and the pointer it asks for, each -// row by its hash (with its cells when the peer's row there is another), -// then each placement by its key; its raster's pixels cross before it, as -// strips of rows (`raster` messages, `encodeStrip`), those over its `src` -// the peer was not sent with the frame before. The stream is ordered and -// loses nothing, so what the authority last sent a peer is what the peer -// holds, but for a raster its `Blobs` let go, which it asks for again. - -const Kind = @import("../Kind.zig"); -const Cell = Kind.c.pa_cell; -const Place = Kind.c.pa_placement; - -/// A replica's frame of a pane of a kind: what Kind.draw draws for it, its -/// placements' pixels its peer's `Blobs`. -pub const Shadow = struct { - gpu: []const u8 = &.{}, - cols: u16 = 0, - rows: u16 = 0, - cells: []Cell = &.{}, - hashes: []Hash = &.{}, - places: std.ArrayList(Place) = .empty, - pointer: u8 = 0, - /// The raster it last asked for again (`apply`'s): asked once. - wanted: u64 = 0, - - pub fn deinit(sh: *Shadow, gpa: std.mem.Allocator) void { - gpa.free(sh.gpu); - gpa.free(sh.cells); - gpa.free(sh.hashes); - sh.places.deinit(gpa); - gpa.destroy(sh); - } - - /// A frame message applied (`encodeShadow`'s), of the pane `serial`, - /// each placement's pixels from `blobs`: one it lacks is not shown, and - /// its name is what to ask for (once), else 0. - pub fn apply(sh: *Shadow, gpa: std.mem.Allocator, bytes: []const u8, serial: u32, blobs: *Blobs) !u64 { - var r: std.Io.Reader = .fixed(bytes); - const cols = try r.takeInt(u16, .little); - const rows = try r.takeInt(u16, .little); - if (cols != sh.cols or rows != sh.rows) { - gpa.free(sh.cells); - gpa.free(sh.hashes); - sh.cells = try gpa.alloc(Cell, @as(usize, cols) * rows); - sh.hashes = try gpa.alloc(Hash, rows); - @memset(std.mem.sliceAsBytes(sh.cells), 0); - @memset(sh.hashes, 0); - sh.cols = cols; - sh.rows = rows; - } - sh.pointer = try r.takeByte(); - for (0..rows) |y| { - sh.hashes[y] = try r.takeInt(u64, .little); - if (try r.takeByte() == 0) continue; - for (sh.cells[y * cols ..][0..cols]) |*c| { - @memcpy(&c.text, try r.take(8)); - c.fg = try r.takeInt(u32, .little); - c.bg = try r.takeInt(u32, .little); - c.attrs = try r.takeInt(u16, .little); - c.len = try r.takeByte(); - c.flags = try r.takeByte(); - } - } - sh.places.clearRetainingCapacity(); - var lacking: u64 = 0; - for (0..try r.takeByte()) |_| { - var pl = std.mem.zeroes(Place); - pl.w = try r.takeInt(u32, .little); - pl.h = try r.takeInt(u32, .little); - inline for (.{ &pl.src.x, &pl.src.y, &pl.src.w, &pl.src.h, &pl.at.x, &pl.at.y, &pl.at.w, &pl.at.h }) |f| f.* = try r.takeInt(u32, .little); - inline for (.{ &pl.dst.x, &pl.dst.y, &pl.dst.w, &pl.dst.h }) |f| f.* = try r.takeInt(u16, .little); - pl.key = try r.takeInt(u64, .little); - const name = std.hash.Wyhash.hash(serial, std.mem.asBytes(&pl.key)); - pl.rgba = (blobs.shows(name, &pl) orelse { - lacking = name; - continue; - }).ptr; - try sh.places.append(gpa, pl); - } - // Older frames have no optional GPU tail. - const n = if (r.seek < r.end) try r.takeInt(u32, .little) else 0; - if (n > 4 << 20) return error.BadGpuFrame; - const gpu = try gpa.dupe(u8, try r.take(n)); - gpa.free(sh.gpu); - sh.gpu = gpu; - if (lacking == sh.wanted) return 0; - sh.wanted = lacking; - return lacking; - } -}; - -/// A raster's strip: at most this many bytes of its rows (17.3). -pub const strip_max = 4 << 20; - -/// How many of a `w`-pixel raster's rows a strip holds. -pub fn stripRows(w: u32) u32 { - return @max(1, strip_max / (@as(u32, @max(w, 1)) * 4)); -} - -/// The strips of `pl`'s raster over its `src` rows, a bit each. -fn stripsOver(pl: *const Place) u64 { - const per = stripRows(pl.w); - const lo = @min(pl.src.y, pl.h) / per; - const hi = (@min(pl.src.y +| pl.src.h, pl.h) + per - 1) / per; - var bits: u64 = 0; - for (lo..@min(hi, 64)) |i| bits |= @as(u64, 1) << @intCast(i); - return bits; -} - -/// Strip `i` of `pl`'s raster, a `raster` message's payload: its key, its -/// size, its first row, and its rows' bytes. -pub fn encodeStrip(pl: *const Place, i: u32, w: *std.Io.Writer) !void { - const y0 = i * stripRows(pl.w); - const row = @as(usize, pl.w) * 4; - try w.writeInt(u64, pl.key, .little); - try w.writeInt(u32, pl.w, .little); - try w.writeInt(u32, pl.h, .little); - try w.writeInt(u32, y0, .little); - try w.writeAll(pl.rgba[y0 * row .. @min(pl.h, y0 + stripRows(pl.w)) * row]); -} - -/// A peer's rasters of the panes of a kind, made from their strips by -/// name (the key with its pane's serial), kept to `max` bytes by least -/// recent use but for those a Shadow shows (17.3). -pub const Blobs = struct { - list: std.ArrayList(Blob) = .empty, - clock: u64 = 0, - - pub const max = 64 << 20; - const Blob = struct { name: u64, w: u32, h: u32, bytes: []u8, have: u64 = 0, used: u64 = 0 }; - - pub fn deinit(b: *Blobs, gpa: std.mem.Allocator) void { - for (b.list.items) |x| gpa.free(x.bytes); - b.list.deinit(gpa); - } - - /// A `raster` message's payload (`encodeStrip`'s) into raster `name`, - /// made at its first strip; `shown`, the pixels Shadows show now. - pub fn strip(b: *Blobs, gpa: std.mem.Allocator, name: u64, payload: []const u8, shown: []const [*]const u8) !void { - var r: std.Io.Reader = .fixed(payload); - _ = try r.takeInt(u64, .little); - const w = try r.takeInt(u32, .little); - const h = try r.takeInt(u32, .little); - const y0 = try r.takeInt(u32, .little); - const rows = r.buffered(); - const row = @as(usize, w) * 4; - if (row == 0 or rows.len % row != 0 or y0 % stripRows(w) != 0 or y0 + rows.len / row > h) return error.BadShadow; - const x = for (b.list.items) |*x| { - if (x.name == name) break x; - } else made: { - var held: usize = row * h; - for (b.list.items) |x| held += x.bytes.len; - while (held > max) { - var old: ?usize = null; - for (b.list.items, 0..) |x, i| if (std.mem.indexOfScalar([*]const u8, shown, x.bytes.ptr) == null and (old == null or x.used < b.list.items[old.?].used)) { - old = i; - }; - const i = old orelse break; - held -= b.list.items[i].bytes.len; - gpa.free(b.list.swapRemove(i).bytes); - } - const bytes = try gpa.alloc(u8, row * h); - errdefer gpa.free(bytes); - try b.list.append(gpa, .{ .name = name, .w = w, .h = h, .bytes = bytes }); - break :made &b.list.items[b.list.items.len - 1]; - }; - if (x.w != w or x.h != h) return error.BadShadow; - @memcpy(x.bytes[y0 * row ..][0..rows.len], rows); - x.have |= @as(u64, 1) << @intCast(@min(63, y0 / stripRows(w))); - b.clock += 1; - x.used = b.clock; - } - - /// Raster `name`'s pixels when it has every strip `pl` shows. - fn shows(b: *Blobs, name: u64, pl: *const Place) ?[]u8 { - for (b.list.items) |*x| if (x.name == name and x.w == pl.w and x.h == pl.h and stripsOver(pl) & ~x.have == 0) { - b.clock += 1; - x.used = b.clock; - return x.bytes; - }; - return null; - } -}; - -/// What the authority last sent one peer of a pane of a kind: its rows' -/// hashes, its placements, and which strips of each raster it holds. -pub const ShadowSent = struct { - serial: u32 = 0, - cols: u16 = 0, - hashes: std.ArrayList(Hash) = .empty, - places: Hash = 0, - keys: std.ArrayList(struct { key: u64, have: u64 }) = .empty, - - pub fn deinit(s: *ShadowSent, gpa: std.mem.Allocator) void { - s.hashes.deinit(gpa); - s.keys.deinit(gpa); - s.* = .{}; - } - - /// The strips of `pl`'s raster over its `src` the peer lacks (a bit - /// each, `encodeStrip`'s `i`), counted sent now. - pub fn owed(s: *ShadowSent, gpa: std.mem.Allocator, pl: *const Place) !u64 { - const need = stripsOver(pl); - for (s.keys.items) |*k| if (k.key == pl.key) { - defer k.have |= need; - return need & ~k.have; - }; - try s.keys.append(gpa, .{ .key = pl.key, .have = need }); - return need; - } -}; - -/// Frame `f` of a pane (the pointer its paint asked for) for a peer that -/// was last sent `sent`: false, and nothing written, when it holds this -/// frame already. Its placements cross by key, their pixels as strips -/// before it (`ShadowSent.owed`), so a frame is small whatever it shows. -pub fn encodeShadow(gpa: std.mem.Allocator, sent: *ShadowSent, f: *const Kind.Frame, pointer: u8, w: *std.Io.Writer) !bool { - var hashes: std.ArrayList(Hash) = .empty; - errdefer hashes.deinit(gpa); - for (0..f.rows) |y| try hashes.append(gpa, std.hash.Wyhash.hash(0, std.mem.sliceAsBytes(f.cells[y * f.cols ..][0..f.cols]))); - const places = f.places[0..@min(f.n, 64)]; - var ph = std.hash.Wyhash.init(pointer); - for (places) |*pl| inline for (.{ pl.w, pl.h, pl.src, pl.at, pl.dst, pl.key }) |v| ph.update(std.mem.asBytes(&v)); - if (f.gpu.len != 0) ph.update(f.gpu); - const places_hash = ph.final(); - if (sent.cols == f.cols and std.mem.eql(Hash, sent.hashes.items, hashes.items) and sent.places == places_hash) { - hashes.deinit(gpa); - return false; - } - try w.writeInt(u16, f.cols, .little); - try w.writeInt(u16, f.rows, .little); - try w.writeByte(pointer); - for (hashes.items, 0..) |h, y| { - try w.writeInt(u64, h, .little); - // Held only at the same size: a peer's Shadow of another starts afresh. - const held = sent.cols == f.cols and sent.hashes.items.len == f.rows and sent.hashes.items[y] == h; - try w.writeByte(@intFromBool(!held)); - if (!held) for (f.cells[y * f.cols ..][0..f.cols]) |*c| { - try w.writeAll(&c.text); - try w.writeInt(u32, c.fg, .little); - try w.writeInt(u32, c.bg, .little); - try w.writeInt(u16, c.attrs, .little); - try w.writeByte(c.len); - try w.writeByte(c.flags); - }; - } - try w.writeByte(@intCast(places.len)); - for (places) |pl| { - try w.writeInt(u32, pl.w, .little); - try w.writeInt(u32, pl.h, .little); - inline for (.{ pl.src.x, pl.src.y, pl.src.w, pl.src.h, pl.at.x, pl.at.y, pl.at.w, pl.at.h }) |v| try w.writeInt(u32, v, .little); - inline for (.{ pl.dst.x, pl.dst.y, pl.dst.w, pl.dst.h }) |v| try w.writeInt(u16, v, .little); - try w.writeInt(u64, pl.key, .little); - } - if (f.gpu.len > 4 << 20) return error.BadGpuFrame; - try w.writeInt(u32, @intCast(f.gpu.len), .little); - try w.writeAll(f.gpu); - sent.hashes.deinit(gpa); - sent.hashes = hashes; - sent.cols = f.cols; - sent.places = places_hash; - // The strips of the rasters this frame shows: a key gone is sent whole again. - var i: usize = 0; - while (i < sent.keys.items.len) { - const kept = for (places) |pl| { - if (pl.key == sent.keys.items[i].key) break true; - } else false; - if (kept) i += 1 else _ = sent.keys.swapRemove(i); - } - return true; -} - test "a replica's screen is its authority's, cell for cell, as states are skipped, resized and fetched" { const gpa = testing.allocator; const io = testing.io; @@ -1568,97 +1292,3 @@ test "a replica's terminal pane draws as its authority's does" { }; } } - -test "a pane of a kind's frame a row taller or shorter is drawn whole at its peer, never a row it let go" { - const gpa = std.testing.allocator; - var cells: [2 * 3]Cell = @splat(std.mem.zeroes(Cell)); - cells[0] = .{ .text = "a".* ++ @as([7]u8, @splat(0)), .fg = 1, .bg = 2, .attrs = 0, .len = 1, .flags = Kind.c.PA_PAINTED }; - var f: Kind.Frame = .{ .cells = &cells, .cols = 2, .rows = 2 }; - var sent: ShadowSent = .{}; - defer sent.deinit(gpa); - var blobs: Blobs = .{}; - const sh = try gpa.create(Shadow); - sh.* = .{}; - defer sh.deinit(gpa); - var out: std.Io.Writer.Allocating = .init(gpa); - defer out.deinit(); - for ([_]u16{ 2, 3, 2 }) |rows| { - f.rows = rows; - out.clearRetainingCapacity(); - try std.testing.expect(try encodeShadow(gpa, &sent, &f, 0, &out.writer)); - _ = try sh.apply(gpa, out.written(), 1, &blobs); - try std.testing.expectEqualStrings("a", sh.cells[0].text[0..1]); - } -} - -test "a pane of a kind crosses as its frame, a row the peer holds as its hash, a raster by key after its strips over what it shows" { - const gpa = std.testing.allocator; - var cells: [3 * 2]Cell = @splat(std.mem.zeroes(Cell)); - cells[0] = .{ .text = "a".* ++ @as([7]u8, @splat(0)), .fg = 1, .bg = 2, .attrs = 0, .len = 1, .flags = Kind.c.PA_PAINTED }; - // A raster of three strips (4 MiB a strip at 1,024 px), of which it shows the second. - const w: u32 = 1024; - const per = stripRows(w); - const pixels = try gpa.alloc(u8, @as(usize, w) * per * 3 * 4); - defer gpa.free(pixels); - @memset(pixels, 5); - var f: Kind.Frame = .{ .cells = &cells, .cols = 3, .rows = 2, .n = 1 }; - f.buf[0] = std.mem.zeroInit(Place, .{ .rgba = pixels.ptr, .w = w, .h = per * 3, .src = .{ .x = 0, .y = per + 1, .w = w, .h = 10 }, .key = 9 }); - f.places = &f.buf; - var sent: ShadowSent = .{}; - defer sent.deinit(gpa); - var blobs: Blobs = .{}; - defer blobs.deinit(gpa); - const sh = try gpa.create(Shadow); - sh.* = .{}; - defer sh.deinit(gpa); - var out: std.Io.Writer.Allocating = .init(gpa); - defer out.deinit(); - const name = std.hash.Wyhash.hash(1, std.mem.asBytes(&f.buf[0].key)); - try std.testing.expectEqual(@as(u64, 0b010), try sent.owed(gpa, &f.buf[0])); - try encodeStrip(&f.buf[0], 1, &out.writer); - try std.testing.expect(out.written().len <= strip_max + 20); - try blobs.strip(gpa, name, out.written(), &.{}); - out.clearRetainingCapacity(); - try std.testing.expect(try encodeShadow(gpa, &sent, &f, 0, &out.writer)); - try std.testing.expectEqual(@as(u64, 0), try sh.apply(gpa, out.written(), 1, &blobs)); - try std.testing.expectEqualStrings("a", sh.cells[0].text[0..1]); - try std.testing.expectEqual(@as(u8, 5), sh.places.items[0].rgba[per * w * 4]); - // The same frame again: nothing to send, no strip owed. - out.clearRetainingCapacity(); - try std.testing.expect(!try encodeShadow(gpa, &sent, &f, 0, &out.writer)); - try std.testing.expectEqual(@as(u64, 0), try sent.owed(gpa, &f.buf[0])); - // Its src moves into the third strip: that one is owed, and a peer - // without it does not show the raster and asks for it, once. - f.buf[0].src.y = 2 * per + 1; - try std.testing.expectEqual(@as(u64, 0b100), try sent.owed(gpa, &f.buf[0])); - out.clearRetainingCapacity(); - try std.testing.expect(try encodeShadow(gpa, &sent, &f, 0, &out.writer)); - try std.testing.expect(out.written().len < 4 + 1 + 2 * 9 + 60 + 8); - try std.testing.expectEqual(name, try sh.apply(gpa, out.written(), 1, &blobs)); - try std.testing.expectEqual(@as(usize, 0), sh.places.items.len); - try std.testing.expectEqual(@as(u64, 0), try sh.apply(gpa, out.written(), 1, &blobs)); -} - -test "optional GPU frames cross shadows, change independently, and disappear" { - const gpa = std.testing.allocator; - var sent: ShadowSent = .{}; - defer sent.deinit(gpa); - const shadow = try gpa.create(Shadow); - shadow.* = .{}; - defer shadow.deinit(gpa); - var blobs: Blobs = .{}; - defer blobs.deinit(gpa); - var cell = std.mem.zeroes(Cell); - var frame: Kind.Frame = .{ .cols = 1, .rows = 1, .cells = @as([*]Cell, @ptrCast(&cell))[0..1], .gpu = "first scene" }; - var out: std.Io.Writer.Allocating = .init(gpa); - defer out.deinit(); - for ([_][]const u8{ "first scene", "second scene", "" }) |bytes| { - frame.gpu = bytes; - out.clearRetainingCapacity(); - try std.testing.expect(try encodeShadow(gpa, &sent, &frame, 0, &out.writer)); - _ = try shadow.apply(gpa, out.written(), 1, &blobs); - try std.testing.expectEqualStrings(bytes, shadow.gpu); - out.clearRetainingCapacity(); - try std.testing.expect(!try encodeShadow(gpa, &sent, &frame, 0, &out.writer)); - } -} diff --git a/src/term/terminal.zig b/src/term/terminal.zig index 70cd4e9d..85ac859d 100644 --- a/src/term/terminal.zig +++ b/src/term/terminal.zig @@ -13,6 +13,7 @@ const Key = pardes.Key; const Pane = panes.Pane; const Term = @import("../Term.zig"); const BodyWalk = @import("../body_layer.zig").BodyWalk; +const screen_state = @import("screen_state.zig"); const EditText = panes.EditText; const File = panes.File; @@ -483,6 +484,65 @@ pub fn takeMarks(state: *State, bytes: []const u8) void { m.finished = if (seq == std.math.maxInt(u32)) null else .{ .seq = seq, .status = if (status == std.math.minInt(i32)) null else status }; } +// ---- its replicas: the screen state they are sent (screen_state.zig) ---- + +/// What `peer` is owed of it, a delta against what it was sent (with the +/// marks of its prompt cycle), onto `out`; false when it has it already. +pub fn encode(state: *State, enc: *screen_state.Encoder, track: *screen_state.Track, peer: *screen_state.Peer, out: *std.Io.Writer) !bool { + var marks: [marks_len]u8 = undefined; + return screen_state.encode(enc, track, peer, &state.vt, state.changes, marksOf(state, &marks), out); +} + +/// Its rows `lo` to `hi` (absolute), as a replica holding them as holes +/// is sent them. +pub fn encodeRows(state: *State, enc: *screen_state.Encoder, track: *screen_state.Track, lo: u64, hi: u64, out: *std.Io.Writer) !void { + return screen_state.encodeRows(enc, track, &state.vt, lo, hi, out); +} + +/// What `track` kept of its versions, freed; `state` null when its pane is +/// gone with the emulator. +pub fn untrack(track: *screen_state.Track, gpa: std.mem.Allocator, state: ?*State) void { + track.deinit(gpa, if (state) |s| &s.vt else null); +} + +/// Whether a step read its rows since `clearRead` (`markRead`). +pub fn wasRead(state: *const State) bool { + return state.read; +} + +pub fn clearRead(state: *State) void { + state.read = false; +} + +/// A replica's terminal takes its authority's delta (and the marks riding +/// it); error.BaseMismatch when it is against a state not held here. +pub fn apply(state: *State, rep: *screen_state.Replica, bytes: []const u8) !screen_state.Replica.Applied { + const applied = try rep.apply(state.gpa, terminalIo(), &state.vt, bytes); + takeMarks(state, applied.extra); + return applied; +} + +/// ...and rows it asked for. +pub fn applyRows(state: *State, rep: *screen_state.Replica, bytes: []const u8) !void { + return rep.applyRows(state.gpa, &state.vt, bytes); +} + +/// The absolute rows its view shows on a replica. +pub fn shown(state: *State, rep: *const screen_state.Replica) [2]u64 { + return rep.shown(&state.vt); +} + +/// Its screen as text, every row's cells and flags (the replica tests +/// compare an authority's and a replica's). +pub fn dumpScreen(state: *State, w: *std.Io.Writer) !void { + return screen_state.dumpScreen(&state.vt, w); +} + +/// Rows `lo` to `hi` shown blank on a replica until they come. +pub fn blank(state: *State, rep: *const screen_state.Replica, lo: u64, hi: u64) void { + rep.blank(&state.vt, lo, hi); +} + const authorityOnly = pardes.tape.authorityOnly; /// Its view to row `at` of its history (from the top), or onto its output. @@ -1093,7 +1153,7 @@ pub fn textRows(state: *State, alloc: std.mem.Allocator, scratch: std.mem.Alloca var n: usize = 0; var it = std.mem.splitScalar(u8, full, '\n'); while (it.next()) |raw| { - const shown = if (pit.next()) |pin| + const kept = if (pit.next()) |pin| if (pin.rowAndCell().row.semantic_prompt != .none) promptRow(pin, raw) else raw else raw; @@ -1101,9 +1161,9 @@ pub fn textRows(state: *State, alloc: std.mem.Allocator, scratch: std.mem.Alloca text[at] = '\n'; at += 1; } - @memcpy(text[at..][0..shown.len], shown); - lines[n] = text[at..][0..shown.len]; - at += shown.len; + @memcpy(text[at..][0..kept.len], kept); + lines[n] = text[at..][0..kept.len]; + at += kept.len; n += 1; } text[at] = '\n'; @@ -1634,24 +1694,23 @@ pub fn due(state: *const State) ?u64 { /// The Petscii builtin on a terminal: its kitty graphics as glyph art, /// or back to pixels where the shell draws pixels. -pub fn togglePetscii(pane: *Pane) void { +pub fn togglePetscii(state: *State) void { if (comptime !images_enabled) return; - const state = pane.terminal orelse return; state.images.petscii = !state.images.petscii; } /// Whether the pane draws its kitty graphics as glyph art by choice; null /// for a pane with no emulator. -pub fn petscii(pane: *const Pane) ?bool { +pub fn petscii(maybe: ?*const State) ?bool { if (comptime !images_enabled) return null; - const state = pane.terminal orelse return null; + const state = maybe orelse return null; return state.images.petscii; } /// Whether the screen showing holds any kitty graphics image. -pub fn hasImages(pane: *const Pane) bool { +pub fn hasImages(maybe: ?*const State) bool { if (comptime !images_enabled) return false; - const state = pane.terminal orelse return false; + const state = maybe orelse return false; return state.vt.screens.active.kitty_images.images.count() > 0; } @@ -2065,9 +2124,9 @@ test "terminal Filter keys indexed truecolor OSC and background-only cells throu try testing.expect(dyn_bg.eql(.{ .r = 95, .g = 95, .b = 95 })); _ = frame.reset(.retain_capacity); const dynamic = try p.render(frame.allocator()); - const blank = dynamic.at(tx + r.w - config.GUTTER - 1, body_y + 2).style; - try testing.expectEqual(asPardesColor(expected[196]), blank.fg); - try testing.expectEqual(asPardesColor(expected[59]), blank.bg); + const edge = dynamic.at(tx + r.w - config.GUTTER - 1, body_y + 2).style; + try testing.expectEqual(asPardesColor(expected[196]), edge.fg); + try testing.expectEqual(asPardesColor(expected[59]), edge.bg); const explicit_before_reverse = dynamic.at(tx, body_y).style.fg; try testing.expectEqual(asPardesColor(expected[196]), explicit_before_reverse); @@ -2552,7 +2611,7 @@ test "a terminal's image is a placement whatever the frontend draws, and the Pet try pardes.dump.dumpState(p); const restored = try pardes.dump.restore(p, p.dump_out.?, "/tmp/pardes.dump.zon"); defer restored.deinit(); - try std.testing.expectEqual(@as(?bool, true), petscii(restored.panes[0].?)); + try std.testing.expectEqual(@as(?bool, true), petscii(restored.panes[0].?.terminal)); try std.testing.expect(p.executeBuiltinLine(0, "Petscii")); _ = frame.reset(.retain_capacity); s = try p.render(frame.allocator()); @@ -2564,12 +2623,12 @@ test "a new terminal draws its program's images as pixels, and one without image const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .cols = 80, .rows = 24, .shells = 1 }); defer p.deinit(); - try std.testing.expectEqual(false, petscii(p.panes[0].?).?); + try std.testing.expectEqual(false, petscii(p.panes[0].?.terminal).?); // A pane without images says nothing of them. try std.testing.expect(std.mem.indexOf(u8, try tagline.tagPrefix(p, p.panes[0].?), "petscii") == null); const id = p.freeSlot().?; const fresh = try p.newShell(id, ""); - try std.testing.expectEqual(false, petscii(fresh).?); + try std.testing.expectEqual(false, petscii(fresh.terminal).?); } test "a program asking the cell size in pixels (CSI 16 t) is told the shell's" { diff --git a/src/wire.zig b/src/wire.zig index 5900c3f7..cd1554b9 100644 --- a/src/wire.zig +++ b/src/wire.zig @@ -46,7 +46,7 @@ const family = switch (config.platform) { /// What makes two cores step differently, hashed: a replica's hello carries /// its own, and one of another build is refused. The protocol, the release /// and commit, the platform and build options, every dependency's content -/// hash (grammars, ghostty, Unicode), the walker codec's assumptions +/// hash (grammars, the terminal emulator, Unicode), the walker codec's assumptions /// (pointer width, byte order) and the tape's shape (tape.shape: what each /// input and each answer of the host's is laid out as). Not the OS: a Linux /// client of a FreeBSD session is the main case, and what differs there is diff --git a/test/replicas.zig b/test/replicas.zig index 8035e051..5208f6ac 100644 --- a/test/replicas.zig +++ b/test/replicas.zig @@ -35,8 +35,8 @@ const std = @import("std"); const libc = std.c; const pardes = @import("pardes"); const replica = pardes.replica; -const screen_state = pardes.screen_state; -const echo = pardes.echo; +const screen_state = pardes.Term.screen_state; +const Echo = pardes.Term.Echo; const Key = pardes.Key; const gpa = std.heap.c_allocator; @@ -216,7 +216,7 @@ fn writeFile(path: [:0]const u8, lines: usize) !void { const Run = struct { seed: u64, rtt_ms: u64, steps: usize, clients: u16, shared: bool, flood_mb: u64 }; /// The terminal pane's screen as a hash of screen_state's dump of it. -fn screenHash(t: *pardes.panes.terminal.VtSlot) u64 { +fn screenHash(t: *pardes.Term.screen_state.Terminal) u64 { var buf: [8192]u8 = undefined; var h: std.Io.Writer.Hashing(std.hash.Wyhash) = .initHasher(.init(0), &buf); screen_state.dumpScreen(t, &h.writer) catch {}; @@ -901,7 +901,7 @@ const EchoTotals = struct { } }; -fn cellCp(state: *pardes.panes.terminal.State, x: u16, y: u16) u21 { +fn cellCp(state: *pardes.Term.State, x: u16, y: u16) u21 { const ci = state.vt.screens.active.pages.getCell(.{ .active = .{ .x = x, .y = y } }) orelse return 0x10ffff; const cp = ci.cell.codepoint(); return if (cp == 0) ' ' else cp; @@ -984,7 +984,7 @@ fn runEcho(seed: u64, rtt_ms: u64, on: bool, et: *EchoTotals) !void { var frame_arena: std.heap.ArenaAllocator = .init(gpa); defer frame_arena.deinit(); - var made: std.ArrayListUnmanaged(echo.Echo.Predicted) = .empty; + var made: std.ArrayListUnmanaged(Echo.Predicted) = .empty; defer made.deinit(gpa); rp.echo.log = &made; while (queue.pop()) |m| { |
