diff options
| -rw-r--r-- | abi/wire.zig | 4 | ||||
| -rw-r--r-- | core/Core.zig | 8 | ||||
| -rw-r--r-- | core/Jump.zig | 2 | ||||
| -rw-r--r-- | core/Term.zig | 77 | ||||
| -rw-r--r-- | core/Turn.zig | 78 | ||||
| -rw-r--r-- | core/dump.zig | 4 | ||||
| -rw-r--r-- | core/edit.zig | 12 | ||||
| -rw-r--r-- | core/jj.zig | 34 | ||||
| -rw-r--r-- | core/keys.zig | 2 | ||||
| -rw-r--r-- | core/locations.zig | 4 | ||||
| -rw-r--r-- | core/ninep/pty.zig | 6 | ||||
| -rw-r--r-- | core/panes.zig | 48 | ||||
| -rw-r--r-- | core/replica.zig | 187 | ||||
| -rw-r--r-- | core/rollback.zig | 36 | ||||
| -rw-r--r-- | core/root.zig | 1 | ||||
| -rw-r--r-- | core/surface.zig | 10 | ||||
| -rw-r--r-- | core/tape.zig | 36 | ||||
| -rw-r--r-- | dev/Inbox.zig | 8 | ||||
| -rw-r--r-- | dev/glide.zig | 51 | ||||
| -rw-r--r-- | dev/gui/gui.zig | 255 | ||||
| -rw-r--r-- | dev/tui/tui.zig | 14 | ||||
| -rw-r--r-- | runtime/9p_io.zig | 7 | ||||
| -rw-r--r-- | test/daemon.py | 6 | ||||
| -rw-r--r-- | test/kitty.zig | 4 | ||||
| -rw-r--r-- | test/perf.zig | 5 | ||||
| -rw-r--r-- | test/replicas.zig | 77 | ||||
| -rw-r--r-- | test/terminal.zig | 8 |
27 files changed, 764 insertions, 220 deletions
diff --git a/abi/wire.zig b/abi/wire.zig index 55a08909..8949edff 100644 --- a/abi/wire.zig +++ b/abi/wire.zig @@ -12,7 +12,9 @@ const build_info = @import("build_info"); /// 31: where a view stands in a terminal's history is the view's: a pane's /// `scrolled_to` (and its share's in each view) in the dump and the digest, -/// the emulator's own view out of both (its `Parts.view` gone); +/// the emulator's own view out of both (its `Parts.view` gone); and the +/// core's count of its emulators' writes (`outside`) in both, which the +/// replica engine's one question of a unit reads; /// 30: the terminals' one road: the screen-state messages are retired (a /// replica's `screen_ack`, 0x04, and the session's `screen`, 0x06: gaps), /// a welcome says no road (its `bytes` byte gone), and a pane's diff --git a/core/Core.zig b/core/Core.zig index a35cea8e..2c6567ed 100644 --- a/core/Core.zig +++ b/core/Core.zig @@ -258,6 +258,10 @@ n_look_src: usize = 0, look_walk_owner: ?u32 = null, /// hands out Pane.serial; monotonic, never reused next_serial: u32 = 0, +/// The writes of its terminals' emulators, which no rollback copy holds +/// (Term.Outside): digested, dumped and copied as any field, so the same on +/// every side; the replica engine's one question of a unit reads it. +outside: pardes.Term.Outside = .{}, /// The column whose tag the running command came from, while it runs: /// the column acme's commands take from their Text's col. exec_column: ?usize = null, @@ -1908,7 +1912,7 @@ pub fn sync(p: *Pardes) void { // What the terminal answers its program (a cursor report, its // attributes) goes as typed bytes go: behind whatever is still // queued for its pty, never ahead of it nor dropped. - if (pane.terminal) |state| p.emitWrite(id, pardes.Term.replies(state)); + if (pane.terminal) |state| p.emitWrite(id, pardes.Term.replies(&p.outside, state)); const r = v.rects[id]; // The session's part of the pane's view geometry (File.geometry), // and its context declarations. @@ -1974,7 +1978,7 @@ pub fn sync(p: *Pardes) void { // doc panes have no pty/emulator grid to reflow; just record // the size so bodyText renders the right number of rows if (pane.isTerminal()) { - pane.resizeGrid(p.live, cols, rows); + pane.resizeGrid(p, cols, rows); p.shell_rows.markStale(pane); // reflow moved every row p.emit(.{ .resize_pty = .{ .pane = .at(id), .cols = cols, .rows = rows } }); pane.fs.winsize = null; diff --git a/core/Jump.zig b/core/Jump.zig index aa633044..b68da32d 100644 --- a/core/Jump.zig +++ b/core/Jump.zig @@ -410,7 +410,7 @@ test "jump history terminal rectangle follows output and clears on reflow" { try std.testing.expectEqualStrings("alpha", try edit.selectionText(p, pane, pane.sel[0])); for (0..40) |_| p.update(.{ .output = .{ .pane = .at(0), .bytes = "more output\r\n" } }); try std.testing.expectEqualStrings("alpha", try edit.selectionText(p, pane, pane.sel[0])); - pane.resizeGrid(p.live, pane.cols - 1, pane.rows); + pane.resizeGrid(p, pane.cols - 1, pane.rows); try std.testing.expect(pane.pointerSelection(pane.sel[0]) == null); try std.testing.expectEqual(.none, pane.sel[0].state); } diff --git a/core/Term.zig b/core/Term.zig index b82017f6..f0329852 100644 --- a/core/Term.zig +++ b/core/Term.zig @@ -14,11 +14,15 @@ const dump = @import("dump.zig"); const File = @import("File.zig"); const iface = plain.term; -/// Writes into this process's emulators (a read fed, a grid reflowed, one -/// opened, closed, loaded or made again): whether a unit's -/// replay made one, the replica engine's one rule (core/replica.zig -/// `confirm`) reads across that replay, on its one thread. -pub var writes: u32 = 0; +/// The writes of a core's emulators, which live outside its rollback copy +/// (`Pardes.outside`): a field of the core, so copied with a speculation, +/// digested and dumped, a function of the tape, the same on every side (one +/// side's emulator written where the others' are not is a digest that says +/// `outside`). Every write below takes it and counts, and so does a write a +/// speculation owes (`resize`): over an input's apply, the count moved is +/// "this input wrote, or owes, state outside the copy", the one question +/// core/replica.zig `confirm` asks a unit. A load sets it from the dump. +pub const Outside = struct { n: u64 = 0 }; /// The reloads this process made (a join's, on every side) and their time, /// for the soak's join line (test/replicas.zig `--bytes`). pub var reloads: struct { n: u32 = 0, ns: u64 = 0, worst_ns: u64 = 0 } = .{}; @@ -67,6 +71,11 @@ pub const State = struct { /// same snapshot again from the dump. written: bool = true, + /// Not walked by a replica's rollback copy (core/rollback.zig): its + /// emulator is written by confirmed units alone, each write counted + /// (Pardes.outside), never by a speculation, so no copy holds any of it. + pub const outside_copy = {}; + /// The emulator as its program has made it, for the replay digest. pub fn digest(s: *const State, h: *walk.Hasher) void { the().digest(s.impl, h); @@ -96,7 +105,6 @@ pub const State = struct { const parts = try walk.load(iface.Parts, arena.allocator(), bytes[8..][0..n], null); o.media(media); out.* = .{ .impl = try o.load(gpa, bytes[8 + n ..], &parts) }; - writes +%= 1; } }; @@ -112,13 +120,13 @@ pub fn emulatorOf(s: *State) *@import("term").terminal.State { /// A new terminal, `cols` by `rows`, allocated with `gpa` (its own from /// then on). Refused in a core without one: `error.NoTerminal`, which a /// word reports as `none` says it. -pub fn open(gpa: std.mem.Allocator, cols: u16, rows: u16) !*State { +pub fn open(outside: *Outside, gpa: std.mem.Allocator, cols: u16, rows: u16) !*State { const o = ops orelse return error.NoTerminal; const s = try gpa.create(State); errdefer gpa.destroy(s); o.media(media); s.* = .{ .impl = try o.open(gpa, cols, rows) }; - writes +%= 1; + outside.n +%= 1; return s; } @@ -137,9 +145,9 @@ fn readMedium(read: *const fn (*const anyopaque) iface.MediumError![]u8, ctx: *c /// It and what it holds, freed, all of it with its own allocator (the /// one it was opened with): the allocator a caller hands is not used. -pub fn close(s: *State, _: std.mem.Allocator) void { +pub fn close(outside: *Outside, s: *State) void { const own = the().gpa(s.impl); - writes +%= 1; + outside.n +%= 1; the().close(s.impl); own.destroy(s); } @@ -148,8 +156,8 @@ pub fn close(s: *State, _: std.mem.Allocator) void { /// every side does it, so that all hold the same pages (ghostty prunes its /// history a page at a time, and a snapshot does not say how its rows were /// cut into pages). The snapshot's hash, which every side compares. -pub fn reload(s: *State) !u64 { - writes +%= 1; +pub fn reload(outside: *Outside, s: *State) !u64 { + outside.n +%= 1; const t0 = @import("FrameStats.zig").nowNs(); defer { reloads.n += 1; @@ -170,8 +178,8 @@ pub fn due(s: *const State) ?u64 { /// Loaded from a dump without its shell: its program's modes reset, its /// history marked off from what the next shell prints. -pub fn revive(s: *State) void { - writes +%= 1; +pub fn revive(outside: *Outside, s: *State) void { + outside.n +%= 1; s.written = true; the().revive(s.impl); } @@ -190,8 +198,8 @@ pub fn stop() void { /// One read of its program's output (`Told` says where the tracked rows /// went), every view's place in its history carried through it (`resize`). -pub fn feed(s: *State, bytes: []const u8, tracked: []const i32, rows: []i32, erased: []bool, places: []?usize) Told { - writes +%= 1; +pub fn feed(outside: *Outside, s: *State, bytes: []const u8, tracked: []const i32, rows: []i32, erased: []bool, places: []?usize) Told { + outside.n +%= 1; s.written = true; return the().feed(s.impl, bytes, tracked, rows, erased, places); } @@ -205,8 +213,11 @@ pub fn grid(s: ?*const State) Grid { /// Its grid reflowed, every view's place in its history (Pane.scrolled_to, /// each view's) carried through it as ghostty carries a view of its own. -pub fn resize(s: *State, cols: u16, rows: u16, places: []?usize) void { - writes +%= 1; +/// A speculation owes it (counted, not made): its input is replayed when it +/// is confirmed (core/replica.zig `confirm`), never taken as speculated. +pub fn resize(outside: *Outside, s: *State, cols: u16, rows: u16, places: []?usize) void { + outside.n +%= 1; + if (tape.speculating()) return; s.written = true; the().resize(s.impl, cols, rows, places); } @@ -218,8 +229,10 @@ pub fn cellPixels(s: *State, w: u32, h: u32) void { /// What it answered its program since the last call, to be written to its /// pty. -pub fn replies(s: *State) []const u8 { - return the().replies(s.impl); +pub fn replies(outside: *Outside, s: *State) []const u8 { + const r = the().replies(s.impl); + if (r.len > 0) outside.n +%= 1; + return r; } // ---- input ---- @@ -277,7 +290,8 @@ pub fn commandOutput(s: ?*State, gpa: std.mem.Allocator, max_rows: usize) !Comma /// The shell exited in the middle of a command: its output ends at the /// cursor. -pub fn endOutputHere(s: *State) void { +pub fn endOutputHere(outside: *Outside, s: *State) void { + outside.n +%= 1; the().endOutputHere(s.impl); } @@ -399,14 +413,14 @@ pub fn hasImages(s: ?*const State) bool { /// 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" }, + .{ "open", "dump.zig:1 panes.zig:1", "WRITE: a terminal made by a step (a shell's pane) or a load, counted (`Outside`); a speculation is refused it" }, + .{ "close", "panes.zig:1", "WRITE: let go by a step that closes its pane, counted; a speculation is refused it" }, .{ "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, every view's place (Pane.scrolled_to, in the copy) carried through it; a unit that feeds lets a copy held ahead go (`Term.writes`), so none is replayed (keys.zig's: a test's)" }, - .{ "resize", "panes.zig:1", "WRITE: a step's reflow, every view's place carried through it; a speculation owes it (`touchTerminal`): its input is taken when confirmed, never as speculated" }, + .{ "feed", "keys.zig:1 panes.zig:3 replica.zig:1", "WRITE: the pty's bytes in a unit, every side in the tape's order, every view's place (Pane.scrolled_to, in the copy) carried through it, counted: a unit that moved the count is applied once, to the confirmed core (replica.zig `confirm`); a speculation is refused it (keys.zig's, replica.zig's: tests')" }, + .{ "resize", "panes.zig:1", "WRITE: a step's reflow, every view's place carried through it, counted; a speculation owes it (counted, not made): 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)" }, + .{ "replies", "Core.zig:1", "WRITE: a step drains the reply buffer (in the digest), counted when it held any (the feed's own unit, which filled it); only the session writes it to the pty (pty_write is off the tape)" }, // ---- reads by a step: in the digest ---- .{ "grid", "Core.zig:2 ansi.zig:3 body_layer.zig:3 draw.zig:2 dump.zig:4 echo.zig:8 exec.zig:2 layout.zig:2 panes.zig:5 replica.zig:2", "READ: the size, the history's length, the cursor: in the digest (a view's place is its pane's; 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 panes.zig:2 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; panes.zig: a view scrolls no history on the alternate screen)" }, @@ -502,6 +516,17 @@ test "every call of the core's into a terminal is listed with its rule (S1): a n try std.testing.expectEqual(@as(usize, 0), wrong); } +// Every WRITE above takes its core's count first (`Outside`): a call +// cannot be written without one, so the count cannot be forgotten at a call +// site (the compiler holds that); that a new op is listed as a WRITE is the +// test's above and a reviewer's. +comptime { + for (calls) |c| if (std.mem.startsWith(u8, c[2], "WRITE")) { + const params = @typeInfo(@TypeOf(@field(@This(), c[0]))).@"fn".param_types; + if (params.len == 0 or params[0] != *Outside) @compileError("Term." ++ c[0] ++ " writes an emulator: it takes its core's count (`*Outside`) first"); + }; +} + fn listedCall(name: []const u8, file: []const u8) bool { for (calls) |c| { if (!std.mem.eql(u8, c[0], name)) continue; diff --git a/core/Turn.zig b/core/Turn.zig index 249c6795..d0e49d44 100644 --- a/core/Turn.zig +++ b/core/Turn.zig @@ -43,6 +43,15 @@ restores: u64 = 0, /// Bumped each time a language server's answer (or its lack) is taken /// in (`lspResponse`): a write that asked one waits for this. lsp_answers: u64 = 0, +/// Reads out of the ptys (a pane's reader, as it reads) and those applied +/// or dropped since (`outputApplied`): a write waits for the output read +/// before it (`awaitOutput`). +reads: std.atomic.Value(u64) = .init(0), +applied: std.atomic.Value(u64) = .init(0), +/// The editor gave the turn up to wait for input (`listen`), not for a +/// call of its own (`rest`, `yield`: a save through its own mount, whose +/// write it would never answer applying output meanwhile). +listening: bool = false, /// All of the above, and `out` reaching zero. settled: std.Io.Condition = .init, /// Every `yield`, ever: a replica's step makes none (each syscall of its @@ -69,12 +78,22 @@ pub fn rest(t: *Turn) void { t.release(); } +/// The editor is about to wait for input, the output its readers read +/// among it (its loop's wait): `rest`, and a write may wait for that +/// output meanwhile (`awaitOutput`). +pub fn listen(t: *Turn) void { + if (t.io == null) return; + t.listening = true; + t.release(); +} + /// The editor takes the turn back -- once every step that is out in a /// syscall has returned, since a step of the editor's may change what /// those still point into. pub fn wake(t: *Turn) void { const io = t.io orelse return; t.mutex.lockUncancelable(io); + t.listening = false; while (t.out != 0) t.settled.waitUncancelable(io, &t.mutex); } @@ -123,6 +142,32 @@ pub fn bump(t: *Turn, counter: *u64) void { t.settled.broadcast(io); } +/// A pty's read applied, or dropped: a write waiting on it told. +pub fn outputApplied(t: *Turn) void { + _ = t.applied.fetchAdd(1, .acq_rel); + if (t.io) |io| t.settled.broadcast(io); +} + +/// With the turn: waits, turn given up meanwhile, until every read out of +/// a pty before now is applied, as a terminal shows a program's output +/// before what it led to: `cmd | pardes -` typed in a pane writes its +/// pager after the shell echoed the line and started the command, and +/// the editor, a read a step, could still hold that echo (a client's keys +/// come a step each, so a shell's echo comes a key a read): the pager's +/// layout then saw the shell's line not yet ended, and its emulator's +/// resize cleared that line as a prompt the shell would draw again +/// (ghostty's Screen.clearPromptForRedraw). Only while the editor waits +/// in its loop (`listening`): resting in a call of its own it applies +/// nothing, and the request goes first, as before. A read its reader +/// drops off the turn wakes nobody: seen at the next recheck. +pub fn awaitOutput(t: *Turn) void { + const mark = t.reads.load(.acquire); + while (t.listening and t.applied.load(.acquire) < mark) t.settled.waitTimeout(t.io.?, &t.mutex, .{ .duration = .{ .raw = .fromMilliseconds(25), .clock = .awake } }) catch |err| switch (err) { + error.Timeout => {}, + error.Canceled => return, + }; +} + /// With the turn: waits, turn given up meanwhile, until `counter` has /// moved past `seen`; stopping ends the wait early. pub fn awaitPast(t: *Turn, counter: *const u64, seen: u64) void { @@ -139,3 +184,36 @@ fn release(t: *Turn) void { t.mutex.unlock(t.io.?); if (woken) if (t.wake_parked) |f| f(t.wake_ctx); } + +test "a write waits for the output read before it while the editor listens, not while it rests in a call of its own" { + const io = std.testing.io; + var t: Turn = .{}; + t.start(io); + _ = t.reads.fetchAdd(2, .acq_rel); + // A save through its own mount: the editor rests in it, applies + // nothing, and the write it waits on is served at once. + t.rest(); + _ = t.take(); + t.awaitOutput(); + try std.testing.expectEqual(@as(u64, 0), t.applied.load(.acquire)); + t.give(); + // Its loop's wait: the write waits for both reads, applied meanwhile. + t.wake(); + t.listen(); + const editor = try std.Thread.spawn(.{}, struct { + fn apply(turn: *Turn) void { + for (0..2) |_| { + turn.wake(); + turn.outputApplied(); + turn.listen(); + } + } + }.apply, .{&t}); + _ = t.take(); + t.awaitOutput(); + try std.testing.expectEqual(@as(u64, 2), t.applied.load(.acquire)); + t.give(); + editor.join(); + t.wake(); + t.stop(); +} diff --git a/core/dump.zig b/core/dump.zig index 547f9f7d..d09f18c2 100644 --- a/core/dump.zig +++ b/core/dump.zig @@ -536,7 +536,7 @@ fn loadImage(gpa: std.mem.Allocator, opts: Options, bytes: []const u8, notes: ?* fn ensureKind(p: *Pardes, pane: *pardes.panes.Pane) !void { if (pane.terminal != null or pane.file != null or pane.addon != null or pane.pdf != null) return; if (p.tape.authorityOnly("open a terminal")) return error.OutOfMemory; - pane.terminal = try pardes.Term.open(pardes.panes.emulatorGpa(p.gpa), @max(1, pane.cols), @max(1, pane.rows)); + pane.terminal = try pardes.Term.open(&p.outside, pardes.panes.emulatorGpa(p.gpa), @max(1, pane.cols), @max(1, pane.rows)); } /// The panes a column lists that are not there (another build's dump left @@ -710,7 +710,7 @@ fn revivePane(p: *Pardes, id: usize, pane: *pardes.panes.Pane, was_on_disk: bool // shell was, ran and said is gone with it (the REPL it ran, the // Term+ word naming it), and the pane waits for the new one like // any new terminal (a line queued for the old one goes to it). - pardes.Term.revive(pane.terminal.?); + pardes.Term.revive(&p.outside, pane.terminal.?); pane.shell_spoke = false; pane.had_shell = false; pane.shell_failed = false; diff --git a/core/edit.zig b/core/edit.zig index f3a87e57..70b765cc 100644 --- a/core/edit.zig +++ b/core/edit.zig @@ -427,8 +427,13 @@ pub var drawing = false; /// A terminal's rows as text (`Term.rows`), kept for one pane until its /// grid moves. Returned slices remain valid until the next cache rebuild -/// or reset. +/// or reset. A replica's rollback copy holds it as any state: its text and +/// rows are made whole and freed whole, never written, so the copy pins +/// them (blobs, freed raw) and puts the cache back with the core: no +/// emulator is written while a copy is held (replica.zig `confirm`: a unit +/// that writes one lets the copy go or is applied after it is put back). pub const RowsCache = struct { + pub const replica = .{ .blob = .{ "text", "rows", "text_alloc" } }; /// whose grid this describes; null = the slot is free pane: ?*const Pane = null, /// the rows joined by '\n' — `flatSurface` hands this back verbatim @@ -442,8 +447,8 @@ pub const RowsCache = struct { stale: bool = false, pub fn reset(c: *RowsCache, gpa: std.mem.Allocator) void { - if (c.text_alloc.len > 0) gpa.free(c.text_alloc); - if (c.rows.len > 0) gpa.free(c.rows); + pardes.memory.freeRaw(gpa, c.text_alloc); + pardes.memory.freeRaw(gpa, c.rows); c.* = .{}; } @@ -470,7 +475,6 @@ const empty_grid = [1][]const u8{""}; /// in `Pardes.shell_rows` while its grid holds still. pub fn shellRows(p: *Pardes, pane: *Pane) ![]const []const u8 { const state = pane.terminal orelse return &empty_grid; - pardes.tape.touchTerminal(); 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 4687a89e..59e0e21d 100644 --- a/core/jj.zig +++ b/core/jj.zig @@ -335,8 +335,8 @@ pub const Line = struct { nmarks: u16 = 0, }; -/// The lanes a row shows at most: the ruled gutter fits three. -pub const levels = 3; +/// The lanes a row shows at most (a window's strips the same). +pub const levels = pardes.Lane.levels; pub const PinIndex = enum(u16) { none = std.math.maxInt(u16), @@ -2554,6 +2554,36 @@ test "the lanes ride with the text: a line typed in a nested block is nobody's, try testing.expectEqual(pardes.tape.digestOf(a.core), pardes.tape.digestOf(r.core())); } +test "a client's own line opened over pinned changes, rolled back by the session's key first: the lanes it spliced under its copy are the copy's again, freed once; the client ends equal" { + 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 }, .{}); + defer a.deinit(); + 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}) })); + r.confirm(try a.local(.{ .command = "Changes ::@" })); + r.confirm(try a.local(.{ .command = "Look a.zig:4" })); + r.settle(); + const serial = a.core.panes[a.core.view().active].?.serial; + // The client opens a line below: an edit of the file, whose step splices + // the pinned lines' values (jj.edited) under the copy it takes. + const typed = try testing.allocator.dupe(u8, try r.input(.{ .key = .{ .cp = 'o', .text = "o" } })); + defer testing.allocator.free(typed); + try testing.expectEqual(@as(usize, 1), r.applied); + // The session's own key comes first: the copy put back, the `o` applied + // again over it, then confirmed. + r.confirm(try a.local(.{ .key = .{ .cp = 'k', .text = "k" } })); + r.settle(); + r.confirm(try a.take(typed)); + r.settle(); + try testing.expect(r.diverged == null); + try testing.expectEqualSlices(Line, answered(a.core, serial).?.lines, answered(r.core(), serial).?.lines); + try testing.expectEqual(pardes.tape.digestOf(a.core), pardes.tape.digestOf(r.core())); +} + /// Two functions four changes wrote: `fn` both, `f2` and `f3` rewrote /// f's line, `g2` g's: f three changes, g two. const Churned = struct { diff --git a/core/keys.zig b/core/keys.zig index 91cb2724..9afb983b 100644 --- a/core/keys.zig +++ b/core/keys.zig @@ -804,7 +804,7 @@ test "raw tty forwards Ctrl letters and former global shortcuts to the child" { } p.update(.{ .key = .{ .cp = Key.up } }); try std.testing.expectEqualStrings("\x1b[A", test_api.ptyBytes(p, null, &buf)); - _ = pardes.Term.feed(p.panes[0].?.terminal.?, "\x1b[?1h", &.{}, &.{}, &.{}, &.{}); // DECCKM + _ = pardes.Term.feed(&p.outside, p.panes[0].?.terminal.?, "\x1b[?1h", &.{}, &.{}, &.{}, &.{}); // DECCKM p.update(.{ .key = .{ .cp = Key.up } }); try std.testing.expectEqualStrings("\x1bOA", test_api.ptyBytes(p, null, &buf)); p.update(.{ .key = .{ .cp = Key.left, .ctrl = true } }); diff --git a/core/locations.zig b/core/locations.zig index 6972647e..10704912 100644 --- a/core/locations.zig +++ b/core/locations.zig @@ -25,6 +25,10 @@ pub const Row = struct { code_start: usize, colors: []u8 = &.{}, + /// Not walked by a replica's rollback copy (core/rollback.zig): made + /// again, never written, in a blob the copy pins whole. + pub const outside_copy = {}; + /// The replay digest's (core/walk.zig): all of it but its colours. They /// are painted from what this process has painted (the owner's /// highlights a frame made, the locations cache: both derived), so a diff --git a/core/ninep/pty.zig b/core/ninep/pty.zig index 923dab88..43973491 100644 --- a/core/ninep/pty.zig +++ b/core/ninep/pty.zig @@ -422,7 +422,7 @@ pub fn shellExited(p: *Pardes, pane: *Pane, status: ?u8) void { const code = status orelse return; if (waitingRun(p, pane)) |slot| if (slot.phase == .sent) { pane.fs.run = null; - if (pane.terminal) |state| pardes.Term.endOutputHere(state); + if (pane.terminal) |state| pardes.Term.endOutputHere(&p.outside, state); finish(p, slot, pane, code); }; var buf: [4]u8 = undefined; @@ -1015,10 +1015,10 @@ test "a run's answer says cut when its output's start is gone, and reads a bound // A resize between its start and end reflows the pins with the text. h = sh.send(p, node); sh.put(p, c ++ "one\r\ntwo\r\n"); - pane.resizeGrid(p.live, 50, 20); + pane.resizeGrid(p, 50, 20); sh.put(p, d ++ prompt); try testing.expectEqualStrings("exit 0\none\ntwo\n", sh.answered(p, node, h, into)); - pane.resizeGrid(p.live, pane.cols, pane.rows); + pane.resizeGrid(p, pane.cols, pane.rows); // A full-screen program leaves nothing on the primary screen, and a D // with no status is not a success. diff --git a/core/panes.zig b/core/panes.zig index 032cb4db..5bf6992a 100644 --- a/core/panes.zig +++ b/core/panes.zig @@ -762,8 +762,8 @@ pub const Pane = struct { var scrolled: Scrolled = .of(pane, p.live); defer scrolled.put(pane, p.live); if (!has_positions) { - _ = Term.feed(state, bytes, &.{}, &.{}, &.{}, scrolled.places()); - } else if (pane.followRows(state, bytes, scrolled.places())) if (paneIdOf(p, pane)) |id| p.setMessage(.at(id), positions_lost); + _ = Term.feed(&p.outside, state, bytes, &.{}, &.{}, &.{}, scrolled.places()); + } else if (pane.followRows(&p.outside, state, bytes, scrolled.places())) if (paneIdOf(p, pane)) |id| p.setMessage(.at(id), positions_lost); p.shell_rows.markStale(pane); } @@ -802,7 +802,7 @@ pub const Pane = struct { /// (the edit copy, the cursors and selections, their undo, the /// 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, places: []?usize) bool { + fn followRows(pane: *Pane, outside: *Term.Outside, state: *Term.State, bytes: []const u8, places: []?usize) bool { const Group = struct { overlay: ?*Text.EditBuffer, cursor: *i32, selection: *Text.CharSel }; var groups: [Text.history_max * 2 + 1]Group = undefined; groups[0] = .{ @@ -898,11 +898,11 @@ pub const Pane = struct { var rows_buf: [512]i32 = undefined; var erased_buf: [512]bool = undefined; // Out of memory for them, the read is parsed and nothing moves. - const track = if (n <= track_buf.len) track_buf[0..n] else pane.gpa.alloc(i32, n) catch return feedLost(state, bytes, places); + const track = if (n <= track_buf.len) track_buf[0..n] else pane.gpa.alloc(i32, n) catch return feedLost(outside, state, bytes, places); defer if (n > track_buf.len) pane.gpa.free(track); - const rows_after = if (n <= rows_buf.len) rows_buf[0..n] else pane.gpa.alloc(i32, n) catch return feedLost(state, bytes, places); + const rows_after = if (n <= rows_buf.len) rows_buf[0..n] else pane.gpa.alloc(i32, n) catch return feedLost(outside, state, bytes, places); defer if (n > rows_buf.len) pane.gpa.free(rows_after); - const erased_after = if (n <= erased_buf.len) erased_buf[0..n] else pane.gpa.alloc(bool, n) catch return feedLost(state, bytes, places); + const erased_after = if (n <= erased_buf.len) erased_buf[0..n] else pane.gpa.alloc(bool, n) catch return feedLost(outside, state, bytes, places); defer if (n > erased_buf.len) pane.gpa.free(erased_after); var k: usize = 0; for (spans[0..nspans]) |span| for ([_]i32{ span.row, span.row +| (span.rows - 1) }) |row| { @@ -913,7 +913,7 @@ pub const Pane = struct { track[k] = at.grid; k += 1; }; - const fed = Term.feed(state, bytes, track, rows_after, erased_after, places); + const fed = Term.feed(outside, state, bytes, track, rows_after, erased_after, places); 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; @@ -994,8 +994,8 @@ pub const Pane = struct { return t; } - fn feedLost(state: *Term.State, bytes: []const u8, places: []?usize) bool { - _ = Term.feed(state, bytes, &.{}, &.{}, &.{}, places); + fn feedLost(outside: *Term.Outside, state: *Term.State, bytes: []const u8, places: []?usize) bool { + _ = Term.feed(outside, state, bytes, &.{}, &.{}, &.{}, places); return true; } @@ -1016,21 +1016,19 @@ pub const Pane = struct { } /// Its terminal's grid reflowed to `cols` by `rows`, every open view's - /// place carried through it (`Scrolled`; `live` the live view's index). - pub fn resizeGrid(pane: *Pane, live: u8, 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 - // it owes the grid (`touchTerminal`): its input is replayed when - // confirmed, never taken as speculated (replica.zig `confirm`). + /// place carried through it (`Scrolled`). A client's speculation does + /// what its replay does (its selections) but the grid, which it owes + /// (Term.resize: counted, not made): its input is replayed when + /// confirmed, never taken as speculated (replica.zig `confirm`). + pub fn resizeGrid(pane: *Pane, p: *Pardes, cols: u16, rows: u16) void { const state = pane.terminal orelse return; if (cols != pane.cols) for (0..pane.sel.len) |button| { pane.clearPointerSelection(button); pane.sel[button].state = .none; }; - if (tape.speculating()) return tape.touchTerminal(); - var scrolled: Scrolled = .of(pane, live); - defer scrolled.put(pane, live); - Term.resize(state, cols, rows, scrolled.places()); + var scrolled: Scrolled = .of(pane, p.live); + defer scrolled.put(pane, p.live); + Term.resize(&p.outside, state, cols, rows, scrolled.places()); } /// The rows its terminal's top is passed over by in a view whose rect @@ -1188,7 +1186,7 @@ pub fn reloadTerminals(p: *Pardes) void { // frontend's draw sets its own view's between steps (ansi.zig), a // window's other than a terminal's, and the snapshot holds it. Term.cellPixels(state, p.view().cell_pixels.w, p.view().cell_pixels.h); - const mine: ?u64 = Term.reload(state) catch null; + const mine: ?u64 = Term.reload(&p.outside, state) catch null; p.shell_rows.markStale(pane); if (tape.value(.reload, sameHash, .{mine}) != mine) tape.diverged("a terminal reloaded at a join is not the session's"); }; @@ -1216,10 +1214,10 @@ pub fn createDoc(gpa: std.mem.Allocator, cols: u16, rows: u16) !*Pane { /// A terminal pane: a pane and its emulator. Slot ownership, serial /// assignment and spawn effects remain core lifecycle invariants. -pub fn createTerminal(gpa: std.mem.Allocator, cols: u16, rows: u16) !*Pane { +pub fn createTerminal(outside: *Term.Outside, gpa: std.mem.Allocator, cols: u16, rows: u16) !*Pane { const pane = try createDoc(gpa, cols, rows); errdefer gpa.destroy(pane); - pane.terminal = try Term.open(emulatorGpa(gpa), cols, rows); + pane.terminal = try Term.open(outside, emulatorGpa(gpa), cols, rows); pane.tty_filter = true; return pane; } @@ -1324,7 +1322,7 @@ pub fn teardownPane(p: *Pardes, pane: *Pane) void { // A pane with none (a file's, a picker's, a preview's) closes in a // speculation as anywhere. if (pane.terminal) |state| if (!p.tape.authorityOnly("close a terminal")) { - Term.close(state, p.gpa); + Term.close(&p.outside, state); pane.terminal = null; }; pane.clearCwd(); @@ -1361,7 +1359,7 @@ pub fn newShell(p: *Pardes, id: usize, cwd: []const u8) !*Pane { if (cwd.len > limits.host_path_cap) return error.PathTooLong; // A speculation opens no emulator: a terminal is the authority's to open. if (p.tape.authorityOnly("open a terminal")) return error.OutOfMemory; - const pane = try panes.createTerminal(p.gpa, p.view().screen_w, p.view().screen_h); + const pane = try panes.createTerminal(&p.outside, p.gpa, p.view().screen_w, p.view().screen_h); // Named by the directory it is started in from the first, so the // shell saying it is there is no rename (`new N /` then `rename`); // out of memory for it, the shell names it when it says. @@ -1394,7 +1392,7 @@ pub fn newCommand(p: *Pardes, id: usize, cwd: []const u8, line: []const u8) !*Pa const owned = try p.gpa.dupe(u8, line); errdefer p.gpa.free(owned); if (p.tape.authorityOnly("open a terminal")) return error.OutOfMemory; - const pane = try panes.createTerminal(p.gpa, p.view().screen_w, p.view().screen_h); + const pane = try panes.createTerminal(&p.outside, p.gpa, p.view().screen_w, p.view().screen_h); pane.command = owned; pane.command_pty = true; pane.body.mode = .tty; diff --git a/core/replica.zig b/core/replica.zig index 0d1802b5..214cc34e 100644 --- a/core/replica.zig +++ b/core/replica.zig @@ -414,9 +414,10 @@ pub const Stats = struct { } }; -/// `terminal`: its speculation read a terminal or moved one's view (or a -/// terminal had the keyboard), so what it did depends on the emulator. -const Pending = struct { seq: u32, msg: []u8, spec: ?[]u8 = null, sent_ns: u64 = 0, terminal: bool = false, guess: ?tape.Guess = null }; +/// `outside`: how far its speculation moved its core's count of writes +/// outside the rollback copy (Pardes.outside): not 0, it owes an emulator +/// a write (a grid's size), which only its replay makes. +const Pending = struct { seq: u32, msg: []u8, spec: ?[]u8 = null, sent_ns: u64 = 0, outside: u64 = 0, guess: ?tape.Guess = null }; pub fn parseUnit(msg: []const u8) ?Unit { if (msg.len < unit_head) return null; @@ -608,10 +609,7 @@ pub const Replica = struct { 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 - // put-off frees done. Put back, it would bring back what was - // freed between steps meanwhile (the shell's rows a draw read - // again after a delta), which `toConfirmed` drops and this - // freed again (a held copy across an input of its own, a + // put-off frees done (a held copy across an input of its own, a // rejoin's old replica). if (r.copy.held) r.copy.release(); c.deinit(); @@ -691,9 +689,14 @@ pub const Replica = struct { r.stats.units += 1; 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. - defer if (r.diverged == null and tape.feedsTerminal(u.tape)) if (r.t.core) |c| if (c.echo != null) r.echo.fed(c); + // THE ONE QUESTION of a unit: did applying it write state outside + // the rollback copy (an emulator: Pardes.outside, the count of those + // writes, moved over its apply, read off the core that applied it)? + // Such a unit is applied once, to the confirmed core, never kept to + // replay over a copy; and its emulators' new state is what the + // predicted echo is judged against. + var moved = false; + defer if (r.diverged == null and moved) 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 @@ -717,19 +720,20 @@ 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) { - // 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. + // Its speculation's own count (`Pending.outside`: the fast + // path's premise, the same records, makes it this unit's): it + // owes an emulator a write (a grid's size), which a speculation + // never makes: kept, the write would be missing; replayed later + // (a rollback's `since`), made then. So it is taken now, on the + // confirmed core, and the ones on top applied again over it. + moved = r.pending.items[0].outside != 0; + if (moved) { r.toConfirmed(); if (tape.replayUnit(&r.t, u.tape)) |why| return r.fail(why); r.freePending(r.pending.orderedRemove(0)); r.dirty = true; return; } - const read_terminal = r.pending.items[0].terminal; r.freePending(r.pending.orderedRemove(0)); r.applied -= 1; if (r.applied == 0) { @@ -753,11 +757,10 @@ pub const Replica = struct { // input kept to replay over it as a unit of the session's // that comes while idle is: a step writes some bytes of the // megabyte the copy is, walked once in `rebase_after` units, - // not once a key. Not over one that read a terminal (replayed - // later it would read the deltas since), nor once a pane - // opened, closed or was torn down since the copy (what it - // holds outside the copy was made or freed: `ahead`'s rule). - if (!read_terminal and !r.panesMoved()) return r.keepSince(u.tape); + // not once a key. Not once a pane opened, closed or was torn + // down since the copy (what it holds outside the copy was + // made or freed: `ahead`'s rule). + if (!r.panesMoved()) return r.keepSince(u.tape); r.copy.release(); rollback.Epoch.select(null); r.clearSince(); @@ -772,13 +775,11 @@ pub const Replica = struct { r.last_digest.clearRetainingCapacity(); if (ends) |d| r.last_digest.appendSlice(r.gpa, d) catch {}; } - // A terminal's output, or a join's reloads, never taken so (the one - // rule): what it writes outside the copy is applied once, at its - // 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 - !tape.feedsTerminal(u.tape)) - { + // The one question needs no read here: the session's digest after + // the unit holds its count of writes outside the copy, so a unit that + // wrote an emulator (a terminal's output, a colour set no other + // digested field shows, a join's reloads) never ends where it began. + if (r.applied > 0 and u.origin != r.id and ends != null and std.mem.eql(u8, ends.?, r.last_digest.items)) { // Nothing a digest covers moved: what was applied on top is // what the session will apply on top of it. Replayed when the // copy is next put back. @@ -807,7 +808,7 @@ pub const Replica = struct { // replayed by a rollback were, if at all, as they came). const check = ends != null and r.checkDue(); r.t.checks = check; - const writes = Term.writes; + const outside = if (r.t.core) |c| c.outside.n else 0; const replayed = tape.replayUnit(&r.t, u.tape); r.t.checks = false; if (replayed) |why| { @@ -821,6 +822,7 @@ pub const Replica = struct { // draw nothing. Read after the replay: before it, it is what the // units before asked (and a first unit has no core yet). if (r.core().needs_frame) r.moved = true; + moved = r.core().outside.n != outside; if (check) { r.since_check = 0; r.stats.checks += 1; @@ -838,15 +840,15 @@ pub const Replica = struct { // or freed here, and is not put back with the copy: a rollback // replaying the unit again would close a terminal freed already (the // soak, a `Del` of the shell). Let go with the copy. - // The one rule: a unit that wrote an emulator (a terminal's output, - // a grid reflowed, a view moved, one reloaded at a join) wrote what - // no copy holds: kept, a rollback would replay it into what it - // wrote already (the bytes fed twice). It goes with the copy: the - // state is the confirmed one, nothing being on top. + // The one question: a unit that wrote an emulator (a terminal's + // output, a grid reflowed, one opened, closed or reloaded at a join) + // wrote what no copy holds: kept, a rollback would replay it into + // what it wrote already (the bytes fed twice). It goes with the + // copy: the state is the confirmed one, nothing being on top. 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 Term.writes != writes) { + if (retiring or moved) { r.copy.release(); rollback.Epoch.select(null); return r.clearSince(); @@ -897,11 +899,6 @@ pub const Replica = struct { if (!whole) return r.fail("out of memory for a rollback"); // The frame its host drew is of the memory put back: drawn again. r.moved = true; - // The rows a terminal was read as are no copy's: what the - // speculation built was the epoch's, freed with it, and what - // was there before is of a grid the deltas since moved on - // from (a rollback never brings a terminal's past back). - r.core().shell_rows = .{}; } r.applied = 0; for (r.since.items) |u| if (tape.replayUnit(&r.t, u)) |why| { @@ -938,8 +935,6 @@ pub const Replica = struct { const c = r.core(); if (!r.copy.held) { const t0 = nowNs(); - // A grid's worth of text the copy would save, and put back stale. - c.shell_rows.reset(c.gpa); r.copy.take(&r.epoch, c) catch return false; r.keepSerials(); rollback.Epoch.select(&r.epoch); @@ -953,6 +948,7 @@ pub const Replica = struct { tape.beginSpeculation(&r.t); // The time it was sent with, every time it is applied. r.t.guess = p.guess; + const outside = c.outside.n; 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, @@ -961,9 +957,9 @@ pub const Replica = struct { // the same bytes in the same order as the session's: it is applied. c.update(in.event); c.step(); - // It owes an emulator a write it skipped (a grid's size): replayed - // when confirmed. - p.terminal = r.t.touched; + // What it owes outside the copy (an emulator's grid: Term.resize + // counts the write a speculation skips): replayed when confirmed. + p.outside = c.outside.n -% outside; const clean = tape.endSpeculation(&r.t); const dt = nowNs() - t0; // Where a blob was written, should one be: the input that did. @@ -4004,6 +4000,101 @@ test "bytes: a session's output taken over a copy held ahead is fed once: a roll try sameTerminals(b.a, b.r); } +test "bytes: a session's reflow of a terminal's grid over a copy held ahead is the count's to decide: the copy goes, and a rollback does not reflow the grid again" { + if (pardes.Term.ops == null) return error.SkipZigTest; // a shell + const b = try BytesPair.init(); + defer b.deinit(); + try b.output("a line long enough to wrap once the grid is narrower than it is now, and then some more\r\n"); + b.r.ready(); + try std.testing.expect(b.r.copy.held); + // The unit carries no output: its sync reflows the grid, which no record + // names; the core that applied it counted the write. + const before = b.r.core().outside.n; + b.r.confirm(try b.a.own(.{ .resize = .{ .cols = 40, .rows = 20 } })); + b.r.settle(); + try std.testing.expect(b.r.core().outside.n != before); + try std.testing.expect(!b.r.copy.held); + try b.rollback(); + try agrees(b.a, b.r); + try sameTerminals(b.a, b.r); +} + +test "the count of writes outside the copy is digested: a session's emulator written where its client's is not (a colour set, which no other digested field shows) is a digest that names `outside`" { + if (pardes.Term.ops == null) return error.SkipZigTest; // a shell + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const b = try BytesPair.init(); + defer b.deinit(); + try std.testing.expectEqualStrings("", try partsApart(b.a, b.r, arena.allocator())); + // A write of one side's emulator that no unit carries, as a stray one + // would be: the count alone says it. + const pane = b.a.core.panes[b.shell.index()].?; + _ = pardes.Term.feed(&b.a.core.outside, pane.terminal.?, "\x1b[31m", &.{}, &.{}, &.{}, &.{}); + try std.testing.expectEqualStrings("outside ", try partsApart(b.a, b.r, arena.allocator())); +} + +test "bytes: a terminal's rows read before an idle client's copy are the copy's: a rollback puts them back, neither dropped nor freed twice" { + if (pardes.Term.ops == null) return error.SkipZigTest; // a shell + const b = try BytesPair.init(); + defer b.deinit(); + try b.output("a line of the program's\r\nand another\r\n"); + // Its rows read between steps (a draw's), then the copy taken while it + // idles (`ready`): the rows are what the core holds at the copy. + const pane = b.r.core().panes[b.shell.index()].?; + _ = try pardes.edit.shellRows(b.r.core(), pane); + const cached = b.r.core().shell_rows.text_alloc.ptr; + b.r.ready(); + try std.testing.expect(b.r.copy.held); + // A key of the client's on top, the session's own key first: the copy + // put back, the rows with it (not left orphaned in the epoch). + try b.rollback(); + try std.testing.expectEqual(cached, b.r.core().shell_rows.text_alloc.ptr); + try agrees(b.a, b.r); + try b.output("after\r\n"); + _ = try pardes.edit.shellRows(b.r.core(), pane); + try agrees(b.a, b.r); +} + +test "bytes: a client's key that reads a terminal's rows, the session's output before it in the session's order: the output rolls it back, its read is made again over the fed rows, and the input is kept on the fast path with the session's reading" { + if (pardes.Term.ops == null) return error.SkipZigTest; // a shell + const gpa = std.testing.allocator; + const b = try BytesPair.init(); + defer b.deinit(); + try b.output("l1\r\nl2\r\nl3\r\n"); + // The shell's pane focused and out of its tty mode (^B): a cursor over + // its rows. + const id = b.shell.index(); + const rect = b.a.core.view().rects[id]; + for ([_]pardes.Event{ + .{ .mouse = .{ .button = .left, .kind = .press, .col = rect.x + 2, .row = rect.y + 1 } }, + .{ .mouse = .{ .button = .left, .kind = .release, .col = rect.x + 2, .row = rect.y + 1 } }, + .{ .key = .{ .cp = 'b', .ctrl = true } }, + }) |ev| { + b.r.confirm(try b.a.own(ev)); + b.r.settle(); + } + try agrees(b.a, b.r); + // G: to the last of its rows, which it reads (edit.shellRows). + const last = try gpa.dupe(u8, try b.r.input(.{ .key = .{ .cp = 'G', .text = "G" } })); + defer gpa.free(last); + try std.testing.expectEqual(@as(usize, 1), b.r.applied); + const read_before = b.r.core().panes[id].?.body.cur_row; + // The program prints two lines before the session takes the G: the + // emulator fed (its count moved, so never a neutral unit), the G + // undone and read again over the rows as fed. + b.a.output(.{ .output = .{ .pane = b.shell, .bytes = "l4\r\nl5\r\n" } }); + b.r.confirm((try b.a.pending()).?); + b.r.settle(); + try std.testing.expectEqual(@as(usize, 1), b.r.applied); + try std.testing.expect(b.r.core().panes[id].?.body.cur_row > read_before); + const fast = b.r.stats.fast; + b.r.confirm(try b.a.take(last)); + b.r.settle(); + try std.testing.expectEqual(fast + 1, b.r.stats.fast); + try agrees(b.a, b.r); + try std.testing.expectEqual(b.a.core.panes[id].?.body.cur_row, b.r.core().panes[id].?.body.cur_row); +} + test "bytes: what a terminal's emulator gains while a copy is held is its own: a rollback frees none of it" { if (pardes.Term.ops == null) return error.SkipZigTest; // a shell const b = try BytesPair.init(); @@ -4276,12 +4367,12 @@ test "bytes: a client joins from a dump with its terminals whole, and every side var line: [128]u8 = undefined; for (0..400) |i| try b.output(try std.fmt.bufPrint(&line, "\x1b[3{d}m{d}\x1b]8;;https://example.com/{d}\x1b\\ link\x1b]8;;\x1b\\\x1b[0m\r\n", .{ i % 8, i, i })); try b.output("half a colour: \x1b[38;2;10;20"); - const reloads = pardes.Term.writes; + const reloads = b.r.core().outside.n; const joined = (try b.a.join(2, null)).?; defer gpa.free(joined.dump); b.r.confirm(joined.unit); try std.testing.expect(b.r.diverged == null); - try std.testing.expect(pardes.Term.writes != reloads); + try std.testing.expect(b.r.core().outside.n != reloads); const late = try Replica.initDump(gpa, 2, joined.view, joined.dump, .{ .cols = 80, .rows = 24 }); defer late.deinit(); late.core().echo = null; diff --git a/core/rollback.zig b/core/rollback.zig index a55d3c87..61fb7b89 100644 --- a/core/rollback.zig +++ b/core/rollback.zig @@ -441,7 +441,8 @@ pub const Copy = struct { // the speculation freed would come back as that. Not the // queues a step drains (undefined between steps), nor the // authority's. - if (attr.@"comptime" or comptime (annotated(T, "authority", name) or ((annotated(T, "local", name) or annotated(T, "derived", name)) and unsaved(name)))) continue; + if (comptime annotated(T, "derived", name) and unsaved(name)) @compileError("rollback: " ++ @typeName(T) ++ "." ++ name ++ " is a cache the copy would skip: a cache the core holds is the copy's, or lives beside what it caches, outside the core"); + if (attr.@"comptime" or comptime (annotated(T, "authority", name) or (annotated(T, "local", name) and unsaved(name)))) continue; // A text and its index: written in place, the epoch // notes what each write takes out (`Epoch.wrote`). if (comptime opaqueTo(F) or annotated(T, "journal", name)) continue; @@ -483,7 +484,7 @@ pub const Copy = struct { const s = @typeInfo(T).@"struct"; inline for (s.field_names, s.field_types, s.field_attrs) |name, F, attr| { if (attr.@"comptime") continue; - if (comptime (annotated(T, "local", name) or annotated(T, "derived", name) or annotated(T, "authority", name)) and unsaved(name)) continue; + if (comptime (annotated(T, "local", name) or annotated(T, "authority", name)) and unsaved(name)) continue; const at = @intFromPtr(&@field(v, name)); if (comptime walk.lengthOf(T, name) != null and @typeInfo(F) == .array) { try c.save(at, walk.lengthIn(v, comptime walk.lengthOf(T, name).?) * @sizeOf(@typeInfo(F).array.child)); @@ -501,7 +502,10 @@ pub const Copy = struct { if (try c.reached([]const E, addr)) return; if (c.pinnable and s.len * @sizeOf(E) >= blob_min and c.epoch.?.owns(addr) != null) { // A blob of rows with allocations of their own is pinned whole: - // they are as immutable as it, and kept alive with it. + // they are as immutable as it, and kept alive with it. Once, + // whatever reaches it (a text and the allocation it is the + // start of), and never saved as well. + if (try c.reached(void, addr)) return; const bytes = std.mem.sliceAsBytes(s); try c.pins.append(c.meta, .{ .addr = addr, .len = bytes.len, .hash = if (checked) std.hash.Wyhash.hash(0, bytes) else 0, .where = c.where }); return; @@ -511,14 +515,16 @@ pub const Copy = struct { } }; -/// A type that hashes itself and says nothing of its fields (`replica`): -/// a terminal, the authority's (its emulator is never written by a -/// speculation: terminal.zig's guards), or a location row, made again and -/// never written. One that says its fields' kinds is walked by them, -/// whatever digest it has (the 9P state, fs.Namespace and a pane's: a -/// replayed request writes its buffers in place). +/// A type the copy does not walk: one that says so (`outside_copy`, with +/// why: a terminal's handle, its emulator written by confirmed units alone, +/// counted in Pardes.outside; a location row, made again and never +/// written). Every other type is walked, whatever digest it has: what a +/// core field points to is the copy's, saved or pinned, so that a write +/// into it in place is put back with the rest (jj.Session's answers, whose +/// lines an edit splices: walked by no one while its digest said "skip +/// me", a rollback over a client's edit freed them twice). fn unwalked(comptime T: type) bool { - return @hasDecl(T, "digest") and @TypeOf(T.digest) == fn (*const T, *walk.Hasher) void and !@hasDecl(T, "replica"); + return @hasDecl(T, "outside_copy"); } fn annotatedStruct(comptime T: type) bool { @@ -527,10 +533,10 @@ fn annotatedStruct(comptime T: type) bool { /// The queues every step drains (empty between steps, asserted when a copy /// is taken: what is in their slots is nothing), the frame statistics -/// (numbers), and the rows a terminal was last read as -/// (a grid's worth of text, emptied when a copy is taken and when it is -/// put back: core/replica.zig), and a replica's predicted echo (core/term/echo.zig: -/// the replica's, never its core's). And the store and Recent, a replica's +/// (numbers), and a replica's predicted echo (core/term/echo.zig: the +/// replica's, never its core's). Never a cache (`.derived`): what a core +/// field caches is the copy's, or lives beside what it caches, outside the +/// core (a compile error says so). And the store and Recent, a replica's /// own: on the host's heap (Pardes.recentGpa), which the epoch never puts a /// free off for, so their bytes put back would point at what is freed. A /// step reads what the authority holds of them off the tape @@ -538,7 +544,7 @@ fn annotatedStruct(comptime T: type) bool { /// `Options.tape`): the process's, which a rollback leaves where it is. fn unsaved(comptime name: []const u8) bool { return std.mem.eql(u8, name, "effects") or std.mem.eql(u8, name, "in_q") or std.mem.eql(u8, name, "frames") or std.mem.eql(u8, name, "own_frames") or - std.mem.eql(u8, name, "shell_rows") or std.mem.eql(u8, name, "echo") or std.mem.eql(u8, name, "store") or + std.mem.eql(u8, name, "echo") or std.mem.eql(u8, name, "store") or std.mem.eql(u8, name, "recent") or std.mem.eql(u8, name, "tape"); } diff --git a/core/root.zig b/core/root.zig index 3bca5e03..a476f90f 100644 --- a/core/root.zig +++ b/core/root.zig @@ -443,6 +443,7 @@ test { _ = @import("Handover.zig"); _ = @import("walk.zig"); _ = @import("views.zig"); + _ = Turn; // A window's build links the window's C (font.c over FreeType and // HarfBuzz) into each of its programs, and their allocator (ui_malloc // and the rest) is gui.zig's. diff --git a/core/surface.zig b/core/surface.zig index 3ab9a933..3452bc77 100644 --- a/core/surface.zig +++ b/core/surface.zig @@ -150,7 +150,15 @@ pub const max_rail_ticks = 4096; /// A pinned change's lane on a body row (jj.paint): a pixel shell draws /// it as a strip in gutter cell `x`, at its `level`'s place (sample A of /// the ruled design: each a third of a cell wide, half that of air between). -pub const Lane = struct { x: u16, y: u16, level: u8, rgb: [3]u8 }; +pub const Lane = struct { + x: u16, + y: u16, + level: u8, + rgb: [3]u8, + + /// The levels a row shows at most: the ruled gutter fits three. + pub const levels = 3; +}; /// Churn's strip on a rail (jj.railHeat): a pixel shell draws its row of /// pane `owner`'s rail, beside the track, in `rgb`. pub const Heat = struct { owner: u8, row: u16, rgb: [3]u8 }; diff --git a/core/tape.zig b/core/tape.zig index dc53a7c9..5f98238d 100644 --- a/core/tape.zig +++ b/core/tape.zig @@ -294,9 +294,6 @@ pub const Tape = struct { /// The authority's last yes or no to each question a replayed unit /// asked it (`authority`), a speculation's guess. answers: std.AutoHashMapUnmanaged(u64, bool) = .empty, - /// It read a terminal (its rows) or moved one's view: what it did - /// depends on the emulator, which deltas write (`touchTerminal`). - touched: bool = false, /// The allocator of the core a replay makes (a replica's rollback epoch, /// core/rollback.zig), when it is not the tape's own. core_gpa: ?std.mem.Allocator = null, @@ -890,11 +887,6 @@ pub const Tape = struct { return true; } - /// 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; - } - /// The core a Restore made is the session's from here. pub fn adopt(t: *Tape, p: *Pardes) void { p.tape = t; @@ -1339,10 +1331,6 @@ pub fn authorityOnly(comptime why: []const u8) bool { return (on orelse &none).authorityOnly(why); } -pub fn touchTerminal() void { - (on orelse &none).touchTerminal(); -} - /// A harmless stand-in for what a host call or a syscall would have /// returned to a speculation that is thrown away once it returns: an /// error where one can be said, else zeroes. @@ -1426,7 +1414,6 @@ pub fn beginSpeculation(t: *Tape) void { t.speculating = true; t.poisoned = false; t.poisoned_by = ""; - t.touched = false; t.no_digest = true; t.yields = pardes.turn.yields; t.buf.clearRetainingCapacity(); @@ -1446,29 +1433,6 @@ pub fn endSpeculation(t: *Tape) bool { /// a message may be (replica.zig `lag_max`'s neighbour, wire's bound). pub const unit_max = 1 << 20; -/// Whether a unit writes a terminal's emulator: feeds one its program's -/// output (a pty's read; an input kept by hash is taken to), or reloads -/// every one at a join (`Site.reload`; a join refused too, which moves -/// nothing a digest covers): never taken as moving nothing (the replica -/// engine's one rule, core/replica.zig `confirm`). -pub fn feedsTerminal(bytes: []const u8) bool { - const Tag = std.meta.Tag(Input); - const EventTag = std.meta.Tag(pardes.Event); - const reload: u16 = @as(u16, host_fns.len) + @backingInt(Site.reload); - var r: walk.Reader = .{ .bytes = bytes }; - while (nextRecord(&r)) |rec| switch (rec.kind) { - .blob => if (rec.payload.len > 0 and rec.payload[0] == @backingInt(Kind.input)) return true, - .host => if (rec.payload.len >= 2 and std.mem.bytesToValue(u16, rec.payload[0..2]) == reload) return true, - .input => { - if (rec.payload.len < @sizeOf(Tag) + @sizeOf(EventTag)) continue; - if (!std.mem.eql(u8, rec.payload[0..@sizeOf(Tag)], std.mem.asBytes(&@as(Tag, .update)))) continue; - if (std.mem.eql(u8, rec.payload[@sizeOf(Tag)..][0..@sizeOf(EventTag)], std.mem.asBytes(&@as(EventTag, .output)))) return true; - }, - else => {}, - }; - return false; -} - /// Whether two tapes record the same inputs, host calls and answers, /// their digests aside. pub fn sameRecords(a: []const u8, b: []const u8) bool { diff --git a/dev/Inbox.zig b/dev/Inbox.zig index d733b971..1df516cb 100644 --- a/dev/Inbox.zig +++ b/dev/Inbox.zig @@ -118,7 +118,9 @@ pub fn acceptReader(q: *Inbox, pane: pardes.Pane.Id, gen: u32) void { /// One of `pane`'s reads applied, or dropped unapplied. pub fn applied(q: *Inbox, pane: pardes.Pane.Id) void { const n = &q.unapplied[pane.index()]; - if (n.load(.acquire) > 0) _ = n.fetchSub(1, .acq_rel); + if (n.load(.acquire) == 0) return; + _ = n.fetchSub(1, .acq_rel); + pardes.turn.outputApplied(); } pub fn cancelReader(q: *Inbox, pane: pardes.Pane.Id, gen: u32) void { @@ -316,8 +318,10 @@ fn readPty(q: *Inbox, pty: std.Io.File, pane: pardes.Pane.Id, gen: u32) void { }, }; if (n == 0) continue; - // Counted at once: out of the pty, the poll no longer sees it. + // Counted at once: out of the pty, the poll no longer sees it, + // nor a write after it (Turn.awaitOutput). _ = q.unapplied[pane.index()].fetchAdd(1, .acq_rel); + _ = pardes.turn.reads.fetchAdd(1, .acq_rel); const bytes = q.gpa.dupe(u8, buf[0..n]) catch |err| { q.applied(pane); failure = err; diff --git a/dev/glide.zig b/dev/glide.zig index 711acb22..62e44bb7 100644 --- a/dev/glide.zig +++ b/dev/glide.zig @@ -39,9 +39,13 @@ pub const Glide = struct { dir: i8 = 0, before: []pardes.Cell = &.{}, /// The rows past the body's top (`above`) and bottom (`below`), nearest - /// first, `bw` cells each: what the gap shows while the picture lags. + /// first, `bw` cells each, and a change's lanes on each (Surface.lanes, + /// a pixel shell's strips in the gutter, not cells): what the gap shows + /// while the picture lags. above: []pardes.Cell = &.{}, below: []pardes.Cell = &.{}, + above_lanes: []RowLanes = &.{}, + below_lanes: []RowLanes = &.{}, nabove: u16 = 0, nbelow: u16 = 0, /// The core's lines a scroll moved, not yet measured; and what the @@ -64,8 +68,10 @@ pub const Glide = struct { /// not move, so a move is measured, and the rows that left are kept, /// below them. held: [pardes.MAX_PANES]u16 = @splat(0), - /// The last frame's cells, which a move is measured against. + /// The last frame's cells, which a move is measured against, and its + /// lanes, which the rows that left take with them. last: []pardes.Cell = &.{}, + last_lanes: std.ArrayList(pardes.Lane) = .empty, last_cols: u16 = 0, last_rows: u16 = 0, @@ -97,7 +103,10 @@ pub const Glide = struct { gpa.free(glide.before); gpa.free(glide.above); gpa.free(glide.below); + gpa.free(glide.above_lanes); + gpa.free(glide.below_lanes); gpa.free(glide.last); + glide.last_lanes.deinit(gpa); } pub fn bw(glide: *const Glide) u16 { @@ -188,6 +197,8 @@ pub const Glide = struct { glide.last_cols = surface.cols; glide.last_rows = surface.rows; glide.caret_row = if (surface.cursor) |c| c.y else null; + glide.last_lanes.clearRetainingCapacity(); + glide.last_lanes.appendSlice(gpa, surface.lanes.items) catch {}; } /// Finds how far the pane's body rows moved, `dir` rows at a time, by @@ -261,28 +272,56 @@ pub const Glide = struct { const src_row: usize = top + if (glide.dir > 0) shift - 1 - i else h - shift + i; @memcpy(keep.*[i * w ..][0..w], glide.before[src_row * w ..][0..w]); } + // Their lanes go with them, from the frame they left. + const keep_lanes = if (glide.dir > 0) glide.above_lanes else glide.below_lanes; + std.mem.copyBackwards(RowLanes, keep_lanes[shift..][0..kept], keep_lanes[0..kept]); + @memset(keep_lanes[0..shift], .{}); + for (glide.last_lanes.items) |lane| { + if (lane.x < x0 or lane.x >= x0 + w or lane.y < glide.body_y + top or lane.y >= glide.body_y + glide.body_h) continue; + const row = lane.y - glide.body_y - top; + if (glide.dir > 0 and row < shift) keep_lanes[shift - 1 - row].add(lane); + if (glide.dir < 0 and row >= h - shift) keep_lanes[row - (h - shift)].add(lane); + } count.* = kept + shift; // What came into view is no longer past the other edge. const other = if (glide.dir > 0) &glide.below else &glide.above; + const other_lanes = if (glide.dir > 0) glide.below_lanes else glide.above_lanes; const other_n = if (glide.dir > 0) &glide.nbelow else &glide.nabove; // ...and after a jump, the rows past it are another place's. const dropped = if (far) other_n.* else @min(other_n.*, shift); std.mem.copyForwards(pardes.Cell, other.*[0 .. @as(usize, other_n.* - dropped) * w], other.*[@as(usize, dropped) * w ..][0 .. @as(usize, other_n.* - dropped) * w]); + std.mem.copyForwards(RowLanes, other_lanes[0 .. other_n.* - dropped], other_lanes[dropped..][0 .. other_n.* - dropped]); other_n.* -= dropped; // An input: the core's rows moved by as many (down positive). glide.follow.kick(@as(f32, @floatFromInt(shift)) * @as(f32, @floatFromInt(glide.dir)), glide.now_ns, glide.pace()); } pub fn ensure(glide: *Glide, gpa: std.mem.Allocator) bool { - const n = @as(usize, glide.bw()) * glide.body_h * reach; - inline for (.{ &glide.above, &glide.below }) |buffer| if (buffer.len < n) { - const grown = gpa.realloc(buffer.*, n) catch return false; - buffer.* = grown; + const rows = @as(usize, glide.body_h) * reach; + inline for (.{ .{ &glide.above, rows * glide.bw() }, .{ &glide.below, rows * glide.bw() }, .{ &glide.above_lanes, rows }, .{ &glide.below_lanes, rows } }) |kept| if (kept[0].len < kept[1]) { + kept[0].* = gpa.realloc(kept[0].*, kept[1]) catch return false; }; return true; } }; +/// A kept row's lanes, as the frame it left drew them: a row has a level +/// each at most. +pub const RowLanes = struct { + n: u8 = 0, + lane: [pardes.Lane.levels]pardes.Lane = undefined, + + pub fn add(row: *RowLanes, lane: pardes.Lane) void { + if (row.n == row.lane.len) return; + row.lane[row.n] = lane; + row.n += 1; + } + + pub fn items(row: *const RowLanes) []const pardes.Lane { + return row.lane[0..row.n]; + } +}; + pub fn sameRow(a: []const pardes.Cell, b: []const pardes.Cell) bool { for (a, b) |x, y| { if (x.default != y.default) return false; diff --git a/dev/gui/gui.zig b/dev/gui/gui.zig index 3193d966..88ba023b 100644 --- a/dev/gui/gui.zig +++ b/dev/gui/gui.zig @@ -455,6 +455,7 @@ const Gui = struct { scroll_lag: f32 = 0, // picture position - core position, in rows scroll_edge: []pardes.Cell = &.{}, // the row that just left the pane scroll_edge_len: u16 = 0, + scroll_edge_lanes: pardes.glide.RowLanes = .{}, // and a change's lanes on it /// Loop steps since the last fractional turn: past `settle_after`, a /// resting `scroll_lag` eases onto the core's row (stepScroll). scroll_idle: u8 = 0, @@ -2696,7 +2697,7 @@ fn waitInput(ctx: ?*anyopaque, timeout_ms: u32) void { s.held = null; if (held) |h| sev = h; // The wait is the 9P connections' turn with the core. - pardes.turn.rest(); + pardes.turn.listen(); const got = held != null or c.SDL_WaitEventTimeout(&sev, ms); pardes.turn.wake(); // A virtual clock: while a render-time animation moves, each loop @@ -3349,6 +3350,8 @@ const WheelRun = struct { mc: MouseCell, drawn: f32 = 0, now_ns: u64 = std.time.ns_per_s, + /// Each frame given a change's lanes (testLanes), as `Changes` would. + lanes: bool = false, fn init(gpa: std.mem.Allocator, core: *pardes.Pardes) !WheelRun { var wr: WheelRun = .{ .g = testGui(10, 20, 6, 12), .core = core, .arena = .init(gpa), .mc = undefined }; @@ -3384,6 +3387,7 @@ const WheelRun = struct { if (!wr.core.needs_frame and !frontendMoving(&wr.g)) return; _ = wr.arena.reset(.retain_capacity); const s = try wr.core.render(wr.arena.allocator()); + if (wr.lanes) try testLanes(gpa, wr.core, s); wr.g.frame = s; wr.g.facts = s.facts.*; wr.g.now_ns = wr.now_ns; @@ -3559,6 +3563,8 @@ fn scrollRows(g: *Gui, in: *Input, gpa: std.mem.Allocator) bool { if (g.scroll_edge.len >= bw) { @memcpy(g.scroll_edge[0..bw], s.cells[@as(usize, srow) * s.cols + r.x + config.GUTTER ..][0..bw]); g.scroll_edge_len = bw; + g.scroll_edge_lanes = .{}; + for (s.lanes.items) |lane| if (lane.y == srow and lane.x >= r.x + config.GUTTER and lane.x < r.x + r.w) g.scroll_edge_lanes.add(lane); } } } @@ -3567,22 +3573,63 @@ fn scrollRows(g: *Gui, in: *Input, gpa: std.mem.Allocator) bool { return moved; } +/// The body a scroll moves, as its rows are drawn: a glide's at its +/// offset, else a touchpad's fraction (scroll_lag); its pane's rect (the +/// rail and the body, Glide.rect's), its body's first row and its rows. +/// Null when nothing lags, or when it was resized under us. +const ScrollBody = struct { + pane: usize, + gliding: bool, + lag: f32, + rect: pardes.Rect, + y0: u16, + bh: u16, + + /// The grid row of the `i`th row that left it, nearest first: over its + /// moving rows (under the `held` ones) while the picture lags a move + /// down, under the body for one up. + fn leftRow(sb: ScrollBody, held: u16, i: usize) i32 { + return if (sb.lag < 0) @as(i32, sb.y0 + held) - 1 - @as(i32, @intCast(i)) else @as(i32, sb.y0) + sb.bh + @as(i32, @intCast(i)); + } + + /// A glide's rows that left it drawn: as many as the lag opens. + fn glideLeft(sb: ScrollBody, glide: *const Glide) u16 { + const gap: u16 = @intFromFloat(@min(@ceil(@abs(sb.lag)), @as(f32, @floatFromInt(@as(u32, sb.bh) * Glide.reach)))); + return @min(gap, if (sb.lag < 0) glide.nabove else glide.nbelow); + } +}; + +fn scrollBody(g: *const Gui, surface: *const pardes.Surface) ?ScrollBody { + const glide = &g.glide; + const gliding = glide.follow.offset != 0; + const sb: ScrollBody = .{ + .pane = if (gliding) glide.pane else g.scroll_pane orelse return null, + .gliding = gliding, + .lag = if (gliding) glide.follow.offset else g.scroll_lag, + .rect = if (gliding) glide.rect else g.scroll_rect, + .y0 = if (gliding) glide.body_y else g.scroll_body_y, + .bh = if (gliding) glide.body_h else g.scroll_body_h, + }; + const bw = sb.rect.w -| config.GUTTER; + if (sb.lag == 0 or bw == 0 or sb.bh == 0 or sb.rect.x + config.GUTTER + bw > surface.cols or sb.y0 + sb.bh > surface.rows) return null; + return sb; +} + /// A scrolling body's picture: its rows moved by the lag, a glide's or a /// touchpad's fraction of a row, and in the gap that opens the rows that /// left. fn emitScrollRows(g: *Gui, instances: [*]CellInstance, base: u32, surface: *const pardes.Surface, layout: CellLayout, win_w: f32, win_h: f32, page: [3]u8, held: u16) u32 { g.scroll_held_px = 0; const glide = &g.glide; - const gliding = glide.follow.offset != 0; - const pane = if (gliding) glide.pane else g.scroll_pane orelse return 0; - const lag = if (gliding) glide.follow.offset else g.scroll_lag; - if (lag == 0) return 0; - const r = if (gliding) glide.rect else g.scroll_rect; - const bh = if (gliding) glide.body_h else g.scroll_body_h; - const y0 = if (gliding) glide.body_y else g.scroll_body_y; - const bw = r.w -| config.GUTTER; + const sb = scrollBody(g, surface) orelse return 0; + const gliding = sb.gliding; + const pane = sb.pane; + const lag = sb.lag; + const r = sb.rect; + const bh = sb.bh; + const y0 = sb.y0; + const bw = r.w - config.GUTTER; const x0 = r.x + config.GUTTER; - if (bw == 0 or bh == 0 or x0 + bw > surface.cols or y0 + bh > surface.rows) return 0; // resized under us // The scissor the shifted rows are drawn in is the scroll's. g.scroll_rect = r; g.scroll_body_y = y0; @@ -3627,7 +3674,7 @@ fn emitScrollRows(g: *Gui, instances: [*]CellInstance, base: u32, surface: *cons // A touchpad's fraction opens one row, the one that left: under the // held rows, where the moving rows start. if (g.scroll_edge_len >= bw) { - const erow: u16 = if (lag > 0) y0 + bh else y0 + kept.rows - 1; + const erow: u16 = @intCast(sb.leftRow(kept.rows, 0)); var i: u16 = 0; while (i < bw) : (i += 1) { emitInstance(g, instances, base + n, x0 + i, erow, shifted, win_w, win_h, cellFontRole(&g.scroll_edge[i]), g.scroll_edge[0..bw], i, null, false, page); @@ -3638,14 +3685,10 @@ fn emitScrollRows(g: *Gui, instances: [*]CellInstance, base: u32, surface: *cons } // A glide's: rows past the top while the picture lags a move down, past // the bottom for one up; as many as it opens. - const gap: u16 = @intFromFloat(@min(@ceil(@abs(lag)), @as(f32, @floatFromInt(@as(u32, bh) * Glide.reach)))); - const nkept = if (lag < 0) glide.nabove else glide.nbelow; const rows = if (lag < 0) glide.above else glide.below; - for (0..@min(gap, nkept)) |i| { + for (0..sb.glideLeft(glide)) |i| { const cells = rows[i * bw ..][0..bw]; - // Row -1 - i above the moving rows (under the held ones), or bh + i - // below the body, in grid rows. - const at_row: i32 = if (lag < 0) @as(i32, y0 + kept.rows) - 1 - @as(i32, @intCast(i)) else @as(i32, y0) + bh + @as(i32, @intCast(i)); + const at_row = sb.leftRow(kept.rows, i); var at = shifted; // emitInstance takes an unsigned row: move the layout instead. at.y_off += @as(f32, @floatFromInt(at_row - @as(i32, y0))) * layout.h; @@ -4916,16 +4959,7 @@ fn buildDecor(g: *Gui, gpa: std.mem.Allocator, surface: *const pardes.Surface, g } else false; if (grid_bottom < win_h and tag_last) try addDecor(g, gpa, 0, grid_bottom, win_w, win_h, chrome.tag_bg, 1, win_w, win_h); try paneDecor(g, gpa, regions, surface.rail_ticks[0..surface.nrail_ticks], surface.heat.items, chrome, layout, surface.cols, surface.rows, win_w, win_h); - // The changes' lanes (jj.paint): a strip a level in the gutter's - // lane cells, each a third of a cell wide with half that of air - // before it, so three take one and a half cells (the ruled - // sample A); whole pixels, so every row's strip lines up. - for (surface.lanes.items) |lane| { - const w = @max(1, @round(layout.w / 3)); - const x0 = @round(@as(f32, @floatFromInt(lane.x)) * layout.w + w / 2 + @as(f32, @floatFromInt(lane.level)) * (w + w / 2)); - const y0 = @as(f32, @floatFromInt(lane.y)) * layout.h; - try addDecor(g, gpa, x0, y0, x0 + w, y0 + layout.h, lane.rgb, 1, win_w, win_h); - } + try laneDecor(g, gpa, surface, layout, win_w, win_h); // A single spine runs down each column, through every tag and body. for (regions) |column| { if (column.kind != .column) continue; @@ -4955,6 +4989,58 @@ fn buildDecor(g: *Gui, gpa: std.mem.Allocator, surface: *const pardes.Surface, g } } +/// The changes' lanes (jj.paint): a strip a level in the gutter's lane +/// cells, each a third of a cell wide with half that of air before it, so +/// three take one and a half cells (the ruled sample A); whole pixels, so +/// every row's strip lines up. A scrolling body's ride its rows as +/// emitScrollRows draws them: the lag less, cut to the body under its held +/// rows (its scissor), and the rows that left keep theirs in the gap. +fn laneDecor(g: *Gui, gpa: std.mem.Allocator, surface: *const pardes.Surface, layout: CellLayout, win_w: f32, win_h: f32) !void { + const w = @max(1, @round(layout.w / 3)); + const b = scrollBody(g, surface) orelse { + for (surface.lanes.items) |lane| try laneStrip(g, gpa, lane, lane.y, null, w, layout, win_w, win_h); + return; + }; + const kept = holdContext(g, surface, b.pane, if (surface.facts.pane(b.pane)) |pane| pane.context_rows else 0, b.bh, layout); + const ride: LaneRide = .{ + .x0 = b.rect.x + config.GUTTER, + .x1 = b.rect.x + b.rect.w, + .y0 = b.y0 + kept.rows, + .y1 = b.y0 + b.bh, + .dy = b.lag * layout.h - kept.lift, + .top = @as(f32, @floatFromInt(b.y0 + kept.rows)) * layout.h + kept.lift, + .bottom = @as(f32, @floatFromInt(b.y0 + b.bh)) * layout.h, + }; + for (surface.lanes.items) |lane| { + const rides = lane.x >= ride.x0 and lane.x < ride.x1 and lane.y >= ride.y0 and lane.y < ride.y1; + try laneStrip(g, gpa, lane, lane.y, if (rides) &ride else null, w, layout, win_w, win_h); + } + if (b.gliding) { + const rows = if (b.lag < 0) g.glide.above_lanes else g.glide.below_lanes; + for (rows[0..b.glideLeft(&g.glide)], 0..) |*row, i| for (row.items()) |lane| try laneStrip(g, gpa, lane, b.leftRow(kept.rows, i), &ride, w, layout, win_w, win_h); + } else if (g.scroll_edge_len >= b.rect.w - config.GUTTER) { + for (g.scroll_edge_lanes.items()) |lane| try laneStrip(g, gpa, lane, b.leftRow(kept.rows, 0), &ride, w, layout, win_w, win_h); + } +} + +/// A scrolling body's moving rows (laneDecor): their columns and rows, how +/// far up they are drawn, and the pixels they are cut to. +const LaneRide = struct { x0: u16, x1: u16, y0: u16, y1: u16, dy: f32, top: f32, bottom: f32 }; + +/// `lane`'s strip, `w` pixels wide, on grid row `row`, riding a scroll's +/// rows when given one. +fn laneStrip(g: *Gui, gpa: std.mem.Allocator, lane: pardes.Lane, row: i32, ride: ?*const LaneRide, w: f32, layout: CellLayout, win_w: f32, win_h: f32) !void { + const x0 = @round(@as(f32, @floatFromInt(lane.x)) * layout.w + w / 2 + @as(f32, @floatFromInt(lane.level)) * (w + w / 2)); + var y0 = @as(f32, @floatFromInt(row)) * layout.h; + var y1 = y0 + layout.h; + if (ride) |r| { + y0 = @max(y0 - r.dy, r.top); + y1 = @min(y1 - r.dy, r.bottom); + if (y1 <= y0) return; + } + try addDecor(g, gpa, x0, y0, x0 + w, y1, lane.rgb, 1, win_w, win_h); +} + /// Each pane's rule between its tag and body, and its scroll rail: a page /// coloured gutter with a thin track and its thumb, running down through the /// pixels past the last whole row. @@ -6650,6 +6736,121 @@ test "a wheel's caret rides with its line, the text's own glide, never a spring try std.testing.expectEqual(@as(f32, @floatFromInt(s.cursor.?.y)), caretRow(&g, s, now).?); } +/// The active pane's body in a frame. +fn testBody(core: *pardes.Pardes, s: *const pardes.Surface) pardes.Rect { + for (s.regionList()) |region| if (region.kind == .body and region.owner == core.view().active) return region.rect; + unreachable; +} + +/// A change's lanes on the active body's rows as jj.paint lays them for a +/// window (Surface.lanes), for a test: line L's on its row, 1 + L % 3 +/// levels, coloured its line, its level and 0x37, so a strip names its line. +fn testLanes(gpa: std.mem.Allocator, core: *pardes.Pardes, s: *pardes.Surface) !void { + const body = testBody(core, s); + const top = core.panes[core.view().active].?.scroll(); + for (0..body.h) |vr| { + const line: usize = @intCast(top + @as(i32, @intCast(vr))); + for (0..1 + line % 3) |level| + try s.lanes.append(gpa, .{ .x = body.x + 1, .y = body.y + @as(u16, @intCast(vr)), .level = @intCast(level), .rgb = .{ @intCast(line), @intCast(level), 0x37 } }); + } +} + +/// The frame's lane strips (testLanes') against where their lines are +/// drawn: line L of a body whose first line is the core's `top`, its rows +/// `lag` behind (a glide's offset or a touchpad's fraction), at body row +/// L - top - lag (emitScrollRows), with its strips there, cut to the body; +/// a line drawn outside it, none. +fn expectLanesRide(g: *Gui, gpa: std.mem.Allocator, core: *pardes.Pardes, s: *const pardes.Surface, lag: f32) !void { + g.decor.clearRetainingCapacity(); + var groups: Groups = .{}; + const layout = fixedCellLayout(g); + const win_h: f32 = @floatFromInt(@as(u32, s.rows) * g.cell_h); + try buildDecor(g, gpa, s, &groups, layout, @floatFromInt(@as(u32, s.cols) * g.cell_w), win_h, false); + const body = testBody(core, s); + const top = core.panes[core.view().active].?.scroll(); + const body_y0 = @as(f32, @floatFromInt(body.y)) * layout.h; + const body_y1 = @as(f32, @floatFromInt(body.y + body.h)) * layout.h; + var strips: [256]u8 = @splat(0); + for (g.decor.items) |item| { + if (@abs(item.bb * 255 - 0x37) > 0.01 or item.bg * 255 > 2.01) continue; + const line: u8 = @intFromFloat(@round(item.br * 255)); + const at = (@as(f32, @floatFromInt(body.y)) + @as(f32, @floatFromInt(@as(i32, line) - top)) - lag) * layout.h; + try std.testing.expectApproxEqAbs(@max(at, body_y0), (1 - item.y0) / 2 * win_h, 0.01); + try std.testing.expectApproxEqAbs(@min(at + layout.h, body_y1), (1 - item.y1) / 2 * win_h, 0.01); + strips[line] += 1; + } + for (strips, 0..) |n, line| { + const at = (@as(f32, @floatFromInt(body.y)) + @as(f32, @floatFromInt(@as(i32, @intCast(line)) - top)) - lag) * layout.h; + const shown = @min(at + layout.h, body_y1) - @max(at, body_y0); + // A sliver under a hundredth of a pixel either way. + if (@abs(shown) < 0.01) continue; + try std.testing.expectEqual(@as(usize, if (shown > 0) 1 + line % 3 else 0), n); + } +} + +test "a change's lanes ride their lines: mid-glide (a wheel's notch, Ctrl-d) and under a touchpad's fraction each strip is where its line is drawn, cut to the body, and the rows that left keep theirs" { + const gpa = std.testing.allocator; + { + const core = try pardes.Pardes.init(gpa, .{ .cols = 80, .rows = 24 }); + defer core.deinit(); + var text: std.ArrayList(u8) = .empty; + defer text.deinit(gpa); + for (0..200) |i| try text.print(gpa, "line {d}\n", .{i}); + _ = try core.setTestFile(text.items); + for ("100G") |ch| core.update(.{ .key = .{ .cp = ch, .text = &.{ch} } }); + var arena: std.heap.ArenaAllocator = .init(gpa); + defer arena.deinit(); + var g = testGui(10, 20, 6, 12); + defer g.glide.deinit(gpa); + defer g.decor.deinit(gpa); + const r = core.view().rects[core.view().active]; + g.scroll_pane = core.view().active; + g.scroll_col = r.x + 10; + g.scroll_row = r.y + r.h - 2; + var now: u64 = std.time.ns_per_s; + var mid: usize = 0; + // The view drawn once at rest, then a notch down (the wheel's) and + // Ctrl-d, each glided to rest, every frame checked. + for ([_]?pardes.Key{ null, null, .{ .cp = 'd', .ctrl = true } }, 0..) |key, step| { + if (key) |k| core.update(.{ .key = k }) else if (step > 0) g.scroll_notch = 1; + var frames: usize = 0; + while (true) : (frames += 1) { + stepGlide(&g, core); + now += std.time.ns_per_s / 60; + core.advance(now); + _ = arena.reset(.retain_capacity); + const s = try core.render(arena.allocator()); + try testLanes(gpa, core, s); + g.now_ns = now; + glideFrame(&g, gpa, s); + if (g.glide.follow.offset != 0) mid += 1; + try expectLanesRide(&g, gpa, core, s, g.glide.follow.offset); + if (!g.glide.moving()) break; + if (frames > 200) return error.NeverSettled; + } + } + try std.testing.expect(mid > 10); + } + // A touchpad's half notch down, settled, then up: the text half a row + // off its cells, and the row that left in the half row it opens. + const core = try wheelRunFile(gpa); + defer core.deinit(); + var wr = try WheelRun.init(gpa, core); + defer wr.deinit(gpa); + defer wr.g.decor.deinit(gpa); + wr.lanes = true; + core.needs_frame = true; + try wr.frame(gpa, &.{}); + for ([_]f32{ -0.5, 0.5 }) |turn| { + try wr.frame(gpa, &.{turn}); + try std.testing.expectEqual(turn, wr.g.scroll_lag); + try expectLanesRide(&wr.g, gpa, core, wr.g.frame.?, wr.g.scroll_lag); + for (0..20) |_| try wr.frame(gpa, &.{}); + try std.testing.expectEqual(@as(f32, 0), wr.g.scroll_lag); + try expectLanesRide(&wr.g, gpa, core, wr.g.frame.?, 0); + } +} + test "every scroll glides on one law: a half page, a page, the far jumps, a run of them retargeting" { const gpa = std.testing.allocator; const core = try pardes.Pardes.init(gpa, .{ .cols = 100, .rows = 40 }); diff --git a/dev/tui/tui.zig b/dev/tui/tui.zig index 5d75722f..d1bbe140 100644 --- a/dev/tui/tui.zig +++ b/dev/tui/tui.zig @@ -791,6 +791,9 @@ pub fn runClient(init: std.process.Init, opts: pardes.Options, path: []const u8, .client = &c, .peers = &no_peers, .ptys = &no_ptys, + // Its own motions (the glide) on the case's clock, as a session's + // own terminal's (`Own.open`). + .test_clock = host_io.testClock(), }; tty = .{ .sh = &sh, .screen = &screen, .loop = &loop, .joins = &start }; no_inbox.wake_fn = Shell.wakeForQueue; @@ -1490,11 +1493,16 @@ const Shell = struct { } else next: { if (wait != 0) { // A virtual clock moves a frame a wake while the tty's own - // motions move (the glide), as the real one would. - s.wake_to = s.core.nextWake() orelse if (s.moving()) s.core.clock.now_ns + pardes.frame_ns else 0; + // motions move (the glide), as the real one would: a + // client's from where it is, its core's clock and wakes + // the session's, still between units. + s.wake_to = if (s.client != null) + (if (s.moving()) (s.test_clock orelse 0) + pardes.frame_ns else 0) + else + s.core.nextWake() orelse if (s.moving()) s.core.clock.now_ns + pardes.frame_ns else 0; requestWake(s.io, wait); } - pardes.turn.rest(); + pardes.turn.listen(); const got = s.loop.nextEvent() catch { pardes.turn.wake(); if (s.client) |c| c.link.quit = true; diff --git a/runtime/9p_io.zig b/runtime/9p_io.zig index 1079b102..50011690 100644 --- a/runtime/9p_io.zig +++ b/runtime/9p_io.zig @@ -183,8 +183,13 @@ pub const Listener = struct { const refused = pardes.ctlfs.Reply.fail(req.tag, pardes.ctlfs.E.IO); return conn.reply(&refused, ""); } - const quiet = pardes.turn.take(); + _ = pardes.turn.take(); defer pardes.turn.give(); + // What changes the core comes after the output already read out of + // the ptys (a pane's `cmd | pardes -`: its pager after the line's + // echo); quiet asked after that wait, which gave the turn up. + if (pardes.ctlfs.needsQuiet(l.core, req)) pardes.turn.awaitOutput(); + const quiet = pardes.turn.out == 0; // A connection a Restore is cutting (`reset`) is the old editor's // client: its fids name the old editor's panes and opens. if (l.cutting(conn)) { diff --git a/test/daemon.py b/test/daemon.py index 6e7bad3f..dc1abcbc 100644 --- a/test/daemon.py +++ b/test/daemon.py @@ -925,7 +925,11 @@ def pair_rows(binary): t, c, nine, session, pane = started('lone', dict(env, PARDES_DAEMON='off')) typed_detach(t, nine, pane) time.sleep(1) - assert c.poll() is None and alive(session), 'a Detach with no daemon is refused' + # Which went, if one did: the client's exit and its screen's last + # words, the session's life (its stderr is /dev/null: no log). + went = [w for w, gone in (('the client', c.poll() is not None), ('the session', not alive(session))) if gone] + assert not went, (f'a Detach with no daemon is refused: {" and ".join(went)} went (client exit {c.poll()}, ' + f'session {"alive" if alive(session) else "gone"}); the terminal\'s last bytes: {t.text()[-600:]!r}') nine.socket.close() t.close() terms.remove(t) diff --git a/test/kitty.zig b/test/kitty.zig index 22b62fb2..0bd849c2 100644 --- a/test/kitty.zig +++ b/test/kitty.zig @@ -641,7 +641,7 @@ test "kitty: an image follows its text when the shell scrolls, resizes and reflo try std.testing.expectEqual(o.y + 2, (try r.placesOf(10))[0].dst.y); // A narrower pane reflows the text; the image stays on its row. const pane = r.pane(0); - pane.resizeGrid(0, 40, pane.rows); + pane.resizeGrid(r.p, 40, pane.rows); const text = try pardes.Term.scrollback(pane.terminal, r.frame.allocator()); var row: usize = 0; var lines = std.mem.splitScalar(u8, text, '\n'); @@ -1167,7 +1167,7 @@ fn fuzzRun(seed: u64, steps: usize, trace: bool) !bool { r.p.update(.{ .resize = .{ .cols = cols, .rows = rows, .cell_pixels = .{ .w = 1 + rng.uintLessThan(u16, 30), .h = 1 + rng.uintLessThan(u16, 60) } } }); r.drain(); }, - 1 => r.pane(0).resizeGrid(0, 1 + rng.uintLessThan(u16, 120), 1 + rng.uintLessThan(u16, 40)), + 1 => r.pane(0).resizeGrid(r.p, 1 + rng.uintLessThan(u16, 120), 1 + rng.uintLessThan(u16, 40)), 2, 3 => { const drawn = try r.places(); if (trace) std.debug.print(" {d} places, {d} placements, {d} images\n", .{ drawn.len, r.placementCount(0), r.storage(0).images.count() }); diff --git a/test/perf.zig b/test/perf.zig index 30e15dcc..8622e31b 100644 --- a/test/perf.zig +++ b/test/perf.zig @@ -316,6 +316,7 @@ fn measureCreation(io: std.Io, reps: usize, json: bool) !void { for ([_]bool{ false, true }) |terminal| { var cold_ns: u64 = 0; var cold_deinit_ns: u64 = 0; + var outside: pardes.Term.Outside = .{}; var calls: usize = 0; var bytes: usize = 0; var live: usize = 0; @@ -325,12 +326,12 @@ fn measureCreation(io: std.Io, reps: usize, json: bool) !void { const allocator = counter.allocator(); const begin = nowNs(); const pane = if (terminal) - try pardes.panes.createTerminal(allocator, screen_cols, screen_rows) + try pardes.panes.createTerminal(&outside, allocator, screen_cols, screen_rows) else try pardes.panes.createDoc(allocator, screen_cols, screen_rows); const constructed = nowNs(); const retained = counter.live; - if (pane.terminal) |state| pardes.Term.close(state, allocator); + if (pane.terminal) |state| pardes.Term.close(&outside, state); allocator.destroy(pane); const destroyed = nowNs(); if (counter.live != 0) return error.LeakedPaneMemory; diff --git a/test/replicas.zig b/test/replicas.zig index a68ce222..8f3e5ca5 100644 --- a/test/replicas.zig +++ b/test/replicas.zig @@ -51,6 +51,12 @@ var trace = false; /// `--witness`: the witness judged at every run's end, not only after a /// divergence (`Witness`). var witness_always = false; +/// `--pair`: client 0 is the session's pair client (Options.pair: a +/// terminal's `pardes` as a client and its session): joined before the +/// session's first effects, its core its own boot (replica.ownBoot), the +/// welcome's digest its check (confirmBoot), the session's own frontend +/// gone (no typist, its view the pair's). +var pair_mode = false; /// The PDF the soak opens (`--pdf`), absolute. var pdf_path: ?[]const u8 = null; const frame_us = 16_667; @@ -246,6 +252,10 @@ const Totals = struct { /// (PARDES_TEST_DIVERGE's), and clients that left; quiet checks. joins: u64 = 0, refused: u64 = 0, + /// A pair's client's own boot the session's core at its join (`--pair`), + /// or not (its dump loaded instead, the fields that differ said). + boots: u64 = 0, + boots_unequal: u64 = 0, rejoined: u64 = 0, detached: u64 = 0, agree: u64 = 0, @@ -1173,6 +1183,9 @@ const Soak = struct { /// `Peers.detach` shut its link; the session's own view's is its /// terminal's, which the soak has none of). detach_view: ?u8 = null, + /// `--pair`: the session's end of client 0's link, its first client's + /// (`options`). + pair_fd: c_int = -1, // ---- the soak ---- /// The soak's time (us): the last message's. @@ -1219,7 +1232,7 @@ const Soak = struct { /// its own (Core.render: drawn whenever a frame is owed and someone /// sees it, and a terminal is always seen). fn watchedHost(_: ?*anyopaque) bool { - return true; + return !pair_mode; } fn ptyWrite(ctx: ?*anyopaque, id: pardes.Pane.Id, bytes: []const u8) void { @@ -1289,7 +1302,10 @@ const Soak = struct { // ---- the session loop's frontend ---- - pub fn options(_: *Soak, _: *pardes.Options) void {} + /// A pair's: its first client on the link `run` made. + pub fn options(s: *Soak, o: *pardes.Options) void { + if (s.pair_fd >= 0) o.pair = s.pair_fd; + } pub fn open(s: *Soak, l: *SessionLoop) !pardes.Host { s.l = l; @@ -1354,6 +1370,8 @@ const Soak = struct { // let go); the first leaves when it is done; the second is put off // the session once (PARDES_TEST_DIVERGE) and joins again for its view. for (s.clients, 0..) |*cl, c| { + // A pair's client joined at the loop's start. + if (pair_mode and c == 0) continue; cl.dialling = true; const at: u64 = switch (c) { 0, 1 => s.random.uintLessThan(u64, 100_000), @@ -1365,7 +1383,7 @@ const Soak = struct { }; try net.send(.{ .at = at, .n = 0, .kind = .dial, .who = @intCast(c + 1), .bytes = &.{} }); } - try net.send(.{ .at = s.random.uintLessThan(u64, 200_000), .n = 0, .kind = .own, .who = 0, .bytes = &.{} }); + if (!pair_mode) try net.send(.{ .at = s.random.uintLessThan(u64, 200_000), .n = 0, .kind = .own, .who = 0, .bytes = &.{} }); try net.send(.{ .at = tui_at, .n = 0, .kind = .output, .who = 0, .bytes = &.{} }); try net.send(.{ .at = session_at, .n = 0, .kind = .output, .who = 2, .bytes = &.{} }); try net.send(.{ .at = flood_at, .n = 0, .kind = .output, .who = 1, .bytes = &.{} }); @@ -1933,7 +1951,7 @@ const Soak = struct { try s.totals.add(&old.stats); old.deinit(); } - const rp = try replica.Replica.initDump(gpa, cl.id, cl.view, m.bytes, .{ .cols = cl.cols, .rows = cl.rows, .distrusted = &cl.distrusted }); + const rp = if (pair_mode and c == 0 and !s.has_link[0]) try s.booted(cl, m.bytes) else try replica.Replica.initDump(gpa, cl.id, cl.view, m.bytes, .{ .cols = cl.cols, .rows = cl.rows, .distrusted = &cl.distrusted }); cl.r = rp; // In process: its clock reads are the session's machine's, and the // units' heads carry the soak's clock (`stamp`). @@ -1978,6 +1996,29 @@ const Soak = struct { if (cl.left > 0 and cl.left == s.r.steps) try net.send(.{ .at = m.at + typistGap(s.random), .n = 0, .kind = .input, .who = m.who, .bytes = &.{} }); } + /// A pair's client's replica: its core its own boot from the options + /// the session was started with (`run`'s), as the pair's client makes + /// it (replica.ownBoot), kept when the welcome's digest is its own + /// (confirmBoot); else the session's dump, loaded, and the fields of + /// the two cores that differ said. + fn booted(s: *Soak, cl: *Client, dump: []const u8) !*replica.Replica { + s.totals.boots += 1; + const boot = try replica.Replica.initBoot(gpa, .{ .cols = 100, .rows = 30, .boot = .tty, .distrusted = &cl.distrusted }); + if (boot.digest() == cl.digest) { + boot.id = cl.id; + boot.view = cl.view; + return boot; + } + defer boot.deinit(); + s.totals.boots_unequal += 1; + const rp = try replica.Replica.initDump(gpa, cl.id, cl.view, dump, .{ .cols = cl.cols, .rows = cl.rows, .distrusted = &cl.distrusted }); + var buf: [4096]u8 = undefined; + var w: std.Io.Writer = .fixed(&buf); + Witness.fieldsDiffer(boot.core(), rp.core(), &w); + std.debug.print("seed {d} rtt {d} ms: the pair's own boot is not the session's core at its join; differ: {s}", .{ s.r.seed, s.r.rtt_ms, w.buffered() }); + return rp; + } + /// At quiescence: every client's digest the session's, its terminals /// the session's cell for cell, its files' texts byte for byte. fn finish(s: *Soak) !void { @@ -2114,6 +2155,12 @@ fn run(init: std.process.Init, r: Run, dir: []const u8, totals: *Totals) !void { var clients: [8]Client = undefined; for (clients[0..r.clients], 0..) |*cl, c| { cl.* = .{ .kind = if (c % 2 == 0) .tty else .window, .left = r.steps, .cols = @intCast(random.intRangeAtMost(u16, 60, 120)), .rows = @intCast(random.intRangeAtMost(u16, 16, 40)) }; + // A pair's client is the terminal the session was started at the + // size of (main.zig `pair`). + if (pair_mode and c == 0) { + cl.cols = 100; + cl.rows = 30; + } var name: [300]u8 = undefined; cl.check = try gpa.dupeSentinel(u8, try std.fmt.bufPrint(&name, "{s}/check-{d}", .{ dir, c }), 0); _ = libc.unlink(cl.check); @@ -2157,9 +2204,23 @@ fn run(init: std.process.Init, r: Run, dir: []const u8, totals: *Totals) !void { .flood = flood, .yes_len = yes.len, .own_left = r.steps, - .typing = r.clients + 1, + .typing = r.clients + @intFromBool(!pair_mode), .media = &media, }; + // A pair's client's link, made before the session (main.zig `pair`): + // its end handed to the session's options, the soak reading the other + // as for a dial (`.dial`). + if (pair_mode) { + const cl = &clients[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; + _ = libc.fcntl(fds[0], libc.F.SETFL, @as(c_int, @bitCast(libc.O{ .NONBLOCK = true }))); + cl.sfd = fds[0]; + cl.cfd = fds[1]; + cl.handed = libc.dup(fds[0]); + if (cl.handed < 0) return error.NoSocket; + soak.pair_fd = cl.handed; + } // The session: THE session loop, from its start to its end. try SessionLoop.run(init, .{ .cols = 100, .rows = 30, .boot = .tty }, &soak); if (soak.err) |err| return err; @@ -3248,6 +3309,10 @@ pub fn main(init: std.process.Init) !void { witness_always = true; continue; } + if (std.mem.eql(u8, name, "--pair")) { + pair_mode = true; + continue; + } if (i + 1 >= args.len) return error.MissingValue; i += 1; const value = args[i]; @@ -3313,6 +3378,8 @@ pub fn main(init: std.process.Init) !void { pardes.Term.reloads = .{}; for (first..first + seeds) |seed| try run(init, .{ .seed = seed, .rtt_ms = rtt, .steps = steps, .clients = clients, .flood_mb = flood_mb }, dir, &t); std.debug.print("rtt {d}: {d} reloads of a terminal at joins, every side (the session's own too), {d} us each, {d} us at worst; {d} kitty images in clients at quiescence, each the session's pixels\n", .{ rtt, pardes.Term.reloads.n, pardes.Term.reloads.ns / @max(1, pardes.Term.reloads.n) / 1000, pardes.Term.reloads.worst_ns / 1000, t.images_equal }); + if (pair_mode) std.debug.print("rtt {d}: the pair's client booted its own core {d} times, {d} of them not the session's at its join\n", .{ rtt, t.boots, t.boots_unequal }); + if (t.boots_unequal > 0) t.unequal += t.boots_unequal; const rollbacks = t.mispredicted + t.foreign; std.debug.print("{d:>4} {d:>6} {d:>7} {d:>7} {d:>6} {d:>6} {d:>6} ({d}+{d}) {d:>5.1}% {d:>6} {d:>5}/{d:<6} {d:>5}/{d:<5} ({d}) {d:>7}/{d:<7} {d:>8} {d:>7}\n", .{ rtt, t.inputs, t.speculated, diff --git a/test/terminal.zig b/test/terminal.zig index bad70081..03bcd294 100644 --- a/test/terminal.zig +++ b/test/terminal.zig @@ -82,9 +82,10 @@ fn lineBreaks(comptime n: usize) [2 * n]u8 { test "replay ownership is terminal-only and construction rolls back on allocation failure" { const Case = struct { fn run(gpa: std.mem.Allocator, terminal: bool) !void { - const pane = if (terminal) try panes.createTerminal(gpa, 40, 12) else try panes.createDoc(gpa, 40, 12); + var outside: Term.Outside = .{}; + const pane = if (terminal) try panes.createTerminal(&outside, gpa, 40, 12) else try panes.createDoc(gpa, 40, 12); defer gpa.destroy(pane); - defer if (pane.terminal) |state| close(state, gpa); + defer if (pane.terminal) |state| close(&outside, state); try std.testing.expectEqual(terminal, pane.terminal != null); } }; @@ -98,7 +99,6 @@ test "document construction allocates only the pane and has inert terminal defau const allocator = failing.allocator(); const pane = try panes.createDoc(allocator, 40, 12); defer allocator.destroy(pane); - defer if (pane.terminal) |state| close(state, allocator); try std.testing.expect(pane.terminal == null); try std.testing.expectEqual(@as(usize, 1), failing.alloc_index); try std.testing.expectEqual(@as(usize, 0), failing.resize_index); @@ -109,7 +109,7 @@ test "document construction allocates only the pane and has inert terminal defau try std.testing.expectEqual(Term.Prompt{}, prompt(pane.terminal)); pane.scrollBy(100); pane.followOutput(); - pane.resizeGrid(0, 80, 24); + pane.resizeGrid(undefined, 80, 24); // no terminal: the core is never read try std.testing.expectEqual(Term.Grid{}, grid(pane.terminal)); try std.testing.expectEqualStrings("", try scrollback(pane.terminal, allocator)); try std.testing.expect(!failing.has_induced_failure); |
