From 5354090b6122faf0d18e246a55e8a4ead0955394 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Tue, 17 Nov 2026 00:17:45 -0300 Subject: Term: output and view through the interface: Term.feed takes one read and the rows the core keeps positions on and gives back a Term.Told (where each went, erased or not, cleared, alive, a pin missed), Term.grid is the plain record of the view and the cursor (total, offset, len, the cursor, whether it shows, the view's row or null while it follows), Term.scroll, Term.follow, Term.viewTo, Term.resize (now or for later) and Term.resizeDeferred move it, Term.cellPixels sizes its cells in pixels and Term.replies hands over what it answered its program; the core's half is the core's: Pane.feedOutput and its row tracking (the edit copy's rows, the cursors and selections, their undo and the pointer's rows, gathered as rows and moved as the feed told, ingestWithPositions's core) and Pane.followOutput, Pane.resizeGrid and Pane.panFor in panes.zig with panes.resizeDeferred, the cursor a program shows read from the grid where the body draws it, tape.viewOnly beside tape.authorityOnly; scrollbar, gridOffset, gridCursor, visibleCursor, viewOf, atBottom and their types go; nothing else changes --- src/Core.zig | 31 ++- src/File.zig | 2 +- src/Jump.zig | 2 +- src/Term.zig | 48 +++++ src/body_layer.zig | 25 ++- src/draw.zig | 12 +- src/dump.zig | 14 +- src/edit.zig | 2 +- src/exec.zig | 10 +- src/keys.zig | 4 +- src/layout.zig | 4 +- src/mouse.zig | 2 +- src/ninep/pty.zig | 6 +- src/panes.zig | 319 +++++++++++++++++++++++++++++- src/replica.zig | 34 ++-- src/tape.zig | 15 +- src/term/echo.zig | 7 +- src/term/terminal.zig | 526 +++++++++++--------------------------------------- src/views.zig | 2 +- 19 files changed, 564 insertions(+), 501 deletions(-) (limited to 'src') diff --git a/src/Core.zig b/src/Core.zig index 1f3e9283..2bf02c5d 100644 --- a/src/Core.zig +++ b/src/Core.zig @@ -1599,7 +1599,7 @@ pub fn update(p: *Pardes, ev: Event) void { const pane = p.panes[o.pane] orelse return; pane.shell_spoke = true; ctlfs.events.notePtyOutput(p, o.pane, o.bytes); - pardes.panes.terminal.feedOutput(p, pane, o.bytes); + pane.feedOutput(p, o.bytes); ctlfs.pty.noteMarks(p, o.pane, pane); exec.flushReplEnter(p, o.pane, true); }, @@ -1796,10 +1796,7 @@ pub fn sync(p: *Pardes) void { // What the terminal answers its program (a cursor report, its // attributes) goes as typed bytes go: behind whatever is still // queued for its pty, never ahead of it nor dropped. - if (pane.terminal) |state| { - p.emitWrite(id, state.reply[0..state.reply_len]); - state.reply_len = 0; - } + if (pane.terminal) |state| p.emitWrite(id, pardes.Term.replies(state)); const r = v.rects[id]; // The session's part of the pane's view geometry (File.geometry), // and its context declarations. @@ -1864,7 +1861,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()) { - pardes.panes.terminal.resizeGrid(pane, cols, rows); + pane.resizeGrid(cols, rows); p.shell_rows.markStale(pane); // reflow moved every row p.emit(.{ .resize_pty = .{ .pane = @intCast(id), .cols = cols, .rows = rows } }); pane.fs.winsize = null; @@ -1873,7 +1870,7 @@ pub fn sync(p: *Pardes) void { pane.rows = rows; if (pane.file) |*file| file.syntax_dirty = true; } - pane.pan = pardes.panes.terminal.panFor(p, pane, r); + pane.pan = pane.panFor(p, r); // A directory pane's entries follow its width, as acme's // columns do (Dir.fit). if (pane.file) |file| if (file.listing != null and r.h > pane.tag_rows) pardes.panes.Dir.fit(p, pane, pane.cols); @@ -1909,7 +1906,7 @@ fn typedInto(p: *Pardes) void { /// Whether the live view sizes terminal `pane`: a terminal shown at two /// sizes takes the size of the view that typed into it last, and any /// view's once that one is gone. The others show it at that size, a -/// shorter one passed down to its cursor (`Pane.pan`, terminal.panFor). +/// shorter one passed down to its cursor (`Pane.pan`, Pane.panFor). // ponytail: a panned view's pointer reports to a terminal's program and // its kitty images are placed as the unpanned rows are. fn sizes(p: *Pardes, pane: *Pane) bool { @@ -3706,13 +3703,13 @@ 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.panes.terminal.scrollGrid(pane, -1); + pardes.Term.scroll(pane.terminal.?, -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.panes.terminal.scrollGrid(pane, -@as(i32, pane.rows)); + pardes.Term.scroll(pane.terminal.?, -@as(i32, pane.rows)); try std.testing.expect((try p.render(frame.allocator())).cursor == null); - pardes.panes.terminal.followOutput(pane); + pane.followOutput(); const returned = (try p.render(frame.allocator())).cursor orelse return error.MissingCursor; try std.testing.expectEqual(live.x, returned.x); try std.testing.expectEqual(live.y, returned.y); @@ -3758,31 +3755,31 @@ test "tty output follows only from the bottom" { p.update(.{ .output = .{ .pane = @intCast(shell), .bytes = std.fmt.bufPrint(&buf, "line {d}\r\n", .{i}) catch unreachable } }); } p.sync(); - const bottom = pardes.panes.terminal.scrollbar(sp).offset; + const bottom = pardes.Term.grid(sp.terminal).offset; 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.panes.terminal.scrollbar(sp).offset; + const parked = pardes.Term.grid(sp.terminal).offset; try std.testing.expect(parked < bottom); for (60..70) |i| { var buf: [32]u8 = undefined; p.update(.{ .output = .{ .pane = @intCast(shell), .bytes = std.fmt.bufPrint(&buf, "line {d}\r\n", .{i}) catch unreachable } }); } p.sync(); - try std.testing.expectEqual(parked, pardes.panes.terminal.scrollbar(sp).offset); + try std.testing.expectEqual(parked, pardes.Term.grid(sp.terminal).offset); // Typing snaps back to live output, so nobody types blind. p.update(.{ .key = .{ .cp = 'x', .text = "x" } }); p.sync(); - try std.testing.expect(pardes.panes.terminal.scrollbar(sp).offset > parked); + try std.testing.expect(pardes.Term.grid(sp.terminal).offset > parked); // ...and from there output follows again. - const live = pardes.panes.terminal.scrollbar(sp).offset; + const live = pardes.Term.grid(sp.terminal).offset; p.update(.{ .output = .{ .pane = @intCast(shell), .bytes = "tail\r\n" } }); p.sync(); - try std.testing.expect(pardes.panes.terminal.scrollbar(sp).offset > live); + try std.testing.expect(pardes.Term.grid(sp.terminal).offset > live); } test "an unasked desktop paste reaches a tty pane's program, not its buffer" { diff --git a/src/File.zig b/src/File.zig index ffac06fd..bedf8ada 100644 --- a/src/File.zig +++ b/src/File.zig @@ -2163,7 +2163,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(vr); - const row_i: i32 = if (raw) terminal.gridOffset(pane) + vr else w.line; + const row_i: i32 = if (raw) @as(i32, @intCast(panes.Term.grid(pane.terminal).offset)) + 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/src/Jump.zig b/src/Jump.zig index 06cf8388..20b001be 100644 --- a/src/Jump.zig +++ b/src/Jump.zig @@ -409,7 +409,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 = 0, .bytes = "more output\r\n" } }); try std.testing.expectEqualStrings("alpha", try edit.selectionText(p, pane, pane.sel[0])); - panes.terminal.resizeGrid(pane, pane.cols - 1, pane.rows); + pane.resizeGrid(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/src/Term.zig b/src/Term.zig index 36315df4..41452757 100644 --- a/src/Term.zig +++ b/src/Term.zig @@ -29,3 +29,51 @@ pub const revive = terminal.revive; /// stopped with the host. pub const start = terminal.TerminalImages.start; pub const stop = terminal.TerminalImages.stop; + +// ---- output and view ---- + +/// One read of its program's output (`Told` says where the tracked rows +/// went). +pub const feed = terminal.feed; +/// Where the view and the cursor are (`Grid`). +pub const grid = terminal.grid; +/// Its view to a row of its history, or onto its output (null). +pub const viewTo = terminal.viewTo; +/// Its view moved by a number of rows (negative scrolls back). +pub const scroll = terminal.scroll; +/// Its view back onto its output. +pub const follow = terminal.follow; +/// Its grid reflowed, now or when `resizeDeferred` makes it. +pub const resize = terminal.resize; +pub const resizeDeferred = terminal.resizeDeferred; +/// Its cells' size in pixels (kitty graphics, CSI 14/16 t). +pub const cellPixels = terminal.cellPixels; +/// What it answered its program since the last call, to be written to its +/// pty. +pub const replies = terminal.replies; + +/// 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. +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). + 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, +}; + +/// What a `feed` told the rows the core keeps positions on: each tracked +/// row where it is after the read, whether the program erased it, whether +/// it cleared the screen, whether the pages the rows were on lived through +/// it (a reset can take them) and whether a row could not be followed (no +/// memory for its pin). Taped: a screen-state replica, which feeds +/// nothing, is told its authority's. +pub const Told = struct { rows: []const i32, erased: []const bool, cleared: bool, alive: bool, failed: bool }; diff --git a/src/body_layer.zig b/src/body_layer.zig index 76aec179..a8d09c66 100644 --- a/src/body_layer.zig +++ b/src/body_layer.zig @@ -37,7 +37,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) panes.terminal.gridOffset(pane) + visible else pane.wrapAt(visible).line; + const source_row = if (raw) @as(i32, @intCast(panes.Term.grid(pane.terminal).offset)) + visible else pane.wrapAt(visible).line; for (rows) |row| { const target = if (row.raw_terminal) (if (raw) row.row else pane.surfRow(row.row)) @@ -230,8 +230,7 @@ pub fn joinBody(p: *Pardes, s: *Surface, arena: std.mem.Allocator, pane: *Pane, fn drawGutter(p: *Pardes, s: *Surface, pane: *Pane, r: pardes.Rect, tx: u16, tw: u16, body_h: u16, active: bool) void { const prefix_width = panes.File.gutterWidth(pane); const goff = pane.scroll(); - const gcur = panes.terminal.gridCursor(pane); - const gcrow = if (pane.body.cur_pinned) pane.body.cur_row else @as(i32, gcur.y) + goff; + const gcrow = if (pane.body.cur_pinned) pane.body.cur_row else @as(i32, panes.Term.grid(pane.terminal).cursor_y) + goff; const typing_body = pane.focus == .body and (pane.prompt == .none or pane.prompt == .del_side or pane.prompt == .repl_choice); const cur_line: i32 = if (active and typing_body) gcrow else std.math.minInt(i32); // the body's first row, the way renderPane derives it @@ -491,10 +490,9 @@ pub fn renderBody(p: *Pardes, s: *Surface, arena: std.mem.Allocator, pane: *Pane // (the tag's or a prompt's cursor wins while that is being typed into) 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 cur = panes.terminal.gridCursor(pane); - const goff = panes.terminal.gridOffset(pane); - const crow = if (pane.body.cur_pinned) pane.body.cur_row else pane.surfRow(@as(i32, @intCast(cur.y)) + goff); - const ccol = if (pane.body.cur_pinned) pane.body.cur_col else @as(i32, @intCast(cur.x)); + 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 ccol = if (pane.body.cur_pinned) pane.body.cur_col else @as(i32, grid.cursor_x); const cwp = pane.wrapRow(crow, ccol); const prow = cwp.row + @as(i32, pane.tag_rows); // Off the view, the cursor is not measured (its column may be @@ -515,9 +513,16 @@ pub fn renderBody(p: *Pardes, s: *Surface, arena: std.mem.Allocator, pane: *Pane if (prow >= pane.tag_rows and cx >= 0 and prow < body_bottom and cx < tw) s.cursor = .{ .x = tx + @as(u16, @intCast(cx)), .y = body_y + @as(u16, @intCast(prow - pane.tag_rows)), .bar = pane.body.mode == .insert }; } - } else if (panes.terminal.visibleCursor(pane)) |cur| { - if (cur.y + pane.tag_rows < body_bottom and cur.x < tw) - s.cursor = .{ .x = tx + cur.x, .y = body_y + cur.y }; + } else if (pane.terminal != null) visible: { + // Where the program shows its cursor, if it does and in the rows + // the view shows (past the rows a short view pans over). + 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); + if (y + pane.tag_rows < body_bottom and grid.cursor_x < tw) + s.cursor = .{ .x = tx + grid.cursor_x, .y = body_y + y }; } } diff --git a/src/draw.zig b/src/draw.zig index a0a28cc7..a779d588 100644 --- a/src/draw.zig +++ b/src/draw.zig @@ -58,7 +58,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()) panes.terminal.gridOffset(pane) else 0; + 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; // 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. @@ -73,8 +73,8 @@ pub fn place(p: *Pardes, s: *Surface) void { .offset = f.scroll, .len = pane.rows, } else blk: { - const gsb = panes.terminal.scrollbar(pane); - break :blk .{ .total = gsb.total, .offset = gsb.offset, .len = gsb.len }; + const grid = panes.Term.grid(pane.terminal); + break :blk .{ .total = grid.total, .offset = grid.offset, .len = grid.len }; }; const track_h: usize = body_h; const total = if (sb.total == 0) 1 else sb.total; @@ -413,9 +413,9 @@ pub fn render(p: *Pardes, arena: std.mem.Allocator) !*Surface { sb_off = 0; sb_total = 0; } else { - const sb = panes.terminal.scrollbar(at); - sb_off = sb.offset; - sb_total = sb.total; + const grid = panes.Term.grid(at.terminal); + sb_off = grid.offset; + sb_total = grid.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/src/dump.zig b/src/dump.zig index 19ba25ce..075bb8cc 100644 --- a/src/dump.zig +++ b/src/dump.zig @@ -1002,12 +1002,13 @@ test "a loaded terminal's history stays above its banner, the cursor where it wa const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 40, .rows = 12 }); defer p.deinit(); while (p.nextEffect()) |_| {} - term.feedOutput(p, p.panes[0].?, "one\r\ntwo\r\n$ "); - const before = term.gridCursor(p.panes[0].?); + p.panes[0].?.feedOutput(p, "one\r\ntwo\r\n$ "); + const before = pardes.Term.grid(p.panes[0].?.terminal); try dumpState(p); const loaded = try load(gpa, .{ .tty_only = true, .cols = 40, .rows = 12 }, p.dump_out.?, null); defer loaded.deinit(); - try std.testing.expectEqual(before, term.gridCursor(loaded.panes[0].?)); + const after = pardes.Term.grid(loaded.panes[0].?.terminal); + try std.testing.expectEqual([2]u16{ before.cursor_x, before.cursor_y }, [2]u16{ after.cursor_x, after.cursor_y }); const q = try initFromDump(gpa, .{ .tty_only = true, .cols = 40, .rows = 12 }, p.dump_out.?); defer q.deinit(); const text = try term.screenTextAlloc(q.panes[0].?, gpa); @@ -1019,11 +1020,10 @@ test "a loaded terminal's history stays above its banner, the cursor where it wa test "an upgraded session's dump keeps its views and its running terminal as they were, and settings the startup config would change" { if (comptime isolated) return error.SkipZigTest; const gpa = std.testing.allocator; - const term = pardes.panes.terminal; const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 40, .rows = 12, .startup_config = "Verbose off\n" }); defer p.deinit(); while (p.nextEffect()) |_| {} - term.feedOutput(p, p.panes[0].?, "one\r\n\x1b[?1049h$ vim"); + p.panes[0].?.feedOutput(p, "one\r\n\x1b[?1049h$ vim"); try std.testing.expect(p.executeBuiltinLine(p.view().active, "Verbose on")); _ = p.openView().?; const bytes = try dumpBytes(p); @@ -1035,7 +1035,9 @@ test "an upgraded session's dump keeps its views and its running terminal as the try std.testing.expectEqual(@as(usize, 2), views.count(q)); try std.testing.expect(q.settings.verbose); // The program's own screen, no banner, and no shell asked for. - try std.testing.expectEqual(term.gridCursor(p.panes[0].?), term.gridCursor(q.panes[0].?)); + const was = pardes.Term.grid(p.panes[0].?.terminal); + const is = pardes.Term.grid(q.panes[0].?.terminal); + try std.testing.expectEqual([2]u16{ was.cursor_x, was.cursor_y }, [2]u16{ is.cursor_x, is.cursor_y }); try std.testing.expect(q.panes[0].?.terminal.?.vt.screens.active_key == .alternate); while (q.nextEffect()) |e| try std.testing.expect(e != .spawn); // Not kept, the same terminal is a new shell's under its history. diff --git a/src/edit.zig b/src/edit.zig index c5466531..5fbabc83 100644 --- a/src/edit.zig +++ b/src/edit.zig @@ -239,7 +239,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(visible); - if (raw) source = .{ .line = panes.terminal.gridOffset(pane) + visible, .at = 0 }; + if (raw) source = .{ .line = @as(i32, @intCast(panes.Term.grid(pane.terminal).offset)) + visible, .at = 0 }; const line = if (raw) modal.lineSlice(body, @intCast(visible)) else pointerSourceLine(pane, terminal_lines, source.line); var next = pane.wrapAt(visible + 1); if (raw) next = .{ .line = source.line + 1, .at = 0 }; diff --git a/src/exec.zig b/src/exec.zig index df578d08..69bbe162 100644 --- a/src/exec.zig +++ b/src/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(visible); const raw = pane.isTerminal() and pane.body.mode == .tty and clicked.r0 >= pane.tag_rows; - const row = if (raw) panes.terminal.gridOffset(pane) + visible else wrapped.line; + const row = if (raw) @as(i32, @intCast(panes.Term.grid(pane.terminal).offset)) + visible else wrapped.line; const raw_line = if (raw) modal.lineSlice(body_layer.bodyText(p.scratch.allocator(), pane) catch "", @intCast(@max(0, visible))) else ""; const col = if (raw) @as(i32, @intCast(panes.File.rawAtDisplay(raw_line, @intCast(@max(0, clicked.c0))))) @@ -772,8 +772,8 @@ fn runCommand(p: *Pardes, from: usize, line: []const u8) ?usize { // saved cursor), mouse reports and bracketed paste off, the cursor // shown, colours reset. (Not DECSTR: ghostty's stream does not // implement it.) - if (panes.terminal.onAlternateScreen(pane)) panes.terminal.feedOutput(p, pane, "\x1b[?1049l"); - panes.terminal.feedOutput(p, pane, "\x1b[?1000l\x1b[?1002l\x1b[?1003l\x1b[?1006l\x1b[?2004l\x1b[?25h\x1b[0m"); + if (panes.terminal.onAlternateScreen(pane)) pane.feedOutput(p, "\x1b[?1049l"); + pane.feedOutput(p, "\x1b[?1000l\x1b[?1002l\x1b[?1003l\x1b[?1006l\x1b[?2004l\x1b[?25h\x1b[0m"); echoCommand(p, pane, line); pane.command_from = winid(p, src); p.emitSpawn(id, pane.serial, pane.cwdSlice()); @@ -823,11 +823,11 @@ fn echoCommand(p: *Pardes, pane: *Pane, line: []const u8) void { var w = std.Io.Writer.fixed(&buf); // A line past the room is cut at its end. echo: { - w.writeAll(if (panes.terminal.gridCursor(pane).x != 0) "\r\n% " else "% ") catch break :echo; + w.writeAll(if (panes.Term.grid(pane.terminal).cursor_x != 0) "\r\n% " else "% ") catch break :echo; for (line) |c| (if (c == '\n') w.writeAll("\r\n") else w.writeByte(c)) catch break :echo; w.writeAll("\r\n") catch break :echo; } - panes.terminal.feedOutput(p, pane, w.buffered()); + pane.feedOutput(p, w.buffered()); } /// Trim and unwrap clickable command-word notation once for every command diff --git a/src/keys.zig b/src/keys.zig index 49ed00c0..7703d573 100644 --- a/src/keys.zig +++ b/src/keys.zig @@ -176,7 +176,7 @@ pub fn handleKey(p: *Pardes, key: Key) void { tagline.focusedHeader(p) == null; if (raw_esc and key.shift) { p.view().prefix = .none; - panes.terminal.followOutput(pane); + pane.followOutput(); var plain = key; plain.shift = false; return panes.terminal.forwardKey(p, p.view().active, plain); @@ -210,7 +210,7 @@ pub fn handleKey(p: *Pardes, key: Key) void { p.view().prefix = .none; if (key.ctrl and !key.alt and key.cp == p.tty_toggle) return toggleTty(p, p.view().active); - panes.terminal.followOutput(pane); // typing snaps back to live output + pane.followOutput(); // typing snaps back to live output // Paste stays the window's, the one exception to forwarding a raw // tty's keys: Ctrl-V types the register at the program and // Ctrl-Shift-V asks the desktop for its clipboard first. Forwarded, diff --git a/src/layout.zig b/src/layout.zig index fca4c846..73114e45 100644 --- a/src/layout.zig +++ b/src/layout.zig @@ -849,7 +849,7 @@ fn blankRows(p: *const Pardes, id: usize) u16 { // The empty line after a final newline shows nothing. (panes.File.nlines(p.gpa, f) -| @intFromBool(std.mem.endsWith(u8, f.content, "\n"))) -| f.scroll else if (pane.isTerminal()) - @as(usize, panes.terminal.gridCursor(pane).y) + 1 + @as(usize, panes.Term.grid(pane.terminal).cursor_y) + 1 else rows; return rows -| @as(u16, @intCast(@min(used, rows))); @@ -1090,7 +1090,7 @@ pub fn splitBelow(p: *Pardes, src_id: usize, nw: *Pane) void { // Its tag may wrap to more than one row: the rows under it are its body. const tag_h = @max(BOX_H, src.tag_rows); const body: u16 = if (src_h > tag_h) src_h - tag_h else 1; - const cur: u16 = if (!src.isTerminal()) body / 2 else panes.terminal.gridCursor(src).y + 1; + const cur: u16 = if (!src.isTerminal()) body / 2 else panes.Term.grid(src.terminal).cursor_y + 1; // cap keep so a content-full source still leaves the new pane a tag + // a few body rows (an Alt-n from a full shell was born 0 rows tall) // ...and the source min_body_rows of its own (placeNew), when it diff --git a/src/mouse.zig b/src/mouse.zig index 783b12b7..49e9927e 100644 --- a/src/mouse.zig +++ b/src/mouse.zig @@ -1157,7 +1157,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.scratch.allocator(), pane) catch |err| return p.reportError(p.view().active, "select", err); - const line = modal.lineSlice(body, @intCast(@max(0, endpoint.row - panes.terminal.gridOffset(pane)))); + const line = modal.lineSlice(body, @intCast(@max(0, endpoint.row - @as(i32, @intCast(panes.Term.grid(pane.terminal).offset))))); 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/src/ninep/pty.zig b/src/ninep/pty.zig index 7333fac7..2ef9c13d 100644 --- a/src/ninep/pty.zig +++ b/src/ninep/pty.zig @@ -302,7 +302,7 @@ pub fn noteMarks(p: *Pardes, id: usize, pane: *Pane) void { // A prompt on the alternate screen (its program killed there): the // emulator leaves it first, as a reused command pane does, so the // run's output lands on the primary screen and is read whole. - if (pardes.panes.terminal.onAlternateScreen(pane)) pardes.panes.terminal.feedOutput(p, pane, "\x1b[?1049l"); + if (pardes.panes.terminal.onAlternateScreen(pane)) pane.feedOutput(p, "\x1b[?1049l"); p.emitWrite(id, slot.line); p.emitWrite(id, "\r"); pardes.panes.terminal.noteCommand(pane, slot.line); @@ -1005,10 +1005,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"); - pardes.panes.terminal.resizeGrid(pane, 50, 20); + pane.resizeGrid(50, 20); sh.put(p, d ++ prompt); try testing.expectEqualStrings("exit 0\none\ntwo\n", sh.answered(p, node, h, into)); - pardes.panes.terminal.resizeGrid(pane, pane.cols, pane.rows); + pane.resizeGrid(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/src/panes.zig b/src/panes.zig index e1eb7e0e..ed2f3767 100644 --- a/src/panes.zig +++ b/src/panes.zig @@ -331,7 +331,7 @@ pub const Pane = struct { sized_by: u8 = 0, /// A terminal shown in a view shorter than it (one that does not size /// it): the rows its top is passed over by, so its cursor stays in - /// sight (terminal.panFor); 0 everywhere else. + /// sight (Pane.panFor); 0 everywhere else. pan: u16 = 0, /// The view whose step a `.name` prompt is (tagline.draftName): only /// that view's focus leaving the pane drops it. @@ -555,7 +555,7 @@ 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(terminal.gridOffset(pane) + pane.pan); + return pane.surfRow(@as(i32, @intCast(Term.grid(pane.terminal).offset)) + pane.pan); } pub fn wrapAt(pane: *Pane, vr: i32) struct { line: i32, at: i32, pad: i32 = 0 } { @@ -592,8 +592,10 @@ pub const Pane = struct { } } else if (pane.addon == null) { // the vt scrolls in SHELL rows; convert through the edit buffer - const off = terminal.gridOffset(pane); - terminal.scrollGrid(pane, pane.gridRow(pane.surfRow(off) + delta) - off); + if (tape.viewOnly("scroll a terminal")) return; + const state = pane.terminal orelse return; + const off: i32 = @intCast(Term.grid(state).offset); + Term.scroll(state, pane.gridRow(pane.surfRow(off) + delta) - off); } } @@ -674,13 +676,301 @@ pub const Pane = struct { pane.body.cur_row = pane.scroll(); pane.body.cur_col = 0; } else { - const cur = terminal.gridCursor(pane); - pane.body.cur_row = pane.surfRow(@as(i32, cur.y) + terminal.gridOffset(pane)); - pane.body.cur_col = @intCast(cur.x); + 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_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. + 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; + if (tape.authorityOnly("a terminal's output")) return; + const has_positions = pane.ovl != null or pane.body.cur_pinned or pane.body.vsel.active or + pane.body.nsel > 0 or pane.body.last_edit != null or pane.look_at != null or + pane.body.ed_undo_len > 0 or pane.body.ed_redo_len > 0 or pane.pointerRowCount() > 0; + // A replica's emulator is what the authority's deltas make it; what + // pardes keeps over it moves as the authority's feed told it. + if (tape.screenReplica()) { + if (has_positions and pane.followRows(state, bytes)) if (paneIdOf(p, pane)) |id| p.setMessage(id, positions_lost); + return; + } + // Sticky bottom, as every other terminal does it: output drags the + // viewport down only when the viewport was already on the last row, + // so a reader scrolled back into the scrollback stays where they + // 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); + if (!has_positions) { + _ = Term.feed(state, bytes, &.{}, &.{}, &.{}); + } else if (pane.followRows(state, bytes)) if (paneIdOf(p, pane)) |id| p.setMessage(id, positions_lost); + p.shell_rows.markStale(pane); + if (pane.body.mode == .tty and at_bottom) pane.followOutput(); + } + + /// 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 { + const on_replica = tape.screenReplica(); + const Group = struct { overlay: ?*Text.EditBuffer, cursor: *i32, selection: *Text.CharSel }; + var groups: [Text.history_max * 2 + 1]Group = undefined; + groups[0] = .{ + .overlay = if (pane.ovl) |*overlay| overlay else null, + .cursor = &pane.body.cur_row, + .selection = &pane.body.vsel, + }; + var ngroups: usize = 1; + for ([_][]Text.Snapshot{ pane.body.ed_undo[0..pane.body.ed_undo_len], pane.body.ed_redo[0..pane.body.ed_redo_len] }) |history| { + for (history) |*snapshot| { + groups[ngroups] = .{ + .overlay = if (snapshot.ovl) |*overlay| overlay else null, + .cursor = &snapshot.cur_row, + .selection = &snapshot.vsel, + }; + ngroups += 1; + } + } + // A position on a row of an edit copy's text stays on it (its line + // of the copy, `edit_row`); one below the copy is tracked on the + // shell row it stands for. + const Position = struct { target: *i32, overlay: ?*Text.EditBuffer, edit_row: ?i32 = null, grid: i32 = -1 }; + const position = struct { + fn of(target: *i32, overlay: ?*Text.EditBuffer) Position { + var grid = target.*; + if (overlay) |edit| { + const lines: i32 = @intCast(modal.lineCount(edit.text)); + if (grid >= edit.row and grid < edit.row +| lines) + return .{ .target = target, .overlay = edit, .edit_row = grid - edit.row }; + if (grid > edit.row) grid = grid -| lines +| edit.rows; + } + return .{ .target = target, .overlay = overlay, .grid = grid }; + } + }.of; + var spans: [groups.len]*Text.EditBuffer = undefined; + var nspans: usize = 0; + var positions: [groups.len * 2 + Text.max_selections * 2 + 4]Position = undefined; + var npositions: usize = 0; + for (groups[0..ngroups]) |group| { + if (group.overlay) |overlay| { + spans[nspans] = overlay; + nspans += 1; + } + positions[npositions] = position(group.cursor, group.overlay); + npositions += 1; + if (group.selection.active) { + positions[npositions] = position(&group.selection.row, group.overlay); + npositions += 1; + } + } + const overlay = groups[0].overlay; + // Where the live pane's own selections sit in `positions`: one whose + // row the program erased goes (below), as the edited copy does. + const vsel_at: ?usize = if (pane.body.vsel.active) 1 else null; + const sels_at = npositions; + var extra: [Text.max_selections * 2 + 2]*i32 = undefined; + var nextra: usize = 0; + for (pane.body.sels[0..pane.body.nsel]) |*selection| { + extra[nextra] = &selection.row; + extra[nextra + 1] = &selection.arow; + nextra += 2; + } + if (pane.body.last_edit) |*at| { + extra[nextra] = &at.row; + nextra += 1; + } + if (pane.look_at) |*at| { + extra[nextra] = &at.row; + nextra += 1; + } + for (extra[0..nextra]) |target| { + positions[npositions] = position(target, overlay); + npositions += 1; + } + var failed = false; + const pointer_positions = pane.gpa.alloc(Position, pane.pointerRowCount()) catch null; + defer if (pointer_positions) |held| pane.gpa.free(held); + if (pointer_positions) |held| { + var index: usize = 0; + for (pane.sel) |gesture| if (pane.pointerSelection(gesture)) |rows| { + for (rows) |*row| { + held[index] = position(&row.row, if (row.raw_terminal) null else overlay); + index += 1; + } + }; + } else failed = true; + const pointers: []Position = pointer_positions orelse &.{}; + // The rows to track, in the order told: each copy's first and last + // row, then the positions, then the pointer's rows. On the stack, + // as the local path never allocated here but for the pointer's rows. + const n = 2 * nspans + npositions + pointers.len; + var track_buf: [512]i32 = undefined; + 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); + 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); + 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); + 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| { + track[k] = row; + k += 1; + }; + for ([_][]Position{ positions[0..npositions], pointers }) |batch| for (batch) |at| { + track[k] = at.grid; + k += 1; + }; + // A replica's emulator is fed by its authority's deltas: it is told + // what the authority's feed told. + const fed: Term.Told = if (on_replica) told: { + @memset(rows_after, 0); + @memset(erased_after, false); + break :told .{ .rows = rows_after, .erased = erased_after, .cleared = false, .alive = false, .failed = false }; + } else Term.feed(state, bytes, track, rows_after, erased_after); + const 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; + const at_position = 2 * nspans; + const at_pointer = at_position + npositions; + var moved = false; + var pointer_rows_lost = !after.alive or pointer_positions == null; + for (0..pointers.len) |i| if (after.erased[at_pointer + i]) { + pointer_rows_lost = true; + }; + // The program cleared the screen, or the rows the live copy stood on + // are gone (pruned, a reset): the copy goes with them, as what the + // program drew next. Kept, the emulator would move its rows to the + // top of what is left, over the program's new text. + var copy_lost = after.cleared or !after.alive; + for (spans[0..nspans], 0..) |span, i| { + if (span == overlay and after.erased[2 * i]) copy_lost = true; + const start = after.rows[2 * i]; + const rows = @max(1, after.rows[2 * i + 1] -| start +| 1); + moved = moved or start != span.row or rows != span.rows; + span.row = start; + span.rows = rows; + } + // The rule above for the copy holds for the selections: one whose + // row is gone (ED 3 erased its history row) goes too, rather than + // being clamped to the top. + const erased = after.erased[at_position..]; + const vsel_lost = if (vsel_at) |i| + erased[i] or (copy_lost and positions[i].edit_row != null) + else + false; + var sels_keep: [Text.max_selections]bool = undefined; + for (0..pane.body.nsel) |i| sels_keep[i] = !(erased[sels_at + 2 * i] or erased[sels_at + 2 * i + 1]); + for ([_][]Position{ positions[0..npositions], pointers }, [_]usize{ at_position, at_pointer }) |batch, first| for (batch, first..) |at, i| { + var row = after.rows[i]; + if (at.overlay) |edit| { + if (at.edit_row) |relative| { + row = edit.row +| relative; + } else if (row > edit.row) { + row = if (row < edit.row +| edit.rows) + edit.row + else + row -| edit.rows +| @as(i32, @intCast(modal.lineCount(edit.text))); + } + } + moved = moved or row != at.target.*; + at.target.* = row; + }; + if (pointer_rows_lost) for (0..pane.sel.len) |button| { + pane.clearPointerSelection(button); + pane.sel[button].state = .none; + }; + if (vsel_lost) { + pane.body.vsel.active = false; + moved = true; + } + if (pane.body.nsel > 0) { + var kept: u16 = 0; + for (0..pane.body.nsel) |i| if (sels_keep[i]) { + pane.body.sels[kept] = pane.body.sels[i]; + kept += 1; + }; + if (kept != pane.body.nsel) { + moved = true; + if (kept == 0) pane.body.dropSels() else pane.body.nsel = kept; + } + } + if (copy_lost) if (pane.ovl) |copy| { + pane.gpa.free(copy.text); + pane.ovl = null; + moved = true; + }; + if (moved) pane.nsel_snap = 0; // Saved regex-preview offsets name the old flat text. + return failed; + } + + fn keepTold(t: Term.Told) Term.Told { + return t; + } + + fn feedLost(state: *Term.State, bytes: []const u8) bool { + if (!tape.screenReplica()) _ = Term.feed(state, bytes, &.{}, &.{}, &.{}); + return true; + } + + fn pointerRowCount(pane: *const Pane) usize { + var count: usize = 0; + for (pane.sel) |gesture| if (pane.pointerSelection(gesture)) |rows| { + count += rows.len; + }; + return count; + } + + /// Its terminal's view snapped back onto live output. + pub fn followOutput(pane: *Pane) void { + if (tape.viewOnly("follow a terminal")) return; + const state = pane.terminal orelse return; + Term.follow(state); + } + + /// Its terminal's grid reflowed to `cols` by `rows`: on a screen-state + /// replica by its authority (the next delta says), on such an authority + /// once the step's unit is out (`resizeDeferred`). + pub fn resizeGrid(pane: *Pane, cols: u16, rows: u16) void { + if (tape.authorityOnly("resize a terminal")) return; + const state = pane.terminal orelse return; + if (cols != pane.cols) for (0..pane.sel.len) |button| { + pane.clearPointerSelection(button); + pane.sel[button].state = .none; + }; + if (tape.screenReplica()) return; + // A client typing at another size than the last typist's read + // history rows its replay held as holes, and the rows came + // renumbered (2026-10-30): the authority's waits for the unit. + Term.resize(state, cols, rows, tape.screenAuthority()); + } + + /// The rows its terminal's top is passed over by in a view whose rect + /// `r` is shorter than it, one that does not size it (Pardes.sizes): as + /// many as keep its cursor's row in sight, as tmux pans a bigger window + /// in a smaller client. 0 in the view that sizes it, and in one tall + /// enough. + pub fn panFor(pane: *const Pane, p: *const Pardes, r: pardes.Rect) u16 { + if (pane.sized_by == p.live or pane.collapsed or !pane.isTerminal()) return 0; + const shown = r.h -| pane.tag_rows; + 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 row = grid.total - grid.len + grid.cursor_y; + const at: usize = if (row < grid.offset) 0 else @min(row - grid.offset, pane.rows - 1); + return @intCast(@min(pane.rows - shown, (at + 1) -| shown)); + } + /// `run ` or `exit ` in the log. /// The whole line, one record as `msg` carries its text: its control /// characters, a newline too, become spaces (events.pushLog). A new pane is @@ -708,8 +998,8 @@ pub const Pane = struct { var buf: [16]u8 = undefined; const code = if (status) |n| std.fmt.bufPrint(&buf, "{d}", .{n}) catch unreachable else "?"; // an exit status fits 16 var said: pardes.Kind.Buf(32) = .{}; - const lead = if (panes.terminal.gridCursor(pane).x != 0) "\r\n" else ""; - panes.terminal.feedOutput(p, pane, said.print("{s}exit {s}\r\n", .{ lead, code })); + const lead = if (Term.grid(pane.terminal).cursor_x != 0) "\r\n" else ""; + pane.feedOutput(p, said.print("{s}exit {s}\r\n", .{ lead, code })); pane.noteRun(p, "exit", code); p.needs_frame = true; } @@ -734,6 +1024,17 @@ pub const terminal = @import("term/terminal.zig"); pub const Term = @import("Term.zig"); +/// What a pane says when a position kept over its terminal's rows could +/// not follow the output (no memory for its pin), so it was reset. +pub const positions_lost = "terminal edit position reset: out of memory"; + +/// The sizes steps gave terminals (`Pane.resizeGrid`), made: between +/// units, on an authority with screen-state replicas (replica.Peers.unit). +pub fn resizeDeferred(p: *Pardes) void { + for (p.panes) |slot| if (slot) |pane| if (pane.terminal) |state| if (Term.resizeDeferred(state)) + p.shell_rows.markStale(pane); +} + /// A pane with nothing in it yet, `cols` by `rows`: what a file, a /// directory, a kind's pane or a terminal is made from. pub fn createDoc(gpa: std.mem.Allocator, cols: u16, rows: u16) !*Pane { diff --git a/src/replica.zig b/src/replica.zig index 635ada75..9a2c80a7 100644 --- a/src/replica.zig +++ b/src/replica.zig @@ -673,7 +673,7 @@ pub const Replica = struct { /// Its terminals' screen state, as the authority's deltas made it. screens: [pardes.MAX_PANES]?ScreenOf = @splat(null), - /// Each terminal's view (`terminal.viewOf`) as the copy was taken, or + /// Each terminal's view (`Term.grid`'s view) as the copy was taken, or /// as the last delta since set it: the copy holds no emulator, and a /// speculation may move a view, so a rollback puts these back. views: [pardes.MAX_PANES]View = @splat(.{}), @@ -1090,12 +1090,12 @@ pub const Replica = struct { fn keepViews(r: *Replica) void { if (!r.t.screen_state) return; - for (r.core().panes, &r.views) |slot, *v| v.* = .{ .at = if (slot) |pane| terminal.viewOf(pane) else null }; + for (r.core().panes, &r.views) |slot, *v| v.* = .{ .at = if (slot) |pane| if (pane.terminal) |state| pardes.Term.grid(state).view else null else null }; } fn putViews(r: *Replica, after: usize) void { if (!r.t.screen_state) return; - for (r.core().panes, r.views) |slot, v| if (v.after == after) if (slot) |pane| if (pane.terminal != null) terminal.viewTo(pane, v.at); + for (r.core().panes, r.views) |slot, v| if (v.after == after) if (slot) |pane| if (pane.terminal) |state| pardes.Term.viewTo(state, v.at); } /// Whether its core loaded from the dump is the session as it was @@ -1182,7 +1182,7 @@ pub const Replica = struct { c.shell_rows.markStale(pane); // Its view is the authority's now: a rollback puts it back // here, and what was applied over a terminal goes on top. - if (r.copy.held) r.views[m.pane] = .{ .at = terminal.viewOf(pane), .after = r.since.items.len }; + if (r.copy.held) r.views[m.pane] = .{ .at = if (pane.terminal) |held| pardes.Term.grid(held).view else null, .after = r.since.items.len }; r.overTerminals(); var seq: [4]u8 = undefined; std.mem.writeInt(u32, &seq, applied.seq, .little); @@ -1903,7 +1903,7 @@ pub const Peers = struct { for (ps.list) |slot| if (slot) |peer| peer.send(&.{ &head, &ps.head, bytes }); ps.t.buf.clearRetainingCapacity(); // The sizes its steps gave terminals, now: the next flush says so. - if (ps.t.core) |core| terminal.resizeDeferred(core); + if (ps.t.core) |core| pardes.panes.resizeDeferred(core); } /// After each of the session's pumps: its unit sent, the clients that @@ -2219,7 +2219,7 @@ pub const Peers = struct { fn stop(ps: *Peers, core: *Pardes) void { if (!ps.recording) return; - terminal.resizeDeferred(core); + pardes.panes.resizeDeferred(core); ps.screens.deinit(core); if (core.host.vtable == &ps.t.vtable) core.host = ps.t.real; tape.on = null; @@ -3093,7 +3093,7 @@ fn key(r: *Replica, cp: u21, sent: *std.ArrayListUnmanaged([]u8)) !void { /// What the session sends a peer: its terminals' changes (`.flush`), or, /// around a step's unit (Peers.input), the rows the step read that the /// peer lacks (`.fill`), after which the caller gives terminals the sizes -/// the step gave them (`terminal.resizeDeferred`), then the unit. +/// the step gave them (`panes.resizeDeferred`), then the unit. fn deliver(a: *Authority, screens: *Screens, peer: u16, r: *Replica, comptime what: enum { flush, fill }) !void { const gpa = std.testing.allocator; var msgs: std.ArrayListUnmanaged([]u8) = .empty; @@ -3583,7 +3583,7 @@ test "a terminal sized again by a client's key: the step reads the grid it had, const u = try std.testing.allocator.dupe(u8, try au.take(msg)); defer std.testing.allocator.free(u); try deliver(au, sc, pe, rr, .fill); - terminal.resizeDeferred(au.core); + pardes.panes.resizeDeferred(au.core); rr.confirm(u); rr.settle(); } @@ -3609,7 +3609,7 @@ test "a terminal sized again by a client's key: the step reads the grid it had, const back = try gpa.dupe(u8, try a.unit(0, a.seq)); defer gpa.free(back); try deliver(a, &screens, peer, r, .fill); - terminal.resizeDeferred(a.core); + pardes.panes.resizeDeferred(a.core); r.confirm(back); r.settle(); try deliver(a, &screens, peer, r, .flush); @@ -3656,7 +3656,7 @@ test "pardes's own keys over a terminal's history apply at once: its view moves try std.testing.expectEqual(@as(u32, 0), r.stats.stopped); try std.testing.expectEqual(sent.items.len, r.applied); const here = r.core().panes[shell].?; - try std.testing.expect(terminal.viewOf(here) != null); + try std.testing.expect(pardes.Term.grid(here.terminal).view != null); // The shell prints while they wait: its unit, then its delta, which // sets the view the authority's (at the bottom still): what was applied // goes on top of it again. @@ -3666,7 +3666,7 @@ test "pardes's own keys over a terminal's history apply at once: its view moves try deliver(a, &screens, peer, r, .flush); r.settle(); try std.testing.expectEqual(sent.items.len, r.applied); - try std.testing.expect(terminal.viewOf(r.core().panes[shell].?) != null); + try std.testing.expect(pardes.Term.grid(r.core().panes[shell].?.terminal).view != null); // The authority takes them in order, the terminal sent before each and // the rows its step read after, as the session's loop does. for (sent.items) |m| { @@ -3684,19 +3684,19 @@ test "pardes's own keys over a terminal's history apply at once: its view moves try std.testing.expect(r.diverged == null and r.quiet()); try std.testing.expectEqual(@as(u32, 0), r.stats.mispredicted); try std.testing.expectEqual(digestOf(a), r.digest()); - try std.testing.expect(terminal.viewOf(a.core.panes[shell].?) != null); - try std.testing.expectEqual(terminal.viewOf(a.core.panes[shell].?), terminal.viewOf(r.core().panes[shell].?)); + try std.testing.expect(pardes.Term.grid(a.core.panes[shell].?.terminal).view != null); + try std.testing.expectEqual(pardes.Term.grid(a.core.panes[shell].?.terminal).view, pardes.Term.grid(r.core().panes[shell].?.terminal).view); // A rollback with nothing confirmed on top puts the view back: one more // key up, and another's unit first. try sent.append(gpa, try gpa.dupe(u8, try r.input(.{ .key = .{ .cp = 'u', .ctrl = true } }))); - const before = terminal.viewOf(a.core.panes[shell].?); - try std.testing.expect(terminal.viewOf(r.core().panes[shell].?).? < before.?); + const before = pardes.Term.grid(a.core.panes[shell].?.terminal).view; + try std.testing.expect(pardes.Term.grid(r.core().panes[shell].?.terminal).view.? < before.?); r.confirm(try a.local(.{ .focus = false })); r.settle(); const last = try gpa.dupe(u8, try a.take(sent.items[sent.items.len - 1])); defer gpa.free(last); r.toConfirmed(); - try std.testing.expectEqual(before, terminal.viewOf(r.core().panes[shell].?)); + try std.testing.expectEqual(before, pardes.Term.grid(r.core().panes[shell].?.terminal).view); r.dirty = true; r.settle(); try deliver(a, &screens, peer, r, .fill); @@ -3707,7 +3707,7 @@ test "pardes's own keys over a terminal's history apply at once: its view moves if (r.diverged) |why| std.debug.print("diverged: {s}\n", .{why}); try std.testing.expect(r.diverged == null and r.quiet()); try std.testing.expectEqual(digestOf(a), r.digest()); - try std.testing.expectEqual(terminal.viewOf(a.core.panes[shell].?), terminal.viewOf(r.core().panes[shell].?)); + try std.testing.expectEqual(pardes.Term.grid(a.core.panes[shell].?.terminal).view, pardes.Term.grid(r.core().panes[shell].?.terminal).view); } test "a replica joined from the session's dump replays the units after it" { diff --git a/src/tape.zig b/src/tape.zig index 608ad6ff..998643f2 100644 --- a/src/tape.zig +++ b/src/tape.zig @@ -136,7 +136,7 @@ pub const results = .{ ?std.Io.File.Kind, ?pardes.filesystem.Resolved, pardes.filesystem.OsReadWrite, anyerror!pardes.filesystem.OsStat, anyerror![]const u8, anyerror![]u8, - anyerror!void, terminal.Told, + anyerror!void, pardes.Term.Told, ?pardes.ctlfs.pty.Printed, @typeInfo(@TypeOf(terminal.greeting)).@"fn".return_type.?, []pardes.Stream.Batch, // What only the authority holds (`authority`): a closed pane's record, @@ -1070,6 +1070,19 @@ pub fn authorityOnly(comptime why: []const u8) bool { return true; } +/// A speculation that moves a terminal's view: a screen-state replica's +/// may (its rollback puts the view back, replica.zig `views`, and a delta +/// sets it), any other stops (`authorityOnly`). +pub fn viewOnly(comptime why: []const u8) bool { + if (!speculating()) return false; + if (screenState()) { + touchTerminal(); + return false; + } + poison(why); + return true; +} + /// A speculation read a terminal's rows or moved its view (`Tape.touched`). pub fn touchTerminal() void { if (on) |t| if (t.speculating) { diff --git a/src/term/echo.zig b/src/term/echo.zig index 4f27a08f..d069fe36 100644 --- a/src/term/echo.zig +++ b/src/term/echo.zig @@ -236,7 +236,8 @@ pub const Echo = struct { fn predict(e: *Echo, pane: *Pane, kind: Kind, seq: u32) bool { const state = pane.terminal orelse return false; const vt = &state.vt; - if (vt.screens.active_key != .primary or !terminal.atBottom(pane) or !vt.modes.get(.cursor_visible)) return false; + const sb = vt.screens.active.pages.scrollbar(); + if (vt.screens.active_key != .primary or sb.offset + sb.len < sb.total or !vt.modes.get(.cursor_visible)) return false; const top = e.tops[e.pane]; const screen = vt.screens.active; const cur: Cursor = e.cursor orelse .{ .x = @intCast(screen.cursor.x), .row = top + screen.cursor.y, .seq = 0 }; @@ -642,7 +643,7 @@ const Rig = struct { const s = try c.render(arena.allocator()); const pane = c.panes[g.shell].?; const body = s.region(.body, g.shell).?.rect; - const y = body.y + terminal.gridCursor(pane).y; + const y = body.y + pardes.Term.grid(pane.terminal).cursor_y; const cell = s.at(body.x + x, y); return .{ .cp = cell.text[0], .ul = cell.style.ul != .off, .cursor = if (s.cursor) |cur| if (cur.y == y) cur.x - body.x else null else null }; } @@ -704,7 +705,7 @@ test "a password prompt shows nothing typed, and a full-screen program is not pr try g.prints(prompt ++ "sudo ls\r\n\x1b]133;C;aid=pardes\x07[sudo] password: "); var arena: std.heap.ArenaAllocator = .init(testing.allocator); defer arena.deinit(); - const x = terminal.gridCursor(g.r.core().panes[g.shell].?).x; + const x = pardes.Term.grid(g.r.core().panes[g.shell].?.terminal).cursor_x; const k = try g.key(.{ .cp = 'h', .text = "h" }); // Predicted, and not drawn: nothing has confirmed an echo here. try testing.expectEqual(@as(u32, 1), g.r.echo.stats.predicted); diff --git a/src/term/terminal.zig b/src/term/terminal.zig index 9472cfe1..50fca2d0 100644 --- a/src/term/terminal.zig +++ b/src/term/terminal.zig @@ -11,6 +11,7 @@ const tracy = @import("../tracy.zig"); const tagline = @import("../tagline.zig"); const Key = pardes.Key; const Pane = panes.Pane; +const Term = @import("../Term.zig"); const EditText = panes.EditText; const File = panes.File; @@ -510,55 +511,21 @@ pub fn terminalIo() std.Io { return std.Io.Threaded.global_single_threaded.io(); } -/// The three numbers ghostty's scrollbar reports; all zero without an emulator. -pub const Scrollbar = struct { total: usize = 0, offset: usize = 0, len: usize = 0 }; - -pub fn scrollbar(pane: *const Pane) Scrollbar { - const state = pane.terminal orelse return .{}; - const sb = state.vt.screens.active.pages.scrollbar(); - return .{ .total = sb.total, .offset = sb.offset, .len = sb.len }; -} - -/// The emulator's viewport offset, in SHELL rows: the top of what it shows. -pub fn gridOffset(pane: *const Pane) i32 { - return @intCast(scrollbar(pane).offset); -} - -/// Where the emulator itself puts the cursor, in active-area cells — the origin -/// without one, which is where an empty pane's cursor belongs anyway. -pub const GridCursor = struct { x: u16 = 0, y: u16 = 0 }; - -pub fn gridCursor(pane: *const Pane) GridCursor { - const state = pane.terminal orelse return .{}; - const cur = state.vt.screens.active.cursor; - return .{ .x = @intCast(cur.x), .y = @intCast(cur.y) }; -} - -pub fn visibleCursor(pane: *const Pane) ?GridCursor { - const state = pane.terminal orelse return null; - if (!state.vt.modes.get(.cursor_visible)) return null; - const cur = state.vt.screens.active.cursor; - const sb = scrollbar(pane); - const row = sb.total - sb.len + cur.y; - if (row < sb.offset + pane.pan or row - sb.offset >= sb.len) return null; - return .{ .x = @intCast(cur.x), .y = @intCast(row - sb.offset - pane.pan) }; -} - -/// The rows terminal `pane`'s top is passed over by in a view whose rect -/// `r` is shorter than it, one that does not size it (Pardes.sizes): as -/// many as keep its cursor's row in sight, as tmux pans a bigger window in -/// a smaller client. 0 in the view that sizes it, and in one tall enough. -pub fn panFor(p: *const Pardes, pane: *const Pane, r: pardes.Rect) u16 { - if (pane.sized_by == p.live or pane.collapsed or !pane.isTerminal()) return 0; - const shown = r.h -| pane.tag_rows; - if (shown == 0 or shown >= pane.rows) return 0; - const state = pane.terminal orelse return 0; - const sb = scrollbar(pane); - // The cursor's row in the viewport; past its end (scrolled back), its - // last row. - const row = sb.total - sb.len + state.vt.screens.active.cursor.y; - const at: usize = if (row < sb.offset) 0 else @min(row - sb.offset, pane.rows - 1); - return @intCast(@min(pane.rows - shown, (at + 1) -| shown)); +/// Where the view and the cursor are (`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, + }; } /// What pardes made of a terminal's stream that its emulator does not hold @@ -596,72 +563,30 @@ pub fn takeMarks(state: *State, bytes: []const u8) void { const authorityOnly = pardes.tape.authorityOnly; -/// A speculation that moves a terminal's view: a screen-state replica's -/// may (its rollback puts the view back, replica.zig `views`, and a delta -/// sets it), any other stops (`authorityOnly`). -fn viewOnly(comptime why: []const u8) bool { - if (!pardes.tape.speculating()) return false; - if (pardes.tape.screenState()) { - pardes.tape.touchTerminal(); - return false; - } - pardes.tape.poison(why); - return true; -} - -/// Where a terminal's view is: its top row counted from the top of its -/// history, or null following its output (a replica's rollback copy, -/// which holds no emulator, keeps it so). -pub fn viewOf(pane: *const Pane) ?usize { - const state = pane.terminal orelse return null; - const pages = &state.vt.screens.active.pages; - if (pages.viewport == .active) return null; - return pages.scrollbar().offset; -} - -pub fn viewTo(pane: *Pane, at: ?usize) void { - const state = pane.terminal orelse return; +/// 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); } -/// Move the emulator's viewport by `delta` shell rows (negative scrolls back). -pub fn scrollGrid(pane: *Pane, delta: i32) void { - if (viewOnly("scroll a terminal")) return; - const state = pane.terminal orelse return; +/// Its view moved by `delta` rows (negative scrolls back). +pub fn scroll(state: *State, delta: i32) void { state.vt.screens.active.scroll(.{ .delta_row = delta }); state.changes +%= 1; } -/// Is the viewport already showing the last row of output? -pub fn atBottom(pane: *const Pane) bool { - const sb = scrollbar(pane); - return sb.offset + sb.len >= sb.total; -} - -/// Snap the viewport back onto live output. -pub fn followOutput(pane: *Pane) void { - if (viewOnly("follow a terminal")) return; - const state = pane.terminal orelse return; +/// Its view back onto the output. +pub fn follow(state: *State) void { const moved = state.vt.screens.active.pages.viewport != .active; state.vt.screens.active.scroll(.active); state.changes +%= @intFromBool(moved); } -/// Reflow the grid. A failed reflow keeps the grid it had rather than dropping -/// a scrollback; the next resize retries with the same numbers. -pub fn resizeGrid(pane: *Pane, cols: u16, rows: u16) void { - if (authorityOnly("resize a terminal")) return; - const state = pane.terminal orelse return; - if (cols != pane.cols) for (0..pane.sel.len) |button| { - pane.clearPointerSelection(button); - pane.sel[button].state = .none; - }; - // A replica's emulator is sized by its authority: the next delta says. - if (pardes.tape.screenReplica()) return; - // ...and the authority's once the step's unit is out (a client typing - // at another size than the last typist's read history rows its replay - // held as holes, and the rows came renumbered, 2026-10-30). - if (pardes.tape.screenAuthority()) { +/// Its grid reflowed to `cols` by `rows`, now or, `later`, when +/// `resizeDeferred` is called. A failed reflow keeps the grid it had +/// rather than dropping a scrollback; the next resize retries with the +/// same numbers. +pub fn resize(state: *State, cols: u16, rows: u16, later: bool) void { + if (later) { state.resize_to = .{ .cols = cols, .rows = rows }; return; } @@ -669,15 +594,30 @@ pub fn resizeGrid(pane: *Pane, cols: u16, rows: u16) void { state.vt.resize(state.gpa, .{ .cols = cols, .rows = rows }) catch {}; } -/// The sizes steps gave terminals (`resizeGrid`), made: between units, on an -/// authority with screen-state replicas (replica.Peers.unit). -pub fn resizeDeferred(p: *Pardes) void { - for (p.panes) |slot| if (slot) |pane| if (pane.terminal) |state| if (state.resize_to) |size| { - state.resize_to = null; - state.changes +%= 1; - p.shell_rows.markStale(pane); - state.vt.resize(state.gpa, .{ .cols = size.cols, .rows = size.rows }) catch {}; - }; +/// The size `resize` left for later, made; whether there was one. +pub fn resizeDeferred(state: *State) bool { + const size = state.resize_to orelse return false; + state.resize_to = null; + state.changes +%= 1; + state.vt.resize(state.gpa, .{ .cols = size.cols, .rows = size.rows }) catch {}; + return true; +} + +/// The emulator's size in pixels follows the core's cells: kitty graphics +/// placements are sized by it, and CSI 14/16 t report it. +pub fn cellPixels(state: *State, w: u32, h: u32) void { + if (comptime !images_enabled) return; + const vt = &state.vt; + vt.width_px = @as(u32, vt.cols) * w; + vt.height_px = @as(u32, vt.rows) * h; +} + +/// What it answered its program (a cursor report, its attributes) since +/// the last call, to be written to its pty behind whatever is queued +/// there; valid until it is fed again. +pub fn replies(state: *State) []const u8 { + defer state.reply_len = 0; + return state.reply[0..state.reply_len]; } /// DECSET 2004: the program wants its pastes bracketed. @@ -908,48 +848,9 @@ fn ingest(state: *State, bytes: []const u8) void { state.changes +%= 1; } -/// What a pane says when a position kept over its terminal's rows could -/// not follow the output (no memory for its pin), so it was reset. -const positions_lost = "terminal edit position reset: out of memory"; - -/// 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. -pub fn feedOutput(p: *Pardes, pane: *Pane, bytes: []const u8) void { - // There are no pty reads at all without an emulator to parse them into. - if (pane.terminal == null) return; - if (authorityOnly("a terminal's output")) return; - 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 pointerRowCount(pane) > 0; - // A replica's emulator is what the authority's deltas make it; what - // pardes keeps over it moves as the authority's ingest told it. - if (pardes.tape.screenReplica()) { - if (has_positions and ingestWithPositions(pane, bytes)) if (panes.paneIdOf(p, pane)) |id| p.setMessage(id, positions_lost); - return; - } - // Sticky bottom, as every other terminal does it: output drags the - // viewport down only when the viewport was already on the last row, so - // a reader scrolled back into the scrollback stays where they scrolled. - const at_bottom = atBottom(pane); - syncPixels(p, pane); - if (!has_positions) { - ingest(pane.terminal.?, bytes); - } else if (ingestWithPositions(pane, bytes)) if (panes.paneIdOf(p, pane)) |id| p.setMessage(id, positions_lost); - p.shell_rows.markStale(pane); - if (pane.body.mode == .tty and at_bottom) followOutput(pane); -} - const RowPin = struct { pin: ?*ghostty_vt.Pin = null, offset: i32 = 0 }; -const PositionPin = struct { - target: *i32, - row: RowPin, - overlay: ?*EditBuffer, - edit_row: ?i32 = null, -}; -fn trackRow(maybe_pages: ?*ghostty_vt.PageList, row: i32, failed: *bool) RowPin { - // A screen-state replica's: told by the tape, not its emulator. - const pages = maybe_pages orelse return .{ .offset = row }; +fn trackRow(pages: *ghostty_vt.PageList, row: i32, failed: *bool) RowPin { if (row < 0) return .{ .offset = row }; const bounded: usize = @min(@as(usize, @intCast(row)), pages.total_rows - 1); var left = pages.total_rows - 1 - bounded; @@ -979,236 +880,43 @@ fn pinnedRow(pages: ?*ghostty_vt.PageList, row: RowPin) i32 { return 0; } -fn trackPosition(pages: ?*ghostty_vt.PageList, target: *i32, overlay: ?*EditBuffer, failed: *bool) PositionPin { - var grid = target.*; - if (overlay) |edit| { - const lines: i32 = @intCast(modal.lineCount(edit.text)); - if (grid >= edit.row and grid < edit.row +| lines) - return .{ .target = target, .row = .{}, .overlay = edit, .edit_row = grid - edit.row }; - if (grid > edit.row) grid = grid -| lines +| edit.rows; +/// 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, track: []const i32, rows: []i32, erased: []bool) Term.Told { + if (track.len == 0) { + ingest(state, bytes); + return .{ .rows = rows[0..0], .erased = erased[0..0], .cleared = false, .alive = true, .failed = false }; } - return .{ .target = target, .row = trackRow(pages, grid, failed), .overlay = overlay }; -} - -fn pointerRowCount(pane: *const Pane) usize { - var count: usize = 0; - for (pane.sel) |gesture| if (pane.pointerSelection(gesture)) |rows| { - count += rows.len; - }; - return count; -} - -/// What an ingest told the positions over it (`ingestWithPositions`): each -/// tracked row where it is after it (the spans' starts and ends, the -/// positions, the pointer rows, in that order) and whether the program -/// erased it, whether the screen was cleared, whether its pages lived and -/// whether a pin could not be made. Taped: a screen-state replica, which -/// ingests nothing, is told the authority's. -pub const Told = struct { rows: []const i32, erased: []const bool, cleared: bool, alive: bool, failed: bool }; - -fn told(t: Told) Told { - return t; -} - -/// `ingest`, with every position kept over the rows (the edit copy, the -/// cursors and selections, their undo, the pointer's rows) moved as the -/// rows move. True when one could not be kept (no memory for its pin). -fn ingestWithPositions(pane: *Pane, bytes: []const u8) bool { - const screens = &pane.terminal.?.vt.screens; + const screens = &state.vt.screens; const key = screens.active_key; const generation = screens.generation(key); - const replica = pardes.tape.screenReplica(); - const pages: ?*ghostty_vt.PageList = if (replica) null else &screens.active.pages; - const Group = struct { overlay: ?*EditBuffer, cursor: *i32, selection: *panes.Text.CharSel }; - var groups: [history_max * 2 + 1]Group = undefined; - groups[0] = .{ - .overlay = if (pane.ovl) |*overlay| overlay else null, - .cursor = &pane.body.cur_row, - .selection = &pane.body.vsel, - }; - var ngroups: usize = 1; - for ([_][]Snapshot{ pane.body.ed_undo[0..pane.body.ed_undo_len], pane.body.ed_redo[0..pane.body.ed_redo_len] }) |history| { - for (history) |*snapshot| { - groups[ngroups] = .{ - .overlay = if (snapshot.ovl) |*overlay| overlay else null, - .cursor = &snapshot.cur_row, - .selection = &snapshot.vsel, - }; - ngroups += 1; - } - } - const Span = struct { overlay: *EditBuffer, start: RowPin, end: RowPin }; - var spans: [groups.len]Span = undefined; - var nspans: usize = 0; - var positions: [groups.len * 2 + panes.Text.max_selections * 2 + 4]PositionPin = undefined; - var npositions: usize = 0; + const pages = &screens.active.pages; var failed = false; - for (groups[0..ngroups]) |group| { - if (group.overlay) |overlay| { - spans[nspans] = .{ - .overlay = overlay, - .start = trackRow(pages, overlay.row, &failed), - .end = trackRow(pages, overlay.row +| (overlay.rows - 1), &failed), - }; - nspans += 1; - } - positions[npositions] = trackPosition(pages, group.cursor, group.overlay, &failed); - npositions += 1; - if (group.selection.active) { - positions[npositions] = trackPosition(pages, &group.selection.row, group.overlay, &failed); - npositions += 1; - } - } - const overlay = groups[0].overlay; - // Where the live pane's own selections sit in `positions`: one whose - // row the program erased goes (below), as the edited copy does. - const vsel_at: ?usize = if (pane.body.vsel.active) 1 else null; - const sels_at = npositions; - var extra: [panes.Text.max_selections * 2 + 2]*i32 = undefined; - var nextra: usize = 0; - for (pane.body.sels[0..pane.body.nsel]) |*selection| { - extra[nextra] = &selection.row; - extra[nextra + 1] = &selection.arow; - nextra += 2; - } - if (pane.body.last_edit) |*at| { - extra[nextra] = &at.row; - nextra += 1; - } - if (pane.look_at) |*at| { - extra[nextra] = &at.row; - nextra += 1; - } - for (extra[0..nextra]) |target| { - positions[npositions] = trackPosition(pages, target, overlay, &failed); - npositions += 1; - } - const pointer_positions = pane.gpa.alloc(PositionPin, pointerRowCount(pane)) catch null; - defer if (pointer_positions) |pins| pane.gpa.free(pins); - if (pointer_positions) |pins| { - var index: usize = 0; - for (pane.sel) |gesture| if (pane.pointerSelection(gesture)) |rows| { - for (rows) |*row| { - pins[index] = trackPosition(pages, &row.row, if (row.raw_terminal) null else overlay, &failed); - index += 1; - } - }; - } else failed = true; - var cleared = false; - var alive: ?*ghostty_vt.PageList = null; - if (!replica) { - // Whether the program cleared the screen (ED 2, a switch of - // screens); pardes reads the flag nowhere else. - pane.terminal.?.vt.flags.dirty.clear = false; - ingest(pane.terminal.?, bytes); - cleared = pane.terminal.?.vt.flags.dirty.clear; - // RIS can destroy the alternate screen and every pin it owned. - alive = if (screens.generation(key) == generation) pages else null; - } - const pointers: []PositionPin = pointer_positions orelse &.{}; - const n = 2 * nspans + npositions + pointers.len; - // On the stack, as the local path never allocated here but for the - // pointer's rows. - var rows_buf: [512]i32 = undefined; - var erased_buf: [512]bool = undefined; - const rows_after = if (n <= rows_buf.len) rows_buf[0..n] else pane.gpa.alloc(i32, n) catch return true; - 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 true; - defer if (n > erased_buf.len) pane.gpa.free(erased_after); - @memset(rows_after, 0); - @memset(erased_after, false); - if (!replica) { - var k: usize = 0; - for (spans[0..nspans]) |span| for ([_]RowPin{ span.start, span.end }) |rp| { - rows_after[k] = pinnedRow(alive, rp); - erased_after[k] = alive != null and rp.pin != null and rp.pin.?.garbage; - k += 1; - }; - for ([_][]PositionPin{ positions[0..npositions], pointers }) |batch| for (batch) |position| { - rows_after[k] = pinnedRow(alive, position.row); - erased_after[k] = alive != null and position.row.pin != null and position.row.pin.?.garbage; - k += 1; - }; - } - const after = pardes.tape.value(.positions, told, .{Told{ .rows = rows_after, .erased = erased_after, .cleared = cleared, .alive = alive != null, .failed = failed }}); - if (after.rows.len != n or after.erased.len != n) return false; // a replica its authority's states apart (diverged) - failed = after.failed; - const at_position = 2 * nspans; - const at_pointer = at_position + npositions; - var moved = false; - var pointer_rows_lost = !after.alive or pointer_positions == null; - for (0..pointers.len) |i| if (after.erased[at_pointer + i]) { - pointer_rows_lost = true; - }; - // The program cleared the screen, or the rows the live copy stood on are - // gone (pruned, a reset): the copy goes with them, as what the program - // drew next. Kept, ghostty would move its rows to the top of what is - // left, over the program's new text. - var copy_lost = after.cleared or !after.alive; - for (spans[0..nspans], 0..) |span, i| { - if (span.overlay == overlay and after.erased[2 * i]) copy_lost = true; - const start = after.rows[2 * i]; - const rows = @max(1, after.rows[2 * i + 1] -| start +| 1); - moved = moved or start != span.overlay.row or rows != span.overlay.rows; - span.overlay.row = start; - span.overlay.rows = rows; - if (alive) |owner| { - if (span.start.pin) |pin| owner.untrackPin(pin); - if (span.end.pin) |pin| owner.untrackPin(pin); - } - } - // The rule above for the copy holds for the selections: one whose row - // is gone (ED 3 erased its history row, which ghostty flags `garbage`) - // goes too, rather than being clamped to the top. - const erased = after.erased[at_position..]; - const vsel_lost = if (vsel_at) |i| - erased[i] or (copy_lost and positions[i].edit_row != null) - else - false; - var sels_keep: [panes.Text.max_selections]bool = undefined; - for (0..pane.body.nsel) |i| sels_keep[i] = !(erased[sels_at + 2 * i] or erased[sels_at + 2 * i + 1]); - for ([_][]PositionPin{ positions[0..npositions], pointers }, [_]usize{ at_position, at_pointer }) |batch, first| for (batch, first..) |position, k| { - var row = after.rows[k]; - if (position.overlay) |edit| { - if (position.edit_row) |relative| { - row = edit.row +| relative; - } else if (row > edit.row) { - row = if (row < edit.row +| edit.rows) - edit.row - else - row -| edit.rows +| @as(i32, @intCast(modal.lineCount(edit.text))); - } - } - moved = moved or row != position.target.*; - position.target.* = row; - if (alive) |owner| if (position.row.pin) |pin| owner.untrackPin(pin); - }; - if (pointer_rows_lost) for (0..pane.sel.len) |button| { - pane.clearPointerSelection(button); - pane.sel[button].state = .none; + var room: [512]RowPin = undefined; + const pins = if (track.len <= room.len) room[0..track.len] else state.gpa.alloc(RowPin, track.len) catch { + ingest(state, bytes); + @memcpy(rows[0..track.len], track); + @memset(erased[0..track.len], false); + return .{ .rows = rows[0..track.len], .erased = erased[0..track.len], .cleared = false, .alive = true, .failed = true }; }; - if (vsel_lost) { - pane.body.vsel.active = false; - moved = true; - } - if (pane.body.nsel > 0) { - var kept: u16 = 0; - for (0..pane.body.nsel) |i| if (sels_keep[i]) { - pane.body.sels[kept] = pane.body.sels[i]; - kept += 1; - }; - if (kept != pane.body.nsel) { - moved = true; - if (kept == 0) pane.body.dropSels() else pane.body.nsel = kept; - } - } - if (copy_lost) if (pane.ovl) |copy| { - pane.gpa.free(copy.text); - pane.ovl = null; - moved = true; - }; - if (moved) pane.nsel_snap = 0; // Saved regex-preview offsets name the old flat text. - return failed; + defer if (track.len > room.len) state.gpa.free(pins); + for (pins, track) |*pin, row| pin.* = trackRow(pages, row, &failed); + // Whether the program cleared the screen (ED 2, a switch of screens); + // pardes reads the flag nowhere else. + state.vt.flags.dirty.clear = false; + ingest(state, bytes); + const cleared = state.vt.flags.dirty.clear; + // RIS can destroy the alternate screen and every pin it owned. + const alive: ?*ghostty_vt.PageList = if (screens.generation(key) == generation) pages else null; + for (pins, rows[0..track.len], erased[0..track.len]) |pin, *row, *gone| { + row.* = pinnedRow(alive, pin); + gone.* = alive != null and pin.pin != null and pin.pin.?.garbage; + if (alive) |owner| if (pin.pin) |held| owner.untrackPin(held); + } + return .{ .rows = rows[0..track.len], .erased = erased[0..track.len], .cleared = cleared, .alive = alive != null, .failed = failed }; } /// A full-screen program has the emulator on its alternate screen. @@ -1416,7 +1124,7 @@ pub fn enterTty(p: *Pardes, id: usize) void { } pane.body.mode = .tty; - followOutput(pane); // entering raw mode is a request for the live shell + pane.followOutput(); // entering raw mode is a request for the live shell pane.body.vsel.active = false; pane.body.nsel = 0; // The raw renderer follows the live cursor. A captured mouse selection @@ -1800,7 +1508,7 @@ const BodyWalk = struct { fn init(pane: *Pane) BodyWalk { const off = pane.scroll(); - const goff = gridOffset(pane); + const goff: i32 = @intCast(grid(pane.terminal).offset); return .{ .pane = pane, .goff = goff, @@ -2003,7 +1711,7 @@ pub fn recolorAnsi(p: *Pardes, s: *Surface, pane: *Pane, r: pardes.Rect, tx: u16 // path needs it per cell. const scnm = pane.terminal.?.vt.modes.get(.reverse_colors); const pages = &pane.terminal.?.vt.screens.active.pages; - const vp_rows: i32 = @intCast(scrollbar(pane).len); + const vp_rows: i32 = @intCast(grid(pane.terminal).len); // Which buffer lines the user has not actually changed, so a row swallowed // by a growing buffer keeps the colour it still stands over. var anchors: ?EditAnchors = null; @@ -2385,16 +2093,6 @@ pub fn undoStep(p: *Pardes, pane: *Pane, back: bool) error{OutOfMemory}!void { pane.ensureCursorVisible(); } -/// The emulator's size in pixels follows the shell's cells: kitty graphics -/// placements are sized by it, and CSI 14/16 t report it. -fn syncPixels(p: *const Pardes, pane: *Pane) void { - if (comptime !images_enabled) return; - const state = pane.terminal orelse return; - const vt = &state.vt; - vt.width_px = @as(u32, vt.cols) * p.view().cell_pixels.w; - vt.height_px = @as(u32, vt.rows) * p.view().cell_pixels.h; -} - /// When the pane's next kitty animation frame is due (ms on the core's /// clock), as its last drawn frame left it; null when nothing plays. pub fn due(state: *const State) ?u64 { @@ -2431,10 +2129,10 @@ pub fn drawImages(p: *Pardes, s: *Surface, pane: *Pane, id: usize, tx: u16, tw: if (comptime !images_enabled) return; const state = pane.terminal orelse return; const screen = state.vt.screens.active; - syncPixels(p, pane); + cellPixels(state, p.view().cell_pixels.w, p.view().cell_pixels.h); // A body taller than this draws its images on the rows that fit. var rows_of: [1024]?u16 = undefined; - const vp_rows: usize = @min(scrollbar(pane).len, rows_of.len); + const vp_rows: usize = @min(grid(state).len, rows_of.len); @memset(rows_of[0..vp_rows], null); var any_placeholder = false; var walk: BodyWalk = .init(pane); @@ -2522,7 +2220,7 @@ test "a terminal made fresh has no size waiting: one never resized keeps its gri @memset(ptr[0..len], 0xAA); return ptr; } - fn resize(ctx: *anyopaque, buf: []u8, a: std.mem.Alignment, n: usize, ra: usize) bool { + fn grow(ctx: *anyopaque, buf: []u8, a: std.mem.Alignment, n: usize, ra: usize) bool { const self: *@This() = @ptrCast(@alignCast(ctx)); return self.child.rawResize(buf, a, n, ra); } @@ -2534,7 +2232,7 @@ test "a terminal made fresh has no size waiting: one never resized keeps its gri const self: *@This() = @ptrCast(@alignCast(ctx)); self.child.rawFree(buf, a, ra); } - const vtable: std.mem.Allocator.VTable = .{ .alloc = alloc, .resize = resize, .remap = remap, .free = free }; + const vtable: std.mem.Allocator.VTable = .{ .alloc = alloc, .resize = grow, .remap = remap, .free = free }; }; var filling: Filling = .{ .child = std.testing.allocator }; const gpa: std.mem.Allocator = .{ .ptr = &filling, .vtable = &Filling.vtable }; @@ -2555,16 +2253,14 @@ test "document construction allocates only the pane and has inert terminal defau try std.testing.expectEqual(@as(usize, 0), failing.resize_index); try std.testing.expect(!failing.has_induced_failure); try std.testing.expectEqual(@as(usize, @sizeOf(Pane)), failing.allocated_bytes); - try std.testing.expectEqual(GridCursor{}, gridCursor(pane)); - try std.testing.expectEqual(Scrollbar{}, scrollbar(pane)); + try std.testing.expectEqual(Term.Grid{}, grid(pane.terminal)); try std.testing.expect(!bracketedPaste(pane)); try std.testing.expect(!reportsMouse(pane)); try std.testing.expect(!promptInputReady(pane)); - scrollGrid(pane, 100); - followOutput(pane); - resizeGrid(pane, 80, 24); - try std.testing.expectEqual(GridCursor{}, gridCursor(pane)); - try std.testing.expectEqual(Scrollbar{}, scrollbar(pane)); + pane.scrollBy(100); + pane.followOutput(); + pane.resizeGrid(80, 24); + try std.testing.expectEqual(Term.Grid{}, grid(pane.terminal)); try std.testing.expectEqualStrings("", try screenTextAlloc(pane, allocator)); try std.testing.expect(!failing.has_induced_failure); } @@ -2581,14 +2277,14 @@ test "terminal state keeps parser fragments and sends emulator replies through i if (effect == .write) return error.PrematureTerminalReply; } p.update(.{ .output = .{ .pane = 0, .bytes = "6n" } }); - var replies: usize = 0; + var answers: usize = 0; while (p.nextEffect()) |effect| { if (effect != .write) continue; try std.testing.expectEqual(@as(u8, 0), effect.write.pane); try std.testing.expectEqualStrings("\x1b[1;1R", effect.write.bytes.slice()); - replies += 1; + answers += 1; } - try std.testing.expectEqual(@as(usize, 1), replies); + try std.testing.expectEqual(@as(usize, 1), answers); try std.testing.expectEqual(@as(u16, 0), state.reply_len); } @@ -2598,12 +2294,12 @@ test "a terminal's dump restores the cells it drew, its history and where its vi defer p.deinit(); while (p.nextEffect()) |_| {} const pane = p.panes[0].?; - feedOutput(p, pane, "\x1b[31mred\x1b[0m\r\ncafé\r\n"); + pane.feedOutput(p, "\x1b[31mred\x1b[0m\r\ncafé\r\n"); for (0..30) |i| { var line: [16]u8 = undefined; - feedOutput(p, pane, std.fmt.bufPrint(&line, "line {d}\r\n", .{i}) catch unreachable); + pane.feedOutput(p, std.fmt.bufPrint(&line, "line {d}\r\n", .{i}) catch unreachable); } - scrollGrid(pane, -5); + 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); @@ -2627,7 +2323,7 @@ test "a restored command pane comes back finished, its command not run again" { while (p.nextEffect()) |_| {} const cmd = p.freeSlot().?; _ = try panes.newCommand(p, cmd, "/tmp", "make test"); - feedOutput(p, p.panes[cmd].?, "ok\r\n"); + p.panes[cmd].?.feedOutput(p, "ok\r\n"); p.update(.{ .exited = .{ .pane = @intCast(cmd), .status = 2 } }); try pardes.dump.dumpState(p); const restored = try pardes.dump.initFromDump(gpa, .{ .tty_only = true, .cols = 60, .rows = 16 }, p.dump_out.?); @@ -2656,7 +2352,7 @@ test "a restored terminal keeps its history above a marker and gets a shell wher defer p.deinit(); while (p.nextEffect()) |_| {} const pane = p.panes[0].?; - feedOutput(p, pane, "old output\r\n$ ls\r\n"); + pane.feedOutput(p, "old output\r\n$ ls\r\n"); try pane.setOwnedCwd("/tmp"); pane.shell = try gpa.dupe(u8, "bash"); // `Term bash`: it comes back as bash try pardes.dump.dumpState(p); @@ -2684,19 +2380,19 @@ test "a position that cannot follow the output for want of memory is said on the const p = try Pardes.init(failing.allocator(), .{ .tty_only = true, .cols = 80, .rows = 24 }); defer p.deinit(); const pane = p.panes[0].?; - feedOutput(p, pane, "one\r\ntwo\r\n"); + pane.feedOutput(p, "one\r\ntwo\r\n"); // More positions than the emulator's pins have room for: following them // through the output needs memory, and there is none. try std.testing.expect(pane.body.reserveSels()); for (pane.body.sels[0..8], 0..) |*range, i| range.* = .{ .row = @intCast(i), .col = 0, .arow = @intCast(i), .acol = 1 }; pane.body.nsel = 8; failing.fail_index = failing.alloc_index; - feedOutput(p, pane, "three\r\n"); + pane.feedOutput(p, "three\r\n"); failing.fail_index = std.math.maxInt(usize); try std.testing.expect(failing.has_induced_failure); - try std.testing.expectEqualStrings(positions_lost, pane.msg[0..pane.msg_len]); + try std.testing.expectEqualStrings(panes.positions_lost, pane.msg[0..pane.msg_len]); const logged = p.messages.at(p.messages.len -| 1) orelse return error.NothingLogged; - try std.testing.expectEqualStrings(positions_lost, logged.slice()); + try std.testing.expectEqualStrings(panes.positions_lost, logged.slice()); } test "raw terminal output needs no position tracking allocations" { @@ -2705,11 +2401,11 @@ test "raw terminal output needs no position tracking allocations" { defer p.deinit(); const pane = p.panes[0].?; pane.body.mode = .tty; - feedOutput(p, pane, "warm"); + pane.feedOutput(p, "warm"); const allocations = failing.alloc_index; failing.fail_index = allocations; const pins = pane.terminal.?.vt.screens.active.pages.countTrackedPins(); - feedOutput(p, pane, " output"); + pane.feedOutput(p, " output"); try std.testing.expectEqual(allocations, failing.alloc_index); try std.testing.expect(!failing.has_induced_failure); try std.testing.expectEqual(pins, pane.terminal.?.vt.screens.active.pages.countTrackedPins()); diff --git a/src/views.zig b/src/views.zig index 953b39a4..dbe7e54c 100644 --- a/src/views.zig +++ b/src/views.zig @@ -341,7 +341,7 @@ fn unpark(p: *Pardes, k: u8) void { layout.compute(p); // Its terminals' cursors moved while it was out: each pan follows. for (p.panes, 0..) |s, id| if (s) |pane| { - pane.pan = pardes.panes.terminal.panFor(p, pane, p.view().rects[id]); + pane.pan = pane.panFor(p, p.view().rects[id]); }; } -- cgit v1.3