diff options
Diffstat (limited to 'src')
| -rw-r--r-- | src/CHANGELOG.md | 17 | ||||
| -rw-r--r-- | src/Core.zig | 107 | ||||
| -rw-r--r-- | src/Effect.zig | 2 | ||||
| -rw-r--r-- | src/File.zig | 90 | ||||
| -rw-r--r-- | src/Jump.zig | 2 | ||||
| -rw-r--r-- | src/Kind.zig | 391 | ||||
| -rw-r--r-- | src/Query.zig | 2 | ||||
| -rw-r--r-- | src/Term.zig | 275 | ||||
| -rw-r--r-- | src/body_layer.zig | 134 | ||||
| -rw-r--r-- | src/builtins.zig | 11 | ||||
| -rw-r--r-- | src/colors.zig | 2 | ||||
| -rw-r--r-- | src/draw.zig | 19 | ||||
| -rw-r--r-- | src/dump.zig | 44 | ||||
| -rw-r--r-- | src/edit.zig | 223 | ||||
| -rw-r--r-- | src/exec.zig | 37 | ||||
| -rw-r--r-- | src/fs.zig | 2 | ||||
| -rw-r--r-- | src/gui/gui.zig | 10 | ||||
| -rw-r--r-- | src/host_io.zig | 4 | ||||
| -rw-r--r-- | src/keys.zig | 61 | ||||
| -rw-r--r-- | src/layout.zig | 4 | ||||
| -rw-r--r-- | src/macos.zig | 6 | ||||
| -rw-r--r-- | src/main.zig | 4 | ||||
| -rw-r--r-- | src/mouse.zig | 32 | ||||
| -rw-r--r-- | src/ninep/ctl.zig | 8 | ||||
| -rw-r--r-- | src/ninep/pane.zig | 4 | ||||
| -rw-r--r-- | src/ninep/pty.zig | 40 | ||||
| -rw-r--r-- | src/ninep/screen.zig | 4 | ||||
| -rw-r--r-- | src/pager.zig | 595 | ||||
| -rw-r--r-- | src/panes.zig | 454 | ||||
| -rw-r--r-- | src/pardes.zig | 16 | ||||
| -rw-r--r-- | src/replica.zig | 111 | ||||
| -rw-r--r-- | src/rollback.zig | 2 | ||||
| -rw-r--r-- | src/surface.zig | 3 | ||||
| -rw-r--r-- | src/tagline.zig | 4 | ||||
| -rw-r--r-- | src/tape.zig | 30 | ||||
| -rw-r--r-- | src/term/TerminalImages.zig (renamed from src/TerminalImages.zig) | 4 | ||||
| -rw-r--r-- | src/term/echo.zig (renamed from src/echo.zig) | 15 | ||||
| -rw-r--r-- | src/term/pager.zig | 371 | ||||
| -rw-r--r-- | src/term/screen_state.zig (renamed from src/screen_state.zig) | 374 | ||||
| -rw-r--r-- | src/term/terminal.zig (renamed from src/terminal.zig) | 1534 | ||||
| -rw-r--r-- | src/tui/tui.zig | 20 | ||||
| -rw-r--r-- | src/views.zig | 2 | ||||
| -rw-r--r-- | src/wire.zig | 6 |
43 files changed, 2553 insertions, 2523 deletions
diff --git a/src/CHANGELOG.md b/src/CHANGELOG.md index f367774e..e398b43f 100644 --- a/src/CHANGELOG.md +++ b/src/CHANGELOG.md @@ -2,6 +2,13 @@ ## Unreleased +- The terminal is reached through one interface, `src/Term.zig`, and its + own files (the emulator, its screen state for replicas, predicted echo, + kitty images, the pager's parse) sit behind it in `src/term/`: the + first step of taking the terminal out of the core + (docs/next-terminal.md). Editing a terminal's text is the core's, on a + copy of its rows, as before; nothing a session does changes. + - A search with a class whose range ends at `\xff` (`[\x80-\xff]`, in an address, `s`, a plumbing rule) no longer takes the editor down: mvzr counted the range past a byte's end. @@ -47,14 +54,8 @@ did it again, a quarter of its time. A package that depends on pardes is given the same filtered queries. -- The core measures a grapheme's cells over uucode itself - (`File.utf8Width`, libvaxis's `gwidth` to the cell on every scalar - value), so libvaxis is the tui's and the gui's alone, not the core - module's. The 256-colour palette Petscii art and the window draw a - palette colour with is pardes's own (`colors.xterm`), ghostty-vt's - default to the entry. A `+Pager` (`pardes -`) reads its program's colour - codes with a parser of its own, which pages what ghostty-vt's did, byte - for byte, about 10% faster. +- The 256-colour palette Petscii art and the window draw a palette colour + with is pardes's own (`colors.xterm`), ghostty-vt's default to the entry. - Commit patches open as `+Diff-<short-hash>` and reuse only their own commit's pane, so another paged patch no longer replaces one already open. diff --git a/src/Core.zig b/src/Core.zig index 9a6e80d4..7d8cfb0e 100644 --- a/src/Core.zig +++ b/src/Core.zig @@ -73,7 +73,6 @@ const memory = pardes.memory; const modal = pardes.modal; const mouse = pardes.mouse; const newer_build_words = pardes.newer_build_words; -const pager = pardes.pager; const platform = pardes.platform; const recent_files = @import("recent.zig"); const sel_slot = pardes.sel_slot; @@ -253,7 +252,7 @@ session_dir_len: ?u16 = null, settings: config.Runtime = .{ .font = .{ .tagline_percent = config.gui_tagline_font_percent } }, locations_config: locations.Config = .{}, locations_cache: locations.Cache = .{}, -tty_filter_palette: pardes.panes.terminal.FilterPalette = .{}, +tty_filter_palette: pardes.Term.FilterPalette = .{}, font_request_taken: bool = false, custom_theme: ?Theme = null, /// bodyChrome's: the theme it was worked out for, and it. @@ -369,10 +368,10 @@ restore_req: ?[]const u8 = null, restore_buf: [1024]u8 = @splat(0), surface: Surface = .{}, -/// A replica's predicted echo (src/echo.zig), drawn over its terminals: +/// A replica's predicted echo (src/term/echo.zig), drawn over its terminals: /// presentation, its own, in no digest and no rollback copy. Null on a /// session's own core. -echo: ?*pardes.echo.Echo = null, +echo: ?*pardes.Term.Echo = null, /// The live view, `views[live]` (`view()`): whose input the session /// takes now, and whose share of the panes is in their own fields /// (views.zig). `views_open` says which views there are, one a window @@ -396,8 +395,8 @@ scratch: std.heap.ArenaAllocator, /// that still own their loop pass their own arena to `render` instead. frame_arena: std.heap.ArenaAllocator, /// the terminal motion surface, memoized against the pane it was built -/// for — see panes.terminal.RowsCache for the lifetime rule -shell_rows: pardes.panes.terminal.RowsCache = .{}, +/// for — see edit.RowsCache for the lifetime rule +shell_rows: pardes.edit.RowsCache = .{}, /// Finished command panes' output, and whether it is a diff /// (File.DiffOutput). diff_output: pardes.panes.File.DiffOutput = .{}, @@ -573,7 +572,7 @@ fn initSession(gpa: std.mem.Allocator, opts: Options) !*Pardes { p.oneColumn(); }, .stdin => { - const page = try pager.parse(gpa, opts.stdin_text.?); + const page = try pardes.Term.page(gpa, opts.stdin_text.?); errdefer gpa.free(page.spans); const content = page.text; errdefer gpa.free(content); @@ -870,9 +869,9 @@ fn reportFocus(p: *Pardes) void { }; if (std.meta.eql(want, v.focus_told)) return; if (v.focus_told) |old| if (p.panes[old.id]) |pane| { - if (pane.serial == old.serial and pardes.panes.terminal.reportsFocus(pane)) p.emitWrite(old.id, "\x1b[O"); + if (pane.serial == old.serial and pardes.Term.modes(pane.terminal).focus) p.emitWrite(old.id, "\x1b[O"); }; - if (want) |new| if (pardes.panes.terminal.reportsFocus(p.panes[new.id].?)) p.emitWrite(new.id, "\x1b[I"); + if (want) |new| if (pardes.Term.modes(p.panes[new.id].?.terminal).focus) p.emitWrite(new.id, "\x1b[I"); v.focus_told = want; } @@ -1001,7 +1000,16 @@ pub fn acknowledgeShell(p: *Pardes, id: usize, executable: []const u8, prompt_ma } else |_| {} } }; - if (id < MAX_PANES) pardes.panes.terminal.shellSpawned(p, id, prompt_marks); + // The lines queued for it go when it can take them: at its first + // prompt, or now when it draws no marks to wait for. + if (id < MAX_PANES) if (p.panes[id]) |pane| if (pane.isTerminal() and pane.pending_command.wait == .spawn) { + if (prompt_marks) { + pane.pending_command.wait = .input; + } else { + pane.greet = false; + pane.releasePendingCommand(p, id, true); + } + }; if (p.settings.shell.effective.set(executable)) p.settings.shell.pending = false; } @@ -1607,7 +1615,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); }, @@ -1805,10 +1813,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. @@ -1873,7 +1878,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; @@ -1882,19 +1887,23 @@ 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); - pardes.panes.terminal.releasePendingCommandIfReady(p, id, pane); + if (pane.pending_command.wait == .input) pane.releasePendingCommand(p, id, tape.value(.prompt, struct { + fn ready(at: *const Pane) bool { + return pardes.Term.prompt(at.terminal).input_ready; + } + }.ready, .{pane})); // Which bands a pane shows is the step's, as its geometry is: // what is drawn under them, and where a click lands, read it. Messages.collectNotices(p, pane, r, id); // The greeting `ls` of a new terminal in a directory is typed at // its shell's FIRST prompt, or never: typed later it would land // in whatever runs then, or in the middle of a line someone - // typed (panes.terminal.greeting). - if (pane.greet and pane.isTerminal() and p.resize_count > 0) switch (tape.value(.prompt, pardes.panes.terminal.greeting, .{pane})) { + // typed (Pane.greeting). + if (pane.greet and pane.isTerminal() and p.resize_count > 0) switch (tape.value(.prompt, Pane.greeting, .{pane})) { .wait => {}, .never => pane.greet = false, .now => { @@ -1918,7 +1927,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 { @@ -1997,7 +2006,7 @@ pub fn nextWake(p: *const Pardes) ?u64 { // A terminal's kitty animation, at its next frame. Only a time still // ahead counts: a pane not drawn keeps the last one it was given, // and a past one would wake every frame for nothing. - for (p.panes) |slot| if (slot) |pane| if (pardes.panes.terminal.animationDueMs(pane)) |due_ms| { + for (p.panes) |slot| if (slot) |pane| if (pane.terminal) |state| if (pardes.Term.due(state)) |due_ms| { const due = due_ms *| std.time.ns_per_ms; if (due > p.clock.stepped_ns) { const wait = @max(1, (due - p.clock.stepped_ns + frame_ns - 1) / frame_ns); @@ -2168,7 +2177,7 @@ pub const Options = struct { file: ?[]const u8 = null, file_line: usize = 0, missing: ?struct { word: []const u8, dir: []const u8 } = null, - /// `pardes -`: stdin as it came, for a +Pager pane at boot (pager.zig + /// `pardes -`: stdin as it came, for a +Pager pane at boot (Term.page /// parses it). stdin_text: ?[]const u8 = null, tty_toggle: u21 = config.tty_toggle_default, @@ -2740,7 +2749,7 @@ test "a command of several lines keeps its tag one row, and its echo does not st _ = exec.execute(p, 1, two); while (p.nextEffect()) |_| {} _ = try p.render(frame.allocator()); - const body = try pardes.panes.terminal.screenTextAlloc(pane, gpa); + const body = try pardes.Term.scrollback(pane.terminal, gpa); defer gpa.free(body); try std.testing.expect(std.mem.indexOf(u8, body, "% def greet(name):\n return name") != null); } @@ -3079,7 +3088,7 @@ test "a command pane shows how its command ended, and the next command there run const pane = p.panes[dst].?; // Its first command is echoed as every later one is. { - const first = try pardes.panes.terminal.screenTextAlloc(pane, gpa); + const first = try pardes.Term.scrollback(pane.terminal, gpa); defer gpa.free(first); try std.testing.expect(std.mem.startsWith(u8, first, "% make -j8")); } @@ -3110,16 +3119,16 @@ test "a command pane shows how its command ended, and the next command there run // A program that crashed out of its full screen leaves the emulator // in its modes; the next command starts clear of them. p.update(.{ .output = .{ .pane = @intCast(dst), .bytes = "\x1b[?1049h\x1b[?2004h\x1b[?1000h" } }); - try std.testing.expect(pardes.panes.terminal.bracketedPaste(pane)); + try std.testing.expect(pardes.Term.modes(pane.terminal).bracketed_paste); // Done, the directory's next command runs there, below what it showed. try std.testing.expectEqual(@as(?usize, dst), exec.execute(p, 1, "make test")); - try std.testing.expect(!pardes.panes.terminal.bracketedPaste(pane)); + try std.testing.expect(!pardes.Term.modes(pane.terminal).bracketed_paste); var respawned = false; while (p.nextEffect()) |effect| if (effect == .spawn and effect.spawn.pane == dst) { respawned = true; }; try std.testing.expect(respawned); - const body = try pardes.panes.terminal.screenTextAlloc(pane, gpa); + const body = try pardes.Term.scrollback(pane.terminal, gpa); defer gpa.free(body); const said = std.mem.indexOf(u8, body, "compiled") orelse return error.OutputLost; const ended = std.mem.indexOf(u8, body, "exit 2") orelse return error.ExitLost; @@ -3244,9 +3253,9 @@ test "a host with no methods at all is a complete in-process pardes" { // the absent child is SILENT: the bytes are dropped, and nothing appears // on the pane's screen to suggest a program answered - const before = p.panes[0].?.terminal.?.vt.screens.active.cursor.y; + const before = pardes.Term.grid(p.panes[0].?.terminal).cursor_y; p.perform(.{ .write = .{ .pane = 0, .bytes = .from("ls\r") } }); - try std.testing.expectEqual(before, p.panes[0].?.terminal.?.vt.screens.active.cursor.y); + try std.testing.expectEqual(before, pardes.Term.grid(p.panes[0].?.terminal).cursor_y); // the clipboard round-trips through the in-process one try p.registers.put(gpa, '+', "copied", 0, 1, true); @@ -3715,13 +3724,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); @@ -3767,31 +3776,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" { @@ -3803,7 +3812,7 @@ test "an unasked desktop paste reaches a tty pane's program, not its buffer" { _ = test_api.ptyBytes(p, null, &buf); const pane = p.panes[0].?; - pardes.panes.terminal.enterTty(p, 0); + pardes.keys.enterTty(p, 0); // No request behind it: the window manager's own paste, or SDL answering a // Ctrl-Shift-V the desktop handled. It still has to reach the shell. p.update(.{ .paste = "ls -la" }); @@ -3820,7 +3829,7 @@ test "a paste larger than the effect ring reaches the program whole and in order const buf = try gpa.alloc(u8, 2 << 20); defer gpa.free(buf); _ = test_api.ptyBytes(p, null, buf); - pardes.panes.terminal.enterTty(p, 0); + pardes.keys.enterTty(p, 0); const text = try gpa.alloc(u8, 1536 * 1024); defer gpa.free(text); @@ -3854,10 +3863,10 @@ test "a bracketed paste larger than the ring still closes its bracket" { const buf = try gpa.alloc(u8, 2 << 20); defer gpa.free(buf); _ = test_api.ptyBytes(p, null, buf); - pardes.panes.terminal.enterTty(p, 0); + pardes.keys.enterTty(p, 0); p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[?2004h" } }); - try std.testing.expect(pardes.panes.terminal.bracketedPaste(p.panes[0].?)); + try std.testing.expect(pardes.Term.modes(p.panes[0].?.terminal).bracketed_paste); const text = try gpa.alloc(u8, 1536 * 1024); defer gpa.free(text); @memset(text, 'z'); @@ -3876,7 +3885,7 @@ test "a terminal's answer to its program waits behind the paste still queued for const buf = try gpa.alloc(u8, 2 << 20); defer gpa.free(buf); _ = test_api.ptyBytes(p, null, buf); - pardes.panes.terminal.enterTty(p, 0); + pardes.keys.enterTty(p, 0); const text = try gpa.alloc(u8, 1536 * 1024); defer gpa.free(text); @@ -3902,7 +3911,7 @@ test "pasted bytes still queued at shutdown are freed, not leaked" { const buf = try gpa.alloc(u8, 2 << 20); defer gpa.free(buf); _ = test_api.ptyBytes(p, null, buf); - pardes.panes.terminal.enterTty(p, 0); + pardes.keys.enterTty(p, 0); const text = try gpa.alloc(u8, 1536 * 1024); defer gpa.free(text); @@ -3931,14 +3940,14 @@ test "leaving tty hides the prompt and keeps the command typed at it" { const rowOf = struct { fn at(pp: *Pardes, pane: *Pane, needle: []const u8) ?[]const u8 { - const rows = pardes.panes.terminal.shellRows(pp, pane) catch return null; + const rows = pardes.edit.shellRows(pp, pane) catch return null; for (rows) |r| if (std.mem.indexOf(u8, r, needle) != null) return r; return null; } }.at; const bodyRowOf = struct { fn at(pp: *Pardes, pane: *Pane, needle: []const u8) ?[]const u8 { - const body = pardes.panes.terminal.bodyText(pp.scratch.allocator(), pane) catch return null; + const body = @import("body_layer.zig").bodyText(pp.scratch.allocator(), pane) catch return null; var it = std.mem.splitScalar(u8, body, '\n'); while (it.next()) |r| if (std.mem.indexOf(u8, r, needle) != null) return r; return null; @@ -3993,7 +4002,7 @@ test "entering tty walks the shell cursor to the column clicked past the prompt" p.shell_rows.stale = true; // The command shows LEFT-HUGGED, so its column 3 is the '3'... - const rows = try pardes.panes.terminal.shellRows(p, sp); + const rows = try pardes.edit.shellRows(p, sp); var row: i32 = 0; const at = for (rows, 0..) |r, i| { if (std.mem.indexOf(u8, r, "0123456789") != null) break i; @@ -4007,7 +4016,7 @@ test "entering tty walks the shell cursor to the column clicked past the prompt" sp.body.cur_col = 3; sp.body.cur_pinned = true; while (p.nextEffect()) |_| {} - pardes.panes.terminal.enterTty(p, shell); + pardes.keys.enterTty(p, shell); // The walk is arrow keys the shell understands. Seven lefts: readline's // cursor sits past the '9' and the click was on the '3'. diff --git a/src/Effect.zig b/src/Effect.zig index 2af28dd7..e161d1db 100644 --- a/src/Effect.zig +++ b/src/Effect.zig @@ -164,7 +164,7 @@ pub fn perform(p: *Pardes, e: Effect) void { return; } if (!pane.isTerminal()) return; - const text = panes.terminal.screenTextAlloc(pane, p.gpa) catch |err| return p.reportError(st.pane, "Save", err); + const text = pardes.Term.scrollback(pane.terminal, p.gpa) catch |err| return p.reportError(st.pane, "Save", err); defer p.gpa.free(text); if (writeChecked(p, st.pane, st.serial, st.path.slice(), text, 0)) |still| ctlfs.events.noteLogAs(p, .save, still, st.path.slice()); diff --git a/src/File.zig b/src/File.zig index 84e88dff..64614191 100644 --- a/src/File.zig +++ b/src/File.zig @@ -2,7 +2,7 @@ //! index, syntax highlights and the body it fills. const panes = @import("panes.zig"); const std = @import("std"); -const uucode = @import("uucode"); +const vaxis = @import("vaxis"); const builtin = @import("builtin"); const pardes = @import("pardes.zig"); const config = @import("config.zig"); @@ -21,7 +21,6 @@ const Stream = @import("Stream.zig"); const Pane = panes.Pane; const Output = panes.Output; const Mini = panes.mini; -const terminal = panes.terminal; const Text = panes.Text; const SYNTAX_CONTEXT_AFTER_ROWS: usize = 2; @@ -128,11 +127,11 @@ pub const State = struct { /// A +Pager whose text is a diff (`git diff`, `show`, `log -p`): drawn /// and looked at as a diff (Pane.colorAlgo). pager_diff: bool = false, - /// A +Pager's colours, as its program printed them (pager.zig): drawn + /// A +Pager's colours, as its program printed them (Term.page): drawn /// over its text by recolorSyntax, never read over 9P. ponytail: any /// edit drops them (setContentSpan); shifting them through the splice, /// as pane.zig's shiftOne moves dot, would keep them. - pager_spans: []pardes.pager.Span = &.{}, + pager_spans: []pardes.Term.Span = &.{}, /// Seconds of the last content change, for the filesystem's stat; zero until edited. mtime: u32 = 0, /// Non-null for a generated output buffer rather than an on-disk file. @@ -186,8 +185,10 @@ pub const NodeStep = struct { ranges: []modal.Selection, primary: usize }; pub fn graphemeDisplayWidth(grapheme: []const u8) usize { if (std.mem.eql(u8, grapheme, "\t")) return config.tab_now; if (grapheme.len == 1 and grapheme[0] >= 0x20 and grapheme[0] < 0x7f) return 1; - if (std.unicode.utf8ValidateSlice(grapheme)) return @max(1, @as(usize, utf8Width(grapheme))); - // Each invalid byte is a cell, as surface.zig draws it, and each valid + if (std.unicode.utf8ValidateSlice(grapheme)) return @max(1, @as(usize, vaxis.gwidth.gwidth(grapheme, .unicode))); + // vaxis's gwidth counts back a replacement rune's 3 bytes over the one + // invalid byte it stood for (`\xee` before `e\u{301}` overflowed it): + // each invalid byte is a cell, as surface.zig draws it, and each valid // run between is measured alone. var width: usize = 0; var run: usize = 0; @@ -198,60 +199,15 @@ pub fn graphemeDisplayWidth(grapheme: []const u8) usize { i += n; continue; } - if (run < i) width += utf8Width(grapheme[run..i]); + if (run < i) width += vaxis.gwidth.gwidth(grapheme[run..i], .unicode); width += 1; i += 1; run = i; } - if (run < grapheme.len) width += utf8Width(grapheme[run..]); + if (run < grapheme.len) width += vaxis.gwidth.gwidth(grapheme[run..], .unicode); return @max(1, width); } -/// The cells valid UTF-8 takes, summed over its graphemes: a grapheme is -/// as wide as its widest code point (a control, a nonspacing or enclosing -/// mark and the joiners, selectors and other format characters below add -/// none; East Asian wide and fullwidth two, the rest one), then at least -/// one under the text selector U+FE0E, else at least two under the emoji -/// selector U+FE0F, with an emoji-presentation code point, or as a flag's -/// two regional indicators. It is libvaxis's `gwidth(.unicode)` over the -/// same uucode tables, which the tui renders with in mode 2027. -pub fn utf8Width(valid: []const u8) u16 { - var total: u16 = 0; - var widest: u16 = 0; - var text_vs = false; - var emoji = false; - var flags: u8 = 0; - var it = uucode.grapheme.utf8Iterator(valid); - while (it.nextCodePoint()) |r| { - const cp = r.code_point; - if (cp == 0xfe0e) { - text_vs = true; - } else if (cp == 0xfe0f) { - emoji = true; - } else { - if (uucode.get(.is_emoji_presentation, cp)) emoji = true; - if (cp >= 0x1f1e6 and cp <= 0x1f1ff) flags += 1; - widest = @max(widest, @as(u16, switch (cp) { - 0...0x1f, 0x7f...0x9f, 0xad, 0x34f, 0x180b...0x180d, 0x200b...0x200d, 0x2060, 0xfe00...0xfe0d, 0xfeff, 0xe0100...0xe01ef => 0, - else => switch (uucode.get(.general_category, cp)) { - .mark_nonspacing, .mark_enclosing => 0, - else => switch (uucode.get(.east_asian_width, cp)) { - .fullwidth, .wide => 2, - else => 1, - }, - }, - })); - } - if (!r.is_break) continue; - total += if (text_vs) @max(1, widest) else if (emoji or flags == 2) @max(2, widest) else widest; - widest = 0; - text_vs = false; - emoji = false; - flags = 0; - } - return total; -} - pub fn displayWidth(text: []const u8) usize { var width: usize = 0; var at: usize = 0; @@ -598,7 +554,7 @@ pub fn open(p: *Pardes, id: usize, path: []const u8, line: usize) !*Pane { std.debug.assert(p.panes[id] == null and !p.reserved_slots[id]); const path_copy = try p.gpa.dupe(u8, path); errdefer p.gpa.free(path_copy); - const pane = try terminal.createDoc(p.gpa, p.view().screen_w, p.view().screen_h); + const pane = try panes.createDoc(p.gpa, p.view().screen_w, p.view().screen_h); errdefer p.gpa.destroy(pane); const history = try History.create(p.gpa); errdefer p.gpa.destroy(history); @@ -1875,8 +1831,8 @@ pub fn recolorSyntax(p: *Pardes, s: *Surface, pane: *Pane, f: *State, r: pardes. // A row whose first byte names a hue (syntax.ground_add, _del): its // grounds, the theme's, worked out once a frame and only for one. var grounds: ?Colors.Grounds = null; - var filtered_storage: terminal.FilteredColors = undefined; - const filtered: ?*terminal.FilteredColors = if (pane.tty_filter and spans.len > 0) blk: { + var filtered_storage: pardes.Term.Filter = undefined; + const filtered: ?*pardes.Term.Filter = if (pane.tty_filter and spans.len > 0) blk: { filtered_storage = .init(p, null); break :blk &filtered_storage; } else null; @@ -1923,11 +1879,11 @@ pub fn recolorSyntax(p: *Pardes, s: *Surface, pane: *Pane, f: *State, r: pardes. const ground: ?[3]u8 = if (lead & syntax.ground_emph != 0) t.row else if (lead & syntax.ground_line != 0) t.line else null; if (ground) |g| s.tint(tx + @as(u16, @intCast(prefix_width)), body_y + vr, tw -| @as(u16, @intCast(prefix_width)), g, null); }; - // A +Pager's own colours (pager.zig) on every row but one in a hue: + // A +Pager's own colours (Term.page) on every row but one in a hue: // an added or removed line is drawn as pardes draws a diff, and // git's red and green on it would only fight the tint. - var span_at = if (tint != null) spans.len else std.sort.partitionPoint(pardes.pager.Span, spans, base + hs, struct { - fn before(at: usize, span: pardes.pager.Span) bool { + var span_at = if (tint != null) spans.len else std.sort.partitionPoint(pardes.Term.Span, spans, base + hs, struct { + fn before(at: usize, span: pardes.Term.Span) bool { return span.end <= at; } }.before); @@ -2004,8 +1960,8 @@ pub fn recolorSyntax(p: *Pardes, s: *Surface, pane: *Pane, f: *State, r: pardes. if (st.fg != .default) cell.style.fg = colors.spanColor(st.fg, false); if (st.bg != .default) cell.style.bg = colors.spanColor(st.bg, true); } else { - if (st.fg != .default) cell.style.fg = if (st.fg == .index) terminal.palColor(p, st.fg.index) else st.fg; - if (st.bg != .default) cell.style.bg = if (st.bg == .index) terminal.palColor(p, st.bg.index) else st.bg; + if (st.fg != .default) cell.style.fg = if (st.fg == .index) pardes.Term.palColor(p, st.fg.index) else st.fg; + if (st.bg != .default) cell.style.bg = if (st.bg == .index) pardes.Term.palColor(p, st.bg.index) else st.bg; } cell.style.bold = cell.style.bold or st.bold; cell.style.dim = st.dim; @@ -2069,7 +2025,7 @@ pub const DiffOutput = struct { e.used = o.clock; return if (e.is_diff) e.rows else null; }; - const shown = terminal.shellRows(p, pane) catch return null; + const shown = pardes.edit.shellRows(p, pane) catch return null; const is_diff = diff.looksLikeDiff(shown); var total: usize = 0; if (is_diff) for (shown) |row| { @@ -2131,7 +2087,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)); @@ -2217,7 +2173,7 @@ pub fn paintWordSelection( } } -test "an invalid byte in a grapheme is one cell, and never reaches utf8Width" { +test "an invalid byte in a grapheme is one cell, and never reaches vaxis's width" { try std.testing.expectEqual(@as(usize, 2), graphemeDisplayWidth("\xeee\xcc\x81")); try std.testing.expectEqual(@as(usize, 3), graphemeDisplayWidth("\xee\xffe")); try std.testing.expectEqual(@as(usize, 3), graphemeDisplayWidth("\u{4e16}\x80")); @@ -2256,11 +2212,11 @@ test "indexed source rows match uncached scans across content changes" { } } -test "the ASCII arm of graphemeDisplayWidth matches the utf8Width it skips" { +test "the ASCII arm of graphemeDisplayWidth matches the gwidth it skips" { const ref = struct { fn width(grapheme: []const u8) usize { if (std.mem.eql(u8, grapheme, "\t")) return config.tab_now; - return @max(1, @as(usize, utf8Width(grapheme))); + return @max(1, @as(usize, vaxis.gwidth.gwidth(grapheme, .unicode))); } }.width; @@ -2275,7 +2231,7 @@ test "the ASCII arm of graphemeDisplayWidth matches the utf8Width it skips" { "\u{1f642}", "\u{1f1e6}\u{1f1e7}", "\xff", }) |g| try std.testing.expectEqual(ref(g), graphemeDisplayWidth(g)); // Two invalid bytes are two cells, as surface.zig draws them, where - // one U+FFFD for the pair would give one. + // vaxis's own count gives the pair one. try std.testing.expectEqual(@as(usize, 2), graphemeDisplayWidth("\xe4\xb8")); } 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/Kind.zig b/src/Kind.zig index 250e1144..04db2579 100644 --- a/src/Kind.zig +++ b/src/Kind.zig @@ -199,7 +199,7 @@ pub const Slot = struct { /// Collapse Del. tail: Buf(160) = .{}, /// A replica's frame of it, as the authority painted it. - shadow: ?*@import("screen_state.zig").Shadow = null, + shadow: ?*Shadow = null, /// Debug: the kind's allocations, which paint must leave as they are /// (the list the page allocator's: a region's first is slow in Debug). used: if (checked) std.ArrayList([]u8) else void = if (checked) .empty else {}, @@ -275,7 +275,7 @@ pub fn openFile(p: *Pardes, id: usize, k: u8, path: []const u8) !*Pane { /// if the kind refused, in `slot.refused`. One call for both cores. pub fn reopen(p: ?*Pardes, id: usize, s: *Slot, bytes: ?[]const u8) bool { // A replica has no kind's code: what the open says is the authority's. - if (authorityOnly("a kind's open")) return false; + if (tape.authorityOnly("a kind's open")) return false; var cl: Call = .{ .p = p, .id = id, .slot = s }; const prev = cl.begin("open"); if (p) |core| if (core.kinds.byName(s.nameOf())) |k| { @@ -530,7 +530,7 @@ fn prefixOf(p: *const Pardes, slot: *const Slot, buf: *[400]u8) []const u8 { pub fn key(p: *Pardes, id: usize, k: pardes.Key) bool { const slot = (p.panes[id] orelse return false).addon orelse return false; if (!caps(p, slot).key) return false; - if (authorityOnly("a key into a kind's pane")) return true; + if (tape.authorityOnly("a key into a kind's pane")) return true; const pk: c.pa_key = .{ .cp = k.cp, .ctrl = @intFromBool(k.ctrl), .alt = @intFromBool(k.alt), .shift = @intFromBool(k.shift), .view = p.live + 1 }; var cl: Call = .{ .p = p, .id = id, .slot = slot }; const prev = cl.begin("key"); @@ -554,7 +554,7 @@ pub fn takesKeys(p: *const Pardes, s: *const Slot) bool { pub fn search(p: *Pardes, id: usize, pat: []const u8) ?[]const u8 { const slot = (p.panes[id] orelse return null).addon orelse return null; if (!caps(p, slot).search) return null; - if (authorityOnly("a kind's search")) return null; + if (tape.authorityOnly("a kind's search")) return null; var cl: Call = .{ .p = p, .id = id, .slot = slot }; const prev = cl.begin("search"); if (slot.ops) |o| o.search.?(slot.st, pat.ptr, @intCast(pat.len)); @@ -570,7 +570,7 @@ pub fn address(p: *Pardes, id: usize, text: []const u8, said: *Buf(160)) bool { const slot = (p.panes[id] orelse return false).addon orelse return false; // By its caps, not its code: a Shadow calls as the authority does. if (!caps(p, slot).address) return false; - if (authorityOnly("a kind's address")) return true; + if (tape.authorityOnly("a kind's address")) return true; var cl: Call = .{ .p = p, .id = id, .slot = slot, .missing = said }; const prev = cl.begin("address"); if (slot.ops) |o| cl.ret = o.address.?(slot.st, text.ptr, @intCast(text.len)); @@ -587,7 +587,7 @@ pub fn takesMouse(p: *const Pardes, s: *const Slot) bool { pub fn mouse(p: *Pardes, id: usize, m: pardes.Mouse, col: u16, row: u16) bool { const slot = (p.panes[id] orelse return false).addon orelse return false; if (!caps(p, slot).mouse) return false; - if (authorityOnly("the mouse in a kind's pane")) return true; + if (tape.authorityOnly("the mouse in a kind's pane")) return true; const pm: c.pa_mouse = .{ .button = switch (m.button) { .left => c.PA_LEFT, @@ -815,7 +815,7 @@ pub fn ctl(p: *Pardes, id: usize, line: []const u8, reply: *[160]u8) ?[]const u8 const slot = (p.panes[id] orelse return "no such pane").addon orelse return "not a kind's pane"; if (!slot.live) return "its addon is not loaded"; if (!caps(p, slot).ctl) return "its kind takes no words"; - if (authorityOnly("a kind's word")) return null; + if (tape.authorityOnly("a kind's word")) return null; var cl: Call = .{ .p = p, .id = id, .slot = slot }; const prev = cl.begin("ctl"); @memset(reply, 0); @@ -841,12 +841,6 @@ pub fn ctlRead(pane: *const Pane, buf: []u8) []const u8 { return buf[0..@min(buf.len, f(slot.st, buf.ptr, @intCast(buf.len)))]; } -fn authorityOnly(comptime why: []const u8) bool { - if (!tape.speculating()) return false; - tape.poison(why); - return true; -} - // ---- a call into a kind ---- /// What a call into a kind did that the core takes on: its answer, a @@ -1192,6 +1186,283 @@ pub fn Buf(comptime n: usize) type { }; } +// ---- a pane of a kind, as a Shadow (architecture §16.5) ---- +// +// A replica's core has no code for a library's kind: such a pane is drawn +// from the authority's frame of it, painted at the size the peer's view +// gives it. A frame crosses as its size and the pointer it asks for, each +// row by its hash (with its cells when the peer's row there is another), +// then each placement by its key; its raster's pixels cross before it, as +// strips of rows (`raster` messages, `encodeStrip`), those over its `src` +// the peer was not sent with the frame before. The stream is ordered and +// loses nothing, so what the authority last sent a peer is what the peer +// holds, but for a raster its `Blobs` let go, which it asks for again. + +const ShadowCell = c.pa_cell; +const Place = c.pa_placement; +/// A row's or a frame's content address, as a terminal's rows have one. +const Hash = u64; + +/// A replica's frame of a pane of a kind: what Kind.draw draws for it, its +/// placements' pixels its peer's `Blobs`. +pub const Shadow = struct { + gpu: []const u8 = &.{}, + cols: u16 = 0, + rows: u16 = 0, + cells: []ShadowCell = &.{}, + hashes: []Hash = &.{}, + places: std.ArrayList(Place) = .empty, + pointer: u8 = 0, + /// The raster it last asked for again (`apply`'s): asked once. + wanted: u64 = 0, + + pub fn deinit(sh: *Shadow, gpa: std.mem.Allocator) void { + gpa.free(sh.gpu); + gpa.free(sh.cells); + gpa.free(sh.hashes); + sh.places.deinit(gpa); + gpa.destroy(sh); + } + + /// A frame message applied (`encodeShadow`'s), of the pane `serial`, + /// each placement's pixels from `blobs`: one it lacks is not shown, and + /// its name is what to ask for (once), else 0. + pub fn apply(sh: *Shadow, gpa: std.mem.Allocator, bytes: []const u8, serial: u32, blobs: *Blobs) !u64 { + var r: std.Io.Reader = .fixed(bytes); + const cols = try r.takeInt(u16, .little); + const rows = try r.takeInt(u16, .little); + if (cols != sh.cols or rows != sh.rows) { + gpa.free(sh.cells); + gpa.free(sh.hashes); + sh.cells = try gpa.alloc(ShadowCell, @as(usize, cols) * rows); + sh.hashes = try gpa.alloc(Hash, rows); + @memset(std.mem.sliceAsBytes(sh.cells), 0); + @memset(sh.hashes, 0); + sh.cols = cols; + sh.rows = rows; + } + sh.pointer = try r.takeByte(); + for (0..rows) |y| { + sh.hashes[y] = try r.takeInt(u64, .little); + if (try r.takeByte() == 0) continue; + for (sh.cells[y * cols ..][0..cols]) |*cell| { + @memcpy(&cell.text, try r.take(8)); + cell.fg = try r.takeInt(u32, .little); + cell.bg = try r.takeInt(u32, .little); + cell.attrs = try r.takeInt(u16, .little); + cell.len = try r.takeByte(); + cell.flags = try r.takeByte(); + } + } + sh.places.clearRetainingCapacity(); + var lacking: u64 = 0; + for (0..try r.takeByte()) |_| { + var pl = std.mem.zeroes(Place); + pl.w = try r.takeInt(u32, .little); + pl.h = try r.takeInt(u32, .little); + inline for (.{ &pl.src.x, &pl.src.y, &pl.src.w, &pl.src.h, &pl.at.x, &pl.at.y, &pl.at.w, &pl.at.h }) |f| f.* = try r.takeInt(u32, .little); + inline for (.{ &pl.dst.x, &pl.dst.y, &pl.dst.w, &pl.dst.h }) |f| f.* = try r.takeInt(u16, .little); + pl.key = try r.takeInt(u64, .little); + const name = std.hash.Wyhash.hash(serial, std.mem.asBytes(&pl.key)); + pl.rgba = (blobs.shows(name, &pl) orelse { + lacking = name; + continue; + }).ptr; + try sh.places.append(gpa, pl); + } + // Older frames have no optional GPU tail. + const n = if (r.seek < r.end) try r.takeInt(u32, .little) else 0; + if (n > 4 << 20) return error.BadGpuFrame; + const gpu = try gpa.dupe(u8, try r.take(n)); + gpa.free(sh.gpu); + sh.gpu = gpu; + if (lacking == sh.wanted) return 0; + sh.wanted = lacking; + return lacking; + } +}; + +/// A raster's strip: at most this many bytes of its rows (17.3). +pub const strip_max = 4 << 20; + +/// How many of a `w`-pixel raster's rows a strip holds. +pub fn stripRows(w: u32) u32 { + return @max(1, strip_max / (@as(u32, @max(w, 1)) * 4)); +} + +/// The strips of `pl`'s raster over its `src` rows, a bit each. +fn stripsOver(pl: *const Place) u64 { + const per = stripRows(pl.w); + const lo = @min(pl.src.y, pl.h) / per; + const hi = (@min(pl.src.y +| pl.src.h, pl.h) + per - 1) / per; + var bits: u64 = 0; + for (lo..@min(hi, 64)) |i| bits |= @as(u64, 1) << @intCast(i); + return bits; +} + +/// Strip `i` of `pl`'s raster, a `raster` message's payload: its key, its +/// size, its first row, and its rows' bytes. +pub fn encodeStrip(pl: *const Place, i: u32, w: *std.Io.Writer) !void { + const y0 = i * stripRows(pl.w); + const row = @as(usize, pl.w) * 4; + try w.writeInt(u64, pl.key, .little); + try w.writeInt(u32, pl.w, .little); + try w.writeInt(u32, pl.h, .little); + try w.writeInt(u32, y0, .little); + try w.writeAll(pl.rgba[y0 * row .. @min(pl.h, y0 + stripRows(pl.w)) * row]); +} + +/// A peer's rasters of the panes of a kind, made from their strips by +/// name (the key with its pane's serial), kept to `max` bytes by least +/// recent use but for those a Shadow shows (17.3). +pub const Blobs = struct { + list: std.ArrayList(Blob) = .empty, + clock: u64 = 0, + + pub const max = 64 << 20; + const Blob = struct { name: u64, w: u32, h: u32, bytes: []u8, have: u64 = 0, used: u64 = 0 }; + + pub fn deinit(b: *Blobs, gpa: std.mem.Allocator) void { + for (b.list.items) |x| gpa.free(x.bytes); + b.list.deinit(gpa); + } + + /// A `raster` message's payload (`encodeStrip`'s) into raster `name`, + /// made at its first strip; `shown`, the pixels Shadows show now. + pub fn strip(b: *Blobs, gpa: std.mem.Allocator, name: u64, payload: []const u8, shown: []const [*]const u8) !void { + var r: std.Io.Reader = .fixed(payload); + _ = try r.takeInt(u64, .little); + const w = try r.takeInt(u32, .little); + const h = try r.takeInt(u32, .little); + const y0 = try r.takeInt(u32, .little); + const rows = r.buffered(); + const row = @as(usize, w) * 4; + if (row == 0 or rows.len % row != 0 or y0 % stripRows(w) != 0 or y0 + rows.len / row > h) return error.BadShadow; + const x = for (b.list.items) |*x| { + if (x.name == name) break x; + } else made: { + var held: usize = row * h; + for (b.list.items) |x| held += x.bytes.len; + while (held > max) { + var old: ?usize = null; + for (b.list.items, 0..) |x, i| if (std.mem.indexOfScalar([*]const u8, shown, x.bytes.ptr) == null and (old == null or x.used < b.list.items[old.?].used)) { + old = i; + }; + const i = old orelse break; + held -= b.list.items[i].bytes.len; + gpa.free(b.list.swapRemove(i).bytes); + } + const bytes = try gpa.alloc(u8, row * h); + errdefer gpa.free(bytes); + try b.list.append(gpa, .{ .name = name, .w = w, .h = h, .bytes = bytes }); + break :made &b.list.items[b.list.items.len - 1]; + }; + if (x.w != w or x.h != h) return error.BadShadow; + @memcpy(x.bytes[y0 * row ..][0..rows.len], rows); + x.have |= @as(u64, 1) << @intCast(@min(63, y0 / stripRows(w))); + b.clock += 1; + x.used = b.clock; + } + + /// Raster `name`'s pixels when it has every strip `pl` shows. + fn shows(b: *Blobs, name: u64, pl: *const Place) ?[]u8 { + for (b.list.items) |*x| if (x.name == name and x.w == pl.w and x.h == pl.h and stripsOver(pl) & ~x.have == 0) { + b.clock += 1; + x.used = b.clock; + return x.bytes; + }; + return null; + } +}; + +/// What the authority last sent one peer of a pane of a kind: its rows' +/// hashes, its placements, and which strips of each raster it holds. +pub const ShadowSent = struct { + serial: u32 = 0, + cols: u16 = 0, + hashes: std.ArrayList(Hash) = .empty, + places: Hash = 0, + keys: std.ArrayList(struct { key: u64, have: u64 }) = .empty, + + pub fn deinit(s: *ShadowSent, gpa: std.mem.Allocator) void { + s.hashes.deinit(gpa); + s.keys.deinit(gpa); + s.* = .{}; + } + + /// The strips of `pl`'s raster over its `src` the peer lacks (a bit + /// each, `encodeStrip`'s `i`), counted sent now. + pub fn owed(s: *ShadowSent, gpa: std.mem.Allocator, pl: *const Place) !u64 { + const need = stripsOver(pl); + for (s.keys.items) |*k| if (k.key == pl.key) { + defer k.have |= need; + return need & ~k.have; + }; + try s.keys.append(gpa, .{ .key = pl.key, .have = need }); + return need; + } +}; + +/// Frame `f` of a pane (the pointer its paint asked for) for a peer that +/// was last sent `sent`: false, and nothing written, when it holds this +/// frame already. Its placements cross by key, their pixels as strips +/// before it (`ShadowSent.owed`), so a frame is small whatever it shows. +pub fn encodeShadow(gpa: std.mem.Allocator, sent: *ShadowSent, f: *const Frame, pointer: u8, w: *std.Io.Writer) !bool { + var hashes: std.ArrayList(Hash) = .empty; + errdefer hashes.deinit(gpa); + for (0..f.rows) |y| try hashes.append(gpa, std.hash.Wyhash.hash(0, std.mem.sliceAsBytes(f.cells[y * f.cols ..][0..f.cols]))); + const places = f.places[0..@min(f.n, 64)]; + var ph = std.hash.Wyhash.init(pointer); + for (places) |*pl| inline for (.{ pl.w, pl.h, pl.src, pl.at, pl.dst, pl.key }) |v| ph.update(std.mem.asBytes(&v)); + if (f.gpu.len != 0) ph.update(f.gpu); + const places_hash = ph.final(); + if (sent.cols == f.cols and std.mem.eql(Hash, sent.hashes.items, hashes.items) and sent.places == places_hash) { + hashes.deinit(gpa); + return false; + } + try w.writeInt(u16, f.cols, .little); + try w.writeInt(u16, f.rows, .little); + try w.writeByte(pointer); + for (hashes.items, 0..) |h, y| { + try w.writeInt(u64, h, .little); + // Held only at the same size: a peer's Shadow of another starts afresh. + const held = sent.cols == f.cols and sent.hashes.items.len == f.rows and sent.hashes.items[y] == h; + try w.writeByte(@intFromBool(!held)); + if (!held) for (f.cells[y * f.cols ..][0..f.cols]) |*cell| { + try w.writeAll(&cell.text); + try w.writeInt(u32, cell.fg, .little); + try w.writeInt(u32, cell.bg, .little); + try w.writeInt(u16, cell.attrs, .little); + try w.writeByte(cell.len); + try w.writeByte(cell.flags); + }; + } + try w.writeByte(@intCast(places.len)); + for (places) |pl| { + try w.writeInt(u32, pl.w, .little); + try w.writeInt(u32, pl.h, .little); + inline for (.{ pl.src.x, pl.src.y, pl.src.w, pl.src.h, pl.at.x, pl.at.y, pl.at.w, pl.at.h }) |v| try w.writeInt(u32, v, .little); + inline for (.{ pl.dst.x, pl.dst.y, pl.dst.w, pl.dst.h }) |v| try w.writeInt(u16, v, .little); + try w.writeInt(u64, pl.key, .little); + } + if (f.gpu.len > 4 << 20) return error.BadGpuFrame; + try w.writeInt(u32, @intCast(f.gpu.len), .little); + try w.writeAll(f.gpu); + sent.hashes.deinit(gpa); + sent.hashes = hashes; + sent.cols = f.cols; + sent.places = places_hash; + // The strips of the rasters this frame shows: a key gone is sent whole again. + var i: usize = 0; + while (i < sent.keys.items.len) { + const kept = for (places) |pl| { + if (pl.key == sent.keys.items[i].key) break true; + } else false; + if (kept) i += 1 else _ = sent.keys.swapRemove(i); + } + return true; +} + test "a kind's head is checked before a core takes it, and a core's kinds are its own" { const Fake = struct { fn paint(_: ?*anyopaque, _: [*c]const c.pa_window, _: [*c]c.pa_paint) callconv(.c) void {} @@ -1219,3 +1490,97 @@ const GpuPaint = struct { return 0; } }; + +test "a pane of a kind's frame a row taller or shorter is drawn whole at its peer, never a row it let go" { + const gpa = std.testing.allocator; + var cells: [2 * 3]ShadowCell = @splat(std.mem.zeroes(ShadowCell)); + cells[0] = .{ .text = "a".* ++ @as([7]u8, @splat(0)), .fg = 1, .bg = 2, .attrs = 0, .len = 1, .flags = c.PA_PAINTED }; + var f: Frame = .{ .cells = &cells, .cols = 2, .rows = 2 }; + var sent: ShadowSent = .{}; + defer sent.deinit(gpa); + var blobs: Blobs = .{}; + const sh = try gpa.create(Shadow); + sh.* = .{}; + defer sh.deinit(gpa); + var out: std.Io.Writer.Allocating = .init(gpa); + defer out.deinit(); + for ([_]u16{ 2, 3, 2 }) |rows| { + f.rows = rows; + out.clearRetainingCapacity(); + try std.testing.expect(try encodeShadow(gpa, &sent, &f, 0, &out.writer)); + _ = try sh.apply(gpa, out.written(), 1, &blobs); + try std.testing.expectEqualStrings("a", sh.cells[0].text[0..1]); + } +} + +test "a pane of a kind crosses as its frame, a row the peer holds as its hash, a raster by key after its strips over what it shows" { + const gpa = std.testing.allocator; + var cells: [3 * 2]ShadowCell = @splat(std.mem.zeroes(ShadowCell)); + cells[0] = .{ .text = "a".* ++ @as([7]u8, @splat(0)), .fg = 1, .bg = 2, .attrs = 0, .len = 1, .flags = c.PA_PAINTED }; + // A raster of three strips (4 MiB a strip at 1,024 px), of which it shows the second. + const w: u32 = 1024; + const per = stripRows(w); + const pixels = try gpa.alloc(u8, @as(usize, w) * per * 3 * 4); + defer gpa.free(pixels); + @memset(pixels, 5); + var f: Frame = .{ .cells = &cells, .cols = 3, .rows = 2, .n = 1 }; + f.buf[0] = std.mem.zeroInit(Place, .{ .rgba = pixels.ptr, .w = w, .h = per * 3, .src = .{ .x = 0, .y = per + 1, .w = w, .h = 10 }, .key = 9 }); + f.places = &f.buf; + var sent: ShadowSent = .{}; + defer sent.deinit(gpa); + var blobs: Blobs = .{}; + defer blobs.deinit(gpa); + const sh = try gpa.create(Shadow); + sh.* = .{}; + defer sh.deinit(gpa); + var out: std.Io.Writer.Allocating = .init(gpa); + defer out.deinit(); + const name = std.hash.Wyhash.hash(1, std.mem.asBytes(&f.buf[0].key)); + try std.testing.expectEqual(@as(u64, 0b010), try sent.owed(gpa, &f.buf[0])); + try encodeStrip(&f.buf[0], 1, &out.writer); + try std.testing.expect(out.written().len <= strip_max + 20); + try blobs.strip(gpa, name, out.written(), &.{}); + out.clearRetainingCapacity(); + try std.testing.expect(try encodeShadow(gpa, &sent, &f, 0, &out.writer)); + try std.testing.expectEqual(@as(u64, 0), try sh.apply(gpa, out.written(), 1, &blobs)); + try std.testing.expectEqualStrings("a", sh.cells[0].text[0..1]); + try std.testing.expectEqual(@as(u8, 5), sh.places.items[0].rgba[per * w * 4]); + // The same frame again: nothing to send, no strip owed. + out.clearRetainingCapacity(); + try std.testing.expect(!try encodeShadow(gpa, &sent, &f, 0, &out.writer)); + try std.testing.expectEqual(@as(u64, 0), try sent.owed(gpa, &f.buf[0])); + // Its src moves into the third strip: that one is owed, and a peer + // without it does not show the raster and asks for it, once. + f.buf[0].src.y = 2 * per + 1; + try std.testing.expectEqual(@as(u64, 0b100), try sent.owed(gpa, &f.buf[0])); + out.clearRetainingCapacity(); + try std.testing.expect(try encodeShadow(gpa, &sent, &f, 0, &out.writer)); + try std.testing.expect(out.written().len < 4 + 1 + 2 * 9 + 60 + 8); + try std.testing.expectEqual(name, try sh.apply(gpa, out.written(), 1, &blobs)); + try std.testing.expectEqual(@as(usize, 0), sh.places.items.len); + try std.testing.expectEqual(@as(u64, 0), try sh.apply(gpa, out.written(), 1, &blobs)); +} + +test "optional GPU frames cross shadows, change independently, and disappear" { + const gpa = std.testing.allocator; + var sent: ShadowSent = .{}; + defer sent.deinit(gpa); + const shadow = try gpa.create(Shadow); + shadow.* = .{}; + defer shadow.deinit(gpa); + var blobs: Blobs = .{}; + defer blobs.deinit(gpa); + var cell = std.mem.zeroes(ShadowCell); + var frame: Frame = .{ .cols = 1, .rows = 1, .cells = @as([*]ShadowCell, @ptrCast(&cell))[0..1], .gpu = "first scene" }; + var out: std.Io.Writer.Allocating = .init(gpa); + defer out.deinit(); + for ([_][]const u8{ "first scene", "second scene", "" }) |bytes| { + frame.gpu = bytes; + out.clearRetainingCapacity(); + try std.testing.expect(try encodeShadow(gpa, &sent, &frame, 0, &out.writer)); + _ = try shadow.apply(gpa, out.written(), 1, &blobs); + try std.testing.expectEqualStrings(bytes, shadow.gpu); + out.clearRetainingCapacity(); + try std.testing.expect(!try encodeShadow(gpa, &sent, &frame, 0, &out.writer)); + } +} diff --git a/src/Query.zig b/src/Query.zig index 4ae57691..4cede3c5 100644 --- a/src/Query.zig +++ b/src/Query.zig @@ -469,7 +469,7 @@ fn makeNameRows(p: *Pardes, id: usize) !void { var out: std.ArrayList(u8) = .empty; defer out.deinit(p.gpa); var rows: std.ArrayList(locations.Row) = .empty; - var spans: std.ArrayList(pardes.pager.Span) = .empty; + var spans: std.ArrayList(pardes.Term.Span) = .empty; errdefer spans.deinit(p.gpa); const chrome = p.bodyChrome(); const tint: pardes.CellStyle = .{ .fg = .{ .rgb = chrome.search_fg }, .bg = .{ .rgb = chrome.search_bg }, .bold = true }; diff --git a/src/Term.zig b/src/Term.zig new file mode 100644 index 00000000..a21c3d97 --- /dev/null +++ b/src/Term.zig @@ -0,0 +1,275 @@ +//! The terminal as the core sees it (docs/next-terminal.md, Phase 0): the +//! entries the core calls and the plain records they take and give. A +//! terminal pane holds a `*State` the core never looks into: what it knows +//! of one it is told here, as numbers, bytes and text. The emulator +//! (ghostty-vt) and what it brings stay behind this file, in src/term/; +//! this is the one file outside it that names a file inside it (and so +//! the one place Phase 1 turns into the module's registration). +const std = @import("std"); +const terminal = @import("term/terminal.zig"); +const pager = @import("term/pager.zig"); +const echo = @import("term/echo.zig"); +/// The screen state replicas are sent (its encoder, a terminal's versions, +/// what a peer holds, a replica's side), and its streams and soak for the +/// replica tests outside src/. +pub const screen_state = @import("term/screen_state.zig"); + +/// A terminal pane's emulator, its parse and what pardes keeps beside it. +pub const State = terminal.State; + +// ---- lifecycle ---- + +/// A new emulator, `cols` by `rows`, allocated with `gpa` (its own from +/// then on). +pub const open = terminal.open; +/// Its emulator and what it holds, freed; the kitty images' caches were +/// `gpa`'s. +pub const close = terminal.close; +/// When its next kitty animation frame is due (ms on the core's clock), as +/// its last drawn frame left it; null when nothing plays. +pub const due = terminal.due; +/// Loaded from a dump without its shell: its program's modes reset, its +/// history marked off from what the next shell prints. +pub const revive = terminal.revive; +/// The PNG resize workers kitty images are decoded with, started and +/// 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 }; + +// ---- input ---- + +/// One key for its program, as the program's keyboard protocol and modes +/// ask for it, written out. +pub const key = terminal.key; +/// One mouse event for its program, as the mode and format it set ask for +/// it; empty when the program does not hear of it. +pub const mouse = terminal.mouse; +/// A wheel turn for its program; null when the wheel is not the program's. +pub const wheel = terminal.wheel; +/// A paste as xterm makes one: three parts, the text between the brackets +/// when the program set 2004. +pub const paste = terminal.paste; +/// The modes its program set that the core decides by (`Modes`). +pub const modes = terminal.modes; +/// How far left or right a click on the prompt line moves the shell's +/// cursor, at the prompt the cursor is at. +pub const promptMoves = terminal.promptMoves; + +/// The key a frontend read (Event.zig). +pub const Key = @import("Event.zig").Key; +pub const MouseMods = struct { shift: bool = false, alt: bool = false, ctrl: bool = false }; +pub const MouseButton = enum { left, middle, right, wheel_up, wheel_down, wheel_left, wheel_right }; +pub const MouseAction = enum { press, release, motion }; +/// Cursor-key presses: so many left, so many right. +pub const Moves = struct { left: usize = 0, right: usize = 0 }; + +/// The modes a program set that the core decides by. +pub const Modes = struct { + /// It tracks the mouse itself (1000, 1002, 1003). + mouse: bool = false, + /// ...every move of it (1003). + all_motion: bool = false, + /// A wheel over it is its own: it tracks the mouse, or it is on the + /// alternate screen with alternate scroll (1007). + wheel: bool = false, + /// It wants to hear focus in and out (1004). + focus: bool = false, + /// It wants its pastes bracketed (2004). + bracketed_paste: bool = false, + /// It has the alternate screen (1049). + alternate: bool = false, +}; + +// ---- prompt and commands ---- + +/// Where its shell is in its command cycle (`Prompt`). +pub const prompt = terminal.prompt; +/// What the newest finished command printed (`CommandOutput`), read from +/// at most so many rows above its end. +pub const commandOutput = terminal.commandOutput; +/// The shell exited in the middle of a command: its output ends at the +/// cursor. +pub const endOutputHere = terminal.endOutputHere; + +/// Where a shell is in its command cycle, as pardes's own OSC 133 marks +/// tell it (marks carrying its `aid` alone: a nested shell's pass it by), +/// and what is at its cursor. All zero without a terminal. +pub const Prompt = struct { + phase: enum { none, prompt, input, running } = .none, + /// Commands started (C at the input phase), prompts drawn (B), and D + /// marks outside a running command (a line the shell handled without + /// starting it). + started: u32 = 0, + prompts: u32 = 0, + declined: u32 = 0, + /// The newest prompt continues an unfinished line (bash's PS2). + continuation: bool = false, + /// The newest command to end: which one, and its status if given. + finished: ?struct { seq: u32, status: ?i32 } = null, + /// The cursor is at a prompt's input, on either screen. + input_ready: bool = false, + /// ...and nothing is typed on its line up to the cursor. + input_empty: bool = false, + /// The cursor is on a prompt's row or at its input, on the primary + /// screen. + at_prompt: bool = false, +}; + +/// What a command printed. `text` is the caller's. +pub const CommandOutput = struct { + text: [:0]const u8, + /// Whether `text` starts where the command did. It does not when that + /// start is not there to read: cut off by the rows asked for, scrolled + /// out of the history or erased from it (ED 3), erased under it while + /// it ran, or never marked (a C or D on the alternate screen). + whole: bool, +}; + +// ---- text ---- + +/// Its whole scrollback as plain text, logical lines (rows it wrapped +/// joined again), ending in a newline: what its body reads and Save +/// writes. The caller's. +pub const scrollback = terminal.scrollback; +/// How long `scrollback` would be, counted without keeping it. +pub const scrollbackLen = terminal.scrollbackLen; +/// Its rows from the top of its history as text, a prompt's own cells cut +/// off (`Rows`). +pub const textRows = terminal.textRows; +/// The rows its view shows as text, prompts cut off or not. +pub const viewport = terminal.viewport; +/// How many bytes of one of its rows, as `viewport` and `textRows` give it +/// uncut, are the prompt it starts with. +pub const promptPrefix = terminal.promptPrefix; +/// A step read its rows: its replicas must hold them for the step's +/// replay. +pub const markRead = terminal.markRead; + +/// A terminal's rows as text: `rows` slices into `text`, which is a prefix +/// of `text_alloc` (a prompt cut off shortens the join), the last row the +/// empty one after the cursor's. +pub const Rows = struct { + text_alloc: []u8, + text: []const u8, + rows: [][]const u8, +}; + +// ---- the pager ---- + +/// A program's output, as a terminal reads it, paged (`pardes -`, a +/// /pager write): its printed text and its SGR colours as spans over it +/// (`Page`), every other control dropped. The emulator's own parse, so a +/// +Pager pages what a terminal pane would print. +pub const page = pager.parse; +pub const Page = pager.Page; +/// Bytes `start..end` of a page's text, drawn in `style`. +pub const Span = pager.Span; + +// ---- draw ---- +// +// ponytail: not yet narrowed to plain data (docs/next-terminal.md's draw +// row): these still take the core's Pardes, Surface and Pane, read the +// pane's edit copy and write the surface's cells and placements +// themselves. Phase 1 needs them as a cell hand-over (`paint`) and a +// placement list (`images`) first. + +/// Its program's colours over the body's rows, through the theme's +/// filter when the pane has it on. +pub const recolor = terminal.recolorAnsi; +/// Its kitty graphics over the body's rows, as placements. +pub const images = terminal.drawImages; +/// The Petscii builtin on it: its kitty graphics as glyph art, or back to +/// pixels; null for none. +pub const petscii = terminal.petscii; +pub const togglePetscii = terminal.togglePetscii; +/// Whether the screen showing holds any kitty graphics image. +pub const hasImages = terminal.hasImages; +/// A program's colours mapped to the theme (Filter): a terminal's cells +/// or a +Pager's spans (`spanColor`). +pub const Filter = terminal.FilteredColors; +/// The theme's 256 colours as the filter maps onto them, kept while the +/// theme is the same (`Pardes.tty_filter_palette`). +pub const FilterPalette = terminal.FilterPalette; +/// A palette index as the theme draws it: its own sixteen, else the index. +pub const palColor = terminal.palColor; + +// ---- its replicas ---- + +/// What a peer is owed of it, a delta against what the peer was sent. +pub const encode = terminal.encode; +/// Rows of it a replica holds as holes. +pub const encodeRows = terminal.encodeRows; +/// A peer's track of it let go. +pub const untrack = terminal.untrack; +/// Whether a step read its rows since `clearRead`. +pub const wasRead = terminal.wasRead; +pub const clearRead = terminal.clearRead; +/// A replica's side: a delta applied, rows applied, the rows its view +/// shows, rows blank until they come. +pub const apply = terminal.apply; +pub const applyRows = terminal.applyRows; +pub const shown = terminal.shown; +pub const blank = terminal.blank; +pub const dumpScreen = terminal.dumpScreen; +pub const Encoder = screen_state.Encoder; +pub const Track = screen_state.Track; +pub const Peer = screen_state.Peer; +pub const Replica = screen_state.Replica; +/// A replica's keys into a terminal drawn at once, before its authority +/// says (predicted echo). +pub const Echo = echo.Echo; + +test { + _ = terminal; + _ = pager; + _ = echo; + _ = screen_state; +} diff --git a/src/body_layer.zig b/src/body_layer.zig index dbf0156d..6c0ffcea 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)) @@ -50,7 +50,7 @@ fn paintTerminalSelection(p: *Pardes, s: *Surface, pane: *Pane, r: Rect, rows: [ lo -|= row.prompt_bytes; hi -|= row.prompt_bytes; } else if (!row.raw_terminal and raw) { - const prefix = panes.terminal.promptPrefixBytes(pane, source_row, line); + const prefix = panes.Term.promptPrefix(pane.terminal, source_row, line); lo += prefix; hi += prefix; } @@ -79,7 +79,7 @@ fn pastView(pane: *Pane, body: []const u8, line: i32, row: i32, at: i32, col: i3 fn paintSourceSelection(p: *Pardes, s: *Surface, pane: *Pane, r: Rect, rows: []const Pane.PointerRow, bg: [3]u8, fg: ?[3]u8) void { if (pane.isTerminal()) return paintTerminalSelection(p, s, pane, r, rows, bg, fg); - const terminal_lines = if (pane.file == null) panes.terminal.cursorLines(p, pane) catch return else &.{}; + const terminal_lines = if (pane.file == null) edit.terminalLines(p, pane) catch return else &.{}; const tx = r.x + config.GUTTER; const width = r.w -| config.GUTTER; const body_y = p.bodyTop(pane, r); @@ -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 @@ -345,11 +344,11 @@ pub fn renderBody(p: *Pardes, s: *Surface, arena: std.mem.Allocator, pane: *Pane pane.places.paint(p, s, pane, r, body_h); panes.Query.paint(p, s, pane, r, body_h); } else if (pane.isTerminal()) { - panes.terminal.recolorAnsi(p, s, pane, r, tx, tw, body_h, body); + panes.Term.recolor(p, s, pane, r, tx, tw, body_h, body); panes.File.recolorDiffOutput(p, s, pane, r, tx, tw, body_h, body); } tz_color.end(); - if (pane.isTerminal()) panes.terminal.drawImages(p, s, pane, id, tx, tw, body_y, body_h); + if (pane.isTerminal()) panes.Term.images(p, s, pane, id, tx, tw, body_y, body_h); const sel_btn = buttonTints(th); if (p.look_hover_preview) |preview| { @@ -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 }; } } @@ -541,5 +546,104 @@ pub fn bodyText(arena: std.mem.Allocator, pane: *Pane) ![]const u8 { return buf; } if (pane.file) |*f| return panes.File.bodyText(arena, pane, f); - return panes.terminal.bodyText(arena, pane); + // A terminal's: the rows its view shows (outside raw mode its prompts + // cut off), the edit copy's lines over the rows the copy covers. + const vp: []const []const u8 = if (pane.terminal) |state| try panes.Term.viewport(state, arena, pane.body.mode != .tty) else &.{}; + const len = fillBody(null, pane, vp); + const out = try arena.alloc(u8, len); + const filled = fillBody(out, pane, vp); + std.debug.assert(filled == out.len); + return out; +} + +pub const BodyRow = union(enum) { + grid: i32, + edit: struct { line: []const u8, idx: usize }, +}; + +/// A terminal pane's body rows, top down: a row of its emulator's view +/// (`grid`, its viewport row), or a line of the edit copy standing in for +/// the rows it covers (`edit`). +pub const BodyWalk = struct { + pane: *Pane, + goff: i32, + g: i32, + /// the buffer can start above the viewport: drop the lines scrolled past + skip: usize, + n: usize = 0, + lines: ?std.mem.SplitIterator(u8, .scalar) = null, + covered: i32 = 0, + line_idx: usize = 0, + + pub fn init(pane: *Pane) BodyWalk { + const off = pane.scroll(); + const goff: i32 = @intCast(panes.Term.grid(pane.terminal).offset); + return .{ + .pane = pane, + .goff = goff, + .g = if (pane.body.mode == .tty) goff + pane.pan else pane.gridRow(off), + .skip = if (pane.ovl) |o| @intCast(@max(0, off - pane.surfRow(o.row))) else 0, + }; + } + + pub fn next(w: *BodyWalk) ?BodyRow { + while (w.n < w.pane.rows) { + if (w.lines) |*it| { + if (it.next()) |line| { + const idx = w.line_idx; + w.line_idx += 1; + // Lines scrolled off the top still count: the index names a + // line of the BUFFER, not of the visible body. + if (w.skip > 0) { + w.skip -= 1; + continue; + } + w.n += 1; + return .{ .edit = .{ .line = line, .idx = idx } }; + } + // The buffer stands in for `rows` shell rows however many lines + // it actually spelled, which is the whole slide. + w.g += w.covered; + w.skip = 0; + w.lines = null; + continue; + } + if (w.pane.body.mode != .tty) if (w.pane.ovl) |o| if (w.g == o.row) { + w.lines = std.mem.splitScalar(u8, o.text, '\n'); + w.covered = o.rows; + w.line_idx = 0; + continue; + }; + const vi = w.g - w.goff; + w.g += 1; + w.n += 1; + return .{ .grid = vi }; + } + return null; + } +}; + +/// Run the terminal body row walk. A null destination counts bytes; a slice +/// fills the exact allocation made from that count. +fn fillBody(dst: ?[]u8, pane: *Pane, viewport: []const []const u8) usize { + var walk: BodyWalk = .init(pane); + var written: usize = 0; + var first = true; + while (walk.next()) |row| { + if (!first) { + if (dst) |out| out[written] = '\n'; + written += 1; + } + first = false; + const bytes = switch (row) { + .edit => |e| e.line, + .grid => |vi| if (vi >= 0 and @as(usize, @intCast(vi)) < viewport.len) + viewport[@intCast(vi)] + else + "", + }; + if (dst) |out| @memcpy(out[written..][0..bytes.len], bytes); + written += bytes.len; + } + return written; } diff --git a/src/builtins.zig b/src/builtins.zig index bb91d0b0..d106330e 100644 --- a/src/builtins.zig +++ b/src/builtins.zig @@ -427,7 +427,12 @@ pub const Kill = struct { for (c.p.panes, 0..) |slot, id| { const pane = slot orelse continue; const command: ?[]const u8 = if (pane.command) |line| (if (pane.command_done) null else line) else null; - if (command == null and !panes.terminal.commandRunning(pane)) continue; + // The command pardes last typed here, running now. + const typed_runs = if (pane.sent_command) |sent| typed: { + const at = panes.Term.prompt(pane.terminal); + break :typed at.phase == .running and at.started == sent.seq; + } else false; + if (command == null and !typed_runs) continue; running = true; const first = if (command) |line| first: { const said = std.mem.trim(u8, line, " \t"); @@ -747,13 +752,13 @@ pub const Petscii = struct { pub const takes_arg = true; pub fn run(c: Ctx) void { // `on|off` sets it, as the tag's `petscii:on` reads; none flips it. - const now = if (c.pane.addon) |k| k.art.glyph else panes.terminal.petscii(c.pane) orelse false; + const now = if (c.pane.addon) |k| k.art.glyph else panes.Term.petscii(c.pane.terminal) orelse false; if (c.arg != null) { const want = stateArg(c, OnOff, "Petscii", "on or off") orelse return; if ((want == .on) == now) return; } if (c.pane.addon) |k| k.art.glyph = !k.art.glyph; - panes.terminal.togglePetscii(c.pane); + if (c.pane.terminal) |state| panes.Term.togglePetscii(state); } }; diff --git a/src/colors.zig b/src/colors.zig index e2e00ea8..d3ab82e2 100644 --- a/src/colors.zig +++ b/src/colors.zig @@ -12,7 +12,7 @@ const MAX_PANES = pardes.MAX_PANES; const BOX_H = pardes.BOX_H; const Pardes = pardes.Pardes; -/// The 256-colour palette a terminal starts from (ghostty-vt's default): +/// The 256-colour palette a terminal starts from (its emulator's default): /// sixteen named colours, a 6x6x6 cube at xterm's levels (0, then 95 to /// 255 by 40) and a ramp of 24 greys from 8 by 10. pub const xterm: [256][3]u8 = blk: { diff --git a/src/draw.zig b/src/draw.zig index 2fabff06..a73613ac 100644 --- a/src/draw.zig +++ b/src/draw.zig @@ -4,6 +4,7 @@ //! chips, the workspace and column tags, the tag layers, drag overlays, the //! debug box, then the cursor. const std = @import("std"); +const vaxis = @import("vaxis"); const pardes = @import("pardes.zig"); const layout = @import("layout.zig"); const config = @import("config.zig"); @@ -58,7 +59,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 +74,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; @@ -239,8 +240,8 @@ pub fn render(p: *Pardes, arena: std.mem.Allocator) !*Surface { const v = p.view(); const taped = pardes.tape.enter(p, .render); defer pardes.tape.leave(p, taped); - panes.terminal.drawing = true; - defer panes.terminal.drawing = false; + edit.drawing = true; + defer edit.drawing = false; panes.File.refreshHighlights(p); const s = &p.surface; const ncells = @as(usize, v.screen_w) * v.screen_h; @@ -322,9 +323,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; @@ -1236,7 +1237,7 @@ test "a wide glyph cut by a tag's or a notice's edge is joined into the grid as const head = !cell.default and cell.len > 1 and i + 1 < row.len and !row[i + 1].default and row[i + 1].len == 0; // A spacer has its head before it; a head its spacer after. if (spacer) try std.testing.expect(i > 0 and row[i - 1].len > 1); - if (i + 1 == row.len) try std.testing.expect(!head and !(cell.len > 1 and panes.File.utf8Width(cell.grapheme()) == 2)); + if (i + 1 == row.len) try std.testing.expect(!head and !(cell.len > 1 and vaxis.gwidth.gwidth(cell.grapheme(), .unicode) == 2)); } // The right edge of each is the band, blank where a glyph was cut. try std.testing.expectEqual(FontRole.tagline, row[row.len - 1].style.font_role); diff --git a/src/dump.zig b/src/dump.zig index a880c7e1..31765836 100644 --- a/src/dump.zig +++ b/src/dump.zig @@ -74,7 +74,7 @@ pub var terminal_gpa: ?std.mem.Allocator = null; // // A dump is everything the session is but what is the host's, the frame's // or worked out again: its panes with their text and undo, terminals with -// their screens, history and kitty images (ghostty's snapshot), registers, +// their screens, history and kitty images (the emulator's snapshot), registers, // places, tags, layout and settings. It crosses builds: its fields are // matched by name. It is an image (Db.zig): a database in memory the walk // writes by name (walk.Put), which the state file keeps under a label, @@ -490,10 +490,8 @@ fn loadImage(gpa: std.mem.Allocator, opts: Options, bytes: []const u8, notes: ?* /// build's dump could not give): a terminal, a new emulator for its shell. fn ensureKind(p: *Pardes, pane: *pardes.panes.Pane) !void { if (pane.terminal != null or pane.file != null or pane.addon != null or pane.pdf != null) return; - const fresh = try pardes.panes.terminal.create(p.gpa, @max(1, pane.cols), @max(1, pane.rows)); - pane.terminal = fresh.terminal; - fresh.terminal = null; - p.gpa.destroy(fresh); + if (pardes.tape.authorityOnly("open a terminal")) return error.OutOfMemory; + pane.terminal = try pardes.Term.open(pardes.panes.emulatorGpa(p.gpa), @max(1, pane.cols), @max(1, pane.rows)); } /// The panes a column lists that are not there (another build's dump left @@ -660,7 +658,18 @@ fn revivePane(p: *Pardes, id: usize, pane: *pardes.panes.Pane, was_on_disk: bool } if (comptime isolated) return; if (pane.cwdSlice().len > effect_path_cap) return; - pardes.panes.terminal.reviveShell(pane); + // Its shell not there, made ready for a new one: what the old + // shell was, ran and said is gone with it (the REPL it ran, the + // Term+ word naming it), and the pane waits for the new one like + // any new terminal (a line queued for the old one goes to it). + pardes.Term.revive(pane.terminal.?); + pane.shell_spoke = false; + pane.had_shell = false; + pane.shell_failed = false; + pane.shell_tail_len = 0; + pane.repl = null; + pane.sent_command = null; + pane.pending_command.wait = .spawn; p.emitSpawn(id, pane.serial, pane.cwdSlice()); return; } @@ -719,7 +728,7 @@ pub fn savePane(gpa: std.mem.Allocator, pane: *pardes.panes.Pane, slim: bool) ![ pub fn loadPane(p: *Pardes, id: usize, bytes: []const u8) !*pardes.panes.Pane { var l = try walk.Load(&.{pardes.panes.Pane}).init(p.gpa, bytes); defer l.deinit(); - l.allocs = .{ .image = p.image_gpa, .terminal = pardes.panes.terminal.emulatorGpa(p.gpa) }; + l.allocs = .{ .image = p.image_gpa, .terminal = pardes.panes.emulatorGpa(p.gpa) }; const pane = try p.gpa.create(pardes.panes.Pane); errdefer { l.rollback(); @@ -989,19 +998,19 @@ test "a pane restored with unsaved text is asked about by Exit, Restore, Del and test "a loaded terminal's history stays above its banner, the cursor where it was" { 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 }); 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); + const text = try pardes.Term.scrollback(q.panes[0].?.terminal, gpa); defer gpa.free(text); try std.testing.expect(std.mem.indexOf(u8, text, "one\ntwo\n") != null); try std.testing.expect(std.mem.indexOf(u8, text, "two").? < std.mem.indexOf(u8, text, "restored history").?); @@ -1010,11 +1019,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); @@ -1026,14 +1034,16 @@ 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].?)); - try std.testing.expect(q.panes[0].?.terminal.?.vt.screens.active_key == .alternate); + 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(pardes.Term.modes(q.panes[0].?.terminal).alternate); while (q.nextEffect()) |e| try std.testing.expect(e != .spawn); // Not kept, the same terminal is a new shell's under its history. kept[0] = false; const r = try resumeFromDump(gpa, .{ .tty_only = true, .cols = 40, .rows = 12 }, bytes, &kept); defer r.deinit(); - try std.testing.expect(r.panes[0].?.terminal.?.vt.screens.active_key == .primary); + try std.testing.expect(!pardes.Term.modes(r.panes[0].?.terminal).alternate); } test "a loaded session asks its host for its font again: a new process has only its built-in face" { diff --git a/src/edit.zig b/src/edit.zig index c5466531..5b94c0d8 100644 --- a/src/edit.zig +++ b/src/edit.zig @@ -105,11 +105,11 @@ pub fn clipRequest(p: *Pardes, id: usize, mode: Paste) void { } /// Text pasted, yanked or sent into the program at `id`, as xterm pastes -/// (terminal.encodePaste). +/// (Term.paste). pub fn typeToTty(p: *Pardes, id: usize, pane: *const Pane, text: []const u8) void { if (text.len == 0) return; const cp = p.scratch.allocator().dupe(u8, text) catch |err| return p.reportError(id, "paste", err); - for (panes.terminal.encodePaste(pane, cp)) |part| if (part.len > 0) p.emitWrite(id, part); + for (panes.Term.paste(pane.terminal, cp)) |part| if (part.len > 0) p.emitWrite(id, part); } pub fn applyPaste(p: *Pardes, whole: []const u8) Error!void { @@ -222,7 +222,7 @@ pub fn capturePointerSelection(p: *Pardes, pane: *Pane, slot: usize) !void { // Refresh the source map before translating the rendered rectangle. const raw = pane.isTerminal() and pane.body.mode == .tty; const body = try body_layer.bodyText(p.scratch.allocator(), pane); - const terminal_lines = if (pane.file == null and !raw) try panes.terminal.cursorLines(p, pane) else &.{}; + const terminal_lines = if (pane.file == null and !raw) try terminalLines(p, pane) else &.{}; const first = @max(0, @min(gesture.r0, gesture.r1) - pane.tag_rows); const logical_rows = if (pane.body_rows > 0) pane.body_rows else pane.rows; const last = @min(@as(i32, logical_rows) - 1, @max(gesture.r0, gesture.r1) - pane.tag_rows); @@ -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 }; @@ -260,7 +260,7 @@ pub fn capturePointerSelection(p: *Pardes, pane: *Pane, slot: usize) !void { .hi = if (right < prefix) lo else if (cols.hi == null) end else @min(end, modal.nextGrapheme(line, at)), .to_edge = cols.hi == null, .raw_terminal = raw, - .prompt_bytes = if (raw) panes.terminal.promptPrefixBytes(pane, source.line, line) else 0, + .prompt_bytes = if (raw) panes.Term.promptPrefix(pane.terminal, source.line, line) else 0, }; } pane.next_pointer_selection += 1; @@ -275,7 +275,7 @@ pub fn selectionText(p: *Pardes, pane: *Pane, sl: Pane.Sel) ![]const u8 { const arena = p.scratch.allocator(); if (pane.rawPointerText(sl)) |text| return arena.dupe(u8, text); if (pane.pointerSelection(sl)) |rows| { - const terminal_lines = if (pane.file == null) try panes.terminal.cursorLines(p, pane) else &.{}; + const terminal_lines = if (pane.file == null) try terminalLines(p, pane) else &.{}; var total: usize = rows.len -| 1; for (rows) |row| { const line = pointerSourceLine(pane, terminal_lines, row.row); @@ -386,7 +386,7 @@ pub fn paneCursorLines(p: *Pardes, t: *Text) Error![]const []const u8 { const pane = t.pane() orelse return &.{}; if (pane.file) |*f| return panes.File.cursorLines(arena, pane, f); if (pane.addon != null) return &.{}; - return panes.terminal.cursorLines(p, pane); + return terminalLines(p, pane); } pub fn paneByteAtDisplay(p: *Pardes, t: *Text, row: i32, from_raw: i32, display_col: i32) i32 { @@ -418,6 +418,111 @@ pub fn pinPaneCursor(p: *Pardes, t: *Text) void { t.cur_col = paneByteAtDisplay(p, t, t.cur_row, 0, t.cur_col); } +// ---- a terminal's rows, and the copy of them an edit makes ---- + +/// Set while a frame is drawn: what it reads is no step's. +pub var drawing = false; + +/// A terminal's rows as text (`Term.rows`), kept for one pane until its +/// grid moves. Returned slices remain valid until the next cache rebuild +/// or reset. +pub const RowsCache = struct { + /// whose grid this describes; null = the slot is free + pane: ?*const Pane = null, + /// the rows joined by '\n' — `flatSurface` hands this back verbatim + /// instead of rebuilding the join on every keystroke + text: []const u8 = &.{}, + /// slices INTO `text`, absolute grid rows from 0 + rows: [][]const u8 = &.{}, + /// `text` is a prefix of this: blanking a prompt row shortens the join, + /// and the slack is not worth a second allocation to reclaim + text_alloc: []u8 = &.{}, + stale: bool = false, + + pub fn reset(c: *RowsCache, gpa: std.mem.Allocator) void { + if (c.text_alloc.len > 0) gpa.free(c.text_alloc); + if (c.rows.len > 0) gpa.free(c.rows); + c.* = .{}; + } + + /// Free a stale entry. Called at the top of `update`, and nowhere else. + pub fn sweep(c: *RowsCache, gpa: std.mem.Allocator) void { + if (c.stale) c.reset(gpa); + } + + /// `pane`'s grid moved: the entry no longer describes it. + pub fn markStale(c: *RowsCache, pane: *const Pane) void { + if (c.pane == pane) c.stale = true; + } + + pub fn dropPane(c: *RowsCache, pane: *const Pane) void { + if (c.pane != pane) return; + c.pane = null; + c.stale = true; + } +}; + +const empty_grid = [1][]const u8{""}; + +/// A terminal pane's rows from the top of its history (`Term.rows`), kept +/// in `Pardes.shell_rows` while its grid holds still. +pub fn shellRows(p: *Pardes, pane: *Pane) ![]const []const u8 { + const state = pane.terminal orelse return &empty_grid; + pardes.tape.touchTerminal(); + // A step's read whether the rows are kept or made: a client that came + // since holds them as holes, and is sent them (Screens.fill). + if (!drawing) panes.Term.markRead(state); + const c = &p.shell_rows; + if (!c.stale and c.pane == pane) return c.rows; + // Another pane's rows, or a dropped pane's still waiting for the step's + // sweep (dropPane keeps them, as they may still be borrowed): this + // step's rows are scratch, and nothing in the slot is written over. + if (c.pane != null or c.text_alloc.len > 0 or c.rows.len > 0) { + c.stale = true; + return (try panes.Term.textRows(state, p.scratch.allocator(), p.scratch.allocator())).rows; + } + const built = try panes.Term.textRows(state, p.gpa, p.scratch.allocator()); + c.* = .{ + .pane = pane, + .text = built.text, + .rows = built.rows, + .text_alloc = built.text_alloc, + }; + return c.rows; +} + +/// The full modal motion surface: shell history with the live edit overlay +/// spliced into the rows it covers. +pub fn terminalLines(p: *Pardes, pane: *Pane) ![]const []const u8 { + const rows = try shellRows(p, pane); + if (pane.ovl == null) return rows; + var last = rows.len; + if (pane.ovl) |overlay| + last = @max(last, @as(usize, @intCast(@max(0, overlay.row + overlay.rows)))); + var count = last; + if (pane.ovl) |overlay| { + if (overlay.row >= 0 and @as(usize, @intCast(overlay.row)) < last) + count = count - @min( + @as(usize, @intCast(overlay.rows)), + last - @as(usize, @intCast(overlay.row)), + ) + @max(1, modal.lineCount(overlay.text)); + } + const lines = try p.scratch.allocator().alloc([]const u8, count); + var n: usize = 0; + var grid_row: usize = 0; + while (grid_row < last) : (grid_row += 1) { + if (pane.ovl) |overlay| if (overlay.row >= 0 and grid_row == @as(usize, @intCast(overlay.row))) { + var overlay_lines = std.mem.splitScalar(u8, overlay.text, '\n'); + while (overlay_lines.next()) |line| : (n += 1) lines[n] = line; + grid_row += @intCast(overlay.rows - 1); + continue; + }; + lines[n] = if (grid_row < rows.len) rows[grid_row] else ""; + n += 1; + } + return lines[0..n]; +} + pub fn flatSurface(p: *Pardes, t: *Text) Error![]const u8 { switch (t.what) { .body => {}, @@ -429,8 +534,25 @@ pub fn flatSurface(p: *Pardes, t: *Text) Error![]const u8 { const pane = t.pane() orelse return ""; if (pane.file) |f| return f.content; if (pane.addon != null) return ""; - const lines = try panes.terminal.cursorLines(p, pane); - return panes.terminal.flatSurface(p, pane, lines); + const lines = try terminalLines(p, pane); + // The kept rows' own join when the lines are them (no edit copy), not + // made again on every keystroke; a join of them in scratch else. + const cache = &p.shell_rows; + if (!cache.stale and cache.pane == pane and + lines.ptr == cache.rows.ptr and lines.len == cache.rows.len) return cache.text; + var total: usize = if (lines.len > 0) lines.len - 1 else 0; + for (lines) |line| total += line.len; + const text = try p.scratch.allocator().alloc(u8, total); + var at: usize = 0; + for (lines, 0..) |line, i| { + if (i > 0) { + text[at] = '\n'; + at += 1; + } + @memcpy(text[at..][0..line.len], line); + at += line.len; + } + return text; } pub fn paneWrapWidth(p: *const Pardes, t: *Text) usize { @@ -455,7 +577,71 @@ fn editText(p: *Pardes, t: *Text, lo: i32, hi: i32, col: i32) Error!?panes.EditT const pane = t.pane() orelse return null; if (pane.file) |f| return .{ .text = f.content, .row0 = 0 }; if (pane.addon != null) return null; - return panes.terminal.editText(p, pane, lo, hi, col); + // A terminal's: its edit copy (`Pane.ovl`), made from the rows `lo` to + // `hi` or widened over them, with one exact allocation; the rows are + // scratch-owned or borrowed, only the joined text is kept. + const want_lo = @max(0, @min(lo, hi)); + const want_hi = @max(want_lo, @max(lo, hi)); + const fresh = pane.ovl == null; + const old: Text.EditBuffer = pane.ovl orelse .{ .row = want_lo, .rows = 1, .text = &.{} }; + const lines: i32 = if (fresh) 1 else @intCast(modal.lineCount(old.text)); + const up = old.row - want_lo; + const down = want_hi - (old.row + lines - 1); + const extending = fresh or up > 0 or down > 0; + var row0 = old.row; + var covered = old.rows; + var text = old.text; + var owned = false; + if (extending) { + const rows = try shellRows(p, pane); + row0 = old.row - @max(0, up); + covered = old.rows + @max(0, up) + @max(0, down); + const up_len: usize = @intCast(@max(0, up)); + const down_len: usize = @intCast(@max(0, down)); + const parts = try p.scratch.allocator().alloc([]const u8, up_len + 1 + down_len); + for (parts[0..up_len], 0..) |*part, i| { + const src = @as(usize, @intCast(row0)) + i; + part.* = if (src < rows.len) rows[src] else ""; + } + const middle: usize = @intCast(old.row); + parts[up_len] = if (fresh) + (if (middle < rows.len) rows[middle] else "") + else + old.text; + for (parts[up_len + 1 ..], 0..) |*part, i| { + const src = @as(usize, @intCast(old.row + old.rows)) + i; + part.* = if (src < rows.len) rows[src] else ""; + } + text = try std.mem.join(p.gpa, "\n", parts); + owned = true; + } + + const row: usize = @intCast(@max(0, want_lo - row0)); + const line_len: i32 = @intCast(modal.lineSlice(text, row).len); + if (col > line_len) { + const spaces = p.scratch.allocator().alloc(u8, @intCast(col - line_len)) catch { + if (owned) p.gpa.free(text); + return null; + }; + @memset(spaces, ' '); + const padded = modal.insertAt(p.gpa, text, .{ .row = row, .col = @intCast(line_len) }, spaces) catch { + if (owned) p.gpa.free(text); + return null; + }; + if (owned) p.gpa.free(text); + text = padded; + owned = true; + } + if (owned) { + if (pane.ovl) |overlay| p.gpa.free(overlay.text); + pane.ovl = .{ .row = row0, .rows = covered, .text = text }; + } + // A terminal's text is its program's: edited here it is a copy, to run + // with Tab or B2, gone when the program draws again. Said at its first + // edit, so it never looks like an edit that was lost. + if (fresh) for (p.panes, 0..) |slot, id| if (slot == pane) + p.setMessage(id, "a copy of the terminal's text: Tab or B2 runs it; what the program draws next replaces it (Ctrl-b types to the program)"); + return .{ .text = pane.ovl.?.text, .row0 = pane.ovl.?.row }; } fn editTextEol(p: *Pardes, t: *Text, b: Bounds) Error!?panes.EditText { @@ -533,7 +719,14 @@ fn setEditTextSpan(p: *Pardes, t: *Text, new: []u8, known_end: ?modal.Cursor, sp const end = known_end orelse modal.positionAt(new, new.len - found.?.tail); t.last_edit = .{ .row = @as(i32, @intCast(end.row)) + row0, .col = @intCast(end.col) }; if (pane.file) |*f| return panes.File.setContentSpan(p, f, new, found); - panes.terminal.setEditText(p, pane, new); + // A terminal's edit copy rewritten: the text it replaces freed. + const overlay = if (pane.ovl) |*value| value else return retireEditText(p, new); + for (0..pane.sel.len) |button| { + pane.clearPointerSelection(button); + pane.sel[button].state = .none; + } + p.gpa.free(overlay.text); + overlay.text = new; } /// The file whose text `t` edits in place (File.replace), the bytes it puts @@ -1863,7 +2056,7 @@ pub fn pushUndo(p: *Pardes, t: *Text) error{OutOfMemory}!void { } const pane = t.pane() orelse return; if (pane.file != null) return panes.File.pushUndo(p, pane); - return panes.terminal.pushUndo(p, pane); + return pane.body.remember(p.gpa, pane.ovl); } /// Undo (back) or redo one step of the text's history: its file's, its @@ -1873,7 +2066,11 @@ pub fn undoStep(p: *Pardes, t: *Text, back: bool) error{OutOfMemory}!void { if (t.what != .body) return; const pane = t.pane() orelse return; if (pane.file != null) return panes.File.undoStep(p, pane, back); - return panes.terminal.undoStep(p, pane, back); + // A terminal's edit copy, as it was. + const to = (try pane.body.step(p.gpa, pane.ovl, back)) orelse return; + if (pane.ovl) |o| p.gpa.free(o.text); + pane.ovl = to.ovl; + pane.ensureCursorVisible(); } /// Undo or redo an edit of a text's own characters; stepping back past its diff --git a/src/exec.zig b/src/exec.zig index ece4f98d..b4c20f45 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))))) @@ -144,7 +144,7 @@ pub fn operandAt(p: *Pardes, pane: *Pane, clicked: Pane.Sel, borrow: bool, for_l lo -|= span.prompt_bytes; hi -|= span.prompt_bytes; } else if (!span.raw_terminal and raw) { - const prefix = panes.terminal.promptPrefixBytes(pane, row, raw_line); + const prefix = panes.Term.promptPrefix(pane.terminal, row, raw_line); lo += prefix; hi += prefix; } @@ -587,7 +587,7 @@ pub fn sendToRepl(p: *Pardes, from: usize, to: usize, text: []const u8) void { var said: pardes.Kind.Buf(128) = .{}; return p.setMessage(from, said.print("Repl: {d} bytes is more than can be sent at once; send less", .{n})); } - const pasted = panes.terminal.bracketedPaste(dst); + const pasted = panes.Term.modes(dst.terminal).bracketed_paste; edit.typeToTty(p, to, dst, clean[0..n]); // A Python block whose last line is indented, or a bare header, is not // over at one Enter, pasted into 3.13's REPL or typed into the old one: @@ -610,7 +610,7 @@ pub fn sendToRepl(p: *Pardes, from: usize, to: usize, text: []const u8) void { dst.repl_enter_due_ns = clockNow(p) + repl_enter_wait_ns; } else for (0..enters) |_| p.emitWrite(to, "\r"); // Line by line, a blank line inside a Python block ends the block. - if (!panes.terminal.bracketedPaste(dst) and !dst.repl_warned and (if (dst.repl) |r| r.lang == python_lang else false) and + if (!panes.Term.modes(dst.terminal).bracketed_paste and !dst.repl_warned and (if (dst.repl) |r| r.lang == python_lang else false) and std.mem.indexOfScalar(u8, text, '\n') != null) { dst.repl_warned = true; @@ -655,7 +655,8 @@ pub fn takesCommandLine(p: *const Pardes, id: usize) bool { // idle, EMPTY prompt is typed at; otherwise a new pane runs the line. // (Text in pardes's own edit buffer is not the shell's yet: an exec of // it, or of anything, types only what it runs.) - if (panes.terminal.promptInputReady(pane) and !panes.terminal.promptInputEmpty(pane)) return false; + const at = panes.Term.prompt(pane.terminal); + if (at.input_ready and !at.input_empty) return false; return !p.hostTtyTaken(id); } @@ -696,9 +697,19 @@ pub fn executeFrom(p: *Pardes, id: usize, txt: []const u8, from_body: bool) ?usi // command pane in the session's directory, never typed into whichever // terminal has the keyboard. if (p.exec_header or !takesCommandLine(p, id)) return runCommand(p, id, cmd); - panes.terminal.padOutputBelowEdits(p, id); - panes.terminal.noteCommand(pane, cmd); - if (panes.terminal.queuePendingCommand(pane, cmd) catch |err| { + // At a prompt with typed text below it: the output area padded with + // newlines so the command's output does not overwrite the buffer. + if (pane.ovl) |o| if (pane.isTerminal()) if (pane.terminal) |state| if (panes.Term.prompt(state).at_prompt) { + // the buffer's LAST surface row: its lines may outnumber the shell + // rows it covers, and it is the bottom one output must clear + const max_row = o.row + @as(i32, @intCast(modal.lineCount(o.text))) - 1; + const grid = panes.Term.grid(state); + const cursor_abs = pane.surfRow(@as(i32, @intCast(grid.offset)) + @as(i32, grid.cursor_y)); + const pad = std.math.clamp(max_row - cursor_abs, 0, @as(i32, pane.rows)); + for (0..@intCast(pad)) |_| p.emitWrite(id, "\r"); + }; + pane.noteCommand(cmd); + if (pane.queuePendingCommand(cmd) catch |err| { p.reportError(id, "queue command", err); return id; }) return id; @@ -756,10 +767,10 @@ pub fn runCommand(p: *Pardes, from: usize, line: []const u8) ?usize { // What the last program left the emulator in goes first: the // alternate screen left (only if it is there: leaving restores a // saved cursor), mouse reports and bracketed paste off, the cursor - // shown, colours reset. (Not DECSTR: ghostty's stream does not + // shown, colours reset. (Not DECSTR: the emulator'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.Term.modes(pane.terminal).alternate) 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()); @@ -809,11 +820,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 @@ -54,7 +54,7 @@ const source_files = [_]Source{ .{ .path = "src/File.zig", .contents = @embedFile("File.zig") }, .{ .path = "src/Output.zig", .contents = @embedFile("Output.zig") }, .{ .path = "src/mini.zig", .contents = @embedFile("mini.zig") }, - .{ .path = "src/terminal.zig", .contents = @embedFile("terminal.zig") }, + .{ .path = "src/term/terminal.zig", .contents = @embedFile("term/terminal.zig") }, .{ .path = "src/layout.zig", .contents = @embedFile("layout.zig") }, .{ .path = "src/fs.zig", .contents = @embedFile("fs.zig") }, .{ .path = "src/look.zig", .contents = @embedFile("look.zig") }, diff --git a/src/gui/gui.zig b/src/gui/gui.zig index 45157dd3..1ec3bca3 100644 --- a/src/gui/gui.zig +++ b/src/gui/gui.zig @@ -624,7 +624,7 @@ const Gui = struct { /// picture follows on a spring (Glide), never the other way round. scroll_notch: i32 = 0, /// A touchpad's fraction toward the next turn sent to a program that - /// owns the wheel (terminal.ownsWheel). + /// owns the wheel (Term.Modes.wheel). program_wheel: f32 = 0, /// A trackpad's horizontal fraction toward the next turn (wheelAt). program_wheel_x: f32 = 0, @@ -1658,11 +1658,11 @@ fn remoteSession(init: std.process.Init, g: *Gui, opts_in: pardes.Options, test_ const have: ?*replica.Have = if (far) &have_store else null; const allocs = pardes.memory.init(gpa); defer pardes.memory.deinit(); - pardes.TerminalImages.start(allocs.image); + pardes.Term.start(allocs.image); pardes.Kind.heap = allocs.addon; pardes.syntax.start(allocs.tree_sitter); defer { - pardes.TerminalImages.stop(); + pardes.Term.stop(); pardes.syntax.stop(); } var o = opts_in; @@ -2443,7 +2443,7 @@ fn wheelAt(g: *Gui, in: *Input, w: WheelTurn, mc: MouseCell) void { // touchpad's fraction of a notch too (pa_mouse.amount). resetScroll(g); in.post(.{ .mouse = .{ .button = if (w.y < 0) .wheel_down else .wheel_up, .kind = .press, .col = mc.col, .row = mc.row, .tag_hit = mc.tag_hit, .body_hit = mc.body_hit, .ctrl = w.mods.ctrl, .shift = w.mods.shift, .alt = w.mods.alt, .amount = @abs(w.y) } }); - } else if (!w.mods.shift and pane.isTerminal() and pardes.panes.terminal.ownsWheel(pane)) { + } else if (!w.mods.shift and pane.isTerminal() and pardes.Term.modes(pane.terminal).wheel) { // The program's (codex, htop, less): every whole turn goes // to it, no glide, for nothing of ours moves. Shift keeps // a terminal's wheel pardes's. @@ -7402,7 +7402,7 @@ test "the window's function and editing keys reach a terminal as its cursor keys .{ .modes = "\x1b[?1l\x1b[>7u", .sym = 'c', .mod = c.SDL_KMOD_LCTRL, .sent = "\x1b[99;5u" }, .{ .modes = "", .sym = 'a', .mod = c.SDL_KMOD_LALT, .sent = "\x1b[97;3u" }, // With event types asked for (2), an arrow says it is a press, as - // ghostty says it. + // the emulator's encoder says it. .{ .modes = "", .sym = c.SDLK_UP, .sent = "\x1b[1;1:1A" }, }; for (cases) |case| { diff --git a/src/host_io.zig b/src/host_io.zig index 3141ff64..0e1d29fd 100644 --- a/src/host_io.zig +++ b/src/host_io.zig @@ -173,13 +173,13 @@ pub fn testClock() ?u64 { /// heap, `pa_api.heap`: the pdf addon's documents and pages). `stopWorkers` /// is its defer. pub fn startWorkers(allocs: pardes.memory.Allocators) void { - pardes.TerminalImages.start(allocs.image); + pardes.Term.start(allocs.image); pardes.Kind.heap = allocs.addon; pardes.syntax.start(allocs.tree_sitter); } pub fn stopWorkers() void { - pardes.TerminalImages.stop(); + pardes.Term.stop(); pardes.syntax.stop(); } diff --git a/src/keys.zig b/src/keys.zig index 49ed00c0..bdf8a454 100644 --- a/src/keys.zig +++ b/src/keys.zig @@ -46,11 +46,52 @@ pub fn cycleMode(p: *Pardes, id: usize) void { .normal => edit.enterInsert(p, &pane.body, .at, 1) catch |err| p.reportError(id, "edit", err), .insert => { edit.exitInsert(p, &pane.body); - if (pane.isTerminal()) panes.terminal.enterTty(p, id); + if (pane.isTerminal()) enterTty(p, id); }, } } +/// Raw tty mode, the keys the program's: the shell's cursor first moved to +/// where the edit cursor was on its prompt line (cursor keys, as a click +/// there would), unless the pointer holds a selection to keep. +pub fn enterTty(p: *Pardes, id: usize) void { + const pane = p.panes[id] orelse return; + const selected = pane.rawPointerText(pane.sel[@backingInt(config.select_button)]) != null; + if (!selected and pane.body.cur_pinned) if (pane.terminal) |state| { + const row = pane.gridRow(pane.body.cur_row) - @as(i32, @intCast(panes.Term.grid(state).offset)); + if (panes.Term.promptMoves(state, row, pane.body.cur_col)) |moves| { + for (0..moves.left) |_| p.emitWrite(id, "\x1b[D"); + for (0..moves.right) |_| p.emitWrite(id, "\x1b[C"); + } + }; + pane.body.mode = .tty; + 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 + // keeps its modal endpoint for the next return to editor mode. + pane.body.cur_pinned = selected; + pane.body.select = false; + pane.body.restore_cursor = false; + pane.body.sticky_col = -1; + pane.body.normal.clear(); +} + +/// One key for the program that owns a raw terminal, its pty write queued. +pub fn forwardKey(p: *Pardes, id: usize, key: Key) void { + const pane = p.panes[id] orelse return; + const state = pane.terminal orelse return; + // A key's text has no bound of its own (an input method's commit, a + // paste as one key): past the stack's room the encoding grows on the + // heap, and emitWrite cuts it into writes. + var room: [256]u8 = undefined; + var first: std.heap.BufferFirstAllocator = .init(&room, p.gpa); + var out: std.Io.Writer.Allocating = .init(first.allocator()); + defer out.deinit(); + panes.Term.key(state, key, &out.writer) catch |err| return p.reportError(id, "key", err); + if (out.written().len > 0) p.emitWrite(id, out.written()); +} + /// One mode transition for the terminal tag command and the Ctrl-B chord. pub fn toggleTty(p: *Pardes, id: usize) void { const pane = p.panes[id] orelse return; @@ -62,7 +103,7 @@ pub fn toggleTty(p: *Pardes, id: usize) void { if (pane.body.mode == .tty) { pane.body.mode = .normal; pane.body.normal.clear(); - } else panes.terminal.enterTty(p, id); + } else enterTty(p, id); } /// Type `keys` again (a macro, `.`): through the modal handling as @@ -176,10 +217,10 @@ 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); + return forwardKey(p, p.view().active, plain); } // Shift-Esc backs out of whatever the pane is in -- a prompt, insert // mode, a pending count, a raw program -- to the previous pane, as @@ -210,7 +251,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, @@ -225,7 +266,7 @@ pub fn handleKey(p: *Pardes, key: Key) void { // Ctrl-V a black hole in every full-screen application. if (p.registers.text(p.gpa, Registers.default)) |text| return edit.typeToTty(p, p.view().active, pane, text); } - return panes.terminal.forwardKey(p, p.view().active, key); + return forwardKey(p, p.view().active, key); } // A kind's pane that takes keys takes them all, as a raw terminal // does; Esc too, first, when its kind is of 2.1 (a PDF's drops its @@ -406,7 +447,7 @@ pub fn handleKey(p: *Pardes, key: Key) void { edit.exitInsert(p, t) else edit.handleInsert(p, t, key), - .tty => panes.terminal.forwardKey(p, p.view().active, key), + .tty => forwardKey(p, p.view().active, key), } // `.`'s log: the keys of the normal command that entered insert // mode, then everything typed until it is left @@ -508,7 +549,7 @@ test "Esc back into a tty leaves its view at the prompt" { p.update(.{ .output = .{ .pane = @intCast(shell), .bytes = std.fmt.bufPrint(&buf, "line {d}\r\n", .{i}) catch unreachable } }); } p.sync(); - const live = sp.terminal.?.vt.screens.active.pages.scrollbar().offset; + const live = pardes.Term.grid(sp.terminal).offset; try std.testing.expect(live > 0); p.update(.{ .key = .{ .cp = Key.escape } }); // shell-prompt heuristic: out to the doc @@ -517,7 +558,7 @@ test "Esc back into a tty leaves its view at the prompt" { p.sync(); try std.testing.expectEqual(shell, p.view().active); - try std.testing.expectEqual(live, sp.terminal.?.vt.screens.active.pages.scrollbar().offset); + try std.testing.expectEqual(live, pardes.Term.grid(sp.terminal).offset); } test "Del from a key asks which neighbour takes the rows; nothing else asks" { @@ -762,7 +803,7 @@ test "raw tty forwards Ctrl letters and former global shortcuts to the child" { } p.update(.{ .key = .{ .cp = Key.up } }); try std.testing.expectEqualStrings("\x1b[A", test_api.ptyBytes(p, null, &buf)); - p.panes[0].?.terminal.?.vt.modes.set(.cursor_keys, true); + _ = pardes.Term.feed(p.panes[0].?.terminal.?, "\x1b[?1h", &.{}, &.{}, &.{}); // DECCKM p.update(.{ .key = .{ .cp = Key.up } }); try std.testing.expectEqualStrings("\x1bOA", test_api.ptyBytes(p, null, &buf)); p.update(.{ .key = .{ .cp = Key.left, .ctrl = true } }); diff --git a/src/layout.zig b/src/layout.zig index 0cfbf04a..dfbea067 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/macos.zig b/src/macos.zig index 254cf2a7..3dc87e1a 100644 --- a/src/macos.zig +++ b/src/macos.zig @@ -340,11 +340,11 @@ fn initCore(runtime: ?*const Runtime, cols_arg: u16, rows_arg: u16) !void { if (found.dir) |d| crash.setDir(d); } - pardes.TerminalImages.start(allocs.image); + pardes.Term.start(allocs.image); pardes.Kind.heap = allocs.addon; // Its addons are compiled in (no loader runs here): image and PDF panes. opts.addons = pardes.Addon.scan(); - errdefer pardes.TerminalImages.stop(); + errdefer pardes.Term.stop(); pardes.syntax.start(allocs.tree_sitter); errdefer pardes.syntax.stop(); @@ -432,7 +432,7 @@ export fn pardes_deinit() void { for (st.tag_cells) |cells| st.gpa.free(cells); if (st.images.len > 0) st.gpa.free(st.images); st.core.deinit(); - pardes.TerminalImages.stop(); + pardes.Term.stop(); pardes.syntax.stop(); st.config_arena.deinit(); st.prompt_rcs.deinit(); diff --git a/src/main.zig b/src/main.zig index ed20dceb..1e5bf9f4 100644 --- a/src/main.zig +++ b/src/main.zig @@ -133,7 +133,7 @@ const help_text = /// `pardes -` inside a session: `text`, stdin as it came, escapes and all, /// into a new +Pager of the directory (/pager): /// written after the directory on that one open, the session parses it -/// (pager.zig) and puts it in as one undo step, left clean. A text the +/// (Term.page) and puts it in as one undo step, left clean. A text the /// session would not take is never lost: it goes to stderr, a terminal, /// with why, and the exit is 1. fn pageInto(io: std.Io, gpa: std.mem.Allocator, dial: []const u8, text: []const u8) void { @@ -167,7 +167,7 @@ fn pageInto(io: std.Io, gpa: std.mem.Allocator, dial: []const u8, text: []const } /// Stdin to its end, as it came (its escapes are the session's to parse, -/// pager.zig), at most a file's limit, a longer one cut there and said so +/// Term.page), at most a file's limit, a longer one cut there and said so /// at its end. fn readStdinText(io: std.Io, gpa: std.mem.Allocator) ![]u8 { const limit = pardes.memory.limits.max_file_bytes; diff --git a/src/mouse.zig b/src/mouse.zig index 2ca984ba..a5ea9bed 100644 --- a/src/mouse.zig +++ b/src/mouse.zig @@ -164,7 +164,7 @@ pub fn sameBodyCell(a: ?Mouse.BodyHit, b: ?Mouse.BodyHit) bool { return first.serial == second.serial and first.row == second.row and first.col == second.col; } -/// A wheel over a terminal whose program owns it (`terminal.ownsWheel`: +/// A wheel over a terminal whose program owns it (`Term.Modes.wheel`: /// codex, htop, less) goes to the program as the program asked, one turn /// per line, instead of scrolling a scrollback the alternate screen does /// not have. Shift keeps it pardes's, as xterm's Shift does. False when @@ -172,19 +172,19 @@ pub fn sameBodyCell(a: ?Mouse.BodyHit, b: ?Mouse.BodyHit) bool { fn programWheel(p: *Pardes, id: usize, m: Mouse, col: u16, row: u16) bool { if (m.shift) return false; const pane = p.panes[id] orelse return false; - if (!pane.isTerminal() or !panes.terminal.ownsWheel(pane)) return false; + if (!pane.isTerminal() or !panes.Term.modes(pane.terminal).wheel) return false; const r = p.view().rects[id]; const body_y = p.bodyTop(pane, r); const gcol = std.math.clamp(col -| (r.x + config.GUTTER), 0, pane.cols -| 1); const grow = std.math.clamp(row -| body_y, 0, pane.rows -| 1); var buf: [64]u8 = undefined; - const wheel: panes.terminal.MouseButton = switch (m.button) { + const wheel: panes.Term.MouseButton = switch (m.button) { .wheel_up => .wheel_up, .wheel_down => .wheel_down, .wheel_left => .wheel_left, else => .wheel_right, }; - const bytes = panes.terminal.wheelBytes(pane, &buf, wheel, gcol, grow, .{ .alt = m.alt, .ctrl = m.ctrl }) orelse return true; + const bytes = panes.Term.wheel(pane.terminal.?, &buf, wheel, gcol, grow, .{ .alt = m.alt, .ctrl = m.ctrl }) orelse return true; for (0..@intCast(config.wheel_rows)) |_| p.emitWrite(id, bytes); return true; } @@ -214,7 +214,7 @@ fn programCell(p: *const Pardes, id: usize, col: u16, row: u16) ?struct { col: i /// A pane whose program tracks the mouse (1000, 1002, 1003, or X10's 9) /// and has the keyboard's raw input: its clicks are the program's. fn tracksMouse(pane: *const Pane) bool { - return pane.isTerminal() and pane.body.mode == .tty and panes.terminal.reportsMouse(pane); + return pane.isTerminal() and pane.body.mode == .tty and panes.Term.modes(pane.terminal).mouse; } /// A program that tracks the mouse gets it over its grid, as xterm gives @@ -265,7 +265,7 @@ pub fn kindLeave(p: *Pardes) void { fn programMouse(p: *Pardes, m: Mouse) bool { const v = p.view(); - const button: ?panes.terminal.MouseButton = switch (m.button) { + const button: ?panes.Term.MouseButton = switch (m.button) { .left => .left, .middle => .middle, .right => .right, @@ -274,7 +274,7 @@ fn programMouse(p: *Pardes, m: Mouse) bool { }; const bit: u3 = if (button) |b| @as(u3, 1) << @intCast(@backingInt(b)) else 0; const at: struct { col: u16, row: u16 } = .{ .col = @min(m.col, v.screen_w -| 1), .row = @min(m.row, v.screen_h -| 1) }; - var mods: panes.terminal.MouseMods = .{ .shift = m.shift, .alt = m.alt, .ctrl = m.ctrl }; + var mods: panes.Term.MouseMods = .{ .shift = m.shift, .alt = m.alt, .ctrl = m.ctrl }; var buf: [64]u8 = undefined; if (v.mouse_grab) |*grab| { if (grab.unshift) mods.shift = false; @@ -291,14 +291,14 @@ fn programMouse(p: *Pardes, m: Mouse) bool { const r = v.rects[grab.id]; const col: i32 = @as(i32, at.col) - @as(i32, r.x + config.GUTTER); const row: i32 = @as(i32, at.row) - @as(i32, p.bodyTop(pane, r)); - const action: panes.terminal.MouseAction = switch (m.kind) { + const action: panes.Term.MouseAction = switch (m.kind) { .press => .press, .release => .release, .drag, .motion => .motion, }; if (m.kind == .press) grab.held |= bit; if (m.kind == .release) grab.held &= ~bit; - const bytes = panes.terminal.mouseBytes(pane, &buf, action, button, mods, col, row, grab.held != 0); + const bytes = panes.Term.mouse(pane.terminal.?, &buf, action, button, mods, col, row, grab.held != 0); if (bytes.len > 0) p.emitWrite(grab.id, bytes); if (grab.held == 0) v.mouse_grab = null; return true; @@ -322,7 +322,7 @@ fn programMouse(p: *Pardes, m: Mouse) bool { pane.focus = .body; pane.closePrompt(); v.mouse_grab = .{ .id = id, .serial = pane.serial, .held = bit, .unshift = shifted_to_program }; - const bytes = panes.terminal.mouseBytes(pane, &buf, .press, button, mods, cell.col, cell.row, true); + const bytes = panes.Term.mouse(pane.terminal.?, &buf, .press, button, mods, cell.col, cell.row, true); if (bytes.len > 0) p.emitWrite(id, bytes); return true; }, @@ -330,11 +330,11 @@ fn programMouse(p: *Pardes, m: Mouse) bool { // pardes's. .release, .drag => return false, .motion => { - const bytes = panes.terminal.mouseBytes(pane, &buf, .motion, null, mods, cell.col, cell.row, false); + const bytes = panes.Term.mouse(pane.terminal.?, &buf, .motion, null, mods, cell.col, cell.row, false); if (bytes.len > 0) p.emitWrite(id, bytes); // Under 1003 the move is the program's; below that pardes // hovers as ever. - return panes.terminal.tracksAllMotion(pane); + return panes.Term.modes(pane.terminal).all_motion; }, } } @@ -426,13 +426,13 @@ fn chordCutPaste(p: *Pardes, cut: bool) edit.Error!void { if (cut) return; const y = p.registers.text(p.gpa, pardes.Registers.default) orelse return; if (y.len == 0) return; - if (panes.terminal.reportsMouse(pane)) { + if (panes.Term.modes(pane.terminal).mouse) { // A click where the text goes, so the program's cursor is there. const col = @max(0, pane.sel[sel_slot].c1); const row = @max(0, pane.sel[sel_slot].r1 - @as(i32, pane.tag_rows)); var mb: [64]u8 = undefined; - for ([_]panes.terminal.MouseAction{ .press, .release }) |action| { - const bytes = panes.terminal.mouseBytes(pane, &mb, action, .left, .{}, col, row, action == .press); + for ([_]panes.Term.MouseAction{ .press, .release }) |action| { + const bytes = panes.Term.mouse(pane.terminal.?, &mb, action, .left, .{}, col, row, action == .press); if (bytes.len > 0) p.emitWrite(s.id, bytes); } } @@ -1090,7 +1090,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/ctl.zig b/src/ninep/ctl.zig index 7bd586dc..c4947504 100644 --- a/src/ninep/ctl.zig +++ b/src/ninep/ctl.zig @@ -426,7 +426,7 @@ pub fn paneText(p: *Pardes, pane: *Pane, buf: *[pane_text_cap]u8) []const u8 { pane.serial, if (pane_files.tagOf(p, pane)) |tag| tag.len else |_| 0, // a length, as a stat's: none when the tag cannot be made // A terminal's body is its history, read whole on an open's first read. - if (pane.isTerminal()) panes.terminal.screenTextLen(pane) else pane_files.bodyOf(pane).len, + if (pane.isTerminal()) pardes.Term.scrollbackLen(pane.terminal) else pane_files.bodyOf(pane).len, // A directory pane is one, as acme's isdir says. @intFromBool(if (pane.file) |f| f.listing != null else false), @intFromBool(pane_files.dirtyOf(pane)), @@ -699,7 +699,7 @@ pub fn writePager(p: *Pardes, req: Req) Reply { /// The text a /pager open wrote after its directory (`held`), a program's /// output for a terminal, put in the +Pager `serial` as `pardes -` once -/// wrote it to the body: through pager.zig's parse, its colours kept +/// wrote it to the body: through the terminal's parse (Term.page), its colours kept /// as the pane's spans, one undo step, and left /// clean. Reads of the pane are its plain text. The held bytes go either way. pub fn fillPager(p: *Pardes, serial: u32, held: *std.ArrayList(u8)) error{OutOfMemory}!void { @@ -708,7 +708,7 @@ pub fn fillPager(p: *Pardes, serial: u32, held: *std.ArrayList(u8)) error{OutOfM const id = p.paneBySerial(serial) orelse return; const pane = p.panes[id].?; const f = if (pane.file) |*file| file else return; - const page = try pardes.pager.parse(p.gpa, held.items); + const page = try pardes.Term.page(p.gpa, held.items); held.clearAndFree(p.gpa); if (page.text.len == 0 and f.content.len == 0) return page.deinit(p.gpa); if (!pane.fs.nomark) panes.File.pushUndo(p, pane) catch |err| { @@ -2638,7 +2638,7 @@ test "what a /pager open writes after its directory is the text: plain in the bo try testing.expectEqual(@as(usize, 0), e.off); try testing.expectEqual(@as(usize, 0), e.removed.len); try testing.expectEqual(f.content.len, e.ins); - // An edit drops the colours (pager.zig's ponytail). + // An edit drops the colours (Term.page's ponytail). try testing.expectEqual(Status.ok, call(p, .{ .tag = 6, .op = .write, .node = Node.of(pn.serial, .body), .data = "more\n" }).reply.status); try testing.expectEqual(@as(usize, 0), f.pager_spans.len); // Undone back to the paged text: the text comes back, its colours diff --git a/src/ninep/pane.zig b/src/ninep/pane.zig index 3f62aef9..6c86053f 100644 --- a/src/ninep/pane.zig +++ b/src/ninep/pane.zig @@ -318,7 +318,7 @@ pub fn fileSize(p: *Pardes, id: usize, f: PaneFile) u64 { const pf = &pane.fs; return switch (f) { // A terminal's body reads its screen and history, as text. - .body => if (pane.file == null and pane.isTerminal()) panes.terminal.screenTextLen(pane) else if (kindText(p, pane)) |t| t.len else bodyOf(pane).len, + .body => if (pane.file == null and pane.isTerminal()) pardes.Term.scrollbackLen(pane.terminal) else if (kindText(p, pane)) |t| t.len else bodyOf(pane).len, // What addr selects, generated by each read: no length, as acme's // data and xdata have none; and rows, made by each read. .data, .xdata, .rows => 0, @@ -448,7 +448,7 @@ fn readBody(p: *Pardes, req: Req, id: usize, pane: *Pane) Reply { // A kind's body is its text (a PDF's, the page shown's): read-only. if (kindText(p, pane)) |text| return tree.window(p, req, text); if (req.handle != 0 and pane.isTerminal()) return screen.readSnapshot(p, req, pane); - const text = panes.terminal.screenTextAlloc(pane, p.gpa) catch + const text = pardes.Term.scrollback(pane.terminal, p.gpa) catch return Reply.fail(req.tag, E.NOMEM); defer p.gpa.free(text); return tree.window(p, req, text); diff --git a/src/ninep/pty.zig b/src/ninep/pty.zig index 350978e3..6e7fe33e 100644 --- a/src/ninep/pty.zig +++ b/src/ninep/pty.zig @@ -137,9 +137,9 @@ pub fn readStatus(p: *Pardes, req: Req, id: usize, pane: *Pane) Reply { // Busy is what a run written now would be told: a command is running // or a line is typed at the prompt. Before the shell's first prompt a // run waits for it rather than answer busy, so that is not busy. - const marks = if (pane.terminal) |state| &state.stream.handler else null; + const marks = pardes.Term.prompt(pane.terminal); const busy = p.hostTtyTaken(id) or (!pane.fs.unmarked and (waitingRun(p, pane) != null or - (if (marks) |m| m.prompts > 0 and (m.phase != .input or !pardes.panes.terminal.promptInputEmpty(pane)) else false))); + (marks.prompts > 0 and (marks.phase != .input or !marks.input_empty)))); const out = p.fs.stage(p.gpa); const size = winsize(pane); out.print(p.gpa, "{d:>11} {d:>11} {d:>11}\n", .{ size[0], size[1], @intFromBool(busy) }) catch return Reply.fail(req.tag, E.NOMEM); @@ -219,8 +219,8 @@ pub fn writeRun(p: *Pardes, req: Req, id: usize, pane: *Pane) Reply { if (std.mem.trim(u8, line, " \t").len == 0) return tree.failText(req.tag, E.INVAL, e_bad_line); for (line) |c| if (c < ' ' and c != '\t') return tree.failText(req.tag, E.INVAL, e_bad_line); const pf = &pane.fs; - const state = pane.terminal orelse return tree.failText(req.tag, E.INVAL, e_bad_line); - const marks = &state.stream.handler; + if (pane.terminal == null) return tree.failText(req.tag, E.INVAL, e_bad_line); + const marks = pardes.Term.prompt(pane.terminal); if (pane.shell_failed) { // Its shell never started: no prompt is coming to wait for. answer(p, slot, "error shell gone", .{}); @@ -230,18 +230,18 @@ pub fn writeRun(p: *Pardes, req: Req, id: usize, pane: *Pane) Reply { } else if (pf.unmarked) { answer(p, slot, "error no prompt marks", .{}); } else if (waitingRun(p, pane) != null or (marks.prompts > 0 and (marks.phase != .input or - !pardes.panes.terminal.promptInputEmpty(pane) or p.hostTtyTaken(id)))) + !marks.input_empty or p.hostTtyTaken(id)))) { // Something is running or someone has typed at the prompt: sending // now would type into the middle of it. The phase is pardes's own // marks: a nested shell's prompt (ssh, a shell with its own - // integration) looks like an empty prompt to ghostty but is not the + // integration) looks like an empty prompt to the emulator but is not the // shell this run knows. // Naming what runs, where the host can tell (Linux). var name: [64]u8 = undefined; if (p.hostForegroundName(id, &name)) |program| answer(p, slot, "busy: {s} is running", .{program}) - else if (pardes.panes.terminal.onAlternateScreen(pane)) + else if (pardes.Term.modes(pane.terminal).alternate) answer(p, slot, "busy alternate screen", .{}) else answer(p, slot, "busy", .{}); @@ -285,27 +285,27 @@ pub fn readRun(p: *Pardes, req: Req) Reply { /// for the prompt means whoever reads the answer can send the next command /// at once instead of finding the shell still drawing it. pub fn noteMarks(p: *Pardes, id: usize, pane: *Pane) void { - const state = pane.terminal orelse return; + if (pane.terminal == null) return; const pf = &pane.fs; const slot = waitingRun(p, pane) orelse return; - const marks = &state.stream.handler; + const marks = pardes.Term.prompt(pane.terminal); if (slot.phase == .waiting) { if (pf.unmarked) { answer(p, slot, "error no prompt marks", .{}); pf.run = null; return; } - if (marks.phase != .input or !pardes.panes.terminal.promptInputEmpty(pane) or p.hostTtyTaken(id)) return; + if (marks.phase != .input or !marks.input_empty or p.hostTtyTaken(id)) return; slot.want = marks.started +% 1; slot.prompts = marks.prompts; slot.declined = marks.declined; // 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.Term.modes(pane.terminal).alternate) pane.feedOutput(p, "\x1b[?1049l"); p.emitWrite(id, slot.line); p.emitWrite(id, "\r"); - pardes.panes.terminal.noteCommand(pane, slot.line); + pane.noteCommand(slot.line); // The run is the shell's first command: a greeting `ls` typed at the // same prompt would run after it, and its C would be taken for ours. pane.greet = false; @@ -322,7 +322,7 @@ pub fn noteMarks(p: *Pardes, id: usize, pane: *Pane) void { // typed into an empty prompt, so throw it away with Ctrl-C, which // drops the whole pending command, and answer at the prompt after // that, so the next line finds the shell clear. - const empty = pardes.panes.terminal.promptInputEmpty(pane); + const empty = marks.input_empty; switch (slot.cleared) { .no => { if (marks.continuation) { @@ -365,7 +365,7 @@ pub fn noteMarks(p: *Pardes, id: usize, pane: *Pane) void { fn finish(p: *Pardes, slot: *Run, pane: *Pane, status_code: ?i32) void { // As the authority's emulator has it (taped): a screen-state replica's // is its deltas', which a lagging client's can be states behind, its - // pins in pages it never had (ghostty's leftWrap overflowed on one). + // pins in pages it never had (the emulator's leftWrap overflowed on one). const printed = pardes.tape.value(.prompt, printedBy, .{ pane, p.scratch.allocator() }) orelse return answer(p, slot, "error out of memory", .{}); // Keep the tail, cut at a line start so the first line kept is whole. @@ -398,9 +398,9 @@ fn finish(p: *Pardes, slot: *Run, pane: *Pane, status_code: ?i32) void { pub const Printed = struct { text: []const u8, whole: bool }; -/// What pane `pane`'s command printed (terminal.commandOutput), in `arena`. +/// What pane `pane`'s command printed (Term.commandOutput), in `arena`. fn printedBy(pane: *Pane, arena: std.mem.Allocator) ?Printed { - const out = pardes.panes.terminal.commandOutput(pane, arena, output_rows) catch return null; + const out = pardes.Term.commandOutput(pane.terminal, arena, output_rows) catch return null; return .{ .text = out.text, .whole = out.whole }; } @@ -413,7 +413,7 @@ pub fn shellExited(p: *Pardes, pane: *Pane, status: ?u8) void { const code = status orelse return; if (waitingRun(p, pane)) |slot| if (slot.phase == .sent) { pane.fs.run = null; - pardes.panes.terminal.endOutputHere(pane); + if (pane.terminal) |state| pardes.Term.endOutputHere(state); finish(p, slot, pane, code); }; var buf: [4]u8 = undefined; @@ -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. @@ -1023,7 +1023,7 @@ test "a run's answer says cut when its output's start is gone, and reads a bound sh.put(p, c ++ "\x1b[?1049hhtop's screen\r\n"); _ = call(p, .{ .tag = 4, .op = .release, .node = node, .handle = h }); sh.put(p, "\x1b]133;D;137;aid=pardes\x07" ++ prompt); - try testing.expect(pardes.panes.terminal.onAlternateScreen(pane)); + try testing.expect(pardes.Term.modes(pane.terminal).alternate); try testing.expect(std.mem.endsWith(u8, rd(p, Node.of(serialOf(p), .pty_status), 0, 64).bytes, " 0\n")); h = sh.send(p, node); sh.put(p, c ++ "after htop\r\n" ++ d ++ prompt); diff --git a/src/ninep/screen.zig b/src/ninep/screen.zig index 634ef640..1bfd9b63 100644 --- a/src/ninep/screen.zig +++ b/src/ninep/screen.zig @@ -64,7 +64,7 @@ pub fn readSnapshot(p: *Pardes, req: Req, pane: ?*Pane) Reply { const snapshot = &(tree.openOf(p, req) orelse return Reply.fail(req.tag, E.INVAL)).what.snapshot; if (snapshot.* == null) { const terminal = pane orelse return Reply.fail(req.tag, E.INVAL); - snapshot.* = panes.terminal.screenTextAlloc(terminal, p.gpa) catch return Reply.fail(req.tag, E.NOMEM); + snapshot.* = pardes.Term.scrollback(terminal.terminal, p.gpa) catch return Reply.fail(req.tag, E.NOMEM); } return tree.window(p, req, snapshot.*.?); } @@ -126,7 +126,7 @@ test "terminal body handles keep one history snapshot across fragmented reads" { const node = Node.of(serialOf(p), .body); p.update(.{ .output = .{ .pane = 0, .bytes = "old caf\xc3\xa9\r\nold tail" } }); while (p.nextEffect()) |_| {} - const original = try panes.terminal.screenTextAlloc(p.panes[0].?, gpa); + const original = try pardes.Term.scrollback(p.panes[0].?.terminal, gpa); defer gpa.free(original); const opened = call(p, .{ .tag = 1, .op = .open, .node = node }); try testing.expectEqual(Status.ok, opened.reply.status); diff --git a/src/pager.zig b/src/pager.zig deleted file mode 100644 index dd7e4032..00000000 --- a/src/pager.zig +++ /dev/null @@ -1,595 +0,0 @@ -//! A program's output, paged into a +Pager (`pardes -`): the text it -//! prints, and its SGR colours as spans over that text. It reads the bytes -//! as a terminal does (ECMA-48's parse as ghostty-vt's table has it, UTF-8 -//! with each ill-formed part one U+FFFD) and keeps what is printed, how SGR -//! styles it and the controls that move along a line (CR, LF, BS, HT and -//! CSI's CHT, REP and the return in CNL and CPL); every other sequence is -//! read to its end and dropped (cursor motion, OSC titles and hyperlinks, -//! DCS, APC, modes). The spans are display state of the pane only: no 9P -//! file reads them (File.recolorSyntax draws them). -const std = @import("std"); -const pardes = @import("pardes.zig"); -const CellStyle = @import("surface.zig").CellStyle; -const Color = @import("surface.zig").Color; - -/// Bytes `start..end` of the text, drawn in `style`. A palette colour stays -/// `.index`, resolved through the theme as it is drawn (terminal.palColor), -/// and `.default` is the pane's own. -pub const Span = struct { start: u32, end: u32, style: CellStyle }; - -/// ponytail: past this many spans the rest of a page is plain, rather than -/// ~100 MB of spans for a 256 MiB coloured log; a packed style if it matters. -pub const max_spans = 4 << 20; - -pub const Page = struct { - text: []u8, - spans: []Span, - - pub fn deinit(page: Page, gpa: std.mem.Allocator) void { - gpa.free(page.text); - gpa.free(page.spans); - } -}; - -/// `raw`, a program's output for a terminal, as text and its spans. Both -/// are `gpa`'s. -pub fn parse(gpa: std.mem.Allocator, raw: []const u8) !Page { - var h: Handler = .{ .gpa = gpa }; - errdefer h.text.deinit(gpa); - errdefer h.spans.deinit(gpa); - try h.text.ensureTotalCapacity(gpa, raw.len); - // The printed code points since the last control, printed as one run. - var run: [4096]u32 = undefined; - var n: usize = 0; - var state: State = .ground; - var i: usize = 0; - feed: while (i < raw.len) { - const c = raw[i]; - if (state != .ground or c == 0x1b) { - h.printRun(run[0..n]); - n = 0; - state = h.step(state, c); - i += 1; - continue; - } - // Printable ASCII, most of a page, straight into the run. - if (c >= 0x20 and c < 0x7f) { - const end = @min(raw.len, i + run.len - n); - while (i < end and raw[i] >= 0x20 and raw[i] < 0x7f) : (i += 1) { - run[n] = raw[i]; - n += 1; - } - if (n < run.len) continue; - h.printRun(&run); - n = 0; - continue; - } - // UTF-8: an ill-formed part (a stray byte, or the longest start of - // a sequence that does not go on) is one U+FFFD; one the input ends - // inside may yet go on, and is not printed. - var cp: u21 = c; - var len: usize = 1; - if (c >= 0x80) { - cp = 0xfffd; - if (c >= 0xc2 and c <= 0xf4) { - const want: usize = if (c < 0xe0) 2 else if (c < 0xf0) 3 else 4; - const lo: u8 = if (c == 0xe0) 0xa0 else if (c == 0xf0) 0x90 else 0x80; - const hi: u8 = if (c == 0xed) 0x9f else if (c == 0xf4) 0x8f else 0xbf; - var acc: u21 = c & (@as(u8, 0x7f) >> @intCast(want)); - while (len < want) : (len += 1) { - if (i + len == raw.len) break :feed; - const b = raw[i + len]; - if (b < (if (len == 1) lo else 0x80) or b > (if (len == 1) hi else 0xbf)) break; - acc = acc << 6 | (b & 0x3f); - } - if (len == want) cp = acc; - } - } - i += len; - // A C1 control that came as UTF-8 is dropped, as xterm drops it. - if (cp >= 0x20 and (cp < 0x80 or cp > 0x9f)) { - run[n] = cp; - n += 1; - if (n < run.len) continue; - } - h.printRun(run[0..n]); - n = 0; - if (cp < 0x20) h.execute(@intCast(cp)); - } - h.printRun(run[0..n]); - if (h.failed) return error.OutOfMemory; - const text = try h.text.toOwnedSlice(gpa); - errdefer gpa.free(text); - return .{ .text = text, .spans = try h.spans.toOwnedSlice(gpa) }; -} - -/// Where the parse is in a sequence: ECMA-48's states, the DCS's data and -/// its ignored tail one (`dcs_body`) and SOS, PM and APC one (`apc`). -const State = enum { ground, esc, esc_inter, csi_entry, csi_param, csi_inter, csi_ignore, osc, dcs_entry, dcs_param, dcs_inter, dcs_body, apc }; - -const Handler = struct { - gpa: std.mem.Allocator, - text: std.ArrayList(u8) = .empty, - spans: std.ArrayList(Span) = .empty, - /// What SGR has set so far. - style: CellStyle = .{}, - /// Where the line being printed starts, and its last character. - line_start: usize = 0, - last: usize = 0, - /// A carriage return not yet followed by a newline: the line starts - /// over at the next print, as on a terminal, so a progress line keeps - /// its last state. - cr: bool = false, - /// A backspace: the next print strikes over the character before it. - bs: bool = false, - failed: bool = false, - /// The control sequence being read: its parameters as ghostty-vt keeps - /// them (24 at most, each saturating at 65535, a bit in `colons` for - /// each one a colon ends), and whether it has an intermediate or a - /// private marker, which no sequence kept here takes. - csi: struct { - params: [24]u16 = undefined, - n: u8 = 0, - acc: u16 = 0, - digits: bool = false, - colons: u32 = 0, - inter: bool = false, - } = .{}, - - /// The state after byte `c` in `state` (not ground's printing, which - /// `parse` decodes), acting on the controls and sequences a page keeps. - fn step(h: *Handler, state: State, c: u8) State { - switch (c) { - 0x18, 0x1a => return .ground, - 0x1b => { - h.csi = .{}; - return .esc; - }, - // A C1 control byte, in all but an OSC's or a DCS's data. - 0x80...0x9f => return if (state == .osc or state == .dcs_body) state else switch (c) { - 0x90 => .dcs_entry, - 0x9b => csi: { - h.csi = .{}; - break :csi .csi_entry; - }, - 0x9d => .osc, - 0x98, 0x9e, 0x9f => .apc, - else => .ground, - }, - 0xa0...0xff => return state, - else => {}, - } - switch (state) { - .osc => return if (c == 0x07) .ground else .osc, - .apc, .dcs_body => return state, - .dcs_entry, .dcs_param, .dcs_inter => return switch (c) { - 0...0x1f, 0x7f => state, - 0x20...0x2f => .dcs_inter, - '0'...'9', ';' => if (state == .dcs_inter) .dcs_body else .dcs_param, - '<'...'?' => if (state == .dcs_entry) .dcs_param else .dcs_body, - else => .dcs_body, - }, - else => {}, - } - if (c < 0x20) { - h.execute(c); - return state; - } - if (c == 0x7f) return state; - switch (state) { - .esc => return switch (c) { - '[' => .csi_entry, - ']' => .osc, - 'P' => .dcs_entry, - 'X', '^', '_' => .apc, - 0x20...0x2f => .esc_inter, - else => .ground, - }, - .esc_inter => return if (c < 0x30) state else .ground, - .csi_ignore => return if (c < 0x40) state else .ground, - else => {}, - } - const p = &h.csi; - switch (c) { - 0x20...0x2f => { - p.inter = true; - return .csi_inter; - }, - '0'...'9', ':', ';' => { - if (state == .csi_inter or (c == ':' and state == .csi_entry)) return .csi_ignore; - if (p.n == p.params.len) return .csi_param; - if (c <= '9') { - p.acc = p.acc *| 10 +| (c - '0'); - p.digits = true; - return .csi_param; - } - p.params[p.n] = p.acc; - if (c == ':') p.colons |= @as(u32, 1) << @intCast(p.n); - p.n += 1; - p.acc = 0; - p.digits = false; - return .csi_param; - }, - '<'...'?' => { - if (state != .csi_entry) return .csi_ignore; - p.inter = true; - return .csi_param; - }, - else => { - h.dispatch(c); - return .ground; - }, - } - } - - /// A C0 control: the line feeds (LF, VT and FF), CR, BS and HT. - fn execute(h: *Handler, c: u8) void { - switch (c) { - '\n', 0x0b, 0x0c => { - h.append("\n"); - h.line_start = h.text.items.len; - h.last = h.line_start; - h.cr = false; - h.bs = false; - }, - '\r' => h.cr = true, - 0x08 => h.bs = h.text.items.len > h.line_start, - '\t' => h.print('\t'), - else => {}, - } - } - - /// The control sequence ending in `f`: SGR, and of the rest what moves - /// along a line, dropped as ghostty-vt drops a malformed one. - fn dispatch(h: *Handler, f: u8) void { - const p = &h.csi; - if (p.n == p.params.len) return; - if (p.digits) { - p.params[p.n] = p.acc; - p.n += 1; - } - if (p.inter or (f != 'm' and p.colons != 0)) return; - if (f == 'm') return h.sgr(p.params[0..p.n], p.colons); - if (p.n > 1) return; - const count: u16 = if (p.n == 0) 1 else p.params[0]; - switch (f) { - // CNL and CPL: down or up, which a page has not, and a return. - 'E', 'F' => h.cr = true, - // CHT; and REP, the last character again, as a terminal draws - // it: a terminal stops at its edge, and this at a line's worth. - 'I' => for (0..@min(count, 64)) |_| h.print('\t'), - 'b' => if (h.text.items.len > h.last) { - const cp = std.unicode.utf8Decode(h.text.items[h.last..]) catch return; - for (0..@min(count, 1024)) |_| h.print(cp); - }, - else => {}, - } - } - - /// SGR's parameters into the style, read as ghostty-vt's sgr.Parser - /// reads them: a colour short of its values leaves them to be read as - /// SGRs of their own, and a colon list it does not know is skipped. - fn sgr(h: *Handler, params: []const u16, colons: u32) void { - const s = &h.style; - if (params.len == 0) s.* = .{}; - var i: usize = 0; - while (i < params.len) { - const p = params[i..]; - const colon = colons >> @intCast(i) & 1 != 0; - i += 1; - // The colons on from p[1], short of the last parameter. - var subs: usize = 0; - while (i + subs < params.len - 1 and colons >> @intCast(i + subs) & 1 != 0) subs += 1; - if (colon and p[0] != 4 and p[0] != 38 and p[0] != 48 and p[0] != 58) { - while (colons >> @intCast(i) & 1 != 0) i += 1; - i += 1; - continue; - } - switch (p[0]) { - 0 => s.* = .{}, - 1 => s.bold = true, - 2 => s.dim = true, - 3 => s.italic = true, - 4 => if (!colon) { - s.ul = .single; - } else if (p.len >= 2) { - if (colons >> @intCast(i) & 1 != 0) { - i += subs + 1; - } else { - i += 1; - s.ul = if (p[1] <= 5) @enumFromInt(p[1]) else .single; - } - }, - 5, 6 => s.blink = true, - 7 => s.reverse = true, - 8 => s.invisible = true, - 9 => s.strikethrough = true, - 21 => s.ul = .double, - // SGR 22 ends faint as well as bold. - 22 => { - s.bold = false; - s.dim = false; - }, - 23 => s.italic = false, - 24 => s.ul = .off, - 25 => s.blink = false, - 27 => s.reverse = false, - 28 => s.invisible = false, - 29 => s.strikethrough = false, - 30...37 => s.fg = .{ .index = @intCast(p[0] - 30) }, - 39 => s.fg = .default, - 40...47 => s.bg = .{ .index = @intCast(p[0] - 40) }, - 49 => s.bg = .default, - 90...97 => s.fg = .{ .index = @intCast(p[0] - 82) }, - 100...107 => s.bg = .{ .index = @intCast(p[0] - 92) }, - // A colour: 5 and an index, or 2 and red, green and blue, - // after a colour space's slot when colons give one. A cell - // has no underline colour (58) to take. - 38, 48, 58 => if (p.len >= 2) { - var color: ?Color = null; - if (p[1] == 5 and p.len >= 3) { - i += 2; - color = .{ .index = @truncate(p[2]) }; - } else if (p[1] == 2 and p.len >= 5) { - if (colon and subs != 3 and subs != 4) { - i += subs + 1; - continue; - } - const at: usize = if (colon and subs == 4) 3 else 2; - i += at + 2; - color = .{ .rgb = .{ @truncate(p[at]), @truncate(p[at + 1]), @truncate(p[at + 2]) } }; - } - if (color) |ink| switch (p[0]) { - 38 => s.fg = ink, - 48 => s.bg = ink, - else => {}, - }; - }, - else => {}, - } - } - } - - // ponytail: bytes that are not UTF-8 reach here as U+FFFD (`parse` - // replaces them, as a terminal shows them); a raw-byte pass if a - // +Pager must keep them. - fn print(h: *Handler, cp: u21) void { - // A control a terminal acts on and never draws: DEL comes in a run - // of printed text, as a terminal's parse hands it on. A tab is - // HT's, printed here. - if ((cp < 0x20 and cp != '\t') or (cp >= 0x7f and cp < 0xa0)) return; - if (h.cr) { - h.text.shrinkRetainingCapacity(h.line_start); - h.cut(h.line_start); - h.last = h.line_start; - h.cr = false; - h.bs = false; - } - var buf: [4]u8 = undefined; - const n = std.unicode.utf8Encode(cp, &buf) catch std.unicode.utf8Encode(0xfffd, &buf) catch unreachable; - if (h.bs) { - // A man page's overstrike: a character struck over itself is - // bold, one struck with `_` (either way round) is underlined; - // any other is replaced, as on a terminal. - h.bs = false; - const prev = h.text.items[h.last..]; - var struck = h.style; - if (std.mem.eql(u8, prev, buf[0..n])) { - struck.bold = true; - } else if (std.mem.eql(u8, prev, "_")) { - h.text.shrinkRetainingCapacity(h.last); - h.append(buf[0..n]); - struck.ul = .single; - } else if (cp == '_') { - struck.ul = .single; - } else { - h.text.shrinkRetainingCapacity(h.last); - h.cut(h.last); - h.last = h.text.items.len; - h.append(buf[0..n]); - h.span(h.last, h.style); - return; - } - h.cut(h.last); - h.span(h.last, struck); - return; - } - h.last = h.text.items.len; - h.append(buf[0..n]); - h.span(h.last, h.style); - } - - /// A run of printed characters (most of a page): the first as `print` - /// takes it, a pending return or backspace and all, the rest straight - /// on, as one span. A 256 MiB page goes through here. - fn printRun(h: *Handler, cps: []const u32) void { - if (cps.len == 0) return; - h.print(@intCast(cps[0])); - const rest = cps[1..]; - if (rest.len == 0) return; - var need: usize = 0; - for (rest) |cp| need += if (cp < 0x80) 1 else std.unicode.utf8CodepointSequenceLength(@intCast(cp)) catch 3; - h.text.ensureUnusedCapacity(h.gpa, need) catch { - h.failed = true; - return; - }; - const from = h.text.items.len; - for (rest) |cp| { - if (cp < 0x20 or (cp >= 0x7f and cp < 0xa0)) continue; - h.last = h.text.items.len; - if (cp < 0x80) { - h.text.appendAssumeCapacity(@intCast(cp)); - continue; - } - var buf: [4]u8 = undefined; - const n = std.unicode.utf8Encode(@intCast(cp), &buf) catch std.unicode.utf8Encode(0xfffd, &buf) catch unreachable; - h.text.appendSliceAssumeCapacity(buf[0..n]); - } - h.span(from, h.style); - } - - fn append(h: *Handler, bytes: []const u8) void { - h.text.appendSlice(h.gpa, bytes) catch { - h.failed = true; - }; - } - - /// `from` to the text's end drawn in `style`: the span before it goes - /// on when it ends there in the same style. - fn span(h: *Handler, from: usize, style: CellStyle) void { - if (std.meta.eql(style, CellStyle{})) return; - const end: u32 = @intCast(h.text.items.len); - if (h.spans.items.len > 0) { - const tail = &h.spans.items[h.spans.items.len - 1]; - if (tail.end == from and std.meta.eql(tail.style, style)) { - tail.end = end; - return; - } - } - if (h.spans.items.len >= max_spans) return; - h.spans.append(h.gpa, .{ .start = @intCast(from), .end = end, .style = style }) catch { - h.failed = true; - }; - } - - /// No span reaches past `at` any more: the text there is gone. - fn cut(h: *Handler, at: usize) void { - while (h.spans.items.len > 0) { - const tail = &h.spans.items[h.spans.items.len - 1]; - if (tail.end <= at) return; - if (tail.start < at) { - tail.end = @intCast(at); - return; - } - _ = h.spans.pop(); - } - } -}; - -// ---- tests ---- - -const testing = std.testing; - -/// The text `raw` pages to, and its spans as `text[start..end]=style` lines. -fn expectPage(raw: []const u8, text: []const u8, spans: []const struct { []const u8, CellStyle }) !void { - const page = try parse(testing.allocator, raw); - defer page.deinit(testing.allocator); - try testing.expectEqualStrings(text, page.text); - for (spans, 0..) |want, i| { - if (i >= page.spans.len) { - std.debug.print("missing span {d}: \"{s}\"\n", .{ i, want[0] }); - return error.TestExpectedEqual; - } - const got = page.spans[i]; - try testing.expectEqualStrings(want[0], page.text[got.start..got.end]); - try testing.expectEqualDeep(want[1], got.style); - } - try testing.expectEqual(spans.len, page.spans.len); -} - -test "git log --color: the commit line yellow, the rest plain" { - try expectPage( - "\x1b[33mcommit 0123abc\x1b[m\x1b[33m (\x1b[m\x1b[1;36mHEAD -> \x1b[m\x1b[1;32mmain\x1b[m\x1b[33m)\x1b[m\nAuthor: a <a@x>\n\n subject\n", - "commit 0123abc (HEAD -> main)\nAuthor: a <a@x>\n\n subject\n", - &.{ - .{ "commit 0123abc (", .{ .fg = .{ .index = 3 } } }, - .{ "HEAD -> ", .{ .fg = .{ .index = 6 }, .bold = true } }, - .{ "main", .{ .fg = .{ .index = 2 }, .bold = true } }, - .{ ")", .{ .fg = .{ .index = 3 } } }, - }, - ); -} - -test "ls --color=always: 01;34 directories and 01;32 executables, reset by 0 and none" { - try expectPage( - "\x1b[0m\x1b[01;34mdir\x1b[0m\n\x1b[01;32mrun.sh\x1b[0m\nplain.txt\n", - "dir\nrun.sh\nplain.txt\n", - &.{ - .{ "dir", .{ .fg = .{ .index = 4 }, .bold = true } }, - .{ "run.sh", .{ .fg = .{ .index = 2 }, .bold = true } }, - }, - ); -} - -test "grep --color=always: the match, the file name and the separator, and EL dropped" { - try expectPage( - "\x1b[35m\x1b[Ka.txt\x1b[m\x1b[K\x1b[36m\x1b[K:\x1b[m\x1b[Kone \x1b[01;31m\x1b[Kfoo\x1b[m\x1b[K two\n", - "a.txt:one foo two\n", - &.{ - .{ "a.txt", .{ .fg = .{ .index = 5 } } }, - .{ ":", .{ .fg = .{ .index = 6 } } }, - .{ "foo", .{ .fg = .{ .index = 1 }, .bold = true } }, - }, - ); -} - -test "a man page's overstrike: bold and underline, and a stray backspace" { - try expectPage( - "N\x08NA\x08AM\x08ME\x08E _\x08u_\x08s x\x08_ a\x08b\x08\n", - "NAME us x b\n", - &.{ - .{ "NAME", .{ .bold = true } }, - .{ "us", .{ .ul = .single } }, - .{ "x", .{ .ul = .single } }, - }, - ); -} - -test "truecolor, 256 colours, background, italic, faint, inverse and curly underline" { - try expectPage( - "\x1b[38;2;255;128;0mo\x1b[48;5;236mb\x1b[0;3;2mi\x1b[7mr\x1b[0;4:3mc\x1b[m.\n", - "obirc.\n", - &.{ - .{ "o", .{ .fg = .{ .rgb = .{ 255, 128, 0 } } } }, - .{ "b", .{ .fg = .{ .rgb = .{ 255, 128, 0 } }, .bg = .{ .index = 236 } } }, - .{ "i", .{ .italic = true, .dim = true } }, - .{ "r", .{ .italic = true, .dim = true, .reverse = true } }, - .{ "c", .{ .ul = .curly } }, - }, - ); -} - -test "every other escape is dropped, and a stray or broken one loses no text after it" { - const cases = [_][2][]const u8{ - .{ "a\x1b]8;;http://x\x1b\\link\x1b]8;;\x07b", "alinkb" }, - .{ "\x1b]0;title\x07\x1b[2J\x1b[H\x1b[?1049hdone\n", "done\n" }, - .{ "\x1b(Bdone", "done" }, - .{ "plain\ttext\n", "plain\ttext\n" }, - .{ "a\r\nb\r\n", "a\nb\n" }, - .{ "10%\r50%\r\x1b[K100%\ndone\n", "100%\ndone\n" }, - .{ "x\x00y\x07z\x0e\x0f\n", "xyz\n" }, - // Controls that are dropped: CAN, FS, DEL and a C1 as UTF-8. - .{ "x\x18y\x1cz\x7f!\u{85}?\n", "xyz!?\n" }, - // A broken CSI: its parameter bytes are eaten up to a final byte, as - // a terminal eats them; CAN abandons one, and the text goes on. - .{ "a\x1b[31;\x18b\x1b[m\n", "ab\n" }, - // An unknown SGR changes nothing; an ESC at the very end is dropped. - .{ "\x1b[99mz\x1b", "z" }, - }; - for (cases) |c| try expectPage(c[0], c[1], &.{}); -} - -test "bytes that are not UTF-8 page as U+FFFD, the text around them kept" { - try expectPage("caf\xe9 \xff\xfe ok\n", "caf\u{fffd} \u{fffd}\u{fffd} ok\n", &.{}); -} - -test "a carriage return's rewrite takes the spans of what it rewrote with it" { - try expectPage("\x1b[31m10%\r\x1b[32m100%\x1b[m\n", "100%\n", &.{.{ "100%", .{ .fg = .{ .index = 2 } } }}); -} - -test "colon colours, an 8-bit CSI, REP, CHT, CNL, a colour short of its values and UTF-8 cut short" { - try expectPage("\x1b[38:2::1:2:3mx\x1b[48:5:7my\x1b[m", "xy", &.{ - .{ "x", .{ .fg = .{ .rgb = .{ 1, 2, 3 } } } }, - .{ "y", .{ .fg = .{ .rgb = .{ 1, 2, 3 } }, .bg = .{ .index = 7 } } }, - }); - // 0x9b in text is a stray byte, U+FFFD; in a sequence (after ESC - // here) it is CSI; as UTF-8 (C2 9B) it is a C1 control, dropped. - try expectPage("x\x9b\x1b\x9b31mr\xc2\x9b32mg", "x\u{fffd}r32mg", &.{.{ "r32mg", .{ .fg = .{ .index = 1 } } }}); - // REP and CHT go on along the line; CNL returns, and `d` starts it over. - try expectPage("ab\x1b[3b\x1b[2Ic\n", "abbbb\t\tc\n", &.{}); - try expectPage("ab\x1b[Ed\n", "d\n", &.{}); - // 38;5 with no index: 38 is unknown and 5 is blink. - try expectPage("\x1b[38;5mx", "x", &.{.{ "x", .{ .blink = true } }}); - try expectPage("ok\xe2\x82", "ok", &.{}); - try expectPage("\xe2\x82x", "\u{fffd}x", &.{}); -} diff --git a/src/panes.zig b/src/panes.zig index 1d1feb19..bb026c30 100644 --- a/src/panes.zig +++ b/src/panes.zig @@ -109,7 +109,7 @@ pub const Pane = struct { pub const Cwd = union(enum) { none, inherited: *Pane, owned: []u8 }; pub const Focus = enum { body, tag }; pub const SessionView = struct { wrap: bool = true, layered: bool = true, body_h: u32 = 0, tagline_h: u32 = 0, rect_h: u16 = 0 }; - terminal: ?*terminal.State = null, + terminal: ?*Term.State = null, gpa: std.mem.Allocator, serial: u32 = 0, /// What the control filesystem keeps of this pane -- addr and limit, the @@ -146,7 +146,12 @@ pub const Pane = struct { /// A shell has run in it (Pardes.acknowledgeShell): a Term whose first /// shell fails to start closes, one started again keeps its pane. had_shell: bool = false, - pending_command: terminal.PendingCommand = .{}, + /// What pardes typed for a shell not ready for it yet: queued until it + /// is started (`spawn`) and then at its prompt (`input`). + pending_command: struct { + bytes: []u8 = &.{}, + wait: enum { none, spawn, input } = .none, + } = .{}, /// The last command line pardes typed into this terminal (an exec, a /// middle click, a pty/run): its first word, which Kill matches, and /// the shell's command count its start (C mark) reaches. @@ -331,7 +336,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 +560,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 +597,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 +681,364 @@ 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)); + } + + /// Whether a new terminal's greeting may be typed now: only at the + /// shell's first prompt (pardes's own marks: no command started; a + /// prompt drawn again for a resize is the same first prompt), with + /// nothing typed at it and no program on the alternate screen. Any + /// later moment is `.never`, for good: something has run or been typed + /// first, and an `ls` then would go into it. A shell pardes cannot mark + /// has no first prompt to find, and is never greeted. + pub fn greeting(pane: *const Pane) enum { wait, now, never } { + if (pane.fs.unmarked) return .never; + // Text typed into the edit buffer that stands in for the prompt row. + if (pane.ovl) |o| if (o.text.len > 0) return .never; + const state = pane.terminal orelse return .wait; + const at = Term.prompt(state); + // (Not `declined`: bash's first prompt comes after a D of its own.) + if (at.started > 0) return .never; + // At a prompt's input (the emulator's semantic marks, pardes's or + // the shell's own), before any command pardes's marks saw run. + if (!at.input_ready) return .wait; + return if (at.input_empty) .now else .never; + } + + /// Remembers a line pardes types into this terminal as the command it + /// started, for Kill: it runs from the shell's next C mark to its D. + /// ponytail: of several lines queued for a shell not up yet, only the + /// last is remembered, as the first of them. + pub fn noteCommand(pane: *Pane, line: []const u8) void { + const state = pane.terminal orelse return; + const said = std.mem.trim(u8, line, " \t"); + const word = said[0 .. std.mem.indexOfAny(u8, said, " \t") orelse said.len]; + var sent: @typeInfo(@FieldType(Pane, "sent_command")).optional.child = .{ .seq = Term.prompt(state).started +% 1 }; + sent.len = @intCast(@min(word.len, sent.word.len)); + @memcpy(sent.word[0..sent.len], word[0..sent.len]); + pane.sent_command = sent; + } + + /// A line for a shell not ready for it (`pending_command`), queued + /// after the ones before it; false when the shell is ready now. + pub fn queuePendingCommand(pane: *Pane, command: []const u8) !bool { + if (pane.pending_command.wait == .none) return false; + const old_len = pane.pending_command.bytes.len; + const new_len = try std.math.add(usize, old_len, try std.math.add(usize, command.len, 1)); + const bytes = if (old_len == 0) + try pane.gpa.alloc(u8, new_len) + else + try pane.gpa.realloc(pane.pending_command.bytes, new_len); + @memcpy(bytes[old_len..][0..command.len], command); + bytes[new_len - 1] = '\r'; + pane.pending_command.bytes = bytes; + pane.greet = false; + return true; + } + + /// The lines queued for its shell, written now that it is `ready`. + pub fn releasePendingCommand(pane: *Pane, p: *Pardes, id: usize, ready: bool) void { + if (!ready) return; + const bytes = pane.pending_command.bytes; + pane.pending_command = .{}; + if (bytes.len > 0) { + p.emitWrite(id, bytes); + pane.gpa.free(bytes); + } + } + /// `run <serial> <word>` or `exit <serial> <N|?>` 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 +1066,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; } @@ -730,7 +1088,53 @@ pub const Dir = @import("Dir.zig"); pub const mini = @import("mini.zig"); -pub const terminal = @import("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 { + const pane = try gpa.create(Pane); + pane.* = .{ + .gpa = gpa, + .cols = cols, + .rows = rows, + }; + return pane; +} + +/// A terminal pane: a pane and its emulator. Slot ownership, serial +/// assignment and spawn effects remain core lifecycle invariants. +pub fn createTerminal(gpa: std.mem.Allocator, cols: u16, rows: u16) !*Pane { + if (tape.authorityOnly("open a terminal")) return error.OutOfMemory; + const pane = try createDoc(gpa, cols, rows); + errdefer gpa.destroy(pane); + pane.terminal = try Term.open(emulatorGpa(gpa), cols, rows); + pane.tty_filter = true; + return pane; +} + +/// A screen-state replica's emulators' allocator (`Term.State.gpa`): the C +/// heap, outside its rollback epoch: written by deltas while a copy is +/// held, no part of it is ever a copy's to save or put back. +pub const emulator_gpa = std.heap.c_allocator; + +/// What a terminal's emulator is made with, by `createTerminal` or a pane's +/// load (dump.loadPane, a closed terminal brought back): `gpa`, but on a +/// screen-state replica `emulator_gpa`. +pub fn emulatorGpa(gpa: std.mem.Allocator) std.mem.Allocator { + return if (tape.screenReplica()) emulator_gpa else gpa; +} // ---- the session's pane slots: making, finding, closing and freeing panes, and their prompts ---- @@ -792,7 +1196,8 @@ pub fn teardownPane(p: *Pardes, pane: *Pane) void { } p.shell_rows.dropPane(pane); for (0..pane.pointer_selections.len) |slot| pane.clearPointerSelection(slot); - panes.terminal.deinitPendingCommand(pane); + if (pane.pending_command.bytes.len > 0) pane.gpa.free(pane.pending_command.bytes); + pane.pending_command = .{}; if (pane.command) |line| p.gpa.free(line); if (pane.shell) |bin| p.gpa.free(bin); @import("Kind.zig").close(p, pane); @@ -813,7 +1218,12 @@ pub fn teardownPane(p: *Pardes, pane: *Pane) void { p.gpa.destroy(q); pane.query = null; } - panes.terminal.deinitEmulator(pane, p.gpa); + // A pane with none (a file's, a picker's, a preview's) closes in a + // speculation as anywhere. + if (pane.terminal) |state| if (!tape.authorityOnly("close a terminal")) { + Term.close(state, p.gpa); + pane.terminal = null; + }; pane.clearCwd(); pane.fs.deinit(p.gpa); p.gpa.destroy(pane); @@ -846,12 +1256,13 @@ pub fn installPane(p: *Pardes, id: usize, pane: *Pane) void { pub fn newShell(p: *Pardes, id: usize, cwd: []const u8) !*Pane { std.debug.assert(p.panes[id] == null); if (cwd.len > limits.host_path_cap) return error.PathTooLong; - const pane = try panes.terminal.create(p.gpa, p.view().screen_w, p.view().screen_h); + const pane = try panes.createTerminal(p.gpa, p.view().screen_w, p.view().screen_h); // Named by the directory it is started in from the first, so the // shell saying it is there is no rename (`new N /` then `rename`); // out of memory for it, the shell names it when it says. if (cwd.len > 0) pane.setOwnedCwd(cwd) catch {}; - panes.terminal.armShellSpawn(pane); + std.debug.assert(pane.pending_command.bytes.len == 0); + pane.pending_command.wait = .spawn; p.installPane(id, pane); p.emitSpawn(id, pane.serial, cwd); return pane; @@ -877,7 +1288,7 @@ pub fn newCommand(p: *Pardes, id: usize, cwd: []const u8, line: []const u8) !*Pa if (cwd.len > limits.host_path_cap) return error.PathTooLong; const owned = try p.gpa.dupe(u8, line); errdefer p.gpa.free(owned); - const pane = try panes.terminal.create(p.gpa, p.view().screen_w, p.view().screen_h); + const pane = try panes.createTerminal(p.gpa, p.view().screen_w, p.view().screen_h); pane.command = owned; pane.command_pty = true; pane.body.mode = .tty; @@ -891,7 +1302,7 @@ pub fn newCommand(p: *Pardes, id: usize, cwd: []const u8, line: []const u8) !*Pa pub fn newDocPane(p: *Pardes, id: usize) !*Pane { std.debug.assert(p.panes[id] == null); - const pane = try panes.terminal.createDoc(p.gpa, p.view().screen_w, p.view().screen_h); + const pane = try panes.createDoc(p.gpa, p.view().screen_w, p.view().screen_h); p.installPane(id, pane); return pane; } @@ -942,7 +1353,7 @@ pub fn paneBySerial(p: *Pardes, serial: u32) ?usize { /// The pane a session word runs with in an empty window. pub fn standIn(p: *Pardes) ?*Pane { - if (p.stand_in == null) p.stand_in = panes.terminal.createDoc(p.gpa, p.view().screen_w, p.view().screen_h) catch null; + if (p.stand_in == null) p.stand_in = panes.createDoc(p.gpa, p.view().screen_w, p.view().screen_h) catch null; return p.stand_in; } @@ -973,7 +1384,7 @@ pub fn setTestFile(p: *Pardes, content: []const u8) !*Pane { errdefer p.gpa.free(path); const history = try panes.File.History.create(p.gpa); errdefer p.gpa.destroy(history); - const pane = try panes.terminal.createDoc(p.gpa, v.screen_w, v.screen_h); + const pane = try panes.createDoc(p.gpa, v.screen_w, v.screen_h); errdefer p.gpa.destroy(pane); try deinitPane(p, p.panes[0].?); p.panes[0] = null; @@ -1145,7 +1556,6 @@ test { _ = Dir; _ = mini; _ = @import("Kind.zig"); - _ = terminal; } test "owned cwd preserves long paths aliases and failed updates" { @@ -1299,7 +1709,7 @@ test "owned cwd EOF failure retains the pane and Del retries its close" { } test "owned cwd restore either copies the directory or preserves the old core" { - // No terminal: ghostty 1.4's snapshot decode leaks when an allocation + // No terminal: the emulator's (1.4) snapshot decode leaks when an allocation // inside it fails, and this fails every allocation of a Restore in turn // (what pardes's own load made is freed, src/walk.zig rollback). var allocator = std.testing.FailingAllocator.init(std.testing.allocator, .{}); diff --git a/src/pardes.zig b/src/pardes.zig index 511f7d35..86530157 100644 --- a/src/pardes.zig +++ b/src/pardes.zig @@ -13,7 +13,6 @@ pub const ctlfs = @import("ninep/tree.zig"); pub const syntax = @import("syntax.zig"); const tracy = @import("tracy.zig"); pub const panes = @import("panes.zig"); -pub const pager = @import("pager.zig"); const locations = @import("locations.zig"); pub const tagline = @import("tagline.zig"); pub const exec = @import("exec.zig"); @@ -72,14 +71,13 @@ pub const config = @import("config.zig"); pub const memory = @import("memory.zig"); pub const tape = @import("tape.zig"); pub const walk = @import("walk.zig"); -pub const screen_state = @import("screen_state.zig"); pub const views = @import("views.zig"); pub const rollback = @import("rollback.zig"); pub const replica = @import("replica.zig"); -pub const echo = @import("echo.zig"); pub const Kind = @import("Kind.zig"); -/// A terminal's kitty pictures; its PNG resize is started with the shell. -pub const TerminalImages = panes.terminal.TerminalImages; +/// The terminal, as the core calls it (src/term/ behind it). +pub const Term = @import("Term.zig"); +pub const keys = @import("keys.zig"); pub const Addon = @import("Addon.zig"); pub const dump = @import("dump.zig"); pub const lsp = @import("lsp/lsp.zig"); @@ -284,13 +282,13 @@ pub const builtin_rows: [std.enums.values(Builtin).len]Row = blk: { namew = @max(namew, @tagName(b).len); } for (std.enums.values(Builtin), 0..) |b, i| { - const keys = if (config.leader_path.get(b)) |path| leaderKeys(path) else ""; + const leader = if (config.leader_path.get(b)) |path| leaderKeys(path) else ""; const rest = shortcuts(b); const named = @tagName(b) ++ (if (rest.len == 0) "" else (&@as([namew - @tagName(b).len]u8, @splat(' '))) ++ " " ++ rest); rows[i] = .{ .path = config.leader_path.get(b), .cmd = b, - .line = keys ++ (&@as([4 + keyw - keys.len]u8, @splat(' '))) ++ " " ++ named, + .line = leader ++ (&@as([4 + keyw - leader.len]u8, @splat(' '))) ++ " " ++ named, }; } const last = "\x7f"; @@ -393,7 +391,7 @@ test { _ = @import("Effect.zig"); _ = @import("tape.zig"); _ = @import("replica.zig"); - _ = @import("echo.zig"); + _ = Term; _ = @import("modal.zig"); _ = @import("tagline.zig"); _ = @import("hunks.zig"); @@ -421,7 +419,6 @@ test { _ = @import("recent.zig"); _ = @import("Store.zig"); _ = @import("Db.zig"); - _ = @import("pager.zig"); _ = @import("Places.zig"); _ = @import("FrameStats.zig"); _ = @import("Query.zig"); @@ -430,6 +427,5 @@ test { _ = @import("Tables.zig"); _ = @import("Handover.zig"); _ = @import("walk.zig"); - _ = screen_state; _ = @import("views.zig"); } diff --git a/src/replica.zig b/src/replica.zig index dd6f34bc..b746ddb6 100644 --- a/src/replica.zig +++ b/src/replica.zig @@ -30,9 +30,8 @@ const walk = @import("walk.zig"); const wire = @import("wire.zig"); const daemon = @import("daemon.zig"); const writeAll = daemon.writeAll; -const screen_state = @import("screen_state.zig"); const c_heap = @import("c_heap"); -const terminal = pardes.panes.terminal; +const Term = pardes.Term; const Allocator = std.mem.Allocator; const Pardes = pardes.Pardes; @@ -281,7 +280,7 @@ pub const Authority = struct { } }; -// ---- terminals as screen state (src/screen_state.zig) ---- +// ---- terminals as screen state (src/term/screen_state.zig) ---- // // A message of either side is u8 pane, u32 the pane's serial (a slot's // next pane is another), u8 kind, and the kind's bytes: @@ -330,7 +329,7 @@ fn writeScreenHead(out: *std.ArrayListUnmanaged(u8), gpa: Allocator, pane: u8, s /// pane, and what each peer was sent of it. pub const Screens = struct { gpa: Allocator, - enc: screen_state.Encoder, + enc: Term.Encoder, tracks: [pardes.MAX_PANES]?Tracked = @splat(null), peers: std.ArrayListUnmanaged(*[pardes.MAX_PANES]PeerOf) = .empty, free_peers: std.ArrayListUnmanaged(u16) = .empty, @@ -338,8 +337,8 @@ pub const Screens = struct { /// Nanoseconds: what each flush spent encoding, for every peer. encode_ns: u64 = 0, - const Tracked = struct { serial: u32, state: *terminal.State, track: screen_state.Track }; - const PeerOf = struct { serial: u32 = 0, peer: screen_state.Peer = .{}, shadow: screen_state.ShadowSent = .{} }; + const Tracked = struct { serial: u32, state: *Term.State, track: Term.Track }; + const PeerOf = struct { serial: u32 = 0, peer: Term.Peer = .{}, shadow: pardes.Kind.ShadowSent = .{} }; pub fn init(gpa: Allocator) Screens { return .{ .gpa = gpa, .enc = .init(gpa) }; @@ -347,7 +346,7 @@ pub const Screens = struct { /// `core` is the session's, its terminals still there. pub fn deinit(s: *Screens, core: *Pardes) void { - for (&s.tracks, 0..) |*slot, id| if (slot.*) |*tr| tr.track.deinit(s.gpa, if (s.live(core, id, tr)) &tr.state.vt else null); + for (&s.tracks, 0..) |*slot, id| if (slot.*) |*tr| Term.untrack(&tr.track, s.gpa, if (s.live(core, id, tr)) tr.state else null); for (s.peers.items) |p| { for (p) |*pp| { pp.peer.deinit(s.gpa); @@ -402,12 +401,11 @@ pub const Screens = struct { pp.peer.reset(); pp.serial = pane.serial; } - var marks: [terminal.marks_len]u8 = undefined; s.out.clearRetainingCapacity(); try writeScreenHead(&s.out, s.gpa, @intCast(id), pane.serial, kind_delta); var w: std.Io.Writer.Allocating = .fromArrayList(s.gpa, &s.out); defer s.out = w.toArrayList(); - if (!try screen_state.encode(&s.enc, &tr.track, &pp.peer, &state.vt, state.changes, terminal.marksOf(state, &marks), &w.writer)) continue; + if (!try Term.encode(state, &s.enc, &tr.track, &pp.peer, &w.writer)) continue; try out.append(s.gpa, try s.gpa.dupe(u8, w.written())); } } @@ -440,14 +438,14 @@ pub const Screens = struct { // lacks, each a message before the frame naming them. for (frame.places[0..@min(frame.n, 64)]) |*pl| { // A row past a strip's bound cannot cross: not shown there. - if (@as(usize, pl.w) * 4 > screen_state.strip_max) continue; + if (@as(usize, pl.w) * 4 > pardes.Kind.strip_max) continue; var owed = try pp.shadow.owed(x.s.gpa, pl); while (owed != 0) : (owed &= owed - 1) { x.s.out.clearRetainingCapacity(); try writeScreenHead(&x.s.out, x.s.gpa, @intCast(id), pane.serial, kind_raster); var w: std.Io.Writer.Allocating = .fromArrayList(x.s.gpa, &x.s.out); defer x.s.out = w.toArrayList(); - try screen_state.encodeStrip(pl, @ctz(owed), &w.writer); + try pardes.Kind.encodeStrip(pl, @ctz(owed), &w.writer); try x.out.append(x.s.gpa, try x.s.gpa.dupe(u8, w.written())); } } @@ -455,7 +453,7 @@ pub const Screens = struct { try writeScreenHead(&x.s.out, x.s.gpa, @intCast(id), pane.serial, kind_shadow); var w: std.Io.Writer.Allocating = .fromArrayList(x.s.gpa, &x.s.out); defer x.s.out = w.toArrayList(); - if (!try screen_state.encodeShadow(x.s.gpa, &pp.shadow, &frame, k.pointer, &w.writer)) continue; + if (!try pardes.Kind.encodeShadow(x.s.gpa, &pp.shadow, &frame, k.pointer, &w.writer)) continue; try x.out.append(x.s.gpa, try x.s.gpa.dupe(u8, w.written())); }; } @@ -473,7 +471,7 @@ pub const Screens = struct { for (core.panes, 0..) |slot, id| { const pane = slot orelse continue; const state = pane.terminal orelse continue; - if (!state.read) continue; + if (!Term.wasRead(state)) continue; const pp = &s.peers.items[peer][id]; if (pp.serial != pane.serial or pp.peer.holes.items.len == 0) continue; const tr = try s.track(core, id); @@ -485,7 +483,7 @@ pub const Screens = struct { try writeScreenHead(&s.out, s.gpa, @intCast(id), pane.serial, kind_rows); var w: std.Io.Writer.Allocating = .fromArrayList(s.gpa, &s.out); defer s.out = w.toArrayList(); - try screen_state.encodeRows(&s.enc, &tr.track, &state.vt, lo, hi, &w.writer); + try Term.encodeRows(state, &s.enc, &tr.track, lo, hi, &w.writer); try out.append(s.gpa, try s.gpa.dupe(u8, w.written())); lo = hi; } @@ -497,7 +495,7 @@ pub const Screens = struct { /// Every peer is filled: the steps' reads are forgotten. pub fn filled(_: *Screens, core: *Pardes) void { for (core.panes) |slot| if (slot) |pane| if (pane.terminal) |state| { - state.read = false; + Term.clearRead(state); }; } @@ -506,7 +504,7 @@ pub const Screens = struct { if (s.tracks[id]) |*tr| { if (s.live(core, id, tr)) return tr; // Its pane closed (its emulator, the pin with it, gone). - tr.track.deinit(s.gpa, null); + Term.untrack(&tr.track, s.gpa, null); } s.tracks[id] = .{ .serial = pane.serial, .state = pane.terminal.?, .track = .init(s.gpa) }; return &s.tracks[id].?; @@ -533,7 +531,7 @@ pub const Screens = struct { try writeScreenHead(&s.out, s.gpa, m.pane, m.serial, kind_rows); var w: std.Io.Writer.Allocating = .fromArrayList(s.gpa, &s.out); defer s.out = w.toArrayList(); - try screen_state.encodeRows(&s.enc, &tr.track, &state.vt, std.mem.readInt(u64, m.payload[0..8], .little), std.mem.readInt(u64, m.payload[8..16], .little), &w.writer); + try Term.encodeRows(state, &s.enc, &tr.track, std.mem.readInt(u64, m.payload[0..8], .little), std.mem.readInt(u64, m.payload[8..16], .little), &w.writer); return try s.gpa.dupe(u8, w.written()); }, else => {}, @@ -673,20 +671,20 @@ 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(.{}), screen_out: std.ArrayListUnmanaged(u8) = .empty, /// Its Shadows' rasters, from the session's strips (17.3). - blobs: screen_state.Blobs = .{}, - /// Its predicted echo (src/echo.zig), drawn over its core's terminals: + blobs: pardes.Kind.Blobs = .{}, + /// Its predicted echo (src/term/echo.zig), drawn over its core's terminals: /// fed by its keys, its units and its deltas here, and by `echoFrame`. - echo: pardes.echo.Echo = .{}, + echo: Term.Echo = .{}, const ScreenOf = struct { serial: u32, - rep: screen_state.Replica = .{}, + rep: Term.Replica = .{}, /// A delta was refused, and a reset asked for: those in flight /// before it are refused unasked. refused: bool = false, @@ -739,7 +737,7 @@ pub const Replica = struct { o.state = .off; // Its emulators off the epoch, as `terminal.create` makes a screen // replica's: deltas write them while a copy is held. - pardes.dump.terminal_gpa = terminal.emulator_gpa; + pardes.dump.terminal_gpa = pardes.panes.emulator_gpa; defer pardes.dump.terminal_gpa = null; const c = try pardes.dump.load(epoch, o, bytes, null); // The chrome's colours are local, never dumped: the restored theme's. @@ -754,13 +752,13 @@ pub const Replica = struct { c.in_len = 0; c.in_head = 0; tape.adoptCore(&r.t, c); - // Its keys into a terminal drawn at once (src/echo.zig). + // Its keys into a terminal drawn at once (src/term/echo.zig). c.echo = &r.echo; return r; } pub fn deinit(r: *Replica) void { - for (&r.screens) |*slot| if (slot.*) |*sc| sc.rep.deinit(terminal.emulator_gpa); + for (&r.screens) |*slot| if (slot.*) |*sc| sc.rep.deinit(pardes.panes.emulator_gpa); if (r.t.core) |c| { const was = Stepping.begin(&r.t, &r.epoch); if (r.copy.held) _ = r.copy.restore(); @@ -1090,12 +1088,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 @@ -1144,7 +1142,7 @@ pub const Replica = struct { // A pane of a kind: the authority's frame of it, drawn as it is. if (m.kind == kind_shadow) if (pane.addon) |k| { const sh = k.shadow orelse sh: { - const made = k.gpa.create(screen_state.Shadow) catch return null; + const made = k.gpa.create(pardes.Kind.Shadow) catch return null; made.* = .{}; k.shadow = made; break :sh made; @@ -1158,7 +1156,7 @@ pub const Replica = struct { const state = pane.terminal orelse return null; const slot = &r.screens[m.pane]; if (slot.* == null or slot.*.?.serial != m.serial) { - if (slot.*) |*old| old.rep.deinit(terminal.emulator_gpa); + if (slot.*) |*old| old.rep.deinit(pardes.panes.emulator_gpa); slot.* = .{ .serial = m.serial }; } const sc = &slot.*.?; @@ -1168,7 +1166,7 @@ pub const Replica = struct { switch (m.kind) { kind_delta => { const t0 = nowNs(); - const applied = sc.rep.apply(state.gpa, terminal.terminalIo(), &state.vt, m.payload) catch |err| { + const applied = Term.apply(state, &sc.rep, m.payload) catch |err| { if (err != error.BaseMismatch) r.fail("a terminal's delta did not apply"); if (sc.refused) return null; sc.refused = true; @@ -1176,13 +1174,12 @@ pub const Replica = struct { }; if (r.stats.samples) r.stats.apply_ns.append(r.gpa, nowNs() - t0) catch {}; sc.refused = false; - terminal.takeMarks(state, applied.extra); r.echo.delta(c, m.pane, sc.rep.top); // Its rows as the core keeps them read are another grid's. c.shell_rows.markStale(pane); // Its view is the authority's now: a rollback puts it back // here, and what was applied over a terminal goes on top. - if (r.copy.held) r.views[m.pane] = .{ .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); @@ -1190,7 +1187,7 @@ pub const Replica = struct { }, kind_rows => { sc.asked = null; - sc.rep.applyRows(state.gpa, &state.vt, m.payload) catch r.fail("a terminal's rows did not apply"); + Term.applyRows(state, &sc.rep, m.payload) catch r.fail("a terminal's rows did not apply"); c.shell_rows.markStale(pane); r.overTerminals(); return null; @@ -1225,13 +1222,13 @@ pub const Replica = struct { const pane = c.panes[id] orelse continue; if (pane.serial != sc.serial) continue; const state = pane.terminal orelse continue; - const shown = sc.rep.shown(&state.vt); + const shown = Term.shown(state, &sc.rep); var holes: std.ArrayList([2]u64) = .empty; defer holes.deinit(r.gpa); sc.rep.missing(shown[0], shown[1], &holes, r.gpa) catch return null; if (holes.items.len == 0) continue; const want: [2]u64 = .{ holes.items[0][0], holes.items[holes.items.len - 1][1] }; - sc.rep.blank(&state.vt, want[0], want[1]); + Term.blank(state, &sc.rep, want[0], want[1]); sc.asked = want; var range: [16]u8 = undefined; std.mem.writeInt(u64, range[0..8], want[0], .little); @@ -1852,7 +1849,7 @@ pub const Peers = struct { boundary_ns: std.ArrayListUnmanaged(u64) = .empty, cut: u32 = 0, head: [unit_head]u8 = undefined, - /// Its clients' terminals as screen state (src/screen_state.zig), while + /// Its clients' terminals as screen state (src/term/screen_state.zig), while /// it records: what each was sent. screens: Screens = undefined, msgs: std.ArrayListUnmanaged([]u8) = .empty, @@ -1903,7 +1900,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 +2216,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 +3090,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; @@ -3422,7 +3419,7 @@ test "a delta applied under a speculation outlives its rollback: the terminal st try std.testing.expect(r.copy.held); try deliver(a, &screens, peer, r, .flush); // The rows the core keeps, read once under the copy. - _ = try terminal.shellRows(r.core(), r.core().panes[shell].?); + _ = try pardes.edit.shellRows(r.core(), r.core().panes[shell].?); } for (sent.items) |m| { r.confirm(try a.take(m)); @@ -3436,7 +3433,7 @@ test "a delta applied under a speculation outlives its rollback: the terminal st // another's unit puts the copy back: the rows it kept are of an older // grid and must not be read. r.confirm(try a.local(.{ .focus = false })); - _ = try terminal.shellRows(r.core(), r.core().panes[shell].?); + _ = try pardes.edit.shellRows(r.core(), r.core().panes[shell].?); try key(r, 'x', &sent); for (0..40) |i| a.output(.{ .output = .{ .pane = shell, .bytes = try std.fmt.bufPrint(&line, "last line {d}\r\n", .{i}) } }); r.confirm((try a.pending()).?); @@ -3445,8 +3442,8 @@ test "a delta applied under a speculation outlives its rollback: the terminal st r.confirm(try a.local(.{ .focus = true })); r.settle(); const n = a.core.panes[shell].?.rows; - const back = try terminal.shellRows(r.core(), r.core().panes[shell].?); - const now = try terminal.shellRows(a.core, a.core.panes[shell].?); + const back = try pardes.edit.shellRows(r.core(), r.core().panes[shell].?); + const now = try pardes.edit.shellRows(a.core, a.core.panes[shell].?); for (now[now.len - n ..], back[back.len - n ..]) |x, y| try std.testing.expectEqualStrings(x, y); for (sent.items) |m| { r.confirm(try a.take(m)); @@ -3460,11 +3457,11 @@ test "a delta applied under a speculation outlives its rollback: the terminal st defer dump_a.deinit(); var dump_r: std.Io.Writer.Allocating = .init(gpa); defer dump_r.deinit(); - try screen_state.dumpScreen(&a.core.panes[shell].?.terminal.?.vt, &dump_a.writer); - try screen_state.dumpScreen(&r.core().panes[shell].?.terminal.?.vt, &dump_r.writer); + try Term.dumpScreen(a.core.panes[shell].?.terminal.?, &dump_a.writer); + try Term.dumpScreen(r.core().panes[shell].?.terminal.?, &dump_r.writer); try std.testing.expectEqualStrings(dump_a.written(), dump_r.written()); - const rows_a = try terminal.shellRows(a.core, a.core.panes[shell].?); - const rows_r = try terminal.shellRows(r.core(), r.core().panes[shell].?); + const rows_a = try pardes.edit.shellRows(a.core, a.core.panes[shell].?); + const rows_r = try pardes.edit.shellRows(r.core(), r.core().panes[shell].?); // As many rows (the history is the authority's to the row), the screen's // the same; above it, rows scrolled past more than a screen at once are // holes until fetched. @@ -3583,7 +3580,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 +3606,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 +3653,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 +3663,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 +3681,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 +3704,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/rollback.zig b/src/rollback.zig index 461ba45b..d5810a86 100644 --- a/src/rollback.zig +++ b/src/rollback.zig @@ -518,7 +518,7 @@ fn annotatedStruct(comptime T: type) bool { /// is taken: what is in their slots is nothing), the frame statistics /// (numbers), and the rows a terminal was last read as /// (a grid's worth of text, emptied when a copy is taken and when it is -/// put back: src/replica.zig), and a replica's predicted echo (src/echo.zig: +/// put back: src/replica.zig), and a replica's predicted echo (src/term/echo.zig: /// the replica's, never its core's). And the store and Recent, a replica's /// own: on the host's heap (Pardes.recentGpa), which the epoch never puts a /// free off for, so their bytes put back would point at what is freed. A diff --git a/src/surface.zig b/src/surface.zig index c0f352ee..b832222f 100644 --- a/src/surface.zig +++ b/src/surface.zig @@ -4,6 +4,7 @@ const pardes = @import("pardes.zig"); const std = @import("std"); const layout = @import("layout.zig"); const uucode = @import("uucode"); +const vaxis = @import("vaxis"); const panes = @import("panes.zig"); const config = @import("config.zig"); const MAX_PANES = pardes.MAX_PANES; @@ -416,7 +417,7 @@ pub const Surface = struct { const width: u16 = if (decoded == null or (cp < 0x80 and cp_slice.len == 1)) 1 else - @max(1, panes.File.utf8Width(cp_slice)); + @max(1, vaxis.gwidth.gwidth(cp_slice, .unicode)); if (width == 2 and col + 1 >= end) return null; var shown = cp_slice; if (shown.len > @typeInfo(@FieldType(Cell, "text")).array.len) { diff --git a/src/tagline.zig b/src/tagline.zig index fa5246c4..1bb4dc85 100644 --- a/src/tagline.zig +++ b/src/tagline.zig @@ -157,9 +157,9 @@ pub fn pathPrefix(p: *const Pardes, arena: std.mem.Allocator, pane: *Pane) ![]co if (pane.file) |f| return if (pane.prompt == .name) pane.input.own orelse f.path else f.path; // A terminal showing kitty graphics says how it draws them, as an image // pane does, and so does one drawing them as glyph art by choice. - if (panes.terminal.petscii(pane)) |chosen| { + if (panes.Term.petscii(pane.terminal)) |chosen| { const on = chosen or !p.view().frontend.native_images; - if (chosen or panes.terminal.hasImages(pane)) + if (chosen or panes.Term.hasImages(pane.terminal)) return std.fmt.allocPrint(arena, "{s} petscii:{s}", .{ (try shownDir(arena, pane)), if (on) "on" else "off" }); } return (try shownDir(arena, pane)); diff --git a/src/tape.zig b/src/tape.zig index c617f2a2..fd5b4b85 100644 --- a/src/tape.zig +++ b/src/tape.zig @@ -21,7 +21,6 @@ const std = @import("std"); const pardes = @import("pardes.zig"); const walk = @import("walk.zig"); const host_io = @import("host_io.zig"); -const terminal = @import("terminal.zig"); const Pardes = pardes.Pardes; const VTable = pardes.Host.VTable; const libc = std.c; @@ -136,8 +135,8 @@ 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, - ?pardes.ctlfs.pty.Printed, @typeInfo(@TypeOf(terminal.greeting)).@"fn".return_type.?, + anyerror!void, pardes.Term.Told, + ?pardes.ctlfs.pty.Printed, @typeInfo(@TypeOf(pardes.panes.Pane.greeting)).@"fn".return_type.?, []pardes.Stream.Batch, // What only the authority holds (`authority`): a closed pane's record, // Recent's entry for a closed jump, the closed panes' names. @@ -253,7 +252,7 @@ pub const Tape = struct { dump_check: bool = false, dumps: usize = 0, dump_bytes: usize = 0, - /// Screen-state terminals (src/screen_state.zig, docs/next-daemon.md + /// Screen-state terminals (src/term/screen_state.zig, docs/next-daemon.md /// phase 5): an authority recording for replicas, or a replica. A /// terminal's emulator is the authority's alone: its output is recorded /// without its bytes (they cross as screen state), its pty writes are @@ -1062,6 +1061,27 @@ pub fn poison(why: []const u8) void { }; } +/// A replica's speculation leaves what is the authority's be (a terminal's +/// emulator, a kind's state): true, and the input waits for its order. +pub fn authorityOnly(comptime why: []const u8) bool { + if (!speculating()) return false; + poison(why); + 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) { @@ -1247,7 +1267,7 @@ pub fn startFromEnv() void { pub fn replayMain(path: []const u8) u8 { const gpa = std.heap.c_allocator; // What a shell starts before its core (tui.zig's localSession). - pardes.TerminalImages.start(gpa); + pardes.Term.start(gpa); pardes.syntax.start(gpa); const bytes = std.Io.Dir.cwd().readFileAlloc(std.Io.Threaded.global_single_threaded.io(), path, gpa, .unlimited) catch |err| { std.debug.print("replay: cannot read {s}: {t}\n", .{ path, err }); diff --git a/src/TerminalImages.zig b/src/term/TerminalImages.zig index f8fed78e..6894945c 100644 --- a/src/TerminalImages.zig +++ b/src/term/TerminalImages.zig @@ -9,13 +9,13 @@ //! through the U+10EEEE placeholder cells the program prints. const std = @import("std"); const ghostty_vt = @import("ghostty-vt"); -const pardes = @import("pardes.zig"); +const pardes = @import("../pardes.zig"); const zstbi = @import("zstbi"); const wuffs = @import("wuffs"); const TerminalImages = @This(); const gfx = ghostty_vt.kitty.graphics; -const PixelRect = @import("surface.zig").RectPx; +const PixelRect = @import("../surface.zig").RectPx; /// The bytes ghostty-vt may hold for one screen's images (it evicts the /// oldest past this): a 4K picture in RGBA, with room for a second. diff --git a/src/echo.zig b/src/term/echo.zig index 3d2ee060..a5c65f7e 100644 --- a/src/echo.zig +++ b/src/term/echo.zig @@ -28,8 +28,8 @@ //! prompt or a program that ignores input confirms none, so nothing typed //! there is ever shown. const std = @import("std"); -const pardes = @import("pardes.zig"); -const terminal = pardes.panes.terminal; +const pardes = @import("../pardes.zig"); +const terminal = @import("terminal.zig"); const Pardes = pardes.Pardes; const Pane = pardes.Pane; const Surface = pardes.Surface; @@ -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 }; @@ -532,7 +533,7 @@ fn blank(cp: u21) bool { /// pardes's marks is trusted only once its echo is confirmed. fn atPrompt(pane: *const Pane) bool { const state = pane.terminal orelse return false; - return state.vt.screens.active_key == .primary and state.stream.handler.phase == .input and terminal.promptInputReady(pane); + return state.vt.screens.active_key == .primary and state.stream.handler.phase == .input and terminal.prompt(state).input_ready; } /// The terminal view `view`'s keys go to, in tty mode: none when they go @@ -552,7 +553,7 @@ fn keyboardPane(c: *const Pardes, view: u8) ?usize { // ---- tests: one authority and one replica, its shell played by hand ---- const testing = std.testing; -const replica = @import("replica.zig"); +const replica = @import("../replica.zig"); const Rig = struct { a: *replica.Authority, @@ -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/pager.zig b/src/term/pager.zig new file mode 100644 index 00000000..dca57024 --- /dev/null +++ b/src/term/pager.zig @@ -0,0 +1,371 @@ +//! A program's output, paged into a +Pager (`pardes -`): the text it +//! prints, and its SGR colours as spans over that text. ghostty-vt, which +//! terminal panes already drive, parses every escape; this keeps what is +//! printed and how SGR styles it, and drops every other control (cursor +//! motion, OSC titles and hyperlinks, modes). The spans are display state +//! of the pane only: no 9P file reads them (File.recolorSyntax draws them). +const std = @import("std"); +const pardes = @import("../pardes.zig"); +const CellStyle = @import("../surface.zig").CellStyle; +const ghostty_vt = @import("ghostty-vt"); + +/// Bytes `start..end` of the text, drawn in `style`. A palette colour stays +/// `.index`, resolved through the theme as it is drawn (terminal.palColor), +/// and `.default` is the pane's own. +pub const Span = struct { start: u32, end: u32, style: CellStyle }; + +/// ponytail: past this many spans the rest of a page is plain, rather than +/// ~100 MB of spans for a 256 MiB coloured log; a packed style if it matters. +pub const max_spans = 4 << 20; + +pub const Page = struct { + text: []u8, + spans: []Span, + + pub fn deinit(page: Page, gpa: std.mem.Allocator) void { + gpa.free(page.text); + gpa.free(page.spans); + } +}; + +/// `raw`, a program's output for a terminal, as text and its spans. Both +/// are `gpa`'s. +pub fn parse(gpa: std.mem.Allocator, raw: []const u8) !Page { + var h: Handler = .{ .gpa = gpa }; + errdefer h.text.deinit(gpa); + errdefer h.spans.deinit(gpa); + try h.text.ensureTotalCapacity(gpa, raw.len); + var stream: ghostty_vt.Stream(*Handler) = .init(.{ .handler = &h }); + defer stream.deinit(); + stream.nextSlice(raw); + if (h.failed) return error.OutOfMemory; + const text = try h.text.toOwnedSlice(gpa); + errdefer gpa.free(text); + return .{ .text = text, .spans = try h.spans.toOwnedSlice(gpa) }; +} + +const Handler = struct { + gpa: std.mem.Allocator, + text: std.ArrayList(u8) = .empty, + spans: std.ArrayList(Span) = .empty, + /// What SGR has set so far. + style: CellStyle = .{}, + /// Where the line being printed starts, and its last character. + line_start: usize = 0, + last: usize = 0, + /// A carriage return not yet followed by a newline: the line starts + /// over at the next print, as on a terminal, so a progress line keeps + /// its last state. + cr: bool = false, + /// A backspace: the next print strikes over the character before it. + bs: bool = false, + failed: bool = false, + + const Action = ghostty_vt.StreamAction; + + pub fn vt(h: *Handler, comptime action: Action.Tag, value: Action.Value(action)) void { + switch (action) { + .print => h.print(value.cp), + .print_slice => h.printRun(value.cps), + // CSI b repeats the last character, as a terminal draws it; + // a terminal stops at its edge, and this at a line's worth. + .print_repeat => if (h.text.items.len > h.last) { + const cp = std.unicode.utf8Decode(h.text.items[h.last..]) catch return; + for (0..@min(value, 1024)) |_| h.print(cp); + }, + .set_attribute => h.attribute(value), + .linefeed => { + h.append("\n"); + h.line_start = h.text.items.len; + h.last = h.line_start; + h.cr = false; + h.bs = false; + }, + .carriage_return => h.cr = true, + .backspace => h.bs = h.text.items.len > h.line_start, + .horizontal_tab => for (0..@min(value, 64)) |_| h.print('\t'), + else => {}, + } + } + + pub fn deinit(_: *Handler) void {} + + // ponytail: bytes that are not UTF-8 reach here as U+FFFD (ghostty's + // decoder replaces them, as a terminal shows them); a raw-byte pass + // through the stream if a +Pager must keep them. + fn print(h: *Handler, cp: u21) void { + // A control a terminal acts on and never draws: ghostty's fast path + // hands those past 0x0f (CAN, DEL, the C1 set) on as printed text. + // A tab is HT's, printed here. + if ((cp < 0x20 and cp != '\t') or (cp >= 0x7f and cp < 0xa0)) return; + if (h.cr) { + h.text.shrinkRetainingCapacity(h.line_start); + h.cut(h.line_start); + h.last = h.line_start; + h.cr = false; + h.bs = false; + } + var buf: [4]u8 = undefined; + const n = std.unicode.utf8Encode(cp, &buf) catch std.unicode.utf8Encode(0xfffd, &buf) catch unreachable; + if (h.bs) { + // A man page's overstrike: a character struck over itself is + // bold, one struck with `_` (either way round) is underlined; + // any other is replaced, as on a terminal. + h.bs = false; + const prev = h.text.items[h.last..]; + var struck = h.style; + if (std.mem.eql(u8, prev, buf[0..n])) { + struck.bold = true; + } else if (std.mem.eql(u8, prev, "_")) { + h.text.shrinkRetainingCapacity(h.last); + h.append(buf[0..n]); + struck.ul = .single; + } else if (cp == '_') { + struck.ul = .single; + } else { + h.text.shrinkRetainingCapacity(h.last); + h.cut(h.last); + h.last = h.text.items.len; + h.append(buf[0..n]); + h.span(h.last, h.style); + return; + } + h.cut(h.last); + h.span(h.last, struck); + return; + } + h.last = h.text.items.len; + h.append(buf[0..n]); + h.span(h.last, h.style); + } + + /// A run of printed characters (most of a page): the first as `print` + /// takes it, a pending return or backspace and all, the rest straight + /// on, as one span. A 256 MiB page goes through here. + fn printRun(h: *Handler, cps: []const u32) void { + if (cps.len == 0) return; + h.print(@intCast(cps[0])); + const rest = cps[1..]; + if (rest.len == 0) return; + var need: usize = 0; + for (rest) |cp| need += if (cp < 0x80) 1 else std.unicode.utf8CodepointSequenceLength(@intCast(cp)) catch 3; + h.text.ensureUnusedCapacity(h.gpa, need) catch { + h.failed = true; + return; + }; + const from = h.text.items.len; + for (rest) |cp| { + if (cp < 0x20 or (cp >= 0x7f and cp < 0xa0)) continue; + h.last = h.text.items.len; + if (cp < 0x80) { + h.text.appendAssumeCapacity(@intCast(cp)); + continue; + } + var buf: [4]u8 = undefined; + const n = std.unicode.utf8Encode(@intCast(cp), &buf) catch std.unicode.utf8Encode(0xfffd, &buf) catch unreachable; + h.text.appendSliceAssumeCapacity(buf[0..n]); + } + h.span(from, h.style); + } + + fn append(h: *Handler, bytes: []const u8) void { + h.text.appendSlice(h.gpa, bytes) catch { + h.failed = true; + }; + } + + /// `from` to the text's end drawn in `style`: the span before it goes + /// on when it ends there in the same style. + fn span(h: *Handler, from: usize, style: CellStyle) void { + if (std.meta.eql(style, CellStyle{})) return; + const end: u32 = @intCast(h.text.items.len); + if (h.spans.items.len > 0) { + const tail = &h.spans.items[h.spans.items.len - 1]; + if (tail.end == from and std.meta.eql(tail.style, style)) { + tail.end = end; + return; + } + } + if (h.spans.items.len >= max_spans) return; + h.spans.append(h.gpa, .{ .start = @intCast(from), .end = end, .style = style }) catch { + h.failed = true; + }; + } + + /// No span reaches past `at` any more: the text there is gone. + fn cut(h: *Handler, at: usize) void { + while (h.spans.items.len > 0) { + const tail = &h.spans.items[h.spans.items.len - 1]; + if (tail.end <= at) return; + if (tail.start < at) { + tail.end = @intCast(at); + return; + } + _ = h.spans.pop(); + } + } + + fn attribute(h: *Handler, attr: ghostty_vt.Attribute) void { + const s = &h.style; + switch (attr) { + .unset => s.* = .{}, + .bold => s.bold = true, + // SGR 22 ends faint as well as bold. + .reset_bold => { + s.bold = false; + s.dim = false; + }, + .faint => s.dim = true, + .italic => s.italic = true, + .reset_italic => s.italic = false, + // SGR's styles in a cell's order (terminal.zig checks it). + .underline => |u| s.ul = @enumFromInt(@intFromEnum(u)), + .blink => s.blink = true, + .reset_blink => s.blink = false, + .inverse => s.reverse = true, + .reset_inverse => s.reverse = false, + .invisible => s.invisible = true, + .reset_invisible => s.invisible = false, + .strikethrough => s.strikethrough = true, + .reset_strikethrough => s.strikethrough = false, + .direct_color_fg => |c| s.fg = .{ .rgb = .{ c.r, c.g, c.b } }, + .direct_color_bg => |c| s.bg = .{ .rgb = .{ c.r, c.g, c.b } }, + .@"8_fg", .@"8_bright_fg" => |name| s.fg = .{ .index = @backingInt(name) }, + .@"8_bg", .@"8_bright_bg" => |name| s.bg = .{ .index = @backingInt(name) }, + .@"256_fg" => |i| s.fg = .{ .index = i }, + .@"256_bg" => |i| s.bg = .{ .index = i }, + .reset_fg => s.fg = .default, + .reset_bg => s.bg = .default, + // A cell has no overline and no underline colour to take. + .overline, .reset_overline, .underline_color, .@"256_underline_color", .reset_underline_color, .unknown => {}, + } + } +}; + +// ---- tests ---- + +const testing = std.testing; + +/// The text `raw` pages to, and its spans as `text[start..end]=style` lines. +fn expectPage(raw: []const u8, text: []const u8, spans: []const struct { []const u8, CellStyle }) !void { + const page = try parse(testing.allocator, raw); + defer page.deinit(testing.allocator); + try testing.expectEqualStrings(text, page.text); + for (spans, 0..) |want, i| { + if (i >= page.spans.len) { + std.debug.print("missing span {d}: \"{s}\"\n", .{ i, want[0] }); + return error.TestExpectedEqual; + } + const got = page.spans[i]; + try testing.expectEqualStrings(want[0], page.text[got.start..got.end]); + try testing.expectEqualDeep(want[1], got.style); + } + try testing.expectEqual(spans.len, page.spans.len); +} + +test "git log --color: the commit line yellow, the rest plain" { + try expectPage( + "\x1b[33mcommit 0123abc\x1b[m\x1b[33m (\x1b[m\x1b[1;36mHEAD -> \x1b[m\x1b[1;32mmain\x1b[m\x1b[33m)\x1b[m\nAuthor: a <a@x>\n\n subject\n", + "commit 0123abc (HEAD -> main)\nAuthor: a <a@x>\n\n subject\n", + &.{ + .{ "commit 0123abc (", .{ .fg = .{ .index = 3 } } }, + .{ "HEAD -> ", .{ .fg = .{ .index = 6 }, .bold = true } }, + .{ "main", .{ .fg = .{ .index = 2 }, .bold = true } }, + .{ ")", .{ .fg = .{ .index = 3 } } }, + }, + ); +} + +test "ls --color=always: 01;34 directories and 01;32 executables, reset by 0 and none" { + try expectPage( + "\x1b[0m\x1b[01;34mdir\x1b[0m\n\x1b[01;32mrun.sh\x1b[0m\nplain.txt\n", + "dir\nrun.sh\nplain.txt\n", + &.{ + .{ "dir", .{ .fg = .{ .index = 4 }, .bold = true } }, + .{ "run.sh", .{ .fg = .{ .index = 2 }, .bold = true } }, + }, + ); +} + +test "grep --color=always: the match, the file name and the separator, and EL dropped" { + try expectPage( + "\x1b[35m\x1b[Ka.txt\x1b[m\x1b[K\x1b[36m\x1b[K:\x1b[m\x1b[Kone \x1b[01;31m\x1b[Kfoo\x1b[m\x1b[K two\n", + "a.txt:one foo two\n", + &.{ + .{ "a.txt", .{ .fg = .{ .index = 5 } } }, + .{ ":", .{ .fg = .{ .index = 6 } } }, + .{ "foo", .{ .fg = .{ .index = 1 }, .bold = true } }, + }, + ); +} + +test "a man page's overstrike: bold and underline, and a stray backspace" { + try expectPage( + "N\x08NA\x08AM\x08ME\x08E _\x08u_\x08s x\x08_ a\x08b\x08\n", + "NAME us x b\n", + &.{ + .{ "NAME", .{ .bold = true } }, + .{ "us", .{ .ul = .single } }, + .{ "x", .{ .ul = .single } }, + }, + ); +} + +test "truecolor, 256 colours, background, italic, faint, inverse and curly underline" { + try expectPage( + "\x1b[38;2;255;128;0mo\x1b[48;5;236mb\x1b[0;3;2mi\x1b[7mr\x1b[0;4:3mc\x1b[m.\n", + "obirc.\n", + &.{ + .{ "o", .{ .fg = .{ .rgb = .{ 255, 128, 0 } } } }, + .{ "b", .{ .fg = .{ .rgb = .{ 255, 128, 0 } }, .bg = .{ .index = 236 } } }, + .{ "i", .{ .italic = true, .dim = true } }, + .{ "r", .{ .italic = true, .dim = true, .reverse = true } }, + .{ "c", .{ .ul = .curly } }, + }, + ); +} + +test "every other escape is dropped, and a stray or broken one loses no text after it" { + const cases = [_][2][]const u8{ + .{ "a\x1b]8;;http://x\x1b\\link\x1b]8;;\x07b", "alinkb" }, + .{ "\x1b]0;title\x07\x1b[2J\x1b[H\x1b[?1049hdone\n", "done\n" }, + .{ "\x1b(Bdone", "done" }, + .{ "plain\ttext\n", "plain\ttext\n" }, + .{ "a\r\nb\r\n", "a\nb\n" }, + .{ "10%\r50%\r\x1b[K100%\ndone\n", "100%\ndone\n" }, + .{ "x\x00y\x07z\x0e\x0f\n", "xyz\n" }, + // Controls ghostty's fast path prints: CAN, FS, DEL and a C1. + .{ "x\x18y\x1cz\x7f!\u{85}?\n", "xyz!?\n" }, + // A broken CSI: its parameter bytes are eaten up to a final byte, as + // a terminal eats them; CAN abandons one, and the text goes on. + .{ "a\x1b[31;\x18b\x1b[m\n", "ab\n" }, + // An unknown SGR changes nothing; an ESC at the very end is dropped. + .{ "\x1b[99mz\x1b", "z" }, + }; + for (cases) |c| try expectPage(c[0], c[1], &.{}); +} + +test "bytes that are not UTF-8 page as U+FFFD, the text around them kept" { + try expectPage("caf\xe9 \xff\xfe ok\n", "caf\u{fffd} \u{fffd}\u{fffd} ok\n", &.{}); +} + +test "a carriage return's rewrite takes the spans of what it rewrote with it" { + try expectPage("\x1b[31m10%\r\x1b[32m100%\x1b[m\n", "100%\n", &.{.{ "100%", .{ .fg = .{ .index = 2 } } }}); +} + +test "colon colours, an 8-bit CSI, REP, CHT, CNL, a colour short of its values and UTF-8 cut short" { + try expectPage("\x1b[38:2::1:2:3mx\x1b[48:5:7my\x1b[m", "xy", &.{ + .{ "x", .{ .fg = .{ .rgb = .{ 1, 2, 3 } } } }, + .{ "y", .{ .fg = .{ .rgb = .{ 1, 2, 3 } }, .bg = .{ .index = 7 } } }, + }); + // 0x9b in text is a stray byte, U+FFFD; in a sequence (after ESC + // here) it is CSI; as UTF-8 (C2 9B) it is a C1 control, dropped. + try expectPage("x\x9b\x1b\x9b31mr\xc2\x9b32mg", "x\u{fffd}r32mg", &.{.{ "r32mg", .{ .fg = .{ .index = 1 } } }}); + // REP and CHT go on along the line; CNL returns, and `d` starts it over. + try expectPage("ab\x1b[3b\x1b[2Ic\n", "abbbb\t\tc\n", &.{}); + try expectPage("ab\x1b[Ed\n", "d\n", &.{}); + // 38;5 with no index: 38 is unknown and 5 is blink. + try expectPage("\x1b[38;5mx", "x", &.{.{ "x", .{ .blink = true } }}); + try expectPage("ok\xe2\x82", "ok", &.{}); + try expectPage("\xe2\x82x", "\u{fffd}x", &.{}); +} diff --git a/src/screen_state.zig b/src/term/screen_state.zig index 8032e79a..43eae542 100644 --- a/src/screen_state.zig +++ b/src/term/screen_state.zig @@ -24,7 +24,7 @@ //! delta against another (one lost) is refused, and the peer started afresh. //! //! The replica writes each delta into a ghostty Terminal, which a replica's -//! terminal pane draws as a local one (src/terminal.zig reads only that). +//! terminal pane draws as a local one (src/term/terminal.zig reads only that). //! Rows that scroll off its active area go into its history, made what the //! authority's are by the delta's tail (their addresses, up to a screen of //! them). Older ones it never saw, or saw before they last changed, are @@ -1135,282 +1135,6 @@ pub fn yesStream(gpa: std.mem.Allocator, lines: usize) ![]u8 { return out; } -// ---- a pane of a kind, as a Shadow (architecture §16.5) ---- -// -// A replica's core has no code for a library's kind: such a pane is drawn -// from the authority's frame of it, painted at the size the peer's view -// gives it. A frame crosses as its size and the pointer it asks for, each -// row by its hash (with its cells when the peer's row there is another), -// then each placement by its key; its raster's pixels cross before it, as -// strips of rows (`raster` messages, `encodeStrip`), those over its `src` -// the peer was not sent with the frame before. The stream is ordered and -// loses nothing, so what the authority last sent a peer is what the peer -// holds, but for a raster its `Blobs` let go, which it asks for again. - -const Kind = @import("Kind.zig"); -const Cell = Kind.c.pa_cell; -const Place = Kind.c.pa_placement; - -/// A replica's frame of a pane of a kind: what Kind.draw draws for it, its -/// placements' pixels its peer's `Blobs`. -pub const Shadow = struct { - gpu: []const u8 = &.{}, - cols: u16 = 0, - rows: u16 = 0, - cells: []Cell = &.{}, - hashes: []Hash = &.{}, - places: std.ArrayList(Place) = .empty, - pointer: u8 = 0, - /// The raster it last asked for again (`apply`'s): asked once. - wanted: u64 = 0, - - pub fn deinit(sh: *Shadow, gpa: std.mem.Allocator) void { - gpa.free(sh.gpu); - gpa.free(sh.cells); - gpa.free(sh.hashes); - sh.places.deinit(gpa); - gpa.destroy(sh); - } - - /// A frame message applied (`encodeShadow`'s), of the pane `serial`, - /// each placement's pixels from `blobs`: one it lacks is not shown, and - /// its name is what to ask for (once), else 0. - pub fn apply(sh: *Shadow, gpa: std.mem.Allocator, bytes: []const u8, serial: u32, blobs: *Blobs) !u64 { - var r: std.Io.Reader = .fixed(bytes); - const cols = try r.takeInt(u16, .little); - const rows = try r.takeInt(u16, .little); - if (cols != sh.cols or rows != sh.rows) { - gpa.free(sh.cells); - gpa.free(sh.hashes); - sh.cells = try gpa.alloc(Cell, @as(usize, cols) * rows); - sh.hashes = try gpa.alloc(Hash, rows); - @memset(std.mem.sliceAsBytes(sh.cells), 0); - @memset(sh.hashes, 0); - sh.cols = cols; - sh.rows = rows; - } - sh.pointer = try r.takeByte(); - for (0..rows) |y| { - sh.hashes[y] = try r.takeInt(u64, .little); - if (try r.takeByte() == 0) continue; - for (sh.cells[y * cols ..][0..cols]) |*c| { - @memcpy(&c.text, try r.take(8)); - c.fg = try r.takeInt(u32, .little); - c.bg = try r.takeInt(u32, .little); - c.attrs = try r.takeInt(u16, .little); - c.len = try r.takeByte(); - c.flags = try r.takeByte(); - } - } - sh.places.clearRetainingCapacity(); - var lacking: u64 = 0; - for (0..try r.takeByte()) |_| { - var pl = std.mem.zeroes(Place); - pl.w = try r.takeInt(u32, .little); - pl.h = try r.takeInt(u32, .little); - inline for (.{ &pl.src.x, &pl.src.y, &pl.src.w, &pl.src.h, &pl.at.x, &pl.at.y, &pl.at.w, &pl.at.h }) |f| f.* = try r.takeInt(u32, .little); - inline for (.{ &pl.dst.x, &pl.dst.y, &pl.dst.w, &pl.dst.h }) |f| f.* = try r.takeInt(u16, .little); - pl.key = try r.takeInt(u64, .little); - const name = std.hash.Wyhash.hash(serial, std.mem.asBytes(&pl.key)); - pl.rgba = (blobs.shows(name, &pl) orelse { - lacking = name; - continue; - }).ptr; - try sh.places.append(gpa, pl); - } - // Older frames have no optional GPU tail. - const n = if (r.seek < r.end) try r.takeInt(u32, .little) else 0; - if (n > 4 << 20) return error.BadGpuFrame; - const gpu = try gpa.dupe(u8, try r.take(n)); - gpa.free(sh.gpu); - sh.gpu = gpu; - if (lacking == sh.wanted) return 0; - sh.wanted = lacking; - return lacking; - } -}; - -/// A raster's strip: at most this many bytes of its rows (17.3). -pub const strip_max = 4 << 20; - -/// How many of a `w`-pixel raster's rows a strip holds. -pub fn stripRows(w: u32) u32 { - return @max(1, strip_max / (@as(u32, @max(w, 1)) * 4)); -} - -/// The strips of `pl`'s raster over its `src` rows, a bit each. -fn stripsOver(pl: *const Place) u64 { - const per = stripRows(pl.w); - const lo = @min(pl.src.y, pl.h) / per; - const hi = (@min(pl.src.y +| pl.src.h, pl.h) + per - 1) / per; - var bits: u64 = 0; - for (lo..@min(hi, 64)) |i| bits |= @as(u64, 1) << @intCast(i); - return bits; -} - -/// Strip `i` of `pl`'s raster, a `raster` message's payload: its key, its -/// size, its first row, and its rows' bytes. -pub fn encodeStrip(pl: *const Place, i: u32, w: *std.Io.Writer) !void { - const y0 = i * stripRows(pl.w); - const row = @as(usize, pl.w) * 4; - try w.writeInt(u64, pl.key, .little); - try w.writeInt(u32, pl.w, .little); - try w.writeInt(u32, pl.h, .little); - try w.writeInt(u32, y0, .little); - try w.writeAll(pl.rgba[y0 * row .. @min(pl.h, y0 + stripRows(pl.w)) * row]); -} - -/// A peer's rasters of the panes of a kind, made from their strips by -/// name (the key with its pane's serial), kept to `max` bytes by least -/// recent use but for those a Shadow shows (17.3). -pub const Blobs = struct { - list: std.ArrayList(Blob) = .empty, - clock: u64 = 0, - - pub const max = 64 << 20; - const Blob = struct { name: u64, w: u32, h: u32, bytes: []u8, have: u64 = 0, used: u64 = 0 }; - - pub fn deinit(b: *Blobs, gpa: std.mem.Allocator) void { - for (b.list.items) |x| gpa.free(x.bytes); - b.list.deinit(gpa); - } - - /// A `raster` message's payload (`encodeStrip`'s) into raster `name`, - /// made at its first strip; `shown`, the pixels Shadows show now. - pub fn strip(b: *Blobs, gpa: std.mem.Allocator, name: u64, payload: []const u8, shown: []const [*]const u8) !void { - var r: std.Io.Reader = .fixed(payload); - _ = try r.takeInt(u64, .little); - const w = try r.takeInt(u32, .little); - const h = try r.takeInt(u32, .little); - const y0 = try r.takeInt(u32, .little); - const rows = r.buffered(); - const row = @as(usize, w) * 4; - if (row == 0 or rows.len % row != 0 or y0 % stripRows(w) != 0 or y0 + rows.len / row > h) return error.BadShadow; - const x = for (b.list.items) |*x| { - if (x.name == name) break x; - } else made: { - var held: usize = row * h; - for (b.list.items) |x| held += x.bytes.len; - while (held > max) { - var old: ?usize = null; - for (b.list.items, 0..) |x, i| if (std.mem.indexOfScalar([*]const u8, shown, x.bytes.ptr) == null and (old == null or x.used < b.list.items[old.?].used)) { - old = i; - }; - const i = old orelse break; - held -= b.list.items[i].bytes.len; - gpa.free(b.list.swapRemove(i).bytes); - } - const bytes = try gpa.alloc(u8, row * h); - errdefer gpa.free(bytes); - try b.list.append(gpa, .{ .name = name, .w = w, .h = h, .bytes = bytes }); - break :made &b.list.items[b.list.items.len - 1]; - }; - if (x.w != w or x.h != h) return error.BadShadow; - @memcpy(x.bytes[y0 * row ..][0..rows.len], rows); - x.have |= @as(u64, 1) << @intCast(@min(63, y0 / stripRows(w))); - b.clock += 1; - x.used = b.clock; - } - - /// Raster `name`'s pixels when it has every strip `pl` shows. - fn shows(b: *Blobs, name: u64, pl: *const Place) ?[]u8 { - for (b.list.items) |*x| if (x.name == name and x.w == pl.w and x.h == pl.h and stripsOver(pl) & ~x.have == 0) { - b.clock += 1; - x.used = b.clock; - return x.bytes; - }; - return null; - } -}; - -/// What the authority last sent one peer of a pane of a kind: its rows' -/// hashes, its placements, and which strips of each raster it holds. -pub const ShadowSent = struct { - serial: u32 = 0, - cols: u16 = 0, - hashes: std.ArrayList(Hash) = .empty, - places: Hash = 0, - keys: std.ArrayList(struct { key: u64, have: u64 }) = .empty, - - pub fn deinit(s: *ShadowSent, gpa: std.mem.Allocator) void { - s.hashes.deinit(gpa); - s.keys.deinit(gpa); - s.* = .{}; - } - - /// The strips of `pl`'s raster over its `src` the peer lacks (a bit - /// each, `encodeStrip`'s `i`), counted sent now. - pub fn owed(s: *ShadowSent, gpa: std.mem.Allocator, pl: *const Place) !u64 { - const need = stripsOver(pl); - for (s.keys.items) |*k| if (k.key == pl.key) { - defer k.have |= need; - return need & ~k.have; - }; - try s.keys.append(gpa, .{ .key = pl.key, .have = need }); - return need; - } -}; - -/// Frame `f` of a pane (the pointer its paint asked for) for a peer that -/// was last sent `sent`: false, and nothing written, when it holds this -/// frame already. Its placements cross by key, their pixels as strips -/// before it (`ShadowSent.owed`), so a frame is small whatever it shows. -pub fn encodeShadow(gpa: std.mem.Allocator, sent: *ShadowSent, f: *const Kind.Frame, pointer: u8, w: *std.Io.Writer) !bool { - var hashes: std.ArrayList(Hash) = .empty; - errdefer hashes.deinit(gpa); - for (0..f.rows) |y| try hashes.append(gpa, std.hash.Wyhash.hash(0, std.mem.sliceAsBytes(f.cells[y * f.cols ..][0..f.cols]))); - const places = f.places[0..@min(f.n, 64)]; - var ph = std.hash.Wyhash.init(pointer); - for (places) |*pl| inline for (.{ pl.w, pl.h, pl.src, pl.at, pl.dst, pl.key }) |v| ph.update(std.mem.asBytes(&v)); - if (f.gpu.len != 0) ph.update(f.gpu); - const places_hash = ph.final(); - if (sent.cols == f.cols and std.mem.eql(Hash, sent.hashes.items, hashes.items) and sent.places == places_hash) { - hashes.deinit(gpa); - return false; - } - try w.writeInt(u16, f.cols, .little); - try w.writeInt(u16, f.rows, .little); - try w.writeByte(pointer); - for (hashes.items, 0..) |h, y| { - try w.writeInt(u64, h, .little); - // Held only at the same size: a peer's Shadow of another starts afresh. - const held = sent.cols == f.cols and sent.hashes.items.len == f.rows and sent.hashes.items[y] == h; - try w.writeByte(@intFromBool(!held)); - if (!held) for (f.cells[y * f.cols ..][0..f.cols]) |*c| { - try w.writeAll(&c.text); - try w.writeInt(u32, c.fg, .little); - try w.writeInt(u32, c.bg, .little); - try w.writeInt(u16, c.attrs, .little); - try w.writeByte(c.len); - try w.writeByte(c.flags); - }; - } - try w.writeByte(@intCast(places.len)); - for (places) |pl| { - try w.writeInt(u32, pl.w, .little); - try w.writeInt(u32, pl.h, .little); - inline for (.{ pl.src.x, pl.src.y, pl.src.w, pl.src.h, pl.at.x, pl.at.y, pl.at.w, pl.at.h }) |v| try w.writeInt(u32, v, .little); - inline for (.{ pl.dst.x, pl.dst.y, pl.dst.w, pl.dst.h }) |v| try w.writeInt(u16, v, .little); - try w.writeInt(u64, pl.key, .little); - } - if (f.gpu.len > 4 << 20) return error.BadGpuFrame; - try w.writeInt(u32, @intCast(f.gpu.len), .little); - try w.writeAll(f.gpu); - sent.hashes.deinit(gpa); - sent.hashes = hashes; - sent.cols = f.cols; - sent.places = places_hash; - // The strips of the rasters this frame shows: a key gone is sent whole again. - var i: usize = 0; - while (i < sent.keys.items.len) { - const kept = for (places) |pl| { - if (pl.key == sent.keys.items[i].key) break true; - } else false; - if (kept) i += 1 else _ = sent.keys.swapRemove(i); - } - return true; -} - test "a replica's screen is its authority's, cell for cell, as states are skipped, resized and fetched" { const gpa = testing.allocator; const io = testing.io; @@ -1517,7 +1241,7 @@ test "several deltas in flight land in order, and a peer at the bound waits for } test "a replica's terminal pane draws as its authority's does" { - const pardes = @import("pardes.zig"); + const pardes = @import("../pardes.zig"); const gpa = testing.allocator; const a = try pardes.Pardes.init(gpa, .{ .tty_only = true, .cols = 60, .rows = 16 }); defer a.deinit(); @@ -1568,97 +1292,3 @@ test "a replica's terminal pane draws as its authority's does" { }; } } - -test "a pane of a kind's frame a row taller or shorter is drawn whole at its peer, never a row it let go" { - const gpa = std.testing.allocator; - var cells: [2 * 3]Cell = @splat(std.mem.zeroes(Cell)); - cells[0] = .{ .text = "a".* ++ @as([7]u8, @splat(0)), .fg = 1, .bg = 2, .attrs = 0, .len = 1, .flags = Kind.c.PA_PAINTED }; - var f: Kind.Frame = .{ .cells = &cells, .cols = 2, .rows = 2 }; - var sent: ShadowSent = .{}; - defer sent.deinit(gpa); - var blobs: Blobs = .{}; - const sh = try gpa.create(Shadow); - sh.* = .{}; - defer sh.deinit(gpa); - var out: std.Io.Writer.Allocating = .init(gpa); - defer out.deinit(); - for ([_]u16{ 2, 3, 2 }) |rows| { - f.rows = rows; - out.clearRetainingCapacity(); - try std.testing.expect(try encodeShadow(gpa, &sent, &f, 0, &out.writer)); - _ = try sh.apply(gpa, out.written(), 1, &blobs); - try std.testing.expectEqualStrings("a", sh.cells[0].text[0..1]); - } -} - -test "a pane of a kind crosses as its frame, a row the peer holds as its hash, a raster by key after its strips over what it shows" { - const gpa = std.testing.allocator; - var cells: [3 * 2]Cell = @splat(std.mem.zeroes(Cell)); - cells[0] = .{ .text = "a".* ++ @as([7]u8, @splat(0)), .fg = 1, .bg = 2, .attrs = 0, .len = 1, .flags = Kind.c.PA_PAINTED }; - // A raster of three strips (4 MiB a strip at 1,024 px), of which it shows the second. - const w: u32 = 1024; - const per = stripRows(w); - const pixels = try gpa.alloc(u8, @as(usize, w) * per * 3 * 4); - defer gpa.free(pixels); - @memset(pixels, 5); - var f: Kind.Frame = .{ .cells = &cells, .cols = 3, .rows = 2, .n = 1 }; - f.buf[0] = std.mem.zeroInit(Place, .{ .rgba = pixels.ptr, .w = w, .h = per * 3, .src = .{ .x = 0, .y = per + 1, .w = w, .h = 10 }, .key = 9 }); - f.places = &f.buf; - var sent: ShadowSent = .{}; - defer sent.deinit(gpa); - var blobs: Blobs = .{}; - defer blobs.deinit(gpa); - const sh = try gpa.create(Shadow); - sh.* = .{}; - defer sh.deinit(gpa); - var out: std.Io.Writer.Allocating = .init(gpa); - defer out.deinit(); - const name = std.hash.Wyhash.hash(1, std.mem.asBytes(&f.buf[0].key)); - try std.testing.expectEqual(@as(u64, 0b010), try sent.owed(gpa, &f.buf[0])); - try encodeStrip(&f.buf[0], 1, &out.writer); - try std.testing.expect(out.written().len <= strip_max + 20); - try blobs.strip(gpa, name, out.written(), &.{}); - out.clearRetainingCapacity(); - try std.testing.expect(try encodeShadow(gpa, &sent, &f, 0, &out.writer)); - try std.testing.expectEqual(@as(u64, 0), try sh.apply(gpa, out.written(), 1, &blobs)); - try std.testing.expectEqualStrings("a", sh.cells[0].text[0..1]); - try std.testing.expectEqual(@as(u8, 5), sh.places.items[0].rgba[per * w * 4]); - // The same frame again: nothing to send, no strip owed. - out.clearRetainingCapacity(); - try std.testing.expect(!try encodeShadow(gpa, &sent, &f, 0, &out.writer)); - try std.testing.expectEqual(@as(u64, 0), try sent.owed(gpa, &f.buf[0])); - // Its src moves into the third strip: that one is owed, and a peer - // without it does not show the raster and asks for it, once. - f.buf[0].src.y = 2 * per + 1; - try std.testing.expectEqual(@as(u64, 0b100), try sent.owed(gpa, &f.buf[0])); - out.clearRetainingCapacity(); - try std.testing.expect(try encodeShadow(gpa, &sent, &f, 0, &out.writer)); - try std.testing.expect(out.written().len < 4 + 1 + 2 * 9 + 60 + 8); - try std.testing.expectEqual(name, try sh.apply(gpa, out.written(), 1, &blobs)); - try std.testing.expectEqual(@as(usize, 0), sh.places.items.len); - try std.testing.expectEqual(@as(u64, 0), try sh.apply(gpa, out.written(), 1, &blobs)); -} - -test "optional GPU frames cross shadows, change independently, and disappear" { - const gpa = std.testing.allocator; - var sent: ShadowSent = .{}; - defer sent.deinit(gpa); - const shadow = try gpa.create(Shadow); - shadow.* = .{}; - defer shadow.deinit(gpa); - var blobs: Blobs = .{}; - defer blobs.deinit(gpa); - var cell = std.mem.zeroes(Cell); - var frame: Kind.Frame = .{ .cols = 1, .rows = 1, .cells = @as([*]Cell, @ptrCast(&cell))[0..1], .gpu = "first scene" }; - var out: std.Io.Writer.Allocating = .init(gpa); - defer out.deinit(); - for ([_][]const u8{ "first scene", "second scene", "" }) |bytes| { - frame.gpu = bytes; - out.clearRetainingCapacity(); - try std.testing.expect(try encodeShadow(gpa, &sent, &frame, 0, &out.writer)); - _ = try shadow.apply(gpa, out.written(), 1, &blobs); - try std.testing.expectEqualStrings(bytes, shadow.gpu); - out.clearRetainingCapacity(); - try std.testing.expect(!try encodeShadow(gpa, &sent, &frame, 0, &out.writer)); - } -} diff --git a/src/terminal.zig b/src/term/terminal.zig index 4ee2e9fa..85ac859d 100644 --- a/src/terminal.zig +++ b/src/term/terminal.zig @@ -1,16 +1,19 @@ //! A terminal pane: its VT emulator, prompt rows, the edit overlay //! typed over shell rows, and the Filter that recolours output to the theme. -const panes = @import("panes.zig"); +const panes = @import("../panes.zig"); const std = @import("std"); -const pardes = @import("pardes.zig"); -const config = @import("config.zig"); +const pardes = @import("../pardes.zig"); +const config = @import("../config.zig"); const Pardes = pardes.Pardes; const Surface = pardes.Surface; -const modal = @import("modal.zig"); -const tracy = @import("tracy.zig"); -const tagline = @import("tagline.zig"); +const modal = @import("../modal.zig"); +const tracy = @import("../tracy.zig"); +const tagline = @import("../tagline.zig"); const Key = pardes.Key; const Pane = panes.Pane; +const Term = @import("../Term.zig"); +const BodyWalk = @import("../body_layer.zig").BodyWalk; +const screen_state = @import("screen_state.zig"); const EditText = panes.EditText; const File = panes.File; @@ -21,7 +24,7 @@ const Snapshot = panes.Text.Snapshot; const history_max = panes.Text.history_max; pub const VtSlot = ghostty_vt.Terminal; -/// A cell of an emulator's pages, as `getCell` reads it (src/echo.zig). +/// A cell of an emulator's pages, as `getCell` reads it (src/term/echo.zig). pub const PageCell = ghostty_vt.PageList.Cell; /// Kitty graphics: a program's images are placements, as a kind's are. pub const images_enabled = true; @@ -321,8 +324,8 @@ pub const State = struct { defer decoded.deinit(gpa); out.* = .{ .gpa = gpa, .vt = decoded.toOwned(), .stream = undefined }; } - if (comptime images_enabled) inline for (.{ .primary, .alternate }) |key| { - if (out.vt.screens.get(key)) |screen| screen.kitty_images.image_limits = .allWithTempDir(tempDir()); + if (comptime images_enabled) inline for (.{ .primary, .alternate }) |which| { + if (out.vt.screens.get(which)) |screen| screen.kitty_images.image_limits = .allWithTempDir(tempDir()); }; out.wire(); const reply = parts.reply[0..@min(parts.reply.len, out.reply.len)]; @@ -403,13 +406,13 @@ const LivePalette = struct { for (&base, synthesized) |*dst, src| dst.* = asGhostRgb(src); } - const key: FilterPaletteKey = .{ .bg = bg, .fg = fg, .base = base }; - if (self.key) |old| if (std.meta.eql(old, key)) return &self.colors; + const wanted: FilterPaletteKey = .{ .bg = bg, .fg = fg, .base = base }; + if (self.key) |old| if (std.meta.eql(old, wanted)) return &self.colors; var seed = GColor.default; for (base, 0..) |rgb, i| seed[i] = rgb; self.colors = GColor.generate256Color(seed, .empty, bg, fg, false); - self.key = key; + self.key = wanted; return &self.colors; } }; @@ -418,85 +421,6 @@ fn asGhostRgb(rgb: [3]u8) GColor.RGB { return .{ .r = rgb[0], .g = rgb[1], .b = rgb[2] }; } -pub const PendingCommand = struct { - bytes: []u8 = &.{}, - wait: enum { none, spawn, input } = .none, -}; - -pub fn armShellSpawn(pane: *Pane) void { - std.debug.assert(pane.pending_command.bytes.len == 0); - pane.pending_command.wait = .spawn; -} - -/// Remembers a line pardes types into this terminal as the command it -/// started, for Kill: it runs from the shell's next C mark to its D. -/// ponytail: of several lines queued for a shell not up yet, only the last -/// is remembered, as the first of them. -pub fn noteCommand(pane: *Pane, line: []const u8) void { - const state = pane.terminal orelse return; - const word = std.mem.trim(u8, line, " \t")[0 .. std.mem.indexOfAny(u8, std.mem.trim(u8, line, " \t"), " \t") orelse std.mem.trim(u8, line, " \t").len]; - var sent: @typeInfo(@FieldType(Pane, "sent_command")).optional.child = .{ .seq = state.stream.handler.started +% 1 }; - sent.len = @intCast(@min(word.len, sent.word.len)); - @memcpy(sent.word[0..sent.len], word[0..sent.len]); - pane.sent_command = sent; -} - -/// Whether the command pardes last typed here is running now. -pub fn commandRunning(pane: *const Pane) bool { - const state = pane.terminal orelse return false; - const sent = pane.sent_command orelse return false; - const marks = &state.stream.handler; - return marks.phase == .running and marks.started == sent.seq; -} - -pub fn queuePendingCommand(pane: *Pane, command: []const u8) !bool { - if (pane.pending_command.wait == .none) return false; - const old_len = pane.pending_command.bytes.len; - const new_len = try std.math.add(usize, old_len, try std.math.add(usize, command.len, 1)); - const bytes = if (old_len == 0) - try pane.gpa.alloc(u8, new_len) - else - try pane.gpa.realloc(pane.pending_command.bytes, new_len); - @memcpy(bytes[old_len..][0..command.len], command); - bytes[new_len - 1] = '\r'; - pane.pending_command.bytes = bytes; - pane.greet = false; - return true; -} - -pub fn shellSpawned(p: *Pardes, id: usize, prompt_marks: bool) void { - const pane = p.panes[id] orelse return; - if (!pane.isTerminal() or pane.pending_command.wait != .spawn) return; - if (prompt_marks) { - pane.pending_command.wait = .input; - releasePendingCommand(p, id, pane, false); - } else { - pane.greet = false; - releasePendingCommand(p, id, pane, true); - } -} - -pub fn releasePendingCommandIfReady(p: *Pardes, id: usize, pane: *Pane) void { - if (pane.pending_command.wait == .input) - releasePendingCommand(p, id, pane, pardes.tape.value(.prompt, promptInputReady, .{pane})); -} - -fn releasePendingCommand(p: *Pardes, id: usize, pane: *Pane, ready: bool) void { - if (!ready) return; - const bytes = pane.pending_command.bytes; - pane.pending_command = .{}; - if (bytes.len > 0) { - p.emitWrite(id, bytes); - pane.gpa.free(bytes); - } -} - -pub fn deinitPendingCommand(pane: *Pane) void { - if (pane.pending_command.bytes.len > 0) - pane.gpa.free(pane.pending_command.bytes); - pane.pending_command = .{}; -} - /// Where a kitty client puts its temporary files: `$TMPDIR`, else /tmp /// (which ghostty accepts whatever this says). The environment block lives /// as long as the process and pardes never edits it (ChildEnv.exportVar). @@ -510,55 +434,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 @@ -594,90 +484,91 @@ pub fn takeMarks(state: *State, bytes: []const u8) void { m.finished = if (seq == std.math.maxInt(u32)) null else .{ .seq = seq, .status = if (status == std.math.minInt(i32)) null else status }; } -/// A screen-state replica's emulators' allocator (`State.gpa`). -pub const emulator_gpa = std.heap.c_allocator; +// ---- its replicas: the screen state they are sent (screen_state.zig) ---- -/// What a terminal's emulator is made with, by `create` or a pane's load -/// (dump.loadPane, a closed terminal brought back): `gpa`, but on a screen- -/// state replica `emulator_gpa`. -pub fn emulatorGpa(gpa: std.mem.Allocator) std.mem.Allocator { - return if (pardes.tape.screenReplica()) emulator_gpa else gpa; +/// What `peer` is owed of it, a delta against what it was sent (with the +/// marks of its prompt cycle), onto `out`; false when it has it already. +pub fn encode(state: *State, enc: *screen_state.Encoder, track: *screen_state.Track, peer: *screen_state.Peer, out: *std.Io.Writer) !bool { + var marks: [marks_len]u8 = undefined; + return screen_state.encode(enc, track, peer, &state.vt, state.changes, marksOf(state, &marks), out); } -/// A replica's speculation leaves an emulator be: it is the authority's -/// (docs/next-daemon.md, phase 5), so the input waits for its order. -fn authorityOnly(comptime why: []const u8) bool { - if (!pardes.tape.speculating()) return false; - pardes.tape.poison(why); - return true; +/// Its rows `lo` to `hi` (absolute), as a replica holding them as holes +/// is sent them. +pub fn encodeRows(state: *State, enc: *screen_state.Encoder, track: *screen_state.Track, lo: u64, hi: u64, out: *std.Io.Writer) !void { + return screen_state.encodeRows(enc, track, &state.vt, lo, hi, out); } -/// 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; +/// What `track` kept of its versions, freed; `state` null when its pane is +/// gone with the emulator. +pub fn untrack(track: *screen_state.Track, gpa: std.mem.Allocator, state: ?*State) void { + track.deinit(gpa, if (state) |s| &s.vt else null); } -/// 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; +/// Whether a step read its rows since `clearRead` (`markRead`). +pub fn wasRead(state: *const State) bool { + return state.read; } -pub fn viewTo(pane: *Pane, at: ?usize) void { - const state = pane.terminal orelse return; +pub fn clearRead(state: *State) void { + state.read = false; +} + +/// A replica's terminal takes its authority's delta (and the marks riding +/// it); error.BaseMismatch when it is against a state not held here. +pub fn apply(state: *State, rep: *screen_state.Replica, bytes: []const u8) !screen_state.Replica.Applied { + const applied = try rep.apply(state.gpa, terminalIo(), &state.vt, bytes); + takeMarks(state, applied.extra); + return applied; +} + +/// ...and rows it asked for. +pub fn applyRows(state: *State, rep: *screen_state.Replica, bytes: []const u8) !void { + return rep.applyRows(state.gpa, &state.vt, bytes); +} + +/// The absolute rows its view shows on a replica. +pub fn shown(state: *State, rep: *const screen_state.Replica) [2]u64 { + return rep.shown(&state.vt); +} + +/// Its screen as text, every row's cells and flags (the replica tests +/// compare an authority's and a replica's). +pub fn dumpScreen(state: *State, w: *std.Io.Writer) !void { + return screen_state.dumpScreen(&state.vt, w); +} + +/// Rows `lo` to `hi` shown blank on a replica until they come. +pub fn blank(state: *State, rep: *const screen_state.Replica, lo: u64, hi: u64) void { + rep.blank(&state.vt, lo, hi); +} + +const authorityOnly = pardes.tape.authorityOnly; + +/// 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; } @@ -685,27 +576,47 @@ 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; } -/// DECSET 2004: the program wants its pastes bracketed. -pub fn bracketedPaste(pane: *const Pane) bool { - const state = pane.terminal orelse return false; - return state.vt.modes.get(.bracketed_paste); +/// 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]; } -/// The program tracks the mouse itself, so a click in its body is its event. -pub fn reportsMouse(pane: *const Pane) bool { - const state = pane.terminal orelse return false; - return state.vt.flags.mouse_event != .none; +/// The modes its program set that the core decides by (`Term.Modes`). +pub fn modes(state: ?*const State) Term.Modes { + const s = state orelse return .{}; + const alternate = s.vt.screens.active_key == .alternate; + const mouse_event = s.vt.flags.mouse_event != .none; + return .{ + .mouse = mouse_event, + .all_motion = s.vt.flags.mouse_event == .any, + // On the alternate screen, which has no scrollback, alternate + // scroll (DECSET 1007, on unless turned off) asks for arrow keys. + .wheel = mouse_event or (alternate and s.vt.modes.get(.mouse_alternate_scroll)), + .focus = s.vt.modes.get(.focus_event), + .bracketed_paste = s.vt.modes.get(.bracketed_paste), + .alternate = alternate, + }; } /// A paste as xterm makes one (ghostty's encoder): the control bytes a @@ -713,35 +624,10 @@ pub fn reportsMouse(pane: *const Pane) bool { /// 2004's brackets early, NUL, ^C and the rest of xterm's list) become /// spaces, then the text goes inside the brackets when the program set /// 2004, else with its newlines as Returns. `text` is rewritten in place. -pub fn encodePaste(pane: *const Pane, text: []u8) [3][]const u8 { - return ghostty_vt.input.encodePaste(text, .{ .bracketed = bracketedPaste(pane) }); -} - -/// DECSET 1004: the program wants to hear when it gains and loses focus. -pub fn reportsFocus(pane: *const Pane) bool { - const state = pane.terminal orelse return false; - return state.vt.modes.get(.focus_event); +pub fn paste(state: ?*const State, text: []u8) [3][]const u8 { + return ghostty_vt.input.encodePaste(text, .{ .bracketed = modes(state).bracketed_paste }); } -/// ...every move of it, a button down or not (1003). -pub fn tracksAllMotion(pane: *const Pane) bool { - const state = pane.terminal orelse return false; - return state.vt.flags.mouse_event == .any; -} - -/// A wheel over the program is the program's: it tracks the mouse, or it is -/// on the alternate screen, which has no scrollback, with alternate scroll -/// (DECSET 1007, on unless turned off) asking for arrow keys instead. -pub fn ownsWheel(pane: *const Pane) bool { - const state = pane.terminal orelse return false; - return reportsMouse(pane) or - (state.vt.screens.active_key == .alternate and state.vt.modes.get(.mouse_alternate_scroll)); -} - -pub const MouseMods = struct { shift: bool = false, alt: bool = false, ctrl: bool = false }; -pub const MouseButton = enum { left, middle, right, wheel_up, wheel_down, wheel_left, wheel_right }; -pub const MouseAction = enum { press, release, motion }; - /// One mouse event for the program, as xterm reports it (ctlseqs; ghostty's /// encoder): the tracking mode it set (1000 clicks, 1002 drags, 1003 all /// motion) decides whether it hears of it, the format it set (1006 SGR, @@ -749,8 +635,7 @@ pub const MouseAction = enum { press, release, motion }; /// ctrl+16. `col`,`row` are the 0-based grid cell; a drag that left the /// grid is reported clamped to its edge, motion only when the cell /// changed. Empty when the program does not hear of it. -pub fn mouseBytes(pane: *Pane, buf: *[64]u8, action: MouseAction, button: ?MouseButton, mods: MouseMods, col: i32, row: i32, any_pressed: bool) []const u8 { - const state = pane.terminal orelse return &.{}; +pub fn mouse(state: *State, buf: *[64]u8, action: Term.MouseAction, button: ?Term.MouseButton, mods: Term.MouseMods, col: i32, row: i32, any_pressed: bool) []const u8 { const input = ghostty_vt.input; var writer = std.Io.Writer.fixed(buf); var opts: input.MouseEncodeOptions = .{ @@ -790,32 +675,32 @@ pub fn mouseBytes(pane: *Pane, buf: *[64]u8, action: MouseAction, button: ?Mouse /// The bytes a wheel turn at grid cell `col`,`row` (0-based) sends the /// program: its mouse report while it tracks the mouse, else, on the /// alternate screen, an arrow key in the cursor keys' mode (none for a -/// sideways turn). Null when the wheel is not the program's (`ownsWheel`). -pub fn wheelBytes(pane: *Pane, buf: *[64]u8, wheel: MouseButton, col: u16, row: u16, mods: MouseMods) ?[]const u8 { - const state = pane.terminal orelse return null; - if (!ownsWheel(pane)) return null; +/// sideways turn). Null when the wheel is not the program's (`Modes.wheel`). +pub fn wheel(state: *State, buf: *[64]u8, turn: Term.MouseButton, col: u16, row: u16, mods: Term.MouseMods) ?[]const u8 { + const now = modes(state); + if (!now.wheel) return null; const m = &state.vt.modes; - if (!reportsMouse(pane)) return switch (wheel) { + if (!now.mouse) return switch (turn) { .wheel_up => if (m.get(.cursor_keys)) "\x1bOA" else "\x1b[A", .wheel_down => if (m.get(.cursor_keys)) "\x1bOB" else "\x1b[B", else => null, }; - return mouseBytes(pane, buf, .press, wheel, mods, col, row, false); + return mouse(state, buf, .press, turn, mods, col, row, false); } /// The whole scrollback as plain text, `gpa`-owned: what a terminal's body /// reads and `Save` writes out. Logical lines: rows the terminal wrapped /// are joined again (ghostty's wrap flags, as pty/run's output is), and /// the last line ends with a newline. -pub fn screenTextAlloc(pane: *Pane, gpa: std.mem.Allocator) ![]const u8 { +pub fn scrollback(state: ?*State, gpa: std.mem.Allocator) ![]const u8 { var out: std.Io.Writer.Allocating = .init(gpa); errdefer out.deinit(); - try writeScreenText(pane, &out.writer); + try writeBody(state, &out.writer); return out.toOwnedSlice(); } -fn writeScreenText(pane: *Pane, w: *std.Io.Writer) !void { - const state = pane.terminal orelse return; +fn writeBody(maybe: ?*State, w: *std.Io.Writer) !void { + const state = maybe orelse return; const screen = state.vt.screens.active; const br = screen.pages.getBottomRight(.screen) orelse return; var both: TeeWriter = .{ .a = w }; @@ -854,30 +739,26 @@ const TeeWriter = struct { } }; -/// How long `screenTextAlloc` would be, counted without keeping it: the -/// length a terminal's body reads as, which its ctl line reports. -pub fn screenTextLen(pane: *Pane) usize { +/// How long `scrollback` would be, counted without keeping it: the length a +/// terminal's body reads as, which its ctl line reports. +pub fn scrollbackLen(state: ?*State) usize { var buf: [256]u8 = undefined; var counting: std.Io.Writer.Discarding = .init(&buf); - writeScreenText(pane, &counting.writer) catch unreachable; // a discarding writer never fails + writeBody(state, &counting.writer) catch unreachable; // a discarding writer never fails return @intCast(counting.fullCount()); } -/// Release the emulator's heap. The Pane allocation itself is the core's. -pub fn deinitEmulator(pane: *Pane, gpa: std.mem.Allocator) void { - // A pane with none (a file's, a picker's, a preview's) closes in a - // speculation as anywhere. - const state = pane.terminal orelse return; - if (authorityOnly("close a terminal")) return; +/// Its emulator and what it holds, freed; its kitty images' caches were +/// `gpa`'s. +pub fn close(state: *State, gpa: std.mem.Allocator) void { if (comptime images_enabled) state.images.deinit(gpa); state.stream.deinit(); const own = state.gpa; state.vt.deinit(own); own.destroy(state); - pane.terminal = null; } -/// A terminal pane's emulator, `cols` by `rows`, as `create` makes one. +/// A terminal pane's emulator, `cols` by `rows`, as `open` makes one. fn emulator(gpa: std.mem.Allocator, cols: u16, rows: u16) !ghostty_vt.Terminal { return ghostty_vt.Terminal.init(terminalIo(), gpa, .{ .cols = cols, @@ -894,109 +775,43 @@ fn emulator(gpa: std.mem.Allocator, cols: u16, rows: u16) !ghostty_vt.Terminal { }); } -/// Allocate the live emulator half of a terminal pane. Slot ownership, serial -/// assignment, and spawn effects remain core lifecycle invariants. -pub fn create(gpa: std.mem.Allocator, cols: u16, rows: u16) !*Pane { - if (authorityOnly("open a terminal")) return error.OutOfMemory; - const pane = try createDoc(gpa, cols, rows); - errdefer gpa.destroy(pane); - const own = emulatorGpa(gpa); - const state = try own.create(State); - errdefer own.destroy(state); +/// A new emulator, `cols` by `rows`, allocated with `gpa`, its own from +/// then on (`State.gpa`). +pub fn open(gpa: std.mem.Allocator, cols: u16, rows: u16) !*State { + const state = try gpa.create(State); + errdefer gpa.destroy(state); // Every other field its default, never what the heap had: a digest // reads them, and two replicas must agree (src/replica.zig). - state.* = .{ .gpa = own, .vt = try emulator(own, cols, rows), .stream = undefined }; + state.* = .{ .gpa = gpa, .vt = try emulator(gpa, cols, rows), .stream = undefined }; state.wire(); - pane.terminal = state; - pane.tty_filter = true; - return pane; -} - -pub fn createDoc(gpa: std.mem.Allocator, cols: u16, rows: u16) !*Pane { - const pane = try gpa.create(Pane); - pane.* = .{ - .gpa = gpa, - .cols = cols, - .rows = rows, - }; - return pane; + return state; } /// Where a restored terminal's history ends and its new shell begins. pub const restored_banner = "\x1b[0m\r\n\x1b[2m\u{2500}\u{2500} restored history \u{2500}\u{2500}\x1b[0m\r\n"; -/// A terminal loaded from a dump, its shell not there, made ready for a new -/// one: its program's screen modes reset (the old program is gone), its -/// history marked off from what the new shell prints, and the pane waiting -/// for it like any new terminal (a line queued for the old one goes to it). -pub fn reviveShell(pane: *Pane) void { - if (pane.terminal == null) return; +/// A terminal loaded from a dump, its shell not there, made ready for a +/// new one: its program's screen modes reset (the old program is gone) and +/// its history marked off from what the new shell prints. +pub fn revive(state: *State) void { // The primary screen, keys, cursor and mouse as a shell starts with // them, the cursor where it was (a soft reset, or leaving a primary // screen for itself, would take it home). - if (pane.terminal.?.vt.screens.active_key == .alternate) ingest(pane, "\x1b[?1049l"); - ingest(pane, "\x1b[?1l\x1b>\x1b[?25h\x1b[?7h\x1b[?1000l\x1b[?1002l\x1b[?1003l\x1b[?1006l\x1b[?2004l\x1b[<u"); - ingest(pane, restored_banner); - // What the old shell was, ran and said is gone with it: the REPL it - // ran, the Term+ word naming it. - pane.shell_spoke = false; - pane.had_shell = false; - pane.shell_failed = false; - pane.shell_tail_len = 0; - pane.repl = null; - pane.sent_command = null; - pane.pending_command.wait = .spawn; + if (state.vt.screens.active_key == .alternate) ingest(state, "\x1b[?1049l"); + ingest(state, "\x1b[?1l\x1b>\x1b[?25h\x1b[?7h\x1b[?1000l\x1b[?1002l\x1b[?1003l\x1b[?1006l\x1b[?2004l\x1b[<u"); + ingest(state, restored_banner); } /// Feed the emulator. Live output and restoration share this byte path, /// then apply different views. -fn ingest(pane: *Pane, bytes: []const u8) void { - pane.terminal.?.stream.nextSlice(bytes); - pane.terminal.?.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, 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); +fn ingest(state: *State, bytes: []const u8) void { + state.stream.nextSlice(bytes); + state.changes +%= 1; } const RowPin = struct { pin: ?*ghostty_vt.Pin = null, offset: i32 = 0 }; -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; @@ -1026,304 +841,103 @@ 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 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 screens = &state.vt.screens; + const active = screens.active_key; + const generation = screens.generation(active); + 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, 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; + 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 }; }; - // 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); - } + 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(active) == 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); } - // 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; - }; - 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; -} - -/// A full-screen program has the emulator on its alternate screen. -pub fn onAlternateScreen(pane: *const Pane) bool { - const state = pane.terminal orelse return false; - return state.vt.screens.active_key == .alternate; -} - -/// Whether a new terminal's greeting may be typed now: only at the shell's -/// first prompt (pardes's own marks: no command started; a prompt drawn -/// again for a resize is the same first prompt), with nothing -/// typed at it and no program on the alternate screen. Any later moment is `.never`, for good: something has run or -/// been typed first, and an `ls` then would go into it. A shell pardes -/// cannot mark has no first prompt to find, and is never greeted. -pub fn greeting(pane: *const Pane) enum { wait, now, never } { - if (pane.fs.unmarked) return .never; - // Text typed into the edit buffer that stands in for the prompt row. - if (pane.ovl) |o| if (o.text.len > 0) return .never; - const state = pane.terminal orelse return .wait; - const marks = &state.stream.handler; - // (Not `declined`: bash's first prompt comes after a D of its own.) - if (marks.started > 0) return .never; - // At a prompt's input (ghostty's semantic marks, pardes's or the - // shell's own), before any command pardes's marks saw run. - if (!promptInputReady(pane)) return .wait; - return if (promptInputEmpty(pane)) .now else .never; + return .{ .rows = rows[0..track.len], .erased = erased[0..track.len], .cleared = cleared, .alive = alive != null, .failed = failed }; } -/// At a prompt's input: on the alternate screen too, where a program killed -/// there (htop, `sig KILL`) left the emulator and the shell then drew its -/// prompt, marks and all. A full-screen program draws no prompt marks. -pub fn promptInputReady(pane: *const Pane) bool { - const state = pane.terminal orelse return false; - return state.vt.screens.active.cursor.semantic_content == .input; +/// Where the shell is in its command cycle (`Term.Prompt`); all zero +/// without an emulator. +pub fn prompt(state: ?*State) Term.Prompt { + const s = state orelse return .{}; + const marks = &s.stream.handler; + const cursor = &s.vt.screens.active.cursor; + // At a prompt's input: on the alternate screen too, where a program + // killed there (htop, `sig KILL`) left the emulator and the shell then + // drew its prompt, marks and all. A full-screen program draws no + // prompt marks. + const ready = cursor.semantic_content == .input; + // Nothing typed on its line: no input left of the cursor and none + // under it (text typed and then Ctrl-A'd starts at the cursor). + // Nothing further right counts: that is where fish draws a right + // prompt, and fish suggests nothing on an empty line. + const empty = ready and empty: { + const row = cursor.page_pin.cells(.all); + for (row[0..@min(cursor.x + 1, row.len)]) |cell| + if (cell.semantic_content == .input and !cell.isEmpty()) break :empty false; + break :empty true; + }; + return .{ + .phase = switch (marks.phase) { + .none => .none, + .prompt => .prompt, + .input => .input, + .running => .running, + }, + .started = marks.started, + .prompts = marks.prompts, + .declined = marks.declined, + .continuation = marks.continuation, + .finished = if (marks.finished) |f| .{ .seq = f.seq, .status = f.status } else null, + .input_ready = ready, + .input_empty = empty, + .at_prompt = s.vt.cursorIsAtPrompt(), + }; } -pub const CommandOutput = struct { - /// Owned by the caller. - text: [:0]const u8, - /// Whether `text` starts where the command did. It does not when that - /// start is not there to read: cut off by `max_rows`, scrolled out of - /// the history or erased from it by ED 3 (ghostty flags the pin - /// `garbage`; an erased end leaves no text at all), erased under it - /// while it ran (`MarkedHandler.lost`), or never pinned (a C or D that - /// came on the alternate screen). - whole: bool, -}; - /// What the newest finished command printed: the screen text between its /// C and D marks, read from at most `max_rows` rows above its end, so a /// command that printed the whole history costs no more than its tail. /// The shell exited in the middle of a command (its `exit 3`): no end mark /// will come, so the command's output ends where the cursor is. -pub fn endOutputHere(pane: *Pane) void { - const state = pane.terminal orelse return; +pub fn endOutputHere(state: *State) void { const marks = &state.stream.handler; if (marks.phase == .running and marks.out_end == null) marks.pinCursor(&marks.out_end, true); } -pub fn commandOutput(pane: *Pane, gpa: std.mem.Allocator, max_rows: usize) !CommandOutput { +pub fn commandOutput(state: ?*State, gpa: std.mem.Allocator, max_rows: usize) !Term.CommandOutput { // Unless there is text to read, whether the nothing it printed is the // whole of it. const whole = printed: { - const state = pane.terminal orelse break :printed true; - const marks = &state.stream.handler; + const s = state orelse break :printed true; + const marks = &s.stream.handler; const start = marks.out_start orelse break :printed false; const end = marks.out_end orelse break :printed false; - const screen = state.vt.screens.get(.primary) orelse break :printed false; + const screen = s.vt.screens.get(.primary) orelse break :printed false; if (end.garbage) break :printed false; var whole = !marks.lost and !start.garbage; // Nothing printed: the whole of it. @@ -1348,31 +962,16 @@ pub fn commandOutput(pane: *Pane, gpa: std.mem.Allocator, max_rows: usize) !Comm return .{ .text = try gpa.dupeSentinel(u8, "", 0), .whole = whole }; } -/// At a prompt with nothing typed on its line: no input left of the -/// cursor and none under it (text typed and then Ctrl-A'd starts at the -/// cursor). Nothing further right counts: that is where fish draws a -/// right prompt, and fish suggests nothing on an empty line. -pub fn promptInputEmpty(pane: *const Pane) bool { - if (!promptInputReady(pane)) return false; - const cursor = &pane.terminal.?.vt.screens.active.cursor; - const row = cursor.page_pin.cells(.all); - for (row[0..@min(cursor.x + 1, row.len)]) |cell| - if (cell.semantic_content == .input and !cell.isEmpty()) return false; - return true; -} - -/// Encode one key for the program that owns a raw terminal and queue its pty -/// write, respecting the application's keyboard protocol and terminal modes. -pub fn forwardKey(p: *Pardes, id: usize, key: Key) void { - const pane = p.panes[id] orelse return; - const state = pane.terminal orelse return; +/// One key for its program, as the program's keyboard protocol and modes +/// ask for it, written to `out`. +pub fn key(state: *State, k: Key, out: *std.Io.Writer) !void { const input = ghostty_vt.input; const function_keys = comptime keys: { var keys: [Key.f25 - Key.f1 + 1]input.Key = undefined; - for (&keys, 1..) |*k, n| k.* = @field(input.Key, std.fmt.comptimePrint("f{d}", .{n})); + for (&keys, 1..) |*slot, n| slot.* = @field(input.Key, std.fmt.comptimePrint("f{d}", .{n})); break :keys keys; }; - const physical: input.Key = switch (key.cp) { + const physical: input.Key = switch (k.cp) { Key.enter => .enter, Key.backspace => .backspace, Key.tab => .tab, @@ -1391,32 +990,25 @@ pub fn forwardKey(p: *Pardes, id: usize, key: Key) void { Key.scroll_lock => .scroll_lock, Key.pause => .pause, Key.menu => .context_menu, - Key.f1...Key.f25 => function_keys[key.cp - Key.f1], - else => if (key.cp < 128) input.Key.fromASCII(@intCast(key.cp)) orelse .unidentified else .unidentified, + Key.f1...Key.f25 => function_keys[k.cp - Key.f1], + else => if (k.cp < 128) input.Key.fromASCII(@intCast(k.cp)) orelse .unidentified else .unidentified, }; var utf8: [4]u8 = undefined; - const text_cp = if (key.shift and key.cp >= 'a' and key.cp <= 'z') key.cp - 'a' + 'A' else key.cp; + const text_cp = if (k.shift and k.cp >= 'a' and k.cp <= 'z') k.cp - 'a' + 'A' else k.cp; // A key with no text of its own types its code point only when that // is a character: the kitty keyboard protocol numbers function and // modifier keys in the private use area (F3 is U+E016), and a shell // was typed those as junk. - const text = if (key.text.len > 0) key.text else if (key.cp >= 32 and key.cp < Key.up and key.cp != Key.backspace and !(key.cp >= 0xE000 and key.cp <= 0xF8FF)) + const text = if (k.text.len > 0) k.text else if (k.cp >= 32 and k.cp < Key.up and k.cp != Key.backspace and !(k.cp >= 0xE000 and k.cp <= 0xF8FF)) utf8[0 .. std.unicode.utf8Encode(text_cp, &utf8) catch return] else ""; - // A key's text has no bound of its own (an input method's commit, a - // paste as one key): past the stack's room the encoding grows on the - // heap, and emitWrite cuts it into writes. - var room: [256]u8 = undefined; - var first: std.heap.BufferFirstAllocator = .init(&room, p.gpa); - var out: std.Io.Writer.Allocating = .init(first.allocator()); - defer out.deinit(); - input.encodeKey(&out.writer, .{ + try input.encodeKey(out, .{ .key = physical, - .mods = .{ .ctrl = key.ctrl, .alt = key.alt, .shift = key.shift }, - .consumed_mods = .{ .shift = key.text.len > 0 and key.shift }, + .mods = .{ .ctrl = k.ctrl, .alt = k.alt, .shift = k.shift }, + .consumed_mods = .{ .shift = k.text.len > 0 and k.shift }, .utf8 = text, - .unshifted_codepoint = if (key.cp >= 'A' and key.cp <= 'Z') key.cp - 'A' + 'a' else if (key.cp < Key.up) key.cp else 0, + .unshifted_codepoint = if (k.cp >= 'A' and k.cp <= 'Z') k.cp - 'A' + 'a' else if (k.cp < Key.up) k.cp else 0, }, options: { var opts = input.KeyEncodeOptions.fromTerminal(&state.vt); // fromTerminal cannot know this one and says so, defaulting to @@ -1430,96 +1022,34 @@ pub fn forwardKey(p: *Pardes, id: usize, key: Key) void { // the floor and forwards Alt-n to the child as a bare `n`. opts.macos_option_as_alt = .true; break :options opts; - }) catch |err| return p.reportError(id, "key", err); - if (out.written().len > 0) p.emitWrite(id, out.written()); + }); } -pub fn enterTty(p: *Pardes, id: usize) void { - const pane = p.panes[id] orelse return; - const selected = pane.rawPointerText(pane.sel[@backingInt(config.select_button)]) != null; - if (!selected and pane.terminal != null and pane.body.cur_pinned and pane.terminal.?.vt.cursorIsAtPrompt()) handoff: { - const screen = pane.terminal.?.vt.screens.active; - const goff: i32 = @intCast(screen.pages.scrollbar().offset); - const vp_row = pane.gridRow(pane.body.cur_row) - goff; - if (vp_row < 0) break :handoff; - - var grid_col: i32 = @max(0, pane.body.cur_col); - if (screen.pages.pin(.{ .viewport = .{ .x = 0, .y = @intCast(vp_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(vp_row) }, - }) orelse break :handoff; - const cursor_pin = screen.cursor.page_pin.*; - var prompts = cursor_pin.promptIterator(.left_up, null); - const prompt_pin = prompts.next() orelse break :handoff; - if (click_pin.before(prompt_pin)) break :handoff; - const moves = screen.promptClickMove(click_pin); - for (0..moves.left) |_| p.emitWrite(id, "\x1b[D"); - for (0..moves.right) |_| p.emitWrite(id, "\x1b[C"); +/// 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. +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 (row_pin.rowAndCell().row.semantic_prompt != .none) switch (promptCut(row_pin)) { + .cut => |cols| grid_col += @intCast(cols), + .keep, .blank => {}, + }; } - - pane.body.mode = .tty; - followOutput(pane); // 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 - // keeps its modal endpoint for the next return to editor mode. - pane.body.cur_pinned = selected; - pane.body.select = false; - pane.body.restore_cursor = false; - pane.body.sticky_col = -1; - pane.body.normal.clear(); + const click_pin = screen.pages.pin(.{ + .viewport = .{ .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); + const prompt_pin = prompts.next() orelse return null; + if (click_pin.before(prompt_pin)) return null; + const moves = screen.promptClickMove(click_pin); + return .{ .left = moves.left, .right = moves.right }; } -// Returned slices remain valid until the next cache rebuild or reset. -pub const RowsCache = struct { - /// whose grid this describes; null = the slot is free - pane: ?*const Pane = null, - /// the rows joined by '\n' — `flatSurface` hands this back verbatim - /// instead of rebuilding the join on every keystroke - text: []const u8 = &.{}, - /// slices INTO `text`, absolute grid rows from 0 - rows: [][]const u8 = &.{}, - /// `text` is a prefix of this: blanking a prompt row shortens the join, - /// and the slack is not worth a second allocation to reclaim - text_alloc: []u8 = &.{}, - stale: bool = false, - - pub fn reset(c: *RowsCache, gpa: std.mem.Allocator) void { - if (c.text_alloc.len > 0) gpa.free(c.text_alloc); - if (c.rows.len > 0) gpa.free(c.rows); - c.* = .{}; - } - - /// Free a stale entry. Called at the top of `update`, and nowhere else. - pub fn sweep(c: *RowsCache, gpa: std.mem.Allocator) void { - if (c.stale) c.reset(gpa); - } - - /// `pane`'s grid moved: the entry no longer describes it. - pub fn markStale(c: *RowsCache, pane: *const Pane) void { - if (c.pane == pane) c.stale = true; - } - - pub fn dropPane(c: *RowsCache, pane: *const Pane) void { - if (c.pane != pane) return; - c.pane = null; - c.stale = true; - } -}; - -const Rows = struct { - text_alloc: []u8, - text: []const u8, - rows: [][]const u8, -}; - -const empty_grid = [1][]const u8{""}; - /// What LEAVING raw tty mode does to one prompt row, decided from its cells /// alone: OSC 133 prompt cells are hidden in normal mode, what was typed at /// them stays. @@ -1545,10 +1075,12 @@ fn promptCut(pin: ghostty_vt.Pin) PromptCut { return .{ .cut = cols }; } -pub fn promptPrefixBytes(pane: *Pane, row: i32, raw: []const u8) usize { +/// How many of the bytes `raw` of its row `row` (from the top of the +/// history), as the emulator dumps it, are the prompt the row starts with. +pub fn promptPrefix(state: ?*State, row: i32, raw: []const u8) usize { if (row < 0) return 0; - const state = pane.terminal orelse return 0; - const pin = state.vt.screens.active.pages.pin(.{ .screen = .{ .x = 0, .y = @intCast(row) } }) orelse return 0; + const s = state orelse return 0; + const pin = s.vt.screens.active.pages.pin(.{ .screen = .{ .x = 0, .y = @intCast(row) } }) orelse return 0; if (pin.rowAndCell().row.semantic_prompt == .none) return 0; return switch (promptCut(pin)) { .keep => 0, @@ -1595,176 +1127,24 @@ fn dumpedBytes(pin: ghostty_vt.Pin, cell: *const ghostty_vt.Cell) usize { return n; } -pub fn shellRows(p: *Pardes, pane: *Pane) ![]const []const u8 { - if (pane.terminal == null) return &empty_grid; - pardes.tape.touchTerminal(); - const c = &p.shell_rows; - if (!c.stale and c.pane == pane) { - // A step's read whether the rows are kept or made: a client that - // came since holds them as holes, and is sent them (Screens.fill). - if (!drawing) pane.terminal.?.read = true; - return c.rows; - } - // Another pane's rows, or a dropped pane's still waiting for the step's - // sweep (dropPane keeps them, as they may still be borrowed): this - // step's rows are scratch, and nothing in the slot is written over. - if (c.pane != null or c.text_alloc.len > 0 or c.rows.len > 0) { - c.stale = true; - return (try buildRows(p.scratch.allocator(), p, pane)).rows; - } - const built = try buildRows(p.gpa, p, pane); - c.* = .{ - .pane = pane, - .text = built.text, - .rows = built.rows, - .text_alloc = built.text_alloc, - }; - return c.rows; -} - -/// The full modal motion surface: shell history with the live edit overlay -/// spliced into the rows it covers. -pub fn cursorLines(p: *Pardes, pane: *Pane) ![]const []const u8 { - const rows = try shellRows(p, pane); - if (pane.ovl == null) return rows; - var last = rows.len; - if (pane.ovl) |overlay| - last = @max(last, @as(usize, @intCast(@max(0, overlay.row + overlay.rows)))); - var count = last; - if (pane.ovl) |overlay| { - if (overlay.row >= 0 and @as(usize, @intCast(overlay.row)) < last) - count = count - @min( - @as(usize, @intCast(overlay.rows)), - last - @as(usize, @intCast(overlay.row)), - ) + @max(1, modal.lineCount(overlay.text)); - } - const lines = try p.scratch.allocator().alloc([]const u8, count); - var n: usize = 0; - var grid_row: usize = 0; - while (grid_row < last) : (grid_row += 1) { - if (pane.ovl) |overlay| if (overlay.row >= 0 and grid_row == @as(usize, @intCast(overlay.row))) { - var overlay_lines = std.mem.splitScalar(u8, overlay.text, '\n'); - while (overlay_lines.next()) |line| : (n += 1) lines[n] = line; - grid_row += @intCast(overlay.rows - 1); - continue; - }; - lines[n] = if (grid_row < rows.len) rows[grid_row] else ""; - n += 1; - } - return lines[0..n]; +/// A step read its rows (its history too): a replica replaying the step +/// must hold them (`State.read`). +pub fn markRead(state: *State) void { + state.read = true; } -/// Flatten `cursorLines` without rebuilding the common cached/no-overlay -/// case. Scratch-owned when a join is required. -pub fn flatSurface(p: *Pardes, pane: *Pane, lines: []const []const u8) ![]const u8 { - const cache = &p.shell_rows; - if (!cache.stale and cache.pane == pane and - lines.ptr == cache.rows.ptr and lines.len == cache.rows.len) return cache.text; - var total: usize = if (lines.len > 0) lines.len - 1 else 0; - for (lines) |line| total += line.len; - const text = try p.scratch.allocator().alloc(u8, total); - var at: usize = 0; - for (lines, 0..) |line, i| { - if (i > 0) { - text[at] = '\n'; - at += 1; - } - @memcpy(text[at..][0..line.len], line); - at += line.len; - } - return text; -} - -/// Materialize or extend the terminal edit overlay with one exact allocation. -/// Row slices are scratch-owned/borrowed; only the joined text is installed. -pub fn editText(p: *Pardes, pane: *Pane, lo: i32, hi: i32, col: i32) error{ OutOfMemory, WriteFailed, UnknownPoint }!?EditText { - const want_lo = @max(0, @min(lo, hi)); - const want_hi = @max(want_lo, @max(lo, hi)); - const fresh = pane.ovl == null; - const old: EditBuffer = pane.ovl orelse .{ .row = want_lo, .rows = 1, .text = &.{} }; - const lines: i32 = if (fresh) 1 else @intCast(modal.lineCount(old.text)); - const up = old.row - want_lo; - const down = want_hi - (old.row + lines - 1); - const extending = fresh or up > 0 or down > 0; - var row0 = old.row; - var covered = old.rows; - var text = old.text; - var owned = false; - if (extending) { - const rows = try shellRows(p, pane); - row0 = old.row - @max(0, up); - covered = old.rows + @max(0, up) + @max(0, down); - const up_len: usize = @intCast(@max(0, up)); - const down_len: usize = @intCast(@max(0, down)); - const parts = try p.scratch.allocator().alloc([]const u8, up_len + 1 + down_len); - for (parts[0..up_len], 0..) |*part, i| { - const src = @as(usize, @intCast(row0)) + i; - part.* = if (src < rows.len) rows[src] else ""; - } - const middle: usize = @intCast(old.row); - parts[up_len] = if (fresh) - (if (middle < rows.len) rows[middle] else "") - else - old.text; - for (parts[up_len + 1 ..], 0..) |*part, i| { - const src = @as(usize, @intCast(old.row + old.rows)) + i; - part.* = if (src < rows.len) rows[src] else ""; - } - text = try std.mem.join(p.gpa, "\n", parts); - owned = true; - } - - const row: usize = @intCast(@max(0, want_lo - row0)); - const line_len: i32 = @intCast(modal.lineSlice(text, row).len); - if (col > line_len) { - const spaces = p.scratch.allocator().alloc(u8, @intCast(col - line_len)) catch { - if (owned) p.gpa.free(text); - return null; - }; - @memset(spaces, ' '); - const padded = modal.insertAt(p.gpa, text, .{ .row = row, .col = @intCast(line_len) }, spaces) catch { - if (owned) p.gpa.free(text); - return null; - }; - if (owned) p.gpa.free(text); - text = padded; - owned = true; - } - if (owned) { - if (pane.ovl) |overlay| p.gpa.free(overlay.text); - pane.ovl = .{ .row = row0, .rows = covered, .text = text }; - } - // A terminal's text is its program's: edited here it is a copy, to run - // with Tab or B2, gone when the program draws again. Said at its first - // edit, so it never looks like an edit that was lost. - if (fresh) for (p.panes, 0..) |slot, id| if (slot == pane) - p.setMessage(id, "a copy of the terminal's text: Tab or B2 runs it; what the program draws next replaces it (Ctrl-b types to the program)"); - return .{ .text = pane.ovl.?.text, .row0 = pane.ovl.?.row }; -} - -/// Consume a rewritten overlay, freeing the terminal edit text it replaces. -pub fn setEditText(p: *Pardes, pane: *Pane, new: []u8) void { - const overlay = if (pane.ovl) |*value| value else return pardes.edit.retireEditText(p, new); - for (0..pane.sel.len) |button| { - pane.clearPointerSelection(button); - pane.sel[button].state = .none; - } - p.gpa.free(overlay.text); - overlay.text = new; -} - -/// Set while a frame is drawn: what it reads is no step's. -pub var drawing = false; - -fn buildRows(alloc: std.mem.Allocator, p: *Pardes, pane: *Pane) !Rows { - if (!drawing) pane.terminal.?.read = true; - const full = try pane.terminal.?.vt.screens.active.dumpStringAlloc(p.scratch.allocator(), .{ .screen = .{} }); - var pit = pane.terminal.?.vt.screens.active.pages.rowIterator(.right_down, .{ .screen = .{} }, null); +/// Its rows from the top of its history as text, a prompt's own cells cut +/// off the rows it starts (what typed text stays), joined by '\n' in +/// `text` with `rows` slices into it and one empty row after them, the +/// cursor's: `alloc`'s, the emulator's dump `scratch`'s. +pub fn textRows(state: *State, alloc: std.mem.Allocator, scratch: std.mem.Allocator) !Term.Rows { + const full = try state.vt.screens.active.dumpStringAlloc(scratch, .{ .screen = .{} }); + var pit = state.vt.screens.active.pages.rowIterator(.right_down, .{ .screen = .{} }, null); // split yields one more item than delimiters; the extra final slot is the // cursor row retained below. const n_rows = std.mem.count(u8, full, "\n") + 2; - const rows = try alloc.alloc([]const u8, n_rows); - errdefer alloc.free(rows); + const lines = try alloc.alloc([]const u8, n_rows); + errdefer alloc.free(lines); // Blanking a prompt row only ever SHORTENS it and the retained cursor row // adds one separator, so the dump's length plus one bounds the join. const text = try alloc.alloc(u8, full.len + 1); @@ -1773,7 +1153,7 @@ fn buildRows(alloc: std.mem.Allocator, p: *Pardes, pane: *Pane) !Rows { var n: usize = 0; var it = std.mem.splitScalar(u8, full, '\n'); while (it.next()) |raw| { - const shown = if (pit.next()) |pin| + const kept = if (pit.next()) |pin| if (pin.rowAndCell().row.semantic_prompt != .none) promptRow(pin, raw) else raw else raw; @@ -1781,141 +1161,45 @@ fn buildRows(alloc: std.mem.Allocator, p: *Pardes, pane: *Pane) !Rows { text[at] = '\n'; at += 1; } - @memcpy(text[at..][0..shown.len], shown); - rows[n] = text[at..][0..shown.len]; - at += shown.len; + @memcpy(text[at..][0..kept.len], kept); + lines[n] = text[at..][0..kept.len]; + at += kept.len; n += 1; } text[at] = '\n'; at += 1; - rows[n] = text[at..][0..0]; + lines[n] = text[at..][0..0]; n += 1; std.debug.assert(n == n_rows); - return .{ .text_alloc = text, .text = text[0..at], .rows = rows }; + return .{ .text_alloc = text, .text = text[0..at], .rows = lines }; } -pub fn bodyText(arena: std.mem.Allocator, pane: *Pane) ![]const u8 { - const vp: []const []const u8 = vp: { - const state = pane.terminal orelse break :vp &.{}; - 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; - var rows_out: std.Io.Writer.Allocating = .init(arena); - try screen.dumpString(&rows_out.writer, .{ .tl = tl, .br = br, .unwrap = false }); - const raw = try rows_out.toOwnedSlice(); - var prompts = screen.pages.rowIterator(.right_down, .{ .viewport = .{} }, null); - 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; - while (lines.next()) |ln| { - vp[n] = if (pane.body.mode != .tty) - if (prompts.next()) |pin| - if (pin.rowAndCell().row.semantic_prompt != .none) promptRow(pin, ln) else ln - else - ln - else - ln; - n += 1; - } - std.debug.assert(n == vp.len); - break :vp vp; - }; - - const len = fillBody(null, pane, vp); - const out = try arena.alloc(u8, len); - const filled = fillBody(out, pane, vp); - std.debug.assert(filled == out.len); - return out; -} - -pub const BodyRow = union(enum) { - grid: i32, - edit: struct { line: []const u8, idx: usize }, -}; - -const BodyWalk = struct { - pane: *Pane, - goff: i32, - g: i32, - /// the buffer can start above the viewport: drop the lines scrolled past - skip: usize, - n: usize = 0, - lines: ?std.mem.SplitIterator(u8, .scalar) = null, - covered: i32 = 0, - line_idx: usize = 0, - - fn init(pane: *Pane) BodyWalk { - const off = pane.scroll(); - const goff = gridOffset(pane); - return .{ - .pane = pane, - .goff = goff, - .g = if (pane.body.mode == .tty) goff + pane.pan else pane.gridRow(off), - .skip = if (pane.ovl) |o| @intCast(@max(0, off - pane.surfRow(o.row))) else 0, - }; - } - - fn next(w: *BodyWalk) ?BodyRow { - while (w.n < w.pane.rows) { - if (w.lines) |*it| { - if (it.next()) |line| { - const idx = w.line_idx; - w.line_idx += 1; - // Lines scrolled off the top still count: the index names a - // line of the BUFFER, not of the visible body. - if (w.skip > 0) { - w.skip -= 1; - continue; - } - w.n += 1; - return .{ .edit = .{ .line = line, .idx = idx } }; - } - // The buffer stands in for `rows` shell rows however many lines - // it actually spelled, which is the whole slide. - w.g += w.covered; - w.skip = 0; - w.lines = null; - continue; - } - if (w.pane.body.mode != .tty) if (w.pane.ovl) |o| if (w.g == o.row) { - w.lines = std.mem.splitScalar(u8, o.text, '\n'); - w.covered = o.rows; - w.line_idx = 0; - continue; - }; - const vi = w.g - w.goff; - w.g += 1; - w.n += 1; - return .{ .grid = vi }; - } - return null; - } -}; - -/// Run the terminal body row walk. A null destination counts bytes; a slice -/// fills the exact allocation made from that count. -fn fillBody(dst: ?[]u8, pane: *Pane, viewport: []const []const u8) usize { - var walk: BodyWalk = .init(pane); - var written: usize = 0; - var first = true; - while (walk.next()) |row| { - if (!first) { - if (dst) |out| out[written] = '\n'; - written += 1; - } - first = false; - const bytes = switch (row) { - .edit => |e| e.line, - .grid => |vi| if (vi >= 0 and @as(usize, @intCast(vi)) < viewport.len) - viewport[@intCast(vi)] +/// 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 { + 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; + var rows_out: std.Io.Writer.Allocating = .init(arena); + try screen.dumpString(&rows_out.writer, .{ .tl = tl, .br = br, .unwrap = false }); + const raw = try rows_out.toOwnedSlice(); + var prompts = screen.pages.rowIterator(.right_down, .{ .viewport = .{} }, null); + 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; + while (lines.next()) |ln| { + vp[n] = if (cut) + if (prompts.next()) |pin| + if (pin.rowAndCell().row.semantic_prompt != .none) promptRow(pin, ln) else ln else - "", - }; - if (dst) |out| @memcpy(out[written..][0..bytes.len], bytes); - written += bytes.len; + ln + else + ln; + n += 1; } - return written; + std.debug.assert(n == vp.len); + return vp; } // Match surviving edit-buffer rows to their original terminal styles. @@ -2050,7 +1334,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; @@ -2173,7 +1457,7 @@ fn cellAt(pages: *const ghostty_vt.PageList, row: ghostty_vt.Pin, x: u16) ?ghost } // A cell's underline styles are SGR's, in SGR's order (`off` its `none`): a -// cast takes one to the other (cellStyle, pager.zig). +// cast takes one to the other (cellStyle, and pager.zig's attribute). comptime { for (@typeInfo(@FieldType(pardes.CellStyle, "ul")).@"enum".field_names, 0..) |name, i| if (@backingInt(@field(ghostty_vt.sgr.Attribute.Underline, if (std.mem.eql(u8, name, "off")) "none" else name)) != i) @compileError("a cell's underline styles are not SGR's"); @@ -2300,7 +1584,7 @@ pub const FilteredColors = struct { return asPardesColor(self.keyedRgb(style.bg(cell, &self.source).?)); } - /// A +Pager span's colour (pager.zig), as `fg` and `bg` map a cell's. + /// A +Pager span's colour (Term.page), as `fg` and `bg` map a cell's. pub fn spanColor(self: *FilteredColors, color: pardes.Color, is_bg: bool) pardes.Color { return switch (color) { .default => color, @@ -2400,76 +1684,33 @@ fn ghostColor(p: *Pardes, color: ghostty_vt.Style.Color, is_bg: bool) pardes.Col }; } -/// executing at a prompt with typed text below it: pad the output area -/// with newlines so the command's output doesn't overwrite the buffer -pub fn padOutputBelowEdits(p: *Pardes, id: usize) void { - // Nothing to pad away from: with no emulator there is no prompt and no - // child whose output could land on top of the edit buffer. - const pane = p.panes[id] orelse return; - const o = pane.ovl orelse return; - if (!pane.isTerminal()) return; - const state = pane.terminal orelse return; - if (!state.vt.cursorIsAtPrompt()) return; - // the buffer's LAST surface row: its lines may outnumber the shell - // rows it covers, and it is the bottom one output must clear - const max_row = o.row + @as(i32, @intCast(modal.lineCount(o.text))) - 1; - const goff: i32 = @intCast(state.vt.screens.active.pages.scrollbar().offset); - const cursor_abs = pane.surfRow(goff + @as(i32, @intCast(state.vt.screens.active.cursor.y))); - const pad = std.math.clamp(max_row - cursor_abs, 0, @as(i32, pane.rows)); - var i: i32 = 0; - while (i < pad) : (i += 1) p.emitWrite(id, "\r"); -} - -pub fn pushUndo(p: *Pardes, pane: *Pane) error{OutOfMemory}!void { - return pane.body.remember(p.gpa, pane.ovl); -} - -/// Undo (back) or redo one step of the edit overlay. -pub fn undoStep(p: *Pardes, pane: *Pane, back: bool) error{OutOfMemory}!void { - const to = (try pane.body.step(p.gpa, pane.ovl, back)) orelse return; - if (pane.ovl) |o| p.gpa.free(o.text); - pane.ovl = to.ovl; - 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 animationDueMs(pane: *const Pane) ?u64 { +pub fn due(state: *const State) ?u64 { if (comptime !images_enabled) return null; - const state = pane.terminal orelse return null; return state.images.animation_due_ms; } /// The Petscii builtin on a terminal: its kitty graphics as glyph art, /// or back to pixels where the shell draws pixels. -pub fn togglePetscii(pane: *Pane) void { +pub fn togglePetscii(state: *State) void { if (comptime !images_enabled) return; - const state = pane.terminal orelse return; state.images.petscii = !state.images.petscii; } /// Whether the pane draws its kitty graphics as glyph art by choice; null /// for a pane with no emulator. -pub fn petscii(pane: *const Pane) ?bool { +pub fn petscii(maybe: ?*const State) ?bool { if (comptime !images_enabled) return null; - const state = pane.terminal orelse return null; + const state = maybe orelse return null; return state.images.petscii; } /// Whether the screen showing holds any kitty graphics image. -pub fn hasImages(pane: *const Pane) bool { +pub fn hasImages(maybe: ?*const State) bool { if (comptime !images_enabled) return false; - const state = pane.terminal orelse return false; + const state = maybe orelse return false; return state.vt.screens.active.kitty_images.images.count() > 0; } @@ -2479,10 +1720,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); @@ -2548,9 +1789,9 @@ fn lineBreaks(comptime n: usize) [2 * n]u8 { test "replay ownership is terminal-only and construction rolls back on allocation failure" { const Case = struct { fn run(gpa: std.mem.Allocator, terminal: bool) !void { - const pane = if (terminal) try create(gpa, 40, 12) else try createDoc(gpa, 40, 12); + const pane = if (terminal) try panes.createTerminal(gpa, 40, 12) else try panes.createDoc(gpa, 40, 12); defer gpa.destroy(pane); - defer deinitEmulator(pane, gpa); + defer if (pane.terminal) |state| close(state, gpa); try std.testing.expectEqual(terminal, pane.terminal != null); } }; @@ -2570,7 +1811,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); } @@ -2582,38 +1823,35 @@ 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 }; - const pane = try create(gpa, 40, 12); + const pane = try panes.createTerminal(gpa, 40, 12); defer gpa.destroy(pane); - defer deinitEmulator(pane, gpa); + defer if (pane.terminal) |state| close(state, gpa); try std.testing.expect(pane.terminal.?.resize_to == null); } test "document construction allocates only the pane and has inert terminal defaults" { var failing = std.testing.FailingAllocator.init(std.testing.allocator, .{ .fail_index = 1 }); const allocator = failing.allocator(); - const pane = try createDoc(allocator, 40, 12); + const pane = try panes.createDoc(allocator, 40, 12); defer allocator.destroy(pane); - defer deinitEmulator(pane, allocator); + defer if (pane.terminal) |state| close(state, allocator); try std.testing.expect(pane.terminal == null); try std.testing.expectEqual(@as(usize, 1), failing.alloc_index); try std.testing.expectEqual(@as(usize, 0), failing.resize_index); 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.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)); - try std.testing.expectEqualStrings("", try screenTextAlloc(pane, allocator)); + try std.testing.expectEqual(Term.Grid{}, grid(pane.terminal)); + try std.testing.expectEqual(Term.Modes{}, modes(pane.terminal)); + try std.testing.expectEqual(Term.Prompt{}, prompt(pane.terminal)); + pane.scrollBy(100); + pane.followOutput(); + pane.resizeGrid(80, 24); + try std.testing.expectEqual(Term.Grid{}, grid(pane.terminal)); + try std.testing.expectEqualStrings("", try scrollback(pane.terminal, allocator)); try std.testing.expect(!failing.has_induced_failure); } @@ -2629,14 +1867,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); } @@ -2646,12 +1884,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); @@ -2675,7 +1913,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.?); @@ -2692,7 +1930,7 @@ test "a restored command pane comes back finished, its command not run again" { try std.testing.expectEqualStrings("make test", again.command.?); try std.testing.expect(again.command_done); try std.testing.expectEqual(@as(?u8, 2), again.command_status); - const text = try screenTextAlloc(again, gpa); + const text = try scrollback(again.terminal, gpa); defer gpa.free(text); try std.testing.expect(std.mem.indexOf(u8, text, "ok") != null); } @@ -2704,7 +1942,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); @@ -2720,7 +1958,7 @@ test "a restored terminal keeps its history above a marker and gets a shell wher try std.testing.expectEqualStrings("bash", again.shell.?); try std.testing.expect(again.command == null); try std.testing.expectEqual(.spawn, again.pending_command.wait); - const text = try screenTextAlloc(again, gpa); + const text = try scrollback(again.terminal, gpa); defer gpa.free(text); const old_at = std.mem.indexOf(u8, text, "old output") orelse return error.HistoryLost; const mark_at = std.mem.indexOf(u8, text, "restored history") orelse return error.NoMarker; @@ -2732,19 +1970,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" { @@ -2753,11 +1991,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()); @@ -2768,10 +2006,10 @@ test "rows asked for after a pane's cached rows were dropped, before the sweep, defer p.deinit(); const pane = p.panes[0].?; try std.testing.expect(pane.terminal != null); - _ = try shellRows(p, pane); + _ = try pardes.edit.shellRows(p, pane); // A pane's teardown drops its entry; the rows stay until the sweep. p.shell_rows.dropPane(pane); - _ = try shellRows(p, pane); + _ = try pardes.edit.shellRows(p, pane); } test "the luminance table answers exactly what ghostty computes" { @@ -2886,9 +2124,9 @@ test "terminal Filter keys indexed truecolor OSC and background-only cells throu try testing.expect(dyn_bg.eql(.{ .r = 95, .g = 95, .b = 95 })); _ = frame.reset(.retain_capacity); const dynamic = try p.render(frame.allocator()); - const blank = dynamic.at(tx + r.w - config.GUTTER - 1, body_y + 2).style; - try testing.expectEqual(asPardesColor(expected[196]), blank.fg); - try testing.expectEqual(asPardesColor(expected[59]), blank.bg); + const edge = dynamic.at(tx + r.w - config.GUTTER - 1, body_y + 2).style; + try testing.expectEqual(asPardesColor(expected[196]), edge.fg); + try testing.expectEqual(asPardesColor(expected[59]), edge.bg); const explicit_before_reverse = dynamic.at(tx, body_y).style.fg; try testing.expectEqual(asPardesColor(expected[196]), explicit_before_reverse); @@ -3076,7 +2314,7 @@ test "terminal Filter holds every projected foreground off the page" { p.settings.theme = @intCast(t); var fc = FilteredColors.init(p, &pane.terminal.?.vt); var refused: usize = 0; - for (fc.target, 0..) |projected, key| { + for (fc.target, 0..) |projected, slot| { const ink = fc.legible(projected); try testing.expect(ink.contrast(fc.default_bg) >= config.tty_filter_min_contrast); if (!ink.eql(projected)) { @@ -3087,7 +2325,7 @@ test "terminal Filter holds every projected foreground off the page" { } // The key a background asks for is handed back untouched, including // the one whose value is the page itself. - try testing.expect(fc.keyedRgb(GColor.default[key]).eql(fc.target[fc.nearestKey(GColor.default[key])])); + try testing.expect(fc.keyedRgb(GColor.default[slot]).eql(fc.target[fc.nearestKey(GColor.default[slot])])); } // Every curated theme owns at least one collapsing key — that is why // the floor exists — and the floor must not be flattening the palette. @@ -3271,9 +2509,9 @@ test "a finished command's output erased by a later ED 3 is not called whole, an const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 40, .rows = 6 }); defer p.deinit(); const pane = p.panes[0].?; - const prompt = "\x1b]133;A;cl=line;aid=pardes\x07$ \x1b]133;B;aid=pardes\x07"; - p.update(.{ .output = .{ .pane = 0, .bytes = prompt ++ "\r\n\x1b]133;C;aid=pardes\x07printed\r\n\x1b]133;D;0;aid=pardes\x07" ++ prompt } }); - const before = try commandOutput(pane, gpa, 100); + const marked = "\x1b]133;A;cl=line;aid=pardes\x07$ \x1b]133;B;aid=pardes\x07"; + p.update(.{ .output = .{ .pane = 0, .bytes = marked ++ "\r\n\x1b]133;C;aid=pardes\x07printed\r\n\x1b]133;D;0;aid=pardes\x07" ++ marked } }); + const before = try commandOutput(pane.terminal, gpa, 100); defer gpa.free(before.text); try std.testing.expect(before.whole); try std.testing.expect(std.mem.startsWith(u8, before.text, "printed")); @@ -3282,7 +2520,7 @@ test "a finished command's output erased by a later ED 3 is not called whole, an // where another program's text would be read as its output. p.update(.{ .output = .{ .pane = 0, .bytes = &lineBreaks(20) } }); p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[3J" } }); - const after = try commandOutput(pane, gpa, 100); + const after = try commandOutput(pane.terminal, gpa, 100); defer gpa.free(after.text); try std.testing.expect(!after.whole); try std.testing.expectEqualStrings("", after.text); @@ -3373,7 +2611,7 @@ test "a terminal's image is a placement whatever the frontend draws, and the Pet try pardes.dump.dumpState(p); const restored = try pardes.dump.restore(p, p.dump_out.?, "/tmp/pardes.dump.zon"); defer restored.deinit(); - try std.testing.expectEqual(@as(?bool, true), petscii(restored.panes[0].?)); + try std.testing.expectEqual(@as(?bool, true), petscii(restored.panes[0].?.terminal)); try std.testing.expect(p.executeBuiltinLine(0, "Petscii")); _ = frame.reset(.retain_capacity); s = try p.render(frame.allocator()); @@ -3385,12 +2623,12 @@ test "a new terminal draws its program's images as pixels, and one without image const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .cols = 80, .rows = 24, .shells = 1 }); defer p.deinit(); - try std.testing.expectEqual(false, petscii(p.panes[0].?).?); + try std.testing.expectEqual(false, petscii(p.panes[0].?.terminal).?); // A pane without images says nothing of them. try std.testing.expect(std.mem.indexOf(u8, try tagline.tagPrefix(p, p.panes[0].?), "petscii") == null); const id = p.freeSlot().?; const fresh = try p.newShell(id, ""); - try std.testing.expectEqual(false, petscii(fresh).?); + try std.testing.expectEqual(false, petscii(fresh.terminal).?); } test "a program asking the cell size in pixels (CSI 16 t) is told the shell's" { diff --git a/src/tui/tui.zig b/src/tui/tui.zig index 77c8ce2b..4c0ded5b 100644 --- a/src/tui/tui.zig +++ b/src/tui/tui.zig @@ -685,11 +685,11 @@ pub fn remote(init: std.process.Init, opts: pardes.Options, path: []const u8, se const have: ?*replica.Have = if (far) &have_store else null; const allocs = pardes.memory.init(gpa); defer pardes.memory.deinit(); - pardes.TerminalImages.start(allocs.image); + pardes.Term.start(allocs.image); pardes.Kind.heap = allocs.addon; pardes.syntax.start(allocs.tree_sitter); defer { - pardes.TerminalImages.stop(); + pardes.Term.stop(); pardes.syntax.stop(); } var o = opts; @@ -2983,7 +2983,7 @@ test "TTY queued results reject old PTY generations and LSP request IDs" { shell.gens[0] = 2; _ = shell.apply(.{ .pty_read = .{ .id = 0, .gen = 1, .bytes = try gpa.dupe(u8, "old session\n") } }); _ = shell.apply(.{ .pty_read = .{ .id = 0, .gen = 2, .bytes = try gpa.dupe(u8, "current session\n") } }); - const text = try pardes.panes.terminal.screenTextAlloc(core.panes[0].?, gpa); + const text = try pardes.Term.scrollback(core.panes[0].?.terminal, gpa); defer gpa.free(text); try std.testing.expect(std.mem.indexOf(u8, text, "old session") == null); try std.testing.expect(std.mem.indexOf(u8, text, "current session") != null); @@ -3344,17 +3344,3 @@ test "the tty draws a glide at whole rows: once a flick or a spin slows, its ste try std.testing.expectEqual(row, (shown.cursor orelse return error.NoCursor).y); } } - -test "the tui's vaxis measures a grapheme as wide as the core lays it out" { - // vaxis renders a cell at gwidth(.unicode) in mode 2027; the core's - // File.utf8Width is that function over the same uucode tables. A vaxis - // that measures otherwise would draw past or short of the core's cells. - for ([_][]const u8{ - "a", "\u{4e16}", "e\u{301}", "\u{301}", - "\u{1f642}", "\u{1f44b}\u{1f3ff}", "\u{1f469}\u{200d}\u{1f680}", "\u{1f1fa}\u{1f1f8}", - "\u{1f1fa}", "\u{2764}\u{fe0e}", "\u{2764}\u{fe0f}", "1\u{fe0f}\u{20e3}", - "\u{1100}\u{1161}", "\u{ff21}", "\u{b1}", "\u{200b}", - "\u{ad}", "\u{fffd}", "\u{85}", "\x7f", - "a\u{4e16}\u{1f642}", "\u{e0100}", "\u{231a}", "\u{2600}", - }) |g| try std.testing.expectEqual(vaxis.gwidth.gwidth(g, .unicode), pardes.panes.File.utf8Width(g)); -} 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]); }; } diff --git a/src/wire.zig b/src/wire.zig index 3dd08b29..cd1554b9 100644 --- a/src/wire.zig +++ b/src/wire.zig @@ -46,7 +46,7 @@ const family = switch (config.platform) { /// What makes two cores step differently, hashed: a replica's hello carries /// its own, and one of another build is refused. The protocol, the release /// and commit, the platform and build options, every dependency's content -/// hash (grammars, ghostty, Unicode), the walker codec's assumptions +/// hash (grammars, the terminal emulator, Unicode), the walker codec's assumptions /// (pointer width, byte order) and the tape's shape (tape.shape: what each /// input and each answer of the host's is laid out as). Not the OS: a Linux /// client of a FreeBSD session is the main case, and what differs there is @@ -88,7 +88,7 @@ pub const ClientTag = enum(u8) { hello = 0x01, bye = 0x02, ping = 0x03, - /// A replica's word about a terminal's state (src/screen_state.zig): the + /// A replica's word about a terminal's state (src/term/screen_state.zig): the /// delta it holds, or rows it asks for. Opaque here. screen_ack = 0x04, /// What is the session's digest, in stream order (a replica checks @@ -170,7 +170,7 @@ pub const ServerTag = enum(u8) { /// A unit of the authority's stream (src/replica.zig): its origin, seq, /// clocks and tape. unit = 0x05, - /// A terminal's delta, or rows asked for (src/screen_state.zig), applied + /// A terminal's delta, or rows asked for (src/term/screen_state.zig), applied /// before the next unit. Opaque here. screen = 0x06, /// The session's digest (u64le), after every unit before it. |
