diff options
| author | Gabriel Schneider <[email protected]> | 2026-11-22 17:55:03 -0300 |
|---|---|---|
| committer | Gabriel Schneider <[email protected]> | 2026-11-22 19:48:03 -0300 |
| commit | 8e850e6c923dcd84b7a5483f73377bd192b94a2b (patch) | |
| tree | 0730a84095f75d8a46e4dcdfebddb8d8b90af7c6 | |
| parent | bad506bd45846e012246a33b5d3097b3e92f02bc (diff) | |
| download | pardes-8e850e6c923dcd84b7a5483f73377bd192b94a2b.tar.gz pardes-8e850e6c923dcd84b7a5483f73377bd192b94a2b.zip | |
terminals: where a view stands in a terminal's history is the view's, not the emulator's (pardes-term-join-10, item 1; the note's point 3, the coordinator's choice): `Pane.scrolled_to` (core/panes.zig), a per-view field (views.zig `pane_fields`, `PaneView`: in the rollback copy, the digest and the dump, each view's own), the row its top shows or null on the output, written only by a step (`scrollBy`, `followOutput`), and carried with every open view's through each write of the emulator that moves rows, once, in the confirmed unit's apply, on every side alike (`Term.feed`/`Term.resize` take the places; core/term/terminal.zig `carry`/`carried` pin each place's row on the primary screen and read the pin back: up by the rows the history drops, 0 when its own row goes, null in the active area or after a reset: a function of the fed bytes); the draw reads the rows from the view's place (`viewport`, `paint`, `ImagesAt.place`, terminal.zig `shown`), and ghostty's own viewport is never moved, read, digested or dumped (`Grid.offset`/`view`, `Parts.view` and the digest's offset gone): two clients no longer scroll one viewport (the new views.zig test failed on the base, `expected 80, found 77`), and a speculation's scroll is in the copy, so `putViews`, the view half of `keepViews` (now `keepSerials`), `viewTo`/`scroll`/`follow` (ops, wrappers, bodies), the Debug screen hash's view exclusion, `reflow`'s column-0 cure and `feedOutput`'s follow-after-read are deleted, and S1's `calls` lists no view write (the rows `viewTo`, `scroll`, `follow` gone); tests: the two-view test (with a dump), the place at the history's cap (`setMaxBytes(1)`), a 300-seed fuzz of the carried place against ghostty's own pinned view, a client's wheel over a shared terminal through output and a rollback, round 6's order explorer (30 seeds a run); the wire at 31 (abi/wire.zig, test/daemon.py `WIRE`): an installed build's dump loads with every view on the output; IN THE WORKSPACE core-test 912/1072 (160 skipped), shell-test 1114/1117 (3 skipped), term-test 16/16, kitty-test 45/45, pane-test 181/182, behaviour-test 275/275, --replay 275/275, process-test 0 of 146 failed, as pairs 0 of 146; gui unit-test 1707/1711, its one error BaselineHarnessMismatch (every base's)
Co-Authored-By: Claude Opus <[email protected]>
Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T
| -rw-r--r-- | abi/term.zig | 56 | ||||
| -rw-r--r-- | abi/wire.zig | 5 | ||||
| -rw-r--r-- | core/Core.zig | 18 | ||||
| -rw-r--r-- | core/Jump.zig | 2 | ||||
| -rw-r--r-- | core/Term.zig | 82 | ||||
| -rw-r--r-- | core/ansi.zig | 5 | ||||
| -rw-r--r-- | core/body_layer.zig | 19 | ||||
| -rw-r--r-- | core/draw.zig | 9 | ||||
| -rw-r--r-- | core/echo.zig | 13 | ||||
| -rw-r--r-- | core/edit.zig | 2 | ||||
| -rw-r--r-- | core/exec.zig | 5 | ||||
| -rw-r--r-- | core/keys.zig | 9 | ||||
| -rw-r--r-- | core/mouse.zig | 2 | ||||
| -rw-r--r-- | core/ninep/pty.zig | 4 | ||||
| -rw-r--r-- | core/panes.zig | 116 | ||||
| -rw-r--r-- | core/replica.zig | 206 | ||||
| -rw-r--r-- | core/term/TerminalImages.zig | 25 | ||||
| -rw-r--r-- | core/term/term.zig | 3 | ||||
| -rw-r--r-- | core/term/terminal.zig | 317 | ||||
| -rw-r--r-- | core/views.zig | 55 | ||||
| -rw-r--r-- | test/daemon.py | 2 | ||||
| -rw-r--r-- | test/kitty.zig | 8 | ||||
| -rw-r--r-- | test/panes.zig | 14 | ||||
| -rw-r--r-- | test/perf.zig | 2 | ||||
| -rw-r--r-- | test/replicas.zig | 19 | ||||
| -rw-r--r-- | test/terminal.zig | 6 |
26 files changed, 683 insertions, 321 deletions
diff --git a/abi/term.zig b/abi/term.zig index d6c48f96..31f155e8 100644 --- a/abi/term.zig +++ b/abi/term.zig @@ -13,22 +13,19 @@ const CellStyle = plain.CellStyle; /// A terminal: its emulator, its parse and what is kept beside it. pub const State = opaque {}; -/// Where the view and the cursor are, in rows counted from the top of the -/// history: `total` rows, the view's top at `offset`, `len` of them shown. -/// All zero without a terminal. +/// How much history there is and where the cursor is, in rows counted from +/// the top of the history: `total` rows, the last `len` of them the active +/// area (the program's screen). All zero without a terminal. Where a view +/// of it stands is the view's, not the terminal's (a `place`: the row its +/// top shows, or null on the output; core/panes.zig `scrolled_to`). pub const Grid = struct { total: usize = 0, - offset: usize = 0, len: usize = 0, - /// The cursor, in cells of the active area (the history's last `len` - /// rows). + /// The cursor, in cells of the active area. cursor_x: u16 = 0, cursor_y: u16 = 0, /// The program shows the cursor (DECTCEM). cursor_visible: bool = false, - /// The view's top row while it is scrolled to one, null while it - /// follows the output. - view: ?usize = null, /// Its grid's width. cols: u16 = 0, }; @@ -211,6 +208,8 @@ pub const PaintedRow = struct { /// `rows_of[v]` is the body row its view's row `v` shows on, null for one /// not shown. pub const ImagesAt = struct { + /// The view's place (`Grid`): the rows it shows. + place: ?usize, pane: u8, serial: u32, tx: u16, @@ -239,8 +238,6 @@ pub const EchoCell = struct { cp: u21, input: bool, style: u32 }; pub const Parts = struct { reply: []const u8 = "", reply_dropped: u32 = 0, - /// The view's top row, counted from the top of the history. - view: usize = 0, phase: Prompt.Phase = .none, started: u32 = 0, prompts: u32 = 0, @@ -293,8 +290,8 @@ pub const Ops = struct { gpa: *const fn (s: *const State) std.mem.Allocator, // ---- the dump and the digest (`Term.State`'s walk hooks) ---- - /// Its screen into the replay digest (`view`: where its view is too). - digest: *const fn (s: *const State, h: *std.hash.Wyhash, view: bool) void, + /// Its screen into the replay digest. + digest: *const fn (s: *const State, h: *std.hash.Wyhash) void, /// What the dump keeps of it beside its emulator. parts: *const fn (s: *const State) Parts, /// Its emulator as the dump keeps it (ghostty's snapshot); `slim`: its @@ -309,16 +306,19 @@ pub const Ops = struct { /// now on (the core's: a recorded answer). media: *const fn (read: Media) void, - // ---- output and view ---- + // ---- output and size ---- /// One read of its program's output (`Told` says where the tracked - /// rows went). - feed: *const fn (s: *State, bytes: []const u8, track: []const i32, rows: []i32, erased: []bool) Told, + /// rows went), every view's `places` carried through it (`resize`). + feed: *const fn (s: *State, bytes: []const u8, track: []const i32, rows: []i32, erased: []bool, places: []?usize) Told, // A null handle: what a pane without a terminal is told (all zero). grid: *const fn (s: ?*const State) Grid, - viewTo: *const fn (s: *State, at: ?usize) void, - scroll: *const fn (s: *State, delta: i32) void, - follow: *const fn (s: *State) void, - resize: *const fn (s: *State, cols: u16, rows: u16) void, + /// Its grid reflowed, every view's place (`Grid`) carried through it as + /// ghostty carries a view of its own: on its row while rows come below, + /// up by the rows the history drops above it, at the history's top when + /// its own row goes, on the output once it falls into the active area + /// or the screen is reset. A function of the bytes and sizes it was + /// given: the same places on every side. + resize: *const fn (s: *State, cols: u16, rows: u16, places: []?usize) void, cellPixels: *const fn (s: *State, w: u32, h: u32) void, replies: *const fn (s: *State) []const u8, @@ -328,6 +328,8 @@ pub const Ops = struct { wheel: *const fn (s: *State, last: *?Parts.Coordinate, buf: *[64]u8, turn: MouseButton, col: u16, row: u16, mods: MouseMods) ?[]const u8, paste: *const fn (s: ?*const State, text: []u8) [3][]const u8, modes: *const fn (s: ?*const State) Modes, + /// The cursor keys a click at its row `row` (from the top of its + /// history), column `col` of the text shown types at the prompt. promptMoves: *const fn (s: *State, row: i32, col: i32) ?Moves, // ---- prompt and commands ---- @@ -339,7 +341,8 @@ pub const Ops = struct { scrollback: *const fn (s: ?*State, gpa: std.mem.Allocator) error{ OutOfMemory, WriteFailed }![]const u8, scrollbackLen: *const fn (s: ?*State) usize, textRows: *const fn (s: *State, alloc: std.mem.Allocator, scratch: std.mem.Allocator) TextError!Rows, - viewport: *const fn (s: *State, arena: std.mem.Allocator, cut: bool) TextError![]const []const u8, + /// The rows a view at `place` (`Grid`) shows, as text. + viewport: *const fn (s: *State, arena: std.mem.Allocator, cut: bool, place: ?usize) TextError![]const []const u8, /// Its rows `first` and the `count` after it (from the top of its /// history) as text, a prompt's own cells cut off: `arena`'s. editRows: *const fn (s: *State, arena: std.mem.Allocator, first: usize, count: usize) (TextError || error{ NoRow })![]const []const u8, @@ -358,10 +361,11 @@ pub const Ops = struct { spanColor: *const fn (f: *Filter, color: Color, is_bg: bool) Color, // ---- draw ---- - /// Its view's rows, `rows.len` of them, `cols` cells each, into - /// `cells`: each cell's style in the theme's colours (through the - /// filter when `filtered`), its bytes and width. - paint: *const fn (s: *State, ink: *const Ink, palette: *FilterPalette, filtered: bool, first: u16, cols: u16, cells: []Painted, rows: []PaintedRow) void, + /// The rows a view at `place` (`Grid`) shows from its row `first`, + /// `rows.len` of them, `cols` cells each, into `cells`: each cell's + /// style in the theme's colours (through the filter when `filtered`), + /// its bytes and width. + paint: *const fn (s: *State, ink: *const Ink, palette: *FilterPalette, filtered: bool, place: ?usize, first: u16, cols: u16, cells: []Painted, rows: []PaintedRow) void, /// Its kitty images over the body's rows, appended to `out` (`gpa`'s; /// what it keeps to draw them is its own allocator's), and their /// placeholder cells blanked in `frame` (`frame_cols` wide). @@ -380,7 +384,7 @@ pub const Ops = struct { /// file, with its rule: a new one fails its test until it is listed. pub const replicated = [_][]const u8{ "open", "close", "revive", "digest", "parts", "snapshot", "load", "reload", - "media", "feed", "grid", "viewTo", "scroll", "follow", "resize", "replies", + "media", "feed", "grid", "resize", "replies", "key", "mouse", "wheel", "paste", "modes", "promptMoves", "prompt", "commandOutput", "endOutputHere", "scrollback", "scrollbackLen", "textRows", "viewport", "editRows", "promptCut", "page", "filter", "spanColor", "hasImages", diff --git a/abi/wire.zig b/abi/wire.zig index 8f7a7bdb..46e51645 100644 --- a/abi/wire.zig +++ b/abi/wire.zig @@ -10,6 +10,9 @@ const pardes = @import("core"); const config = @import("pardes_options"); 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); /// 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 @@ -59,7 +62,7 @@ const build_info = @import("build_info"); /// part B); 14: the hello names a session and /// carries the semantics hash, and a ping is answered (phase 5's /// groundwork); 13: the frames went (phase 3). -pub const version: u16 = 30; +pub const version: u16 = 31; /// The terminal's build and the window's step alike (`semantics`). const family = switch (config.platform) { diff --git a/core/Core.zig b/core/Core.zig index 1dd03524..2d832f48 100644 --- a/core/Core.zig +++ b/core/Core.zig @@ -1973,7 +1973,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(cols, rows); + pane.resizeGrid(p.live, 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; @@ -3865,11 +3865,11 @@ test "raw terminal cursor follows its active row only while that row is visible" try std.testing.expectEqual(rect.x + config.GUTTER + 3, live.x); try std.testing.expectEqual(body_y + 2, live.y); - pardes.Term.scroll(pane.terminal.?, -1); + pane.scrollBy(-1); const scrolled = (try p.render(frame.allocator())).cursor orelse return error.MissingCursor; try std.testing.expectEqual(live.x, scrolled.x); try std.testing.expectEqual(live.y + 1, scrolled.y); - pardes.Term.scroll(pane.terminal.?, -@as(i32, pane.rows)); + pane.scrollBy(-@as(i32, pane.rows)); try std.testing.expect((try p.render(frame.allocator())).cursor == null); pane.followOutput(); const returned = (try p.render(frame.allocator())).cursor orelse return error.MissingCursor; @@ -3919,31 +3919,31 @@ test "tty output follows only from the bottom" { p.update(.{ .output = .{ .pane = .at(shell), .bytes = std.fmt.bufPrint(&buf, "line {d}\r\n", .{i}) catch unreachable } }); } p.sync(); - const bottom = pardes.Term.grid(sp.terminal).offset; + const bottom = sp.termTop(); try std.testing.expect(bottom > 0); // Scrolled back, the reader stays put however much the shell prints. sp.scrollBy(-10); p.sync(); - const parked = pardes.Term.grid(sp.terminal).offset; + const parked = sp.termTop(); try std.testing.expect(parked < bottom); for (60..70) |i| { var buf: [32]u8 = undefined; p.update(.{ .output = .{ .pane = .at(shell), .bytes = std.fmt.bufPrint(&buf, "line {d}\r\n", .{i}) catch unreachable } }); } p.sync(); - try std.testing.expectEqual(parked, pardes.Term.grid(sp.terminal).offset); + try std.testing.expectEqual(parked, sp.termTop()); // Typing snaps back to live output, so nobody types blind. p.update(.{ .key = .{ .cp = 'x', .text = "x" } }); p.sync(); - try std.testing.expect(pardes.Term.grid(sp.terminal).offset > parked); + try std.testing.expect(sp.termTop() > parked); // ...and from there output follows again. - const live = pardes.Term.grid(sp.terminal).offset; + const live = sp.termTop(); p.update(.{ .output = .{ .pane = .at(shell), .bytes = "tail\r\n" } }); p.sync(); - try std.testing.expect(pardes.Term.grid(sp.terminal).offset > live); + try std.testing.expect(sp.termTop() > live); } test "an unasked desktop paste reaches a tty pane's program, not its buffer" { diff --git a/core/Jump.zig b/core/Jump.zig index 66dbd2b6..aa633044 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(pane.cols - 1, pane.rows); + pane.resizeGrid(p.live, 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 580db4fa..b82017f6 100644 --- a/core/Term.zig +++ b/core/Term.zig @@ -14,8 +14,8 @@ 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, a -/// view moved, one opened, closed, loaded or made again): whether a unit's +/// 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; @@ -69,12 +69,7 @@ pub const State = struct { /// The emulator as its program has made it, for the replay digest. pub fn digest(s: *const State, h: *walk.Hasher) void { - s.digestScreen(h, true); - } - - /// `view`: where its view is too (a replica's speculation may move it). - pub fn digestScreen(s: *const State, h: *walk.Hasher, view: bool) void { - the().digest(s.impl, h, view); + the().digest(s.impl, h); } pub fn dumpWrite(s: *const State, gpa: std.mem.Allocator, w: *std.Io.Writer) !void { @@ -191,45 +186,29 @@ pub fn stop() void { if (ops) |o| o.stop(); } -// ---- output and view ---- +// ---- output and size ---- /// One read of its program's output (`Told` says where the tracked rows -/// went). -pub fn feed(s: *State, bytes: []const u8, tracked: []const i32, rows: []i32, erased: []bool) Told { +/// 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; s.written = true; - return the().feed(s.impl, bytes, tracked, rows, erased); + return the().feed(s.impl, bytes, tracked, rows, erased, places); } -/// Where the view and the cursor are; all zero without a terminal. +/// How much history it has and where its cursor is; all zero without a +/// terminal. Where a view stands in it is the view's (Pane.scrolled_to). pub fn grid(s: ?*const State) Grid { const o = ops orelse return .{}; return o.grid(if (s) |state| state.impl else null); } -/// Its view to a row of its history, or onto its output (null). -pub fn viewTo(s: *State, at: ?usize) void { - writes +%= 1; - the().viewTo(s.impl, at); -} - -/// Its view moved by a number of rows (negative scrolls back). -pub fn scroll(s: *State, delta: i32) void { - writes +%= 1; - the().scroll(s.impl, delta); -} - -/// Its view back onto its output. -pub fn follow(s: *State) void { - writes +%= 1; - the().follow(s.impl); -} - -/// Its grid reflowed. -pub fn resize(s: *State, cols: u16, rows: u16) void { +/// 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; s.written = true; - the().resize(s.impl, cols, rows); + the().resize(s.impl, cols, rows, places); } /// Its cells' size in pixels (kitty graphics, CSI 14/16 t). @@ -275,8 +254,8 @@ pub fn modes(s: ?*const State) Modes { return o.modes(if (s) |state| state.impl else null); } -/// How far left or right a click on the prompt line moves the shell's -/// cursor, at the prompt the cursor is at. +/// How far left or right a click on the prompt line (its row from the top of +/// the history) moves the shell's cursor, at the prompt the cursor is at. pub fn promptMoves(s: *State, row: i32, col: i32) ?Moves { return the().promptMoves(s.impl, row, col); } @@ -324,9 +303,10 @@ pub fn textRows(s: *State, alloc: std.mem.Allocator, scratch: std.mem.Allocator) return the().textRows(s.impl, alloc, scratch); } -/// The rows its view shows as text, prompts cut off or not. -pub fn viewport(s: *State, arena: std.mem.Allocator, cut: bool) iface.TextError![]const []const u8 { - return the().viewport(s.impl, arena, cut); +/// The rows a view at `place` (Pane.scrolled_to) shows as text, prompts +/// cut off or not. +pub fn viewport(s: *State, arena: std.mem.Allocator, cut: bool, place: ?usize) iface.TextError![]const []const u8 { + return the().viewport(s.impl, arena, cut, place); } /// Its rows `first` and the `count` after it as text, prompts cut off (the @@ -386,10 +366,11 @@ pub fn spanColor(f: *Filter, color: plain.Color, is_bg: bool) plain.Color { // images as placements; which of the body's rows they stand under is the // core's (core/ansi.zig). -/// Its view's rows from `first`, `rows.len` of them, as cells in the -/// theme's colours, through the theme's filter when the pane has it on. -pub fn paint(s: *State, ink: *const Ink, palette: *FilterPalette, filtered: bool, first: u16, cols: u16, cells: []Painted, rows: []PaintedRow) void { - the().paint(s.impl, ink, palette, filtered, first, cols, cells, rows); +/// The rows a view at `place` (Pane.scrolled_to) shows from its row +/// `first`, `rows.len` of them, as cells in the theme's colours, through +/// the theme's filter when the pane has it on. +pub fn paint(s: *State, ink: *const Ink, palette: *FilterPalette, filtered: bool, place: ?usize, first: u16, cols: u16, cells: []Painted, rows: []PaintedRow) void { + the().paint(s.impl, ink, palette, filtered, place, first, cols, cells, rows); } /// Its kitty graphics over the body's rows, as placements. @@ -422,16 +403,13 @@ pub const calls = [_]struct { []const u8, []const u8, []const u8 }{ .{ "close", "panes.zig:1", "WRITE: let go by a step that closes its pane: a copy held across it is let go (retiring panes); a unit that closes one is never kept over a copy" }, .{ "revive", "dump.zig:1", "WRITE: a load's (a join's dump, a Restore): no copy is held" }, .{ "reload", "panes.zig:1", "WRITE: a join's step remakes each terminal written since its last reload, on every side (panes.reloadTerminals, the session's choice taped, the snapshot's hash compared)" }, - .{ "feed", "keys.zig:1 panes.zig:3", "WRITE: the pty's bytes in a unit, every side in the tape's order; a unit that feeds lets a copy held ahead go (`Term.writes`), so none is replayed (keys.zig's: a test's)" }, - .{ "viewTo", "replica.zig:2", "WRITE: a rollback puts each view back by its row (`putViews`), exact since a reflow keeps a view a row (pardes-term-join-6)" }, - .{ "scroll", "Core.zig:2 panes.zig:1", "WRITE: a step moves the view; outside the copy, put back by `putViews`" }, - .{ "follow", "panes.zig:1", "WRITE: a step puts the view on the output; put back by `putViews`" }, - .{ "resize", "panes.zig:1", "WRITE: a step's reflow; a speculation owes it (`touchTerminal`): its input is taken when confirmed, never as speculated" }, + .{ "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" }, .{ "endOutputHere", "ninep/pty.zig:1", "WRITE: a 9P pty/run's step ends a command's output at the cursor: the session's step, replayed as such" }, .{ "replies", "Core.zig:1", "WRITE: a step drains the reply buffer (in the digest); only the session writes it to the pty (pty_write is off the tape)" }, // ---- reads by a step: in the digest ---- - .{ "grid", "Core.zig:8 ansi.zig:4 body_layer.zig:5 draw.zig:3 dump.zig:4 echo.zig:8 edit.zig:1 exec.zig:3 keys.zig:3 layout.zig:2 mouse.zig:1 panes.zig:6 replica.zig:4", "READ: the size, the view, the cursor: in the digest (ansi.zig, body_layer.zig, draw.zig, echo.zig: a draw's)" }, - .{ "modes", "Core.zig:5 draw.zig:1 dump.zig:2 echo.zig:3 exec.zig:3 mouse.zig:4 ninep/pty.zig:3 replica.zig:1", "READ: the program's modes (mouse, focus, bracketed paste, the alternate screen): in the digest (draw.zig, echo.zig: a draw's)" }, + .{ "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)" }, .{ "prompt", "Core.zig:1 builtins.zig:1 echo.zig:1 exec.zig:3 ninep/pty.zig:1 panes.zig:1", "READ: the OSC 133 cycle: in the digest (`marksOf`); Core.zig's and ninep/pty.zig's also taped (`.prompt`, each side's compared)" }, .{ "promptPrefix", "body_layer.zig:1 edit.zig:1 exec.zig:1", "READ: a row's prompt cells (`promptCut`): the active area's in the digest; a history row's text is not (below)" }, .{ "hasImages", "replica.zig:3 tagline.zig:1", "READ: whether it holds a kitty image (the tag's prefix): in the digest" }, @@ -448,7 +426,7 @@ pub const calls = [_]struct { []const u8, []const u8, []const u8 }{ .{ "scrollbackLen", "ninep/ctl.zig:1 ninep/pane.zig:1", "READ, NOT COVERED: the history's text's length (its row count is in the digest)" }, .{ "commandOutput", "ninep/pty.zig:1", "READ, NOT COVERED: a command's output rows (a 9P pty/run): taped as the session's answer" }, .{ "textRows", "edit.zig:2", "READ, NOT COVERED: every row's text, the history's among them (a selection, a Look over a shell)" }, - .{ "viewport", "body_layer.zig:1 replica.zig:1", "READ: the view's rows' text (body_layer.zig: a draw's; replica.zig: a test's)" }, + .{ "viewport", "body_layer.zig:1 replica.zig:1", "READ: the rows' text a view's place (in the digest, with its pane) shows (body_layer.zig: a draw's; replica.zig: a test's)" }, .{ "editRows", "ansi.zig:1", "READ: rows' text for a draw" }, // ---- local ---- .{ "due", "Core.zig:1", "LOCAL: its next wake (a blink, an animation): the loop's, never a step's state" }, @@ -457,7 +435,7 @@ pub const calls = [_]struct { []const u8, []const u8, []const u8 }{ .{ "paint", "ansi.zig:1", "LOCAL: its cells drawn" }, .{ "images", "ansi.zig:1", "LOCAL: its kitty images drawn" }, .{ "start", "tape.zig:1", "LOCAL: the module's start, a test's (its own process's)" }, - .{ "emulatorOf", "Core.zig:2 ninep/pty.zig:3", "the module's state itself: tests only" }, + .{ "emulatorOf", "Core.zig:2 ninep/pty.zig:3 replica.zig:1", "the module's state itself: tests only" }, }; test "every call of the core's into a terminal is listed with its rule (S1): a new read, writer or local use fails until it is" { diff --git a/core/ansi.zig b/core/ansi.zig index 5f522536..14553817 100644 --- a/core/ansi.zig +++ b/core/ansi.zig @@ -86,7 +86,7 @@ pub fn recolor(p: *Pardes, s: *Surface, pane: *Pane, r: pardes.Rect, tx: u16, tw const tz_paint = tracy.zone(@src(), "termPaint"); defer tz_paint.end(); const ink = inkOf(p.theme()); - Term.paint(state, &ink, &p.tty_filter_palette, pane.tty_filter, @intCast(lo), cols, cells, rows); + Term.paint(state, &ink, &p.tty_filter_palette, pane.tty_filter, pane.scrolled_to, @intCast(lo), cols, cells, rows); } const filtered = pane.tty_filter; // Which buffer lines the user has not actually changed, so a row swallowed @@ -221,6 +221,7 @@ pub fn images(p: *Pardes, s: *Surface, pane: *Pane, id: usize, tx: u16, tw: u16, rows_of[@intCast(vi)] = vr; } Term.images(state, p.gpa, .{ + .place = pane.scrolled_to, .pane = @intCast(id), .serial = pane.serial, .tx = tx, @@ -440,7 +441,7 @@ pub fn recolorDiffOutput(p: *Pardes, s: *Surface, pane: *Pane, r: pardes.Rect, t const line = shown.next() orelse continue; const vr: i32 = @intCast(vi); const w = pane.wrapAt(p.settings.tab, vr); - const row_i: i32 = if (raw) @as(i32, @intCast(panes.Term.grid(pane.terminal).offset)) + vr else w.line; + const row_i: i32 = if (raw) @as(i32, @intCast(pane.termTop())) + vr else w.line; if (row_i < 0 or row_i >= @as(i64, @intCast(rows.len))) continue; const row: usize = @intCast(row_i); const from: usize = if (raw) 0 else @intCast(@max(0, w.at)); diff --git a/core/body_layer.zig b/core/body_layer.zig index 817176bb..cb518af4 100644 --- a/core/body_layer.zig +++ b/core/body_layer.zig @@ -38,7 +38,7 @@ fn paintTerminalSelection(p: *Pardes, s: *Surface, pane: *Pane, r: Rect, rows: [ var visible: i32 = 0; while (lines.next()) |line| : (visible += 1) { if (visible >= r.h -| pane.tag_rows) break; - const source_row = if (raw) @as(i32, @intCast(panes.Term.grid(pane.terminal).offset)) + visible else pane.wrapAt(p.settings.tab, visible).line; + const source_row = if (raw) @as(i32, @intCast(pane.termTop())) + visible else pane.wrapAt(p.settings.tab, visible).line; for (rows) |row| { const target = if (row.raw_terminal) (if (raw) row.row else pane.surfRow(row.row)) @@ -497,7 +497,7 @@ pub fn renderBody(p: *Pardes, s: *Surface, arena: std.mem.Allocator, pane: *Pane if (active and pane.focus == .body and (pane.prompt == .none or pane.prompt == .del_side or pane.prompt == .repl_choice)) { if (pane.body.mode != .tty) { const grid = panes.Term.grid(pane.terminal); - const crow = if (pane.body.cur_pinned) pane.body.cur_row else pane.surfRow(@as(i32, grid.cursor_y) + @as(i32, @intCast(grid.offset))); + const crow = if (pane.body.cur_pinned) pane.body.cur_row else pane.surfRow(@as(i32, grid.cursor_y) + @as(i32, @intCast(pane.termTop()))); const ccol = if (pane.body.cur_pinned) pane.body.cur_col else @as(i32, grid.cursor_x); const cwp = pane.wrapRow(p.settings.tab, crow, ccol); const prow = cwp.row + @as(i32, pane.tag_rows); @@ -528,8 +528,9 @@ pub fn renderBody(p: *Pardes, s: *Surface, arena: std.mem.Allocator, pane: *Pane const grid = panes.Term.grid(pane.terminal); if (!grid.cursor_visible) break :visible; const row = grid.total - grid.len + grid.cursor_y; - if (row < grid.offset + pane.pan or row - grid.offset >= grid.len) break :visible; - const y: u16 = @intCast(row - grid.offset - pane.pan); + const top = pane.termTop(); + if (row < top + pane.pan or row - top >= grid.len) break :visible; + const y: u16 = @intCast(row - top - pane.pan); if (y + pane.tag_rows < body_bottom and grid.cursor_x < tw) s.cursor = .{ .x = tx + grid.cursor_x, .y = body_y + y }; } @@ -557,7 +558,7 @@ pub fn bodyText(tab: u16, arena: std.mem.Allocator, pane: *Pane) ![]const u8 { if (pane.file) |*f| return panes.File.bodyText(tab, arena, pane, f); // A terminal's: the rows its view shows (outside raw mode its prompts // cut off), the edit copy's lines over the rows the copy covers. - const vp: []const []const u8 = if (pane.terminal) |state| try panes.Term.viewport(state, arena, pane.body.mode != .tty) else &.{}; + const vp: []const []const u8 = if (pane.terminal) |state| try panes.Term.viewport(state, arena, pane.body.mode != .tty, pane.scrolled_to) else &.{}; const len = fillBody(null, pane, vp); const out = try arena.alloc(u8, len); const filled = fillBody(out, pane, vp); @@ -570,9 +571,9 @@ pub const BodyRow = union(enum) { edit: struct { line: []const u8, idx: usize }, }; -/// A terminal pane's body rows, top down: a row of its emulator's view -/// (`grid`, its viewport row), or a line of the edit copy standing in for -/// the rows it covers (`edit`). +/// A terminal pane's body rows, top down: a row of this view of its +/// emulator (`grid`, counted from the view's top), or a line of the edit +/// copy standing in for the rows it covers (`edit`). pub const BodyWalk = struct { pane: *Pane, goff: i32, @@ -586,7 +587,7 @@ pub const BodyWalk = struct { pub fn init(pane: *Pane) BodyWalk { const off = pane.scroll(); - const goff: i32 = @intCast(panes.Term.grid(pane.terminal).offset); + const goff: i32 = @intCast(pane.termTop()); return .{ .pane = pane, .goff = goff, diff --git a/core/draw.zig b/core/draw.zig index ed317650..3d2a1452 100644 --- a/core/draw.zig +++ b/core/draw.zig @@ -105,7 +105,7 @@ pub fn place(p: *Pardes, s: *Surface) void { // A folded pane is its tag rows and nothing else. if (pane.collapsed) continue; const body_h = r.h -| pane.tag_rows; - const line: i32 = if (pane.file) |f| @intCast(@min(f.scroll, std.math.maxInt(i32))) else if (pane.isTerminal()) @intCast(panes.Term.grid(pane.terminal).offset) else 0; + const line: i32 = if (pane.file) |f| @intCast(@min(f.scroll, std.math.maxInt(i32))) else if (pane.isTerminal()) @intCast(pane.termTop()) else 0; // The text it shows, for a frontend's glide to tell apart: a file's // path, a generated text's revision with it (rows rewritten as its // view moved are another text's); none for a terminal or a picture. @@ -121,7 +121,7 @@ pub fn place(p: *Pardes, s: *Surface) void { .len = pane.rows, } else blk: { const grid = panes.Term.grid(pane.terminal); - break :blk .{ .total = grid.total, .offset = grid.offset, .len = grid.len }; + break :blk .{ .total = grid.total, .offset = pane.termTop(), .len = grid.len }; }; const track_h: usize = body_h; const total = if (sb.total == 0) 1 else sb.total; @@ -371,9 +371,8 @@ pub fn render(p: *Pardes, arena: std.mem.Allocator) !*Surface { sb_off = 0; sb_total = 0; } else { - const grid = panes.Term.grid(at.terminal); - sb_off = grid.offset; - sb_total = grid.total; + sb_off = at.termTop(); + sb_total = panes.Term.grid(at.terminal).total; } const effective_font = p.settings.font.effective_name.get(); const font_name = if (effective_font.len == 0) "default" else effective_font; diff --git a/core/echo.zig b/core/echo.zig index 93b877b8..b1200ca2 100644 --- a/core/echo.zig +++ b/core/echo.zig @@ -237,7 +237,7 @@ pub const Echo = struct { fn predict(e: *Echo, pane: *Pane, kind: Kind, seq: u32) bool { const state = pane.terminal orelse return false; const g = Term.grid(state); - if (Term.modes(state).alternate or g.offset + g.len < g.total or !g.cursor_visible) return false; + if (Term.modes(state).alternate or pane.termTop() + g.len < g.total or !g.cursor_visible) return false; const top = e.tops[e.pane]; const cur: Cursor = e.cursor orelse .{ .x = g.cursor_x, .row = top + g.cursor_y, .seq = 0 }; if (cur.row < top or cur.row - top >= g.len or e.n == max) return false; @@ -457,17 +457,18 @@ pub const Echo = struct { const top = e.tops[id]; // Off a prompt, the trust is inferred: underlined, as mosh does. const flag = !atPrompt(pane); + const shown = pane.termTop(); const at = struct { - fn f(sb_: @TypeOf(sb), pan: u16, h: u16, top_: u64, row: u64) ?u16 { + fn f(sb_: @TypeOf(sb), shown_: usize, pan: u16, h: u16, top_: u64, row: u64) ?u16 { if (row < top_ or row - top_ >= sb_.len) return null; const screen_row = sb_.total - sb_.len + (row - top_); - if (screen_row < sb_.offset + pan) return null; - const y = screen_row - sb_.offset - pan; + if (screen_row < shown_ + pan) return null; + const y = screen_row - shown_ - pan; return if (y < h) @intCast(y) else null; } }.f; for (e.cells[0..e.n]) |cell| { - const y = at(sb, pane.pan, body_h, top, cell.row) orelse continue; + const y = at(sb, shown, pane.pan, body_h, top, cell.row) orelse continue; if (cell.x >= tw) continue; const dst = s.at(tx + cell.x, body_y + y); // Typed text continues the text before it (mosh's heuristic). @@ -484,7 +485,7 @@ pub const Echo = struct { } if (!active or pane.focus != .body) return; const cur = e.cursor orelse return; - const y = at(sb, pane.pan, body_h, top, cur.row) orelse return; + const y = at(sb, shown, pane.pan, body_h, top, cur.row) orelse return; if (cur.x < tw) s.cursor = .{ .x = tx + cur.x, .y = body_y + y }; } }; diff --git a/core/edit.zig b/core/edit.zig index a475fac2..f3a87e57 100644 --- a/core/edit.zig +++ b/core/edit.zig @@ -241,7 +241,7 @@ pub fn capturePointerSelection(p: *Pardes, pane: *Pane, slot: usize) !void { const left: i32 = if (cols.first) @max(cols.lo, prefix) else prefix; const right: i32 = cols.hi orelse std.math.maxInt(i32) / 2; var source = pane.wrapAt(p.settings.tab, visible); - if (raw) source = .{ .line = @as(i32, @intCast(panes.Term.grid(pane.terminal).offset)) + visible, .at = 0 }; + if (raw) source = .{ .line = @as(i32, @intCast(pane.termTop())) + visible, .at = 0 }; const line = if (raw) modal.lineSlice(body, @intCast(visible)) else pointerSourceLine(pane, terminal_lines, source.line); var next = pane.wrapAt(p.settings.tab, visible + 1); if (raw) next = .{ .line = source.line + 1, .at = 0 }; diff --git a/core/exec.zig b/core/exec.zig index 52f54541..ae9111f8 100644 --- a/core/exec.zig +++ b/core/exec.zig @@ -112,7 +112,7 @@ pub fn operandAt(p: *Pardes, pane: *Pane, clicked: Pane.Sel, borrow: bool, for_l const visible = clicked.r0 - @as(i32, pane.tag_rows); const wrapped = pane.wrapAt(p.settings.tab, visible); const raw = pane.isTerminal() and pane.body.mode == .tty and clicked.r0 >= pane.tag_rows; - const row = if (raw) @as(i32, @intCast(panes.Term.grid(pane.terminal).offset)) + visible else wrapped.line; + const row = if (raw) @as(i32, @intCast(pane.termTop())) + visible else wrapped.line; const raw_line = if (raw) modal.lineSlice(body_layer.bodyText(p.settings.tab, p.scratch.allocator(), pane) catch "", @intCast(@max(0, visible))) else ""; const col = if (raw) @as(i32, @intCast(panes.File.rawAtDisplay(p.settings.tab, raw_line, @intCast(@max(0, clicked.c0))))) @@ -703,8 +703,7 @@ pub fn executeFrom(p: *Pardes, id: usize, txt: []const u8, from_body: bool) ?usi // the buffer's LAST surface row: its lines may outnumber the shell // rows it covers, and it is the bottom one output must clear const max_row = o.row + @as(i32, @intCast(modal.lineCount(o.text))) - 1; - const grid = panes.Term.grid(state); - const cursor_abs = pane.surfRow(@as(i32, @intCast(grid.offset)) + @as(i32, grid.cursor_y)); + const cursor_abs = pane.surfRow(@as(i32, @intCast(pane.termTop())) + @as(i32, panes.Term.grid(state).cursor_y)); const pad = std.math.clamp(max_row - cursor_abs, 0, @as(i32, pane.rows)); for (0..@intCast(pad)) |_| p.emitWrite(id, "\r"); }; diff --git a/core/keys.zig b/core/keys.zig index 8bfe8315..91cb2724 100644 --- a/core/keys.zig +++ b/core/keys.zig @@ -58,8 +58,7 @@ pub fn enterTty(p: *Pardes, id: usize) void { const pane = p.panes[id] orelse return; const selected = pane.rawPointerText(pane.sel[@backingInt(config.select_button)]) != null; if (!selected and pane.body.cur_pinned) if (pane.terminal) |state| { - const row = pane.gridRow(pane.body.cur_row) - @as(i32, @intCast(panes.Term.grid(state).offset)); - if (panes.Term.promptMoves(state, row, pane.body.cur_col)) |moves| { + if (panes.Term.promptMoves(state, pane.gridRow(pane.body.cur_row), pane.body.cur_col)) |moves| { for (0..moves.left) |_| p.emitWrite(id, "\x1b[D"); for (0..moves.right) |_| p.emitWrite(id, "\x1b[C"); } @@ -546,7 +545,7 @@ test "Esc back into a tty leaves its view at the prompt" { p.update(.{ .output = .{ .pane = .at(shell), .bytes = std.fmt.bufPrint(&buf, "line {d}\r\n", .{i}) catch unreachable } }); } p.sync(); - const live = pardes.Term.grid(sp.terminal).offset; + const live = sp.termTop(); try std.testing.expect(live > 0); p.update(.{ .key = .{ .cp = Key.escape } }); // shell-prompt heuristic: out to the doc @@ -555,7 +554,7 @@ test "Esc back into a tty leaves its view at the prompt" { p.sync(); try std.testing.expectEqual(shell, p.view().active); - try std.testing.expectEqual(live, pardes.Term.grid(sp.terminal).offset); + try std.testing.expectEqual(live, sp.termTop()); } test "Del from a key asks which neighbour takes the rows; nothing else asks" { @@ -805,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.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/mouse.zig b/core/mouse.zig index e41f8910..91d2932c 100644 --- a/core/mouse.zig +++ b/core/mouse.zig @@ -1093,7 +1093,7 @@ fn mirrorTtySelection(p: *Pardes, pane: *Pane) void { const forward = gesture.r1 > gesture.r0 or (gesture.r1 == gesture.r0 and gesture.c1 >= gesture.c0); const endpoint = rows[if (forward) rows.len - 1 else 0]; const body = body_layer.bodyText(p.settings.tab, p.scratch.allocator(), pane) catch |err| return p.reportError(.at(p.view().active), "select", err); - const line = modal.lineSlice(body, @intCast(@max(0, endpoint.row - @as(i32, @intCast(panes.Term.grid(pane.terminal).offset))))); + const line = modal.lineSlice(body, @intCast(@max(0, endpoint.row - @as(i32, @intCast(pane.termTop()))))); const byte = if (forward) modal.prevGrapheme(line, @min(endpoint.hi, line.len)) else endpoint.lo; pane.body.cur_row = pane.surfRow(endpoint.row); var shown = std.mem.trimEnd(u8, line[@min(endpoint.prompt_bytes, line.len)..], " \t"); diff --git a/core/ninep/pty.zig b/core/ninep/pty.zig index ec752311..923dab88 100644 --- a/core/ninep/pty.zig +++ b/core/ninep/pty.zig @@ -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(50, 20); + pane.resizeGrid(p.live, 50, 20); sh.put(p, d ++ prompt); try testing.expectEqualStrings("exit 0\none\ntwo\n", sh.answered(p, node, h, into)); - pane.resizeGrid(pane.cols, pane.rows); + pane.resizeGrid(p.live, 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 d9759d18..032cb4db 100644 --- a/core/panes.zig +++ b/core/panes.zig @@ -375,6 +375,13 @@ pub const Pane = struct { /// it): the rows its top is passed over by, so its cursor stays in /// sight (Pane.panFor); 0 everywhere else. pan: u16 = 0, + /// Where this view stands in its terminal's history: the row its top + /// shows, counted from the history's top; null, on the output, following + /// it. Each view's own (views.zig), so the copy a rollback puts back + /// holds it, and the digest and the dump: the emulator keeps no view. + /// Carried with every other view's through each write of the emulator + /// that moves rows (`Scrolled`); one the active area holds is null. + scrolled_to: ?usize = null, /// The view whose step a `.name` prompt is (tagline.draftName): only /// that view's focus leaving the pane drops it. prompt_view: u8 = 0, @@ -597,7 +604,15 @@ pub const Pane = struct { /// current scroll offset: file top line, or the scrollback offset pub fn scroll(pane: *Pane) i32 { if (pane.file) |f| return @intCast(f.scroll); - return pane.surfRow(@as(i32, @intCast(Term.grid(pane.terminal).offset)) + pane.pan); + return pane.surfRow(@as(i32, @intCast(pane.termTop())) + pane.pan); + } + + /// The row of its terminal's history (from the top) this view's top + /// shows: where it is scrolled to, else the output's first. + pub fn termTop(pane: *const Pane) usize { + const g = Term.grid(pane.terminal); + const output = g.total - g.len; + return @min(pane.scrolled_to orelse output, output); } /// The line and byte a body row shows from; a ghost row (jj.zig) is no @@ -637,10 +652,14 @@ pub const Pane = struct { f.syntax_dirty = true; } } else if (pane.addon == null) { - // the vt scrolls in SHELL rows; convert through the edit buffer + // the vt scrolls in SHELL rows; convert through the edit buffer. + // The alternate screen has no history (ghostty's scrolls none): + // the place on the primary's stays. const state = pane.terminal orelse return; - const off: i32 = @intCast(Term.grid(state).offset); - Term.scroll(state, pane.gridRow(pane.surfRow(off) + delta) - off); + if (Term.modes(state).alternate) return; + const g = Term.grid(state); + const to: i64 = pane.gridRow(pane.surfRow(@intCast(pane.termTop())) + delta); + pane.scrolled_to = if (to >= g.total - g.len) null else @intCast(@max(0, to)); } } @@ -722,15 +741,16 @@ pub const Pane = struct { pane.body.cur_col = 0; } else { const grid = Term.grid(pane.terminal); - pane.body.cur_row = pane.surfRow(@as(i32, grid.cursor_y) + @as(i32, @intCast(grid.offset))); + pane.body.cur_row = pane.surfRow(@as(i32, grid.cursor_y) + @as(i32, @intCast(pane.termTop()))); pane.body.cur_col = grid.cursor_x; } pane.body.cur_pinned = true; } - /// Record and parse one live pty read, invalidate its motion surface, - /// and follow it only when the body (possibly parked under a tag edit) - /// is raw. + /// Record and parse one live pty read and invalidate its motion surface. + /// Sticky bottom, as every other terminal does it: a view on the output + /// follows it, one scrolled back into the history stays on its row + /// (`Scrolled`, every view's). pub fn feedOutput(pane: *Pane, p: *Pardes, bytes: []const u8) void { // There are no pty reads at all without an emulator to parse them into. const state = pane.terminal orelse return; @@ -738,25 +758,51 @@ pub const Pane = struct { const has_positions = pane.ovl != null or pane.body.cur_pinned or pane.body.vsel.active or pane.body.nsel > 0 or pane.body.last_edit != null or pane.look_at != null or pane.body.ed_undo_len > 0 or pane.body.ed_redo_len > 0 or pane.pointerRowCount() > 0; - // Sticky bottom, as every other terminal does it: output drags the - // viewport down only when the viewport was already on the last row, - // so a reader scrolled back into the scrollback stays where they - // scrolled. - const grid = Term.grid(state); - const at_bottom = grid.offset + grid.len >= grid.total; Term.cellPixels(state, p.view().cell_pixels.w, p.view().cell_pixels.h); + var scrolled: Scrolled = .of(pane, p.live); + defer scrolled.put(pane, p.live); if (!has_positions) { - _ = Term.feed(state, bytes, &.{}, &.{}, &.{}); - } else if (pane.followRows(state, bytes)) if (paneIdOf(p, pane)) |id| p.setMessage(.at(id), positions_lost); + _ = 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); p.shell_rows.markStale(pane); - if (pane.body.mode == .tty and at_bottom) pane.followOutput(); } + /// Every open view's place in its terminal's history (`scrolled_to`: + /// the live view's in the pane, each other's in its share, `pv`), + /// carried through a write of the emulator that moves rows + /// (`Term.feed`, `Term.resize`) and put back after it. + const Scrolled = struct { + at: [views.max]?usize = @splat(null), + /// One stands off the output: else the write carries none, at no + /// cost (a terminal's output, read after read). + any: bool = false, + + fn of(pane: *const Pane, live: u8) Scrolled { + var pl: Scrolled = .{}; + for (&pl.at, 0..) |*at, k| { + if (k == live) at.* = pane.scrolled_to else if (pane.pv_known >> @intCast(k) & 1 != 0) at.* = pane.pv[k].scrolled_to; + pl.any = pl.any or at.* != null; + } + return pl; + } + + fn places(pl: *Scrolled) []?usize { + return pl.at[0..if (pl.any) pl.at.len else 0]; + } + + fn put(pl: *const Scrolled, pane: *Pane, live: u8) void { + if (!pl.any) return; + for (pl.at, 0..) |at, k| { + if (k == live) pane.scrolled_to = at else if (pane.pv_known >> @intCast(k) & 1 != 0) pane.pv[k].scrolled_to = at; + } + } + }; + /// Its terminal fed `bytes`, with every position kept over its rows /// (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) bool { + fn followRows(pane: *Pane, 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] = .{ @@ -852,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); + const track = if (n <= track_buf.len) track_buf[0..n] else pane.gpa.alloc(i32, n) catch return feedLost(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); + const rows_after = if (n <= rows_buf.len) rows_buf[0..n] else pane.gpa.alloc(i32, n) catch return feedLost(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); + const erased_after = if (n <= erased_buf.len) erased_buf[0..n] else pane.gpa.alloc(bool, n) catch return feedLost(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| { @@ -867,7 +913,7 @@ pub const Pane = struct { track[k] = at.grid; k += 1; }; - const fed = Term.feed(state, bytes, track, rows_after, erased_after); + const fed = Term.feed(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; @@ -948,8 +994,8 @@ pub const Pane = struct { return t; } - fn feedLost(state: *Term.State, bytes: []const u8) bool { - _ = Term.feed(state, bytes, &.{}, &.{}, &.{}); + fn feedLost(state: *Term.State, bytes: []const u8, places: []?usize) bool { + _ = Term.feed(state, bytes, &.{}, &.{}, &.{}, places); return true; } @@ -961,14 +1007,17 @@ pub const Pane = struct { return count; } - /// Its terminal's view snapped back onto live output. + /// This view of its terminal snapped back onto live output. On the + /// alternate screen (no history) the place on the primary's stays, as + /// ghostty's own did. pub fn followOutput(pane: *Pane) void { const state = pane.terminal orelse return; - Term.follow(state); + if (!Term.modes(state).alternate) pane.scrolled_to = null; } - /// Its terminal's grid reflowed to `cols` by `rows`. - pub fn resizeGrid(pane: *Pane, cols: u16, rows: u16) void { + /// 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 @@ -979,7 +1028,9 @@ pub const Pane = struct { pane.sel[button].state = .none; }; if (tape.speculating()) return tape.touchTerminal(); - Term.resize(state, cols, rows); + var scrolled: Scrolled = .of(pane, live); + defer scrolled.put(pane, live); + Term.resize(state, cols, rows, scrolled.places()); } /// The rows its terminal's top is passed over by in a view whose rect @@ -993,10 +1044,11 @@ pub const Pane = struct { if (shown == 0 or shown >= pane.rows) return 0; const state = pane.terminal orelse return 0; const grid = Term.grid(state); - // The cursor's row in the viewport; past its end (scrolled back), - // its last row. + const top = pane.termTop(); + // The cursor's row in the view; past its end (scrolled back), its + // last row. const row = grid.total - grid.len + grid.cursor_y; - const at: usize = if (row < grid.offset) 0 else @min(row - grid.offset, pane.rows - 1); + const at: usize = if (row < top) 0 else @min(row - top, pane.rows - 1); return @intCast(@min(pane.rows - shown, (at + 1) -| shown)); } diff --git a/core/replica.zig b/core/replica.zig index 3aac5e82..6072eea4 100644 --- a/core/replica.zig +++ b/core/replica.zig @@ -479,10 +479,6 @@ pub const Replica = struct { rtt_ns: u64 = 0, gmtoff: i32 = 0, - /// Each terminal's view (`Term.grid`'s view) as the copy was taken: the - /// copy holds no emulator, and a speculation may move a view, so a - /// rollback puts these back. - views: [pardes.MAX_PANES]?usize = @splat(null), /// Its panes' serials as the copy was taken, and whether one was being /// torn down then (`panesMoved`). serials: [pardes.MAX_PANES]u32 = @splat(0), @@ -907,9 +903,6 @@ pub const Replica = struct { r.core().shell_rows = .{}; } r.applied = 0; - // Its views as the copy was taken, or as the last delta set them - // (which the units since may move again). - if (held) r.putViews(); for (r.since.items) |u| if (tape.replayUnit(&r.t, u)) |why| { trace(r.gpa, "replica {d}: a unit kept since the copy came to another state replayed again: {s}\n", .{ r.id, why }, &.{u}); return r.fail(why); @@ -947,7 +940,7 @@ pub const Replica = struct { // 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.keepViews(); + r.keepSerials(); rollback.Epoch.select(&r.epoch); if (r.stats.samples) r.stats.copy_ns.append(r.gpa, nowNs() - t0) catch {}; r.stats.copy_bytes += r.copy.savedBytes(); @@ -1033,23 +1026,22 @@ pub const Replica = struct { rollback.Epoch.select(&r.epoch); defer rollback.Epoch.select(null); r.copy.take(&r.epoch, c) catch return; - r.keepViews(); + r.keepSerials(); if (r.stats.samples) r.stats.copy_ns.append(r.gpa, nowNs() - t0) catch {}; r.stats.copy_bytes += r.copy.savedBytes(); r.stats.copies += 1; } - fn keepViews(r: *Replica) void { + fn keepSerials(r: *Replica) void { const c = r.core(); for (c.panes, &r.serials) |slot, *n| n.* = if (slot) |pane| pane.serial else 0; r.retiring = for (c.retired_panes.current, c.retired_panes.previous) |x, y| { if (x != null or y != null) break true; } else false; - for (r.core().panes, &r.views) |slot, *v| v.* = if (slot) |pane| if (pane.terminal) |state| pardes.Term.grid(state).view else null else null; } /// Whether a pane opened, closed or is torn down since the copy was - /// taken (`keepViews`). + /// taken (`keepSerials`). fn panesMoved(r: *const Replica) bool { const c = r.core(); if (r.retiring) return true; @@ -1058,10 +1050,6 @@ pub const Replica = struct { return false; } - fn putViews(r: *Replica) void { - for (r.core().panes, r.views) |slot, at| if (slot) |pane| if (pane.terminal) |state| pardes.Term.viewTo(state, at); - } - /// Whether its core loaded from the dump is the session as it was /// dumped, by the welcome's `digest`. pub fn loaded(r: *Replica, want: u64) bool { @@ -1138,8 +1126,7 @@ fn terminalDigests(p: *const Pardes, out: *[pardes.MAX_PANES]u64) void { const pane = slot orelse continue; const state = pane.terminal orelse continue; var h = walk.Hasher.init(0); - // Its view aside: a speculation may move it (`views`). - state.digestScreen(&h, false); + state.digest(&h); d.* = h.final(); } } @@ -4006,7 +3993,7 @@ test "bytes: a session's output that moves nothing the digest covers (a colour s try sameTerminals(b.a, b.r); } -test "bytes: a terminal's view a rollback puts back is the session's through a reflow: a view on a wrapped line's second row, joined into the row above by the session's widening, is the same row after its narrowing on every side" { +test "bytes: a terminal's view is the same row on every side through a reflow and a rollback: a view on a wrapped line's second row, joined into the row above by the session's widening, is the same row after its narrowing on every side" { if (pardes.Term.ops == null) return error.SkipZigTest; // a shell const b = try BytesPair.init(); defer b.deinit(); @@ -4024,13 +4011,12 @@ test "bytes: a terminal's view a rollback puts back is the session's through a r } b.r.confirm((try b.a.pending()).?); b.r.settle(); - for ([_]*Pardes{ b.a.core, b.r.core() }) |core| pardes.Term.viewTo(core.panes[id].?.terminal.?, 1); - // The session's frontend widens: the line one row, the view at row 0, - // its cell mid-row. + for ([_]*Pardes{ b.a.core, b.r.core() }) |core| core.panes[id].?.scrolled_to = 1; + // The session's frontend widens: the line one row, the view at row 0. b.r.confirm(try b.a.own(.{ .resize = .{ .cols = 200, .rows = 24 } })); b.r.settle(); try agrees(b.a, b.r); - try std.testing.expectEqual(@as(?usize, 0), pardes.Term.grid(b.a.core.panes[id].?.terminal).view); + try std.testing.expectEqual(@as(?usize, 0), b.a.core.panes[id].?.scrolled_to); // A key of the client's on top, the session's first: the copy put back. try b.rollback(); try agrees(b.a, b.r); @@ -4040,6 +4026,178 @@ test "bytes: a terminal's view a rollback puts back is the session's through a r try agrees(b.a, b.r); } +/// Where view `k` stands in terminal pane `id`'s history (Pane.scrolled_to): +/// the pane's own field while `k` is live, its share's else. +fn placeIn(p: *const Pardes, k: u8, id: usize) ?usize { + const pane = p.panes[id].?; + return if (p.live == k) pane.scrolled_to else pane.pv[k].scrolled_to; +} + +test "bytes: a client's wheel over a terminal is its own view's: applied at once, the session's view on the output and following it, the client's on its row through output and a rollback" { + if (pardes.Term.ops == null) return error.SkipZigTest; // a shell + const gpa = std.testing.allocator; + const b = try BytesPair.init(); + defer b.deinit(); + const id = b.shell.index(); + var line: [32]u8 = undefined; + for (0..100) |i| b.a.output(.{ .output = .{ .pane = b.shell, .bytes = try std.fmt.bufPrint(&line, "line-{d}\r\n", .{i}) } }); + b.r.confirm((try b.a.pending()).?); + b.r.settle(); + // The client in a view of its own, laid out by a step of its own. + const opened = try b.a.openView(1); + b.r.view = opened.view; + b.r.confirm(opened.unit); + b.r.settle(); + const focus = try gpa.dupe(u8, try b.r.input(.{ .focus = true })); + defer gpa.free(focus); + b.r.confirm(try b.a.take(focus)); + b.r.settle(); + const rect = b.a.core.views[b.r.view].?.rects[id]; + const wheel = try gpa.dupe(u8, try b.r.input(.{ .mouse = .{ .button = .wheel_up, .kind = .press, .col = rect.x + 2, .row = rect.y + rect.h -| 1 } })); + defer gpa.free(wheel); + // Applied at once, nothing of it outside the copy: the session's own + // view (the replica's core holds it too) is where it was. + try std.testing.expectEqual(@as(usize, 1), b.r.applied); + const back = placeIn(b.r.core(), b.r.view, id).?; + try std.testing.expectEqual(@as(?usize, null), placeIn(b.r.core(), 0, id)); + b.r.confirm(try b.a.take(wheel)); + b.r.settle(); + try agrees(b.a, b.r); + // The program prints: the view on the output follows, the client's stays. + try b.output("more-1\r\nmore-2\r\n"); + try agrees(b.a, b.r); + for ([_]*Pardes{ b.a.core, b.r.core() }) |core| { + try std.testing.expectEqual(@as(?usize, null), placeIn(core, 0, id)); + try std.testing.expectEqual(@as(?usize, back), placeIn(core, b.r.view, id)); + } + // A wheel of the client's on top, the session's own key first: the + // copy put back, the wheel applied again over it. + const again = try gpa.dupe(u8, try b.r.input(.{ .mouse = .{ .button = .wheel_up, .kind = .press, .col = rect.x + 2, .row = rect.y + rect.h -| 1 } })); + defer gpa.free(again); + b.r.confirm(try b.a.local(.{ .key = .{ .cp = 'j', .text = "j" } })); + b.r.settle(); + b.r.confirm(try b.a.take(again)); + b.r.settle(); + try agrees(b.a, b.r); + try std.testing.expect(placeIn(b.r.core(), b.r.view, id).? < back); +} + +/// Seeds of the explorer below a run of the suite takes; 3,000 were run +/// once (reports/pardes-term-join-10.md). +const view_orders = 30; + +test "bytes: terminal views under random orders of the session's output, each view's wheels, keys and resizes, a copy taken ahead and rollbacks, the history at its cap: every side agrees (an explorer)" { + if (pardes.Term.ops == null) return error.SkipZigTest; // a shell + const gpa = std.testing.allocator; + const Ev = pardes.Event; + const K = pardes.Key; + var seed: u64 = 0; + while (seed < view_orders) : (seed += 1) { + const b = try BytesPair.init(); + defer b.deinit(); + var prng: std.Random.DefaultPrng = .init(seed); + const rnd = prng.random(); + var sent: std.ArrayListUnmanaged([]u8) = .empty; + var units: std.ArrayListUnmanaged([]u8) = .empty; + var trail: std.ArrayListUnmanaged(u8) = .empty; + defer { + for (sent.items) |m| gpa.free(m); + sent.deinit(gpa); + for (units.items) |m| gpa.free(m); + units.deinit(gpa); + trail.deinit(gpa); + } + var line: [64]u8 = undefined; + // The history at its cap: the emulator's byte limit at its least, + // on both sides alike, then flooded past it. + for ([_]*Pardes{ b.a.core, b.r.core() }) |core| pardes.Term.emulatorOf(core.panes[b.shell.index()].?.terminal.?).vt.screens.active.pages.setMaxBytes(1); + var n_out: usize = 0; + while (n_out < 6000) : (n_out += 1) b.a.output(.{ .output = .{ .pane = b.shell, .bytes = try std.fmt.bufPrint(&line, "line {d}\r\n", .{n_out}) } }); + b.r.confirm((try b.a.pending()).?); + b.r.settle(); + // The session's view at or near the history's top, on both sides. + const top = rnd.uintLessThan(usize, 4); + for ([_]*Pardes{ b.a.core, b.r.core() }) |core| core.panes[b.shell.index()].?.scrolled_to = top; + b.a.core.view().active = b.shell.index(); + b.r.confirm(try b.a.own(.{ .focus = true })); + const opened = try b.a.openView(1); + b.r.view = opened.view; + b.r.confirm(opened.unit); + b.r.settle(); + for (0..150) |_| { + const who = rnd.uintLessThan(u8, 10); + if (who < 2) { + // the session's own pty, or its taking a client's input + if (rnd.boolean()) { + try trail.print(gpa, "So ", .{}); + for (0..rnd.intRangeAtMost(usize, 1, 600)) |_| { + b.a.output(.{ .output = .{ .pane = b.shell, .bytes = try std.fmt.bufPrint(&line, "line {d}\r\n", .{n_out}) } }); + n_out += 1; + } + try units.append(gpa, try gpa.dupe(u8, (try b.a.pending()).?)); + } else if (sent.items.len > 0) { + try trail.print(gpa, "St ", .{}); + const m = sent.orderedRemove(0); + defer gpa.free(m); + try units.append(gpa, try gpa.dupe(u8, try b.a.take(m))); + } + continue; + } + if (who < 5) { + if (rnd.uintLessThan(u8, 4) == 0) { + try trail.print(gpa, "Rr ", .{}); + b.r.ready(); + } else if (units.items.len > 0) { + try trail.print(gpa, "R ", .{}); + const u = units.orderedRemove(0); + defer gpa.free(u); + b.r.confirm(u); + b.r.settle(); + } + continue; + } + // an input, the session's frontend's (view 0) or the client's + const client = who >= 7; + const k: u8 = if (client) b.r.view else 0; + const rect = b.a.core.views[k].?.rects[b.shell.index()]; + const ev: Ev, const name: []const u8 = switch (rnd.uintLessThan(u8, 20)) { + 14 => .{ .{ .key = .{ .cp = 'g', .text = "g" } }, "g" }, + 15 => .{ .{ .key = .{ .cp = 'G', .text = "G" } }, "G" }, + 16 => .{ .{ .key = .{ .cp = 'n', .text = "n" } }, "n" }, + 17 => .{ .{ .key = .{ .cp = 'N', .text = "N" } }, "N" }, + 18 => .{ .{ .key = .{ .cp = '/', .text = "/" } }, "/" }, + 19 => .{ .{ .paste = "line 1" }, "p" }, + 0, 1, 2, 3 => .{ .{ .mouse = .{ .button = .wheel_up, .kind = .press, .col = rect.x + 2, .row = rect.y + rect.h -| 1 } }, "wu" }, + 4, 5 => .{ .{ .mouse = .{ .button = .wheel_down, .kind = .press, .col = rect.x + 2, .row = rect.y + rect.h -| 1 } }, "wd" }, + 6 => .{ .{ .key = .{ .cp = 'b', .ctrl = true } }, "^b" }, + 7 => .{ .{ .key = .{ .cp = 'j', .text = "j" } }, "j" }, + 8 => .{ .{ .key = .{ .cp = 'k', .text = "k" } }, "k" }, + 9 => .{ .{ .key = .{ .cp = 'u', .ctrl = true } }, "^u" }, + 10 => .{ .{ .key = .{ .cp = 'd', .ctrl = true } }, "^d" }, + 11 => .{ .{ .key = .{ .cp = K.escape } }, "esc" }, + 13 => .{ .{ .key = .{ .cp = K.enter } }, "ent" }, + 12 => .{ .{ .resize = .{ .cols = rnd.intRangeAtMost(u16, 60, 90), .rows = rnd.intRangeAtMost(u16, 6, 14) } }, "rs" }, + else => .{ .{ .mouse = .{ .button = .left, .kind = .press, .col = rect.x + 2, .row = rect.y + rect.h -| 1 } }, "cl" }, + }; + try trail.print(gpa, "{s}{s} ", .{ if (client) "C" else "S", name }); + if (client) { + try sent.append(gpa, try gpa.dupe(u8, try b.r.input(ev))); + } else { + try units.append(gpa, try gpa.dupe(u8, try b.a.own(ev))); + if (ev == .mouse) try units.append(gpa, try gpa.dupe(u8, try b.a.own(.{ .mouse = .{ .button = .left, .kind = .release, .col = ev.mouse.col, .row = ev.mouse.row } }))); + } + if (b.r.diverged) |why| { + std.debug.print("seed {d}: diverged {s}: {s}\n", .{ seed, why, trail.items }); + return error.TestExpectedEqual; + } + if (sent.items.len == 0 and units.items.len == 0 and b.r.quiet() and digestOf(b.a) != b.r.digest()) { + std.debug.print("seed {d}: digests differ: {s}\n", .{ seed, trail.items }); + return error.TestExpectedEqual; + } + } + } +} + test "bytes: a mouse motion a speculation told a terminal's program is told again when its input is replayed: the cell last told is the pane's, put back with it" { if (pardes.Term.ops == null) return error.SkipZigTest; // a shell const gpa = std.testing.allocator; @@ -4331,7 +4489,7 @@ fn firstOnPair(by_dump: bool) !void { try std.testing.expectEqual(reloads, pardes.Term.reloads.n); var arena: std.heap.ArenaAllocator = .init(gpa); defer arena.deinit(); - const rows = try pardes.Term.viewport(r.core().panes[shell].?.terminal.?, arena.allocator(), false); + const rows = try pardes.Term.viewport(r.core().panes[shell].?.terminal.?, arena.allocator(), false, r.core().panes[shell].?.scrolled_to); try std.testing.expect(std.mem.indexOf(u8, rows[0], "first$") != null); if (!by_dump) return; // One that comes after the shell's bytes: every side reloads. diff --git a/core/term/TerminalImages.zig b/core/term/TerminalImages.zig index d0d364a1..e3996b92 100644 --- a/core/term/TerminalImages.zig +++ b/core/term/TerminalImages.zig @@ -157,16 +157,18 @@ fn decodePng(gpa: std.mem.Allocator, bytes: []const u8) ghostty_vt.sys.DecodeErr return .{ .width = scaled.width, .height = scaled.height, .data = gpa.dupe(u8, scaled.data) catch return error.InvalidData }; } -/// Draw the active screen's images. `rows_of[v]` is the body row the -/// viewport's row `v` is shown on, if it is shown; `cols` how many of its -/// columns the body shows, from `tx`. The caches are `own`'s (the -/// emulator's), `out` is `gpa`'s. +/// Draw the active screen's images over the rows a view shows, `top` to +/// `bottom`. `rows_of[v]` is the body row the view's row `v` is shown on, +/// if it is shown; `cols` how many of its columns the body shows, from +/// `tx`. The caches are `own`'s (the emulator's), `out` is `gpa`'s. pub fn draw( ti: *TerminalImages, own: std.mem.Allocator, gpa: std.mem.Allocator, vt: *ghostty_vt.Terminal, where: plain.term.ImagesAt, + top: ghostty_vt.Pin, + bottom: ghostty_vt.Pin, rows_of: []const ?u16, out: *std.ArrayList(plain.Placement), frame: []plain.Cell, @@ -184,8 +186,7 @@ pub fn draw( const now_ms = where.now_ms; ti.animation_due_ms = if (storage.animationTick(vt.io(), now_ms)) |delay| now_ms +| delay else null; const pages = &screen.pages; - const top = pages.getTopLeft(.viewport); - const bottom = pages.getBottomRight(.viewport) orelse return; + const origin = pages.pointFromPin(.screen, top) orelse return; const cw: u32 = @max(1, where.cell_w); const ch: u32 = @max(1, where.cell_h); const ctx: Ctx = .{ .ti = ti, .own = own, .gpa = gpa, .out = out, .pane = where.pane, .serial = where.serial, .tx = where.tx, .body_y = where.body_y, .cols = where.cols, .rows_of = rows_of, .cw = cw, .ch = ch, .glyph = where.petscii }; @@ -202,11 +203,12 @@ pub fn draw( // them on a row at a time. The placeholders themselves are not text. var runs: PlaceholderRuns = .init(top, bottom); while (runs.next()) |run| { - const at = pages.pointFromPin(.viewport, run.pin) orelse continue; - const v = at.viewport.y; + const at = pages.pointFromPin(.screen, run.pin) orelse continue; + if (at.screen.y < origin.screen.y) continue; + const v = at.screen.y - origin.screen.y; if (v >= rows_of.len) continue; const row = rows_of[v] orelse continue; - for (@as(usize, at.viewport.x)..@as(usize, at.viewport.x) + run.width) |x| { + for (@as(usize, at.screen.x)..@as(usize, at.screen.x) + run.width) |x| { if (x >= where.cols) break; const cell = &frame[@as(usize, where.body_y + row) * frame_cols + where.tx + x]; cell.text[0] = ' '; @@ -217,7 +219,7 @@ pub fn draw( const rp = run.renderPlacement(&target.placement, &img, cw, ch) catch continue; if (rp.dest_width == 0 or rp.dest_height == 0 or rp.source_width == 0 or rp.source_height == 0) continue; ctx.place(img, target.placement.z, .{ .x = rp.source_x, .y = rp.source_y, .w = rp.source_width, .h = rp.source_height }, .{ - .x = @as(i64, at.viewport.x) * cw + rp.offset_x, + .x = @as(i64, at.screen.x) * cw + rp.offset_x, .y = @as(i64, v) * ch + rp.offset_y, .w = rp.dest_width, .h = rp.dest_height, @@ -225,8 +227,7 @@ pub fn draw( } // Placements on a cell: they move with the text they were put on, and - // go where it goes, above the viewport or off the screen. - const origin = pages.pointFromPin(.screen, top) orelse return; + // go where it goes, above the view or off the screen. var it = storage.placements.iterator(); while (it.next()) |entry| { const placed = entry.value_ptr.*; diff --git a/core/term/term.zig b/core/term/term.zig index 058154a7..025f7239 100644 --- a/core/term/term.zig +++ b/core/term/term.zig @@ -32,9 +32,6 @@ pub const ops: iface.Ops = .{ .media = terminal_.media, .feed = cast(iface.Ops, "feed", terminal_.feed), .grid = cast(iface.Ops, "grid", terminal_.grid), - .viewTo = cast(iface.Ops, "viewTo", terminal_.viewTo), - .scroll = cast(iface.Ops, "scroll", terminal_.scroll), - .follow = cast(iface.Ops, "follow", terminal_.follow), .resize = cast(iface.Ops, "resize", terminal_.resize), .cellPixels = cast(iface.Ops, "cellPixels", terminal_.cellPixels), .replies = cast(iface.Ops, "replies", terminal_.replies), diff --git a/core/term/terminal.zig b/core/term/terminal.zig index 44038a18..b1beff15 100644 --- a/core/term/terminal.zig +++ b/core/term/terminal.zig @@ -201,19 +201,18 @@ pub const State = struct { /// The emulator as its program has made it, for the replay digest (the /// core's Term.State.digest, core/walk.zig): the active screen's text, how -/// much history is above it and, with `view`, where the view is, the -/// cursor, the answers not yet written. Not its pages (their addresses are -/// its own), nor the history's text (the screen's was all of it once, and -/// a session's digest is taken every step), nor the kitty images, whose -/// media is read off the host. -pub fn digest(s: *const State, h: *std.hash.Wyhash, view: bool) void { +/// much history is above it, the cursor, the answers not yet written. Not +/// its pages (their addresses are its own), nor the history's text (the +/// screen's was all of it once, and a session's digest is taken every +/// step), nor the kitty images, whose media is read off the host. Where a +/// view stands is the view's (the core digests it with the pane). +pub fn digest(s: *const State, h: *std.hash.Wyhash) void { const screen = s.vt.screens.active; const sb = screen.pages.scrollbar(); const cur = screen.cursor; - const offset = if (view) sb.offset else 0; // Everything a step reads of it (abi/term.zig `replicated`): its - // size, the view and the cursor, its modes (the alternate screen, - // the mouse's, focus reports, bracketed paste: `modes`), whether it + // size and the cursor, its modes (the alternate screen, the + // mouse's, focus reports, bracketed paste: `modes`), whether it // holds a kitty image (the tag says so: tagline.zig), the reply // buffer, the OSC 133 cycle (`prompt`), the active area's text. Not // the history's text, only its length (a step's read of it: not @@ -222,7 +221,7 @@ pub fn digest(s: *const State, h: *std.hash.Wyhash, view: bool) void { const mode_bits: @Int(.unsigned, @bitSizeOf(Modes)) = @bitCast(s.vt.modes.values); const modes_word: @Int(.unsigned, (@bitSizeOf(Modes) + 7) / 8 * 8) = mode_bits; const mouse_flags: [2]u8 = .{ @intCast(@intFromEnum(s.vt.flags.mouse_event)), @intCast(@intFromEnum(s.vt.flags.mouse_format)) }; - const facts = .{ s.vt.cols, s.vt.rows, sb.total, offset, sb.len, cur.x, cur.y, modes_word, s.vt.screens.active_key, mouse_flags, s.reply_dropped, hasImages(s) }; + const facts = .{ s.vt.cols, s.vt.rows, sb.total, sb.len, cur.x, cur.y, modes_word, s.vt.screens.active_key, mouse_flags, s.reply_dropped, hasImages(s) }; inline for (facts) |fact| h.update(std.mem.asBytes(&fact)); h.update(s.reply[0..s.reply_len]); var marks: [marks_len]u8 = undefined; @@ -254,7 +253,6 @@ pub fn parts(s: *const State) Term.Parts { return .{ .reply = s.reply[0..s.reply_len], .reply_dropped = s.reply_dropped, - .view = s.vt.screens.active.pages.scrollbar().offset, .phase = h.phase, .started = h.started, .prompts = h.prompts, @@ -397,9 +395,6 @@ fn install(out: *State, continuation: ghostty_vt.snapshot.Continuation, saved: * if (screen.pages.pin(.{ .screen = at })) |pin| @field(h, pair[0]) = screen.pages.trackPin(pin) catch null; }; } - const screen = out.vt.screens.active; - const bottom = screen.pages.scrollbar().offset; - screen.scroll(.{ .delta_row = @as(isize, @intCast(saved.view)) - @as(isize, @intCast(bottom)) }); return whole; } @@ -450,24 +445,93 @@ pub fn terminalIo() std.Io { return std.Io.Threaded.global_single_threaded.io(); } -/// Where the view and the cursor are (`Term.Grid`); all zero without an -/// emulator. +/// How much history there is and where the cursor is (`Term.Grid`); all +/// zero without an emulator. pub fn grid(state: ?*const State) Term.Grid { const s = state orelse return .{}; const screen = s.vt.screens.active; const sb = screen.pages.scrollbar(); return .{ .total = sb.total, - .offset = sb.offset, .len = sb.len, .cursor_x = @intCast(screen.cursor.x), .cursor_y = @intCast(screen.cursor.y), .cursor_visible = s.vt.modes.get(.cursor_visible), - .view = if (screen.pages.viewport == .active) null else sb.offset, .cols = screen.pages.cols, }; } +/// The first and last rows a view at `place` shows (`Term.Grid`: a row of +/// the history from its top; null, or one the active area holds: the +/// active area). Ghostty's own viewport is never moved: it is the active +/// area's. +fn shown(pages: *ghostty_vt.PageList, place: ?usize) struct { top: ghostty_vt.Pin, bottom: ghostty_vt.Pin } { + const active = pages.getTopLeft(.active); + const last = pages.getBottomRight(.active) orelse active; + const sb = pages.scrollbar(); + const row = place orelse return .{ .top = active, .bottom = last }; + const above = (sb.total - sb.len) -| row; + if (above == 0) return .{ .top = active, .bottom = last }; + const top = active.up(above) orelse pages.getTopLeft(.screen); + var bottom = top.down(sb.len - 1) orelse last; + bottom.x = bottom.node.cols() - 1; + return .{ .top = top, .bottom = bottom }; +} + +/// Each view's place (`Term.Grid`) held through a write of the emulator, +/// as ghostty holds a view of its own (`carried` after it): pinned to its +/// row of the primary screen, the only one with a history. One the active +/// area holds is on the output (null). +const Carry = struct { + pages: *ghostty_vt.PageList, + generation: usize, + pins: [max_places]?*ghostty_vt.Pin = @splat(null), + + /// The core's views (core/views.zig `max`), with room. + const max_places = 8; +}; + +fn carry(state: *State, places: []?usize) Carry { + const screens = &state.vt.screens; + const pages = &screens.get(.primary).?.pages; + var c: Carry = .{ .pages = pages, .generation = screens.generation(.primary) }; + std.debug.assert(places.len <= Carry.max_places); + const bottom = pages.total_rows - pages.rows; + for (places, c.pins[0..places.len]) |*place, *pin| { + const row = place.* orelse continue; + if (row >= bottom) { + place.* = null; + continue; + } + const at = pages.pin(.{ .screen = .{ .y = @intCast(row) } }) orelse { + place.* = null; + continue; + }; + // No room to follow it: on the output, as at a reset. + pin.* = pages.trackPin(at) catch null; + if (pin.* == null) place.* = null; + } + return c; +} + +/// `carry`'s places where the write left their rows: the history's top +/// for one whose row it dropped or erased, the output for one in the +/// active area now or on a screen made again. +fn carried(state: *State, c: Carry, places: []?usize) void { + const alive = state.vt.screens.generation(.primary) == c.generation; + const bottom = c.pages.total_rows - c.pages.rows; + for (places, c.pins[0..places.len]) |*place, held| { + const pin = held orelse continue; + if (!alive) { + place.* = null; + continue; + } + const row: usize = @intCast(pinnedRow(c.pages, .{ .pin = pin })); + c.pages.untrackPin(pin); + place.* = if (row >= bottom) null else row; + } +} + /// What pardes made of a terminal's stream that its emulator does not hold /// (the OSC 133 cycle, MarkedHandler), as bytes its digest holds: phase u8, started, prompts, declined u32, continuation /// and lost u8, a finished command's seq u32 and status i32 (all ones: @@ -524,38 +588,15 @@ pub fn dumpScreen(t: *ghostty_vt.Terminal, w: *std.Io.Writer) !void { while (it.next()) |p| try dumpRow(p.node.page(), p.rowAndCell().row, t.cols, w); } -/// Its view to row `at` of its history (from the top), or onto its output. -pub fn viewTo(state: *State, at: ?usize) void { - state.vt.screens.active.scroll(if (at) |row| .{ .row = row } else .active); -} - -/// Its view moved by `delta` rows (negative scrolls back). -pub fn scroll(state: *State, delta: i32) void { - state.vt.screens.active.scroll(.{ .delta_row = delta }); -} - -/// Its view back onto the output. -pub fn follow(state: *State) void { - state.vt.screens.active.scroll(.active); -} - -/// Its grid reflowed to `cols` by `rows`. A failed reflow keeps the grid -/// it had rather than dropping a scrollback; the next resize retries with -/// the same numbers. -pub fn resize(state: *State, cols: u16, rows: u16) void { - reflow(state, cols, rows); -} - -/// Its grid reflowed, and its view a row of its history again, as `viewTo` -/// and `grid` have it: ghostty's view follows a cell, which a widening -/// can leave mid-row (a wrapped line's second row joined to its first) and -/// the next narrowing carries a row down, where a view put back at its row -/// (a replica's rollback, core/replica.zig `putViews`) stays. -fn reflow(state: *State, cols: u16, rows: u16) void { +/// Its grid reflowed to `cols` by `rows`, every view's place carried +/// through it (`carry`: a row's first cell, so a place is a row again after +/// every reflow, whatever a widening joined). A failed reflow keeps the +/// grid it had rather than dropping a scrollback; the next resize retries +/// with the same numbers. +pub fn resize(state: *State, cols: u16, rows: u16, places: []?usize) void { + const held: ?Carry = if (places.len == 0) null else carry(state, places); + defer if (held) |c| carried(state, c, places); state.vt.resize(state.gpa, .{ .cols = cols, .rows = rows }) catch {}; - inline for (.{ .primary, .alternate }) |which| if (state.vt.screens.get(which)) |screen| { - if (screen.pages.viewport == .pin) screen.pages.viewport_pin.x = 0; - }; } /// The emulator's size in pixels follows the core's cells: kitty graphics @@ -831,9 +872,12 @@ fn pinnedRow(pages: ?*ghostty_vt.PageList, row: RowPin) i32 { /// One read of its program's output. `track` are rows (absolute, from the /// top of the history) the core keeps positions on; each is told in /// `rows` where it is after the read and in `erased` whether the program -/// erased it (a negative row passes through untouched). With nothing -/// tracked the read is parsed and nothing more. -pub fn feed(state: *State, bytes: []const u8, tracked: []const i32, rows: []i32, erased: []bool) Term.Told { +/// erased it (a negative row passes through untouched). Every view's +/// place is carried through it as `resize` carries them. With nothing +/// tracked and no view off the output the read is parsed and nothing more. +pub fn feed(state: *State, bytes: []const u8, tracked: []const i32, rows: []i32, erased: []bool, places: []?usize) Term.Told { + const carrying: ?Carry = if (places.len == 0) null else carry(state, places); + defer if (carrying) |c| carried(state, c, places); if (tracked.len == 0) { ingest(state, bytes); return .{ .rows = rows[0..0], .erased = erased[0..0], .cleared = false, .alive = true, .failed = false }; @@ -1008,22 +1052,23 @@ pub fn key(state: *State, k: Key, out: *std.Io.Writer) !void { }); } -/// How many cells left or right of the cursor a click on viewport row -/// `row`, column `col` of the text shown (the prompt cut off) is, at the -/// prompt the cursor is at: what moves the shell's cursor there. Null -/// when the cursor is at no prompt, or the click is before the prompt. +/// How many cells left or right of the cursor a click on row `row` (from +/// the top of the history), column `col` of the text shown (the prompt cut +/// off) is, at the prompt the cursor is at: what moves the shell's cursor +/// there. Null when the cursor is at no prompt, or the click is before the +/// prompt. pub fn promptMoves(state: *State, row: i32, col: i32) ?Term.Moves { if (!state.vt.cursorIsAtPrompt() or row < 0) return null; const screen = state.vt.screens.active; var grid_col: i32 = @max(0, col); - if (screen.pages.pin(.{ .viewport = .{ .x = 0, .y = @intCast(row) } })) |row_pin| { + if (screen.pages.pin(.{ .screen = .{ .x = 0, .y = @intCast(row) } })) |row_pin| { if (row_pin.rowAndCell().row.semantic_prompt != .none) switch (promptCut(row_pin)) { .cut => |cols| grid_col += @intCast(cols), .keep, .blank => {}, }; } const click_pin = screen.pages.pin(.{ - .viewport = .{ .x = @intCast(grid_col), .y = @intCast(row) }, + .screen = .{ .x = @intCast(grid_col), .y = @intCast(row) }, }) orelse return null; const cursor_pin = screen.cursor.page_pin.*; var prompts = cursor_pin.promptIterator(.left_up, null); @@ -1170,17 +1215,16 @@ pub fn textRows(state: *State, alloc: std.mem.Allocator, scratch: std.mem.Alloca return .{ .text_alloc = text, .text = text[0..at], .rows = lines }; } -/// The rows its view shows as text, a prompt's own cells cut off the rows -/// it starts when `cut` (as the core shows them outside raw mode): `arena`'s. -pub fn viewport(state: *State, arena: std.mem.Allocator, cut: bool) ![]const []const u8 { +/// The rows a view at `place` shows as text, a prompt's own cells cut off +/// the rows it starts when `cut` (as the core shows them outside raw +/// mode): `arena`'s. +pub fn viewport(state: *State, arena: std.mem.Allocator, cut: bool, place: ?usize) ![]const []const u8 { const screen = state.vt.screens.active; - var tl = screen.pages.getTopLeft(.viewport); - tl.x = 0; - const br = screen.pages.getBottomRight(.viewport) orelse return error.UnknownPoint; + const rows = shown(&screen.pages, place); var rows_out: std.Io.Writer.Allocating = .init(arena); - try screen.dumpString(&rows_out.writer, .{ .tl = tl, .br = br, .unwrap = false }); + try screen.dumpString(&rows_out.writer, .{ .tl = rows.top, .br = rows.bottom, .unwrap = false }); const raw = try rows_out.toOwnedSlice(); - var prompts = screen.pages.rowIterator(.right_down, .{ .viewport = .{} }, null); + var prompts = rows.top.rowIterator(.right_down, rows.bottom); const vp = try arena.alloc([]const u8, std.mem.count(u8, raw, "\n") + 1); var lines = std.mem.splitScalar(u8, raw, '\n'); var n: usize = 0; @@ -1198,13 +1242,13 @@ pub fn viewport(state: *State, arena: std.mem.Allocator, cut: bool) ![]const []c return vp; } -/// Its view's rows as cells, for the core's paint (Term.paint, the core's -/// core/ansi.zig): `rows.len` rows from the view's row `first`, `cols` -/// cells each into `cells`, each its style in the theme's colours (through -/// the filter when `filtered`), the bytes it spells in the view's text and -/// its width; each row whether a prompt starts it, and how much of it that -/// is. -pub fn paint(state: *State, ink: *const Ink, palette: *FilterPalette, filtered: bool, first: u16, cols: u16, cells: []Painted, rows: []PaintedRow) void { +/// The rows of a view at `place` as cells, for the core's paint +/// (Term.paint, the core's core/ansi.zig): `rows.len` rows from the view's +/// row `first`, `cols` cells each into `cells`, each its style in the +/// theme's colours (through the filter when `filtered`), the bytes it +/// spells in the view's text and its width; each row whether a prompt +/// starts it, and how much of it that is. +pub fn paint(state: *State, ink: *const Ink, palette: *FilterPalette, filtered: bool, place: ?usize, first: u16, cols: u16, cells: []Painted, rows: []PaintedRow) void { var filter_storage: Filter = undefined; const filter: ?*Filter = if (filtered) blk: { filter_storage = filterOf(ink, palette, &state.vt); @@ -1214,9 +1258,10 @@ pub fn paint(state: *State, ink: *const Ink, palette: *FilterPalette, filtered: // path needs it per cell. const scnm = state.vt.modes.get(.reverse_colors); const pages = &state.vt.screens.active.pages; + const top = shown(pages, place).top; for (rows, 0..) |*row, vi| { row.* = .{ .prompt = null, .placeholder = false, .len = 0 }; - const row_pin = pages.pin(.{ .viewport = .{ .y = @intCast(first + vi) } }) orelse continue; + const row_pin = top.down(first + vi) orelse continue; const flags = row_pin.rowAndCell().row; if (flags.semantic_prompt != .none) row.prompt = promptCut(row_pin); row.placeholder = flags.kitty_virtual_placeholder; @@ -1480,13 +1525,14 @@ pub fn hasImages(maybe: ?*const State) bool { pub fn images(state: *State, gpa: std.mem.Allocator, at: ImagesAt, out: *std.ArrayList(plain.Placement), frame: []plain.Cell, frame_cols: u16) void { if (comptime !images_enabled) return; const screen = state.vt.screens.active; + const view = shown(&screen.pages, at.place); var rows_of: [1024]?u16 = undefined; const vp_rows = @min(at.rows_of.len, rows_of.len); var any_placeholder = false; for (rows_of[0..vp_rows], at.rows_of[0..vp_rows], 0..) |*slot, body_row, vi| { slot.* = null; const vr = body_row orelse continue; - const row_pin = screen.pages.pin(.{ .viewport = .{ .y = @intCast(vi) } }) orelse continue; + const row_pin = view.top.down(vi) orelse continue; const flags = row_pin.rowAndCell().row; if (!at.tty_mode and flags.semantic_prompt != .none) continue; any_placeholder = any_placeholder or flags.kitty_virtual_placeholder; @@ -1495,28 +1541,105 @@ pub fn images(state: *State, gpa: std.mem.Allocator, at: ImagesAt, out: *std.Arr // Nothing to draw, no placeholder to blank and nothing cached to let // go: the common case costs the rows' flags. if (!any_placeholder and screen.kitty_images.placements.count() == 0 and state.images.converted.count() == 0) return; - state.images.draw(state.gpa, gpa, &state.vt, at, rows_of[0..vp_rows], out, frame, frame_cols); + state.images.draw(state.gpa, gpa, &state.vt, at, view.top, view.bottom, rows_of[0..vp_rows], out, frame, frame_cols); } -test "a view put back at the row it reports is the view it was, through a reflow: a view on a wrapped line's second row, joined into the row above by a widening and parted again by a narrowing, is the same row put back or not" { - // The bytes soak's divergence (reports/pardes-term-join-6.md): a - // client's rollback puts each terminal's view back at its row - // (core/replica.zig `putViews`), and ghostty's view is a cell, which - // a widening leaves mid-row and the next narrowing carries a row down. +test "a view's place at the history's cap: it keeps showing its line while output drops the rows above it, and goes to the top once its own row is dropped; on the output it follows" { const gpa = std.testing.allocator; - const left = try open(gpa, 20, 2); - defer close(left); - const put = try open(gpa, 20, 2); - defer close(put); - for ([_]*State{ left, put }) |s| { - // Lines two rows long at 20 columns, one at 40. - for (0..30) |_| ingest(s, "abcdefghijklmnopqrstuvwxyz0123\r\n"); - viewTo(s, 1); - resize(s, 40, 2); + const s = try open(gpa, 20, 4); + defer close(s); + // The history at its least (whole pages are dropped past it), filled + // to it: a line no longer grows it. + s.vt.screens.active.pages.setMaxBytes(1); + var line: [32]u8 = undefined; + var n: usize = 0; + while (true) : (n += 1) { + const before = grid(s).total; + ingest(s, try std.fmt.bufPrint(&line, "line-{d}\r\n", .{n})); + if (before > grid(s).len and grid(s).total <= before) break; + } + // A page dropped: the next page is the newest. Fed into it past a + // screenful, so its own rows reach into the history. + for (0..100) |_| { + ingest(s, try std.fmt.bufPrint(&line, "line-{d}\r\n", .{n})); + n += 1; + } + var arena: std.heap.ArenaAllocator = .init(gpa); + defer arena.deinit(); + // One view on the history's last row (in that newest page), one on the + // output. + const at = grid(s).total - grid(s).len - 1; + var places = [_]?usize{ at, null }; + const was = (try viewport(s, arena.allocator(), false, places[0]))[0]; + // Fed a line at a time until the history drops the page above it. + while (places[0].? == at) : (n += 1) { + _ = feed(s, try std.fmt.bufPrint(&line, "line-{d}\r\n", .{n}), &.{}, &.{}, &.{}, &places); + try std.testing.expectEqual(@as(?usize, null), places[1]); + } + // Moved up by the rows dropped, on the same line. + try std.testing.expect(places[0].? < at); + try std.testing.expectEqualStrings(was, (try viewport(s, arena.allocator(), false, places[0]))[0]); + // Fed until its own row is dropped: the history's top. + while (places[0].? > 0) : (n += 1) _ = feed(s, try std.fmt.bufPrint(&line, "line-{d}\r\n", .{n}), &.{}, &.{}, &.{}, &places); + try std.testing.expectEqual(@as(?usize, 0), places[0]); + try std.testing.expectEqual(@as(?usize, null), places[1]); +} + +test "a view's place is carried through output, the history's cap and reflows as ghostty carries a view of its own, a row's first cell each time (a fuzz)" { + // The oracle: an emulator scrolled by ghostty itself to the same row, + // fed and resized alike, its view put at its row's first cell after a + // reflow (a widening can leave ghostty's mid-row: pardes-term-join-6), + // and at the output when it reaches the active area. + const gpa = std.testing.allocator; + var seed: u64 = 0; + while (seed < 300) : (seed += 1) { + var prng: std.Random.DefaultPrng = .init(seed); + const rnd = prng.random(); + var cols: u16 = rnd.intRangeAtMost(u16, 20, 60); + var rows: u16 = rnd.intRangeAtMost(u16, 2, 6); + const ours = try open(gpa, cols, rows); + defer close(ours); + const oracle = try open(gpa, cols, rows); + defer close(oracle); + const capped = rnd.boolean(); + for ([_]*State{ ours, oracle }) |s| if (capped) s.vt.screens.active.pages.setMaxBytes(1); + var places = [_]?usize{null}; + var line: [200]u8 = undefined; + for (0..80) |_| { + switch (rnd.uintLessThan(u8, 4)) { + 0, 1 => for (0..rnd.intRangeAtMost(usize, 1, 400)) |i| { + const len = rnd.intRangeAtMost(usize, 0, 150); + for (line[0..len], 0..) |*c, j| c.* = 'a' + @as(u8, @intCast((i + j) % 26)); + _ = feed(ours, line[0..len], &.{}, &.{}, &.{}, &places); + _ = feed(ours, "\r\n", &.{}, &.{}, &.{}, &places); + ingest(oracle, line[0..len]); + ingest(oracle, "\r\n"); + }, + 2 => { + if (rnd.boolean()) cols = rnd.intRangeAtMost(u16, 20, 60); + rows = rnd.intRangeAtMost(u16, 2, 6); + resize(ours, cols, rows, &places); + oracle.vt.resize(gpa, .{ .cols = cols, .rows = rows }) catch {}; + const pages = &oracle.vt.screens.active.pages; + if (pages.viewport == .pin) pages.viewport_pin.x = 0; + }, + else => { + const sb = ours.vt.screens.active.pages.scrollbar(); + const to = rnd.uintLessThan(usize, sb.total); + places[0] = if (to >= sb.total - sb.len) null else to; + oracle.vt.screens.active.scroll(.{ .row = to }); + }, + } + const pages = &oracle.vt.screens.active.pages; + const sb = pages.scrollbar(); + if (sb.offset >= sb.total - sb.len) pages.scroll(.active); + const want: ?usize = if (pages.viewport == .active) null else pages.scrollbar().offset; + if (want != places[0]) { + std.debug.print("seed {d}: carried {?d}, ghostty's own {?d}\n", .{ seed, places[0], want }); + return error.TestExpectedEqual; + } + } } - viewTo(put, grid(put).view); - for ([_]*State{ left, put }) |s| resize(s, 20, 2); - try std.testing.expectEqual(grid(left), grid(put)); } test "the luminance table answers exactly what ghostty computes" { @@ -1560,8 +1683,8 @@ fn expectSame(gpa: std.mem.Allocator, a: *const State, b: *const State) !void { try std.testing.expectEqualSlices(u8, a.reply[0..a.reply_len], b.reply[0..b.reply_len]); var ha: std.hash.Wyhash = .init(0); var hb: std.hash.Wyhash = .init(0); - digest(a, &ha, true); - digest(b, &hb, true); + digest(a, &ha); + digest(b, &hb); try std.testing.expectEqual(ha.final(), hb.final()); } @@ -1647,8 +1770,8 @@ fn feedReflowing(s: *State, bytes: []const u8, from: usize, to: usize, stops: [2 const rows = s.vt.rows; var at = from; while (at < to) { - if (at == stops[0]) resize(s, cols / 2 + 1, rows + 3); - if (at == stops[1]) resize(s, cols * 2 - 2, rows - 3); + if (at == stops[0]) resize(s, cols / 2 + 1, rows + 3, &.{}); + if (at == stops[1]) resize(s, cols * 2 - 2, rows - 3, &.{}); var end = @min(to, at + 4096); for (stops) |stop| if (at < stop and stop < end) { end = stop; diff --git a/core/views.zig b/core/views.zig index 663610c3..f414eb6c 100644 --- a/core/views.zig +++ b/core/views.zig @@ -38,9 +38,10 @@ pub const max = 4; pub const away_kept_ns: u64 = 30 * std.time.ns_per_s; /// A pane's fields that are each view's own: where it is in the view's -/// layout, which of its texts has the keyboard, how far it is scrolled, and -/// what the view's step measured of it (its tag's rows, its bands). -const pane_fields = [_][:0]const u8{ "focus", "vweight", "collapsed", "docked_to", "hscroll", "tag_scroll", "tag_top", "tag_rows", "view", "layers", "notices", "pan", "follow_scroll" }; +/// layout, which of its texts has the keyboard, how far it is scrolled (a +/// terminal's history too), and what the view's step measured of it (its +/// tag's rows, its bands). +const pane_fields = [_][:0]const u8{ "focus", "vweight", "collapsed", "docked_to", "hscroll", "tag_scroll", "tag_top", "tag_rows", "view", "layers", "notices", "pan", "follow_scroll", "scrolled_to" }; /// The body's: its cursor, selections and mode. Its undo stays the pane's. const body_fields = [_][:0]const u8{ "mode", "cur_pinned", "cur_row", "cur_col", "vsel", "sels", "nsel", "select", "sticky_col", "restore_cursor", "last_edit", "reg_wait", "normal", "find_op", "find_ch" }; @@ -60,6 +61,7 @@ pub const PaneView = struct { notices: Pane.Notices = .{}, pan: u16 = 0, follow_scroll: usize = 0, + scrolled_to: ?usize = null, body: Part(Text, &body_fields) = .{}, /// A document's scroll and size; a terminal's size is its pty's, which /// every view shows (sized by its last typist, `Pardes.sync`). @@ -944,6 +946,53 @@ test "a terminal shown in a view shorter than it keeps its cursor in sight" { try testing.expectEqual(@as(u16, 0), term.pan); } +test "each view has its own place in a terminal's history: a wheel in one scrolls it back, the other stays on the output and follows it" { + if (pardes.Term.ops == null) return error.SkipZigTest; // a shell + const gpa = testing.allocator; + const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24 }); + defer p.deinit(); + const id = p.view().active; + const term = p.panes[id].?; + var out: std.ArrayList(u8) = .empty; + defer out.deinit(gpa); + for (0..100) |i| try out.print(gpa, "line-{d}\r\n", .{i}); + p.update(.{ .output = .{ .pane = .at(id), .bytes = out.items } }); + p.sync(); + const bottom = term.scroll(); + try testing.expect(bottom > 0); + const k = p.openView().?; + p.toView(k); + const r = p.view().rects[id]; + const at = .{ .col = r.x + r.w / 2, .row = p.bodyTop(term, r) + 1 }; + for (0..3) |_| p.update(.{ .mouse = .{ .button = .wheel_up, .kind = .press, .col = at.col, .row = at.row } }); + p.sync(); + const back = term.scroll(); + try testing.expect(back < bottom); + // The session's view is where it was: on the output. + p.toView(.at(0)); + p.sync(); + try testing.expectEqual(bottom, term.scroll()); + // Output comes: the view on the output follows it, the one scrolled + // back stays on its row. + p.update(.{ .output = .{ .pane = .at(id), .bytes = "more-1\r\nmore-2\r\n" } }); + p.sync(); + try testing.expectEqual(bottom + 2, term.scroll()); + p.toView(k); + p.sync(); + try testing.expectEqual(back, term.scroll()); + // A session's dump keeps each view's place. + const bytes = try pardes.dump.dumpBytes(p); + defer gpa.free(bytes); + const loaded = try pardes.dump.load(gpa, .{ .tty_only = true, .cols = 80, .rows = 24 }, bytes, null); + defer loaded.deinit(); + try testing.expectEqual(pardes.walk.digest(Pardes, p), pardes.walk.digest(Pardes, loaded)); + const lt = loaded.panes[id].?; + loaded.toView(k); + try testing.expectEqual(back, lt.scroll()); + loaded.toView(.at(0)); + try testing.expectEqual(bottom + 2, lt.scroll()); +} + test "a session's dump keeps its views: loaded, each where it was; revived for one client, the live one alone" { const gpa = testing.allocator; const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24 }); diff --git a/test/daemon.py b/test/daemon.py index 55cffaf4..c91e6dde 100644 --- a/test/daemon.py +++ b/test/daemon.py @@ -276,7 +276,7 @@ class Replica: """A replica's connection (abi/wire.zig): length-prefixed messages, a tag byte and a little-endian u32 length. It is a near client: its first word after the hello says so.""" - WIRE = 30 + WIRE = 31 def __init__(self, path, timeout=10): self.path, self.timeout = path, timeout diff --git a/test/kitty.zig b/test/kitty.zig index 76d97421..22b62fb2 100644 --- a/test/kitty.zig +++ b/test/kitty.zig @@ -641,14 +641,14 @@ 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(40, pane.rows); + pane.resizeGrid(0, 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'); while (lines.next()) |line| : (row += 1) if (std.mem.startsWith(u8, line, "marker")) break; const drawn = try r.placesOf(10); try std.testing.expectEqual(@as(usize, 1), drawn.len); - const viewport_top: usize = pardes.Term.grid(pane.terminal).offset; + const viewport_top: usize = pane.termTop(); try std.testing.expectEqual(o.y + @as(u16, @intCast(row - viewport_top)), drawn[0].dst.y); } @@ -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(1 + rng.uintLessThan(u16, 120), 1 + rng.uintLessThan(u16, 40)), + 1 => r.pane(0).resizeGrid(0, 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() }); @@ -1224,7 +1224,7 @@ test "kitty: scrolled back by pardes, an image shows on its row; scrolled forwar r.feed(0, &nl); try std.testing.expectEqual(@as(usize, 0), (try r.placesOf(20)).len); // Back to the top of the history: the marker row is the body's first. - pardes.Term.scroll(pane.terminal.?, -1000); + pane.scrollBy(-1000); const o = r.origin(0); const drawn = try r.placesOf(20); try std.testing.expectEqual(@as(usize, 1), drawn.len); diff --git a/test/panes.zig b/test/panes.zig index 32cfd530..0a0bd3f9 100644 --- a/test/panes.zig +++ b/test/panes.zig @@ -965,7 +965,7 @@ test "terminal overlay recoloring never materializes unrelated history" { _ = try p.render(frame.allocator()); try testing.expect(p.shell_rows.pane == null); - pane.ovl.?.row = @intCast(pardes.Term.grid(pane.terminal).offset); + pane.ovl.?.row = @intCast(pane.termTop()); p.gpa.free(pane.ovl.?.text); pane.ovl.?.text = try p.gpa.dupe(u8, "caf\xc3\xa9 \xe7\x95\x8c"); _ = frame.reset(.retain_capacity); @@ -994,8 +994,8 @@ test "terminal output keeps following new rows after scrollback eviction" { for (0..3) |phase| { if (phase > 0) { pane.body.mode = .normal; - pardes.Term.scroll(pane.terminal.?, -30); - try std.testing.expect(pages.scrollbar().offset < pages.scrollbar().total - pane.rows); + pane.scrollBy(-30); + try std.testing.expect(pane.termTop() < pages.scrollbar().total - pane.rows); pardes.keys.enterTty(p, 0); } for (phase * 20_000..(phase + 1) * 20_000) |n| { @@ -1008,7 +1008,7 @@ test "terminal output keeps following new rows after scrollback eviction" { try std.testing.expect(evictions > phase); try std.testing.expect(pages.page_size <= pages.limits.max(.bytes)); const sb = pages.scrollbar(); - try std.testing.expectEqual(sb.total - pane.rows, sb.offset); + try std.testing.expectEqual(sb.total - pane.rows, pane.termTop()); const full = try pardes.Term.scrollback(pane.terminal, gpa); defer gpa.free(full); var last_buf: [16]u8 = undefined; @@ -2686,14 +2686,14 @@ const TerminalTests = struct { p.update(.{ .output = .{ .pane = .at(0), .bytes = bytes } }); } p.shell_rows.stale = true; - pardes.Term.scroll(pane.terminal.?, -20); + pane.scrollBy(-20); // ONE buffer line standing in for SIX shell rows: everything below slides // UP five, so the last rows of the body resolve past the viewport's bottom // edge. `PageList.pin` answers for those rows anyway — it walks down the // pagelist, not the viewport — so without a bound of its own this pass // painted the scrollback's colours onto rows the text pass left blank. - const anchor: i32 = @intCast(pardes.Term.grid(pane.terminal).offset); + const anchor: i32 = @intCast(pane.termTop()); pane.ovl = .{ .row = anchor, .rows = 6, .text = try p.gpa.dupe(u8, "one") }; p.shell_rows.stale = true; @@ -2958,7 +2958,7 @@ const TerminalTests = struct { // a buffer whose covered span STRADDLES the viewport top is an ordinary // state. tty mode does not apply the buffer, so it must not be moved by one // either — and `surfRow`/`gridRow` are not inverses across that span. - const anchor: i32 = @intCast(pardes.Term.grid(pane.terminal).offset); + const anchor: i32 = @intCast(pane.termTop()); pane.ovl = .{ .row = anchor - 1, .rows = 4, .text = try p.gpa.dupe(u8, "one\ntwo") }; p.shell_rows.stale = true; _ = frame.reset(.retain_capacity); diff --git a/test/perf.zig b/test/perf.zig index e9ee43d7..30e15dcc 100644 --- a/test/perf.zig +++ b/test/perf.zig @@ -1138,7 +1138,7 @@ fn measureTerminalSession(io: std.Io, mib: usize, reps: usize, json: bool) !void const begin = nowNs(); core.update(.{ .output = .{ .pane = .at(0), .bytes = update } }); pump(core); - const cursor_row = @as(i32, @intCast(pardes.Term.grid(pane.terminal).offset)) + @as(i32, pardes.Term.grid(pane.terminal).cursor_y); + const cursor_row = @as(i32, @intCast(pane.termTop())) + @as(i32, pardes.Term.grid(pane.terminal).cursor_y); pane.ovl.?.row = if (phase == 0) 0 else cursor_row - 1; pane.body.cur_row = pane.ovl.?.row; pane.body.cur_col = 0; diff --git a/test/replicas.zig b/test/replicas.zig index 90f7c10d..a68ce222 100644 --- a/test/replicas.zig +++ b/test/replicas.zig @@ -856,19 +856,18 @@ const Watchdog = struct { /// the untraced one. const Named = struct { const Parted = struct { c: usize, origin: u16, seq: u32, parts: []u64, terms: [pardes.MAX_PANES]Term }; - /// A terminal pane's: its screen's digest without its view and with - /// it, and where its view and cursor stand. - const Term = struct { content: u64 = 0, viewed: u64 = 0, grid: pardes.Term.Grid = .{} }; + /// A terminal pane's: its screen's digest, where the live view stands + /// in it (the pane's, `scrolled_to`), and its grid. + const Term = struct { content: u64 = 0, place: ?usize = null, grid: pardes.Term.Grid = .{} }; fn terms(p: *const pardes.Pardes) [pardes.MAX_PANES]Term { var out: [pardes.MAX_PANES]Term = @splat(.{}); for (p.panes, &out) |slot, *t| { - const state = (slot orelse continue).terminal orelse continue; + const pane = slot orelse continue; + const state = pane.terminal orelse continue; var a = pardes.walk.Hasher.init(0); - state.digestScreen(&a, false); - var b = pardes.walk.Hasher.init(0); - state.digestScreen(&b, true); - t.* = .{ .content = a.final(), .viewed = b.final(), .grid = pardes.Term.grid(state) }; + state.digest(&a); + t.* = .{ .content = a.final(), .place = pane.scrolled_to, .grid = pardes.Term.grid(state) }; } return out; } @@ -898,8 +897,8 @@ const Named = struct { const theirs = arena.allocator().create(pardes.tape.Parts) catch return; const want = pardes.tape.digestParts(rp.core(), theirs); w.print("seed {d} rtt {d} ms: client {d} names: at unit {d}/{d}, against the witness's replay: {s}\n", tag ++ .{ x.c + 1, u.origin, u.seq, pardes.tape.partsDiffer(x.parts, want, arena.allocator()) }) catch {}; - for (x.terms, terms(rp.core()), 0..) |a, b, id| if (a.viewed != b.viewed or a.content != b.content) { - w.print(" pane {d}'s terminal: content {s}, view {s}; the client's {any}; the witness's {any}\n", .{ id, if (a.content == b.content) "equal" else "DIFFERS", if (a.viewed == b.viewed) "equal" else "DIFFERS", a.grid, b.grid }) catch {}; + for (x.terms, terms(rp.core()), 0..) |a, b, id| if (a.place != b.place or a.content != b.content) { + w.print(" pane {d}'s terminal: content {s}, view {s}; the client's {any} at {?d}; the witness's {any} at {?d}\n", .{ id, if (a.content == b.content) "equal" else "DIFFERS", if (a.place == b.place) "equal" else "DIFFERS", a.grid, a.place, b.grid, b.place }) catch {}; }; }; } diff --git a/test/terminal.zig b/test/terminal.zig index 7e7106a1..bad70081 100644 --- a/test/terminal.zig +++ b/test/terminal.zig @@ -25,7 +25,6 @@ const close = Term.close; const grid = Term.grid; const modes = Term.modes; const prompt = Term.prompt; -const scroll = Term.scroll; const scrollback = Term.scrollback; const commandOutput = Term.commandOutput; const filterOf = emu.filterOf; @@ -110,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(80, 24); + pane.resizeGrid(0, 80, 24); 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); @@ -139,7 +138,7 @@ test "terminal state keeps parser fragments and sends emulator replies through i try std.testing.expectEqual(@as(u16, 0), state.reply_len); } -test "a terminal's dump restores the cells it drew, its history and where its view was" { +test "a terminal's dump restores the cells it drew and its history (where a view stands is the view's, dumped with its pane)" { const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 40, .rows = 12 }); defer p.deinit(); @@ -150,7 +149,6 @@ test "a terminal's dump restores the cells it drew, its history and where its vi var line: [16]u8 = undefined; pane.feedOutput(p, std.fmt.bufPrint(&line, "line {d}\r\n", .{i}) catch unreachable); } - scroll(pane.terminal.?, -5); const bytes = try pardes.walk.save(State, gpa, pane.terminal.?); defer gpa.free(bytes); var arena: std.heap.ArenaAllocator = .init(gpa); |
