summaryrefslogtreecommitdiff
path: root/core
diff options
context:
space:
mode:
authorGabriel Schneider <[email protected]>2026-11-22 16:50:34 -0300
committerGabriel Schneider <[email protected]>2026-11-22 16:53:19 -0300
commit9863a63b614d200852853825031189364dcacfdc (patch)
treed235648a2ac14b3e311746ced3433ed6865e2061 /core
parent6544f73a6b50e5ba68564beea7784593bb54348e (diff)
parentbad506bd45846e012246a33b5d3097b3e92f02bc (diff)
downloadpardes-9863a63b614d200852853825031189364dcacfdc.tar.gz
pardes-9863a63b614d200852853825031189364dcacfdc.zip
integration: the old road deleted and the emulator's boundary on the gathered line: pardes-merge56 (`qvwrwxtu`: the installed tree and the source view's changes to their last slice) and pardes-term-join-9 (`twssqzqw`, fourteen changes on pardes-merge55: every client's terminals by the pty's bytes and nothing else: the delta protocol, its flow control and core/term/screen_state.zig deleted (-3,605 +504 lines), the wire at 30, one soak; S1: abi/term.zig's Ops in replicated and local, the terminal's digest covering what a step reads, every call of the core's into a terminal listed with its rule as a test; a client's own join again judged after its goodbye; a pty's size one fact the core hands its host for every fork, adopt and resize; a closed view sizes no terminal); no textual conflict; one semantic one, resolved here: core/jj.zig's Churn test (the layers' last round) called Authority.init and Replica.init with the road's flag the deletion took away: the argument removed; core-test 916/1073 (157 skipped), shell-test 1115/1118; its gate: .scratch/sketch/reorg/merge57, the numbers in PARDES.md (2026-11-22)
Co-Authored-By: Claude Fable 5.2 <[email protected]> Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T
Diffstat (limited to 'core')
-rw-r--r--core/Core.zig33
-rw-r--r--core/Effect.zig11
-rw-r--r--core/Term.zig228
-rw-r--r--core/dump.zig17
-rw-r--r--core/echo.zig57
-rw-r--r--core/edit.zig3
-rw-r--r--core/jj.zig24
-rw-r--r--core/ninep/harness.zig2
-rw-r--r--core/panes.zig49
-rw-r--r--core/replica.zig1419
-rw-r--r--core/root.zig5
-rw-r--r--core/tagline.zig2
-rw-r--r--core/tape.zig70
-rw-r--r--core/term/screen_state.zig1213
-rw-r--r--core/term/term.zig30
-rw-r--r--core/term/terminal.zig230
-rw-r--r--core/views.zig25
17 files changed, 503 insertions, 2915 deletions
diff --git a/core/Core.zig b/core/Core.zig
index ae9ba52f..2b0a898d 100644
--- a/core/Core.zig
+++ b/core/Core.zig
@@ -950,8 +950,9 @@ fn reportFocus(p: *Pardes) void {
// A client's own step records what it told and writes nothing: the
// session's step makes the write, off the tape on both sides
// (tape.hostCall's pty_write), so the switch shows at once and the
- // program hears of it a round trip later.
- if (p.tape.speculating and p.tape.screen_state) return;
+ // program hears of it a round trip later (a write there would stop the
+ // speculation: pty_write is `keeps_stopping`'s).
+ if (p.tape.speculating) return;
if (v.focus_told) |old| if (p.panes[old.id]) |pane| {
if (pane.serial == old.serial and pardes.Term.modes(pane.terminal).focus) p.emitWrite(old.id, "\x1b[O");
};
@@ -1685,7 +1686,6 @@ fn updateInner(p: *Pardes, ev: Event) void {
pane.shell_spoke = true;
ctlfs.events.notePtyOutput(p, o.pane.index(), o.bytes);
pane.feedOutput(p, o.bytes);
- pane.term_images = if (p.tape.screen_state) p.tape.value(.images, pardes.Term.hasImages, .{pane.terminal}) else pardes.Term.hasImages(pane.terminal);
ctlfs.pty.noteMarks(p, o.pane.index(), pane);
exec.flushReplEnter(p, o.pane.index(), true);
},
@@ -2014,6 +2014,16 @@ pub fn sync(p: *Pardes) void {
tagline.revealHeader(p);
}
+/// Pane `id`'s pty as its host is to size it: its grid (or `cells`, a
+/// size 9P's pty/ctl gave), in pixels at the cell of the view that sizes
+/// it: a program sizes its kitty graphics by them.
+pub fn ptySize(p: *const Pardes, id: Pane.Id, cells: ?[2]u16) pardes.PtySize {
+ const pane = p.panes[id.index()] orelse return .{ .cols = 1, .rows = 1 };
+ const c = cells orelse .{ pane.cols, pane.rows };
+ const cell = (if (pane.sized_by) |k| p.views[k] orelse p.views[p.live].? else p.views[p.live].?).cell_pixels;
+ return .{ .cols = @max(c[0], 1), .rows = @max(c[1], 1), .w_px = std.math.cast(u16, @as(u32, c[0]) * cell.w) orelse 0, .h_px = std.math.cast(u16, @as(u32, c[1]) * cell.h) orelse 0 };
+}
+
/// The view typing goes into is the one its terminal is sized for
/// (`sizes`).
fn typedInto(p: *Pardes) void {
@@ -2021,16 +2031,15 @@ fn typedInto(p: *Pardes) void {
}
/// Whether the live view sizes terminal `pane`: a terminal shown at two
-/// sizes takes the size of the view that typed into it last, and any
-/// view's once that one is gone. The others show it at that size, a
-/// shorter one passed down to its cursor (`Pane.pan`, Pane.panFor).
+/// sizes takes the size of the view that typed into it last, and keeps it
+/// once that view is gone until another types into it (views.dropView):
+/// a view nobody types in never takes it. The others show it at that
+/// size, a shorter one passed down to its cursor (`Pane.pan`,
+/// Pane.panFor).
// ponytail: a panned view's pointer reports to a terminal's program and
// its kitty images are placed as the unpanned rows are.
-fn sizes(p: *Pardes, pane: *Pane) bool {
- if (pane.sized_by == p.live) return true;
- if (Views.isOpen(p, pane.sized_by)) return false;
- pane.sized_by = p.live;
- return true;
+fn sizes(p: *const Pardes, pane: *const Pane) bool {
+ return pane.sized_by == p.live;
}
pub fn theme(p: *const Pardes) *const Theme {
@@ -2889,7 +2898,7 @@ test "a spawn is for the pane it was made for, not whatever took the slot since"
var command: [32]u8 = undefined;
var core: *Pardes = undefined;
const vtable: Host.VTable = .{ .spawn = spawn };
- fn spawn(_: ?*anyopaque, id: pardes.Pane.Id, _: []const u8) void {
+ fn spawn(_: ?*anyopaque, id: pardes.Pane.Id, _: []const u8, _: pardes.PtySize) void {
const pane = id.index();
spawns += 1;
const line = core.panes[pane].?.command.?;
diff --git a/core/Effect.zig b/core/Effect.zig
index cabfe8ea..abfe4711 100644
--- a/core/Effect.zig
+++ b/core/Effect.zig
@@ -22,6 +22,10 @@ const Host = pardes.Host;
/// to the shell itself when the shell is in the foreground.
pub const PtySignal = enum(u8) { int, term, hup, quit, kill };
+/// A pty's size as the core gives it to its host: in cells, and in pixels
+/// at the cell of the view that sizes its pane (Core.ptySize).
+pub const PtySize = struct { cols: u16, rows: u16, w_px: u16 = 0, h_px: u16 = 0 };
+
/// IO the core wants done. Payloads are inline (fixed buffers): effects are
/// queued values with no lifetime ties back into the core.
pub const WatchMode = enum { reconcile, baseline_disk };
@@ -118,14 +122,15 @@ fn performInner(p: *Pardes, e: Effect) void {
defer panes.File.syncTwins(p);
switch (e) {
// The host reads the pane (its command, its shell) as it forks,
- // so the slot must still hold the pane the spawn was for.
- .spawn => |s| if (if (p.panes[s.pane.index()]) |pane| pane.serial != s.serial else true) {} else p.tape.host(p, .spawn, .{ s.pane, if (s.cwd.len == 0) (p.spawn_dirs[s.pane.index()] orelse "") else s.cwd.slice() }) orelse {
+ // so the slot must still hold the pane the spawn was for. It forks
+ // at the pane's grid: laid out by the step that asked (`sync`).
+ .spawn => |s| if (if (p.panes[s.pane.index()]) |pane| pane.serial != s.serial else true) {} else p.tape.host(p, .spawn, .{ s.pane, if (s.cwd.len == 0) (p.spawn_dirs[s.pane.index()] orelse "") else s.cwd.slice(), p.ptySize(s.pane, null) }) orelse {
p.fallback.spawned[s.pane.index()] = true;
},
// A pane with no child is silent: nothing invents output on its
// screen, and the bytes are dropped rather than transcribed.
.write => |w| _ = p.tape.host(p, .pty_write, .{ w.pane, w.bytes.slice() }),
- .resize_pty => |r| _ = p.tape.host(p, .pty_resize, .{ r.pane, r.cols, r.rows }),
+ .resize_pty => |r| _ = p.tape.host(p, .pty_resize, .{ r.pane, p.ptySize(r.pane, .{ r.cols, r.rows }) }),
// A signal for a pane that closed, its slot retaken in the same
// step, would reach another pane's child.
.signal_pty => |s| if (if (p.panes[s.pane.index()]) |pane| pane.serial != s.serial else true) {} else p.tape.host(p, .pty_signal, .{ s.pane, s.sig }) orelse {},
diff --git a/core/Term.zig b/core/Term.zig
index 6ef9b0a5..580db4fa 100644
--- a/core/Term.zig
+++ b/core/Term.zig
@@ -50,14 +50,9 @@ pub const Painted = iface.Painted;
pub const PaintedRow = iface.PaintedRow;
pub const ImagesAt = iface.ImagesAt;
pub const EchoCell = iface.EchoCell;
-pub const Peer = iface.Peer;
-pub const Applied = iface.Applied;
-pub const Encoder = iface.Encoder;
-pub const Track = iface.Track;
-pub const Replica = iface.Replica;
fn the() *const iface.Ops {
- return ops orelse unreachable; // no State, Encoder or Replica is made without it
+ return ops orelse unreachable; // no State is made without it
}
/// A terminal pane's terminal: the module's handle, and the walk's hooks
@@ -73,11 +68,7 @@ pub const State = struct {
written: bool = true,
/// The emulator as its program has made it, for the replay digest.
- /// Under screen-state terminals the emulator is the authority's, and a
- /// replica's is what the last delta made it: compared as screens
- /// (test/replicas.zig), not step by step.
pub fn digest(s: *const State, h: *walk.Hasher) void {
- if (tape.screenState()) return;
s.digestScreen(h, true);
}
@@ -140,10 +131,8 @@ pub fn open(gpa: std.mem.Allocator, cols: u16, rows: u16) !*State {
/// session's machine's) as its emulator reads it, made the tape's answer
/// (P30: the device's answer as it was, as a file's bytes are): the session
/// reads it, a temporary file deleted and shared memory unlinked there once,
-/// and every replica is handed the same bytes, or the same failure. Under
-/// screen state a replica feeds no emulator: the read is the session's.
+/// and every replica is handed the same bytes, or the same failure.
fn media(ctx: *const anyopaque, read: *const fn (*const anyopaque) iface.MediumError![]u8, gpa: std.mem.Allocator) iface.MediumError![]u8 {
- if (tape.screenState()) return read(ctx);
return tape.valueIn(.medium, gpa, readMedium, .{ read, ctx });
}
@@ -236,16 +225,11 @@ pub fn follow(s: *State) void {
the().follow(s.impl);
}
-/// Its grid reflowed, now or when `resizeDeferred` makes it.
-pub fn resize(s: *State, cols: u16, rows: u16, later: bool) void {
+/// Its grid reflowed.
+pub fn resize(s: *State, cols: u16, rows: u16) void {
writes +%= 1;
s.written = true;
- the().resize(s.impl, cols, rows, later);
-}
-
-pub fn resizeDeferred(s: *State) bool {
- writes +%= 1;
- return the().resizeDeferred(s.impl);
+ the().resize(s.impl, cols, rows);
}
/// Its cells' size in pixels (kitty graphics, CSI 14/16 t).
@@ -365,12 +349,6 @@ pub fn promptPrefix(tab: u16, s: ?*State, row: i32, raw: []const u8) usize {
};
}
-/// A step read its rows: its replicas must hold them for the step's
-/// replay.
-pub fn markRead(s: *State) void {
- the().markRead(s.impl);
-}
-
/// What a predicted echo reads of a cell of its active area.
pub fn echoCell(s: *const State, x: u16, y: u16) ?EchoCell {
return the().echoCell(s.impl, x, y);
@@ -425,82 +403,134 @@ pub fn hasImages(s: ?*const State) bool {
return o.hasImages(if (s) |state| state.impl else null);
}
-// ---- its replicas ----
-
-pub fn encoder(gpa: std.mem.Allocator) !*Encoder {
- return the().encoder(gpa);
-}
-
-pub fn encoderFree(e: *Encoder) void {
- the().encoderFree(e);
-}
-
-pub fn track(gpa: std.mem.Allocator) !*Track {
- return the().track(gpa);
-}
-
-/// A peer's track of it let go (`s` null: it is gone).
-pub fn untrack(t: *Track, gpa: std.mem.Allocator, s: ?*State) void {
- the().untrack(t, gpa, if (s) |state| state.impl else null);
-}
-
-/// What a peer is owed of it, a delta against what the peer was sent.
-pub fn encode(s: *State, e: *Encoder, t: *Track, peer: *Peer, out: *std.Io.Writer) !bool {
- return the().encode(s.impl, e, t, peer, out);
-}
-
-/// Rows of it a replica holds as holes.
-pub fn encodeRows(s: *State, e: *Encoder, t: *Track, lo: u64, hi: u64, out: *std.Io.Writer) !void {
- return the().encodeRows(s.impl, e, t, lo, hi, out);
-}
-
-/// Whether a step read its rows since `clearRead`.
-pub fn wasRead(s: *const State) bool {
- return the().wasRead(s.impl);
-}
-
-pub fn clearRead(s: *State) void {
- the().clearRead(s.impl);
-}
+// ---- the boundary (S1): every call of the core's into its terminal ----
-/// A replica's side of one terminal: made, freed, where its active area
-/// begins, and the history rows it does not hold.
-pub fn replica(gpa: std.mem.Allocator) !*Replica {
- return the().replica(gpa);
-}
-
-pub fn replicaFree(r: *Replica, gpa: std.mem.Allocator) void {
- the().replicaFree(r, gpa);
-}
-
-pub fn replicaTop(r: *const Replica) u64 {
- return the().replicaTop(r);
-}
-
-pub fn missing(r: *const Replica, lo: u64, hi: u64, out: *std.ArrayList([2]u64), gpa: std.mem.Allocator) !void {
- return the().missing(r, lo, hi, out, gpa);
-}
-
-/// A replica's side: a delta applied, rows applied, the rows its view
-/// shows, rows blank until they come.
-pub fn apply(s: *State, r: *Replica, bytes: []const u8) !Applied {
- return the().apply(s.impl, r, bytes);
-}
-
-pub fn applyRows(s: *State, r: *Replica, bytes: []const u8) !void {
- return the().applyRows(s.impl, r, bytes);
-}
-
-pub fn shown(s: *State, r: *const Replica) [2]u64 {
- return the().shown(s.impl, r);
-}
+/// Every call of the core's (core/, but this file and the module's own
+/// core/term/) into a terminal, by entry, its files and how many in each
+/// (a test's among them), and its rule: the emulator is outside the
+/// rollback copy and its digest is the terminal's (`State.digest`, which
+/// covers what abi/term.zig `replicated` lists a step reads, but the
+/// history's text). A READ from a step is covered by the digest or is
+/// said not to be; a WRITE outside the copy is never made by a unit kept
+/// to replay, or its record puts it back exactly; a LOCAL entry
+/// (abi/term.zig `local`) is never read into a step's state. A new call
+/// fails the test below until it is listed here with its rule (round 6's
+/// and pardes-image-loop's tables, kept as a test).
+pub const calls = [_]struct { []const u8, []const u8, []const u8 }{
+ // ---- writes: outside the copy ----
+ .{ "open", "dump.zig:1 panes.zig:1", "WRITE: a terminal made by a step (a shell's pane) or a load; a copy held across a pane's opening is let go (replica.zig `confirm`: serials)" },
+ .{ "close", "panes.zig:1", "WRITE: let go by a step that closes its pane: a copy held across it is let go (retiring panes); a unit that closes one is never kept over a copy" },
+ .{ "revive", "dump.zig:1", "WRITE: a load's (a join's dump, a Restore): no copy is held" },
+ .{ "reload", "panes.zig:1", "WRITE: a join's step remakes each terminal written since its last reload, on every side (panes.reloadTerminals, the session's choice taped, the snapshot's hash compared)" },
+ .{ "feed", "keys.zig:1 panes.zig:3", "WRITE: the pty's bytes in a unit, every side in the tape's order; a unit that feeds lets a copy held ahead go (`Term.writes`), so none is replayed (keys.zig's: a test's)" },
+ .{ "viewTo", "replica.zig:2", "WRITE: a rollback puts each view back by its row (`putViews`), exact since a reflow keeps a view a row (pardes-term-join-6)" },
+ .{ "scroll", "Core.zig:2 panes.zig:1", "WRITE: a step moves the view; outside the copy, put back by `putViews`" },
+ .{ "follow", "panes.zig:1", "WRITE: a step puts the view on the output; put back by `putViews`" },
+ .{ "resize", "panes.zig:1", "WRITE: a step's reflow; a speculation owes it (`touchTerminal`): its input is taken when confirmed, never as speculated" },
+ .{ "endOutputHere", "ninep/pty.zig:1", "WRITE: a 9P pty/run's step ends a command's output at the cursor: the session's step, replayed as such" },
+ .{ "replies", "Core.zig:1", "WRITE: a step drains the reply buffer (in the digest); only the session writes it to the pty (pty_write is off the tape)" },
+ // ---- reads by a step: in the digest ----
+ .{ "grid", "Core.zig:8 ansi.zig:4 body_layer.zig:5 draw.zig:3 dump.zig:4 echo.zig:8 edit.zig:1 exec.zig:3 keys.zig:3 layout.zig:2 mouse.zig:1 panes.zig:6 replica.zig:4", "READ: the size, the view, the cursor: in the digest (ansi.zig, body_layer.zig, draw.zig, echo.zig: a draw's)" },
+ .{ "modes", "Core.zig:5 draw.zig:1 dump.zig:2 echo.zig:3 exec.zig:3 mouse.zig:4 ninep/pty.zig:3 replica.zig:1", "READ: the program's modes (mouse, focus, bracketed paste, the alternate screen): in the digest (draw.zig, echo.zig: a draw's)" },
+ .{ "prompt", "Core.zig:1 builtins.zig:1 echo.zig:1 exec.zig:3 ninep/pty.zig:1 panes.zig:1", "READ: the OSC 133 cycle: in the digest (`marksOf`); Core.zig's and ninep/pty.zig's also taped (`.prompt`, each side's compared)" },
+ .{ "promptPrefix", "body_layer.zig:1 edit.zig:1 exec.zig:1", "READ: a row's prompt cells (`promptCut`): the active area's in the digest; a history row's text is not (below)" },
+ .{ "hasImages", "replica.zig:3 tagline.zig:1", "READ: whether it holds a kitty image (the tag's prefix): in the digest" },
+ .{ "key", "keys.zig:1", "READ: a key's bytes for the pty from its modes (in the digest): a write the session makes" },
+ .{ "mouse", "mouse.zig:4", "READ: a report's bytes from its modes (in the digest); the last cell told is the pane's (in the copy)" },
+ .{ "wheel", "mouse.zig:1", "READ: a wheel's report from its modes (in the digest)" },
+ .{ "paste", "edit.zig:1", "READ: a paste's bracketing from its modes (in the digest)" },
+ .{ "promptMoves", "keys.zig:1", "READ: the cursor keys a click at its prompt types, from the prompt's cells and the cursor (in the digest)" },
+ .{ "page", "Core.zig:1 ninep/ctl.zig:1", "PURE: a pager's parse of bytes the step holds; no emulator" },
+ .{ "filter", "File.zig:1", "PURE: a pager's colours from the theme; no emulator" },
+ .{ "spanColor", "File.zig:2", "PURE: as `filter`" },
+ // ---- reads by a step: NOT in the digest (the history's text) ----
+ .{ "scrollback", "Core.zig:3 Effect.zig:1 dump.zig:1 ninep/pane.zig:1 ninep/screen.zig:2", "READ, NOT COVERED: the history's text (a 9P read, a Save, an exit dump): each side fed the same bytes; a parting there is found when it reaches the core's state" },
+ .{ "scrollbackLen", "ninep/ctl.zig:1 ninep/pane.zig:1", "READ, NOT COVERED: the history's text's length (its row count is in the digest)" },
+ .{ "commandOutput", "ninep/pty.zig:1", "READ, NOT COVERED: a command's output rows (a 9P pty/run): taped as the session's answer" },
+ .{ "textRows", "edit.zig:2", "READ, NOT COVERED: every row's text, the history's among them (a selection, a Look over a shell)" },
+ .{ "viewport", "body_layer.zig:1 replica.zig:1", "READ: the view's rows' text (body_layer.zig: a draw's; replica.zig: a test's)" },
+ .{ "editRows", "ansi.zig:1", "READ: rows' text for a draw" },
+ // ---- local ----
+ .{ "due", "Core.zig:1", "LOCAL: its next wake (a blink, an animation): the loop's, never a step's state" },
+ .{ "cellPixels", "ansi.zig:1 panes.zig:2", "LOCAL: a frontend's draw sets its view's cell size (ansi.zig); a step sets the view's (in the digest) before each feed (panes.zig), so a reply to CSI 16 t is the step's" },
+ .{ "echoCell", "echo.zig:1", "LOCAL: the predicted echo's judge reads a cell; the echo is no core state" },
+ .{ "paint", "ansi.zig:1", "LOCAL: its cells drawn" },
+ .{ "images", "ansi.zig:1", "LOCAL: its kitty images drawn" },
+ .{ "start", "tape.zig:1", "LOCAL: the module's start, a test's (its own process's)" },
+ .{ "emulatorOf", "Core.zig:2 ninep/pty.zig:3", "the module's state itself: tests only" },
+};
-pub fn blank(s: *State, r: *const Replica, lo: u64, hi: u64) void {
- the().blank(s.impl, r, lo, hi);
+test "every call of the core's into a terminal is listed with its rule (S1): a new read, writer or local use fails until it is" {
+ const gpa = std.testing.allocator;
+ const io = std.testing.io;
+ var dir = try std.Io.Dir.cwd().openDir(io, "core", .{ .iterate = true });
+ defer dir.close(io);
+ var walker = try dir.walk(gpa);
+ defer walker.deinit();
+ var wrong: usize = 0;
+ var counts: std.StringHashMapUnmanaged(usize) = .empty;
+ defer {
+ var it = counts.keyIterator();
+ while (it.next()) |k| gpa.free(k.*);
+ counts.deinit(gpa);
+ }
+ while (try walker.next(io)) |e| {
+ if (e.kind != .file or !std.mem.endsWith(u8, e.basename, ".zig")) continue;
+ if (std.mem.eql(u8, e.path, "Term.zig") or std.mem.startsWith(u8, e.path, "term/")) continue;
+ const src = try e.dir.readFileAlloc(io, e.basename, gpa, .limited(16 << 20));
+ defer gpa.free(src);
+ var lines = std.mem.splitScalar(u8, src, '\n');
+ while (lines.next()) |line| {
+ if (std.mem.startsWith(u8, std.mem.trimStart(u8, line, " \t"), "//")) continue;
+ var at: usize = 0;
+ while (std.mem.indexOfPos(u8, line, at, "Term.")) |i| {
+ at = i + 5;
+ var end = at;
+ while (end < line.len and (std.ascii.isAlphanumeric(line[end]) or line[end] == '_')) end += 1;
+ if (end == at or end >= line.len or line[end] != '(' or !std.ascii.isLower(line[at])) continue;
+ if (i > 0 and (std.ascii.isAlphanumeric(line[i - 1]) or line[i - 1] == '_')) continue;
+ const k = try std.fmt.allocPrint(gpa, "{s} {s}", .{ line[at..end], e.path });
+ const got = try counts.getOrPut(gpa, k);
+ if (got.found_existing) {
+ gpa.free(k);
+ got.value_ptr.* += 1;
+ } else got.value_ptr.* = 1;
+ }
+ }
+ }
+ // Each listed file's count is what the tree has, and nothing else calls.
+ for (calls) |c| {
+ var files = std.mem.tokenizeScalar(u8, c[1], ' ');
+ while (files.next()) |fc| {
+ const colon = std.mem.lastIndexOfScalar(u8, fc, ':').?;
+ const want = try std.fmt.parseInt(usize, fc[colon + 1 ..], 10);
+ var buf: [256]u8 = undefined;
+ const pair = try std.fmt.bufPrint(&buf, "{s} {s}", .{ c[0], fc[0..colon] });
+ const have = counts.get(pair) orelse 0;
+ if (have == want) continue;
+ wrong += 1;
+ std.debug.print("core/{s}: {d} calls of Term.{s}, Term.zig's `calls` says {d}: {s}\n", .{ fc[0..colon], have, c[0], want, c[2] });
+ }
+ }
+ var it = counts.iterator();
+ while (it.next()) |kv| {
+ const space = std.mem.indexOfScalar(u8, kv.key_ptr.*, ' ').?;
+ const name = kv.key_ptr.*[0..space];
+ const file = kv.key_ptr.*[space + 1 ..];
+ if (listedCall(name, file)) continue;
+ wrong += 1;
+ std.debug.print("core/{s}: {d} calls of Term.{s}, not in Term.zig's `calls`: list it with its rule (a step's read the digest covers, a write the copy puts back, a local use)\n", .{ file, kv.value_ptr.*, name });
+ }
+ try std.testing.expectEqual(@as(usize, 0), wrong);
}
-pub fn dumpScreen(s: *State, w: *std.Io.Writer) !void {
- return the().dumpScreen(s.impl, w);
+fn listedCall(name: []const u8, file: []const u8) bool {
+ for (calls) |c| {
+ if (!std.mem.eql(u8, c[0], name)) continue;
+ var files = std.mem.tokenizeScalar(u8, c[1], ' ');
+ while (files.next()) |fc| if (std.mem.eql(u8, fc[0..std.mem.lastIndexOfScalar(u8, fc, ':').?], file)) return true;
+ }
+ return false;
}
// ---- a core without a terminal (core-test's) ----
diff --git a/core/dump.zig b/core/dump.zig
index 18ac28f7..c3742a21 100644
--- a/core/dump.zig
+++ b/core/dump.zig
@@ -255,16 +255,12 @@ pub fn image(p: *Pardes, name: []const u8) ![]u8 {
return pardes.Db.image(gpa, name, buf.written(), w.blobs.items, panes, names.written());
}
-/// A dump for a screen-state replica's join (core/replica.zig): its blobs'
-/// bytes left out and noted in `deferred` (they are the session's, alive
-/// while pinned: memory.zig `pin`), its terminals' emulators left out (the
-/// first delta brings each afresh). What is left is the session's mutable
-/// state, made in its step.
+/// A dump for a replica's join (core/replica.zig): its blobs' bytes left
+/// out and noted in `deferred` (they are the session's, alive while pinned:
+/// memory.zig `pin`), each terminal whole (as the join's step reloaded it
+/// on every side: panes.reloadTerminals), its sequence in flight with it.
+/// What is left is the session's mutable state, made in its step.
pub fn dumpJoin(p: *Pardes, deferred: *std.ArrayListUnmanaged(walk.Deferred)) ![]u8 {
- // Under bytes, each terminal whole (as the join's step reloaded it on
- // every side: panes.reloadTerminals), its sequence in flight with it.
- slim_terminals = p.tape.screen_state;
- defer slim_terminals = false;
// The join's file reads are the session's host's, between its steps:
// with its io, which the core's tape holds (a walk's hook takes no more).
join_files = p.tape.io;
@@ -272,8 +268,7 @@ pub fn dumpJoin(p: *Pardes, deferred: *std.ArrayListUnmanaged(walk.Deferred)) ![
return dumpWith(p, deferred);
}
-/// `dumpJoin`'s under screen state and `dumpExit`'s: a terminal dumps its
-/// size, not its emulator.
+/// `dumpExit`'s: a terminal dumps its size, not its emulator.
pub var slim_terminals = false;
/// `dumpJoin`'s: a plain kind's pane carries its file (SlotRecord.file),
/// read with this io.
diff --git a/core/echo.zig b/core/echo.zig
index 95127f55..93b877b8 100644
--- a/core/echo.zig
+++ b/core/echo.zig
@@ -18,9 +18,10 @@
//! never drawn where the completion was not.
//!
//! Judged as mosh does, once the authority confirmed the key and `grace`
-//! passed: at a delta, a cell the screen shows goes, and one it does not is
-//! a misprediction, and every prediction goes. With no delta (nothing
-//! changed: no echo), a frame judges it `stale` later. Shown at once at a
+//! passed: when the terminal is fed a unit's output (`fed`), a cell the
+//! screen shows goes, and one it does not is a misprediction, and every
+//! prediction goes. With no output (no echo), a frame judges it `stale`
+//! later. Shown at once at a
//! shell's prompt (pardes's OSC 133 marks say its line editor echoes);
//! elsewhere only once an echo was confirmed there since the last key that
//! was not predicted (`cat`, a shell without marks), and underlined; never
@@ -37,19 +38,19 @@ const Key = pardes.Key;
const ms = std.time.ns_per_ms;
/// After the authority confirmed a key, how long its echo has to come back
-/// before a delta that does not show it makes a misprediction (mosh's
+/// before output that does not show it makes a misprediction (mosh's
/// ECHO_TIMEOUT): the shell's echo, then the authority's next frame.
// ponytail: fixed; a loaded host's later echo makes a drawn character go and
// come back. The echo delay measured per terminal would be the bound.
pub const grace_ns = 50 * ms;
-/// With no delta at all, how much longer a frame waits to judge a key.
+/// With no output at all, how much longer a frame waits to judge a key.
pub const stale_ns = 250 * ms;
const never = std.math.maxInt(u64);
/// Cells predicted at once: a line typed a round trip ahead.
const max = 64;
/// A cell predicted: `cp` at column `x` of absolute row `row` (the
-/// authority's numbering, screen_state's), a space for a cell backspace
+/// authority's numbering), a space for a cell backspace
/// cleared; `was` what the screen showed there before; `seq` the key's.
pub const Cell = struct { x: u16, row: u64, cp: u21, was: u21, seq: u32, due: u64 = never };
pub const Cursor = struct { x: u16, row: u64, seq: u32, due: u64 = never };
@@ -73,7 +74,7 @@ pub const Echo = struct {
view: u8 = 0,
pane: u8 = 0,
serial: u32 = 0,
- /// Each terminal's last delta: its active area's first row, absolute.
+ /// Each terminal's active area's first row, absolute, as last fed.
tops: [pardes.MAX_PANES]u64 = @splat(0),
cells: [max]Cell = undefined,
n: u8 = 0,
@@ -347,7 +348,7 @@ pub const Echo = struct {
};
if (e.wait <= seq and e.wait_due == never) {
// The authority stepped a key this did not predict, after every
- // one it did: its deltas from here show that key's doing, which
+ // one it did: its output from here shows that key's doing, which
// no prediction knew of. They go, judged neither way.
e.wait_due = due;
e.drop();
@@ -355,30 +356,24 @@ pub const Echo = struct {
e.catchUp(c);
}
- /// Terminal `id`'s delta was applied, its active area's first row now
- /// `top`.
- pub fn delta(e: *Echo, c: *Pardes, id: u8, top: u64) void {
- if (id == e.pane and top != e.tops[id] and (e.n > 0 or e.cursor != null)) {
+ /// The emulators were fed a unit's output (the session's echo among
+ /// it, perhaps): judged, the active area's first row its grid's.
+ /// ponytail: at the history's cap that row stops moving as the output
+ /// scrolls; a guess there is judged wrong and taken back, never kept.
+ pub fn fed(e: *Echo, c: *Pardes) void {
+ const pane = c.panes[e.pane] orelse return;
+ const g = Term.grid(pane.terminal orelse return);
+ const top = g.total - g.len;
+ if (top != e.tops[e.pane] and (e.n > 0 or e.cursor != null)) {
// Scrolled: the rows predicted are others now.
- e.tops[id] = top;
+ e.tops[e.pane] = top;
return e.lose();
}
- e.tops[id] = top;
- if (id == e.pane) e.judge(c, 0);
+ e.tops[e.pane] = top;
+ e.judge(c, 0);
e.catchUp(c);
}
- /// The pty's bytes road: the emulators were fed a unit's output (the
- /// session's echo among it, perhaps): judged as at a delta, the active
- /// area's first row its grid's. ponytail: at the history's cap that
- /// row stops moving as the output scrolls; a guess there is judged
- /// wrong and taken back, never kept.
- pub fn fed(e: *Echo, c: *Pardes) void {
- const pane = c.panes[e.pane] orelse return;
- const g = Term.grid(pane.terminal orelse return);
- e.delta(c, e.pane, g.total - g.len);
- }
-
/// Once a frame: what is stale judged. Whether to draw.
pub fn frame(e: *Echo, c: *Pardes) bool {
if (e.n > 0 or e.cursor != null) e.judge(c, stale_ns);
@@ -588,8 +583,8 @@ const Rig = struct {
g.now = 1_000 * ms;
// The one road: the shell's bytes in the units, fed to the
// replica's own emulator.
- g.a = try replica.Authority.init(gpa, .{ .cols = 60, .rows = 16, .boot = .tty_shell }, .{ .ctx = g, .vtable = &vtable }, false);
- g.r = try replica.Replica.init(gpa, 1, try g.a.unit(0, 0), false);
+ g.a = try replica.Authority.init(gpa, .{ .cols = 60, .rows = 16, .boot = .tty_shell }, .{ .ctx = g, .vtable = &vtable });
+ g.r = try replica.Replica.init(gpa, 1, try g.a.unit(0, 0));
g.r.core().echo = &g.r.echo;
g.shell = for (g.a.core.panes, 0..) |slot, id| {
if (slot) |pane| if (pane.isTerminal()) break @intCast(id);
@@ -671,8 +666,8 @@ test "keys typed at a shell's prompt are drawn at once, and the authority's echo
try testing.expectEqual(@as(u8, 's'), (try g.drawn(&arena, 3)).cp);
// The authority's core draws no overlay of its own.
try testing.expect(g.a.core.echo == null);
- // The authority takes them, its shell echoes, the delta lands after the
- // grace: confirmed, and the screen's own cells and cursor shown.
+ // The authority takes them, its shell echoes, its output lands after
+ // the grace: confirmed, and the screen's own cells and cursor shown.
try g.take(l);
try g.take(s);
try testing.expectEqualStrings("ls", g.written.items);
@@ -711,7 +706,7 @@ test "a password prompt shows nothing typed, and a full-screen program is not pr
try testing.expectEqual(@as(u32, 1), g.r.echo.stats.predicted);
try testing.expectEqual(@as(u8, ' '), (try g.drawn(&arena, x)).cp);
try g.take(k);
- // No echo, so no delta: a frame lets it go once it is stale.
+ // No echo, so no output: a frame lets it go once it is stale.
g.later(grace_ns + stale_ns);
_ = g.r.echoFrame();
try testing.expectEqual(@as(u8, 0), g.r.echo.n);
diff --git a/core/edit.zig b/core/edit.zig
index 7a57fd09..a475fac2 100644
--- a/core/edit.zig
+++ b/core/edit.zig
@@ -471,9 +471,6 @@ const empty_grid = [1][]const u8{""};
pub fn shellRows(p: *Pardes, pane: *Pane) ![]const []const u8 {
const state = pane.terminal orelse return &empty_grid;
pardes.tape.touchTerminal();
- // A step's read whether the rows are kept or made: a client that came
- // since holds them as holes, and is sent them (Screens.fill).
- if (!drawing) panes.Term.markRead(state);
const c = &p.shell_rows;
if (!c.stale and c.pane == pane) return c.rows;
// Another pane's rows, or a dropped pane's still waiting for the step's
diff --git a/core/jj.zig b/core/jj.zig
index 64a27ead..a0dfec10 100644
--- a/core/jj.zig
+++ b/core/jj.zig
@@ -1842,9 +1842,9 @@ test "a client replays the open of a file at a revision and ends equal" {
var repo = try Repo.init(gpa) orelse return error.SkipZigTest;
defer repo.deinit(gpa);
const R = pardes.replica;
- const a = try R.Authority.init(gpa, .{ .cols = 80, .rows = 24 }, .{}, false);
+ const a = try R.Authority.init(gpa, .{ .cols = 80, .rows = 24 }, .{});
defer a.deinit();
- const r = try R.Replica.init(gpa, 1, try a.unit(0, 0), false);
+ const r = try R.Replica.init(gpa, 1, try a.unit(0, 0));
defer r.deinit();
var line: [4200]u8 = undefined;
r.confirm(try a.local(.{ .command = try std.fmt.bufPrint(&line, "Look {s}@@-:2", .{repo.file}) }));
@@ -1950,9 +1950,9 @@ test "a client replays Changes from what the session's jj answered and ends equa
var repo = try Repo.init(gpa) orelse return error.SkipZigTest;
defer repo.deinit(gpa);
const R = pardes.replica;
- const a = try R.Authority.init(gpa, .{ .cols = 80, .rows = 24 }, .{}, false);
+ const a = try R.Authority.init(gpa, .{ .cols = 80, .rows = 24 }, .{});
defer a.deinit();
- const r = try R.Replica.init(gpa, 1, try a.unit(0, 0), false);
+ const r = try R.Replica.init(gpa, 1, try a.unit(0, 0));
defer r.deinit();
var line: [4200]u8 = undefined;
r.confirm(try a.local(.{ .command = try std.fmt.bufPrint(&line, "Look {s}@@-", .{repo.file}) }));
@@ -1990,10 +1990,10 @@ const WorkerJj = struct {
fn init(repo: *const Repo, at: []const u8) !WorkerJj {
const shell = try testing.allocator.create(Shell);
shell.* = .{ .q = .{ .gpa = testing.allocator, .lsp_allocator = testing.allocator, .io = testing.io } };
- const a = try R.Authority.init(testing.allocator, .{ .cols = 80, .rows = 24 }, .{ .vtable = &vtable, .ctx = shell }, false);
+ const a = try R.Authority.init(testing.allocator, .{ .cols = 80, .rows = 24 }, .{ .vtable = &vtable, .ctx = shell });
errdefer a.deinit();
shell.core = a.core;
- const r = try R.Replica.init(testing.allocator, 1, try a.unit(0, 0), false);
+ const r = try R.Replica.init(testing.allocator, 1, try a.unit(0, 0));
var line: [4200]u8 = undefined;
r.confirm(try a.local(.{ .command = try std.fmt.bufPrint(&line, "Look {s}{s}", .{ repo.file, at }) }));
const id = a.core.view().active;
@@ -2325,9 +2325,9 @@ test "ghost rows ride with the text: a line deleted above moves them up, a line
var repo = try Ghosts.repo() orelse return error.SkipZigTest;
defer repo.deinit(testing.allocator);
const R = pardes.replica;
- const a = try R.Authority.init(testing.allocator, .{ .cols = 80, .rows = 24 }, .{}, false);
+ const a = try R.Authority.init(testing.allocator, .{ .cols = 80, .rows = 24 }, .{});
defer a.deinit();
- const r = try R.Replica.init(testing.allocator, 1, try a.unit(0, 0), false);
+ const r = try R.Replica.init(testing.allocator, 1, try a.unit(0, 0));
defer r.deinit();
var line: [4200]u8 = undefined;
r.confirm(try a.local(.{ .command = try std.fmt.bufPrint(&line, "Look {s}", .{repo.file}) }));
@@ -2507,9 +2507,9 @@ test "the lanes ride with the text: a line typed in a nested block is nobody's,
var repo = try Stack.repo(null) orelse return error.SkipZigTest;
defer repo.deinit(testing.allocator);
const R = pardes.replica;
- const a = try R.Authority.init(testing.allocator, .{ .cols = 80, .rows = 24 }, .{}, false);
+ const a = try R.Authority.init(testing.allocator, .{ .cols = 80, .rows = 24 }, .{});
defer a.deinit();
- const r = try R.Replica.init(testing.allocator, 1, try a.unit(0, 0), false);
+ const r = try R.Replica.init(testing.allocator, 1, try a.unit(0, 0));
defer r.deinit();
const Keys = struct {
fn send(au: *R.Authority, re: *R.Replica, keys: []const u8) !void {
@@ -2654,9 +2654,9 @@ test "Churn's counts ride with the text, and a client replays them equal" {
var repo = try Churned.repo() orelse return error.SkipZigTest;
defer repo.deinit(testing.allocator);
const R = pardes.replica;
- const a = try R.Authority.init(testing.allocator, .{ .cols = 80, .rows = 24 }, .{}, false);
+ const a = try R.Authority.init(testing.allocator, .{ .cols = 80, .rows = 24 }, .{});
defer a.deinit();
- const r = try R.Replica.init(testing.allocator, 1, try a.unit(0, 0), false);
+ const r = try R.Replica.init(testing.allocator, 1, try a.unit(0, 0));
defer r.deinit();
var line: [4200]u8 = undefined;
r.confirm(try a.local(.{ .command = try std.fmt.bufPrint(&line, "Look {s}", .{repo.file}) }));
diff --git a/core/ninep/harness.zig b/core/ninep/harness.zig
index cf75d80d..1449ae54 100644
--- a/core/ninep/harness.zig
+++ b/core/ninep/harness.zig
@@ -153,7 +153,7 @@ pub fn nameAt(list: []const Dirent, want: []const u8) ?Dirent {
/// none.
pub const starting: pardes.Host.VTable = .{ .spawn = startNothing };
-fn startNothing(_: ?*anyopaque, _: pardes.Pane.Id, _: []const u8) void {}
+fn startNothing(_: ?*anyopaque, _: pardes.Pane.Id, _: []const u8, _: pardes.PtySize) void {}
pub const FakeTty = struct {
taken: bool,
diff --git a/core/panes.zig b/core/panes.zig
index 289de70f..d9759d18 100644
--- a/core/panes.zig
+++ b/core/panes.zig
@@ -134,11 +134,6 @@ pub const Pane = struct {
/// cell), and its kitty graphics drawn as glyph art (Petscii).
term_mouse: ?Term.Coordinate = null,
term_petscii: bool = false,
- /// Whether its terminal holds a kitty image, as the session's emulator
- /// said after its program's last output (taped under screen state: a
- /// client's emulator is fed the session's cells, never an image). Its
- /// tag says so (tagline.zig), on every side.
- term_images: bool = false,
gpa: std.mem.Allocator,
serial: u32 = 0,
/// What the control filesystem keeps of this pane -- addr and limit, the
@@ -372,9 +367,10 @@ pub const Pane = struct {
/// The views `pv` holds a share for (a pane retired before a view came
/// has none of it).
pv_known: u8 = 0,
- /// The view that last typed into it: a terminal shown at two sizes takes
- /// that view's (Pardes.sync).
- sized_by: u8 = 0,
+ /// The view that last typed into it, while that view is open: a
+ /// terminal shown at two sizes takes that view's (Pardes.sync); none,
+ /// it keeps the size it has.
+ sized_by: ?u8 = 0,
/// A terminal shown in a view shorter than it (one that does not size
/// it): the rows its top is passed over by, so its cursor stays in
/// sight (Pane.panFor); 0 everywhere else.
@@ -642,7 +638,6 @@ pub const Pane = struct {
}
} else if (pane.addon == null) {
// the vt scrolls in SHELL rows; convert through the edit buffer
- if (tape.viewOnly("scroll a terminal")) return;
const state = pane.terminal orelse return;
const off: i32 = @intCast(Term.grid(state).offset);
Term.scroll(state, pane.gridRow(pane.surfRow(off) + delta) - off);
@@ -743,12 +738,6 @@ pub const Pane = struct {
const has_positions = pane.ovl != null or pane.body.cur_pinned or pane.body.vsel.active or
pane.body.nsel > 0 or pane.body.last_edit != null or pane.look_at != null or
pane.body.ed_undo_len > 0 or pane.body.ed_redo_len > 0 or pane.pointerRowCount() > 0;
- // A replica's emulator is what the authority's deltas make it; what
- // pardes keeps over it moves as the authority's feed told it.
- if (tape.screenReplica()) {
- if (has_positions and pane.followRows(state, bytes)) if (paneIdOf(p, pane)) |id| p.setMessage(.at(id), positions_lost);
- return;
- }
// Sticky bottom, as every other terminal does it: output drags the
// viewport down only when the viewport was already on the last row,
// so a reader scrolled back into the scrollback stays where they
@@ -768,7 +757,6 @@ pub const Pane = struct {
/// pointer's rows) moved as the rows move (`Term.Told`). True when one
/// could not be kept (no memory for its pin).
fn followRows(pane: *Pane, state: *Term.State, bytes: []const u8) bool {
- const on_replica = tape.screenReplica();
const Group = struct { overlay: ?*Text.EditBuffer, cursor: *i32, selection: *Text.CharSel };
var groups: [Text.history_max * 2 + 1]Group = undefined;
groups[0] = .{
@@ -879,13 +867,7 @@ pub const Pane = struct {
track[k] = at.grid;
k += 1;
};
- // A replica's emulator is fed by its authority's deltas: it is told
- // what the authority's feed told.
- const fed: Term.Told = if (on_replica) told: {
- @memset(rows_after, 0);
- @memset(erased_after, false);
- break :told .{ .rows = rows_after, .erased = erased_after, .cleared = false, .alive = false, .failed = false };
- } else Term.feed(state, bytes, track, rows_after, erased_after);
+ const fed = Term.feed(state, bytes, track, rows_after, erased_after);
const after = tape.value(.positions, keepTold, .{Term.Told{ .rows = fed.rows, .erased = fed.erased, .cleared = fed.cleared, .alive = fed.alive, .failed = failed or fed.failed }});
if (after.rows.len != n or after.erased.len != n) return false; // a replica its authority's states apart (diverged)
failed = after.failed;
@@ -967,7 +949,7 @@ pub const Pane = struct {
}
fn feedLost(state: *Term.State, bytes: []const u8) bool {
- if (!tape.screenReplica()) _ = Term.feed(state, bytes, &.{}, &.{}, &.{});
+ _ = Term.feed(state, bytes, &.{}, &.{}, &.{});
return true;
}
@@ -981,14 +963,11 @@ pub const Pane = struct {
/// Its terminal's view snapped back onto live output.
pub fn followOutput(pane: *Pane) void {
- if (tape.viewOnly("follow a terminal")) return;
const state = pane.terminal orelse return;
Term.follow(state);
}
- /// Its terminal's grid reflowed to `cols` by `rows`: on a screen-state
- /// replica by its authority (the next delta says), on such an authority
- /// once the step's unit is out (`resizeDeferred`).
+ /// Its terminal's grid reflowed to `cols` by `rows`.
pub fn resizeGrid(pane: *Pane, cols: u16, rows: u16) void {
// A client's speculation does what its replay does (its
// selections) but the grid: it waits for no round trip. Under bytes
@@ -999,12 +978,8 @@ pub const Pane = struct {
pane.clearPointerSelection(button);
pane.sel[button].state = .none;
};
- if (tape.screenReplica()) return;
if (tape.speculating()) return tape.touchTerminal();
- // A client typing at another size than the last typist's read
- // history rows its replay held as holes, and the rows came
- // renumbered (2026-10-30): the authority's waits for the unit.
- Term.resize(state, cols, rows, tape.screenAuthority());
+ Term.resize(state, cols, rows);
}
/// The rows its terminal's top is passed over by in a view whose rect
@@ -1155,7 +1130,6 @@ pub const positions_lost = "terminal edit position reset: out of memory";
/// session's snapshot's hash is taped, and each replica's own compared
/// with it: a check of the whole emulator at every join.
pub fn reloadTerminals(p: *Pardes) void {
- if (tape.screenState()) return;
for (p.panes) |slot| if (slot) |pane| if (pane.terminal) |state| {
if (!tape.value(.reload, written, .{state})) continue;
// Its cells' size in pixels as a feed sets it (`feedOutput`): a
@@ -1176,13 +1150,6 @@ fn written(s: *Term.State) bool {
return s.written;
}
-/// The sizes steps gave terminals (`Pane.resizeGrid`), made: between
-/// units, on an authority with screen-state replicas (replica.Peers.unit).
-pub fn resizeDeferred(p: *Pardes) void {
- for (p.panes) |slot| if (slot) |pane| if (pane.terminal) |state| if (Term.resizeDeferred(state))
- p.shell_rows.markStale(pane);
-}
-
/// A pane with nothing in it yet, `cols` by `rows`: what a file, a
/// directory, a kind's pane or a terminal is made from.
pub fn createDoc(gpa: std.mem.Allocator, cols: u16, rows: u16) !*Pane {
diff --git a/core/replica.zig b/core/replica.zig
index 993d9e2c..3aac5e82 100644
--- a/core/replica.zig
+++ b/core/replica.zig
@@ -164,9 +164,7 @@ pub const Authority = struct {
/// A session booted with `opts`; `unit` is its first, which a replica
/// is made from.
- /// `screens`: its terminals cross as screen state (`Screens`), not as
- /// their pty's bytes.
- pub fn init(gpa: Allocator, options: pardes.Options, host: pardes.Host, screens: bool) !*Authority {
+ pub fn init(gpa: Allocator, options: pardes.Options, host: pardes.Host) !*Authority {
// A replay gives its core every allocator (tape.zig), and a digest
// tells an allocator from none.
var opts = options;
@@ -177,9 +175,6 @@ pub const Authority = struct {
errdefer gpa.destroy(a);
a.* = .{ .gpa = gpa, .t = tape.memory(gpa), .core = undefined, .host = host };
errdefer tape.release(&a.t);
- a.t.screen_state = screens;
- // One word a digest: every pty read is a unit.
- a.t.whole_digest = screens and std.c.getenv("PARDES_REPLICA_TRACE") == null;
// A digest at a unit's end, as the session's (Peers.unit).
a.t.no_digest = true;
opts.tape = &a.t;
@@ -355,208 +350,6 @@ pub const Authority = struct {
}
};
-// ---- terminals as screen state (core/term/screen_state.zig) ----
-//
-// A message of either side is u8 pane, u32 the pane's serial (a slot's
-// next pane is another), u8 kind, and the kind's bytes:
-// to a replica: kind 1, a delta; kind 2, rows (encodeRows): asked for,
-// or a step read them;
-// to the authority: kind 1, an acknowledgement (u32 seq); kind 2, a
-// request for rows (u64 lo, u64 hi, absolute); kind 3, a
-// delta refused: start this terminal afresh.
-// In the authority's stream to a peer, before it steps any input but a
-// pty's output, and once a frame: its own steps since the last unit, as one
-// (`Authority.pending`), then what the peer is owed of the terminals
-// (`Screens.flush`). After a step, before its unit: the rows it read that
-// the peer holds as holes (`Screens.fill`, then `filled`). A replica takes
-// them in that order between units (`Replica.screen`), so a step it replays
-// reads the terminal its authority's step read.
-
-const kind_delta = 1;
-const kind_rows = 2;
-const kind_ack = 1;
-const kind_reset = 3;
-
-const ScreenMsg = struct { pane: u8, serial: u32, kind: u8, payload: []const u8 };
-
-fn parseScreen(msg: []const u8) ?ScreenMsg {
- if (msg.len < 6) return null;
- return .{ .pane = msg[0], .serial = std.mem.readInt(u32, msg[1..5], .little), .kind = msg[5], .payload = msg[6..] };
-}
-
-fn writeScreenHead(out: *std.ArrayListUnmanaged(u8), gpa: Allocator, pane: u8, serial: u32, kind: u8) !void {
- var head: [6]u8 = undefined;
- head[0] = pane;
- std.mem.writeInt(u32, head[1..5], serial, .little);
- head[5] = kind;
- try out.appendSlice(gpa, &head);
-}
-
-/// The authority's side of its replicas' terminals: a track each terminal
-/// pane, and what each peer was sent of it.
-pub const Screens = struct {
- gpa: Allocator,
- /// Made the first time a terminal is encoded (`encoder`).
- enc: ?*Term.Encoder = null,
- tracks: [pardes.MAX_PANES]?Tracked = @splat(null),
- peers: std.ArrayListUnmanaged(*[pardes.MAX_PANES]PeerOf) = .empty,
- free_peers: std.ArrayListUnmanaged(u16) = .empty,
- out: std.ArrayListUnmanaged(u8) = .empty,
- /// Nanoseconds: what each flush spent encoding, for every peer.
- encode_ns: u64 = 0,
-
- const Tracked = struct { serial: u32, state: *Term.State, track: *Term.Track };
- const PeerOf = struct { serial: u32 = 0, peer: Term.Peer = .{} };
-
- pub fn init(gpa: Allocator) Screens {
- return .{ .gpa = gpa };
- }
-
- /// `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| 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);
- s.gpa.destroy(p);
- }
- s.peers.deinit(s.gpa);
- s.free_peers.deinit(s.gpa);
- s.out.deinit(s.gpa);
- if (s.enc) |e| Term.encoderFree(e);
- }
-
- fn live(_: *const Screens, core: *Pardes, id: usize, tr: *const Tracked) bool {
- const pane = core.panes[id] orelse return false;
- return pane.serial == tr.serial and pane.terminal == tr.state;
- }
-
- /// A new peer, with nothing yet: its first delta of each terminal
- /// starts it afresh.
- pub fn addPeer(s: *Screens) !u16 {
- if (s.free_peers.pop()) |again| return again;
- const p = try s.gpa.create([pardes.MAX_PANES]PeerOf);
- p.* = @splat(.{});
- try s.peers.append(s.gpa, p);
- return @intCast(s.peers.items.len - 1);
- }
-
- /// Peer `peer` gone: what it was sent forgotten, its number free for
- /// the next `addPeer` (a socket's clients come and go).
- pub fn dropPeer(s: *Screens, peer: u16) void {
- for (s.peers.items[peer]) |*pp| pp.peer.deinit(s.gpa);
- s.peers.items[peer].* = @splat(.{});
- s.free_peers.append(s.gpa, peer) catch {};
- }
-
- /// What `peer` is owed of every terminal, each a message onto `out`
- /// (owned): nothing for one it has as it is, or with `bound` in flight.
- pub fn flush(s: *Screens, core: *Pardes, peer: u16, out: *std.ArrayListUnmanaged([]u8)) !void {
- const t0 = nowNs();
- defer s.encode_ns += nowNs() - t0;
- for (core.panes, 0..) |slot, id| {
- const pane = slot orelse continue;
- const state = pane.terminal orelse continue;
- const tr = try s.track(core, id);
- const pp = &s.peers.items[peer][id];
- if (pp.serial != pane.serial) {
- pp.peer.reset();
- pp.serial = pane.serial;
- }
- 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 Term.encode(state, try s.encoder(), tr.track, &pp.peer, &w.writer)) continue;
- try out.append(s.gpa, try s.gpa.dupe(u8, w.written()));
- }
- }
-
- /// Rows a peer holds as holes of every terminal a step read (its rows,
- /// history and all: text mode over a shell), each a rows message onto
- /// `out` (owned): sent after the step and before its unit, so the
- /// replica's replay reads what the authority's step read. A history row
- /// never changes, so each goes once. Then `filled`.
- // ponytail: a step that reads a terminal's rows reads all of them (its
- // motion surface), so the first after a flood sends its whole history.
- pub fn fill(s: *Screens, core: *Pardes, peer: u16, out: *std.ArrayListUnmanaged([]u8)) !void {
- for (core.panes, 0..) |slot, id| {
- const pane = slot orelse continue;
- const state = pane.terminal orelse 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);
- for (pp.peer.holes.items) |hole| {
- var lo = hole[0];
- while (lo < hole[1]) {
- const hi = @min(hole[1], lo + 512);
- s.out.clearRetainingCapacity();
- 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 Term.encodeRows(state, try s.encoder(), tr.track, lo, hi, &w.writer);
- try out.append(s.gpa, try s.gpa.dupe(u8, w.written()));
- lo = hi;
- }
- }
- pp.peer.holes.clearRetainingCapacity();
- }
- }
-
- /// 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| {
- Term.clearRead(state);
- };
- }
-
- fn track(s: *Screens, core: *Pardes, id: usize) !*Tracked {
- const pane = core.panes[id].?;
- if (s.tracks[id]) |*tr| {
- if (s.live(core, id, tr)) return tr;
- // Its pane closed (its emulator, the pin with it, gone).
- Term.untrack(tr.track, s.gpa, null);
- s.tracks[id] = null;
- }
- s.tracks[id] = .{ .serial = pane.serial, .state = pane.terminal.?, .track = try Term.track(s.gpa) };
- return &s.tracks[id].?;
- }
-
- /// The encoder, made the first time a terminal is encoded.
- fn encoder(s: *Screens) !*Term.Encoder {
- if (s.enc) |e| return e;
- s.enc = try Term.encoder(s.gpa);
- return s.enc.?;
- }
-
- /// A peer's message (`Replica.screen`'s, `Replica.screenRequest`'s):
- /// an answer for it (owned), or null.
- pub fn take(s: *Screens, core: *Pardes, peer: u16, msg: []const u8) !?[]u8 {
- const m = parseScreen(msg) orelse return null;
- const pane = core.panes[m.pane] orelse return null;
- if (pane.serial != m.serial) return null;
- const state = pane.terminal orelse return null;
- const pp = &s.peers.items[peer][m.pane];
- if (pp.serial != m.serial) return null;
- switch (m.kind) {
- kind_ack => if (m.payload.len == 4) pp.peer.ack(std.mem.readInt(u32, m.payload[0..4], .little)),
- kind_reset => pp.peer.reset(),
- kind_rows => {
- if (m.payload.len != 16) return null;
- const tr = try s.track(core, m.pane);
- s.out.clearRetainingCapacity();
- 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 Term.encodeRows(state, try s.encoder(), 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 => {},
- }
- return null;
- }
-};
-
// ---- a replica ----
pub const Stats = struct {
@@ -588,8 +381,6 @@ pub const Stats = struct {
rollback_ns: std.ArrayListUnmanaged(u64) = .empty,
copy_bytes: u64 = 0,
copies: u32 = 0,
- /// Nanoseconds: a terminal's delta applied.
- apply_ns: std.ArrayListUnmanaged(u64) = .empty,
/// What stopped them (`Tape.poisoned_by`), a count a name.
stops: [16]Stop = @splat(.{}),
@@ -619,7 +410,6 @@ pub const Stats = struct {
s.spec_ns.deinit(gpa);
s.copy_ns.deinit(gpa);
s.rollback_ns.deinit(gpa);
- s.apply_ns.deinit(gpa);
}
};
@@ -689,17 +479,14 @@ pub const Replica = struct {
rtt_ns: u64 = 0,
gmtoff: i32 = 0,
- /// Its terminals' screen state, as the authority's deltas made it.
- screens: [pardes.MAX_PANES]?ScreenOf = @splat(null),
- /// Each terminal's view (`Term.grid`'s view) as the copy was taken, or
- /// as the last delta since set it: the copy holds no emulator, and a
- /// speculation may move a view, so a rollback puts these back.
+ /// Each terminal's view (`Term.grid`'s view) as the copy was taken: the
+ /// copy holds no emulator, and a speculation may move a view, so a
+ /// rollback puts these back.
views: [pardes.MAX_PANES]?usize = @splat(null),
/// Its panes' serials as the copy was taken, and whether one was being
/// torn down then (`panesMoved`).
serials: [pardes.MAX_PANES]u32 = @splat(0),
retiring: bool = false,
- screen_out: std.ArrayListUnmanaged(u8) = .empty,
/// A record's bytes by hash coming in pieces (`blobPiece`), and how
/// many of them came.
incoming: ?tape.Big = null,
@@ -709,26 +496,16 @@ pub const Replica = struct {
cache: ?Cache = null,
io: std.Io = undefined,
/// Its predicted echo (core/term/echo.zig), drawn over its core's terminals:
- /// fed by its keys, its units and its deltas here, and by `echoFrame`.
+ /// fed by its keys and its units here, and by `echoFrame`.
echo: Echo = .{},
- const ScreenOf = struct {
- serial: u32,
- rep: *Term.Replica,
- /// A delta was refused, and a reset asked for: those in flight
- /// before it are refused unasked.
- refused: bool = false,
- /// The rows asked for and not yet answered.
- asked: ?[2]u64 = null,
- };
-
- /// A replica of the session whose first unit is `first`; `screens`
- /// as the authority's (its terminals fed by `screen`). In process, its
- /// timing samples kept for the harness that reads them.
- pub fn init(gpa: Allocator, id: u16, first: []const u8, screens: bool) !*Replica {
+ /// A replica of the session whose first unit is `first`, its terminals
+ /// fed the pty's bytes the units carry. In process, its timing samples
+ /// kept for the harness that reads them; no predicted echo (a joined
+ /// client's has one: `made`).
+ pub fn init(gpa: Allocator, id: u16, first: []const u8) !*Replica {
const r = try gpa.create(Replica);
r.* = .{ .gpa = gpa, .id = id, .t = tape.memory(gpa), .stats = .{ .samples = true } };
- r.t.screen_state = screens;
r.t.core_gpa = r.epoch.allocator();
r.t.checks = false;
r.confirm(first);
@@ -736,7 +513,6 @@ pub const Replica = struct {
r.deinit();
return error.NoCore;
}
- if (screens) r.core().echo = &r.echo;
return r;
}
@@ -769,8 +545,6 @@ pub const Replica = struct {
r.* = .{ .gpa = gpa, .id = id, .view = view orelse 0, .t = tape.memory(gpa), .guess = true };
r.t.skips_render = true;
r.t.checks = false;
- // Its terminals are the session's deltas (Peers sends them).
- r.t.screen_state = true;
errdefer {
tape.release(&r.t);
r.epoch.deinit();
@@ -834,7 +608,6 @@ pub const Replica = struct {
}
pub fn deinit(r: *Replica) void {
- for (&r.screens) |*slot| if (slot.*) |*sc| Term.replicaFree(sc.rep, pardes.panes.emulator_gpa);
if (r.t.core) |c| {
const was = Stepping.begin(&r.t, &r.epoch);
// The state it ends on is whole as it is: the copy let go, its
@@ -854,7 +627,6 @@ pub const Replica = struct {
for (r.since.items) |u| r.gpa.free(u);
r.since.deinit(r.gpa);
r.out.deinit(r.gpa);
- r.screen_out.deinit(r.gpa);
r.last_digest.deinit(r.gpa);
r.stats.deinit(r.gpa);
tape.release(&r.t);
@@ -923,8 +695,8 @@ pub const Replica = struct {
r.since_check +|= 1;
if (u.origin == r.id) if (r.t.core) |c| r.echo.confirmed(c, u.seq);
// The pty's bytes fed its emulators: its predicted echo judged
- // against them, as a screen-state delta judges it (`screen`).
- defer if (!r.t.screen_state and r.diverged == null and tape.feedsTerminal(u.tape)) if (r.t.core) |c| if (c.echo != null) r.echo.fed(c);
+ // against them.
+ defer if (r.diverged == null and tape.feedsTerminal(u.tape)) if (r.t.core) |c| if (c.echo != null) r.echo.fed(c);
// A copy taken ahead (`ready`), nothing on top: it stays the point a
// rollback goes back to, the unit replayed on it and kept in `since`,
// not let go and taken again (a megabyte walked) for each unit of
@@ -948,11 +720,12 @@ pub const Replica = struct {
// nothing ends on again (`neutral`); none, not known.
r.last_digest.clearRetainingCapacity();
if (lastDigest(u.tape)) |d| r.last_digest.appendSlice(r.gpa, d) catch {};
- if (r.pending.items[0].terminal and (r.applied > 1 or !r.t.screen_state)) {
- // Right, but what it did read a terminal: replayed later (a
- // rollback's `since`) it would read the deltas that came
- // after it. So it is taken now, over the emulator its step
- // read, and the ones on top applied again over it.
+ if (r.pending.items[0].terminal) {
+ // Right, but what it did wrote an emulator (or owes one a
+ // write: a grid's size): replayed later (a rollback's
+ // `since`) it would write it again. So it is taken now, over
+ // the emulator its step read, and the ones on top applied
+ // again over it.
r.toConfirmed();
if (tape.replayUnit(&r.t, u.tape)) |why| return r.fail(why);
r.freePending(r.pending.orderedRemove(0));
@@ -1007,7 +780,7 @@ pub const Replica = struct {
// place, and much of it no digest covers (a colour set, a mode, the
// pages a reload remakes).
if (r.applied > 0 and u.origin != r.id and ends != null and std.mem.eql(u8, ends.?, r.last_digest.items) and
- (r.t.screen_state or !tape.feedsTerminal(u.tape)))
+ !tape.feedsTerminal(u.tape))
{
// Nothing a digest covers moved: what was applied on top is
// what the session will apply on top of it. Replayed when the
@@ -1076,7 +849,7 @@ pub const Replica = struct {
const c = r.core();
for (c.retired_panes.current, c.retired_panes.previous) |x, y| retiring = retiring or x != null or y != null;
for (c.panes, serials) |slot, n| retiring = retiring or (if (slot) |pane| pane.serial else 0) != n;
- if (retiring or (!r.t.screen_state and Term.writes != writes)) {
+ if (retiring or Term.writes != writes) {
r.copy.release();
rollback.Epoch.select(null);
return r.clearSince();
@@ -1189,18 +962,14 @@ pub const Replica = struct {
c.toView(.at(r.view));
// Input into a terminal: what reaches its program (a key in tty
// mode, a paste, a mouse report) is a pty write, the authority's,
- // and stops here (phase 6 predicts its echo). The rest (pardes's
- // own keys over it, the wheel) reads its emulator, here the last
- // delta's and there what the pty has said since: it is applied,
- // and applied again over each delta while it waits (`screen`), so
- // what the authority's unit confirms read the emulator its step
- // read (the deltas come before it).
- const keyboard = if (c.panes[c.view().active]) |pane| pane.terminal != null else false;
+ // and stops here (core/echo.zig predicts its echo). The rest
+ // (pardes's own keys over it, the wheel) reads its emulator, fed
+ // the same bytes in the same order as the session's: it is applied.
c.update(in.event);
c.step();
- // Under bytes: it owes an emulator a write it skipped (a grid's
- // size), replayed when confirmed.
- p.terminal = if (r.t.screen_state) keyboard or r.t.touched else r.t.touched;
+ // It owes an emulator a write it skipped (a grid's size): replayed
+ // when confirmed.
+ p.terminal = r.t.touched;
const clean = tape.endSpeculation(&r.t);
const dt = nowNs() - t0;
// Where a blob was written, should one be: the input that did.
@@ -1315,134 +1084,6 @@ pub const Replica = struct {
return pardes.views.drawOne(c, r.view, present) catch true;
}
- /// One of the authority's terminal messages (`Screens.flush`, or an
- /// answer to `screenRequests`), taken between units in stream order: a
- /// delta written into its pane's emulator, or fetched rows. The
- /// message for the authority (an acknowledgement, or a request to start
- /// afresh), valid until the next call, or null.
- pub fn screen(r: *Replica, msg: []const u8) ?[]const u8 {
- const m = parseScreen(msg) orelse return null;
- const c = r.t.core orelse return null;
- const pane = c.panes[m.pane] orelse return null;
- if (pane.serial != m.serial) return null; // a pane gone: its slot's next is another
- const state = pane.terminal orelse return null;
- const slot = &r.screens[m.pane];
- if (slot.* == null or slot.*.?.serial != m.serial) {
- if (slot.*) |*old| Term.replicaFree(old.rep, pardes.panes.emulator_gpa);
- slot.* = null;
- const rep = Term.replica(pardes.panes.emulator_gpa) catch {
- r.fail("no memory for a terminal's replica");
- return null;
- };
- slot.* = .{ .serial = m.serial, .rep = rep };
- }
- const sc = &slot.*.?;
- // The emulator is the authority's: on the C heap, outside the
- // rollback epoch, so a copy held now never saves or puts back any
- // of what this writes (State.gpa).
- switch (m.kind) {
- kind_delta => {
- // A unit kept to replay (`since`) read the emulator as it is
- // now, and its step may have read it (a key over a shell's
- // text reads its rows, an output its prompt): replayed over
- // this delta it would read another (the soak, a copy taken
- // ahead, three clients: another's key that read the rows,
- // replayed by a rollback after the full-screen program
- // redrew them, came to another state). So the units since go
- // before it: let go with the copy when nothing is on top (the
- // state is the confirmed one), else replayed now.
- if (r.copy.held and r.since.items.len > 0) {
- const was = Stepping.begin(&r.t, &r.epoch);
- defer was.end();
- if (r.applied == 0) {
- r.copy.release();
- rollback.Epoch.select(null);
- r.clearSince();
- } else {
- r.toConfirmed();
- r.dirty = true;
- }
- }
- const t0 = nowNs();
- 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;
- return r.screenMessage(m.pane, m.serial, kind_reset, &.{});
- };
- if (r.stats.samples) r.stats.apply_ns.append(r.gpa, nowNs() - t0) catch {};
- sc.refused = false;
- r.echo.delta(c, m.pane, Term.replicaTop(sc.rep));
- // Its rows as the core keeps them read are another grid's.
- c.shell_rows.markStale(pane);
- // Its view is the authority's now: a rollback puts it back
- // here, and what was applied over a terminal goes on top.
- if (r.copy.held) r.views[m.pane] = pardes.Term.grid(state).view;
- r.overTerminals();
- var seq: [4]u8 = undefined;
- std.mem.writeInt(u32, &seq, applied.seq, .little);
- return r.screenMessage(m.pane, m.serial, kind_ack, &seq);
- },
- kind_rows => {
- sc.asked = null;
- 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;
- },
- else => return null,
- }
- }
-
- /// A terminal was written (a delta, rows): what is applied over the
- /// emulator (`Pending.terminal`) read the one before it, and the
- /// authority's step reads this one (it comes before that step's unit).
- /// Back to the confirmed position, to be applied again over it.
- fn overTerminals(r: *Replica) void {
- const any = for (r.pending.items[0..r.applied]) |p| {
- if (p.terminal) break true;
- } else false;
- if (!any) return;
- const was = Stepping.begin(&r.t, &r.epoch);
- defer was.end();
- r.toConfirmed();
- r.dirty = true;
- }
-
- /// A request for the rows a terminal shows here and does not hold (its
- /// holes in view, after a scroll back), one a terminal at a time; null
- /// when none is owed. Until the answer, a hole shows blank.
- pub fn screenRequest(r: *Replica) ?[]const u8 {
- const c = r.t.core orelse return null;
- for (&r.screens, 0..) |*slot, id| {
- const sc: *ScreenOf = if (slot.*) |*x| x else continue;
- if (sc.asked != null) continue;
- const pane = c.panes[id] orelse continue;
- if (pane.serial != sc.serial) continue;
- const state = pane.terminal orelse continue;
- const shown = Term.shown(state, sc.rep);
- var holes: std.ArrayList([2]u64) = .empty;
- defer holes.deinit(r.gpa);
- Term.missing(sc.rep, 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] };
- 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);
- std.mem.writeInt(u64, range[8..16], want[1], .little);
- return r.screenMessage(@intCast(id), sc.serial, kind_rows, &range);
- }
- return null;
- }
-
- fn screenMessage(r: *Replica, pane: u8, serial: u32, kind: u8, payload: []const u8) ?[]const u8 {
- r.screen_out.clearRetainingCapacity();
- writeScreenHead(&r.screen_out, r.gpa, pane, serial, kind) catch return null;
- r.screen_out.appendSlice(r.gpa, payload) catch return null;
- return r.screen_out.items;
- }
-
/// A piece of a record's bytes by hash (Peer.blob): whole and checked
/// against its hash, kept for the unit that names it (tape.keepFile),
/// and a file's, a far client's, on disk (`cache`) for its next join.
@@ -1720,8 +1361,6 @@ pub const Peer = struct {
again: bool = false,
/// ...or that its window was closed (Peers.closed).
close: bool = false,
- /// Its number in the session's `Screens`.
- sid: u16 = 0,
/// Inputs read (each one's seq, as the client numbered them).
seq: u32 = 0,
/// The `stamp` frame its next input came with (its reader's).
@@ -1740,6 +1379,9 @@ pub const Peer = struct {
/// Cut off (`send`): the words why are the last it is sent, and its
/// view is kept for it (views.away), as for a bye's `again`.
cut: bool = false,
+ /// Its client's join again for its view, come before this link's end
+ /// was heard: judged once it is let go (`Peers.join`, `letGo`).
+ rejoin: ?Peers.Joining = null,
/// Its writer has ended (what it was sent, written).
done: std.atomic.Value(bool) = .init(false),
/// Its join, which its writer writes before what it is sent: the
@@ -2010,13 +1652,6 @@ pub const Peer = struct {
peer.send(&.{pong});
return true;
},
- // Its word about a terminal (an ack, rows asked, a reset), to
- // the session's Screens at the next boundary.
- .screen_ack => {
- const msg = peer.peers.gpa.dupe(u8, payload) catch return false;
- peer.peers.post(.{ .screen = .{ .peer = peer, .msg = msg } });
- return true;
- },
.check => {
peer.peers.post(.{ .check = peer });
return true;
@@ -2090,6 +1725,13 @@ pub fn dying() void {
};
}
+/// Whether the other end of socket `fd` has hung up (shut, or closed).
+fn hungUp(fd: c_int) bool {
+ const rdhup = if (@hasDecl(libc.POLL, "RDHUP")) libc.POLL.RDHUP else 0;
+ var p = [1]libc.pollfd{.{ .fd = fd, .events = libc.POLL.IN | rdhup, .revents = 0 }};
+ return libc.poll(&p, 1, 0) == 1 and p[0].revents & (libc.POLL.HUP | rdhup) != 0;
+}
+
/// The process at the other end of unix socket `fd` (Linux's SO_PEERCRED),
/// or 0: a client's through ssh is ssh's.
fn peerPid(fd: c_int) libc.pid_t {
@@ -2152,25 +1794,13 @@ pub const Peers = struct {
boundary_ns: std.ArrayListUnmanaged(u64) = .empty,
cut: u32 = 0,
head: [unit_head]u8 = undefined,
- /// Its clients' terminals as screen state (core/term/screen_state.zig), while
- /// it records: what each was sent.
- screens: Screens = undefined,
- msgs: std.ArrayListUnmanaged([]u8) = .empty,
/// False: its clients' links are in this process's memory, a thread
/// for none of them (the soak's, test/replicas.zig): what a client's
/// writer would write (its join, then `out`) and its reader read
/// (`Peer.take`, then `.gone` posted) are its driver's to do.
threads: bool = true,
- /// After each flush of a client's terminals, told: the soak's record
- /// of each terminal as each version left it (test/replicas.zig).
- flushed: ?struct { ctx: *anyopaque, f: *const fn (*anyopaque, *Pardes, *Screens) void } = null,
- /// Its clients' terminals cross as the pty's bytes in its units, each
- /// client's emulator its own (P29, P32), not as screen state: every
- /// session's (runtime/session.zig) but under PARDES_TERM_SCREEN, the
- /// soak's `--bytes`; its welcome says so to each client.
- bytes: bool = false,
- pub const Note = union(enum) { join: Joining, input: Msg, screen: Msg, gone: *Peer, check: *Peer, joined: *Peer };
+ pub const Note = union(enum) { join: Joining, input: Msg, gone: *Peer, check: *Peer, joined: *Peer };
/// A connection to join, and the view it joins again for, if it does.
pub const Joining = daemon.Joining;
pub const Msg = struct { peer: *Peer, msg: []u8 };
@@ -2191,13 +1821,13 @@ pub const Peers = struct {
ps.lock.unlock(ps.io);
switch (note) {
.join => |j| _ = libc.close(j.fd),
- .input, .screen => |in| ps.gpa.free(in.msg),
+ .input => |in| ps.gpa.free(in.msg),
.gone, .check, .joined => {},
}
return;
};
ps.mail.store(true, .release);
- if (note != .screen) ps.urgent.store(true, .release);
+ ps.urgent.store(true, .release);
ps.lock.unlock(ps.io);
if (ps.wake) |w| w(ps.wake_ctx);
}
@@ -2227,8 +1857,6 @@ pub const Peers = struct {
const head = wire.header(@backingInt(wire.ServerTag.unit), unit_head + bytes.len);
for (ps.list) |slot| if (slot) |peer| peer.send(&.{ &head, &ps.head, bytes });
ps.t.buf.clearRetainingCapacity();
- // The sizes its steps gave terminals, now: the next flush says so.
- if (ps.t.core) |core| pardes.panes.resizeDeferred(core);
}
/// After each of the session's pumps: its unit sent, the clients that
@@ -2239,12 +1867,8 @@ pub const Peers = struct {
const t0 = nowNs();
defer if (ps.recording and ps.samples) ps.boundary_ns.append(ps.gpa, nowNs() - t0) catch {};
if (ps.recording) {
- // The rows the pump's steps read, then its unit, then what the
- // terminals came to (the next steps read that).
- ps.screensOut(core, .fill);
ps.seq += 1;
ps.unit(0, ps.seq);
- ps.screensOut(core, .flush);
}
if (!ps.mail.load(.acquire)) return;
ps.lock.lockUncancelable(ps.io);
@@ -2257,20 +1881,6 @@ pub const Peers = struct {
ps.input(core, in.peer, in.msg);
ps.gpa.free(in.msg);
},
- .screen => |in| {
- defer ps.gpa.free(in.msg);
- // An acknowledgement (or a reset): room again in its flight
- // for what its terminals came to since. Its flush at this
- // boundary came before it, and at the bound sent nothing:
- // with no step after it, that client kept an old screen.
- const reply = (ps.screens.take(core, in.peer.sid, in.msg) catch null) orelse {
- ps.screensTo(core, in.peer, .flush);
- continue;
- };
- defer ps.gpa.free(reply);
- const head = wire.header(@backingInt(wire.ServerTag.screen), reply.len);
- in.peer.send(&.{ &head, reply });
- },
.gone => |peer| ps.leave(core, peer),
.joined => |peer| released(peer),
.check => |peer| {
@@ -2285,20 +1895,12 @@ pub const Peers = struct {
const in = parseInput(msg) orelse return;
const t0 = nowNs();
defer if (ps.samples) ps.input_ns.append(ps.gpa, nowNs() - t0) catch {};
- // The terminals as this step reads them, then the step, the rows
- // it read, its unit (part B terminal notes' order).
- ps.screensOut(core, .flush);
core.toView(peer.view);
ps.t.stamp = stampOf(in);
core.update(in.event);
core.step();
ps.t.stamp = null;
- ps.screensOut(core, .fill);
ps.unit(peer.id, in.seq);
- // What the step made of a kind's pane (the tick after a key or a
- // click into it: another layout) goes now, not at the next pump's:
- // one may not come before the client looks.
- ps.screensOut(core, .flush);
}
/// What its steps recorded passed a unit's bound (`tape.unit_max`): a
@@ -2309,37 +1911,20 @@ pub const Peers = struct {
ps.unit(0, ps.seq);
}
- const ScreensOut = enum { flush, fill };
-
- /// What each client is owed of the terminals (`Screens.flush`), or the
- /// rows a step read that it lacks (`Screens.fill`, then `filled`), each
- /// a screen message queued for it.
- fn screensOut(ps: *Peers, core: *Pardes, comptime what: ScreensOut) void {
- for (ps.list) |slot| if (slot) |peer| ps.screensTo(core, peer, what);
- if (what == .fill) ps.screens.filled(core);
- }
-
- fn screensTo(ps: *Peers, core: *Pardes, peer: *Peer, comptime what: ScreensOut) void {
- if (ps.bytes) return;
- defer {
- for (ps.msgs.items) |m| ps.gpa.free(m);
- ps.msgs.clearRetainingCapacity();
- }
- (switch (what) {
- .flush => ps.screens.flush(core, peer.sid, &ps.msgs),
- .fill => ps.screens.fill(core, peer.sid, &ps.msgs),
- }) catch return;
- if (what == .flush) if (ps.flushed) |h| h.f(h.ctx, core, &ps.screens);
- for (ps.msgs.items) |m| {
- const head = wire.header(@backingInt(wire.ServerTag.screen), m.len);
- peer.send(&.{ &head, m });
- }
- }
-
/// A client on `joining.fd` joined: a dump of the session now, its
/// threads started. At a step boundary (`boundary`), or a session's
/// first client before its first effects (runtime/session.zig).
pub fn join(ps: *Peers, core: *Pardes, joining: Joining) void {
+ // A join for a view whose client's link has hung up is that client
+ // joining again (runtime/client.zig `run`: its bye, its link shut,
+ // then its dial): its goodbye comes on that link and this join
+ // through the daemon, in no order between them. Held until that
+ // link is let go, its view kept for it by then; a view whose link
+ // is up is another client's.
+ if (joining.view) |v| for (ps.list) |slot| if (slot) |p| if (p.view.index() == v and p.rejoin == null and hungUp(p.fd)) {
+ p.rejoin = joining;
+ return;
+ };
const fd = joining.fd;
const t0 = nowNs();
defer {
@@ -2355,12 +1940,9 @@ pub const Peers = struct {
if (tape.on != null) return daemon.refuseReplica(fd, "that session records a tape of its own (PARDES_RECORD)");
ps.t = tape.memory(ps.gpa);
ps.t.unit_digests = true;
- // Terminals cross as screen state: a unit carries no pty bytes,
- // and its digest is a word (PARDES_REPLICA_TRACE: one a field).
- ps.t.screen_state = !ps.bytes;
+ // A unit's digest is a word (PARDES_REPLICA_TRACE: one a field).
ps.t.whole_digest = std.c.getenv("PARDES_REPLICA_TRACE") == null;
ps.t.cut = .{ .ctx = ps, .f = cutUnit };
- ps.screens = .init(ps.gpa);
tape.on = &ps.t;
core.tape = &ps.t;
ps.recording = true;
@@ -2425,7 +2007,7 @@ pub const Peers = struct {
// (a pair's client, its own boot: `writeJoin`).
const digest = tape.digestOf(core);
peer.digest = digest;
- peer.welcome_len = (wire.encodeServer(&peer.welcome, .{ .welcome = .{ .pid = @intCast(libc.getpid()), .session = ps.name[0..@min(ps.name.len, wire.max_name)], .client = peer.id, .view = peer.view, .dump_len = whole, .gmtoff = gmtoff(), .digest = digest, .semantics = wire.semantics, .blobs = @intCast(blobs.items.len), .bytes = ps.bytes } }) catch unreachable).len;
+ peer.welcome_len = (wire.encodeServer(&peer.welcome, .{ .welcome = .{ .pid = @intCast(libc.getpid()), .session = ps.name[0..@min(ps.name.len, wire.max_name)], .client = peer.id, .view = peer.view, .dump_len = whole, .gmtoff = gmtoff(), .digest = digest, .semantics = wire.semantics, .blobs = @intCast(blobs.items.len) } }) catch unreachable).len;
if (ps.threads) peer.writer = std.Thread.spawn(.{}, Peer.writeLoop, .{peer}) catch null;
if (ps.threads) peer.reader = std.Thread.spawn(.{}, Peer.readLoop, .{peer}) catch null;
if (ps.threads and (peer.writer == null or peer.reader == null)) {
@@ -2438,11 +2020,6 @@ pub const Peers = struct {
slot.* = peer;
peer.pid = peerPid(fd);
ps.tellClients();
- // Its terminals afresh, after its dump and before any unit.
- if (ps.screens.addPeer()) |sid| {
- peer.sid = sid;
- ps.screensTo(core, peer, .flush);
- } else |_| _ = libc.shutdown(fd, 2);
log.info("client {d} joined '{s}' as view {d}: a {d} KB dump ({d} KB of state) in {d} us", .{ peer.id, ps.name, k, whole >> 10, bytes.len >> 10, (nowNs() - t0) / 1000 });
if (std.c.getenv("PARDES_REPLICA_TRACE") != null) std.debug.print("session: client {d} joined after unit {d}\n", .{ peer.id, ps.seq });
}
@@ -2492,7 +2069,6 @@ pub const Peers = struct {
};
log.info("client {d} left '{s}'", .{ peer.id, ps.name });
ps.tellClients();
- ps.screens.dropPeer(peer.sid);
core.undrawn &= ~(@as(u8, 1) << @intCast(peer.view.index()));
// Cut off, it joins again after the words why (`send`); its reader
// has ended and no other thread sets `cut` now.
@@ -2535,7 +2111,7 @@ pub const Peers = struct {
var i: usize = 0;
while (i < ps.inbox.items.len) {
const mine = switch (ps.inbox.items[i]) {
- .input, .screen => |in| in.peer == peer,
+ .input => |in| in.peer == peer,
.gone, .check, .joined => |p| p == peer,
.join => false,
};
@@ -2544,12 +2120,13 @@ pub const Peers = struct {
continue;
}
switch (ps.inbox.items[i]) {
- .input, .screen => |in| ps.gpa.free(in.msg),
+ .input => |in| ps.gpa.free(in.msg),
else => {},
}
_ = ps.inbox.orderedRemove(i);
}
ps.lock.unlock(io);
+ if (peer.rejoin) |j| ps.post(.{ .join = j });
ps.gpa.destroy(peer);
}
@@ -2601,6 +2178,10 @@ pub const Peers = struct {
_ = ps.inbox.orderedRemove(i);
}
ps.lock.unlock(ps.io);
+ for (ps.list) |slot| if (slot) |p| if (p.rejoin) |j| {
+ again.append(ps.gpa, j) catch continue;
+ p.rejoin = null;
+ };
ps.drop(core, false);
ps.restored = true;
for (again.items) |j| ps.post(.{ .join = j });
@@ -2662,8 +2243,6 @@ pub const Peers = struct {
fn stop(ps: *Peers, core: *Pardes) void {
if (!ps.recording) return;
- pardes.panes.resizeDeferred(core);
- ps.screens.deinit(core);
tape.on = null;
core.tape = core.opts.tape orelse &tape.none;
tape.release(&ps.t);
@@ -2682,7 +2261,6 @@ pub const Peers = struct {
slot.* = null;
core.undrawn &= ~(@as(u8, 1) << @intCast(peer.view.index()));
ps.closeViewOf(core, peer, again);
- ps.screens.dropPeer(peer.sid);
ps.letGo(peer);
};
ps.tellClients();
@@ -2690,7 +2268,7 @@ pub const Peers = struct {
ps.lock.lockUncancelable(ps.io);
for (ps.inbox.items) |note| switch (note) {
.join => |j| _ = libc.close(j.fd),
- .input, .screen => |in| ps.gpa.free(in.msg),
+ .input => |in| ps.gpa.free(in.msg),
.gone, .check, .joined => {},
};
ps.inbox.clearRetainingCapacity();
@@ -2704,7 +2282,6 @@ pub const Peers = struct {
ps.taken.deinit(ps.gpa);
ps.input_ns.deinit(ps.gpa);
ps.boundary_ns.deinit(ps.gpa);
- ps.msgs.deinit(ps.gpa);
ps.each_join.deinit(ps.gpa);
}
@@ -2759,9 +2336,6 @@ pub const Joined = struct {
/// Its replica is its own boot, the welcome not read yet (`ownBoot`,
/// `confirmBoot`).
booted: bool = false,
- /// Its session's terminals come as the pty's bytes, not screen state
- /// (the welcome's word, Peers.bytes).
- bytes: bool = false,
};
/// A blob a far join was sent: where it is in the dump, and its hash.
@@ -2842,7 +2416,6 @@ fn joinOn(gpa: Allocator, fd: c_int, session: ?[]const u8, why: []u8, have: ?*Ha
r.j.gmtoff = w.gmtoff;
r.j.digest = w.digest;
r.j.semantics = w.semantics;
- r.j.bytes = w.bytes;
if (r.boot == w.digest) {
r.done = true;
return false;
@@ -3110,18 +2683,6 @@ pub fn sendInput(fd: c_int, msg: []const u8) bool {
return writeAll(fd, msg[head_len..]);
}
-/// A message `Replica.screen` or `screenRequest` made, to the session.
-pub fn sendScreen(fd: c_int, msg: []const u8) bool {
- var buf: [64]u8 = undefined;
- if (wire.header_len + msg.len > buf.len) {
- const head = wire.header(@backingInt(wire.ClientTag.screen_ack), msg.len);
- return writeAll(fd, &head) and writeAll(fd, msg);
- }
- buf[0..wire.header_len].* = wire.header(@backingInt(wire.ClientTag.screen_ack), msg.len);
- @memcpy(buf[wire.header_len..][0..msg.len], msg);
- return writeAll(fd, buf[0 .. wire.header_len + msg.len]);
-}
-
/// Asks the session's digest, answered in stream order.
pub fn askCheck(fd: c_int) bool {
var out: [16]u8 = undefined;
@@ -3136,9 +2697,9 @@ pub fn bye(fd: c_int, how: @FieldType(wire.ClientMsg, "bye")) void {
}
/// What the session streams a client after its dump, as its frontend's loop
-/// takes it: a unit's and a terminal message's bytes and a refusal's words
-/// on the C heap, the loop's to free.
-pub const Said = union(enum) { unit: []u8, screen: []u8, checked: u64, refused: []u8, blob: []u8, ended: u8, left };
+/// takes it: a unit's bytes and a refusal's words on the C heap, the loop's
+/// to free.
+pub const Said = union(enum) { unit: []u8, checked: u64, refused: []u8, blob: []u8, ended: u8, left };
/// The session's stream off `fd`, each message handed to `post` until the
/// link ends (a refusal ends it too); `post` says whether it took it (one
@@ -3149,7 +2710,6 @@ pub fn readLink(gpa: Allocator, fd: c_int, rest: *Framer, ctx: anytype, comptime
const t = std.enums.fromInt(wire.ServerTag, tag) orelse return false;
const msg: Said = switch (t) {
.unit => .{ .unit = std.heap.c_allocator.dupe(u8, payload) catch return false },
- .screen => .{ .screen = std.heap.c_allocator.dupe(u8, payload) catch return false },
.blob => .{ .blob = std.heap.c_allocator.dupe(u8, payload) catch return false },
.check => .{ .checked = (wire.decodeServer(tag, payload) catch return false).check },
.refused => .{ .refused = std.heap.c_allocator.dupe(u8, (wire.decodeServer(tag, payload) catch return false).refused) catch return false },
@@ -3158,11 +2718,11 @@ pub fn readLink(gpa: Allocator, fd: c_int, rest: *Framer, ctx: anytype, comptime
.pong, .welcome, .dump, .blobs, .zstd => return true,
};
if (!post(x, msg)) switch (msg) {
- .unit, .screen, .refused, .blob => |b| std.heap.c_allocator.free(b),
+ .unit, .refused, .blob => |b| std.heap.c_allocator.free(b),
.checked, .ended, .left => {},
};
// A last word ends the stream.
- return msg == .unit or msg == .screen or msg == .checked or msg == .blob;
+ return msg == .unit or msg == .checked or msg == .blob;
}
};
rest.run(gpa, fd, ctx, Take.take);
@@ -3259,16 +2819,14 @@ pub fn join(gpa: Allocator, j: *Joined, path: []const u8, session: []const u8, o
return fromDump(gpa, j, o, have, why, t0);
}
-/// The replica of the dump `j` brought, on the road its welcome says, its
-/// load checked by the session's digest, and what it takes of `j`; null,
-/// and why in `why`, when it does not load as the session.
+/// The replica of the dump `j` brought, its load checked by the session's
+/// digest (its emulators' among it), and what it takes of `j`; null, and
+/// why in `why`, when it does not load as the session.
fn fromDump(gpa: Allocator, j: *Joined, o: pardes.Options, have: ?*Have, why: []u8, t0: u64) ?*Replica {
const r = Replica.initDump(gpa, j.client, j.view, j.dump, o) catch |err| {
_ = std.fmt.bufPrint(why, "the session's dump would not load: {t}\x00", .{err}) catch {};
return null;
};
- // Before the check: on the bytes road the digest covers its emulators.
- road(r, j.bytes);
if (!r.loaded(j.digest)) {
r.deinit();
_ = std.fmt.bufPrint(why, "the session's dump loaded as another session (a build's dump is not complete)\x00", .{}) catch {};
@@ -3278,14 +2836,6 @@ fn fromDump(gpa: Allocator, j: *Joined, o: pardes.Options, have: ?*Have, why: []
return r;
}
-/// Its terminals its own emulators, fed the pty's bytes its units carry
-/// (`bytes`, its session's Peers.bytes), or the session's screen state;
-/// its echo predicted on either (core/echo.zig).
-fn road(r: *Replica, bytes: bool) void {
- r.t.screen_state = !bytes;
- r.core().echo = &r.echo;
-}
-
/// What a replica joined by `j` takes of it, and of the environment.
fn takeJoined(r: *Replica, j: *Joined, have: ?*Have, t0: u64) void {
// PARDES_NO_ECHO: no predicted echo (the gates' baseline).
@@ -3323,10 +2873,7 @@ fn ownBoot(gpa: Allocator, j: *Joined, fd: c_int, o: pardes.Options, why: *[600]
_ = std.fmt.bufPrint(why, "the session hung up\x00", .{}) catch {};
return null;
}
- // Its session is this process's child, on the road this environment
- // says (runtime/session.zig): the welcome says it again.
- j.* = .{ .fd = fd, .pid = 0, .client = r.id, .view = r.view, .gmtoff = gmtoff(), .dump = &.{}, .digest = digest, .semantics = wire.semantics, .booted = true, .bytes = std.c.getenv("PARDES_TERM_SCREEN") == null };
- road(r, j.bytes);
+ j.* = .{ .fd = fd, .pid = 0, .client = r.id, .view = r.view, .gmtoff = gmtoff(), .dump = &.{}, .digest = digest, .semantics = wire.semantics, .booted = true };
takeJoined(r, j, null, t0);
return r;
}
@@ -3345,7 +2892,6 @@ pub fn confirmBoot(gpa: Allocator, j: *Joined, r: *Replica, o: pardes.Options, w
if (j.dump.len == 0) {
r.id = j.client;
r.view = j.view;
- road(r, j.bytes);
return r;
}
defer {
@@ -3576,11 +3122,6 @@ pub const Link = struct {
// after it in the stream and its digest covers it.
if (!c.asked) c.changed = true;
},
- .screen => |bytes| {
- defer std.heap.c_allocator.free(bytes);
- if (c.r.screen(bytes)) |reply| if (!sendScreen(c.fd, reply)) c.cut();
- c.dirty = true;
- },
.blob => |bytes| {
defer std.heap.c_allocator.free(bytes);
c.r.blobPiece(bytes);
@@ -3604,9 +3145,7 @@ pub const Link = struct {
}
/// Its own view drawn, by the frontend (`drew` is whether anything was
- /// written to it): a rollback it may have shown counted, and the
- /// history rows it shows and does not hold (a scroll back) asked for,
- /// blank until they come.
+ /// written to it): a rollback it may have shown counted.
pub fn drawn(c: *Link, drew: bool) void {
if (c.r.stats.mispredicted > c.mispredicted) {
c.mispredicted = c.r.stats.mispredicted;
@@ -3617,10 +3156,6 @@ pub const Link = struct {
// What moved before this frame is in it: not drawn again at the
// next unit (a stopped input's rollback, under its own frame).
c.r.moved = false;
- while (c.r.screenRequest()) |req| if (!sendScreen(c.fd, req)) {
- c.cut();
- break;
- };
}
/// The session's unit `bytes`, taken now: how far behind it is. Past
@@ -3763,7 +3298,7 @@ const TestHost = struct {
/// A host with ptys whose pump polls for a frame, as a client's does.
const PtyHost = struct {
- fn resized(_: ?*anyopaque, _: pardes.Pane.Id, _: u16, _: u16) void {}
+ fn resized(_: ?*anyopaque, _: pardes.Pane.Id, _: pardes.PtySize) void {}
fn poll(_: ?*anyopaque) void {}
const vtable: pardes.Host.VTable = .{ .watched = TestHost.watched, .pty_resize = resized, .poll_frame = poll };
fn host() pardes.Host {
@@ -3817,29 +3352,6 @@ fn key(r: *Replica, cp: u21, sent: *std.ArrayListUnmanaged([]u8)) !void {
try sent.append(std.testing.allocator, try std.testing.allocator.dupe(u8, msg));
}
-/// What the session sends a peer: its terminals' changes (`.flush`), or,
-/// around a step's unit (Peers.input), the rows the step read that the
-/// peer lacks (`.fill`), after which the caller gives terminals the sizes
-/// the step gave them (`panes.resizeDeferred`), then the unit.
-fn deliver(a: *Authority, screens: *Screens, peer: u16, r: *Replica, comptime what: enum { flush, fill }) !void {
- const gpa = std.testing.allocator;
- var msgs: std.ArrayListUnmanaged([]u8) = .empty;
- defer {
- for (msgs.items) |m| gpa.free(m);
- msgs.deinit(gpa);
- }
- switch (what) {
- .flush => try screens.flush(a.core, peer, &msgs),
- .fill => {
- try screens.fill(a.core, peer, &msgs);
- screens.filled(a.core);
- },
- }
- for (msgs.items) |m| if (r.screen(m)) |reply| {
- _ = try screens.take(a.core, peer, reply);
- };
-}
-
/// The blob cache of a test, in its own directory (never the user's).
fn testCache(tmp: *std.testing.TmpDir, buf: *[4200]u8, cap: u64) !Cache {
var dir_buf: [std.Io.Dir.max_path_bytes]u8 = undefined;
@@ -3935,34 +3447,21 @@ fn inputOf(buf: []u8, client: u16, seq: u32, ev: pardes.Event) ![]const u8 {
}
/// An input of a replica's in the session's order, as `Peers.input` takes
-/// it: the terminals flushed to every peer, the step, the rows it read that
-/// each peer holds as holes (`fill`), then its unit to every replica.
-fn takeAll(a: *Authority, screens: *Screens, rs: []const *Replica, ps: []const u16, msg: []const u8) !void {
+/// it: the step, then its unit to every replica.
+fn takeAll(a: *Authority, rs: []const *Replica, msg: []const u8) !void {
const gpa = std.testing.allocator;
- for (rs, ps) |r, peer| try deliver(a, screens, peer, r, .flush);
const u = try gpa.dupe(u8, try a.take(msg));
defer gpa.free(u);
- var rows: std.ArrayListUnmanaged([]u8) = .empty;
- defer rows.deinit(gpa);
- for (rs, ps) |r, peer| {
- rows.clearRetainingCapacity();
- try screens.fill(a.core, peer, &rows);
- for (rows.items) |m| {
- _ = r.screen(m);
- gpa.free(m);
- }
- }
- screens.filled(a.core);
for (rs) |r| {
r.confirm(u);
r.settle();
}
}
-fn sendAs(r: *Replica, a: *Authority, screens: *Screens, rs: []const *Replica, ps: []const u16, ev: pardes.Event) !void {
+fn sendAs(r: *Replica, a: *Authority, rs: []const *Replica, ev: pardes.Event) !void {
const msg = try std.testing.allocator.dupe(u8, try r.input(ev));
defer std.testing.allocator.free(msg);
- try takeAll(a, screens, rs, ps, msg);
+ try takeAll(a, rs, msg);
}
fn shows(p: *Pardes, text: []const u8) !bool {
@@ -4044,9 +3543,9 @@ test "an Upgrade tells a client handed to the session and not joined yet that it
test "a replica's own keys apply at once, confirm on the fast path, and end at the authority's digest" {
const gpa = std.testing.allocator;
- const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host(), false);
+ const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host());
defer a.deinit();
- const r = try Replica.init(gpa, 1, try a.unit(0, 0), false);
+ const r = try Replica.init(gpa, 1, try a.unit(0, 0));
defer r.deinit();
try std.testing.expectEqual(digestOf(a), r.digest());
var sent: std.ArrayListUnmanaged([]u8) = .empty;
@@ -4071,9 +3570,9 @@ test "a replica's own keys apply at once, confirm on the fast path, and end at t
test "an input's time is its client's: an edit's second confirms on the fast path though the authority takes it in the next" {
const gpa = std.testing.allocator;
- const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host(), false);
+ const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host());
defer a.deinit();
- const r = try Replica.init(gpa, 1, try a.unit(0, 0), false);
+ const r = try Replica.init(gpa, 1, try a.unit(0, 0));
defer r.deinit();
var sent: std.ArrayListUnmanaged([]u8) = .empty;
defer {
@@ -4108,13 +3607,13 @@ test "an input's time is its client's: an edit's second confirms on the fast pat
test "another client's input first: a replica rolls back, replays it and applies its own again" {
const gpa = std.testing.allocator;
- const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host(), false);
+ const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host());
defer a.deinit();
const first = try gpa.dupe(u8, try a.unit(0, 0));
defer gpa.free(first);
- const r1 = try Replica.init(gpa, 1, first, false);
+ const r1 = try Replica.init(gpa, 1, first);
defer r1.deinit();
- const r2 = try Replica.init(gpa, 2, first, false);
+ const r2 = try Replica.init(gpa, 2, first);
defer r2.deinit();
var s1: std.ArrayListUnmanaged([]u8) = .empty;
var s2: std.ArrayListUnmanaged([]u8) = .empty;
@@ -4149,11 +3648,11 @@ test "another client's input first: a replica rolls back, replays it and applies
test "the copy taken for an input of its own stays once the input is confirmed: the next takes none, and a rollback replays the first over it" {
const gpa = std.testing.allocator;
- const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host(), false);
+ const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host());
defer a.deinit();
const first = try gpa.dupe(u8, try a.unit(0, 0));
defer gpa.free(first);
- const r = try Replica.init(gpa, 1, first, false);
+ const r = try Replica.init(gpa, 1, first);
defer r.deinit();
var sent: std.ArrayListUnmanaged([]u8) = .empty;
defer {
@@ -4182,7 +3681,7 @@ test "a client marks its view moved for a unit of the session's whose steps aske
// clock, or a ctl write's close, draws nothing; a client presented it
// again (the corpus's pet: one picture twice).
const gpa = std.testing.allocator;
- const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host(), false);
+ const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host());
defer a.deinit();
// A client as a dial joins it: it draws none of its replay.
const r = try joinedNow(a, 1, 0);
@@ -4207,9 +3706,9 @@ test "the session's pump units that moved nothing, kept under a key applied on t
// of them is the bound's is the arrivals' parity, and a pump's unit
// while idle turns it.
const gpa = std.testing.allocator;
- const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host(), false);
+ const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host());
defer a.deinit();
- const r = try Replica.init(gpa, 1, try a.unit(0, 0), false);
+ const r = try Replica.init(gpa, 1, try a.unit(0, 0));
defer r.deinit();
var sent: std.ArrayListUnmanaged([]u8) = .empty;
defer {
@@ -4255,11 +3754,11 @@ test "a rollback over a Tab it applied measures tabs as its core has them again"
// a Tab undone left it, and the next replayed step measured the files'
// tabs otherwise (the soak, five clients).
const gpa = std.testing.allocator;
- const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host(), false);
+ const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host());
defer a.deinit();
const first = try gpa.dupe(u8, try a.unit(0, 0));
defer gpa.free(first);
- const r = try Replica.init(gpa, 1, first, false);
+ const r = try Replica.init(gpa, 1, first);
defer r.deinit();
const was = r.core().settings.tab;
const msg = try gpa.dupe(u8, try r.input(.{ .command = "Tab 2" }));
@@ -4275,101 +3774,12 @@ test "a rollback over a Tab it applied measures tabs as its core has them again"
try agrees(a, r);
}
-test "a delta applied under a speculation outlives its rollback: the terminal stays the authority's newest" {
- if (pardes.Term.ops == null) return error.SkipZigTest; // a shell
- const gpa = std.testing.allocator;
- const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .boot = .tty }, TestHost.host(), true);
- defer a.deinit();
- var screens: Screens = .init(gpa);
- defer screens.deinit(a.core);
- const peer = try screens.addPeer();
- const r = try Replica.init(gpa, 1, try a.unit(0, 0), true);
- defer r.deinit();
- const shell: u8 = for (a.core.panes, 0..) |slot, id| {
- if (slot) |pane| if (pane.isTerminal()) break @intCast(id);
- } else return error.NoShell;
- // Typing goes to the text pane under the shell (the host's write of
- // `active`, taped).
- a.core.view().active = for (a.core.panes, 0..) |slot, id| {
- if (slot) |pane| if (pane.file != null) break id;
- } else return error.NoTextPane;
- r.confirm(try a.local(.{ .focus = true }));
- try deliver(a, &screens, peer, r, .flush);
- var sent: std.ArrayListUnmanaged([]u8) = .empty;
- defer {
- for (sent.items) |m| gpa.free(m);
- sent.deinit(gpa);
- }
- // Typed into the file, at once: a copy is held.
- try key(r, 'o', &sent);
- try std.testing.expect(r.copy.held);
- var line: [64]u8 = undefined;
- for (0..3) |round| {
- // The shell prints: its unit rolls the replica back and applies the
- // key again; then its delta lands, under the new copy.
- for (0..40) |i| a.output(.{ .output = .{ .pane = .at(shell), .bytes = try std.fmt.bufPrint(&line, "round {d} line {d}\r\n", .{ round, i }) } });
- r.confirm((try a.pending()).?);
- r.settle();
- try std.testing.expect(r.copy.held);
- try deliver(a, &screens, peer, r, .flush);
- // The rows the core keeps, read once under the copy.
- _ = try pardes.edit.shellRows(r.core(), r.core().panes[shell].?);
- }
- for (sent.items) |m| {
- r.confirm(try a.take(m));
- r.settle();
- gpa.free(m);
- }
- sent.clearRetainingCapacity();
- try deliver(a, &screens, peer, r, .flush);
- // Drawn (its rows read, between steps), then typed into: the copy keeps
- // those rows. The shell prints, its delta lands under the copy, and then
- // another's unit puts the copy back: the rows it kept are of an older
- // grid and must not be read.
- r.confirm(try a.local(.{ .focus = false }));
- _ = try pardes.edit.shellRows(r.core(), r.core().panes[shell].?);
- try key(r, 'x', &sent);
- for (0..40) |i| a.output(.{ .output = .{ .pane = .at(shell), .bytes = try std.fmt.bufPrint(&line, "last line {d}\r\n", .{i}) } });
- r.confirm((try a.pending()).?);
- r.settle();
- try deliver(a, &screens, peer, r, .flush);
- r.confirm(try a.local(.{ .focus = true }));
- r.settle();
- const n = a.core.panes[shell].?.rows;
- const back = try pardes.edit.shellRows(r.core(), r.core().panes[shell].?);
- const now = try pardes.edit.shellRows(a.core, a.core.panes[shell].?);
- for (now[now.len - n ..], back[back.len - n ..]) |x, y| try std.testing.expectEqualStrings(x, y);
- for (sent.items) |m| {
- r.confirm(try a.take(m));
- r.settle();
- }
- try deliver(a, &screens, peer, r, .flush);
- if (r.diverged) |why| std.debug.print("diverged: {s}\n", .{why});
- try std.testing.expect(r.diverged == null and r.quiet());
- try std.testing.expectEqual(digestOf(a), r.digest());
- var dump_a: std.Io.Writer.Allocating = .init(gpa);
- defer dump_a.deinit();
- var dump_r: std.Io.Writer.Allocating = .init(gpa);
- defer dump_r.deinit();
- 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].?);
- // As many rows (the history is the authority's to the row), the screen's
- // the same; above it, rows scrolled past more than a screen at once are
- // holes until fetched.
- try std.testing.expectEqual(rows_a.len, rows_r.len);
- const shown = a.core.panes[shell].?.rows;
- for (rows_a[rows_a.len - shown ..], rows_r[rows_r.len - shown ..]) |x, y| try std.testing.expectEqualStrings(x, y);
-}
-
test "a closed terminal brought back on a screen-state replica: its emulator on the C heap, never the rollback epoch's" {
if (pardes.Term.ops == null) return error.SkipZigTest; // a shell
const gpa = std.testing.allocator;
- const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .boot = .tty }, TestHost.host(), true);
+ const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .boot = .tty }, TestHost.host());
defer a.deinit();
- const r = try Replica.init(gpa, 1, try a.unit(0, 0), true);
+ const r = try Replica.init(gpa, 1, try a.unit(0, 0));
defer r.deinit();
const shell: u8 = for (a.core.panes, 0..) |slot, id| {
if (slot) |pane| if (pane.isTerminal()) break @intCast(id);
@@ -4392,13 +3802,13 @@ test "a closed terminal brought back on a screen-state replica: its emulator on
test "a view that sized a terminal closing leaves nothing queued: the others' replicas copy, type and agree" {
if (pardes.Term.ops == null) return error.SkipZigTest; // a shell
const gpa = std.testing.allocator;
- const a = try Authority.init(gpa, .{ .cols = 100, .rows = 30, .boot = .tty }, TestHost.host(), true);
+ const a = try Authority.init(gpa, .{ .cols = 100, .rows = 30, .boot = .tty }, TestHost.host());
defer a.deinit();
const first = try gpa.dupe(u8, try a.unit(0, 0));
defer gpa.free(first);
- const r1 = try Replica.init(gpa, 1, first, true);
+ const r1 = try Replica.init(gpa, 1, first);
defer r1.deinit();
- const r2 = try Replica.init(gpa, 2, first, true);
+ const r2 = try Replica.init(gpa, 2, first);
defer r2.deinit();
a.core.view().active = for (a.core.panes, 0..) |slot, id| {
if (slot) |pane| if (pane.isTerminal()) break id;
@@ -4436,244 +3846,12 @@ test "a view that sized a terminal closing leaves nothing queued: the others' re
try std.testing.expectEqual(digestOf(a), r1.digest());
}
-test "a terminal sized again by a client's key: the step reads the grid it had, on both sides" {
- if (pardes.Term.ops == null) return error.SkipZigTest; // a shell
- const gpa = std.testing.allocator;
- const a = try Authority.init(gpa, .{ .cols = 50, .rows = 20, .boot = .tty }, TestHost.host(), true);
- defer a.deinit();
- var screens: Screens = .init(gpa);
- defer screens.deinit(a.core);
- const peer = try screens.addPeer();
- const r = try Replica.init(gpa, 1, try a.unit(0, 0), true);
- defer r.deinit();
- const shell: u8 = for (a.core.panes, 0..) |slot, id| {
- if (slot) |pane| if (pane.isTerminal()) break @intCast(id);
- } else return error.NoShell;
- a.core.view().active = shell;
- // History the replica holds as holes, of lines a narrow grid wraps in
- // two, which a wider one unwraps.
- var line: [96]u8 = undefined;
- for (0..60) |i| a.output(.{ .output = .{ .pane = .at(shell), .bytes = try std.fmt.bufPrint(&line, "{d:0>4} xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\r\n", .{i}) } });
- r.confirm((try a.pending()).?);
- // Out of terminal mode in the session's view, which sizes it; then a
- // client's own view (a copy of it), wider: its first key sizes the
- // terminal again, in that key's step (the soak's tty and window at two
- // sizes, 2026-10-30: the client's replay read holes the session's step
- // had read as text, and the fill came in the new grid's numbers).
- r.confirm(try a.local(.{ .key = .{ .cp = 'b', .ctrl = true } }));
- for ([_]u21{ 'g', 'g' }) |cp| r.confirm(try a.local(.{ .key = .{ .cp = cp, .text = &.{@intCast(cp)} } }));
- const opened = try a.openView(1);
- r.view = opened.view;
- r.confirm(opened.unit);
- try deliver(a, &screens, peer, r, .flush);
- var sent: std.ArrayListUnmanaged([]u8) = .empty;
- defer {
- for (sent.items) |m| gpa.free(m);
- sent.deinit(gpa);
- }
- const Step = struct {
- fn take(au: *Authority, sc: *Screens, pe: u16, rr: *Replica, msg: []const u8) !void {
- try deliver(au, sc, pe, rr, .flush);
- const u = try std.testing.allocator.dupe(u8, try au.take(msg));
- defer std.testing.allocator.free(u);
- try deliver(au, sc, pe, rr, .fill);
- pardes.panes.resizeDeferred(au.core);
- rr.confirm(u);
- rr.settle();
- }
- };
- try sent.append(gpa, try gpa.dupe(u8, try r.input(.{ .resize = .{ .cols = 120, .rows = 30 } })));
- try key(r, 'g', &sent);
- try key(r, 'g', &sent);
- for (sent.items) |m| try Step.take(a, &screens, peer, r, m);
- for (sent.items) |m| gpa.free(m);
- sent.clearRetainingCapacity();
- // The session's view types into it, which sizes it back (the client's
- // copy of its history all holes again, a new numbering); then the
- // client's key that reads all of it, and sizes it again.
- try deliver(a, &screens, peer, r, .flush);
- {
- const was = Stepping.begin(&a.t, null);
- a.core.toView(.at(0));
- a.core.update(.{ .key = .{ .cp = 'k', .text = "k" } });
- a.core.step();
- was.end();
- }
- a.seq += 1;
- const back = try gpa.dupe(u8, try a.unit(0, a.seq));
- defer gpa.free(back);
- try deliver(a, &screens, peer, r, .fill);
- pardes.panes.resizeDeferred(a.core);
- r.confirm(back);
- r.settle();
- try deliver(a, &screens, peer, r, .flush);
- try key(r, 'w', &sent);
- try key(r, 'w', &sent);
- for (sent.items) |m| try Step.take(a, &screens, peer, r, m);
- try deliver(a, &screens, peer, r, .flush);
- if (r.diverged) |why| std.debug.print("diverged: {s}\n", .{why});
- try std.testing.expect(r.diverged == null and r.quiet());
- try std.testing.expectEqual(digestOf(a), r.digest());
-}
-
-test "pardes's own keys over a terminal's history apply at once: its view moves here, a delta while they wait puts them on top again, the authority's ends the same" {
- if (pardes.Term.ops == null) return error.SkipZigTest; // a shell
- const gpa = std.testing.allocator;
- const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .boot = .tty }, TestHost.host(), true);
- defer a.deinit();
- var screens: Screens = .init(gpa);
- defer screens.deinit(a.core);
- const peer = try screens.addPeer();
- const r = try Replica.init(gpa, 1, try a.unit(0, 0), true);
- defer r.deinit();
- const shell: u8 = for (a.core.panes, 0..) |slot, id| {
- if (slot) |pane| if (pane.isTerminal()) break @intCast(id);
- } else return error.NoShell;
- a.core.view().active = shell;
- r.confirm(try a.local(.{ .focus = true }));
- var line: [64]u8 = undefined;
- for (0..200) |i| a.output(.{ .output = .{ .pane = .at(shell), .bytes = try std.fmt.bufPrint(&line, "history line {d}\r\n", .{i}) } });
- r.confirm((try a.pending()).?);
- try deliver(a, &screens, peer, r, .flush);
- r.settle();
- var sent: std.ArrayListUnmanaged([]u8) = .empty;
- defer {
- for (sent.items) |m| gpa.free(m);
- sent.deinit(gpa);
- }
- // Normal mode in the shell, up a few rows, then half a screen and more:
- // the cursor leaves the view, and the view follows it back.
- const keys = [_]pardes.Key{
- .{ .cp = a.core.opts.tty_toggle, .ctrl = true }, .{ .cp = 'k', .text = "k" }, .{ .cp = 'k', .text = "k" },
- .{ .cp = 'u', .ctrl = true }, .{ .cp = 'u', .ctrl = true }, .{ .cp = 'k', .text = "k" },
- };
- for (keys) |k| try sent.append(gpa, try gpa.dupe(u8, try r.input(.{ .key = k })));
- try std.testing.expectEqual(@as(u32, 0), r.stats.stopped);
- try std.testing.expectEqual(sent.items.len, r.applied);
- const here = r.core().panes[shell].?;
- try std.testing.expect(pardes.Term.grid(here.terminal).view != null);
- // The shell prints while they wait: its unit, then its delta, which
- // sets the view the authority's (at the bottom still): what was applied
- // goes on top of it again.
- for (0..5) |i| a.output(.{ .output = .{ .pane = .at(shell), .bytes = try std.fmt.bufPrint(&line, "late line {d}\r\n", .{i}) } });
- r.confirm((try a.pending()).?);
- r.settle();
- try deliver(a, &screens, peer, r, .flush);
- r.settle();
- try std.testing.expectEqual(sent.items.len, r.applied);
- try std.testing.expect(pardes.Term.grid(r.core().panes[shell].?.terminal).view != null);
- // The authority takes them in order, the terminal sent before each and
- // the rows its step read after, as the session's loop does.
- for (sent.items) |m| {
- try deliver(a, &screens, peer, r, .flush);
- r.settle();
- const u = try gpa.dupe(u8, try a.take(m));
- defer gpa.free(u);
- try deliver(a, &screens, peer, r, .fill);
- r.confirm(u);
- r.settle();
- }
- try deliver(a, &screens, peer, r, .flush);
- r.settle();
- if (r.diverged) |why| std.debug.print("diverged: {s}\n", .{why});
- try std.testing.expect(r.diverged == null and r.quiet());
- try std.testing.expectEqual(@as(u32, 0), r.stats.mispredicted);
- try std.testing.expectEqual(digestOf(a), r.digest());
- try std.testing.expect(pardes.Term.grid(a.core.panes[shell].?.terminal).view != null);
- try std.testing.expectEqual(pardes.Term.grid(a.core.panes[shell].?.terminal).view, pardes.Term.grid(r.core().panes[shell].?.terminal).view);
- // A rollback with nothing confirmed on top puts the view back: one more
- // key up, and another's unit first.
- try sent.append(gpa, try gpa.dupe(u8, try r.input(.{ .key = .{ .cp = 'u', .ctrl = true } })));
- const before = pardes.Term.grid(a.core.panes[shell].?.terminal).view;
- try std.testing.expect(pardes.Term.grid(r.core().panes[shell].?.terminal).view.? < before.?);
- r.confirm(try a.local(.{ .focus = false }));
- r.settle();
- const last = try gpa.dupe(u8, try a.take(sent.items[sent.items.len - 1]));
- defer gpa.free(last);
- r.toConfirmed();
- try std.testing.expectEqual(before, pardes.Term.grid(r.core().panes[shell].?.terminal).view);
- r.dirty = true;
- r.settle();
- try deliver(a, &screens, peer, r, .fill);
- r.confirm(last);
- r.settle();
- try deliver(a, &screens, peer, r, .flush);
- r.settle();
- if (r.diverged) |why| std.debug.print("diverged: {s}\n", .{why});
- try std.testing.expect(r.diverged == null and r.quiet());
- try std.testing.expectEqual(digestOf(a), r.digest());
- try std.testing.expectEqual(pardes.Term.grid(a.core.panes[shell].?.terminal).view, pardes.Term.grid(r.core().panes[shell].?.terminal).view);
-}
-
-test "a unit kept over a copy taken ahead is never replayed over a delta that came after it: the session's key read a shell's rows, the program redrew them" {
- if (pardes.Term.ops == null) return error.SkipZigTest; // a shell
- const gpa = std.testing.allocator;
- const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .boot = .tty }, TestHost.host(), true);
- defer a.deinit();
- var screens: Screens = .init(gpa);
- defer screens.deinit(a.core);
- const peer = try screens.addPeer();
- const r = try Replica.init(gpa, 1, try a.unit(0, 0), true);
- defer r.deinit();
- const shell: u8 = for (a.core.panes, 0..) |slot, id| {
- if (slot) |pane| if (pane.isTerminal()) break @intCast(id);
- } else return error.NoShell;
- a.core.view().active = shell;
- r.confirm(try a.local(.{ .focus = true }));
- var line: [96]u8 = undefined;
- for (0..30) |i| a.output(.{ .output = .{ .pane = .at(shell), .bytes = try std.fmt.bufPrint(&line, "line {d} {s}\r\n", .{ i, "words of a length its own"[0 .. i % 20 + 4] }) } });
- r.confirm((try a.pending()).?);
- try deliver(a, &screens, peer, r, .flush);
- // Out of the shell's tty mode, in the session's view: keys over its text.
- r.confirm(try a.local(.{ .key = .{ .cp = a.core.opts.tty_toggle, .ctrl = true } }));
- r.settle();
- // The client idle: a copy taken ahead. The session's keys read the rows
- // (up, to the line's end): replayed here over the copy, and kept.
- r.ready();
- try std.testing.expect(r.copy.held);
- for ([_]u21{ 'k', 'k', '$' }) |cp| {
- const u = try gpa.dupe(u8, try a.local(.{ .key = .{ .cp = cp, .text = &.{@intCast(cp)} } }));
- defer gpa.free(u);
- try deliver(a, &screens, peer, r, .fill);
- r.confirm(u);
- r.settle();
- }
- // The program redraws the screen: other rows where those keys read.
- a.output(.{ .output = .{ .pane = .at(shell), .bytes = "\x1b[H\x1b[2J" } });
- for (0..30) |i| a.output(.{ .output = .{ .pane = .at(shell), .bytes = try std.fmt.bufPrint(&line, "{d}\r\n", .{i}) } });
- r.confirm((try a.pending()).?);
- r.settle();
- try deliver(a, &screens, peer, r, .flush);
- // The client types, and the session's key comes first: a rollback, which
- // must not replay the keys that read the rows over the redrawn ones.
- var sent: std.ArrayListUnmanaged([]u8) = .empty;
- defer {
- for (sent.items) |m| gpa.free(m);
- sent.deinit(gpa);
- }
- try key(r, 'h', &sent);
- try std.testing.expectEqual(@as(usize, 1), r.applied);
- {
- const u = try gpa.dupe(u8, try a.local(.{ .key = .{ .cp = '0', .text = "0" } }));
- defer gpa.free(u);
- try deliver(a, &screens, peer, r, .fill);
- r.confirm(u);
- r.settle();
- }
- try deliver(a, &screens, peer, r, .flush);
- r.confirm(try a.take(sent.items[0]));
- r.settle();
- if (r.diverged) |why| std.debug.print("diverged: {s}\n", .{why});
- try std.testing.expect(r.diverged == null and r.quiet());
- try std.testing.expectEqual(digestOf(a), r.digest());
-}
-
test "a unit that closes or tears down a terminal is never kept over a copy taken ahead: a rollback would close its emulator again" {
if (pardes.Term.ops == null) return error.SkipZigTest; // a shell
const gpa = std.testing.allocator;
- const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .boot = .tty }, TestHost.host(), true);
+ const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .boot = .tty }, TestHost.host());
defer a.deinit();
- const r = try Replica.init(gpa, 1, try a.unit(0, 0), true);
+ const r = try Replica.init(gpa, 1, try a.unit(0, 0));
defer r.deinit();
const text = for (a.core.panes, 0..) |slot, id| {
if (slot) |pane| if (pane.file != null) break id;
@@ -4738,9 +3916,9 @@ const BytesPair = struct {
fn init() !BytesPair {
const gpa = std.testing.allocator;
- const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .boot = .tty }, TestHost.host(), false);
+ const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .boot = .tty }, TestHost.host());
errdefer a.deinit();
- const r = try Replica.init(gpa, 1, try a.unit(0, 0), false);
+ const r = try Replica.init(gpa, 1, try a.unit(0, 0));
var shell: ?pardes.Pane.Id = null;
for (a.core.panes, 0..) |slot, id| if (slot) |pane| {
if (pane.isTerminal()) shell = .at(id) else if (pane.file != null) a.core.view().active = @intCast(id);
@@ -4900,7 +4078,6 @@ test "bytes: a client joins from a dump with its terminals whole, and every side
try std.testing.expect(pardes.Term.writes != reloads);
const late = try Replica.initDump(gpa, 2, joined.view, joined.dump, .{ .cols = 80, .rows = 24 });
defer late.deinit();
- late.t.screen_state = false;
late.core().echo = null;
try std.testing.expectEqual(joined.digest, late.digest());
b.a.output(.{ .output = .{ .pane = b.shell, .bytes = ";30mthe rest of it\x1b[0m\r\n" } });
@@ -4958,7 +4135,7 @@ test "a Restore tells its clients so before it lets them go (each joins again, s
fn post(l: *@This(), msg: Said) bool {
switch (msg) {
.refused => |w| l.words = w,
- .unit, .screen, .blob => |b| std.heap.c_allocator.free(b),
+ .unit, .blob => |b| std.heap.c_allocator.free(b),
.checked, .ended, .left => {},
}
return true;
@@ -5054,13 +4231,14 @@ fn ownBootAgainst(edited: bool) !void {
/// A session's first client on a socket pair (runtime/session.zig's, then
/// the client's first join on its end), the session's first effects after:
/// its boot shell spawned, its first bytes output; the client quiet and
-/// checked. Bytes: the client loaded as the soak's bytes clients are
-/// (`replica.join` loads the screen-state kind until the switch).
-fn firstOnPair(bytes: bool) !void {
+/// checked. `by_dump`: the client joined by the session's dump, as any
+/// client loads one (`fromDump`); else it makes its own core (Options.pair,
+/// `confirmBoot`).
+fn firstOnPair(by_dump: bool) !void {
if (pardes.Term.ops == null) return error.SkipZigTest; // a shell
const gpa = std.testing.allocator;
const Spawns = struct {
- fn spawn(ctx: ?*anyopaque, _: pardes.Pane.Id, _: []const u8) void {
+ fn spawn(ctx: ?*anyopaque, _: pardes.Pane.Id, _: []const u8, _: pardes.PtySize) void {
const n: *u32 = @ptrCast(@alignCast(ctx.?));
n.* += 1;
}
@@ -5073,7 +4251,7 @@ fn firstOnPair(bytes: bool) !void {
const core = try Pardes.init(gpa, opts);
defer core.deinit();
core.host = .{ .ctx = &spawns, .vtable = &Spawns.vtable };
- var ps: Peers = .{ .gpa = gpa, .io = std.testing.io, .name = "pair", .bytes = bytes, .detached = true };
+ var ps: Peers = .{ .gpa = gpa, .io = std.testing.io, .name = "pair", .detached = true };
defer ps.deinit();
defer live_peers = null;
defer ps.dropAll(core);
@@ -5081,12 +4259,10 @@ fn firstOnPair(bytes: bool) !void {
ps.join(core, .{ .fd = fds[0], .own = true });
var j: Joined = undefined;
var why: [600]u8 = @splat(0);
- const r = if (bytes) r: {
- // Joined by its dump as any client loads one (`fromDump`): the
- // welcome says the road, and its load is checked on it.
+ const r = if (by_dump) r: {
+ // Joined by its dump as any client loads one (`fromDump`).
j = joinOn(gpa, fds[1], null, &why, null, null, null) orelse return error.JoinFailed;
defer gpa.free(j.dump);
- try std.testing.expect(j.bytes);
break :r fromDump(gpa, &j, opts, null, &why, nowNs()) orelse {
std.debug.print("the join: {s}\n", .{std.mem.sliceTo(&why, 0)});
return error.JoinFailed;
@@ -5123,7 +4299,7 @@ fn firstOnPair(bytes: bool) !void {
} else return error.NoShell;
core.update(.{ .output = .{ .pane = .at(shell), .bytes = "first$ " } });
ps.boundary(core);
- // Its check, answered after every unit and terminal message before it.
+ // Its check, answered after every unit before it.
try std.testing.expect(askCheck(j.fd));
while (!ps.mail.load(.acquire)) std.Thread.yield() catch {};
ps.boundary(core);
@@ -5134,9 +4310,6 @@ fn firstOnPair(bytes: bool) !void {
fn take(t: *@This(), tag: u8, payload: []const u8) bool {
switch (std.enums.fromInt(wire.ServerTag, tag) orelse return false) {
.unit => t.r.confirm(payload),
- .screen => if (t.r.screen(payload)) |reply| {
- _ = sendScreen(t.fd, reply);
- },
.check => {
t.digest = (wire.decodeServer(tag, payload) catch return false).check;
return false;
@@ -5160,7 +4333,7 @@ fn firstOnPair(bytes: bool) !void {
defer arena.deinit();
const rows = try pardes.Term.viewport(r.core().panes[shell].?.terminal.?, arena.allocator(), false);
try std.testing.expect(std.mem.indexOf(u8, rows[0], "first$") != null);
- if (!bytes) return;
+ if (!by_dump) return;
// One that comes after the shell's bytes: every side reloads.
var late: [2]c_int = undefined;
if (libc.socketpair(libc.AF.UNIX, libc.SOCK.STREAM | libc.SOCK.CLOEXEC, 0, &late) != 0) return error.NoSocket;
@@ -5228,7 +4401,6 @@ test "bytes: a join reloads only the terminals written since their last reload:
try std.testing.expectEqual(2, pardes.Term.reloads.n - before);
const late = try Replica.initDump(gpa, 3, joined.view, joined.dump, .{ .cols = 80, .rows = 24 });
defer late.deinit();
- late.t.screen_state = false;
late.core().echo = null;
try std.testing.expectEqual(joined.digest, late.digest());
// Output into both until each has pruned its history (whole pages, by
@@ -5357,7 +4529,7 @@ test "bytes: a kitty image shown by a file, a temporary file or shared memory is
test "a replica joined from the session's dump replays the units after it" {
const gpa = std.testing.allocator;
- const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host(), false);
+ const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host());
defer a.deinit();
_ = try a.local(.{ .key = .{ .cp = 'j', .text = "j" } });
const was = Stepping.begin(&a.t, null);
@@ -5393,7 +4565,7 @@ test "a replica joined from a dump replays a step that opens a file's pane and s
// No rows for a second pane: the Look's pane of a kind is made, the
// placement says it has no room (a message in the step that made the
// pane, which was not in /log yet), and the pane goes.
- const a = try Authority.init(gpa, .{ .cols = 80, .rows = 5, .file = "mise.toml" }, TestHost.host(), false);
+ const a = try Authority.init(gpa, .{ .cols = 80, .rows = 5, .file = "mise.toml" }, TestHost.host());
defer a.deinit();
var words: [64]pardes.Kind.LoadedWord = undefined;
const zon = pardes.Kind.loadedOf(&Zon.ops, "/x/zon.so", @splat(9), &words);
@@ -5427,7 +4599,7 @@ const Zon = struct {
test "a replica joined from a themed dump paints its taglines in the restored theme" {
const gpa = std.testing.allocator;
- const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "build.zig" }, TestHost.host(), false);
+ const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "build.zig" }, TestHost.host());
defer a.deinit();
_ = try a.local(.{ .command = "Theme rose_pine_moon" });
const was = Stepping.begin(&a.t, null);
@@ -5460,7 +4632,7 @@ test "a host's Adopt and a terminal reader's failure are inputs: a replica makes
if (pardes.Term.ops == null) return error.SkipZigTest; // a shell, opened by a key
const gpa = std.testing.allocator;
// Its terminals as screen state, as a session's for its clients are.
- const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host(), true);
+ const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host());
defer a.deinit();
const was = Stepping.begin(&a.t, null);
const bytes = try pardes.dump.dumpBytes(a.core);
@@ -5486,7 +4658,7 @@ test "a host's Adopt and a terminal reader's failure are inputs: a replica makes
test "a join's dump, its blobs put back where they go, is the session's dump" {
const gpa = std.testing.allocator;
- const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host(), false);
+ const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host());
defer a.deinit();
const text = try gpa.alloc(u8, 20000);
defer gpa.free(text);
@@ -5612,7 +4784,7 @@ test "a far join is sent each blob once: joined again with them on disk or in th
const io = std.testing.io;
zstd.gpa = gpa;
defer zstd.gpa = std.heap.c_allocator;
- const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host(), false);
+ const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host());
defer a.deinit();
const text = try gpa.alloc(u8, 30000);
defer gpa.free(text);
@@ -5707,7 +4879,7 @@ test "a far join is sent each blob once: joined again with them on disk or in th
test "a replica joined after a pane closed: the session's jump to it, its Panes and Recent rows, asked by either" {
const gpa = std.testing.allocator;
- const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host(), false);
+ const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host());
defer a.deinit();
// A file looked at and closed: a jump to it, Recent's, a closed pane.
var cwd: [std.Io.Dir.max_path_bytes]u8 = undefined;
@@ -5759,7 +4931,7 @@ test "a replica joined after a pane closed: the session's jump to it, its Panes
test "a replica's Del of a file its session's Recent knows asks the host what the session asked" {
const gpa = std.testing.allocator;
- const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host(), false);
+ const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host());
defer a.deinit();
var cwd: [std.Io.Dir.max_path_bytes]u8 = undefined;
var line: [std.Io.Dir.max_path_bytes + 32]u8 = undefined;
@@ -5778,11 +4950,11 @@ test "a replica's Del of a file its session's Recent knows asks the host what th
test "a client leaves, and one joins: what the leave queued (a terminal's resize) is done in its unit, on every side, before the join's dump" {
const gpa = std.testing.allocator;
- const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .boot = .tty }, PtyHost.host(), true);
+ const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .boot = .tty }, PtyHost.host());
defer a.deinit();
const first = try gpa.dupe(u8, try a.unit(0, 0));
defer gpa.free(first);
- const old = try Replica.init(gpa, 1, first, true);
+ const old = try Replica.init(gpa, 1, first);
defer old.deinit();
// A second client, bigger, types into the terminal: it sizes it.
const opened = try a.openView(2);
@@ -5817,11 +4989,11 @@ test "a client leaves, and one joins: what the leave queued (a terminal's resize
test "a client that diverged joins again for its view: kept for it meanwhile, its pane in it again; the other client agrees" {
const gpa = std.testing.allocator;
- const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host(), false);
+ const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host());
defer a.deinit();
const first = try gpa.dupe(u8, try a.unit(0, 0));
defer gpa.free(first);
- const old = try Replica.init(gpa, 1, first, false);
+ const old = try Replica.init(gpa, 1, first);
defer old.deinit();
const opened = try a.openView(2);
old.confirm(opened.unit);
@@ -5860,13 +5032,21 @@ test "a client cut off for what it left unread is told why and joins again for i
// welcome, the dump with its blobs in place); and what it queued for one,
// down its link in order, the link's end after it if it was cut off.
const MemoryLinks = struct {
- fn join(ps: *Peers, core: *Pardes, view: ?u8, fd: *c_int) !struct { r: *Replica, peer: *Peer } {
+ /// `old`: the link it had, whose end the session hears after this
+ /// join came: held until then.
+ fn join(ps: *Peers, core: *Pardes, view: ?u8, fd: *c_int, old: ?*Peer) !struct { r: *Replica, peer: *Peer } {
const gpa = std.testing.allocator;
var fds: [2]c_int = undefined;
if (libc.socketpair(libc.AF.UNIX, libc.SOCK.STREAM | libc.SOCK.CLOEXEC, 0, &fds) != 0) return error.NoSocket;
fd.* = fds[1];
ps.handed(fds[0], view);
ps.boundary(core);
+ if (old) |o| {
+ for (ps.list) |slot| if (slot) |p| if (p.fd == fds[0]) return error.NotHeld;
+ ps.post(.{ .gone = o });
+ ps.boundary(core);
+ ps.boundary(core);
+ }
const peer = for (ps.list) |slot| {
if (slot) |p| if (p.fd == fds[0]) break p;
} else return error.Refused;
@@ -5914,7 +5094,7 @@ test "a client cut off for what it left unread is told why and joins again for i
defer ps.deinit();
defer ps.dropAll(core);
var fd: c_int = -1;
- const first = try MemoryLinks.join(&ps, core, null, &fd);
+ const first = try MemoryLinks.join(&ps, core, null, &fd, null);
defer _ = libc.close(fd);
var link: Link = .{ .r = first.r, .fd = fd };
defer link.deinit(gpa);
@@ -5941,13 +5121,12 @@ test "a client cut off for what it left unread is told why and joins again for i
// It was told why, and joins again (as a divergence's client does)...
try std.testing.expect(link.rejoins());
try std.testing.expect(std.mem.indexOf(u8, link.notice(), "behind") != null);
- // ...once its old link's end is heard: its view kept for it meanwhile.
- ps.post(.{ .gone = first.peer });
- ps.boundary(core);
- try std.testing.expect(pardes.views.isAway(core, view.index()));
+ // ...its old link shut, at once (runtime/client.zig `run`): a join that
+ // comes before that link's end is heard, on another connection, waits
+ // for it, its view kept for it meanwhile.
first.r.deinit();
_ = libc.close(fd);
- const back = try MemoryLinks.join(&ps, core, view.index(), &fd);
+ const back = try MemoryLinks.join(&ps, core, view.index(), &fd, first.peer);
defer back.r.deinit();
try std.testing.expectEqual(view, back.peer.view);
link.reset(back.r, &.{ .fd = fd, .pid = 0, .client = back.r.id, .view = view.index(), .gmtoff = 0, .dump = &.{} });
@@ -5961,9 +5140,9 @@ test "a client cut off for what it left unread is told why and joins again for i
test "a client whose session's units come more than two seconds later than its quickest lets its link go, says so once, and joins again; its first unit after a join learns the clocks again" {
const gpa = std.testing.allocator;
- const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host(), false);
+ const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host());
defer a.deinit();
- const r = try Replica.init(gpa, 1, try a.unit(0, 0), false);
+ const r = try Replica.init(gpa, 1, try a.unit(0, 0));
var fds: [2]c_int = undefined;
if (libc.socketpair(libc.AF.UNIX, libc.SOCK.STREAM | libc.SOCK.CLOEXEC, 0, &fds) != 0) return error.NoSocket;
defer for (fds) |fd| {
@@ -6061,7 +5240,7 @@ test "a client's writer, the client cut off while it waits on the socket, writes
test "a client joined from a dump moves through another view's pane as the session does, its lines not wrapped" {
const gpa = std.testing.allocator;
- const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "build.zig" }, TestHost.host(), false);
+ const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "build.zig" }, TestHost.host());
defer a.deinit();
// The first client's Wrap off (SPC t w), and its cursor down into the
// file's long lines, near the bottom of its view.
@@ -6090,7 +5269,7 @@ test "a client joined from a dump moves through another view's pane as the sessi
test "a client joined from a dump makes a `/` query's rows as the session does, though only the session has drawn its owner" {
const gpa = std.testing.allocator;
- const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "build.zig" }, TestHost.host(), false);
+ const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "build.zig" }, TestHost.host());
defer a.deinit();
// The session draws: its owner's colours painted for the view (File.refreshHighlights).
{
@@ -6126,7 +5305,7 @@ test "a client joined from a dump asks a worker for a `/` query's colours as the
};
const gpa = std.testing.allocator;
// A view as tall as the text: the frame paints every line of it.
- const a = try Authority.init(gpa, .{ .cols = 80, .rows = 500, .file = "build.zig" }, .{ .vtable = &Paints.vtable }, false);
+ const a = try Authority.init(gpa, .{ .cols = 80, .rows = 500, .file = "build.zig" }, .{ .vtable = &Paints.vtable });
defer a.deinit();
{
const was = Stepping.begin(&a.t, null);
@@ -6156,7 +5335,7 @@ test "a client joined from a dump asks a worker for a `/` query's colours as the
const vtable: pardes.Host.VTable = .{ .watched = TestHost.watched, .search = search };
};
const gpa = std.testing.allocator;
- const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "build.zig" }, .{ .vtable = &Paints.vtable }, false);
+ const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "build.zig" }, .{ .vtable = &Paints.vtable });
defer a.deinit();
{
const p = a.core;
@@ -6177,49 +5356,11 @@ test "a client joined from a dump asks a worker for a `/` query's colours as the
}
}
-test "a step that reads a terminal's rows as the core keeps them sends a new client the ones it holds as holes" {
- if (pardes.Term.ops == null) return error.SkipZigTest; // a shell
- const gpa = std.testing.allocator;
- const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .boot = .tty }, PtyHost.host(), true);
- defer a.deinit();
- var screens: Screens = .init(gpa);
- defer screens.deinit(a.core);
- const first = try gpa.dupe(u8, try a.unit(0, 0));
- defer gpa.free(first);
- const r1 = try Replica.init(gpa, 1, first, true);
- defer r1.deinit();
- const r2 = try Replica.init(gpa, 2, first, true);
- defer r2.deinit();
- const shell: u8 = for (a.core.panes, 0..) |slot, id| {
- if (slot) |pane| if (pane.isTerminal()) break @intCast(id);
- } else return error.NoShell;
- a.core.view().active = shell;
- var line: [64]u8 = undefined;
- for (0..60) |i| a.output(.{ .output = .{ .pane = .at(shell), .bytes = try std.fmt.bufPrint(&line, "line {d} of the shell's history\r\n", .{i}) } });
- const out = try gpa.dupe(u8, (try a.pending()).?);
- defer gpa.free(out);
- for ([_]*Replica{ r1, r2 }) |r| r.confirm(out);
- // The first client alone has the terminal; it reads all of its rows
- // (its text, the cursor on the first): the core keeps them.
- const p1 = [_]u16{try screens.addPeer()};
- for ([_]pardes.Event{ .{ .key = .{ .cp = 'b', .ctrl = true } }, .{ .key = .{ .cp = 'g', .text = "g" } }, .{ .key = .{ .cp = 'g', .text = "g" } } }) |ev| {
- const msg = try gpa.dupe(u8, try r1.input(ev));
- defer gpa.free(msg);
- try takeAll(a, &screens, &.{r1}, &p1, msg);
- r2.confirm(a.out.items);
- }
- // A second comes: its history all holes. The first reads the rows the
- // core kept, nothing written since.
- const ps = [_]u16{ p1[0], try screens.addPeer() };
- try sendAs(r1, a, &screens, &.{ r1, r2 }, &ps, .{ .key = .{ .cp = 'O', .text = "O" } });
- for ([_]*Replica{ r1, r2 }) |r| try agrees(a, r);
-}
-
test "a replica with no code for a kind whose state is not plain shows its pane as a line saying so, and its keys go to the authority" {
const gpa = std.testing.allocator;
- const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host(), false);
+ const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host());
defer a.deinit();
- const r = try Replica.init(gpa, 1, try a.unit(0, 0), false);
+ const r = try Replica.init(gpa, 1, try a.unit(0, 0));
defer r.deinit();
// What the host read off the library, as the `addon` event: the
// replica's core takes the kind's words, never its code.
@@ -6277,9 +5418,9 @@ const Placed = struct {
test "a kind's place moved in a step of another view's: a replica's key that reads it guesses the authority's" {
const gpa = std.testing.allocator;
- const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host(), false);
+ const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host());
defer a.deinit();
- const r = try Replica.init(gpa, 1, try a.unit(0, 0), false);
+ const r = try Replica.init(gpa, 1, try a.unit(0, 0));
defer r.deinit();
var words: [64]pardes.Kind.LoadedWord = undefined;
const placed = pardes.Kind.loadedOf(&Placed.ops, "/x/placed.so", @splat(7), &words);
@@ -6333,7 +5474,7 @@ const Jobber = struct {
test "a client joined from a dump numbers a kind's next job as the session does" {
const gpa = std.testing.allocator;
- const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host(), false);
+ const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host());
defer a.deinit();
var words: [64]pardes.Kind.LoadedWord = undefined;
const jobber = pardes.Kind.loadedOf(&Jobber.ops, "/x/jobber.so", @splat(7), &words);
@@ -6350,9 +5491,9 @@ test "a client joined from a dump numbers a kind's next job as the session does"
test "a replica's word that opens a kind's pane with no file waits for the authority's open: never mispredicted" {
const gpa = std.testing.allocator;
- const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host(), false);
+ const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host());
defer a.deinit();
- const r = try Replica.init(gpa, 1, try a.unit(0, 0), false);
+ const r = try Replica.init(gpa, 1, try a.unit(0, 0));
defer r.deinit();
var words: [64]pardes.Kind.LoadedWord = undefined;
const placed = pardes.Kind.loadedOf(&Placed.ops, "/x/placed.so", @splat(7), &words);
@@ -6371,7 +5512,7 @@ test "a replica's word that opens a kind's pane with no file waits for the autho
test "a client joined from a dump tells a kind each view's facts as the session does, the live one's and another's" {
const gpa = std.testing.allocator;
- const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host(), false);
+ const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host());
defer a.deinit();
var words: [64]pardes.Kind.LoadedWord = undefined;
const placed = pardes.Kind.loadedOf(&Placed.ops, "/x/placed.so", @splat(7), &words);
@@ -6441,10 +5582,10 @@ const BusyHost = struct {
test "a kind's job answered at once inside its host's call (no worker free) is taken by a client as the session took it" {
const gpa = std.testing.allocator;
- const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, .{ .vtable = &BusyHost.vtable }, false);
+ const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, .{ .vtable = &BusyHost.vtable });
defer a.deinit();
BusyHost.core = a.core;
- const r = try Replica.init(gpa, 1, try a.unit(0, 0), false);
+ const r = try Replica.init(gpa, 1, try a.unit(0, 0));
defer r.deinit();
var words: [64]pardes.Kind.LoadedWord = undefined;
const asker = pardes.Kind.loadedOf(&Asker.ops, "/x/asker.so", @splat(7), &words);
@@ -6465,9 +5606,9 @@ test "a kind's job answered at once inside its host's call (no worker free) is t
test "a closed terminal with a kitty image brought back on a client: its image drawn under a speculation, rolled back by another's unit, is drawn again from what the emulator holds" {
if (pardes.Term.ops == null) return error.SkipZigTest; // a shell
const gpa = std.testing.allocator;
- const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .boot = .tty }, TestHost.host(), true);
+ const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .boot = .tty }, TestHost.host());
defer a.deinit();
- const r = try Replica.init(gpa, 1, try a.unit(0, 0), true);
+ const r = try Replica.init(gpa, 1, try a.unit(0, 0));
defer r.deinit();
const shell: u8 = for (a.core.panes, 0..) |slot, id| {
if (slot) |pane| if (pane.isTerminal()) break @intCast(id);
@@ -6539,40 +5680,35 @@ fn partsApart(a: *Authority, r: *Replica, arena: std.mem.Allocator) ![]const u8
return if (std.mem.eql(u64, w, g)) "" else tape.partsDiffer(g, w, arena);
}
-test "a terminal's program shows a kitty image under screen state: the client's emulator never has it, and its tag says what the session's does" {
+test "a terminal's program shows a kitty image: the client's emulator has it as the session's does, and its tag says what the session's does" {
if (pardes.Term.ops == null) return error.SkipZigTest; // a shell
const gpa = std.testing.allocator;
var arena: std.heap.ArenaAllocator = .init(gpa);
defer arena.deinit();
- const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .boot = .tty }, TestHost.host(), true);
+ const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .boot = .tty }, TestHost.host());
defer a.deinit();
- var screens: Screens = .init(gpa);
- defer screens.deinit(a.core);
- const peer = try screens.addPeer();
- const r = try Replica.init(gpa, 1, try a.unit(0, 0), true);
+ const r = try Replica.init(gpa, 1, try a.unit(0, 0));
defer r.deinit();
const shell: u8 = for (a.core.panes, 0..) |slot, id| {
if (slot) |pane| if (pane.isTerminal()) break @intCast(id);
} else return error.NoShell;
- try deliver(a, &screens, peer, r, .flush);
try std.testing.expectEqualStrings("", try partsApart(a, r, arena.allocator()));
- // In the session's order: the pump's unit, then what its terminals came
- // to; then a step after both, on every side.
+ // In the session's order: the pump's unit, its bytes fed on every side;
+ // then a step after it.
a.output(.{ .output = .{ .pane = .at(shell), .bytes = "\x1b_Ga=T,i=7,f=24,s=2,v=2;ESIzESIzESIzESIz\x1b\\" } });
r.confirm((try a.pending()).?);
r.settle();
- try deliver(a, &screens, peer, r, .flush);
r.confirm(try a.local(.{ .focus = true }));
r.settle();
try std.testing.expect(pardes.Term.hasImages(a.core.panes[shell].?.terminal));
- try std.testing.expect(!pardes.Term.hasImages(r.core().panes[shell].?.terminal));
+ try std.testing.expect(pardes.Term.hasImages(r.core().panes[shell].?.terminal));
try std.testing.expectEqualStrings("", try partsApart(a, r, arena.allocator()));
try agrees(a, r);
const prefix = try pardes.tagline.prefixIn(r.core(), arena.allocator(), r.core().panes[shell].?);
try std.testing.expect(std.mem.indexOf(u8, prefix, " petscii:") != null);
}
-test "a command typed into a shell with prompt marks under screen state: every side notes it as the session's emulator numbers it, and Kill finds it" {
+test "a command typed into a shell with prompt marks: every side notes it as its own emulator, fed the same bytes, numbers it, and Kill finds it" {
if (pardes.Term.ops == null) return error.SkipZigTest; // a shell
const gpa = std.testing.allocator;
var arena: std.heap.ArenaAllocator = .init(gpa);
@@ -6584,12 +5720,9 @@ test "a command typed into a shell with prompt marks under screen state: every s
fn write(_: ?*anyopaque, _: pardes.Pane.Id, _: []const u8) void {}
const vtable: pardes.Host.VTable = .{ .watched = TestHost.watched, .tty_taken = taken, .pty_write = write };
};
- const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .boot = .tty }, .{ .vtable = &ShellHost.vtable }, true);
+ const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .boot = .tty }, .{ .vtable = &ShellHost.vtable });
defer a.deinit();
- var screens: Screens = .init(gpa);
- defer screens.deinit(a.core);
- const peer = try screens.addPeer();
- const r = try Replica.init(gpa, 1, try a.unit(0, 0), true);
+ const r = try Replica.init(gpa, 1, try a.unit(0, 0));
defer r.deinit();
const shell: u8 = for (a.core.panes, 0..) |slot, id| {
if (slot) |pane| if (pane.isTerminal()) break @intCast(id);
@@ -6599,7 +5732,6 @@ test "a command typed into a shell with prompt marks under screen state: every s
a.output(.{ .output = .{ .pane = .at(shell), .bytes = prompt ++ "ls\r\n\x1b]133;C;aid=pardes\x07a b\r\n\x1b]133;D;0;aid=pardes\x07" ++ prompt } });
r.confirm((try a.pending()).?);
r.settle();
- try deliver(a, &screens, peer, r, .flush);
a.core.view().active = shell;
r.confirm(try a.local(.{ .focus = true }));
r.settle();
@@ -6607,7 +5739,7 @@ test "a command typed into a shell with prompt marks under screen state: every s
// Exec'd in the shell: typed at its prompt, the command noted.
r.confirm(try a.local(.{ .command = "Exec sleep 9" }));
r.settle();
- // Its marks cross with the cells (Term.marksOf): numbered alike.
+ // Its marks are its bytes' on every side: numbered alike.
try std.testing.expectEqual(@as(u32, 2), a.core.panes[shell].?.sent_command.?.seq);
try std.testing.expectEqual(@as(u32, 2), r.core().panes[shell].?.sent_command.?.seq);
try std.testing.expectEqualStrings("", try partsApart(a, r, arena.allocator()));
@@ -6615,7 +5747,6 @@ test "a command typed into a shell with prompt marks under screen state: every s
a.output(.{ .output = .{ .pane = .at(shell), .bytes = "sleep 9\r\n\x1b]133;C;aid=pardes\x07" } });
r.confirm((try a.pending()).?);
r.settle();
- try deliver(a, &screens, peer, r, .flush);
r.confirm(try a.local(.{ .command = "Kill" }));
r.settle();
try std.testing.expectEqualStrings("", try partsApart(a, r, arena.allocator()));
@@ -6642,7 +5773,7 @@ test "a step of the session's own that reads a terminal right after its output,
core.view().active = shell;
// The session as runtime/session.zig runs it; the client's link in
// memory.
- var ps: Peers = .{ .gpa = gpa, .io = std.testing.io, .threads = false, .bytes = true };
+ var ps: Peers = .{ .gpa = gpa, .io = std.testing.io, .threads = false };
defer ps.deinit();
defer ps.dropAll(core);
var fds: [2]c_int = undefined;
@@ -6670,7 +5801,6 @@ test "a step of the session's own that reads a terminal right after its output,
try whole.appendSlice(gpa, peer.dump[pos..]);
const r = try Replica.initDump(gpa, w.client, w.view.index(), whole.items, .{ .cols = 80, .rows = 24, .boot = .tty });
defer r.deinit();
- road(r, w.bytes);
try std.testing.expect(r.loaded(w.digest));
var link: Link = .{ .r = r, .fd = fds[1] };
defer link.deinit(gpa);
@@ -6680,7 +5810,6 @@ test "a step of the session's own that reads a terminal right after its output,
var at: usize = 0;
while (try wire.framed(from.out.items[at..])) |m| : (at += m.total) l.take(switch (std.enums.fromInt(wire.ServerTag, m.tag).?) {
.unit => .{ .unit = try std.heap.c_allocator.dupe(u8, m.payload) },
- .screen => .{ .screen = try std.heap.c_allocator.dupe(u8, m.payload) },
else => return error.UnexpectedFrame,
});
from.out.clearRetainingCapacity();
@@ -6711,7 +5840,7 @@ test "a step of the session's own that reads a terminal right after its output,
test "a far client's own Del of a pane whose kind's state is not plain, rolled back by another's unit: the pane comes back whole, and is closed again with the session's order" {
const gpa = std.testing.allocator;
- const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host(), false);
+ const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host());
defer a.deinit();
var words: [64]pardes.Kind.LoadedWord = undefined;
const counter = pardes.Kind.loadedOf(&Counter.ops, "/x/counter.so", @splat(7), &words);
@@ -6792,7 +5921,7 @@ const SeenHost = struct {
test "a client's step that asks the session's host for something that returns nothing goes on at once, and the session's unit confirms it: nothing rolled back" {
const gpa = std.testing.allocator;
var h: SeenHost = .{};
- const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, h.host(), false);
+ const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, h.host());
defer a.deinit();
h.core = a.core;
const r = try joinedFresh(a);
@@ -6812,7 +5941,7 @@ test "a client's step that asks the session's host for something that returns no
test "a client's step whose session's host says something into the core during the call it made: its speculation rolled back, then the session's state" {
const gpa = std.testing.allocator;
var h: SeenHost = .{ .tell = true };
- const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, h.host(), false);
+ const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, h.host());
defer a.deinit();
h.core = a.core;
const r = try joinedFresh(a);
@@ -6835,7 +5964,7 @@ test "a client's ThemeFile waits for the session, whose host loads the file into
const dir = dir_buf[0..try tmp.dir.realPath(std.testing.io, &dir_buf)];
var line: [std.Io.Dir.max_path_bytes + 16]u8 = undefined;
var h: SeenHost = .{};
- const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, h.host(), false);
+ const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, h.host());
defer a.deinit();
h.core = a.core;
const r = try joinedFresh(a);
@@ -6855,7 +5984,7 @@ test "a client's ThemeFile waits for the session, whose host loads the file into
test "a client's yank and paste of the system clipboard are its own frontend's: its view counts them, at once and as the session does, and the session's host is asked neither" {
const gpa = std.testing.allocator;
var h: SeenHost = .{};
- const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, h.host(), false);
+ const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, h.host());
defer a.deinit();
h.core = a.core;
_ = try a.unit(0, 0);
@@ -6888,7 +6017,7 @@ test "a client's yank and paste of the system clipboard are its own frontend's:
test "a client's own Zerox and Del of a file pane are instant: what Recent keeps of the file is what its open learned, not a question to the disk; Recent has its place as the session's always did" {
const gpa = std.testing.allocator;
var h: SeenHost = .{};
- const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, h.host(), false);
+ const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, h.host());
defer a.deinit();
h.core = a.core;
var cwd: [std.Io.Dir.max_path_bytes]u8 = undefined;
@@ -6931,7 +6060,7 @@ const Still = struct {
test "a client's n in a kind's pane is a motion: it steps to the next place a result row holds at once, asking the disk nothing of words that might name files" {
const gpa = std.testing.allocator;
- const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host(), false);
+ const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host());
defer a.deinit();
var cwd: [std.Io.Dir.max_path_bytes]u8 = undefined;
const dir = std.mem.span(@as([*:0]u8, @ptrCast(std.c.getcwd(&cwd, cwd.len) orelse return error.NoCwd)));
@@ -7255,7 +6384,7 @@ const Walk = struct {
test "a far client's every word and key, on a file's pane, a kind's and a shell's, and the gestures between them beside a shell that asked for focus events: what waits is in may_wait, with why, and nothing else waits" {
const gpa = std.testing.allocator;
- const a = try Authority.init(gpa, .{ .cols = 120, .rows = 40, .boot = .tty }, FullHost.host(), true);
+ const a = try Authority.init(gpa, .{ .cols = 120, .rows = 40, .boot = .tty }, FullHost.host());
defer a.deinit();
var cwd: [std.Io.Dir.max_path_bytes]u8 = undefined;
var line: [std.Io.Dir.max_path_bytes + 32]u8 = undefined;
@@ -7296,13 +6425,9 @@ test "a far client's every word and key, on a file's pane, a kind's and a shell'
a.core.view().active = id;
_ = a.local(.{ .key = .{ .cp = a.core.opts.tty_toggle, .ctrl = true } }) catch {};
};
- var screens: Screens = .init(gpa);
- defer screens.deinit(a.core);
- const peer = try screens.addPeer();
const r = try joinedFresh(a);
defer r.deinit();
r.core().kinds.ops[r.core().kinds.byName("still").?] = &Still.ops;
- try deliver(a, &screens, peer, r, .flush);
r.settle();
try std.testing.expectEqual(id, r.core().view().active);
if (on == .shell) try std.testing.expect(pardes.Term.modes(r.core().panes[id].?.terminal).focus);
@@ -7384,7 +6509,7 @@ test "a far client's click into a shell whose program asked for focus events is
const vtable: pardes.Host.VTable = .{ .watched = TestHost.watched, .pty_write = write };
};
Told.len = 0;
- const a = try Authority.init(gpa, .{ .cols = 120, .rows = 40, .boot = .tty }, .{ .vtable = &Told.vtable }, true);
+ const a = try Authority.init(gpa, .{ .cols = 120, .rows = 40, .boot = .tty }, .{ .vtable = &Told.vtable });
defer a.deinit();
const shell: u8 = for (a.core.panes, 0..) |slot, id| {
if (slot) |pane| if (pane.isTerminal()) break @intCast(id);
@@ -7392,12 +6517,8 @@ test "a far client's click into a shell whose program asked for focus events is
a.output(.{ .output = .{ .pane = .at(shell), .bytes = "\x1b[?1004h$ " } });
_ = (try a.pending()).?;
_ = try a.local(.{ .command = "New" });
- var screens: Screens = .init(gpa);
- defer screens.deinit(a.core);
- const peer = try screens.addPeer();
const r = try joinedFresh(a);
defer r.deinit();
- try deliver(a, &screens, peer, r, .flush);
r.settle();
Told.len = 0;
const rect = r.core().view().rects[shell];
@@ -7411,10 +6532,8 @@ test "a far client's click into a shell whose program asked for focus events is
try std.testing.expectEqual(@as(u32, 0), r.stats.stopped);
try std.testing.expectEqual(@as(usize, shell), r.core().view().active);
for (sent.items) |m| {
- try deliver(a, &screens, peer, r, .flush);
const u = try gpa.dupe(u8, try a.take(m));
defer gpa.free(u);
- try deliver(a, &screens, peer, r, .fill);
r.confirm(u);
r.settle();
}
@@ -7426,7 +6545,7 @@ test "a far client's click into a shell whose program asked for focus events is
test "a far client's own Look of ~/x, bare Shell and a word that runs in the session's directory read the session's facts: its speculation asks its own machine's environment nothing" {
const gpa = std.testing.allocator;
- const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host(), false);
+ const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host());
defer a.deinit();
const r = try joinedFresh(a);
defer r.deinit();
@@ -7464,7 +6583,7 @@ test "a far client's replay of the session's DumpDir takes the session's answer
// The session's machine: a directory it may not write in.
if (std.c.mkdir(ro, 0o500) != 0) return error.NoDir;
defer _ = std.c.chmod(ro, 0o700);
- const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host(), false);
+ const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host());
defer a.deinit();
const r = try joinedFresh(a);
defer r.deinit();
@@ -7522,7 +6641,7 @@ test "a far client's replay of the session's Fonts and Font takes the session's
if (fonts.list(arena.allocator(), null).len == session_faces and client_named.len > 0 and std.mem.eql(u8, client_named[0].path, session_first)) return error.SkipZigTest;
_ = Shell.setenv("HOME", session_home, 1);
// A window's view: the font words are a window's.
- const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml", .windowed = true }, TestHost.host(), false);
+ const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml", .windowed = true }, TestHost.host());
defer a.deinit();
const r = try joinedFresh(a);
defer r.deinit();
@@ -7545,7 +6664,7 @@ test "a far client's replay of the session's Fonts and Font takes the session's
// cover; an answer let go (not quiet then) covers nothing.
test "an idle client's check answered covers the units that came while it was asked: it asks no other until something changes" {
const gpa = std.testing.allocator;
- const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "build.zig" }, TestHost.host(), false);
+ const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "build.zig" }, TestHost.host());
defer a.deinit();
const r = try joinedNow(a, 1, 0);
defer r.deinit();
@@ -7594,7 +6713,7 @@ test "an idle client's check answered covers the units that came while it was as
// to look at, at its own focus-in (upgrade.noticeNewer).
test "a far client's window found again is instant: its refocus asks the session's host nothing, and the session's unit confirms it" {
const gpa = std.testing.allocator;
- const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, FullHost.host(), false);
+ const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, FullHost.host());
defer a.deinit();
const r = try joinedFresh(a);
defer r.deinit();
@@ -7643,7 +6762,7 @@ const Pointed = struct {
// client's speculation).
test "a far client's drag in a kind's pane it grabbed, the pane since too short for a row of body: the kind is told its edge, at once and as on the session" {
const gpa = std.testing.allocator;
- const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host(), false);
+ const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host());
defer a.deinit();
var words: [64]pardes.Kind.LoadedWord = undefined;
const pointed = pardes.Kind.loadedOf(&Pointed.ops, "/x/pointed.so", @splat(8), &words);
@@ -7744,7 +6863,7 @@ test "a far client's frame drawn under a speculation that rolls back asks a pict
}
};
const gpa = std.testing.allocator;
- const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host(), false);
+ const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host());
defer a.deinit();
var words: [64]pardes.Kind.LoadedWord = undefined;
const drawn = pardes.Kind.loadedOf(&Drawn.ops, "/x/drawn.so", @splat(9), &words);
@@ -7804,7 +6923,7 @@ test "a far client's click into a shell whose queue is backed up: the session's
}
const vtable: pardes.Host.VTable = .{ .watched = TestHost.watched, .pty_write = write };
};
- const a = try Authority.init(gpa, .{ .cols = 120, .rows = 40, .boot = .tty }, .{ .vtable = &Told.vtable }, true);
+ const a = try Authority.init(gpa, .{ .cols = 120, .rows = 40, .boot = .tty }, .{ .vtable = &Told.vtable });
defer a.deinit();
const shell: u8 = for (a.core.panes, 0..) |slot, id| {
if (slot) |pane| if (pane.isTerminal()) break @intCast(id);
@@ -7812,12 +6931,8 @@ test "a far client's click into a shell whose queue is backed up: the session's
a.output(.{ .output = .{ .pane = .at(shell), .bytes = "\x1b[?1004h$ " } });
_ = (try a.pending()).?;
_ = try a.local(.{ .command = "New" });
- var screens: Screens = .init(gpa);
- defer screens.deinit(a.core);
- const peer = try screens.addPeer();
const r = try joinedFresh(a);
defer r.deinit();
- try deliver(a, &screens, peer, r, .flush);
r.settle();
// A 9P write into the shell, past the ring: the rest parked, on both.
const big = try gpa.alloc(u8, pardes.memory.limits.effect_cap * pardes.effect_write_cap + 100);
@@ -7848,10 +6963,8 @@ test "a far client's click into a shell whose queue is backed up: the session's
try std.testing.expectEqual(@as(usize, 0), r.applied);
for (r.stats.stops) |st| if (st.n > 0) try std.testing.expectEqualStrings("pty_write", st.name);
for (sent.items) |m| {
- try deliver(a, &screens, peer, r, .flush);
const u = try gpa.dupe(u8, try a.take(m));
defer gpa.free(u);
- try deliver(a, &screens, peer, r, .fill);
r.confirm(u);
r.settle();
}
@@ -7912,7 +7025,7 @@ test "a client joined from a dump makes a `/` query's rows as the session does,
}
};
const gpa = std.testing.allocator;
- const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "build.zig" }, .{ .vtable = &WorkerSearch.vtable }, false);
+ const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "build.zig" }, .{ .vtable = &WorkerSearch.vtable });
defer a.deinit();
WorkerSearch.init(a);
defer WorkerSearch.q.deinit();
@@ -7939,7 +7052,7 @@ test "a client joined from a dump makes a `/` query's rows as the session does,
// elsewhere on a core that drew than on one that did not.
test "a client joined from a dump lands a click on a rail's tick as the session does, the session's ticks drawn before the places changed" {
const gpa = std.testing.allocator;
- const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "build.zig" }, TestHost.host(), false);
+ const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "build.zig" }, TestHost.host());
defer a.deinit();
_ = try a.local(.{ .command = "Search /pub" });
const owner: usize = 0;
@@ -8006,7 +7119,7 @@ test "a far client's step that asks for a search goes on at once, and a session
const dir = dir_buf[0..try tmp.dir.realPath(std.testing.io, &dir_buf)];
var path_buf: [std.Io.Dir.max_path_bytes + 8]u8 = undefined;
const path = try std.fmt.bufPrint(&path_buf, "{s}/a.zig", .{dir});
- const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = path }, .{ .vtable = &LoopSearch.vtable }, false);
+ const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = path }, .{ .vtable = &LoopSearch.vtable });
defer a.deinit();
LoopSearch.core = a.core;
const r = try joinedFresh(a);
@@ -8053,7 +7166,7 @@ test "a far client's replay of a message its session's host stamped takes the se
const was = if (std.c.getenv("PARDES_NOTIME")) |v| try gpa.dupeSentinel(u8, std.mem.span(v), 0) else null;
defer if (was) |v| gpa.free(v);
defer _ = if (was) |v| Shell.setenv("PARDES_NOTIME", v, 1) else @import("dev").host_io.testUnsetenv("PARDES_NOTIME");
- const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, .{ .vtable = &Stamping.vtable }, false);
+ const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, .{ .vtable = &Stamping.vtable });
defer a.deinit();
Stamping.core = a.core;
const r = try joinedFresh(a);
@@ -8082,9 +7195,9 @@ test "a client joined from a dump takes a 9P pty/run in a shell as the session d
fn write(_: ?*anyopaque, _: pardes.Pane.Id, _: []const u8) void {}
const vtable: pardes.Host.VTable = .{ .watched = TestHost.watched, .tty_taken = taken, .pty_write = write };
};
- const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .boot = .tty }, .{ .vtable = &RunHost.vtable }, false);
+ const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .boot = .tty }, .{ .vtable = &RunHost.vtable });
defer a.deinit();
- const r = try Replica.init(gpa, 1, try a.unit(0, 0), false);
+ const r = try Replica.init(gpa, 1, try a.unit(0, 0));
defer r.deinit();
const shell: u8 = for (a.core.panes, 0..) |slot, id| {
if (slot) |pane| if (pane.isTerminal()) break @intCast(id);
@@ -8107,7 +7220,6 @@ test "a client joined from a dump takes a 9P pty/run in a shell as the session d
r.confirm(joined.unit);
const late = try Replica.initDump(gpa, 2, joined.view, joined.dump, .{ .cols = 80, .rows = 24 });
defer late.deinit();
- late.t.screen_state = false;
late.core().echo = null;
try std.testing.expectEqual(joined.digest, late.digest());
const node = pardes.ctlfs.Node.of(a.core.panes[shell].?.serial, .pty_run);
@@ -8146,158 +7258,6 @@ test "a client joined from a dump takes a 9P pty/run in a shell as the session d
try agrees(a, late);
}
-// The same run with the terminals crossing as screen state (a session's
-// clients', until the switch to bytes): a replica's emulator is the
-// deltas', its marks not the session's.
-test "a client of screen-state terminals takes a 9P pty/run in a shell as the session does" {
- if (pardes.Term.ops == null) return error.SkipZigTest; // a shell
- const gpa = std.testing.allocator;
- const RunHost = struct {
- fn taken(_: ?*anyopaque, _: pardes.Pane.Id) bool {
- return false;
- }
- fn write(_: ?*anyopaque, _: pardes.Pane.Id, _: []const u8) void {}
- const vtable: pardes.Host.VTable = .{ .watched = TestHost.watched, .tty_taken = taken, .pty_write = write };
- };
- const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .boot = .tty }, .{ .vtable = &RunHost.vtable }, true);
- defer a.deinit();
- var screens: Screens = .init(gpa);
- defer screens.deinit(a.core);
- const peer = try screens.addPeer();
- const r = try Replica.init(gpa, 1, try a.unit(0, 0), true);
- defer r.deinit();
- const shell: u8 = for (a.core.panes, 0..) |slot, id| {
- if (slot) |pane| if (pane.isTerminal()) break @intCast(id);
- } else return error.NoShell;
- const Step = struct {
- var second: ?*Replica = null;
- fn take(s: *Authority, sc: *Screens, p: u16, x: *Replica, u: []const u8) !void {
- const gpa_ = std.testing.allocator;
- const kept = try gpa_.dupe(u8, u);
- defer gpa_.free(kept);
- // The unit first, its screens at the frame after (Peers).
- x.confirm(kept);
- x.settle();
- if (second) |y| {
- y.confirm(kept);
- y.settle();
- }
- try deliver(s, sc, p, x, .flush);
- if (second) |y| try deliver(s, sc, p + 1, y, .flush);
- }
- fn serve(s: *Authority, sc: *Screens, p: u16, x: *Replica, req: pardes.ctlfs.Req) !pardes.ctlfs.Reply {
- const was = Stepping.begin(&s.t, null);
- const reply = s.core.serveFs(req);
- s.core.pump(s.host) catch {};
- was.end();
- s.seq += 1;
- try take(s, sc, p, x, try s.unit(0, s.seq));
- return reply;
- }
- fn output(s: *Authority, sc: *Screens, p: u16, x: *Replica, pane: u8, bytes: []const u8) !void {
- s.output(.{ .output = .{ .pane = .at(pane), .bytes = bytes } });
- try take(s, sc, p, x, (try s.pending()).?);
- }
- };
- const prompt = "\x1b]133;A;cl=line;aid=pardes\x07$ \x1b]133;B;aid=pardes\x07";
- try Step.output(a, &screens, peer, r, shell, prompt ++ "ls\r\n\x1b]133;C;aid=pardes\x07a b\r\n\x1b]133;D;0;aid=pardes\x07" ++ prompt);
- // A second client joins now, from the session's dump.
- const joined = (try a.join(2, null)).?;
- defer gpa.free(joined.dump);
- try Step.take(a, &screens, peer, r, joined.unit);
- const late = try Replica.initDump(gpa, 2, joined.view, joined.dump, .{ .cols = 80, .rows = 24 });
- defer late.deinit();
- const peer2 = try screens.addPeer();
- try deliver(a, &screens, peer2, late, .flush);
- Step.second = late;
- defer Step.second = null;
- const node = pardes.ctlfs.Node.of(a.core.panes[shell].?.serial, .pty_run);
- for (0..2) |_| {
- const h = (try Step.serve(a, &screens, peer, r, .{ .tag = 1, .op = .open, .node = node, .omode = 2 })).handle;
- _ = try Step.serve(a, &screens, peer, r, .{ .tag = 2, .op = .write, .node = node, .handle = h, .data = "true\n" });
- try Step.output(a, &screens, peer, r, shell, "true\r\n\x1b]133;C;aid=pardes\x07\x1b]133;D;0;aid=pardes\x07" ++ prompt);
- const answer = try Step.serve(a, &screens, peer, r, .{ .tag = 3, .op = .read, .node = node, .handle = h, .size = 64 });
- try std.testing.expectEqualStrings("exit 0\n", a.core.fsPayload(answer));
- _ = try Step.serve(a, &screens, peer, r, .{ .tag = 4, .op = .release, .node = node, .handle = h, .opened = true });
- }
- try agrees(a, r);
- try agrees(a, late);
-}
-
-// daemon.py --clients' client C (2026-11-20): idle, a copy taken ahead; the
-// session's script opens pty/run and its command prints, replayed over the
-// copy and kept; the client types into the shell, its speculation stops at
-// the pty write, and the rollback replays the open again over a record the
-// copy never held (it holds the opens as far as `opens_len`), whose line
-// and output the epoch had freed: freed again there, the client's C heap
-// was corrupt.
-test "a 9P open the session made over a copy taken ahead, replayed after a rollback: the record past the opens the copy holds is written over, never freed again" {
- if (pardes.Term.ops == null) return error.SkipZigTest; // a shell
- const gpa = std.testing.allocator;
- const RunHost = struct {
- fn taken(_: ?*anyopaque, _: pardes.Pane.Id) bool {
- return false;
- }
- fn write(_: ?*anyopaque, _: pardes.Pane.Id, _: []const u8) void {}
- const vtable: pardes.Host.VTable = .{ .watched = TestHost.watched, .tty_taken = taken, .pty_write = write };
- };
- const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .boot = .tty }, .{ .vtable = &RunHost.vtable }, true);
- defer a.deinit();
- var screens: Screens = .init(gpa);
- defer screens.deinit(a.core);
- const peer = try screens.addPeer();
- const r = try Replica.init(gpa, 1, try a.unit(0, 0), true);
- defer r.deinit();
- const shell: u8 = for (a.core.panes, 0..) |slot, id| {
- if (slot) |pane| if (pane.isTerminal()) break @intCast(id);
- } else return error.NoShell;
- const prompt = "\x1b]133;A;cl=line;aid=pardes\x07$ \x1b]133;B;aid=pardes\x07";
- a.output(.{ .output = .{ .pane = .at(shell), .bytes = prompt } });
- r.confirm((try a.pending()).?);
- try deliver(a, &screens, peer, r, .flush);
- r.ready();
- try std.testing.expect(r.copy.held and r.core().fs.opens_len == 0);
- const node = pardes.ctlfs.Node.of(a.core.panes[shell].?.serial, .pty_run);
- const Serve = struct {
- fn serve(s: *Authority, x: *Replica, req: pardes.ctlfs.Req) !pardes.ctlfs.Reply {
- const was = Stepping.begin(&s.t, null);
- const reply = s.core.serveFs(req);
- s.core.pump(s.host) catch {};
- was.end();
- s.seq += 1;
- const u = try std.testing.allocator.dupe(u8, try s.unit(0, s.seq));
- defer std.testing.allocator.free(u);
- x.confirm(u);
- x.settle();
- return reply;
- }
- };
- const h = (try Serve.serve(a, r, .{ .tag = 1, .op = .open, .node = node, .omode = 2 })).handle;
- _ = try Serve.serve(a, r, .{ .tag = 2, .op = .write, .node = node, .handle = h, .data = "echo x\n" });
- a.output(.{ .output = .{ .pane = .at(shell), .bytes = "echo x\r\n\x1b]133;C;aid=pardes\x07x\r\n\x1b]133;D;0;aid=pardes\x07" ++ prompt } });
- r.confirm((try a.pending()).?);
- r.settle();
- // Kept over the copy: the record past its opens holds the run's output.
- try std.testing.expect(r.copy.held and r.since.items.len > 0);
- try std.testing.expectEqualStrings("x\n", r.core().fs.opens[h - 1].what.run.output);
- var sent: std.ArrayListUnmanaged([]u8) = .empty;
- defer {
- for (sent.items) |m| gpa.free(m);
- sent.deinit(gpa);
- }
- // A key into the shell: its speculation stops at the pty write, and
- // the copy is put back, the units since replayed (the open again).
- try key(r, 'e', &sent);
- try std.testing.expect(r.applied == 0 and r.stats.stopped > 0);
- r.confirm(try a.take(sent.items[0]));
- r.settle();
- try deliver(a, &screens, peer, r, .flush);
- _ = try Serve.serve(a, r, .{ .tag = 3, .op = .release, .node = node, .handle = h, .opened = true });
- if (r.diverged) |why| std.debug.print("diverged: {s}\n", .{why});
- try std.testing.expect(r.diverged == null and r.quiet());
- try agrees(a, r);
-}
-
test "a script's half line held over a copy taken ahead, its next write run and its rest moved to the front in place, put back by a rollback: the line replayed is the session's" {
var n = try NinepJoin.init("one\n", TestHost.host());
defer n.deinit();
@@ -8341,7 +7301,7 @@ test "a far client's Del with panes above and below is applied at once, and its
}
const vtable: pardes.Host.VTable = .{ .watched = TestHost.watched, .now = now };
};
- const a = try Authority.init(gpa, .{ .cols = 80, .rows = 30, .file = "mise.toml" }, .{ .vtable = &Clocked.vtable }, false);
+ const a = try Authority.init(gpa, .{ .cols = 80, .rows = 30, .file = "mise.toml" }, .{ .vtable = &Clocked.vtable });
defer a.deinit();
_ = try a.local(.{ .command = "New" });
const mid = a.core.view().active;
@@ -8393,7 +7353,7 @@ const NinepJoin = struct {
serial: u32,
fn init(text: []const u8, host: pardes.Host) !NinepJoin {
- const a = try Authority.init(std.testing.allocator, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, host, false);
+ const a = try Authority.init(std.testing.allocator, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, host);
errdefer a.deinit();
const was = Stepping.begin(&a.t, null);
const pane = try a.core.setTestFile(text);
@@ -8445,7 +7405,6 @@ const NinepJoin = struct {
const joined = (try n.a.join(1, null)).?;
defer std.testing.allocator.free(joined.dump);
const r = try Replica.initDump(std.testing.allocator, 1, joined.view, joined.dump, .{ .cols = 80, .rows = 24 });
- r.t.screen_state = false;
r.core().echo = null;
n.late = r;
try std.testing.expectEqual(joined.digest, r.digest());
@@ -8691,7 +7650,7 @@ const RunJoin = struct {
/// The session at its shell's first prompt, and the shell's slot.
fn init(n: *NinepJoin) !u8 {
- const a = try Authority.init(std.testing.allocator, .{ .cols = 80, .rows = 24, .boot = .tty }, .{ .vtable = &vtable }, false);
+ const a = try Authority.init(std.testing.allocator, .{ .cols = 80, .rows = 24, .boot = .tty }, .{ .vtable = &vtable });
n.* = .{ .a = a, .serial = 0 };
_ = try a.unit(0, 0);
const shell: u8 = for (a.core.panes, 0..) |slot, id| {
diff --git a/core/root.zig b/core/root.zig
index f2c97d35..3cc9a90f 100644
--- a/core/root.zig
+++ b/core/root.zig
@@ -67,6 +67,7 @@ pub const CellPixels = @import("Event.zig").CellPixels;
pub const Event = @import("Event.zig").Event;
/// What goes out (Effect.zig).
pub const PtySignal = @import("Effect.zig").PtySignal;
+pub const PtySize = @import("Effect.zig").PtySize;
pub const WatchMode = @import("Effect.zig").WatchMode;
pub const effect_path_cap = @import("Effect.zig").effect_path_cap;
pub const effect_write_cap = @import("Effect.zig").effect_write_cap;
@@ -644,7 +645,7 @@ const machine_lines = [_]struct { []const u8, usize, []const u8 }{
.{ "ninep/pty.zig", 1, "a 9P exec's shell check (tape.site(.shell))" },
.{ "ninep/screen.zig", 1, "a 9P address's text type" },
.{ "ninep/tree.zig", 1, "the daemon's registry (/sessions, tape.site(.sessions))" },
- .{ "term/terminal.zig", 2, "the emulator's image files (TMPDIR) and its Io: the session's emulator (a client's are written by deltas)" },
+ .{ "term/terminal.zig", 2, "the emulator's image files (TMPDIR) and its Io: each side's emulator, a medium's read taped (Term.media)" },
};
/// The lines of `src` that name the machine (`machine_lines`'s rules).
@@ -739,7 +740,7 @@ const kept_out = [_]struct { []const u8, []const u8, []const u8 }{
.{ "Core.zig", "surface facts frames own_frames chrome frame_arena scratch echo undrawn", "the frame's own and the views drawn here: written by frames (and chrome by a theme's step), read by frames and the runner; no step reads them" },
.{ "Core.zig", "needs_frame", "whether to draw: steps set it, the loop reads it; no step's outcome reads it" },
.{ "Core.zig", "effects effects_head effects_len in_q in_head in_len opts dump_out dump_export tape", "this process's queues, options and tape, drained or set by its host" },
- .{ "Core.zig", "shell_rows", "a terminal's rows as read here, swept at every update; a terminal is in no digest (Term.zig)" },
+ .{ "Core.zig", "shell_rows", "a terminal's rows as read here, swept at every update; the terminal's own digest covers its active area, not its history (Term.zig `calls`)" },
.{ "Core.zig", "diff_output locations_cache tty_filter_palette body_chrome", "caches of pure functions of their key (a text, a theme): a step finds what it would make; a query row's colours from them are out of its digest (locations.Row.digest), and what a step asks a worker to paint is never decided by them (Stream.paintRows)" },
.{ "Core.zig", "retired_panes", "panes torn down this step, freed at its end" },
.{ "Core.zig", "distrusted frames tape", "Options: the client's own list, its runner's statistics, its tape" },
diff --git a/core/tagline.zig b/core/tagline.zig
index 26f83fba..02d1b277 100644
--- a/core/tagline.zig
+++ b/core/tagline.zig
@@ -160,7 +160,7 @@ pub fn pathPrefix(p: *const Pardes, arena: std.mem.Allocator, pane: *Pane) ![]co
if (pane.terminal != null) {
const chosen = pane.term_petscii;
const on = chosen or !p.view().frontend.native_images;
- if (chosen or pane.term_images)
+ if (chosen or pardes.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/core/tape.zig b/core/tape.zig
index f231831d..1cbf8aed 100644
--- a/core/tape.zig
+++ b/core/tape.zig
@@ -140,9 +140,6 @@ pub const Site = enum(u16) {
/// A kitty image's medium as a terminal's emulator read it (a file, a
/// temporary file, shared memory: Term.media), its bytes or its failure.
medium,
- /// Whether a terminal holds a kitty image after its program's output
- /// (Pane.term_images): a screen-state replica's emulator never has one.
- images,
};
/// What the sites return. wire.semantics hashes their shape with the
@@ -311,13 +308,6 @@ pub const Tape = struct {
dump_check: bool = false,
dumps: usize = 0,
dump_bytes: usize = 0,
- /// Screen-state terminals (core/term/screen_state.zig, docs/next-daemon.md
- /// phase 5): an authority recording for replicas, or a replica. A
- /// terminal's emulator is the authority's alone: its output is recorded
- /// without its bytes (they cross as screen state), its pty writes are
- /// not recorded, and no digest covers it. A replica's core never writes
- /// one but by `apply`.
- screen_state: bool = false,
/// The session's (replica.Peers): called between two of its inputs once
/// what it recorded since its last unit passes `unit_max`, to send that
/// as a unit: a pump of a flood's reads is cut into units under it.
@@ -423,12 +413,7 @@ pub const Tape = struct {
t.noteWrites();
t.noteHost(core);
}
- // A terminal's output crosses as screen state, not as its bytes.
- if (t.screen_state and input.* == .update and input.update.args[0] == .output) {
- var bare = input.*;
- bare.update.args[0].output.bytes = &.{};
- t.record(.input, Input, &bare);
- } else t.record(.input, Input, input);
+ t.record(.input, Input, input);
return .{ .tape = t };
}
@@ -806,12 +791,12 @@ pub const Tape = struct {
// output) is the session's answer, kept, and a replica whose
// emulators are fed the same bytes asks its own and compares: a
// check a unit, for nothing (P30: a digest, not state).
- if (comptime s == .positions or s == .prompt) if (!t.screen_state) {
+ if (comptime s == .positions or s == .prompt) {
const mine = @call(.auto, f, full);
t.scratch.clearRetainingCapacity();
walk.encode(R, &mine, &t.scratch.writer) catch @panic("tape: out of memory");
if (!std.mem.eql(u8, t.scratch.written(), t.last_ret.bytes[t.last_ret.at..])) t.diverge("what this replica's terminal told ({t}) is not what the session's did", .{s});
- };
+ }
var ret = t.last_ret;
return walk.decode(R, &ret, a orelse t.arena.allocator()) catch {
t.diverge("the tape's answer to {t} is short", .{s});
@@ -885,17 +870,6 @@ pub const Tape = struct {
return t.depth > 0 or t.replay or t.speculating;
}
- /// A replica's core under screen-state terminals: its emulators are
- /// written by `apply` alone, never by its own steps.
- pub fn screenReplica(t: *const Tape) bool {
- return t.screen_state and (t.replay or t.speculating);
- }
-
- /// An authority recording for screen-state replicas.
- pub fn screenAuthority(t: *const Tape) bool {
- return t.screen_state and !t.replay and !t.speculating;
- }
-
/// What a speculation reached is the authority's (`why`): the input is
/// undone and waits for the authority's order.
pub fn poison(t: *Tape, why: []const u8) void {
@@ -913,14 +887,6 @@ pub const Tape = struct {
return true;
}
- /// A speculation that moves a terminal's view: it may (its rollback
- /// puts the view back, replica.zig `views`); a screen-state replica's
- /// says it did (a delta sets the view again).
- pub fn viewOnly(t: *Tape, comptime _: []const u8) bool {
- if (t.speculating and t.screen_state) t.touched = true;
- return false;
- }
-
/// A speculation read a terminal's rows or moved its view (`Tape.touched`).
pub fn touchTerminal(t: *Tape) void {
if (t.speculating) t.touched = true;
@@ -1153,7 +1119,8 @@ fn tagOf(comptime entry: anytype, comptime Made: type) [:0]const u8 {
/// The entries that answer stop by nature: the answer is the session's.
const keeps_stopping = [_]Host.Fn{
// A shell's input: a device by the user's line (a far shell may feel
- // like ssh), and off the tape with screen-state terminals.
+ // like ssh; core/echo.zig predicts its echo), and off the tape outside
+ // a speculation.
.pty_write,
// Its host says into the core on every call that the shell started
// and where (host_io.forkShell: acknowledgeShell, setCwd), and gives
@@ -1197,8 +1164,10 @@ fn hostCall(t: *Tape, p: *const Pardes, comptime f: Host.Fn, args: Host.Args(f))
const R = Host.Ret(f);
const name = @tagName(f);
// A terminal's answers and what is typed at it from its output are the
- // authority's to write, never a replica's: off the tape on both sides.
- if (comptime std.mem.eql(u8, name, "pty_write")) if (t.screen_state and !t.speculating) {
+ // authority's to write, never a replica's: off the tape on both sides
+ // (a replica's replay of the step writes nothing, and checks nothing:
+ // a write returns nothing a step reads).
+ if (comptime std.mem.eql(u8, name, "pty_write")) if (!t.speculating) {
if (!t.replay) _ = p.host.call(f, args);
return;
};
@@ -1353,19 +1322,6 @@ pub fn stepping() bool {
return (on orelse &none).stepping();
}
-/// Screen-state terminals, on either side (`Tape.screen_state`).
-pub fn screenState() bool {
- return (on orelse &none).screen_state;
-}
-
-pub fn screenReplica() bool {
- return (on orelse &none).screenReplica();
-}
-
-pub fn screenAuthority() bool {
- return (on orelse &none).screenAuthority();
-}
-
pub fn poison(why: []const u8) void {
(on orelse &none).poison(why);
}
@@ -1380,10 +1336,6 @@ pub fn authorityOnly(comptime why: []const u8) bool {
return (on orelse &none).authorityOnly(why);
}
-pub fn viewOnly(comptime why: []const u8) bool {
- return (on orelse &none).viewOnly(why);
-}
-
pub fn touchTerminal() void {
(on orelse &none).touchTerminal();
}
@@ -1832,11 +1784,11 @@ test "a core pumped twice with one host and once with another: which functions i
const R = pardes.replica;
var first: Pumped = .{ .ns = 0 };
var second: Pumped = .{ .ns = 1 << 40 };
- const a = try R.Authority.init(gpa, .{ .cols = 80, .rows = 24 }, .{ .ctx = &first, .vtable = &Pumped.one }, false);
+ const a = try R.Authority.init(gpa, .{ .cols = 80, .rows = 24 }, .{ .ctx = &first, .vtable = &Pumped.one });
defer a.deinit();
const boot = Pumped.said(a.t.buf.items);
try std.testing.expectEqual(Host.mask(.{ .vtable = &Pumped.one }), boot.mask);
- const r = try R.Replica.init(gpa, 1, try a.unit(0, 0), false);
+ const r = try R.Replica.init(gpa, 1, try a.unit(0, 0));
defer r.deinit();
const hosts = [_]Host{ .{ .ctx = &first, .vtable = &Pumped.one }, .{ .ctx = &second, .vtable = &Pumped.more } };
for (hosts, [_]usize{ 0, 1 }, 1..) |h, sets, seq| {
diff --git a/core/term/screen_state.zig b/core/term/screen_state.zig
deleted file mode 100644
index ec72a841..00000000
--- a/core/term/screen_state.zig
+++ /dev/null
@@ -1,1213 +0,0 @@
-//! Screen-state terminals (docs/next-daemon.md, "Terminals cross as
-//! authoritative screen state", phase 5). A replica is sent a terminal's
-//! state, never its pty's bytes, so a `cat` of a gigabyte costs it screens.
-//!
-//! The authority encodes a delta for one peer: a header (the cursor, the
-//! active area's first row as an absolute row, the history's extent), the
-//! content address of the terminal-wide state, the content address of each
-//! row of the active area, and the blobs behind the addresses the peer does
-//! not hold. Both kinds of blob are ghostty's own snapshot records, so they
-//! cross exactly: the terminal-wide state is a TERMINAL record (modes,
-//! colours, title, tab stops...), and a row is the PAGE record of a one-row
-//! page (its styles, graphemes, hyperlinks, wide cells, wrap and prompt
-//! marks). A row's address is a hash of what the row shows, not of its blob,
-//! whose style ids are its source page's. An unchanged row costs 8 bytes.
-//!
-//! Each state the authority sends is a version of its terminal (`Track`),
-//! made once whatever the number of peers. A peer's next delta is against
-//! the version it was last sent: the stream is ordered and loses nothing,
-//! so the peer has that one by the time it applies the next. Several are
-//! in flight (`bound`); acknowledgements free their room, and a peer at the
-//! bound gets nothing until one comes, then the newest version, the ones
-//! between skipped. Peers at the same base are sent the same bytes. A
-//! replica holds the blobs of the state it applied last and no others; a
-//! delta against another (one lost) is refused, and the peer started afresh.
-//!
-//! The replica writes each delta into a ghostty Terminal, which a replica's
-//! terminal pane draws as a local one (core/term/terminal.zig reads only that).
-//! Rows that scroll off its active area go into its history, made what the
-//! authority's are by the delta's tail (their addresses, up to a screen of
-//! them). Older ones it never saw, or saw before they last changed, are
-//! holes there, fetched by absolute row on demand (`encodeRows`,
-//! `applyRows`).
-const std = @import("std");
-const vt = @import("ghostty-vt");
-const plain = @import("plain");
-const snapshot = vt.snapshot;
-pub const Terminal = vt.Terminal;
-const Page = vt.page.Page;
-const Row = vt.page.Row;
-const Pin = vt.Pin;
-const Screen = vt.Screen;
-
-// ponytail: 64 bits: two of a million distinct rows collide about once in
-// 4*10^7 sessions; phase 6's cache, shared across sessions, wants 128.
-pub const Hash = u64;
-
-/// What a row shows, hashed: its wrap and prompt flags, and each of its
-/// first `cols` cells up to the last one that is not blank, with its style,
-/// grapheme and hyperlink by value. Not the page's style or hyperlink ids,
-/// nor its derived flags. Its width is in it: a blob is a row that wide.
-/// (A page can be wider than its terminal: ghostty narrows them lazily.)
-pub fn rowHash(page: *Page, row: *Row, cols: u16) Hash {
- var h = std.hash.Wyhash.init(0);
- h.update(&.{rowFlags(row)});
- h.update(std.mem.asBytes(&cols));
- const all = page.getCells(row);
- const cells = all[0..@min(cols, all.len)];
- var n = cells.len;
- while (n > 0 and @as(u64, @bitCast(cells[n - 1])) == 0) n -= 1;
- for (cells[0..n]) |*c| {
- var word = c.*;
- word.style_id = 0;
- h.update(std.mem.asBytes(&@as(u64, @bitCast(word))));
- if (c.style_id != 0) h.update(std.mem.asBytes(&page.styles.get(page.memory, c.style_id).hash()));
- if (c.hasGrapheme()) h.update(std.mem.sliceAsBytes(page.lookupGrapheme(c).?));
- if (c.hyperlink) if (page.lookupHyperlink(c)) |id|
- h.update(std.mem.asBytes(&page.hyperlink_set.get(page.memory, id).hash(page.memory)));
- }
- return h.final();
-}
-
-fn rowFlags(row: *const Row) u8 {
- return @as(u8, @intFromBool(row.wrap)) | @as(u8, @intFromBool(row.wrap_continuation)) << 1 |
- @as(u8, @backingInt(row.semantic_prompt)) << 2;
-}
-
-/// The authority's absolute row numbers for one terminal: its primary
-/// screen's active area starts at `top`, and a row `d` above it in its
-/// history is `top - d`. Kept by a tracked pin at the last active top, so
-/// it counts the rows scrolled since. A resize renumbers (`epoch`).
-pub const Rows = struct {
- pin: ?*Pin = null,
- top: u64 = 0,
- epoch: u32 = 0,
- cols: u16 = 0,
- rows: u16 = 0,
-
- pub fn update(n: *Rows, t: *Terminal) !void {
- const pages = &t.screens.get(.primary).?.pages;
- const top = pages.getTopLeft(.active);
- const y = pages.pointFromPin(.screen, top).?.screen.y;
- if (n.pin) |p| {
- if (t.cols != n.cols or t.rows != n.rows) n.epoch +%= 1;
- // The last top was pruned away: every row the peer has is
- // older than the oldest row here.
- const was: ?u32 = if (p.garbage) null else if (pages.pointFromPin(.screen, p.*)) |pt| pt.screen.y else null;
- n.top += if (was) |w| y -| w else @as(u64, y) + t.rows;
- // A reflow (a resize to fewer columns) puts more rows above the
- // last top than ever scrolled past it: numbered from here, the
- // history's oldest row is still row 0 or later. A resize
- // renumbers anyway (`epoch`), so no peer holds the old numbers.
- n.top = @max(n.top, y);
- p.* = top;
- } else {
- n.pin = try pages.trackPin(top);
- n.top = y;
- }
- n.cols = t.cols;
- n.rows = t.rows;
- }
-
- pub fn deinit(n: *Rows, t: *Terminal) void {
- if (n.pin) |p| t.screens.get(.primary).?.pages.untrackPin(p);
- n.* = .{};
- }
-
- /// The pin of absolute row `abs`, if the terminal still has it.
- fn pinAt(n: *const Rows, t: *Terminal, abs: u64) ?Pin {
- return pinOf(&t.screens.get(.primary).?.pages, n.top, abs);
- }
-};
-
-fn pinOf(pages: *const vt.PageList, top: u64, abs: u64) ?Pin {
- if (abs >= top) return pages.pin(.{ .active = .{ .y = std.math.cast(u32, abs - top) orelse return null } });
- const d = std.math.cast(usize, top - abs) orelse return null;
- return pages.getTopLeft(.active).up(d);
-}
-
-/// The authority's scratch: a one-row page each blob is copied into
-/// (fresh, so the blob holds that row's styles alone) and encoded from.
-pub const Encoder = struct {
- gpa: std.mem.Allocator,
- scratch: ?Page = null,
- blob: std.Io.Writer.Allocating,
- /// The rows a delta sends a blob for, and the addresses it lists once.
- needed: std.ArrayList(struct { pin: Pin, hash: Hash }) = .empty,
- listed: std.AutoHashMapUnmanaged(Hash, void) = .empty,
- tail: std.ArrayList(Pin) = .empty,
-
- pub fn init(gpa: std.mem.Allocator) Encoder {
- return .{ .gpa = gpa, .blob = .init(gpa) };
- }
-
- pub fn deinit(e: *Encoder) void {
- if (e.scratch) |*s| s.deinit();
- e.blob.deinit();
- e.needed.deinit(e.gpa);
- e.listed.deinit(e.gpa);
- e.tail.deinit(e.gpa);
- }
-
- /// The PAGE record of `row` alone, its first `cols` cells.
- fn rowBlob(e: *Encoder, page: *Page, row: *Row, cols: u16, w: *std.Io.Writer) !void {
- var cap: vt.page.Capacity = if (e.scratch) |s| s.capacity else .{ .cols = cols, .rows = 1, .styles = 64 };
- if (cap.cols != cols) cap = .{ .cols = cols, .rows = 1, .styles = 64 };
- for (0..16) |_| {
- const s = try scratchPage(&e.scratch, cap);
- s.cloneRowFrom(page, s.getRow(0), row) catch {
- // Room for this row: everything doubled until it fits.
- cap.styles *|= 2;
- cap.grapheme_bytes *|= 2;
- cap.hyperlink_bytes *|= 2;
- cap.string_bytes *|= 2;
- continue;
- };
- break;
- } else return error.RowTooBig;
- var rw: snapshot.record.Writer = .init(e.gpa, w);
- defer rw.deinit();
- try snapshot.page.encode(&e.scratch.?, &rw);
- }
-};
-
-/// `slot`'s one-row scratch page, ready for `cap`: reused when it has that
-/// capacity, else made again.
-fn scratchPage(slot: *?Page, cap: vt.page.Capacity) !*Page {
- if (slot.*) |*s| {
- if (std.meta.eql(s.capacity, cap)) {
- s.reinit();
- return s;
- }
- s.deinit();
- slot.* = null;
- }
- slot.* = try Page.init(cap);
- return &slot.*.?;
-}
-
-/// Holes older than a history's oldest row are gone with it.
-fn clampHoles(holes: *std.ArrayList([2]u64), oldest: u64) void {
- var i: usize = 0;
- while (i < holes.items.len) {
- const hole = &holes.items[i];
- hole[0] = @max(hole[0], oldest);
- if (hole[0] >= hole[1]) _ = holes.orderedRemove(i) else i += 1;
- }
-}
-
-/// Deltas a peer may have in flight. At 207 ms and 60 frames a second about
-/// 13 are; past the bound a peer gets nothing until an acknowledgement, and
-/// then the newest state, the ones between skipped.
-pub const bound = plain.term.flight_bound;
-
-/// What a peer holds once it has a version: the addresses of its active
-/// rows and its meta. A delta against it sends no blob for these.
-const Known = struct {
- version: u32,
- epoch: u32,
- top: u64,
- addrs: std.AutoHashMapUnmanaged(Hash, void) = .empty,
-};
-
-/// One terminal as the authority numbers it, for all of its peers: each
-/// state it sends is a version, made once whatever the number of peers.
-pub const Track = struct {
- rows: Rows = .{},
- version: u32 = 0,
- /// The emulator's change count the newest version was made at, and its
- /// history's rows.
- changes: u32 = 0,
- history: u64 = 0,
- /// The newest version: its active rows (pins, good while the emulator
- /// is unchanged) and their addresses, and its meta.
- pins: std.ArrayList(Pin) = .empty,
- hashes: std.ArrayList(Hash) = .empty,
- meta: std.Io.Writer.Allocating,
- meta_hash: Hash = 0,
- /// The newest versions, oldest first: the bases a peer's next delta may
- /// have. A peer whose base has gone starts afresh.
- known: std.ArrayList(Known) = .empty,
- /// The last delta encoded, for the next peer at the same base.
- cache: std.Io.Writer.Allocating,
- cache_base: u32 = 0,
- cache_version: u32 = 0,
-
- const kept = bound + 8;
-
- pub fn init(gpa: std.mem.Allocator) Track {
- return .{ .meta = .init(gpa), .cache = .init(gpa) };
- }
-
- /// `t` is the terminal, or null when it is gone already (with its pins).
- pub fn deinit(tr: *Track, gpa: std.mem.Allocator, t: ?*Terminal) void {
- if (t) |term| tr.rows.deinit(term);
- tr.pins.deinit(gpa);
- tr.hashes.deinit(gpa);
- tr.meta.deinit();
- for (tr.known.items) |*k| k.addrs.deinit(gpa);
- tr.known.deinit(gpa);
- tr.cache.deinit();
- }
-
- fn find(tr: *const Track, version: u32) ?*const Known {
- if (version == 0) return null;
- for (tr.known.items) |*k| if (k.version == version) return if (k.epoch == tr.rows.epoch) k else null;
- return null;
- }
-
- /// A version of `t` as it is now.
- fn advance(tr: *Track, gpa: std.mem.Allocator, t: *Terminal, changes: u32) !void {
- try tr.rows.update(t);
- tr.version +%= 1;
- if (tr.version == 0) tr.version = 1;
- tr.changes = changes;
- const primary = &t.screens.get(.primary).?.pages;
- tr.history = primary.total_rows - primary.rows;
- tr.meta.clearRetainingCapacity();
- {
- var rw: snapshot.record.Writer = .init(gpa, &tr.meta.writer);
- defer rw.deinit();
- try snapshot.terminal.encode(t, &rw);
- }
- tr.meta_hash = std.hash.Wyhash.hash(0, tr.meta.written());
- tr.pins.clearRetainingCapacity();
- tr.hashes.clearRetainingCapacity();
- var it = t.screens.active.pages.rowIterator(.right_down, .{ .active = .{} }, null);
- while (it.next()) |p| {
- try tr.pins.append(gpa, p);
- try tr.hashes.append(gpa, rowHash(p.node.page(), p.rowAndCell().row, t.cols));
- }
- if (tr.known.items.len == kept) {
- tr.known.items[0].addrs.deinit(gpa);
- _ = tr.known.orderedRemove(0);
- }
- var k: Known = .{ .version = tr.version, .epoch = tr.rows.epoch, .top = tr.rows.top };
- errdefer k.addrs.deinit(gpa);
- try k.addrs.ensureTotalCapacity(gpa, @intCast(tr.hashes.items.len + 1));
- for (tr.hashes.items) |h| k.addrs.putAssumeCapacity(h, {});
- k.addrs.putAssumeCapacity(tr.meta_hash, {});
- try tr.known.append(gpa, k);
- }
-};
-
-/// What the authority knows of one peer of one terminal: a plain record
-/// both sides name (abi/term.zig), the core keeping one a peer.
-pub const Peer = plain.term.Peer;
-
-/// Its replica's holes once it applies a delta to `tr`'s newest version
-/// against `base`, as Replica.apply makes them.
-fn noteSent(peer: *Peer, gpa: std.mem.Allocator, tr: *const Track, base: ?*const Known, rows: u16) !void {
- const top = tr.rows.top;
- const history = tr.history;
- if (base) |b| {
- if (top > peer.top) {
- const tail = @min(top -| b.top, rows, history);
- if (top - peer.top >= @as(u64, rows) + history) {
- peer.holes.clearRetainingCapacity();
- if (history > tail) try peer.holes.append(gpa, .{ top - history, top - tail });
- } else if (top - tail > peer.top) try peer.holes.append(gpa, .{ peer.top, top - tail });
- }
- } else {
- peer.holes.clearRetainingCapacity();
- if (history > 0) try peer.holes.append(gpa, .{ top - history, top });
- }
- peer.top = top;
- clampHoles(&peer.holes, top -| history);
-}
-
-/// The delta's fixed header: u32 seq, u32 base (0: none, the replica
-/// starts afresh), u8 flags, u32 epoch, u64 meta, u16 cursor x and y, u8
-/// cursor style, u8 pending wrap, u8 the cursor's semantic content, the
-/// kitty keyboard flags, u64 top, u64 history rows, u64 the viewport's top
-/// as an absolute row (all ones: following the active area), u16 and the
-/// caller's extra bytes; then u16 rows and a u64 per active row, u16 and a
-/// u64 per row of the tail (those that scrolled off the active area since
-/// the base, up to a screen of them, oldest first), and a u16 blob count
-/// and each blob as u64 hash, u32 length, bytes.
-const flag_reset: u8 = 1;
-const KittyFlags = @FieldType(Screen, "kitty_keyboard");
-const following = std.math.maxInt(u64);
-
-/// The delta that takes `peer` from what it was last sent to `t` as it is,
-/// onto `out`; false (nothing written) when it has that already, or has
-/// `bound` in flight. `changes` counts the emulator's writes (a new count
-/// is a new version); `extra` rides along (the caller's own state of the
-/// terminal), the same for every peer of one version. A peer at the same
-/// base as the last one encoded is sent the same bytes.
-pub fn encode(e: *Encoder, tr: *Track, peer: *Peer, t: *Terminal, changes: u32, extra: []const u8, out: *std.Io.Writer) !bool {
- if (tr.version == 0 or changes != tr.changes) try tr.advance(e.gpa, t, changes);
- if (peer.sent == tr.version or peer.n == bound) return false;
- const base = tr.find(peer.sent);
- const base_version = if (base) |b| b.version else 0;
- if (tr.cache_version != tr.version or tr.cache_base != base_version) {
- tr.cache.clearRetainingCapacity();
- try write(e, tr, base, t, extra, &tr.cache.writer);
- tr.cache_version = tr.version;
- tr.cache_base = base_version;
- }
- try out.writeAll(tr.cache.written());
- try noteSent(peer, e.gpa, tr, base, t.rows);
- peer.sent = tr.version;
- peer.flight[peer.n] = tr.version;
- peer.n += 1;
- return true;
-}
-
-fn write(e: *Encoder, tr: *Track, base: ?*const Known, t: *Terminal, extra: []const u8, out: *std.Io.Writer) !void {
- const gpa = e.gpa;
- const reset = base == null;
- const screen = t.screens.active;
- const pages = &t.screens.get(.primary).?.pages;
- const history = pages.total_rows - pages.rows;
- const top = tr.rows.top;
- try out.writeInt(u32, tr.version, .little);
- try out.writeInt(u32, if (base) |b| b.version else 0, .little);
- try out.writeByte(if (reset) flag_reset else 0);
- try out.writeInt(u32, tr.rows.epoch, .little);
- try out.writeInt(u64, tr.meta_hash, .little);
- try out.writeInt(u16, screen.cursor.x, .little);
- try out.writeInt(u16, screen.cursor.y, .little);
- try out.writeByte(@backingInt(screen.cursor.cursor_style));
- try out.writeByte(@intFromBool(screen.cursor.pending_wrap));
- try out.writeByte(@backingInt(screen.cursor.semantic_content));
- // ponytail: raw bytes, as the hello refuses a peer of another build.
- try out.writeAll(std.mem.asBytes(&screen.kitty_keyboard));
- try out.writeInt(u64, top, .little);
- try out.writeInt(u64, history, .little);
- try out.writeInt(u64, if (pages.viewport == .active) following else top - history + pages.scrollbar().offset, .little);
- try out.writeInt(u16, @intCast(extra.len), .little);
- try out.writeAll(extra);
-
- // The active rows, then the tail: what scrolled off since the base,
- // which may have changed after it was sent.
- e.listed.clearRetainingCapacity();
- e.needed.clearRetainingCapacity();
- const tail: u16 = if (base) |b| @intCast(@min(top -| b.top, t.rows, history)) else 0;
- e.tail.clearRetainingCapacity();
- for (0..tail) |j| try e.tail.append(gpa, pages.getTopLeft(.active).up(tail - j).?);
- try out.writeInt(u16, @intCast(tr.pins.items.len), .little);
- for (tr.pins.items, tr.hashes.items) |p, h| {
- try out.writeInt(u64, h, .little);
- try needBlob(e, base, p, h);
- }
- try out.writeInt(u16, tail, .little);
- for (e.tail.items) |p| {
- const h = rowHash(p.node.page(), p.rowAndCell().row, t.cols);
- try out.writeInt(u64, h, .little);
- try needBlob(e, base, p, h);
- }
- const meta_new = if (base) |b| !b.addrs.contains(tr.meta_hash) else true;
- try out.writeInt(u16, @intCast(e.needed.items.len + @intFromBool(meta_new)), .little);
- if (meta_new) {
- try out.writeInt(u64, tr.meta_hash, .little);
- try out.writeInt(u32, @intCast(tr.meta.written().len), .little);
- try out.writeAll(tr.meta.written());
- }
- for (e.needed.items) |need| {
- e.blob.clearRetainingCapacity();
- try e.rowBlob(need.pin.node.page(), need.pin.rowAndCell().row, t.cols, &e.blob.writer);
- try out.writeInt(u64, need.hash, .little);
- try out.writeInt(u32, @intCast(e.blob.written().len), .little);
- try out.writeAll(e.blob.written());
- }
-}
-
-/// A blob goes for an address the base does not hold, once.
-fn needBlob(e: *Encoder, base: ?*const Known, p: Pin, h: Hash) !void {
- if ((try e.listed.getOrPut(e.gpa, h)).found_existing) return;
- if (base) |b| if (b.addrs.contains(h)) return;
- try e.needed.append(e.gpa, .{ .pin = p, .hash = h });
-}
-
-/// The primary screen's rows `[lo, hi)` the authority still has, for a
-/// replica that holds them as holes: u32 epoch, u32 blobs, each u64 hash,
-/// u32 length, bytes, then u32 rows, each u64 row and u64 hash. A blob goes
-/// once a message (a flood's rows are one).
-// ponytail: blobs once a message, not once a peer: phase 6's content cache.
-pub fn encodeRows(e: *Encoder, tr: *Track, t: *Terminal, lo: u64, hi: u64, out: *std.Io.Writer) !void {
- try tr.rows.update(t);
- var blobs: std.Io.Writer.Allocating = .init(e.gpa);
- defer blobs.deinit();
- var rows: std.Io.Writer.Allocating = .init(e.gpa);
- defer rows.deinit();
- e.listed.clearRetainingCapacity();
- var nblobs: u32 = 0;
- var nrows: u32 = 0;
- var abs = lo;
- // The active area is the deltas'.
- while (abs < @min(hi, tr.rows.top)) : (abs += 1) {
- const p = tr.rows.pinAt(t, abs) orelse continue;
- const h = rowHash(p.node.page(), p.rowAndCell().row, t.cols);
- try rows.writer.writeInt(u64, abs, .little);
- try rows.writer.writeInt(u64, h, .little);
- nrows += 1;
- if ((try e.listed.getOrPut(e.gpa, h)).found_existing) continue;
- e.blob.clearRetainingCapacity();
- try e.rowBlob(p.node.page(), p.rowAndCell().row, t.cols, &e.blob.writer);
- try blobs.writer.writeInt(u64, h, .little);
- try blobs.writer.writeInt(u32, @intCast(e.blob.written().len), .little);
- try blobs.writer.writeAll(e.blob.written());
- nblobs += 1;
- }
- try out.writeInt(u32, tr.rows.epoch, .little);
- try out.writeInt(u32, nblobs, .little);
- try out.writeAll(blobs.written());
- try out.writeInt(u32, nrows, .little);
- try out.writeAll(rows.written());
-}
-
-/// A replica's terminal: what it was sent, written into a ghostty Terminal.
-pub const Replica = struct {
- seq: u32 = 0,
- epoch: u32 = 0,
- meta: Hash = 0,
- top: u64 = 0,
- /// The address of each active row as the Terminal holds it, a list per
- /// screen (primary, alternate).
- held: [2]std.ArrayList(Hash) = .{ .empty, .empty },
- /// The blobs of the last state applied: what the authority takes it to
- /// hold. Owned copies.
- blobs: std.AutoHashMapUnmanaged(Hash, []u8) = .empty,
- /// History rows it cannot vouch for (written blank, or seen before
- /// they last changed), `[lo, hi)` absolute, oldest first.
- holes: std.ArrayList([2]u64) = .empty,
- /// The one-row page each row blob is decoded into.
- scratch: ?Page = null,
-
- pub fn deinit(r: *Replica, gpa: std.mem.Allocator) void {
- for (&r.held) |*h| h.deinit(gpa);
- var it = r.blobs.valueIterator();
- while (it.next()) |b| gpa.free(b.*);
- r.blobs.deinit(gpa);
- r.holes.deinit(gpa);
- if (r.scratch) |*s| s.deinit();
- }
-
- pub const Applied = plain.term.Applied;
-
- /// Write one delta into `t`: the seq to acknowledge, and the caller's
- /// extra bytes (borrowed from `bytes`). error.BaseMismatch: the delta
- /// is against a state this replica does not have (one was lost, or it
- /// started afresh), so `t` is as it was and it must be sent a reset.
- pub fn apply(r: *Replica, gpa: std.mem.Allocator, io: std.Io, t: *Terminal, bytes: []const u8) !Applied {
- var in: std.Io.Reader = .fixed(bytes);
- const seq = try in.takeInt(u32, .little);
- const base = try in.takeInt(u32, .little);
- const flags = try in.takeByte();
- const reset = flags & flag_reset != 0;
- if (!reset and base != r.seq) return error.BaseMismatch;
- const epoch = try in.takeInt(u32, .little);
- const meta = try in.takeInt(u64, .little);
- const cx = try in.takeInt(u16, .little);
- const cy = try in.takeInt(u16, .little);
- const style = try in.takeByte();
- const wrap = try in.takeByte();
- const semantic = try in.takeByte();
- var kitty: KittyFlags = undefined;
- @memcpy(std.mem.asBytes(&kitty), try in.take(@sizeOf(KittyFlags)));
- const top = try in.takeInt(u64, .little);
- const history = try in.takeInt(u64, .little);
- const viewport = try in.takeInt(u64, .little);
- const extra = try in.take(try in.takeInt(u16, .little));
- const nrows = try in.takeInt(u16, .little);
- const hashes = try in.take(@as(usize, nrows) * 8);
- const tail = try in.takeInt(u16, .little);
- const tails = try in.take(@as(usize, tail) * 8);
- // The delta's blobs, borrowed from `bytes` while it applies.
- var fresh: std.AutoHashMapUnmanaged(Hash, []const u8) = .empty;
- defer fresh.deinit(gpa);
- for (0..try in.takeInt(u16, .little)) |_| {
- const h = try in.takeInt(u64, .little);
- try fresh.put(gpa, h, try in.take(try in.takeInt(u32, .little)));
- }
- const blobOf = struct {
- fn of(rr: *Replica, f: *const std.AutoHashMapUnmanaged(Hash, []const u8), h: Hash) ![]const u8 {
- if (f.get(h)) |b| return b;
- if (rr.blobs.get(h)) |b| return b;
- return error.MissingBlob;
- }
- }.of;
-
- if (reset or meta != r.meta) {
- var reader: std.Io.Reader = .fixed(try blobOf(r, &fresh, meta));
- var next = try snapshot.terminal.decode(&reader, try snapshot.record.nextHeader(&reader), io, gpa);
- if (reset) {
- std.mem.swap(Terminal, t, &next);
- next.deinit(gpa);
- for (&r.held) |*h| h.clearRetainingCapacity();
- r.holes.clearRetainingCapacity();
- r.top = top;
- r.epoch = epoch;
- // The authority's history, blank, to be fetched. Its own
- // limit is the authority's row count (below), not bytes:
- // its pages may pack rows otherwise.
- const primary = t.screens.get(.primary).?;
- primary.pages.setMaxBytes(null);
- try scrollUp(primary, history);
- if (history > 0) try r.holes.append(gpa, .{ top -| history, top });
- } else {
- defer next.deinit(gpa);
- try takeMeta(t, &next, io, gpa);
- }
- r.meta = meta;
- }
- if (epoch != r.epoch) return error.Renumbered;
-
- // The primary screen scrolled `top - r.top` rows since the last
- // delta: as many go up into the history here (no more than its
- // history holds and the screen), each beyond the tail a hole.
- const primary = t.screens.get(.primary).?;
- if (top > r.top) {
- const k = top - r.top;
- const held = &r.held[0];
- if (k >= @as(u64, t.rows) + history) {
- // A flood: nothing held here is in this state. The rows stay
- // where they are, renumbered: the active ones written below,
- // the tail too, the rest holes (blanked when they come into
- // view, `blank`), not grown and trimmed by the thousand. As
- // many more as the history is longer there, grown blank.
- const have = primary.pages.total_rows - primary.pages.rows;
- if (have < history) try scrollUp(primary, history - have);
- held.clearRetainingCapacity();
- try held.appendNTimes(gpa, unknown, t.rows);
- r.holes.clearRetainingCapacity();
- if (history > tail) try r.holes.append(gpa, .{ top - history, top - tail });
- } else {
- try scrollUp(primary, @min(k, @as(u64, t.rows) + history));
- if (k >= held.items.len) held.clearRetainingCapacity() else {
- std.mem.copyForwards(Hash, held.items, held.items[@intCast(k)..]);
- held.shrinkRetainingCapacity(held.items.len - @as(usize, @intCast(k)));
- }
- if (top - tail > r.top) try r.holes.append(gpa, .{ r.top, top - tail });
- }
- r.top = top;
- }
- // The history as long as the authority's (it prunes a page at a
- // time, and an ED 3 takes it all): row numbers and the scrollbar
- // say the same on both. ponytail: one pruned shorter than that
- // (its pages packed otherwise) stays shorter.
- const have = primary.pages.total_rows - primary.pages.rows;
- if (have > history) primary.pages.eraseHistory(.{ .history = .{ .y = @intCast(have - history - 1) } });
- r.trimHoles(primary);
- for (0..tail) |j| {
- const p = pinOf(&primary.pages, top, top - tail + j) orelse continue;
- const h = std.mem.readInt(u64, tails[j * 8 ..][0..8], .little);
- if (rowHash(p.node.page(), p.rowAndCell().row, t.cols) != h) try r.writeRow(gpa, primary, p, try blobOf(r, &fresh, h));
- }
-
- const screen = t.screens.active;
- const held = &r.held[@backingInt(t.screens.active_key)];
- const blank_row = blankHash(t.cols);
- while (held.items.len < nrows) try held.append(gpa, blank_row);
- held.shrinkRetainingCapacity(nrows);
- for (0..nrows) |y| {
- const h = std.mem.readInt(u64, hashes[y * 8 ..][0..8], .little);
- if (h == held.items[y]) continue;
- try r.writeRow(gpa, screen, screen.pages.pin(.{ .active = .{ .y = @intCast(y) } }).?, try blobOf(r, &fresh, h));
- held.items[y] = h;
- }
- screen.cursorReload();
- screen.cursorAbsolute(@min(cx, t.cols - 1), @min(cy, t.rows - 1));
- screen.cursor.cursor_style = @fromBackingInt(@intCast(style));
- screen.cursor.pending_wrap = wrap != 0;
- screen.cursor.semantic_content = @fromBackingInt(@intCast(semantic));
- screen.kitty_keyboard = kitty;
- const oldest = r.top -| (primary.pages.total_rows - primary.pages.rows);
- primary.pages.scroll(if (viewport == following) .active else .{ .row = @intCast(viewport -| oldest) });
-
- // Hold the blobs of this state, and no others.
- var keep: std.AutoHashMapUnmanaged(Hash, []u8) = .empty;
- errdefer keep.deinit(gpa);
- try keep.ensureTotalCapacity(gpa, nrows + tail + 1);
- for (0..nrows + tail + 1) |i| {
- const h = if (i == nrows + tail) meta else if (i < nrows)
- std.mem.readInt(u64, hashes[i * 8 ..][0..8], .little)
- else
- std.mem.readInt(u64, tails[(i - nrows) * 8 ..][0..8], .little);
- if (keep.contains(h)) continue;
- const b = if (r.blobs.fetchRemove(h)) |kv| kv.value else try gpa.dupe(u8, try blobOf(r, &fresh, h));
- keep.putAssumeCapacity(h, b);
- }
- var old = r.blobs.valueIterator();
- while (old.next()) |b| gpa.free(b.*);
- r.blobs.deinit(gpa);
- r.blobs = keep;
- r.seq = seq;
- return .{ .seq = seq, .extra = extra };
- }
-
- /// The holes in `[lo, hi)` blank: until their rows come, a hole shows
- /// nothing rather than what that row held before a flood renumbered it.
- pub fn blank(r: *const Replica, t: *Terminal, lo: u64, hi: u64) void {
- const primary = t.screens.get(.primary).?;
- const oldest = r.top -| (primary.pages.total_rows - primary.pages.rows);
- for (r.holes.items) |hole| {
- const a = @max(lo, hole[0], oldest);
- const b = @min(hi, hole[1], r.top);
- if (a >= b) continue;
- primary.clearRows(.{ .screen = .{ .y = @intCast(a - oldest) } }, .{ .screen = .{ .y = @intCast(b - 1 - oldest) } }, false);
- }
- }
-
- /// The holes in `[lo, hi)`: the rows to fetch before showing them.
- pub fn missing(r: *const Replica, lo: u64, hi: u64, out: *std.ArrayList([2]u64), gpa: std.mem.Allocator) !void {
- for (r.holes.items) |hole| {
- const a = @max(lo, hole[0]);
- const b = @min(hi, hole[1]);
- if (a < b) try out.append(gpa, .{ a, b });
- }
- }
-
- /// The absolute row the viewport of `t`'s primary screen starts at, and
- /// how many it shows.
- pub fn shown(r: *const Replica, t: *Terminal) [2]u64 {
- const pages = &t.screens.get(.primary).?.pages;
- const sb = pages.scrollbar();
- const oldest = r.top -| (pages.total_rows - pages.rows);
- return .{ oldest + sb.offset, oldest + sb.offset + sb.len };
- }
-
- /// Write fetched history rows (`encodeRows`) into `t`.
- pub fn applyRows(r: *Replica, gpa: std.mem.Allocator, t: *Terminal, bytes: []const u8) !void {
- var in: std.Io.Reader = .fixed(bytes);
- if (try in.takeInt(u32, .little) != r.epoch) return; // numbered before a resize
- const primary = t.screens.get(.primary).?;
- var blobs: std.AutoHashMapUnmanaged(Hash, []const u8) = .empty;
- defer blobs.deinit(gpa);
- for (0..try in.takeInt(u32, .little)) |_| {
- const h = try in.takeInt(u64, .little);
- try blobs.put(gpa, h, try in.take(try in.takeInt(u32, .little)));
- }
- for (0..try in.takeInt(u32, .little)) |_| {
- const abs = try in.takeInt(u64, .little);
- const blob = blobs.get(try in.takeInt(u64, .little)) orelse return error.MissingBlob;
- // Only a hole is written: a row the replica holds is the
- // authority's already, and newer than what this fetch saw.
- if (abs >= r.top or !r.inHole(abs)) continue;
- const p = pinOf(&primary.pages, r.top, abs) orelse continue;
- try r.writeRow(gpa, primary, p, blob);
- try r.fill(gpa, abs);
- }
- }
-
- fn inHole(r: *const Replica, abs: u64) bool {
- for (r.holes.items) |hole| if (abs >= hole[0] and abs < hole[1]) return true;
- return false;
- }
-
- /// Row `abs` is written: out of the holes.
- fn fill(r: *Replica, gpa: std.mem.Allocator, abs: u64) !void {
- for (r.holes.items, 0..) |*hole, i| {
- if (abs < hole[0] or abs >= hole[1]) continue;
- if (abs == hole[0]) hole[0] += 1 else if (abs + 1 == hole[1]) hole[1] -= 1 else {
- try r.holes.insert(gpa, i + 1, .{ abs + 1, hole[1] });
- r.holes.items[i][1] = abs;
- }
- if (r.holes.items[i][0] == r.holes.items[i][1]) _ = r.holes.orderedRemove(i);
- return;
- }
- }
-
- fn trimHoles(r: *Replica, primary: *Screen) void {
- clampHoles(&r.holes, r.top -| (primary.pages.total_rows - primary.pages.rows));
- }
-
- fn writeRow(r: *Replica, gpa: std.mem.Allocator, screen: *Screen, p: Pin, blob: []const u8) !void {
- var reader: std.Io.Reader = .fixed(blob);
- var dec: snapshot.page.Decoder = undefined;
- try dec.init(&reader, try snapshot.record.nextHeader(&reader));
- const src = try scratchPage(&r.scratch, dec.capacity());
- try dec.decode(src, gpa);
- if (src.size.cols != screen.pages.cols) return error.BadRow;
- _ = screen.clonePartialRowGrowCapacity(p.node, p.y, src, src.getRow(0), 0, src.size.cols);
- }
-};
-
-/// `k` blank rows onto the bottom of a screen's active area, its top `k`
-/// going up into the history, as `k` linefeeds at the bottom would. A
-/// flood's thousands are grown a row at a time without the cursor (the
-/// page list's fast path, a counter), which is put back after.
-fn scrollUp(screen: *Screen, k: u64) !void {
- if (k == 0) return;
- screen.cursorAbsolute(0, screen.pages.rows - 1);
- if (k <= screen.pages.rows or screen.no_scrollback or screen.cursor.style_id != 0) {
- for (0..@intCast(k)) |_| try screen.cursorDownScroll();
- return;
- }
- for (0..@intCast(k)) |_| _ = try screen.pages.grow();
- screen.cursorReload();
-}
-
-/// No row's address: what a row whose content is not known is held as.
-const unknown: Hash = std.math.maxInt(Hash);
-
-/// `rowHash` of a row never written.
-fn blankHash(cols: u16) Hash {
- var h = std.hash.Wyhash.init(0);
- h.update(&.{0});
- h.update(std.mem.asBytes(&cols));
- return h.final();
-}
-
-/// The terminal-wide state of `next` (a decoded TERMINAL record) into `t`,
-/// whose screens and pages stay: what `snapshot.terminal.decode` sets.
-fn takeMeta(t: *Terminal, next: *Terminal, io: std.Io, gpa: std.mem.Allocator) !void {
- if (t.cols != next.cols or t.rows != next.rows) try t.resize(gpa, .{ .cols = next.cols, .rows = next.rows });
- t.width_px = next.width_px;
- t.height_px = next.height_px;
- t.scrolling_region = next.scrolling_region;
- t.status_display = next.status_display;
- t.previous_char = next.previous_char;
- t.cursor = next.cursor;
- t.modes = next.modes;
- t.flags.shell_redraws_prompt = next.flags.shell_redraws_prompt;
- t.flags.modify_other_keys_2 = next.flags.modify_other_keys_2;
- t.flags.mouse_event = next.flags.mouse_event;
- t.flags.mouse_format = next.flags.mouse_format;
- t.flags.mouse_shift_capture = next.flags.mouse_shift_capture;
- t.flags.password_input = next.flags.password_input;
- t.mouse_shape = next.mouse_shape;
- t.colors = next.colors;
- try t.setPwd(next.getPwd() orelse "");
- try t.setTitle(next.getTitle() orelse "");
- std.mem.swap(@TypeOf(t.tabstops), &t.tabstops, &next.tabstops);
- const key = next.screens.active_key;
- if (key != t.screens.active_key) {
- if (t.screens.get(key) == null) _ = try t.screens.getInit(io, gpa, key, .{ .cols = t.cols, .rows = t.rows, .max_scrollback_bytes = 0 });
- t.screens.switchTo(key);
- }
-}
-
-// ---- checks: a replica against its authority, cell for cell ----
-
-/// What a row shows, written out value by value (not `rowHash`'s walk):
-/// its flags, then each cell's word without its page's ids, its style, its
-/// grapheme and its hyperlink's URI.
-fn dumpRow(page: *Page, row: *Row, cols: u16, w: *std.Io.Writer) !void {
- try w.print("{d}:", .{rowFlags(row)});
- const all = page.getCells(row);
- for (all[0..@min(cols, all.len)]) |*c| {
- var word = c.*;
- word.style_id = 0;
- try w.print(" {x}", .{@as(u64, @bitCast(word))});
- if (c.style_id != 0) try snapshot.style.encode(page.styles.get(page.memory, c.style_id).*, w);
- if (c.hasGrapheme()) for (page.lookupGrapheme(c).?) |cp| try w.print("+{x}", .{cp});
- if (c.hyperlink) if (page.lookupHyperlink(c)) |id| try w.print("@{s}", .{page.hyperlink_set.get(page.memory, id).uri.slice(page.memory)});
- }
- try w.writeByte('\n');
-}
-
-/// The state a replica must match: the terminal-wide state, the cursor,
-/// the history's extent and the viewport, the active screen's rows.
-pub fn dumpScreen(t: *Terminal, w: *std.Io.Writer) !void {
- const screen = t.screens.active;
- const sb = t.screens.get(.primary).?.pages.scrollbar();
- try w.print("{d}x{d} {s} cursor {d},{d} {s} {} {s} title {s} pwd {s} scrollbar {d} {d} {d}\n", .{
- t.cols, t.rows, @tagName(t.screens.active_key),
- screen.cursor.x, screen.cursor.y, @tagName(screen.cursor.cursor_style),
- screen.cursor.pending_wrap, @tagName(screen.cursor.semantic_content), t.getTitle() orelse "",
- t.getPwd() orelse "", sb.total, sb.offset,
- sb.len,
- });
- try w.writeAll(std.mem.asBytes(&t.modes.values));
- try w.writeAll(std.mem.asBytes(&screen.kitty_keyboard));
- try w.print(" mouse {s} {s} {s}\n", .{ @tagName(t.flags.mouse_event), @tagName(t.flags.mouse_format), @tagName(t.mouse_shape) });
- for (t.colors.palette.current) |c| try w.print("{x}{x}{x}", .{ c.r, c.g, c.b });
- try w.writeByte('\n');
- var it = screen.pages.rowIterator(.right_down, .{ .active = .{} }, null);
- while (it.next()) |p| try dumpRow(p.node.page(), p.rowAndCell().row, t.cols, w);
-}
-
-/// An authority and its replica, fed one stream of pty bytes, the deltas
-/// and fetches between them at random: a delta encoded at a random step
-/// (so the states between are skipped), several in flight and each landing
-/// a random number of steps later, in order, one lost now and then (the
-/// replica refuses the next and is started afresh), random resizes of the
-/// authority, random fetches of holes. After each delta, the replica's
-/// screen is the authority's as it was encoded, and every history row it
-/// holds outside its holes is what the authority holds at that absolute
-/// row.
-pub const Soak = struct {
- gpa: std.mem.Allocator,
- io: std.Io,
- a: *Terminal,
- stream: vt.TerminalStream,
- track: Track,
- enc: Encoder,
- peer: Peer = .{},
- /// The authority's writes, as terminal.State counts them.
- changes: u32 = 0,
- b: *Terminal,
- rep: Replica = .{},
- prng: std.Random.DefaultPrng,
- /// The deltas in flight, oldest first, each with the authority's dump
- /// when it was encoded and the step it lands at.
- flight: std.ArrayList(struct { delta: []u8, expect: []u8, at: u64 }) = .empty,
- got: std.Io.Writer.Allocating,
- now: u64 = 0,
- resizes: bool = true,
- drops: bool = true,
- /// The replica refused a delta and the authority started it afresh:
- /// what was in flight before is refused too.
- refused: bool = false,
- stats: struct { deltas: u64 = 0, bytes: u64 = 0, fetched: u64 = 0, history_checked: u64 = 0, lost: u64 = 0, refused: u64 = 0, most_in_flight: u64 = 0 } = .{},
-
- pub fn init(gpa: std.mem.Allocator, io: std.Io, cols: u16, rows: u16, scrollback: usize, seed: u64) !*Soak {
- const s = try gpa.create(Soak);
- errdefer gpa.destroy(s);
- const a = try gpa.create(Terminal);
- a.* = try Terminal.init(io, gpa, .{ .cols = cols, .rows = rows, .max_scrollback_bytes = scrollback });
- const b = try gpa.create(Terminal);
- // Room to spare: its pages may pack rows otherwise, and it keeps the
- // authority's history to the row.
- b.* = try Terminal.init(io, gpa, .{ .cols = 2, .rows = 2, .max_scrollback_bytes = 2 * scrollback });
- s.* = .{
- .gpa = gpa,
- .io = io,
- .a = a,
- .stream = a.vtStream(),
- .track = .init(gpa),
- .enc = .init(gpa),
- .b = b,
- .prng = .init(seed),
- .got = .init(gpa),
- };
- return s;
- }
-
- pub fn deinit(s: *Soak) void {
- const gpa = s.gpa;
- s.stream.deinit();
- s.track.deinit(gpa, s.a);
- s.a.deinit(gpa);
- gpa.destroy(s.a);
- s.b.deinit(gpa);
- gpa.destroy(s.b);
- s.enc.deinit();
- s.peer.deinit(gpa);
- s.rep.deinit(gpa);
- for (s.flight.items) |f| {
- gpa.free(f.delta);
- gpa.free(f.expect);
- }
- s.flight.deinit(gpa);
- s.got.deinit();
- gpa.destroy(s);
- }
-
- /// `bytes` into the authority in random pieces, a step after each.
- pub fn feed(s: *Soak, bytes: []const u8) !void {
- var at: usize = 0;
- const random = s.prng.random();
- while (at < bytes.len) {
- const n = @min(bytes.len - at, 1 + random.uintLessThan(usize, 512));
- s.stream.nextSlice(bytes[at..][0..n]);
- s.changes +%= 1;
- at += n;
- try s.step();
- }
- }
-
- pub fn step(s: *Soak) !void {
- const random = s.prng.random();
- s.now += 1;
- if (s.resizes and random.uintLessThan(u32, 200) == 0) {
- try s.a.resize(s.gpa, .{ .cols = 10 + random.uintLessThan(u16, 200), .rows = 3 + random.uintLessThan(u16, 60) });
- s.changes +%= 1;
- }
- // A frame now and then; the states between are skipped.
- if (random.boolean()) try s.send(s.now + random.uintLessThan(u64, 12));
- while (s.flight.items.len > 0 and s.flight.items[0].at <= s.now) try s.land();
- if (random.uintLessThan(u32, 8) == 0) try s.fetch();
- }
-
- /// A delta, if the peer is owed one, sent to land at step `at`.
- fn send(s: *Soak, at: u64) !void {
- var d: std.Io.Writer.Allocating = .init(s.gpa);
- defer d.deinit();
- if (!try encode(&s.enc, &s.track, &s.peer, s.a, s.changes, "extra", &d.writer)) return;
- var expect: std.Io.Writer.Allocating = .init(s.gpa);
- defer expect.deinit();
- try dumpScreen(s.a, &expect.writer);
- const last = if (s.flight.items.len > 0) s.flight.items[s.flight.items.len - 1].at else 0;
- try s.flight.append(s.gpa, .{ .delta = try d.toOwnedSlice(), .expect = try expect.toOwnedSlice(), .at = @max(at, last) });
- s.stats.deltas += 1;
- s.stats.bytes += s.flight.items[s.flight.items.len - 1].delta.len;
- s.stats.most_in_flight = @max(s.stats.most_in_flight, s.flight.items.len);
- }
-
- /// The oldest delta in flight applied (or lost), acknowledged, checked.
- fn land(s: *Soak) !void {
- const f = s.flight.orderedRemove(0);
- defer s.gpa.free(f.delta);
- defer s.gpa.free(f.expect);
- if (s.drops and s.prng.random().uintLessThan(u32, 50) == 0) {
- s.stats.lost += 1;
- return;
- }
- const applied = s.rep.apply(s.gpa, s.io, s.b, f.delta) catch |err| switch (err) {
- error.BaseMismatch => {
- // Asked once: the authority starts it afresh.
- if (!s.refused) s.peer.reset();
- s.refused = true;
- s.stats.refused += 1;
- return;
- },
- else => return err,
- };
- s.refused = false;
- if (!std.mem.eql(u8, applied.extra, "extra")) return error.ExtraLost;
- s.peer.ack(applied.seq);
- s.got.clearRetainingCapacity();
- try dumpScreen(s.b, &s.got.writer);
- if (!std.mem.eql(u8, f.expect, s.got.written())) {
- reportDiff(f.expect, s.got.written());
- return error.ReplicaDiffers;
- }
- try s.checkHistory();
- }
-
- /// Everything in flight landed, then a last delta of the end, until the
- /// replica holds it: what the replica shows at quiescence.
- fn settle(s: *Soak) !void {
- s.drops = false;
- for (0..4) |_| {
- while (s.flight.items.len > 0) try s.land();
- try s.send(0);
- if (s.flight.items.len == 0) return;
- }
- return error.NeverSettled;
- }
-
- /// Every history row the replica holds, outside its holes and inside
- /// what the authority still has, is the authority's (rows in history
- /// never change; a resize renumbers and starts the replica afresh).
- fn checkHistory(s: *Soak) !void {
- // Numbered as of now: the authority may have scrolled on since.
- try s.track.rows.update(s.a);
- if (s.rep.epoch != s.track.rows.epoch) return;
- const pages = &s.b.screens.get(.primary).?.pages;
- const have = pages.total_rows - pages.rows;
- var ra: std.Io.Writer.Allocating = .init(s.gpa);
- defer ra.deinit();
- var rb: std.Io.Writer.Allocating = .init(s.gpa);
- defer rb.deinit();
- var d: u64 = 1;
- while (d <= have) : (d += 1 + d / 8) {
- const abs = s.rep.top - d;
- if (s.rep.inHole(abs)) continue;
- const pb = pinOf(pages, s.rep.top, abs) orelse continue;
- const pa = s.track.rows.pinAt(s.a, abs) orelse continue;
- ra.clearRetainingCapacity();
- rb.clearRetainingCapacity();
- try dumpRow(pa.node.page(), pa.rowAndCell().row, s.a.cols, &ra.writer);
- try dumpRow(pb.node.page(), pb.rowAndCell().row, s.b.cols, &rb.writer);
- if (!std.mem.eql(u8, ra.written(), rb.written())) {
- std.debug.print("history row {d} ({d} above the top) differs\n", .{ abs, d });
- reportDiff(ra.written(), rb.written());
- return error.ReplicaHistoryDiffers;
- }
- s.stats.history_checked += 1;
- }
- }
-
- /// Some holes fetched from the authority, as a replica scrolled back.
- fn fetch(s: *Soak) !void {
- if (s.rep.holes.items.len == 0) return;
- const random = s.prng.random();
- const hole = s.rep.holes.items[random.uintLessThan(usize, s.rep.holes.items.len)];
- const lo = hole[0] + random.uintLessThan(u64, hole[1] - hole[0]);
- const hi = @min(hole[1], lo + 1 + random.uintLessThan(u64, 80));
- s.rep.blank(s.b, lo, hi);
- var out: std.Io.Writer.Allocating = .init(s.gpa);
- defer out.deinit();
- try encodeRows(&s.enc, &s.track, s.a, lo, hi, &out.writer);
- try s.rep.applyRows(s.gpa, s.b, out.written());
- s.stats.fetched += hi - lo;
- try s.checkHistory();
- }
-};
-
-fn reportDiff(want: []const u8, got: []const u8) void {
- var wl = std.mem.splitScalar(u8, want, '\n');
- var gl = std.mem.splitScalar(u8, got, '\n');
- var line: usize = 0;
- while (true) : (line += 1) {
- const a = wl.next();
- const b = gl.next();
- if (a == null and b == null) return;
- if (a != null and b != null and std.mem.eql(u8, a.?, b.?)) continue;
- std.debug.print("line {d} differs:\n authority {s}\n replica {s}\n", .{ line, a orelse "(none)", b orelse "(none)" });
- return;
- }
-}
-
-/// Drive one stream through a soak, then settle: the replica's screen at
-/// quiescence is the authority's.
-pub fn soak(gpa: std.mem.Allocator, io: std.Io, bytes: []const u8, cols: u16, rows: u16, scrollback: usize, seed: u64, resizes: bool) !@FieldType(Soak, "stats") {
- const s = try Soak.init(gpa, io, cols, rows, scrollback, seed);
- defer s.deinit();
- s.resizes = resizes;
- try s.feed(bytes);
- try s.settle();
- return s.stats;
-}
-
-const testing = std.testing;
-
-/// A shell's: prompts marked (OSC 133), colours of the three kinds, wide
-/// and combined graphemes, hyperlinks, tabs, a title and a directory, long
-/// lines that wrap, and a clear (ED2, ED3) now and then.
-pub fn shellStream(gpa: std.mem.Allocator) ![]u8 {
- var out: std.Io.Writer.Allocating = .init(gpa);
- errdefer out.deinit();
- const w = &out.writer;
- try w.writeAll("\x1b]0;a shell\x07\x1b]7;file://host/home/someone\x07");
- for (0..400) |i| {
- try w.print("\x1b]133;A\x07$ \x1b]133;B\x07ls -l {d}\r\n\x1b]133;C\x07", .{i});
- try w.print("\x1b[1;31mred\x1b[0m \x1b[4;38;5;{d}m256\x1b[0m \x1b[38;2;{d};100;200;48;5;17mtrue\x1b[0m 漢字 e\u{301} 👩\u{200d}💻 ", .{ i % 256, i % 256 });
- try w.print("\x1b]8;;https://example.com/{d}\x07link\x1b]8;;\x07\tx\r\n", .{i});
- if (i % 7 == 0) {
- for (0..12) |_| try w.writeAll("a long line that wraps ");
- try w.writeAll("\r\n");
- }
- try w.writeAll("\x1b]133;D;0\x07");
- if (i % 97 == 96) try w.writeAll("\x1b[H\x1b[2J\x1b[3J");
- if (i % 50 == 0) try w.print("\x1b]2;title {d}\x07\x1b]4;1;rgb:{x:0>2}/20/30\x07", .{ i, i % 256 });
- }
- return out.toOwnedSlice();
-}
-
-/// A full-screen program's: the alternate screen and its modes, a status
-/// line, a scrolling region scrolled both ways, lines inserted and
-/// deleted, cursor shapes, the kitty keyboard pushed and popped.
-pub fn tuiStream(gpa: std.mem.Allocator) ![]u8 {
- var out: std.Io.Writer.Allocating = .init(gpa);
- errdefer out.deinit();
- const w = &out.writer;
- try w.writeAll("before the program\r\n\x1b[?1049h\x1b[?25l\x1b[?1000h\x1b[?1006h\x1b[?2004h\x1b[?1h\x1b[>1u\x1b[4 q\x1b[H\x1b[2J");
- for (0..300) |f| {
- try w.print("\x1b[1;1H\x1b[44;97m status {d} \x1b[K\x1b[0m", .{f});
- try w.print("\x1b[3;18r\x1b[18;1H\r\n\x1b[3{d}mline {d}\x1b[0m", .{ f % 8, f });
- if (f % 3 == 0) try w.writeAll("\x1b[3;1H\x1bM\x1b[2mreversed in\x1b[0m");
- if (f % 5 == 0) try w.writeAll("\x1b[6;1H\x1b[2L\x1b[9;1H\x1b[M");
- try w.writeAll("\x1b[r");
- try w.print("\x1b[{d};{d}H\x1b[7m*\x1b[0m\x1b[{d}X", .{ 2 + f % 20, 1 + (f * 7) % 70, f % 5 });
- if (f % 11 == 0) try w.writeAll("\x1b[?25h\x1b[6 q") else if (f % 11 == 5) try w.writeAll("\x1b[?25l\x1b[2 q");
- }
- try w.writeAll("\x1b[<u\x1b[?1049l\x1b[?25h\x1b[?1000l\x1b[0 qafter the program\r\n");
- return out.toOwnedSlice();
-}
-
-pub fn yesStream(gpa: std.mem.Allocator, lines: usize) ![]u8 {
- const out = try gpa.alloc(u8, lines * 3);
- for (0..lines) |i| @memcpy(out[i * 3 ..][0..3], "y\r\n");
- return out;
-}
-
-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;
- const shell = try shellStream(gpa);
- defer gpa.free(shell);
- const tui = try tuiStream(gpa);
- defer gpa.free(tui);
- const yes = try yesStream(gpa, 30_000);
- defer gpa.free(yes);
- var fetched: u64 = 0;
- var history: u64 = 0;
- for (0..4) |seed| {
- // A small scrollback, so it wraps (pruned at its oldest pages).
- for ([_][]const u8{ shell, tui, yes }) |bytes| {
- const st = soak(gpa, io, bytes, 80, 24, 64 * 1024, seed, seed != 0) catch |err| {
- std.debug.print("soak seed {d} stream {d} bytes: {s}\n", .{ seed, bytes.len, @errorName(err) });
- return err;
- };
- try testing.expect(st.deltas > 10);
- fetched += st.fetched;
- history += st.history_checked;
- }
- }
- // The holes were fetched, and history rows compared, at all.
- try testing.expect(fetched > 0 and history > 0);
-}
-
-test "under a flood a delta is a screen of hashes: an unchanged row costs its address alone" {
- const gpa = testing.allocator;
- const s = try Soak.init(gpa, testing.io, 200, 60, 1 << 20, 1);
- defer s.deinit();
- s.resizes = false;
- s.drops = false;
- const yes = try yesStream(gpa, 10_000);
- defer gpa.free(yes);
- var last: []u8 = &.{};
- defer gpa.free(last);
- for (0..3) |_| {
- s.stream.nextSlice(yes);
- s.changes += 1;
- try s.send(0);
- try testing.expectEqual(@as(usize, 1), s.flight.items.len);
- gpa.free(last);
- last = try gpa.dupe(u8, s.flight.items[0].delta);
- try s.land();
- }
- // The last: 60 rows and the tail's 60, of hashes the replica holds, no
- // blob; the header and counts around them.
- const d = last;
- const at = 4 + 4 + 1 + 4 + 8 + 2 + 2 + 1 + 1 + 1 + @sizeOf(KittyFlags) + 8 + 8 + 8 + 2 + "extra".len;
- const nrows = std.mem.readInt(u16, d[at..][0..2], .little);
- const tail = std.mem.readInt(u16, d[at + 2 + nrows * 8 ..][0..2], .little);
- const blobs = std.mem.readInt(u16, d[at + 4 + (nrows + tail) * 8 ..][0..2], .little);
- if (d.len >= (nrows + tail) * 8 + 128) std.debug.print("delta {d} bytes: {d} rows, {d} tail, {d} blobs\n", .{ d.len, nrows, tail, blobs });
- try testing.expectEqual(@as(u16, 0), blobs);
- try testing.expect(d.len < (nrows + tail) * 8 + 128);
- try testing.expect(s.rep.holes.items.len > 0);
-}
-
-test "a reflow to fewer columns keeps every history row numbered at or past 0" {
- const gpa = testing.allocator;
- const s = try Soak.init(gpa, testing.io, 80, 24, 1 << 20, 3);
- defer s.deinit();
- s.resizes = false;
- s.drops = false;
- // Lines of 69 columns scrolled into the history, then the screen
- // narrowed so that each wraps in three: more rows above the last top
- // than ever scrolled past it (a window client's font, 2026-10-30: the
- // session's peer started afresh at `top - history`, which overflowed).
- var line: [80]u8 = undefined;
- for (0..200) |i| {
- s.stream.nextSlice(try std.fmt.bufPrint(&line, "{d:0>4} xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\r\n", .{i}));
- s.changes += 1;
- }
- try s.send(0);
- try s.land();
- try s.a.resize(gpa, .{ .cols = 30, .rows = 24 });
- s.changes += 1;
- try s.send(0);
- try s.land();
- try s.settle();
- try testing.expect(s.track.rows.top >= s.track.history);
-}
-
-test "several deltas in flight land in order, and a peer at the bound waits for an acknowledgement" {
- const gpa = testing.allocator;
- const s = try Soak.init(gpa, testing.io, 80, 24, 1 << 20, 2);
- defer s.deinit();
- s.resizes = false;
- s.drops = false;
- var line: [64]u8 = undefined;
- for (0..bound + 5) |i| {
- s.stream.nextSlice(try std.fmt.bufPrint(&line, "line {d}\r\n", .{i}));
- s.changes += 1;
- try s.send(1000);
- }
- // The bound's worth went; the rest wait, and are skipped.
- try testing.expectEqual(@as(usize, bound), s.flight.items.len);
- try s.land();
- try s.send(1000);
- try testing.expectEqual(@as(usize, bound), s.flight.items.len);
- try s.settle();
- try testing.expectEqual(@as(u64, 0), s.stats.refused);
-}
-
diff --git a/core/term/term.zig b/core/term/term.zig
index 59511727..058154a7 100644
--- a/core/term/term.zig
+++ b/core/term/term.zig
@@ -1,7 +1,7 @@
//! The terminal, a module of its own (docs/next-terminal.md, Phase 1):
//! ghostty-vt's emulator and what pardes keeps beside it (terminal.zig),
-//! the screen state its replicas are sent (screen_state.zig), the kitty
-//! images it draws (TerminalImages.zig) and the pager's parse (pager.zig).
+//! the kitty images it draws (TerminalImages.zig) and the pager's parse
+//! (pager.zig).
//! It imports std, ghostty-vt, wuffs, zstbi and `plain`, never the core:
//! the core reaches it through `ops` (core/Term.zig), the records of
//! abi/term.zig in and out.
@@ -10,11 +10,8 @@ const plain = @import("plain");
const iface = plain.term;
const terminal_ = @import("terminal.zig");
const pager = @import("pager.zig");
-const screen_state_ = @import("screen_state.zig");
const TerminalImages = terminal_.TerminalImages;
-/// The screen state replicas are sent, its streams and soak (test/replicas.zig).
-pub const screen_state = screen_state_;
/// The emulator itself, for the tests that read it through a core
/// (test/terminal.zig).
pub const terminal = terminal_;
@@ -39,7 +36,6 @@ pub const ops: iface.Ops = .{
.scroll = cast(iface.Ops, "scroll", terminal_.scroll),
.follow = cast(iface.Ops, "follow", terminal_.follow),
.resize = cast(iface.Ops, "resize", terminal_.resize),
- .resizeDeferred = cast(iface.Ops, "resizeDeferred", terminal_.resizeDeferred),
.cellPixels = cast(iface.Ops, "cellPixels", terminal_.cellPixels),
.replies = cast(iface.Ops, "replies", terminal_.replies),
.key = cast(iface.Ops, "key", terminal_.key),
@@ -57,7 +53,6 @@ pub const ops: iface.Ops = .{
.viewport = cast(iface.Ops, "viewport", terminal_.viewport),
.editRows = cast(iface.Ops, "editRows", terminal_.editRows),
.promptCut = cast(iface.Ops, "promptCut", terminal_.promptCutAt),
- .markRead = cast(iface.Ops, "markRead", terminal_.markRead),
.echoCell = cast(iface.Ops, "echoCell", terminal_.echoCell),
.page = pager.parse,
.filter = terminal_.pagerFilter,
@@ -65,32 +60,12 @@ pub const ops: iface.Ops = .{
.paint = cast(iface.Ops, "paint", terminal_.paint),
.images = cast(iface.Ops, "images", terminal_.images),
.hasImages = cast(iface.Ops, "hasImages", terminal_.hasImages),
- .encoder = cast(iface.Ops, "encoder", terminal_.encoder),
- .encoderFree = cast(iface.Ops, "encoderFree", terminal_.encoderFree),
- .track = cast(iface.Ops, "track", terminal_.track),
- .untrack = cast(iface.Ops, "untrack", terminal_.untrack),
- .encode = cast(iface.Ops, "encode", terminal_.encode),
- .encodeRows = cast(iface.Ops, "encodeRows", terminal_.encodeRows),
- .wasRead = cast(iface.Ops, "wasRead", terminal_.wasRead),
- .clearRead = cast(iface.Ops, "clearRead", terminal_.clearRead),
- .replica = cast(iface.Ops, "replica", terminal_.replica),
- .replicaFree = cast(iface.Ops, "replicaFree", terminal_.replicaFree),
- .replicaTop = cast(iface.Ops, "replicaTop", terminal_.replicaTop),
- .missing = cast(iface.Ops, "missing", terminal_.missing),
- .apply = cast(iface.Ops, "apply", terminal_.apply),
- .applyRows = cast(iface.Ops, "applyRows", terminal_.applyRows),
- .shown = cast(iface.Ops, "shown", terminal_.shown),
- .blank = cast(iface.Ops, "blank", terminal_.blank),
- .dumpScreen = cast(iface.Ops, "dumpScreen", terminal_.dumpScreen),
};
/// The term's handle types as the interface names them, and the module's
/// own behind each: a pointer to one is a pointer to the other.
const handles = .{
.{ iface.State, terminal_.State },
- .{ iface.Encoder, screen_state_.Encoder },
- .{ iface.Track, screen_state_.Track },
- .{ iface.Replica, screen_state_.Replica },
};
/// The interface's handle for one of this module's own types, or the type
@@ -160,5 +135,4 @@ test {
_ = &ops;
_ = terminal_;
_ = pager;
- _ = screen_state_;
}
diff --git a/core/term/terminal.zig b/core/term/terminal.zig
index 187ed144..44038a18 100644
--- a/core/term/terminal.zig
+++ b/core/term/terminal.zig
@@ -5,7 +5,6 @@ const std = @import("std");
const plain = @import("plain");
const Key = plain.Key;
const Term = plain.term;
-const screen_state = @import("screen_state.zig");
const ghostty_vt = @import("ghostty-vt");
const Ink = plain.term.Ink;
@@ -183,18 +182,6 @@ pub const State = struct {
reply_dropped: u32 = 0,
/// The kitty graphics its program placed, as drawn (TerminalImages.zig).
images: TerminalImages = if (images_enabled) .{} else {},
- /// Counts the emulator's writes (output, a resize, its view scrolled):
- /// a new count is a new state for its replicas (screen_state.Track).
- changes: u32 = 0,
- /// A step read its rows (its history too): a replica replaying that
- /// step must hold them, so its authority sends the ones it does not
- /// before the step's unit (replica.Screens.fill).
- read: bool = false,
- /// The size a step gave it, on an authority with screen-state replicas:
- /// made after the step's unit (`resizeDeferred`), so that the rest of
- /// the step reads the grid it had, as its replicas' replays do, and the
- /// rows sent them for it (Screens.fill) are of that grid's numbering.
- resize_to: ?struct { cols: u16, rows: u16 } = null,
/// The stream over the emulator, its answers to the program and its
/// size reports routed here, PNG decoded: what `create` and a dump's
@@ -224,9 +211,22 @@ pub fn digest(s: *const State, h: *std.hash.Wyhash, view: bool) void {
const sb = screen.pages.scrollbar();
const cur = screen.cursor;
const offset = if (view) sb.offset else 0;
- const facts = .{ sb.total, offset, sb.len, cur.x, cur.y, s.vt.modes.get(.cursor_visible), s.vt.screens.active_key, s.reply_dropped };
+ // Everything a step reads of it (abi/term.zig `replicated`): its
+ // size, the view and the cursor, its modes (the alternate screen,
+ // the mouse's, focus reports, bracketed paste: `modes`), whether it
+ // holds a kitty image (the tag says so: tagline.zig), the reply
+ // buffer, the OSC 133 cycle (`prompt`), the active area's text. Not
+ // the history's text, only its length (a step's read of it: not
+ // covered; core/Term.zig `calls`).
+ const Modes = @TypeOf(s.vt.modes.values);
+ const mode_bits: @Int(.unsigned, @bitSizeOf(Modes)) = @bitCast(s.vt.modes.values);
+ const modes_word: @Int(.unsigned, (@bitSizeOf(Modes) + 7) / 8 * 8) = mode_bits;
+ const mouse_flags: [2]u8 = .{ @intCast(@intFromEnum(s.vt.flags.mouse_event)), @intCast(@intFromEnum(s.vt.flags.mouse_format)) };
+ const facts = .{ s.vt.cols, s.vt.rows, sb.total, offset, sb.len, cur.x, cur.y, modes_word, s.vt.screens.active_key, mouse_flags, s.reply_dropped, hasImages(s) };
inline for (facts) |fact| h.update(std.mem.asBytes(&fact));
h.update(s.reply[0..s.reply_len]);
+ var marks: [marks_len]u8 = undefined;
+ h.update(marksOf(s, &marks));
var buf: [4096]u8 = undefined;
var text: std.Io.Writer.Hashing(std.hash.Wyhash) = .initHasher(h.*, &buf);
if (screen.pages.getBottomRight(.active)) |br|
@@ -338,11 +338,10 @@ pub fn reload(s: *State) !u64 {
var reply: [@typeInfo(@FieldType(State, "reply")).array.len]u8 = undefined;
@memcpy(reply[0..saved.reply.len], saved.reply);
saved.reply = reply[0..saved.reply.len];
- const kept = .{ s.changes, s.read, s.resize_to };
if (comptime images_enabled) s.images.deinit(gpa);
s.stream.deinit();
s.vt.deinit(gpa);
- s.* = .{ .gpa = gpa, .vt = decoded.toOwned(), .stream = undefined, .changes = kept[0] +% 1, .read = kept[1], .resize_to = kept[2] };
+ s.* = .{ .gpa = gpa, .vt = decoded.toOwned(), .stream = undefined };
// Short of room for its sequence in flight it goes on without it (lost
// at the next cut), as ghostty's stream does: not worth a terminal.
_ = install(s, decoded.continuation, &saved);
@@ -470,13 +469,12 @@ pub fn grid(state: ?*const State) Term.Grid {
}
/// What pardes made of a terminal's stream that its emulator does not hold
-/// (the OSC 133 cycle, MarkedHandler), for a replica's delta: phase u8,
-/// started, prompts, declined u32, continuation and lost u8, a finished
-/// command's seq u32 and status i32 (all ones: none; i32 min: no status).
-// ponytail: the output pins stay the authority's (its 9P pty/run reads them).
-pub const marks_len = 1 + 4 * 3 + 2 + 4 + 4;
+/// (the OSC 133 cycle, MarkedHandler), as bytes its digest holds: phase u8, started, prompts, declined u32, continuation
+/// and lost u8, a finished command's seq u32 and status i32 (all ones:
+/// none; i32 min: no status).
+const marks_len = 1 + 4 * 3 + 2 + 4 + 4;
-pub fn marksOf(state: *const State, buf: *[marks_len]u8) []const u8 {
+fn marksOf(state: *const State, buf: *[marks_len]u8) []const u8 {
const m = &state.stream.handler;
var w: std.Io.Writer = .fixed(buf);
w.writeByte(@backingInt(m.phase)) catch unreachable;
@@ -487,121 +485,43 @@ pub fn marksOf(state: *const State, buf: *[marks_len]u8) []const u8 {
return w.buffered();
}
-/// A replica's terminal takes its authority's marks (`marksOf`).
-pub fn takeMarks(state: *State, bytes: []const u8) void {
- if (bytes.len != marks_len) return;
- const m = &state.stream.handler;
- m.phase = @fromBackingInt(@intCast(bytes[0]));
- m.started = std.mem.readInt(u32, bytes[1..5], .little);
- m.prompts = std.mem.readInt(u32, bytes[5..9], .little);
- m.declined = std.mem.readInt(u32, bytes[9..13], .little);
- m.continuation = bytes[13] != 0;
- m.lost = bytes[14] != 0;
- const seq = std.mem.readInt(u32, bytes[15..19], .little);
- const status = std.mem.readInt(i32, bytes[19..23], .little);
- 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, tr: *screen_state.Track, peer: *screen_state.Peer, out: *std.Io.Writer) !bool {
- var marks: [marks_len]u8 = undefined;
- return screen_state.encode(enc, tr, 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, tr: *screen_state.Track, lo: u64, hi: u64, out: *std.Io.Writer) !void {
- return screen_state.encodeRows(enc, tr, &state.vt, lo, hi, out);
-}
-
-/// What a session's authority keeps to encode its terminals for its
-/// peers, and what it keeps of one terminal for them: made and freed.
-pub fn encoder(gpa: std.mem.Allocator) !*screen_state.Encoder {
- const e = try gpa.create(screen_state.Encoder);
- e.* = .init(gpa);
- return e;
-}
-
-pub fn encoderFree(e: *screen_state.Encoder) void {
- const gpa = e.gpa;
- e.deinit();
- gpa.destroy(e);
-}
-
-pub fn track(gpa: std.mem.Allocator) !*screen_state.Track {
- const t = try gpa.create(screen_state.Track);
- t.* = .init(gpa);
- return t;
-}
-
-/// A replica's side of one terminal: made, freed, where its active area
-/// begins, and the history rows `lo..hi` it does not hold.
-pub fn replica(gpa: std.mem.Allocator) !*screen_state.Replica {
- const r = try gpa.create(screen_state.Replica);
- r.* = .{};
- return r;
-}
-
-pub fn replicaFree(r: *screen_state.Replica, gpa: std.mem.Allocator) void {
- r.deinit(gpa);
- gpa.destroy(r);
-}
-
-pub fn replicaTop(r: *const screen_state.Replica) u64 {
- return r.top;
-}
-
-pub fn missing(r: *const screen_state.Replica, lo: u64, hi: u64, out: *std.ArrayList([2]u64), gpa: std.mem.Allocator) !void {
- return r.missing(lo, hi, out, gpa);
-}
-
-/// What `track` kept of its versions, freed; `state` null when its pane is
-/// gone with the emulator.
-/// A peer's track of it let go, and freed (`state` null: it is gone).
-pub fn untrack(t: *screen_state.Track, gpa: std.mem.Allocator, state: ?*State) void {
- t.deinit(gpa, if (state) |s| &s.vt else null);
- gpa.destroy(t);
-}
-
-/// 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) !Term.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);
+/// What a row shows, written out value by value: its flags, then each
+/// cell's word without its page's ids, its style, its grapheme and its
+/// hyperlink's URI.
+fn dumpRow(page: *ghostty_vt.page.Page, row: *ghostty_vt.page.Row, cols: u16, w: *std.Io.Writer) !void {
+ try w.print("{d}:", .{@as(u8, @intFromBool(row.wrap)) | @as(u8, @intFromBool(row.wrap_continuation)) << 1 | @as(u8, @backingInt(row.semantic_prompt)) << 2});
+ const all = page.getCells(row);
+ for (all[0..@min(cols, all.len)]) |*c| {
+ var word = c.*;
+ word.style_id = 0;
+ try w.print(" {x}", .{@as(u64, @bitCast(word))});
+ if (c.style_id != 0) try ghostty_vt.snapshot.style.encode(page.styles.get(page.memory, c.style_id).*, w);
+ if (c.hasGrapheme()) for (page.lookupGrapheme(c).?) |cp| try w.print("+{x}", .{cp});
+ if (c.hyperlink) if (page.lookupHyperlink(c)) |id| try w.print("@{s}", .{page.hyperlink_set.get(page.memory, id).uri.slice(page.memory)});
+ }
+ try w.writeByte('\n');
}
-/// 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);
+/// What an emulator shows, cell for cell: the terminal-wide state, the
+/// cursor, the history's extent and the viewport, the active screen's rows
+/// (test/replicas.zig compares a client's terminal with its session's by it).
+pub fn dumpScreen(t: *ghostty_vt.Terminal, w: *std.Io.Writer) !void {
+ const screen = t.screens.active;
+ const sb = t.screens.get(.primary).?.pages.scrollbar();
+ try w.print("{d}x{d} {s} cursor {d},{d} {s} {} {s} title {s} pwd {s} scrollbar {d} {d} {d}\n", .{
+ t.cols, t.rows, @tagName(t.screens.active_key),
+ screen.cursor.x, screen.cursor.y, @tagName(screen.cursor.cursor_style),
+ screen.cursor.pending_wrap, @tagName(screen.cursor.semantic_content), t.getTitle() orelse "",
+ t.getPwd() orelse "", sb.total, sb.offset,
+ sb.len,
+ });
+ try w.writeAll(std.mem.asBytes(&t.modes.values));
+ try w.writeAll(std.mem.asBytes(&screen.kitty_keyboard));
+ try w.print(" mouse {s} {s} {s}\n", .{ @tagName(t.flags.mouse_event), @tagName(t.flags.mouse_format), @tagName(t.mouse_shape) });
+ for (t.colors.palette.current) |c| try w.print("{x}{x}{x}", .{ c.r, c.g, c.b });
+ try w.writeByte('\n');
+ var it = screen.pages.rowIterator(.right_down, .{ .active = .{} }, null);
+ while (it.next()) |p| try dumpRow(p.node.page(), p.rowAndCell().row, t.cols, w);
}
/// Its view to row `at` of its history (from the top), or onto its output.
@@ -612,43 +532,26 @@ pub fn viewTo(state: *State, at: ?usize) void {
/// Its view moved by `delta` rows (negative scrolls back).
pub fn scroll(state: *State, delta: i32) void {
state.vt.screens.active.scroll(.{ .delta_row = delta });
- state.changes +%= 1;
}
/// Its view back onto the output.
pub fn follow(state: *State) void {
- const moved = state.vt.screens.active.pages.viewport != .active;
state.vt.screens.active.scroll(.active);
- state.changes +%= @intFromBool(moved);
}
-/// Its grid reflowed to `cols` by `rows`, now or, `later`, when
-/// `resizeDeferred` is called. A failed reflow keeps the grid it had
-/// rather than dropping a scrollback; the next resize retries with the
-/// same numbers.
-pub fn resize(state: *State, cols: u16, rows: u16, later: bool) void {
- if (later) {
- state.resize_to = .{ .cols = cols, .rows = rows };
- return;
- }
+/// Its grid reflowed to `cols` by `rows`. A failed reflow keeps the grid
+/// it had rather than dropping a scrollback; the next resize retries with
+/// the same numbers.
+pub fn resize(state: *State, cols: u16, rows: u16) void {
reflow(state, cols, rows);
}
-/// The size `resize` left for later, made; whether there was one.
-pub fn resizeDeferred(state: *State) bool {
- const size = state.resize_to orelse return false;
- state.resize_to = null;
- reflow(state, size.cols, size.rows);
- return true;
-}
-
/// Its grid reflowed, and its view a row of its history again, as `viewTo`
/// and `grid` have it: ghostty's view follows a cell, which a widening
/// can leave mid-row (a wrapped line's second row joined to its first) and
/// the next narrowing carries a row down, where a view put back at its row
/// (a replica's rollback, core/replica.zig `putViews`) stays.
fn reflow(state: *State, cols: u16, rows: u16) void {
- state.changes +%= 1;
state.vt.resize(state.gpa, .{ .cols = cols, .rows = rows }) catch {};
inline for (.{ .primary, .alternate }) |which| if (state.vt.screens.get(which)) |screen| {
if (screen.pages.viewport == .pin) screen.pages.viewport_pin.x = 0;
@@ -891,7 +794,6 @@ pub fn revive(state: *State) void {
/// then apply different views.
fn ingest(state: *State, bytes: []const u8) void {
state.stream.nextSlice(bytes);
- state.changes +%= 1;
}
const RowPin = struct { pin: ?*ghostty_vt.Pin = null, offset: i32 = 0 };
@@ -1227,12 +1129,6 @@ pub fn editRows(state: *State, arena: std.mem.Allocator, first: usize, count: us
return shell;
}
-/// A step read its rows (its history too): a replica replaying the step
-/// must hold them (`State.read`).
-pub fn markRead(state: *State) void {
- state.read = true;
-}
-
/// Its rows from the top of its history as text, a prompt's own cells cut
/// off the rows it starts (what typed text stays), joined by '\n' in
/// `text` with `rows` slices into it and one empty row after them, the
@@ -1616,10 +1512,10 @@ test "a view put back at the row it reports is the view it was, through a reflow
// Lines two rows long at 20 columns, one at 40.
for (0..30) |_| ingest(s, "abcdefghijklmnopqrstuvwxyz0123\r\n");
viewTo(s, 1);
- resize(s, 40, 2, false);
+ resize(s, 40, 2);
}
viewTo(put, grid(put).view);
- for ([_]*State{ left, put }) |s| resize(s, 20, 2, false);
+ for ([_]*State{ left, put }) |s| resize(s, 20, 2);
try std.testing.expectEqual(grid(left), grid(put));
}
@@ -1751,8 +1647,8 @@ fn feedReflowing(s: *State, bytes: []const u8, from: usize, to: usize, stops: [2
const rows = s.vt.rows;
var at = from;
while (at < to) {
- if (at == stops[0]) resize(s, cols / 2 + 1, rows + 3, false);
- if (at == stops[1]) resize(s, cols * 2 - 2, rows - 3, false);
+ if (at == stops[0]) resize(s, cols / 2 + 1, rows + 3);
+ if (at == stops[1]) resize(s, cols * 2 - 2, rows - 3);
var end = @min(to, at + 4096);
for (stops) |stop| if (at < stop and stop < end) {
end = stop;
diff --git a/core/views.zig b/core/views.zig
index 704fc859..663610c3 100644
--- a/core/views.zig
+++ b/core/views.zig
@@ -423,6 +423,7 @@ pub fn closeKeeping(p: *Pardes, k: u8) void {
inline for (sized ++ laid_out) |name| @field(v, name) = @field(p.views[k].?, name);
v.jumps.force = force;
for (p.panes) |s| if (s) |pane| {
+ if (pane.sized_by == k) pane.sized_by = other;
if (pane.pv_known & bit(other) != 0 and pane.pv[other].body.sels.len > 0) p.gpa.free(pane.pv[other].body.sels);
pane.pv[other] = fresh(pane);
pane.pv_known |= bit(other);
@@ -447,8 +448,10 @@ fn dropView(p: *Pardes, k: u8) void {
}
pane.pv[k].body.sels = &.{};
pane.pv_known &= ~bit(k);
- // A name it was drafting goes with it.
+ // A name it was drafting goes with it; a terminal it sized keeps
+ // its size (Pardes.sizes), for no view that is not typed in.
if (pane.prompt == .name and pane.prompt_view == k) pane.closePrompt();
+ if (pane.sized_by == k) pane.sized_by = null;
};
p.views_open &= ~bit(k);
p.views_away &= ~bit(k);
@@ -700,10 +703,28 @@ test "a terminal shown at two sizes takes the size of the view that typed into i
try testing.expectEqual(big, .{ term.cols, term.rows });
p.update(.{ .key = .{ .cp = Key.right } });
try testing.expectEqual(small, .{ term.cols, term.rows });
- // That view gone, the one left sizes it.
+ // Its pty in pixels at the cell of the view that sizes it, whichever
+ // is live.
+ p.views[k.index()].?.cell_pixels = .{ .w = 10, .h = 20 };
+ p.update(.{ .key = .{ .cp = Key.right } });
+ p.toView(k);
+ p.update(.{ .key = .{ .cp = Key.right } });
+ p.toView(.at(0));
+ try testing.expectEqual(pardes.PtySize{ .cols = big[0], .rows = big[1], .w_px = big[0] * 10, .h_px = big[1] * 20 }, p.ptySize(.at(p.view().active), null));
+ p.update(.{ .key = .{ .cp = Key.right } });
+ try testing.expectEqual(pardes.PtySize{ .cols = small[0], .rows = small[1], .w_px = small[0] * 8, .h_px = small[1] * 16 }, p.ptySize(.at(p.view().active), null));
+ // That view gone, the size stays until the one left types into it; a
+ // view opened in its place sizes nothing it has not typed into.
p.toView(k);
p.closeView(.at(0));
try testing.expectEqual(k.index(), p.live);
+ try testing.expectEqual(small, .{ term.cols, term.rows });
+ const again = p.openView().?;
+ p.toView(again);
+ p.update(.{ .resize = .{ .cols = 100, .rows = 30 } });
+ try testing.expectEqual(small, .{ term.cols, term.rows });
+ p.toView(k);
+ p.update(.{ .key = .{ .cp = Key.right } });
try testing.expectEqual(big, .{ term.cols, term.rows });
}