From 8e850e6c923dcd84b7a5483f73377bd192b94a2b Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Sun, 22 Nov 2026 17:55:03 -0300 Subject: 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 Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T --- core/term/TerminalImages.zig | 25 ++-- core/term/term.zig | 3 - core/term/terminal.zig | 317 ++++++++++++++++++++++++++++++------------- 3 files changed, 233 insertions(+), 112 deletions(-) (limited to 'core/term') 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; -- cgit v1.3