diff options
Diffstat (limited to 'src')
70 files changed, 8834 insertions, 6280 deletions
diff --git a/src/Art.zig b/src/Art.zig index 6cc33e2e..2e2941c6 100644 --- a/src/Art.zig +++ b/src/Art.zig @@ -6,7 +6,7 @@ //! the same on every client. One of these a frontend keeps the art of the //! pictures it shows, while it shows them. const std = @import("std"); -const ghostty_vt = @import("ghostty-vt"); +const colors = @import("colors.zig"); const pardes = @import("pardes.zig"); const Art = @This(); @@ -76,7 +76,7 @@ fn gridOf(art: *Art, gpa: std.mem.Allocator, place: Placement, cell_h: u32) ?Gri } const colours = switch (place.art.palette) { .commodore => commodore, - .terminal => terminal_palette, + .terminal => colors.xterm[0..16].*, }; const grid = (if (place.at == null) fitted(gpa, place.raster, place.src, place.dst.w, place.dst.h, colours, place.art.ascii) @@ -466,34 +466,6 @@ fn renderRect(gpa: std.mem.Allocator, raster: Raster, src: RectPx, cols: usize, return .{ .cells = cells, .cols = cols, .rows = rows }; } -pub const terminal_palette = [16][3]u8{ - .{ 0x1D, 0x1F, 0x21 }, // black - .{ 0xCC, 0x66, 0x66 }, // red - .{ 0xB5, 0xBD, 0x68 }, // green - .{ 0xF0, 0xC6, 0x74 }, // yellow - .{ 0x81, 0xA2, 0xBE }, // blue - .{ 0xB2, 0x94, 0xBB }, // magenta - .{ 0x8A, 0xBE, 0xB7 }, // cyan - .{ 0xC5, 0xC8, 0xC6 }, // white - .{ 0x66, 0x66, 0x66 }, // bright black - .{ 0xD5, 0x4E, 0x53 }, // bright red - .{ 0xB9, 0xCA, 0x4A }, // bright green - .{ 0xE7, 0xC5, 0x47 }, // bright yellow - .{ 0x7A, 0xA6, 0xDA }, // bright blue - .{ 0xC3, 0x97, 0xD8 }, // bright magenta - .{ 0x70, 0xC0, 0xB1 }, // bright cyan - .{ 0xEA, 0xEA, 0xEA }, // bright white -}; - -comptime { - for (terminal_palette, 0..) |rgb, i| { - const c = ghostty_vt.color.default[i]; - if (rgb[0] != c.r or rgb[1] != c.g or rgb[2] != c.b) @compileError( - "terminal palette differs from the emulator", - ); - } -} - test "sextant codepoints: blocks + endpoints" { try std.testing.expectEqual(@as(u21, ' '), sextantCp(0)); try std.testing.expectEqual(@as(u21, 0x2588), sextantCp(63)); diff --git a/src/CHANGELOG.md b/src/CHANGELOG.md index dc130be1..44d55707 100644 --- a/src/CHANGELOG.md +++ b/src/CHANGELOG.md @@ -2,6 +2,105 @@ ## Unreleased +- The terminal is a module of its own (`src/term/`: the emulator, its + screen state for replicas, kitty images, the pager's parse), which never + imports the core and is reached through one table of plain-data + entries, `src/Term.zig` the core's side (docs/next-terminal.md). Editing + a terminal's text is the core's, on a copy of its rows, as before, and + predicted echo stays the core's; nothing a session does changes, and a + session dumped before loads after. `zig build core-test` builds the core + without the terminal (no ghostty, no C++): a shell boot is a scratch + pane there and a test that needs a terminal skips; `zig build + shell-test` runs the same tests with it. + +- A diff paged (`git show | pardes -`) is a plumbing message, as acme's + `plumb -i` sends what it shows: `type text/x-diff` to `edit`, which a + default rule makes `showdiff`, its +Pager stacked in a +Diff as before. + Take the rule out and the +Pager stays as text; a program reading + `plumb/edit` sees the diff. The `edit` port shows any message's data + with `action=showdata` (stacked with `showdiff`). + +- A port the plumbing rules name is a file a program reads, + `plumb/<port>`, as Plan 9's plumber serves one: every open reads its + own copy of what is sent there from then on (`cat plumb/edit` sees each + file a look opens), a read held until a message comes. A message to a + port no one reads runs its rule set's `start`, or with `plumb client` + waits for the port's first reader. + +- A look asks the plumber first, as acme's does: once the pane's own + readings are done and a name already open in a pane is focused, what + is looked at is sent (`type text`, `src pardes`, `wdir` the pane's + directory), and only what no rule set takes is Look's own. The default + rules keep every look as it was: the browser for a URL, a bare `.diff` + or `.patch` stacked in a +Diff, `git show` of a commit hash in a git + work tree are now rules of `src/plumbing`, no longer written into + Look. `Diff` takes a file or a revision (`Diff fix.patch`, `Diff + 3f2a9c1`), and a rule's Diff that cannot declines, so the look goes + on. `Plumb` opens your plumbing file (`<config>/plumbing`, `include + basic` until you save one), read at start and applied when saved; the + one-line `Plumb suffix .svg to image` rules are gone, refused in words + (write a rule set: `data matches '.*\.svg'`, `arg isfile $data`, + `plumb to image`). A program a rule starts runs detached, as Plan 9's + plumber starts one, with no pane; a failure to start it is said. + +- 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. + +- The plumber, Plan 9's, is in the session: `plumb/rules` holds its + rules in plumb(6)'s language (rule sets of `object verb arg` lines, + variables, `include`, `matches` over the whole text or around a click, + `isfile` and `isdir` finding a name as a look does), and `plumb/send` + takes a message and sends it where they say, to a port pardes reads + (`edit`, `web`, a loaded kind) or to a word or command started, with + Plan 9's words when it cannot. A session starts with `include basic`, + pardes's rules (`src/plumbing`). Kept in a dump. `$1`-`$9` are refused, + the regular expressions having no submatches. + +- A query pane's row looked at on its address (its gutter) opens the + row's place however the look arrives, as a click there always did: an + empty look written back to the pane's `event` file, and the whole row + written to its `look` file, now take the address the row holds, not a + word of its text. A diff's lines answer all three ways through the same + one function (`look.rowAddressAt`). + +- Each pane's directory over 9P has a `rows` file: a line a body row of a + results pane (+Search, +Callstack, +Diff, a language server's list), + where it points (`path`, line, column, the address's end, where its code + starts) and how it is coloured (runs of `keyword`, `string`, ... and the + grounds `add`, `del`, `emph`, `line`), so a 9P client reads their + addresses as data, not by parsing the text. A write at offset 0 replaces + a pane's rows, a later one adds to them; rows its text cannot hold are + refused. An edit drops them, as before. The editor's own producers set + rows the same one way. + +- A drag draws no guide lines: no dashes where a pane or column would + land, no rail for a carried column, no dashed seam under a pane rule + held. The line between two columns no longer resizes them (nor, at a + pane's corner, the panes too): a press there is a press in the pane. + A column resizes by its box, left of its tag; a pane by its own box, + or in a window by the rule above it. + +- An edit to the core recompiles it about 2 s sooner again (`core-test`, + 16 % fewer of the compiler's instructions, 4.4 MB less code in a Debug + test): a load's note on a field (another build's dump) is written from + the type's and the field's names at run time, where every type and + field had its own copy of the code that writes one; one byte dump's + reader serves a session, a pane and the rest, where each had its own; + and what tells a replica's build from another's (`wire.semantics`) + joins its two long parts on, and the tape's shape writes its numbers + itself and copies each line it builds once, where it formatted them + and copied the line again for each piece, at every compile. + +- An edit to the core recompiles it about 3 s sooner (`core-test`, 13 s to + 10 s): the build keeps each grammar's highlight patterns that pardes + colours once, where every compile of every program that takes the core + did it again, a quarter of its time. A package that depends on pardes + is given the same filtered queries. + +- 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 c5187616..ecfd8fa7 100644 --- a/src/Core.zig +++ b/src/Core.zig @@ -39,6 +39,7 @@ const Rect = pardes.Rect; const Registers = pardes.Registers; const RowMetrics = pardes.RowMetrics; const Store = @import("Store.zig"); +const Plumb = @import("Plumb.zig"); const Db = pardes.Db; const Stream = pardes.Stream; const Surface = pardes.Surface; @@ -72,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; @@ -208,9 +208,9 @@ db: Db = .{}, /// (`stdio.h`, `<foo.h>`) is tried in, in order. The session's, seeded /// with C's (/usr/include, /usr/local/include), kept in a dump. incl: std.ArrayList([]u8) = .empty, -/// Plumb's rules, the user's, tried in order before the built-in ones -/// (look.resolve), the first to match taking the look. Kept in a dump. -plumb: std.ArrayList([]u8) = .empty, +/// The plumber's rules (Plumb.zig): plumb/rules and plumb/send's, the +/// defaults (`include basic`) until something writes others. Kept in a dump. +plumber: Plumb = .{}, /// Zerox's groups of panes on one buffer (File.syncTwins), and the id /// the next takes. twin_groups: std.ArrayList(pardes.panes.File.TwinGroup) = .empty, @@ -227,6 +227,11 @@ next_serial: u32 = 0, /// The column whose tag the running command came from, while it runs: /// the column acme's commands take from their Text's col. exec_column: ?usize = null, +/// While a word a plumbing rule started runs (Plumb.run): whether it +/// declined the message, saying nothing (Diff on a file with no hunk, a +/// revision outside a git work tree), so that the send is refused and a +/// look looks itself. Null while no rule's word runs. +plumb_declined: ?bool = null, /// Panes made this step that found no room in their column /// (layout.placeNew): closed at the step's end, once whatever made them /// is done with them. @@ -246,7 +251,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. @@ -267,8 +272,10 @@ unattended: bool = false, haptic: HapticSlot = if (platform == .macos) .none else {}, /// The look just run found nothing (look.zig missed). look_missed: bool = false, -/// The look being run opens a .diff or .patch as text, not its +Diff: -/// Diff going back from a +Diff, Edit's B (it edits the file). +/// The look being run opens what it names, unplumbed (Plumb.zig): a +/// .diff as text, not stacked in a +Diff (Diff going back from a +Diff, +/// Edit's B, which edits the file), and the `edit` port's open of a +/// message the plumber already matched. look_text: bool = false, look_hover_wait: ?look.LookHoverWait = null, /// The place a look-hover last found nothing to open: the pointer @@ -362,10 +369,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.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 @@ -389,11 +396,11 @@ 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 = .{}, +/// (ansi.DiffOutput). +diff_output: pardes.ansi.DiffOutput = .{}, /// What the replay digest leaves out (src/walk.zig): what drawing /// keeps, what is recomputed, and what only the session that performs @@ -519,7 +526,17 @@ fn initSession(gpa: std.mem.Allocator, opts: Options) !*Pardes { p.boot = Boot.of(opts); // Asked once, at the start, whoever asks first after. _ = p.sessionDir(); - switch (p.boot) { + // A core built without a terminal (a test configuration: core-test's) + // boots to a scratch pane where a shell would have been, and says why + // once. + const shell_boot = switch (p.boot) { + .tty, .tty_shell, .shell, .classic => true, + .document, .missing, .stdin => false, + }; + if (pardes.Term.ops == null and shell_boot) { + _ = try pardes.panes.newScratch(p, 0, 0, .scratch); + p.oneColumn(); + } else switch (p.boot) { .document => { const path = opts.file.?; const opened = initial_doc: { @@ -566,7 +583,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); @@ -757,8 +774,7 @@ pub fn deinit(p: *Pardes) void { p.recent.deinit(p.recentGpa()); for (p.incl.items) |dir| p.gpa.free(dir); p.incl.deinit(p.gpa); - for (p.plumb.items) |rule| p.gpa.free(rule); - p.plumb.deinit(p.gpa); + p.plumber.deinit(p.gpa); for (p.twin_groups.items) |group| p.gpa.free(group.path); p.twin_groups.deinit(p.gpa); p.fs.batch.bytes.deinit(p.gpa); @@ -862,9 +878,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; } @@ -993,7 +1009,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; } @@ -1599,7 +1624,7 @@ pub fn update(p: *Pardes, ev: Event) void { const pane = p.panes[o.pane] orelse return; pane.shell_spoke = true; ctlfs.events.notePtyOutput(p, o.pane, o.bytes); - pardes.panes.terminal.feedOutput(p, pane, o.bytes); + pane.feedOutput(p, o.bytes); ctlfs.pty.noteMarks(p, o.pane, pane); exec.flushReplEnter(p, o.pane, true); }, @@ -1796,10 +1821,7 @@ pub fn sync(p: *Pardes) void { // What the terminal answers its program (a cursor report, its // attributes) goes as typed bytes go: behind whatever is still // queued for its pty, never ahead of it nor dropped. - if (pane.terminal) |state| { - p.emitWrite(id, state.reply[0..state.reply_len]); - state.reply_len = 0; - } + if (pane.terminal) |state| p.emitWrite(id, pardes.Term.replies(state)); const r = v.rects[id]; // The session's part of the pane's view geometry (File.geometry), // and its context declarations. @@ -1864,7 +1886,7 @@ pub fn sync(p: *Pardes) void { // doc panes have no pty/emulator grid to reflow; just record // the size so bodyText renders the right number of rows if (pane.isTerminal()) { - pardes.panes.terminal.resizeGrid(pane, cols, rows); + pane.resizeGrid(cols, rows); p.shell_rows.markStale(pane); // reflow moved every row p.emit(.{ .resize_pty = .{ .pane = @intCast(id), .cols = cols, .rows = rows } }); pane.fs.winsize = null; @@ -1873,19 +1895,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 => { @@ -1909,7 +1935,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 { @@ -1988,7 +2014,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); @@ -2159,7 +2185,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, @@ -2293,6 +2319,7 @@ test "topbar hover highlights exactly the executable word" { } test "pane-tag Exec prefers Term and argument builtins before shell fallback" { + if (pardes.Term.ops == null) return error.SkipZigTest; // a shell const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .cols = 100, .rows = 30 }); defer p.deinit(); @@ -2468,6 +2495,7 @@ test "TreeContext command and custom tag survive a workspace round trip" { test "Filter is ordered after Del and toggles only its terminal or +Pager pane" { const testing = std.testing; + if (pardes.Term.ops == null) return error.SkipZigTest; // it reads the emulator const del = std.meta.stringToEnum(Builtin, "Del") orelse return error.MissingDelBuiltin; const filter = std.meta.stringToEnum(Builtin, "Filter") orelse return error.MissingFilterBuiltin; try testing.expectEqual(@backingInt(del) + 1, @backingInt(filter)); @@ -2476,12 +2504,12 @@ test "Filter is ordered after Del and toggles only its terminal or +Pager pane" defer p.deinit(); while (p.nextEffect()) |_| {} const first = p.panes[0].?; - const palette_before = first.terminal.?.vt.colorForXterm(.{ .palette = 1 }).?; + const palette_before = pardes.Term.emulatorOf(first.terminal.?).vt.colorForXterm(.{ .palette = 1 }).?; try testing.expect(first.tty_filter); try testing.expect(p.executeBuiltinLine(0, "Filter")); try testing.expect(!first.tty_filter); - try testing.expect(palette_before.eql(first.terminal.?.vt.colorForXterm(.{ .palette = 1 }).?)); + try testing.expect(palette_before.eql(pardes.Term.emulatorOf(first.terminal.?).vt.colorForXterm(.{ .palette = 1 }).?)); const second_id = p.freeSlot().?; const second = try p.newShell(second_id, ""); @@ -2514,6 +2542,7 @@ test "Filter is ordered after Del and toggles only its terminal or +Pager pane" } test "compact tag commands stay beside their own prefix across layout changes" { + if (pardes.Term.ops == null) return error.SkipZigTest; // a shell const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .cols = 100, .rows = 30 }); defer p.deinit(); @@ -2558,6 +2587,7 @@ test "compact tag commands stay beside their own prefix across layout changes" { } test "Term spawns a raw shell in the caller's directory" { + if (pardes.Term.ops == null) return error.SkipZigTest; // a shell const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 100, .rows = 30 }); defer p.deinit(); @@ -2583,6 +2613,7 @@ test "Term spawns a raw shell in the caller's directory" { } test "a terminal respawned into a closed pane's slot hangs the old shell up first" { + if (pardes.Term.ops == null) return error.SkipZigTest; // a shell // Hosts keep a shell per slot: were the spawn first, the close would // end the new shell and leave the old one running. const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 100, .rows = 30 }); @@ -2653,6 +2684,7 @@ test "an empty column shows its theme's empty_col under its tag: acme's white, e } test "unknown Exec from a document runs as a command pane in its directory, typed into no terminal" { + if (pardes.Term.ops == null) return error.SkipZigTest; // a command pane const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{}); defer p.deinit(); @@ -2680,6 +2712,7 @@ test "unknown Exec from a document runs as a command pane in its directory, type } test "Exec in a terminal whose tty is taken runs as a command pane instead of typing at the program" { + if (pardes.Term.ops == null) return error.SkipZigTest; // a command pane const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{}); defer p.deinit(); @@ -2711,6 +2744,7 @@ test "Exec in a terminal whose tty is taken runs as a command pane instead of ty } test "a command of several lines keeps its tag one row, and its echo does not staircase" { + if (pardes.Term.ops == null) return error.SkipZigTest; // a command pane const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 100, .rows = 30 }); defer p.deinit(); @@ -2731,12 +2765,13 @@ 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); } test "a spawn is for the pane it was made for, not whatever took the slot since" { + if (pardes.Term.ops == null) return error.SkipZigTest; // a command pane const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .tty_only = true }); defer p.deinit(); @@ -2767,6 +2802,7 @@ test "a spawn is for the pane it was made for, not whatever took the slot since" } test "a REPL bound for a language takes the exec made on a body in it; tags, Exec by name and command words still run" { + if (pardes.Term.ops == null) return error.SkipZigTest; // the classic boot's three shells const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .shells = 3, .cols = 100, .rows = 30 }); defer p.deinit(); @@ -3007,6 +3043,7 @@ test "a restored terminal's tag names neither the REPL it was nor the shell it h } test "a Term started by a shell's path keeps the path in its Term+ word" { + if (pardes.Term.ops == null) return error.SkipZigTest; // a shell const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true }); defer p.deinit(); while (p.nextEffect()) |_| {} @@ -3017,6 +3054,7 @@ test "a Term started by a shell's path keeps the path in its Term+ word" { } test "Tty, Term's old name in saved tags, runs as Term, bare and with its +shell" { + if (pardes.Term.ops == null) return error.SkipZigTest; // a shell const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true }); defer p.deinit(); while (p.nextEffect()) |_| {} @@ -3029,6 +3067,7 @@ test "Tty, Term's old name in saved tags, runs as Term, bare and with its +shell } test "Term+fish, one word a tag can hold, opens a terminal on that shell" { + if (pardes.Term.ops == null) return error.SkipZigTest; // a shell const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true }); defer p.deinit(); while (p.nextEffect()) |_| {} @@ -3058,6 +3097,7 @@ test "Term+fish, one word a tag can hold, opens a terminal on that shell" { } test "a command pane shows how its command ended, and the next command there runs below it" { + if (pardes.Term.ops == null) return error.SkipZigTest; // a command pane const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{}); defer p.deinit(); @@ -3070,7 +3110,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")); } @@ -3101,16 +3141,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; @@ -3156,6 +3196,7 @@ test "a command pane shows how its command ended, and the next command there run } test "a terminal its program gave back takes command lines again" { + if (pardes.Term.ops == null) return error.SkipZigTest; // a command pane const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{}); defer p.deinit(); @@ -3189,6 +3230,7 @@ test "a terminal its program gave back takes command lines again" { } test "the host is asked about a tty only where a command line is about to go" { + if (pardes.Term.ops == null) return error.SkipZigTest; // the classic boot's three shells const p = try Pardes.init(std.testing.allocator, .{ .shells = 3, .cols = 100, .rows = 30 }); defer p.deinit(); while (p.nextEffect()) |_| {} @@ -3235,9 +3277,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); @@ -3352,6 +3394,7 @@ test "startup config overrides restored styling before initFromDump returns" { } test "restored terminals keep monotonic nonzero pane identities" { + if (pardes.Term.ops == null) return error.SkipZigTest; // the classic boot's three shells const gpa = std.testing.allocator; const source = try Pardes.init(gpa, .{ .shells = 3 }); defer source.deinit(); @@ -3646,6 +3689,7 @@ test "argv naming nothing boots an errors pane rather than failing the launch" { } test "raw terminal cursor obeys visibility without hiding modal and tag cursors" { + if (pardes.Term.ops == null) return error.SkipZigTest; // a shell const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 40, .rows = 12 }); defer p.deinit(); @@ -3690,6 +3734,7 @@ test "raw terminal cursor obeys visibility without hiding modal and tag cursors" } test "raw terminal cursor follows its active row only while that row is visible" { + if (pardes.Term.ops == null) return error.SkipZigTest; // a shell const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 40, .rows = 12 }); defer p.deinit(); @@ -3706,19 +3751,20 @@ 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); } test "the bare tty startup opens a text pane under the shell, unfocused" { + if (pardes.Term.ops == null) return error.SkipZigTest; // a shell const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .boot = .tty }); defer p.deinit(); try std.testing.expectEqual(Boot.tty, p.boot); @@ -3744,6 +3790,7 @@ test "the bare tty startup opens a text pane under the shell, unfocused" { } test "tty output follows only from the bottom" { + if (pardes.Term.ops == null) return error.SkipZigTest; // a shell, opened by a key const p = try Pardes.init(std.testing.allocator, .{ .cols = 80, .rows = 24, .file = "mise.toml" }); defer p.deinit(); p.update(.{ .resize = .{ .cols = 80, .rows = 24 } }); @@ -3758,34 +3805,35 @@ 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" { + if (pardes.Term.ops == null) return error.SkipZigTest; // a shell const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24 }); defer p.deinit(); @@ -3794,7 +3842,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" }); @@ -3804,6 +3852,7 @@ test "an unasked desktop paste reaches a tty pane's program, not its buffer" { } test "a paste larger than the effect ring reaches the program whole and in order" { + if (pardes.Term.ops == null) return error.SkipZigTest; // a shell const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24 }); defer p.deinit(); @@ -3811,7 +3860,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); @@ -3838,6 +3887,7 @@ test "bytes for a terminal past what may wait for it are dropped and said, never } test "a bracketed paste larger than the ring still closes its bracket" { + if (pardes.Term.ops == null) return error.SkipZigTest; // a shell const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24 }); defer p.deinit(); @@ -3845,10 +3895,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'); @@ -3860,6 +3910,7 @@ test "a bracketed paste larger than the ring still closes its bracket" { } test "a terminal's answer to its program waits behind the paste still queued for its pty" { + if (pardes.Term.ops == null) return error.SkipZigTest; // a shell const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24 }); defer p.deinit(); @@ -3867,7 +3918,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); @@ -3886,6 +3937,7 @@ test "a terminal's answer to its program waits behind the paste still queued for } test "pasted bytes still queued at shutdown are freed, not leaked" { + if (pardes.Term.ops == null) return error.SkipZigTest; // a shell const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24 }); defer p.deinit(); @@ -3893,7 +3945,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); @@ -3903,6 +3955,7 @@ test "pasted bytes still queued at shutdown are freed, not leaked" { } test "leaving tty hides the prompt and keeps the command typed at it" { + if (pardes.Term.ops == null) return error.SkipZigTest; // a shell, opened by a key const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }); defer p.deinit(); @@ -3922,14 +3975,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; @@ -3968,6 +4021,7 @@ test "leaving tty hides the prompt and keeps the command typed at it" { } test "entering tty walks the shell cursor to the column clicked past the prompt" { + if (pardes.Term.ops == null) return error.SkipZigTest; // a shell, opened by a key const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }); defer p.deinit(); @@ -3984,7 +4038,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; @@ -3998,7 +4052,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..08694e93 100644 --- a/src/Effect.zig +++ b/src/Effect.zig @@ -46,6 +46,10 @@ pub const Effect = union(enum) { /// and ends the shell, rather than leave it running with nobody to read. close_pty: struct { pane: u8 }, open_link: Buf(256), + /// A program a plumbing rule starts (Plumb.run): its directory, then + /// its argv, each ended by a NUL. A failure to start it is said at + /// pane `pane`. + start: struct { pane: u8, line: Buf(effect_path_cap) }, /// write this pane's file content to its path; the shell reads both off /// the core (content is unbounded, effects are fixed-size values) save_file: struct { pane: u8 }, @@ -132,6 +136,18 @@ pub fn perform(p: *Pardes, e: Effect) void { f(p.host.ctx, u.slice()) else p.fallback.setLink(u.slice()), + // Plan 9's plumber's, detached (host_io.startDetached); in-process + // (a test), kept to look at. + .start => |st| { + var why_buf: [64]u8 = undefined; + const why = if (v.start) |f| f(p.host.ctx, st.line.slice(), &why_buf) else p.fallback.start(st.line.slice()); + const w = why orelse return; + var words = std.mem.splitScalar(u8, st.line.slice(), 0); + _ = words.next(); // its directory + const prog = words.next() orelse ""; + var said: pardes.Kind.Buf(160) = .{}; + p.reportFailure(st.pane, said.print("plumb start: {s}: {s}", .{ prog[0..@min(64, prog.len)], w })); + }, .save_file => |sf| { const pane = p.panes[sf.pane] orelse return; const f = if (pane.file) |*file| file else return; @@ -164,7 +180,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()); @@ -329,6 +345,7 @@ test "Detach asks the host to let its terminal go, and says so when there is not } test "Save on a scratch asks for a path in its inherited dir and makes it a file" { + if (pardes.Term.ops == null) return error.SkipZigTest; // the classic boot's three shells const p = try Pardes.init(std.testing.allocator, .{ .shells = 3, .cols = 100, .rows = 30 }); defer p.deinit(); while (p.nextEffect()) |_| {} @@ -362,6 +379,7 @@ test "Save on a scratch asks for a path in its inherited dir and makes it a file } test "Save on a terminal writes its plaintext scrollback and stays a terminal" { + if (pardes.Term.ops == null) return error.SkipZigTest; // a shell const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 40, .rows = 8 }); defer p.deinit(); while (p.nextEffect()) |_| {} @@ -390,6 +408,7 @@ test "Save on a terminal writes its plaintext scrollback and stays a terminal" { } test "Save on an output buffer writes its rows out and leaves the buffer alone" { + if (pardes.Term.ops == null) return error.SkipZigTest; // the classic boot's three shells const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .shells = 3, .cols = 100, .rows = 30 }); defer p.deinit(); @@ -442,6 +461,7 @@ test "Save on an output buffer writes its rows out and leaves the buffer alone" } test "Save takes the path as an argument, relative to the pane's own directory" { + if (pardes.Term.ops == null) return error.SkipZigTest; // a shell const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 40, .rows = 8 }); defer p.deinit(); while (p.nextEffect()) |_| {} @@ -541,6 +561,7 @@ test "Save elsewhere copies a file's bytes and keeps the pane on its own file" { } test "saves armed in one batch stay with their own panes" { + if (pardes.Term.ops == null) return error.SkipZigTest; // the classic boot's three shells const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .shells = 3, .cols = 100, .rows = 30 }); defer p.deinit(); @@ -570,6 +591,7 @@ test "saves armed in one batch stay with their own panes" { } test "a save whose pane is gone before the drain writes nothing" { + if (pardes.Term.ops == null) return error.SkipZigTest; // the classic boot's three shells const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .shells = 3, .cols = 100, .rows = 30 }); defer p.deinit(); @@ -624,6 +646,7 @@ test "Save reaches every tagline with text behind it and no other" { } test "a save path that names no file is refused before anything is rewritten" { + if (pardes.Term.ops == null) return error.SkipZigTest; // the classic boot's three shells const p = try Pardes.init(std.testing.allocator, .{ .shells = 3, .cols = 100, .rows = 30 }); defer p.deinit(); while (p.nextEffect()) |_| {} diff --git a/src/Event.zig b/src/Event.zig index aa93f412..faea73cc 100644 --- a/src/Event.zig +++ b/src/Event.zig @@ -49,36 +49,7 @@ pub const Mouse = struct { amount: f32 = 0, }; -pub const Key = struct { - cp: u21, // codepoint or one of the specials below - text: []const u8 = "", - ctrl: bool = false, - alt: bool = false, - shift: bool = false, - - pub const enter: u21 = 0x0D; - pub const escape: u21 = 0x1B; - pub const tab: u21 = 0x09; - pub const backspace: u21 = 0x7F; - // private-use plane for non-text keys, matching no real codepoint - pub const up: u21 = 0xF0001; - pub const down: u21 = 0xF0002; - pub const left: u21 = 0xF0003; - pub const right: u21 = 0xF0004; - pub const home: u21 = 0xF0005; - pub const end: u21 = 0xF0006; - pub const page_up: u21 = 0xF0007; - pub const page_down: u21 = 0xF0008; - pub const delete: u21 = 0xF0009; - pub const insert: u21 = 0xF000A; - pub const print_screen: u21 = 0xF000B; - pub const scroll_lock: u21 = 0xF000C; - pub const pause: u21 = 0xF000D; - pub const menu: u21 = 0xF000E; - /// F1 to F25, in order: Fn is `f1 + n - 1`. - pub const f1: u21 = 0xF0011; - pub const f25: u21 = f1 + 24; -}; +pub const Key = @import("plain").Key; pub fn hit(key: Key, binding: []const config.Chord) bool { for (binding) |c| { diff --git a/src/File.zig b/src/File.zig index d1cfe088..0c3c3a2f 100644 --- a/src/File.zig +++ b/src/File.zig @@ -13,6 +13,7 @@ const filesystem = @import("fs.zig"); const syntax = @import("syntax.zig"); const diff = @import("diff.zig"); const tracy = @import("tracy.zig"); +const ansi = @import("ansi.zig"); const limits = @import("memory.zig").limits; const locations = @import("locations.zig"); const Colors = @import("colors.zig"); @@ -21,7 +22,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 +128,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. @@ -555,7 +555,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); @@ -617,6 +617,29 @@ pub fn setContent(p: *Pardes, f: *State, new: []u8) void { setContentSpan(p, f, new, null); } +/// `rows`, a row a line of the text from its first (where each points, how +/// it is coloured: locations.Row), made the pane's, taken: the one way a +/// pane's rows are set, by a producer in the editor (Output.fillRows, a +/// query pane) or from outside (the pane's `rows` file). RowsMismatch, the +/// rows still the caller's, for rows the text cannot hold: more of them +/// than it has lines, or an offset or styles past its line's end. Rows +/// equal to the pane's keep its painting; others drop it, to be painted +/// from them. An edit of the text drops them (setContentSpan). +pub fn setRows(p: *Pardes, f: *State, rows: []locations.Row) error{RowsMismatch}!void { + var lines = std.mem.splitScalar(u8, f.content, '\n'); + for (rows) |row| { + const line = lines.next() orelse return error.RowsMismatch; + if (row.location_end > line.len or row.code_start > line.len or row.colors.len > line.len - row.code_start) return error.RowsMismatch; + } + if (locations.equalRows(f.location_rows, rows)) return locations.freeRows(p.gpa, rows); + locations.freeRows(p.gpa, f.location_rows); + f.location_rows = rows; + if (f.highlights.len > 0) p.tree_sitter_gpa.free(f.highlights); + f.highlights = &.{}; + f.highlight_start = 0; + f.syntax_dirty = true; +} + /// `setContent` for a splice that knows what it left alone at either end, /// so it is not found again by comparing the whole text. The edit is what /// lies between them, made by `edit`, which takes `new`, a whole text its @@ -1790,62 +1813,9 @@ fn fillBody(dst: ?[]u8, pane: *Pane, f: *State, width: usize, record_wrap: bool) return written; } -const SynStyle = struct { fg: [3]u8, bold: bool }; - -/// How added and removed diff lines are told apart in every theme: a row -/// ground a little way from the page toward green or red (the theme's own -/// ANSI green and red where it has a palette), and the prefix column in -/// that hue, pushed toward the ink until it reads on that ground. The -/// syntax colours are drawn over the ground unchanged. -pub const DiffTints = struct { - added_bg: [3]u8, - removed_bg: [3]u8, - /// The words a changed line changed (hunks.zig), on a stronger ground. - added_emph_bg: [3]u8, - removed_emph_bg: [3]u8, - /// A +Diff line added or removed whole: a faint ground. - added_line_bg: [3]u8, - removed_line_bg: [3]u8, - added_fg: [3]u8, - removed_fg: [3]u8, - - pub fn of(p: *Pardes) DiffTints { - const th = p.theme(); - const page = th.bg orelse th.tag_bg; - const ink = th.fg orelse th.tag_fg; - const green: [3]u8 = if (th.palette) |pal| pal[2] else .{ 0x2e, 0xa0, 0x43 }; - const red: [3]u8 = if (th.palette) |pal| pal[1] else .{ 0xcf, 0x22, 0x2e }; - const added_bg = Colors.mixOklab(page, green, 0.18); - const removed_bg = Colors.mixOklab(page, red, 0.18); - return .{ - .added_bg = added_bg, - .removed_bg = removed_bg, - .added_emph_bg = Colors.mixOklab(page, green, 0.28), - .removed_emph_bg = Colors.mixOklab(page, red, 0.28), - .added_line_bg = Colors.mixOklab(page, green, 0.07), - .removed_line_bg = Colors.mixOklab(page, red, 0.07), - .added_fg = legible(green, ink, added_bg), - .removed_fg = legible(red, ink, removed_bg), - }; - } +pub const SynStyle = struct { fg: [3]u8, bold: bool }; - fn legible(hue: [3]u8, ink: [3]u8, ground: [3]u8) [3]u8 { - var fg = hue; - var step: usize = 0; - while (step < 4 and Colors.contrast(fg, ground) < 3) : (step += 1) fg = Colors.mixOklab(fg, ink, 0.4); - return fg; - } - - /// The row ground and prefix ink for a line's style byte, if it is an - /// added or removed line. - pub fn forStyle(t: *const DiffTints, style: u8) ?struct { bg: [3]u8, fg: [3]u8, emph_bg: [3]u8, line_bg: [3]u8 } { - if (style & syntax.diff_added != 0) return .{ .bg = t.added_bg, .fg = t.added_fg, .emph_bg = t.added_emph_bg, .line_bg = t.added_line_bg }; - if (style & syntax.diff_removed != 0) return .{ .bg = t.removed_bg, .fg = t.removed_fg, .emph_bg = t.removed_emph_bg, .line_bg = t.removed_line_bg }; - return null; - } -}; - -fn synStyle(p: *Pardes, sy: syntax.Syn) ?SynStyle { +pub fn synStyle(p: *Pardes, sy: syntax.Syn) ?SynStyle { return .{ .fg = Colors.synInk(p.theme(), sy) orelse return null, .bold = false }; } @@ -1859,15 +1829,13 @@ pub fn recolorSyntax(p: *Pardes, s: *Surface, pane: *Pane, f: *State, r: pardes. const prefix_width = gutterWidth(pane); const tz_recolor = tracy.zone(@src(), "synRecolor"); defer tz_recolor.end(); - // A diff's rows, and a +Diff's (hunks.zig): their markers coloured. - // A diff's whole row is tinted; a +Diff tints only the words a - // changed line changed. - const algo = pane.colorAlgo(); - const tints: ?DiffTints = if ((algo == .diff or algo == .locations) and highlights.len > 0) DiffTints.of(p) else null; - const row_tint = algo == .diff; - var filtered_storage: terminal.FilteredColors = undefined; - const filtered: ?*terminal.FilteredColors = if (pane.tty_filter and spans.len > 0) blk: { - filtered_storage = .init(p, null); + // 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; + const ink = ansi.inkOf(p.theme()); + var filtered_storage: pardes.Term.Filter = undefined; + const filtered: ?*pardes.Term.Filter = if (pane.tty_filter and spans.len > 0) blk: { + filtered_storage = pardes.Term.filter(&ink, &p.tty_filter_palette); break :blk &filtered_storage; } else null; // indexed start, same as bodyText — an empty tail simply paints nothing @@ -1902,21 +1870,22 @@ pub fn recolorSyntax(p: *Pardes, s: *Surface, pane: *Pane, f: *State, r: pardes. const metadata: ?locations.Row = if (row_index < f.location_rows.len) f.location_rows[row_index] else null; const decoration = Output.decorateRow(f.output, line, metadata); const chrome: ?*const pardes.ChromeTheme = if (decoration.plain()) null else p.bodyChrome(); - // An added or removed line's row, every wrapped row of it, is tinted. - const tint = if (tints) |*t| if (base >= highlight_start and base - highlight_start < highlights.len) - t.forStyle(highlights[base - highlight_start]) - else - null else null; + // The row's first byte: its hue and its ground, on every wrapped + // row of it (syntax.ground_add). + const lead: u8 = if (base >= highlight_start and base - highlight_start < highlights.len) highlights[base - highlight_start] else 0; + const tint: ?Colors.Grounds.Ground = if (lead & (syntax.ground_add | syntax.ground_del) == 0) null else (grounds orelse ground: { + grounds = .of(p.theme()); + break :ground grounds.?; + }).forStyle(lead); if (tint) |t| if (prefix_width < tw) { - // A +Diff line added or removed whole: faintly (hunks.zig). - const whole = highlights[base - highlight_start] & syntax.diff_whole != 0; - if (row_tint or whole) s.tint(tx + @as(u16, @intCast(prefix_width)), body_y + vr, tw -| @as(u16, @intCast(prefix_width)), if (row_tint) t.bg else t.line_bg, null); + 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 the diff - // look tints: 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 { + // 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.Term.Span, spans, base + hs, struct { + fn before(at: usize, span: pardes.Term.Span) bool { return span.end <= at; } }.before); @@ -1948,7 +1917,7 @@ pub fn recolorSyntax(p: *Pardes, s: *Surface, pane: *Pane, f: *State, r: pardes. const hidx = idx - highlight_start; if (hidx < highlights.len) { if (if (tint != null and hs + c == 0) - SynStyle{ .fg = tint.?.fg, .bold = true } + SynStyle{ .fg = tint.?.ink, .bold = true } else synStyle(p, @fromBackingInt(@intCast(highlights[hidx] & syntax.syn_bits)))) |ss| { @@ -1960,10 +1929,10 @@ pub fn recolorSyntax(p: *Pardes, s: *Surface, pane: *Pane, f: *State, r: pardes. cell.style.bold = ss.bold; } } - if (tint) |t| if (highlights[hidx] & syntax.diff_emph != 0) { + if (tint) |t| if (highlights[hidx] & syntax.ground_emph != 0 and hs + c > 0) { var fill: usize = 0; while (fill < cells and prefix_width + screen_c + fill < tw) : (fill += 1) - s.at(tx + @as(u16, @intCast(prefix_width + screen_c + fill)), body_y + vr).style.bg = .{ .rgb = t.emph_bg }; + s.at(tx + @as(u16, @intCast(prefix_width + screen_c + fill)), body_y + vr).style.bg = .{ .rgb = t.emph }; }; } } @@ -1990,11 +1959,11 @@ pub fn recolorSyntax(p: *Pardes, s: *Surface, pane: *Pane, f: *State, r: pardes. // palette colour through the theme's sixteen and // truecolor as it is. if (filtered) |colors| { - if (st.fg != .default) cell.style.fg = colors.spanColor(st.fg, false); - if (st.bg != .default) cell.style.bg = colors.spanColor(st.bg, true); + if (st.fg != .default) cell.style.fg = pardes.Term.spanColor(colors, st.fg, false); + if (st.bg != .default) cell.style.bg = pardes.Term.spanColor(colors, 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) ink.palColor(st.fg.index) else st.fg; + if (st.bg != .default) cell.style.bg = if (st.bg == .index) ink.palColor(st.bg.index) else st.bg; } cell.style.bold = cell.style.bold or st.bold; cell.style.dim = st.dim; @@ -2012,169 +1981,6 @@ pub fn recolorSyntax(p: *Pardes, s: *Surface, pane: *Pane, f: *State, r: pardes. } } -/// What finished command panes printed, kept while it cannot change: a -/// copy of the terminal's rows, and whether they are a diff. Taken once -/// when a finished pane is first drawn, so neither a frame nor a look dumps -/// the whole scrollback again; a still running command is shown as it -/// printed. Keyed by the pane and its width (a resize rewraps every row); -/// a rerun in the pane drops it (exec.runCommand). -pub const DiffOutput = struct { - const Entry = struct { - serial: u32, - cols: u16, - is_diff: bool, - /// The rows joined by '\n'; `rows` are slices of it. - text: []u8, - rows: [][]const u8, - used: u64, - }; - slots: [4]?Entry = @splat(null), - clock: u64 = 0, - - pub fn reset(o: *DiffOutput, gpa: std.mem.Allocator) void { - for (&o.slots) |*slot| { - if (slot.*) |e| { - gpa.free(e.text); - gpa.free(e.rows); - } - slot.* = null; - } - } - - /// A pane's command runs again: what it printed before is gone. - pub fn drop(o: *DiffOutput, gpa: std.mem.Allocator, serial: u32) void { - for (&o.slots) |*slot| if (slot.*) |e| if (e.serial == serial) { - gpa.free(e.text); - gpa.free(e.rows); - slot.* = null; - }; - } - - /// A finished command pane's rows when they are a diff, else null. - pub fn lines(o: *DiffOutput, p: *Pardes, pane: *Pane) ?[]const []const u8 { - if (pane.command == null or !pane.command_done or pane.command_pty or pane.terminal == null) return null; - o.clock += 1; - for (&o.slots) |*slot| if (slot.*) |*e| if (e.serial == pane.serial and e.cols == pane.cols) { - e.used = o.clock; - return if (e.is_diff) e.rows else null; - }; - const shown = terminal.shellRows(p, pane) catch return null; - const is_diff = diff.looksLikeDiff(shown); - var total: usize = 0; - if (is_diff) for (shown) |row| { - total += row.len + 1; - }; - const text = p.gpa.alloc(u8, total) catch return null; - const rows = p.gpa.alloc([]const u8, if (is_diff) shown.len else 0) catch { - p.gpa.free(text); - return null; - }; - var at: usize = 0; - for (rows, 0..) |*row, i| { - @memcpy(text[at..][0..shown[i].len], shown[i]); - row.* = text[at..][0..shown[i].len]; - at += shown[i].len; - text[at] = '\n'; - at += 1; - } - // An empty slot, else the least recently used. - var oldest: usize = 0; - for (&o.slots, 0..) |*slot, i| { - const e = slot.* orelse { - oldest = i; - break; - }; - if (e.used < o.slots[oldest].?.used) oldest = i; - } - if (o.slots[oldest]) |old| { - p.gpa.free(old.text); - p.gpa.free(old.rows); - } - o.slots[oldest] = .{ .serial = pane.serial, .cols = pane.cols, .is_diff = is_diff, .text = text, .rows = rows, .used = o.clock }; - return if (is_diff) rows else null; - } -}; - -/// A command pane whose output is a diff (`git diff`, `diff -u`): its -/// rows coloured as a .diff file's are, over what the program printed. -/// The rows are the terminal's own, so a line it wrapped goes on in the -/// row below (syntax.highlightDiffRows). -pub fn recolorDiffOutput(p: *Pardes, s: *Surface, pane: *Pane, r: pardes.Rect, tx: u16, tw: u16, body_h: u16, body: []const u8) void { - if (pane.command == null) return; - const tz = tracy.zone(@src(), "diffRecolor"); - defer tz.end(); - const rows = p.diff_output.lines(p, pane) orelse return; - // The copy's rows are one text, joined as a file's lines are. - const flat_start = @intFromPtr(rows[0].ptr); - const last = rows[rows.len - 1]; - const flat = rows[0].ptr[0 .. @intFromPtr(last.ptr) + last.len - flat_start]; - const raw = pane.body.mode == .tty; - const View = struct { row: usize, at: usize }; - const arena = p.scratch.allocator(); - const views = arena.alloc(?View, body_h) catch return; - var lo: usize = std.math.maxInt(usize); - var hi: usize = 0; - var shown = std.mem.splitScalar(u8, body, '\n'); - for (views, 0..) |*view, vi| { - view.* = null; - 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; - 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)); - if (from > rows[row].len or !std.mem.startsWith(u8, rows[row][from..], line)) continue; - view.* = .{ .row = row, .at = from }; - const start = @intFromPtr(rows[row].ptr) - flat_start; - lo = @min(lo, start); - hi = @max(hi, start + rows[row].len); - } - if (lo > hi) return; - const styles = syntax.highlightDiffRows(arena, flat, lo, hi, true) catch return; - const tints = DiffTints.of(p); - const ink = p.theme().fg orelse p.theme().tag_fg; - const body_y = p.bodyTop(pane, r); - shown = std.mem.splitScalar(u8, body, '\n'); - for (views, 0..) |maybe, vr| { - const line = shown.next() orelse break; - const view = maybe orelse continue; - const base = @intFromPtr(rows[view.row].ptr) - flat_start - lo; - const tint = if (base < styles.len) tints.forStyle(styles[base]) else null; - if (tint) |t| s.tint(tx, body_y + @as(u16, @intCast(vr)), tw, t.bg, null); - var c: usize = 0; - var screen_c: usize = 0; - while (c < line.len and screen_c < tw) { - const grapheme_end = modal.nextGrapheme(line, c); - if (grapheme_end <= c) break; - const cells = graphemeDisplayWidth(line[c..grapheme_end]); - const style = styles[base + view.at + c]; - const prefix = view.at + c == 0 and (line[0] == '+' or line[0] == '-'); - // On an added or removed line, what the program coloured red or - // green is the tint's to say now: its code takes the page's ink. - const paint: ?SynStyle = if (tint != null and prefix) - .{ .fg = tint.?.fg, .bold = true } - else if (synStyle(p, @fromBackingInt(@intCast(style & syntax.syn_bits)))) |ss| - ss - else if (tint != null) - .{ .fg = ink, .bold = false } - else - null; - if (paint) |ss| { - var fill: usize = 0; - while (fill < cells and screen_c + fill < tw) : (fill += 1) { - const cell = s.at(tx + @as(u16, @intCast(screen_c + fill)), body_y + @as(u16, @intCast(vr))); - if (cell.default) continue; - cell.style.fg = .{ .rgb = ss.fg }; - cell.style.bold = ss.bold; - } - } - screen_c += cells; - c = grapheme_end; - } - } -} - pub fn paintWordSelection( p: *Pardes, s: *Surface, diff --git a/src/Handover.zig b/src/Handover.zig index 2f5689f2..8eb29d5d 100644 --- a/src/Handover.zig +++ b/src/Handover.zig @@ -577,6 +577,7 @@ test "a pane edited while it is on its way to another window stays here too" { } test "a terminal's grip let go past the edge stays: its shell is this window's" { + if (pardes.Term.ops == null) return error.SkipZigTest; // the classic boot's three shells const p = try Pardes.init(std.testing.allocator, .{ .cols = 100, .rows = 30, .shells = 3 }); defer p.deinit(); p.update(.{ .resize = .{ .cols = 100, .rows = 30 } }); diff --git a/src/Jump.zig b/src/Jump.zig index 06cf8388..2e23d932 100644 --- a/src/Jump.zig +++ b/src/Jump.zig @@ -400,6 +400,7 @@ test "Back and Forward take the same steps from the mouse's side buttons and jum } test "jump history terminal rectangle follows output and clears on reflow" { + if (pardes.Term.ops == null) return error.SkipZigTest; // it reads the emulator const p = try Pardes.init(std.testing.allocator, .{ .cols = 60, .rows = 12, .tty_only = true }); defer p.deinit(); const pane = p.panes[0].?; @@ -409,7 +410,7 @@ test "jump history terminal rectangle follows output and clears on reflow" { try std.testing.expectEqualStrings("alpha", try edit.selectionText(p, pane, pane.sel[0])); for (0..40) |_| p.update(.{ .output = .{ .pane = 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/Messages.zig b/src/Messages.zig index f400df54..90bedd6f 100644 --- a/src/Messages.zig +++ b/src/Messages.zig @@ -382,6 +382,7 @@ pub fn reportError(p: *Pardes, id: usize, operation: []const u8, err: anyerror) pub fn errorWords(err: anyerror, buf: []u8) []const u8 { return switch (err) { error.FileTooLarge => "too large", + error.NoTerminal => pardes.Term.none, error.NotAFile => "not a regular file", // In the words a mount turns into EISDIR and EACCES (cloud9.fs.enameErrno). error.IsDirectory => "is a directory", @@ -575,6 +576,7 @@ test "the message log keeps what the row forgets, and collapses repeats" { } test "Msg writes the transient row by hand, bare or with text, and input ends it" { + if (pardes.Term.ops == null) return error.SkipZigTest; // the classic boot's three shells const p = try Pardes.init(std.testing.allocator, .{ .shells = 3, .cols = 100, .rows = 30 }); defer p.deinit(); while (p.nextEffect()) |_| {} @@ -747,6 +749,7 @@ test "messages stack, oldest on top, each on its own timing" { } test "a builtin announces itself on the message row, and Verbose silences it" { + if (pardes.Term.ops == null) return error.SkipZigTest; // a terminal's tag row const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 80, .rows = 24 }); defer p.deinit(); const pane = p.panes[p.view().active].?; diff --git a/src/Output.zig b/src/Output.zig index 0c6fdfc2..2e49ceb3 100644 --- a/src/Output.zig +++ b/src/Output.zig @@ -14,8 +14,6 @@ const lsp = @import("lsp/lsp.zig"); const look = @import("look.zig"); const locations = @import("locations.zig"); const layout = @import("layout.zig"); -const hunks = @import("hunks.zig"); -const diff = @import("diff.zig"); const Pane = panes.Pane; const File = panes.File; @@ -414,17 +412,19 @@ pub fn fillResults(p: *Pardes, id: usize, dir: []const u8, from: Origin, arg: [] result_rows = formatted.rows; anchor = formatted.anchor; } - _ = try fillRows(p, id, dir, from, arg, result_content, result_rows, anchor); + _ = try fillRows(p, id, dir, from, null, arg, result_content, result_rows, anchor); } /// Rows already laid out (`content`, `rows` its metadata, both taken /// when it succeeds, the caller's still when it fails) into the pane they -/// belong in: the one a run of `from` with `arg` in `dir` showed last, +/// belong in: the one named `name` (null: its origin's own name, as `open` +/// gives it) that a run of `from` with `arg` in `dir` showed last, /// refilled, else a new one placed by pane `id`. Its id. -pub fn fillRows(p: *Pardes, id: usize, dir: []const u8, from: Origin, arg: []const u8, result_content: []u8, result_rows: []locations.Row, anchor: ?usize) !usize { +pub fn fillRows(p: *Pardes, id: usize, dir: []const u8, from: Origin, name: ?[]const u8, arg: []const u8, result_content: []u8, result_rows: []locations.Row, anchor: ?usize) !usize { const pane = p.panes[id] orelse return error.MissingPane; if (arg.len > max_arg) return error.ArgumentTooLong; const by_arg = std.meta.activeTag(from) != .query; + const own = name orelse if (from == .kind) arg else traits(from).name; for (p.panes, 0..) |slot, i| { const rp = slot orelse continue; const rf = if (rp.file) |*f| f else continue; @@ -440,8 +440,7 @@ pub fn fillRows(p: *Pardes, id: usize, dir: []const u8, from: Origin, arg: []con if (!shared and !std.meta.eql(o.from, from)) continue; if (!shared and by_arg and !std.mem.eql(u8, o.arg(), arg)) continue; if (!std.mem.eql(u8, std.Io.Dir.path.dirname(rf.path) orelse "", dir)) continue; - if (std.meta.eql(from, Origin{ .cmd = .Diff }) and - !std.mem.eql(u8, diff.commitHash(rf.content) orelse "", diff.commitHash(result_content) orelse "")) continue; + if (!std.mem.eql(u8, std.Io.Dir.path.basename(rf.path), std.Io.Dir.path.basename(own))) continue; o.from = from; p.fs.refilled = rp.serial; try setArg(o, arg); @@ -451,16 +450,10 @@ pub fn fillRows(p: *Pardes, id: usize, dir: []const u8, from: Origin, arg: []con File.setContent(p, rf, result_content); resetBody(p, rp); } - if (locations.equalRows(rf.location_rows, result_rows)) { + File.setRows(p, rf, result_rows) catch |err| { locations.freeRows(p.gpa, result_rows); - } else { - locations.freeRows(p.gpa, rf.location_rows); - rf.location_rows = result_rows; - if (rf.highlights.len > 0) p.tree_sitter_gpa.free(rf.highlights); - rf.highlights = &.{}; - rf.highlight_start = 0; - rf.syntax_dirty = true; - } + p.reportError(id, "rows", err); + }; p.view().active = id; if (traits(from).steps) { pane.search_pane = i; @@ -470,8 +463,17 @@ pub fn fillRows(p: *Pardes, id: usize, dir: []const u8, from: Origin, arg: []con return i; } const free = p.freeSlot() orelse return error.NoPaneSlots; + const path = if (name) |named| try std.fmt.allocPrint(p.gpa, "{s}/{s}", .{ std.mem.trimEnd(u8, dir, "/"), named }) else null; + errdefer if (path) |owned| p.gpa.free(owned); const np = try open(p, free, dir, from, arg, result_content); - np.file.?.location_rows = result_rows; + if (path) |owned| { + p.gpa.free(np.file.?.path); + np.file.?.path = owned; + } + File.setRows(p, &np.file.?, result_rows) catch |err| { + locations.freeRows(p.gpa, result_rows); + p.reportError(id, "rows", err); + }; layout.placeNew(p, id, id, free, .doc); p.view().active = id; if (traits(from).steps) { @@ -482,67 +484,6 @@ pub fn fillRows(p: *Pardes, id: usize, dir: []const u8, from: Origin, arg: []con return free; } -/// Diff: `content`, the diff at `path` (a file, a +Pager), stacked as a -/// diff viewer shows it (hunks.zig), in a +Diff where its files are found -/// (hunks.sourceRoot), placed by pane `id`, refilled when it is there. Its -/// arg names the diff (its base name, or its whole path when the +Diff -/// stands elsewhere), for Diff to go back to it. The +Diff's id; -/// NoHunks when there is none in it. -pub fn openDiff(p: *Pardes, id: usize, path: []const u8, content: []const u8) !usize { - const dir = std.Io.Dir.path.dirname(path) orelse p.sessionDir(); - const root = hunks.sourceRoot(p, dir, content); - const result = try hunks.format(p, root, content); - errdefer { - p.gpa.free(result.content); - locations.freeRows(p.gpa, result.rows); - } - var has_hunk = false; - for (result.rows) |row| has_hunk = has_hunk or row.kind == .match; - if (!has_hunk) return error.NoHunks; - const arg = if (std.mem.eql(u8, root, dir) or path.len > max_arg) std.Io.Dir.path.basename(path) else path; - const title = if (diff.commitHash(content)) |hash| - try std.fmt.allocPrint(p.gpa, "{s}/{s}-{s}", .{ std.mem.trimEnd(u8, root, "/"), config.diff_buffer, hash[0..@min(hash.len, 12)] }) - else - null; - errdefer if (title) |name| p.gpa.free(name); - const hid = try fillRows(p, id, root, .{ .cmd = .Diff }, arg, result.content, result.rows, null); - if (title) |name| { - const f = &p.panes[hid].?.file.?; - p.gpa.free(f.path); - f.path = name; - } - return hid; -} - -/// Diff on a +Diff: the diff it stacks, as text. A pane holding it -/// already (the newest: a +Pager folded under its +Diff unfolds) is -/// shown; else the file is opened as text. -pub fn showDiffText(p: *Pardes, id: usize, source: []const u8) void { - var newest: ?usize = null; - for (p.panes, 0..) |slot, i| { - const f = (slot orelse continue).file orelse continue; - if (!std.mem.eql(u8, f.path, source)) continue; - if (newest == null or p.panes[newest.?].?.serial < slot.?.serial) newest = i; - } - if (newest) |i| { - if (p.panes[i].?.collapsed) layout.toggleCollapse(p, i); - p.view().active = i; - return; - } - p.look_text = true; - defer p.look_text = false; - look.lookAt(p, id, source); -} - -/// The diff a +Diff stacks (openDiff's arg): its path. -pub fn diffSource(p: *Pardes, f: *const File.State) ?[]const u8 { - const o = f.output orelse return null; - if (!std.meta.eql(o.from, Origin{ .cmd = .Diff })) return null; - const arg = o.arg(); - if (arg.len > 0 and arg[0] == '/') return arg; - return std.Io.Dir.path.join(p.scratch.allocator(), &.{ std.Io.Dir.path.dirname(f.path) orelse "", arg }) catch null; -} - pub fn openJumps(p: *Pardes, id: usize) !void { var out: std.Io.Writer.Allocating = .init(p.gpa); errdefer out.deinit(); diff --git a/src/Plumb.zig b/src/Plumb.zig new file mode 100644 index 00000000..5299a8c3 --- /dev/null +++ b/src/Plumb.zig @@ -0,0 +1,1566 @@ +//! The plumber (Plan 9's plumber(4), windows/plumb/): the rules, and a +//! message matched against them and sent where they say. The language is +//! plumb(6)'s as rules.c and match.c read it, and its refusals are their +//! words; docs/next-plumber.md is the design. The rules are kept as their +//! text, a step's state as any other (digested, dumped, replicated), and +//! parsed again for each message: a send reads no file, and asks the disk +//! only at `isfile` and `isdir`, through the taped resolve sites Look uses. +const Plumb = @This(); +const std = @import("std"); +const pardes = @import("pardes.zig"); +const fs = @import("fs.zig"); +const look = @import("look.zig"); +const layout = @import("layout.zig"); +const Kind = @import("Kind.zig"); +const tape = @import("tape.zig"); +const events = @import("ninep/events.zig"); +const Regex = @import("regexp.zig").Regex; +const Pardes = pardes.Pardes; + +/// The rules in force once any were written, as plumb/rules reads them: +/// what `print` makes of them, an include's text in its place, in the +/// order they were written. +text: std.ArrayList(u8) = .empty, +/// Whether rules were written (or cleared): until then the rules in force +/// are `include basic`'s, so a session starts with the defaults, and so +/// does a dump made before the plumber. +written: bool = false, +/// Every port a rule has named this session, in the order they were +/// named, never dropped (plumber(4)'s directory): plumb/<port>'s files, +/// a port's index its node. +ports: std.ArrayList([]u8) = .empty, +/// The rules in force read, kept until their text changes (by its hash): +/// a send parses nothing (29k instructions a send in a fast build, half +/// of what a URL's costs). Each process's own. +parsed: ?struct { hash: u64, rules: Rules } = null, +parsed_arena: ?std.heap.ArenaAllocator = null, + +pub const replica = .{ .derived = .{ "parsed", "parsed_arena" } }; + +/// The default rules, which `include basic` names, as Plan 9's names +/// /lib/plumb/basic. +pub const basic = @embedFile("plumbing"); + +/// The most rule text kept (Plan 9's whole basic is about 4 KiB), variables +/// and ports, as Plan 9's NDIR less its fixed files; deeper includes, as +/// rules.c's pushinput. +pub const max_text = 64 * 1024; +const max_vars = 32; +const max_ports = 32; +const max_depth = 10; + +/// fsys.c's and match.c's words for a message that went nowhere. +pub const e_bad_msg = "bad plumb message format"; +pub const e_no_port = "couldn't find destination for message"; +pub const e_no_start = "no start action for plumb message"; +pub const e_client = "no port for \"client\" rule"; +pub const e_empty = "empty argument list"; + +pub fn deinit(pl: *Plumb, gpa: std.mem.Allocator) void { + if (pl.parsed_arena) |*a| a.deinit(); + pl.text.deinit(gpa); + for (pl.ports.items) |name| gpa.free(name); + pl.ports.deinit(gpa); +} + +// ---- the message ---- + +/// A plumb message (plumb.h, plumb(6)): six lines of header, then `data`. +pub const Msg = struct { + src: []const u8 = "", + dst: []const u8 = "", + wdir: []const u8 = "", + type: []const u8 = "", + /// `name=value` pairs, blank-separated, as they are packed: a value + /// holding a blank, a quote, `=` or a tab quoted rc's way. + attr: []const u8 = "", + data: []const u8 = "", + + /// plumbpack: the header lines, the data's length, the data. + pub fn pack(m: Msg, w: *std.Io.Writer) std.Io.Writer.Error!void { + try w.print("{s}\n{s}\n{s}\n{s}\n{s}\n{d}\n{s}", .{ m.src, m.dst, m.wdir, m.type, m.attr, m.data.len, m.data }); + } +}; + +/// plumbunpackpartial: a whole message, `more` bytes of its data still to +/// come, or one malformed (a header line short, a count the data passes). +pub const Unpacked = union(enum) { msg: Msg, more: usize, bad }; + +pub fn unpack(bytes: []const u8) Unpacked { + var lines: [6][]const u8 = undefined; + var at: usize = 0; + for (&lines) |*line| { + const nl = std.mem.indexOfScalarPos(u8, bytes, at, '\n') orelse return .bad; + line.* = bytes[at..nl]; + at = nl + 1; + } + // atoi's: digits after blanks, else 0. + const count = std.mem.trimStart(u8, lines[5], " \t"); + var n: usize = 0; + for (count) |c| { + if (c < '0' or c > '9') break; + n = std.math.mul(usize, n, 10) catch return .bad; + n = std.math.add(usize, n, c - '0') catch return .bad; + } + const rest = bytes.len - at; + if (n > rest) return .{ .more = n - rest }; + if (n < rest) return .bad; + return .{ .msg = .{ .src = lines[0], .dst = lines[1], .wdir = lines[2], .type = lines[3], .attr = lines[4], .data = bytes[at..] } }; +} + +/// One `name=value` of packed attributes, its value unquoted. +const Attr = struct { name: []const u8, value: []const u8 }; + +/// The attribute at `at.*` in `attr`, read as plumbunpackattr reads it, +/// its value unquoted into `buf`; null at their end, or at one with no +/// `=`, where Plan 9 stops. +fn nextAttr(attr: []const u8, at: *usize, buf: *[4096]u8) ?Attr { + var i = at.*; + while (i < attr.len and (attr[i] == ' ' or attr[i] == '\t')) i += 1; + if (i >= attr.len or attr[i] == '\n') return null; + const start = i; + while (i < attr.len and attr[i] != '=' and attr[i] != ' ' and attr[i] != '\t' and attr[i] != '\n') i += 1; + if (i >= attr.len or attr[i] != '=') return null; + const name = attr[start..i]; + i += 1; + var n: usize = 0; + var quoting = false; + while (i < attr.len and attr[i] != '\n' and n < buf.len) { + const c = attr[i]; + i += 1; + if (c == '\'') { + if (!quoting) { + quoting = true; + continue; + } + if (i < attr.len and attr[i] == '\'') { + i += 1; + } else { + quoting = false; + continue; + } + } else if (!quoting and (c == ' ' or c == '\t')) break; + buf[n] = c; + n += 1; + } + at.* = i; + return .{ .name = name, .value = buf[0..n] }; +} + +/// plumblookup: the first attribute named `name`'s value. +fn attrValue(attr: []const u8, name: []const u8, buf: *[4096]u8) ?[]const u8 { + var at: usize = 0; + while (nextAttr(attr, &at, buf)) |a| if (std.mem.eql(u8, a.name, name)) return a.value; + return null; +} + +/// `attr` packed again (plumbpackattr): the first attribute named `drop` +/// left out (plumbdelattr), those of `add` after it (plumbaddattr). +fn repack(arena: std.mem.Allocator, attr: []const u8, drop: ?[]const u8, add: []const u8) error{OutOfMemory}![]const u8 { + var out: std.Io.Writer.Allocating = .init(arena); + var dropped = drop == null; + var buf: [4096]u8 = undefined; + for ([2][]const u8{ attr, add }) |from| { + var at: usize = 0; + while (nextAttr(from, &at, &buf)) |a| { + if (!dropped and std.mem.eql(u8, a.name, drop.?)) { + dropped = true; + continue; + } + const w = &out.writer; + if (out.written().len > 0) w.writeByte(' ') catch return error.OutOfMemory; + w.print("{s}=", .{a.name}) catch return error.OutOfMemory; + // mesg.c's quote: a value with a blank, a quote, `=` or a tab. + if (std.mem.indexOfAny(u8, a.value, " '=\t") == null) { + w.writeAll(a.value) catch return error.OutOfMemory; + continue; + } + w.writeByte('\'') catch return error.OutOfMemory; + for (a.value) |c| { + if (c == '\'') w.writeByte('\'') catch return error.OutOfMemory; + w.writeByte(c) catch return error.OutOfMemory; + } + w.writeByte('\'') catch return error.OutOfMemory; + } + } + return out.written(); +} + +// ---- the rules ---- + +/// rules.c's objects and verbs, in its order (`kind` is an old `type`). +const Obj = enum { arg, attr, data, dst, plumb, src, type, wdir }; +const Verb = enum { add, client, delete, is, isdir, isfile, matches, set, start, to }; + +/// A line `object verb arg`: `qarg` is `arg` expanded with the variables +/// alone, its first word, as rules.c's parserule keeps it. +const Rule = struct { obj: Obj, verb: Verb, arg: []const u8, qarg: []const u8 }; +const Set = struct { pats: []const Rule, acts: []const Rule, port: ?[]const u8 }; +const Var = struct { name: []const u8, value: []const u8, qvalue: []const u8 }; + +/// The rules as read, each item where it was written: printed back in +/// that order, a variable given again later means what it meant to the +/// rules between (Plan 9's printrules puts every variable first). +const Rules = struct { + items: std.ArrayList(union(enum) { variable: Var, ports: []const Rule, set: Set }) = .empty, + vars: std.ArrayList(Var) = .empty, + /// Every port a rule set or a declaration names, once, in order. + ports: std.ArrayList([]const u8) = .empty, + + fn print(r: *const Rules, w: *std.Io.Writer) std.Io.Writer.Error!void { + for (r.items.items) |item| switch (item) { + .variable => |v| try w.print("{s}={s}\n\n", .{ v.name, v.value }), + .ports => |acts| { + for (acts) |a| try printRule(w, a); + try w.writeByte('\n'); + }, + .set => |set| { + for (set.pats) |a| try printRule(w, a); + for (set.acts) |a| try printRule(w, a); + try w.writeByte('\n'); + }, + }; + } + + fn printRule(w: *std.Io.Writer, r: Rule) std.Io.Writer.Error!void { + try w.print("{s}\t{s}\t{s}\n", .{ @tagName(r.obj), @tagName(r.verb), r.arg }); + } + + fn named(r: *const Rules, port: []const u8) bool { + for (r.ports.items) |n| if (std.mem.eql(u8, n, port)) return true; + return false; + } +}; + +/// What a message is matched with, beside the rules: the message, and what +/// the rule set's patterns found so far (match.c's Exec). +const Exec = struct { + m: *Msg, + /// The last `data matches`'s match, `$0`. + match0: []const u8 = "", + /// The span a click match took, which every other `data matches` of + /// the set must take too. + span: ?[2]usize = null, + clearclick: bool = false, + setdata: bool = false, + /// What `isfile` and `isdir` found: `$file`, `$dir`. + file: ?[]const u8 = null, + dir: ?[]const u8 = null, +}; + +/// rules.c's expand: the first word of `s` (a blank outside quotes ends +/// it), quotes rc's (`'...'`, `''` a quote), `$name` a variable's value, +/// with a message the message's (`$data`, `$0`, `$file`, ...); a `$` that +/// names nothing stays. Past `out` (Plan 9's 4 KiB ebuf), `TooLong`. +/// Answers the word and how much of `s` it took. +fn expand(r: *const Rules, e: ?*const Exec, s: []const u8, out: *[4096]u8) error{TooLong}!struct { []const u8, usize } { + var w = std.Io.Writer.fixed(out); + var i: usize = 0; + var quoting = false; + while (i < s.len and (quoting or (s[i] != ' ' and s[i] != '\t'))) { + if (s[i] == '\'') { + i += 1; + if (!quoting) { + quoting = true; + } else if (i < s.len and s[i] == '\'') { + w.writeByte('\'') catch return error.TooLong; + i += 1; + } else quoting = false; + continue; + } + if (quoting or s[i] != '$') { + w.writeByte(s[i]) catch return error.TooLong; + i += 1; + continue; + } + i += 1; + const took = dollar(r, e, s[i..], &w) catch return error.TooLong; + if (took) |n| i += n else w.writeByte('$') catch return error.TooLong; + } + return .{ w.buffered(), i }; +} + +/// rules.c's dollar: the value `$` then `s` names, written to `w`; how +/// much of `s` its name took, or null when it names nothing. +fn dollar(r: *const Rules, e: ?*const Exec, s: []const u8, w: *std.Io.Writer) std.Io.Writer.Error!?usize { + if (e) |x| if (s.len > 0 and std.ascii.isDigit(s[0])) { + // `$1`-`$9` were refused at parse (no submatches): `$0` alone. + if (s[0] == '0') try w.writeAll(x.match0); + return 1; + }; + var n: usize = 0; + while (n < s.len and std.ascii.isAlphanumeric(s[n])) n += 1; + const name = s[0..n]; + if (e) |x| { + const m = x.m; + const field: ?[]const u8 = if (std.mem.eql(u8, name, "src")) m.src else if (std.mem.eql(u8, name, "dst")) m.dst else if (std.mem.eql(u8, name, "attr")) m.attr else if (std.mem.eql(u8, name, "data")) m.data else if (std.mem.eql(u8, name, "type")) m.type else if (std.mem.eql(u8, name, "wdir")) m.wdir else null; + if (field) |f| { + try w.writeAll(f); + return n; + } + // rules.c's filename: what isfile or isdir found, else the data + // made absolute in wdir. + const found = if (std.mem.eql(u8, name, "file")) x.file else if (std.mem.eql(u8, name, "dir")) x.dir else null; + if (found != null or std.mem.eql(u8, name, "file") or std.mem.eql(u8, name, "dir")) { + if (found) |f| { + try w.writeAll(f); + } else if ((m.data.len > 0 and m.data[0] == '/') or m.wdir.len == 0) { + try w.writeAll(m.data); + } else try w.print("{s}/{s}", .{ m.wdir, m.data }); + return n; + } + } + for (r.vars.items) |v| if (std.mem.eql(u8, v.name, name)) { + try w.writeAll(v.qvalue); + return n; + }; + return null; +} + +/// Reads rule text into `rules` (rules.c's readrules): line by line, a +/// blank line (or a comment, or a variable) ending a rule set, an include +/// read in its place. A refusal is `why`: `<file>:<line>: <rules.c's words>`. +const Parser = struct { + arena: std.mem.Allocator, + /// Where an include is read from: none, only `basic`. + p: ?*Pardes, + /// Rules written, not the ones in force read again: their patterns + /// compiled and their bounds counted. + check: bool, + rules: Rules = .{}, + pats: std.ArrayList(Rule) = .empty, + acts: std.ArrayList(Rule) = .empty, + port: ?[]const u8 = null, + commands: usize = 0, + file: []const u8 = "", + line: usize = 0, + depth: usize = 0, + why: []const u8 = "", + + const Error = error{ Parse, OutOfMemory }; + + fn fail(ps: *Parser, comptime fmt: []const u8, args: anytype) Error { + ps.why = try std.fmt.allocPrint(ps.arena, "{s}:{d}: " ++ fmt, .{ ps.file, ps.line } ++ args); + return error.Parse; + } + + fn feed(ps: *Parser, name: []const u8, text: []const u8) Error!void { + ps.file = name; + ps.line = 0; + const whole = if (std.mem.endsWith(u8, text, "\n")) text[0 .. text.len - 1] else text; + var lines = std.mem.splitScalar(u8, whole, '\n'); + while (lines.next()) |line| { + ps.line += 1; + try ps.take(line); + } + } + + /// The text read, ended as its end ends a rule set. + fn finish(ps: *Parser) Error!void { + try ps.endSet(); + } + + /// rules.c's readrule, for one line. + fn take(ps: *Parser, raw: []const u8) Error!void { + const l = std.mem.trimStart(u8, raw, " \t"); + if (l.len == 0 or l[0] == '#') return ps.endSet(); + if (std.mem.startsWith(u8, l, "include")) return ps.include(l); + if (try ps.assignment(l)) return; + const obj_end = std.mem.indexOfAny(u8, l, " \t") orelse return ps.fail("malformed rule", .{}); + const obj_word = l[0..obj_end]; + const obj = std.meta.stringToEnum(Obj, obj_word) orelse + if (std.mem.eql(u8, obj_word, "kind")) .type else return ps.fail("unknown object {s}", .{obj_word}); + const rest = std.mem.trimStart(u8, l[obj_end..], " \t"); + const verb_end = std.mem.indexOfAny(u8, rest, " \t") orelse return ps.fail("malformed rule", .{}); + const verb = std.meta.stringToEnum(Verb, rest[0..verb_end]) orelse return ps.fail("unknown verb {s}", .{rest[0..verb_end]}); + const arg = std.mem.trimStart(u8, rest[verb_end..], " \t"); + if (arg.len == 0) return ps.fail("malformed rule", .{}); + // parserule. + const action = verb == .client or verb == .start or verb == .to; + if ((obj == .plumb) != action or (obj != .attr and (verb == .add or verb == .delete))) + return ps.fail("{s} not valid verb for object {s}", .{ @tagName(verb), @tagName(obj) }); + // pardes's regular expressions have no capture groups (regexp.zig, + // mvzr), and the user chose never to have an engine of pardes's + // own: a submatch is refused, never silently empty. + var quoting = false; + for (arg, 0..) |c, i| { + if (c == '\'') quoting = !quoting; + if (!quoting and c == '$' and i + 1 < arg.len and arg[i + 1] >= '1' and arg[i + 1] <= '9') + return ps.fail("${c}: no submatches (the regular expressions have no capture groups): use $0 and several matches", .{arg[i + 1]}); + } + const r: Rule = .{ .obj = obj, .verb = verb, .arg = arg, .qarg = try ps.word(arg) }; + if (verb == .matches and ps.check) { + var pat: [4096 + 4]u8 = undefined; + _ = Regex.compile(anchored(r.qarg, &pat)) catch |err| return ps.fail("{s}", .{Regex.message(err)}); + } + if (obj != .plumb) return ps.pats.append(ps.arena, r); + try ps.acts.append(ps.arena, r); + if (verb != .to) { + ps.commands += 1; + return; + } + // readruleset's: a declaration names many, a rule set one. + if (ps.pats.items.len > 0 and ps.port != null) return ps.fail("too many ports", .{}); + for ([_][]const u8{ ".", "..", "send", "rules" }) |bad| if (std.mem.eql(u8, r.qarg, bad)) + return ps.fail("illegal port name {s}", .{r.qarg}); + ps.port = r.qarg; + } + + /// readruleset's end: a rule set kept, ports declared, or a refusal. + fn endSet(ps: *Parser) Error!void { + const pats = ps.pats.items; + const acts = ps.acts.items; + const port = ps.port; + const commands = ps.commands; + ps.pats = .empty; + ps.acts = .empty; + ps.port = null; + ps.commands = 0; + if (commands > 1) return ps.fail("ruleset has more than one client or start action", .{}); + if (pats.len == 0 and acts.len == 0) return; + if (pats.len > 0 and acts.len > 0) { + try ps.rules.items.append(ps.arena, .{ .set = .{ .pats = pats, .acts = acts, .port = port } }); + } else { + if (acts.len == 0 or port == null) return ps.fail("ruleset must have patterns and actions", .{}); + for (acts) |a| if (a.verb != .to) return ps.fail("ruleset must have actions", .{}); + try ps.rules.items.append(ps.arena, .{ .ports = acts }); + } + for (acts) |a| if (a.verb == .to and !ps.rules.named(a.qarg)) { + if (ps.check and ps.rules.ports.items.len >= max_ports) return ps.fail("too many ports; max {d}", .{max_ports}); + try ps.rules.ports.append(ps.arena, a.qarg); + }; + } + + /// `s`'s first word expanded with the variables: a slice of `s` when + /// that changes nothing (no quote, no `$`), as in most rules. What a + /// parse keeps slices the text it read, which outlives it (the rules in + /// force, a write's, an include read into the arena, src/plumbing). + fn word(ps: *Parser, s: []const u8) Error![]const u8 { + var buf: [4096]u8 = undefined; + const w, const took = expand(&ps.rules, null, s, &buf) catch return ps.fail("string-too-long", .{}); + return if (std.mem.eql(u8, w, s[0..took])) s[0..took] else ps.arena.dupe(u8, w); + } + + /// rules.c's assignment: `name=value`, its value expanded once, now; + /// it ends a rule set as a blank line does. + fn assignment(ps: *Parser, l: []const u8) Error!bool { + if (!std.ascii.isAlphabetic(l[0])) return false; + var i: usize = 0; + while (i < l.len and std.ascii.isAlphanumeric(l[i])) i += 1; + const name = l[0..i]; + while (i < l.len and (l[i] == ' ' or l[i] == '\t')) i += 1; + if (i >= l.len or l[i] != '=') return false; + try ps.endSet(); + const value = std.mem.trimStart(u8, l[i + 1 ..], " \t"); + const v: Var = .{ .name = name, .value = value, .qvalue = try ps.word(value) }; + try ps.rules.items.append(ps.arena, .{ .variable = v }); + for (ps.rules.vars.items) |*old| if (std.mem.eql(u8, old.name, name)) { + old.* = v; + return true; + }; + if (ps.check and ps.rules.vars.items.len >= max_vars) return ps.fail("too many variables; max {d}", .{max_vars}); + try ps.rules.vars.append(ps.arena, v); + return true; + } + + /// rules.c's include: `include basic` is src/plumbing; another name + /// the configuration directory's file, an absolute one where it says. + fn include(ps: *Parser, l: []const u8) Error!void { + var words = std.mem.tokenizeAny(u8, l, " \t"); + const first = words.next().?; + const name = words.next() orelse ""; + const third = words.next(); + if (!std.mem.eql(u8, first, "include") or name.len == 0 or name[0] == '#' or (third != null and third.?[0] != '#')) + return ps.fail("malformed include statement", .{}); + if (ps.depth >= max_depth) return ps.fail("include stack too deep; max {d}", .{max_depth}); + const text = if (std.mem.eql(u8, name, "basic")) basic else text: { + var buf: [4096]u8 = undefined; + const p = ps.p orelse return ps.fail("can't open {s} for inclusion", .{name}); + const path = if (name[0] == '/') name else std.fmt.bufPrint(&buf, "{s}/{s}", .{ p.configDir() orelse "", name }) catch name; + break :text fs.readFile(ps.arena, path) catch return ps.fail("can't open {s} for inclusion", .{path}); + }; + const file = ps.file; + const line = ps.line; + ps.depth += 1; + try ps.feed(name, text); + ps.depth -= 1; + ps.file = file; + ps.line = line; + } +}; + +/// `pat` matching only the whole of what it is run over: `^(pat)$` (its +/// own anchors dropped, mvzr taking `^` only first), in `out`. +fn anchored(pat: []const u8, out: *[4096 + 4]u8) []const u8 { + var core = pat; + if (core.len > 0 and core[0] == '^') core = core[1..]; + if (core.len > 1 and core[core.len - 1] == '$' and core[core.len - 2] != '\\') core = core[0 .. core.len - 1]; + return std.fmt.bufPrint(out, "^({s})$", .{core}) catch pat; +} + +/// The rules in force as text to read again. +fn source(p: *Pardes) []const u8 { + return if (p.plumber.written) p.plumber.text.items else "include basic\n"; +} + +/// The rules in force read, for a send. +fn rulesOf(p: *Pardes, arena: std.mem.Allocator) Parser.Error!Rules { + var ps: Parser = .{ .arena = arena, .p = p, .check = false }; + try ps.feed("plumb/rules", source(p)); + try ps.finish(); + return ps.rules; +} + +/// The rules in force, read once for every send until they change. A +/// send made while a rule's word runs (a look it makes) reads them into +/// the step's scratch: the send it runs in holds the kept ones. +fn inForceRules(p: *Pardes) Parser.Error!Rules { + const pl = &p.plumber; + const hash = std.hash.Wyhash.hash(0, source(p)); + if (pl.parsed) |c| if (c.hash == hash) return c.rules; + if (p.plumb_declined != null) return rulesOf(p, p.scratch.allocator()); + pl.parsed = null; + if (pl.parsed_arena) |*a| a.deinit(); + pl.parsed_arena = .init(p.gpa); + const rules = try rulesOf(p, pl.parsed_arena.?.allocator()); + pl.parsed = .{ .hash = hash, .rules = rules }; + return rules; +} + +/// The rules in force as plumb/rules reads them, the defaults printed +/// (in the step's scratch) while none were written. +pub fn inForce(p: *Pardes) []const u8 { + if (p.plumber.written) return p.plumber.text.items; + const arena = p.scratch.allocator(); + const rules = rulesOf(p, arena) catch return ""; + var out: std.Io.Writer.Allocating = .init(arena); + rules.print(&out.writer) catch return ""; + return out.written(); +} + +/// What the `Plumb` word says to a rule written after it. +pub const e_word = "Plumb takes no rule now: rules are plumb(6) rule sets, in <config>/plumbing (Plumb opens it) or written to plumb/rules"; + +/// The plumbing file, the user's rules beside init (plumber(4)'s +/// $home/lib/plumbing), in `buf`; null with no configuration directory. +pub fn filePath(p: *Pardes, buf: *[4096]u8) ?[]const u8 { + const dir = p.configDir() orelse return null; + return std.fmt.bufPrint(buf, "{s}/plumbing", .{std.mem.trimEnd(u8, dir, "/")}) catch null; +} + +/// At boot, the plumbing file's rules in force, if it is there (the +/// plumber reading $home/lib/plumbing); a refusal is said, as an init +/// line that fails is, and the defaults stay. Either way the ports the +/// rules in force name have their files. +pub fn boot(p: *Pardes) void { + if (rulesOf(p, p.scratch.allocator())) |rules| notePorts(p, rules.ports.items) catch {} else |_| {} + var buf: [4096]u8 = undefined; + const path = filePath(p, &buf) orelse return; + const text = fs.read(p, path) catch return; + defer p.gpa.free(text); + if (apply(p, false, "plumbing", text)) |why| p.reportFailure(p.view().active, why); +} + +/// A file saved from pane `pane`: when it is the plumbing file, its rules +/// in force now, or the save says why not and the rules stay as they were +/// (plumb.ms's `cp lib/plumbing /mnt/plumb/rules`, done for you). +pub fn saved(p: *Pardes, pane: usize, path: []const u8, text: []const u8) void { + var buf: [4096]u8 = undefined; + const mine = filePath(p, &buf) orelse return; + if (!std.mem.eql(u8, mine, path)) return; + if (apply(p, false, "plumbing", text)) |why| p.reportFailure(pane, why); +} + +/// `names` added to the session's ports, those it has not yet, in order; +/// none when they would be more than max_ports. +fn notePorts(p: *Pardes, names: []const []const u8) error{ TooMany, OutOfMemory }!void { + var new: usize = 0; + for (names) |n| new += @intFromBool(portIndex(p, n) == null); + if (p.plumber.ports.items.len + new > max_ports) return error.TooMany; + try p.plumber.ports.ensureUnusedCapacity(p.gpa, new); + for (names) |n| if (portIndex(p, n) == null) p.plumber.ports.appendAssumeCapacity(try p.gpa.dupe(u8, n)); +} + +/// The port named `name`'s index, its file's node. +pub fn portIndex(p: *const Pardes, name: []const u8) ?u8 { + for (p.plumber.ports.items, 0..) |n, i| if (std.mem.eql(u8, n, name)) return @intCast(i); + return null; +} + +pub fn portName(p: *const Pardes, index: u8) ?[]const u8 { + return if (index < p.plumber.ports.items.len) p.plumber.ports.items[index] else null; +} + +/// Whether a program reads port `index` (an open of its file): the +/// authority's 9P state, asked through the tape. +fn portRead(p: *Pardes, index: u8) bool { + for (&p.fs.opens) |*o| if (o.node != 0 and o.what == .port and o.what.port.index == index) return true; + return false; +} + +/// `m` packed onto `q` (a reader's, the held ones'), after `lead` (a +/// held message's port); false when it is over what a queue holds. +fn enqueue(p: *Pardes, q: *events.Queue, lead: []const u8, m: *const Msg) bool { + var out: std.Io.Writer.Allocating = .init(p.scratch.allocator()); + out.writer.writeAll(lead) catch return false; + m.pack(&out.writer) catch return false; + if (out.written().len + 4 > q.cap) return false; + q.push(p.gpa, out.written()); + return true; +} + +/// A copy of `m` to every reader of port `index` (plumber(4)'s queuesend: +/// every fid open when it was sent), each read held for one answered. +fn fanOut(p: *Pardes, index: u8, m: *const Msg) void { + for (&p.fs.opens) |*o| if (o.node != 0 and o.what == .port and o.what.port.index == index) { + if (!enqueue(p, &o.what.port.queue, "", m)) { + var said: Kind.Buf(160) = .{}; + events.notePath(p, "err -", said.print("plumb/{s}: a message of {d} bytes is over a reader's {d} KiB, not sent to it", .{ portName(p, index).?, m.data.len, events.queue_cap / 1024 })); + } + }; + p.fs.news = true; +} + +/// A port's file opened (tree.zig): what `client` rules held for it, the +/// opener's (plumber(4)'s queueheld). +pub fn opened(p: *Pardes, index: u8, q: *events.Queue) void { + const held = &p.fs.plumb_held; + var kept: events.Queue = .{}; + while (held.peek()) |record| { + if (record[0] == index) { + q.push(p.gpa, record[1..]); + } else kept.push(p.gpa, record); + held.pop(); + } + held.deinit(p.gpa); + held.* = kept; +} + +/// No rules at all: a `>` to plumb/rules, before what it writes. +pub fn clear(p: *Pardes) void { + p.plumber.text.clearRetainingCapacity(); + p.plumber.written = true; +} + +/// `more` (read from `name`) read after the rules in force (`keep`) or in +/// their place, and what that makes kept as the rules: plumb/rules' write +/// and its close's rest, the plumbing file saved or read at boot. Null +/// when taken, else why not, in the step's scratch, the rules as they were. +pub fn apply(p: *Pardes, keep: bool, name: []const u8, more: []const u8) ?[]const u8 { + const arena = p.scratch.allocator(); + var ps: Parser = .{ .arena = arena, .p = p, .check = true }; + const said = said: { + if (keep) { + ps.feed("plumb/rules", source(p)) catch break :said ps.why; + ps.finish() catch break :said ps.why; + } + ps.feed(name, more) catch break :said ps.why; + ps.finish() catch break :said ps.why; + var out: std.Io.Writer.Allocating = .init(arena); + ps.rules.print(&out.writer) catch break :said "out of memory"; + if (out.written().len > max_text) break :said std.fmt.comptimePrint("rules too long; max {d} KiB", .{max_text / 1024}); + notePorts(p, ps.rules.ports.items) catch |err| break :said switch (err) { + error.TooMany => std.fmt.comptimePrint("too many ports; max {d}", .{max_ports}), + error.OutOfMemory => "out of memory", + }; + p.plumber.text.clearRetainingCapacity(); + p.plumber.text.appendSlice(p.gpa, out.written()) catch break :said "out of memory"; + p.plumber.written = true; + return null; + }; + return if (said.len > 0) said else "out of memory"; +} + +// ---- matching ---- + +/// One message's match (fsys.c's write of `send` through dispose): the +/// rules, and what the disk said of a name, asked once however many rules +/// ask it. +const Send = struct { + p: *Pardes, + /// The pane a look sent from, whose jump list's directories a name is + /// looked for in too; none from plumb/send. + from: ?usize, + arena: std.mem.Allocator, + rules: Rules, + /// The data as a look sent it (`Seen`): a message to `edit` that still + /// holds it is Look's to open. + looked: ?[]const u8 = null, + memo_name: ?[]const u8 = null, + memo_wdir: []const u8 = "", + memo: ?fs.Resolved = null, + memo_buf: [4096]u8 = undefined, + + /// Where a name is, as Look finds it: the place written after it + /// (`:12`, `:12:5`) no part of it, then the message's directory, the + /// jump list's panes' (from a look), then Incl's (look.zig's + /// resolveLookTarget). Each stat is a taped resolve site; a name is + /// asked once a send. + fn resolve(s: *Send, wdir: []const u8, raw: []const u8) ?fs.Resolved { + const name = look.parsePathLine(std.mem.trim(u8, raw, " \t\r\n")).path; + if (s.memo_name) |n| if (std.mem.eql(u8, n, name) and std.mem.eql(u8, s.memo_wdir, wdir)) return s.memo; + s.memo_name = s.arena.dupe(u8, name) catch return null; + s.memo_wdir = s.arena.dupe(u8, wdir) catch return null; + s.memo = s.search(wdir, name); + return s.memo; + } + + fn search(s: *Send, wdir: []const u8, name: []const u8) ?fs.Resolved { + if (name.len == 0) return null; + var dirs: look.Dirs = .init(s.p, s.from, wdir); + while (dirs.next()) |dir| { + if (fs.resolve(s.p, name, dir, &s.memo_buf)) |found| return found; + if (name[0] == '/' or fs.dotRelative(name)) return null; + } + for (s.p.incl.items) |dir| if (fs.resolve(s.p, name, dir, &s.memo_buf)) |found| return found; + return null; + } + + /// match.c's matchruleset: the message tried against `set`, rewritten + /// in place by its patterns (a `set` stays though a later one fails). + fn matchSet(s: *Send, set: Set, e: *Exec) error{OutOfMemory}!bool { + const m = e.m; + if (m.dst.len > 0 and set.port != null and !std.mem.eql(u8, m.dst, set.port.?)) return false; + for (set.pats) |r| if (!try s.pattern(e, r)) return false; + if (set.port) |port| if (m.dst.len == 0) { + m.dst = port; + }; + // match.c's rewrite: a click match's span is the data now. + if (e.clearclick) { + m.attr = try repack(s.arena, m.attr, "click", ""); + if (e.setdata) m.data = e.match0; + } + return true; + } + + /// match.c's matchpat. + fn pattern(s: *Send, e: *Exec, r: Rule) error{OutOfMemory}!bool { + const m = e.m; + const field: ?*[]const u8 = switch (r.obj) { + .data => &m.data, + .dst => &m.dst, + .type => &m.type, + .wdir => &m.wdir, + .src => &m.src, + .arg, .attr, .plumb => null, + }; + var buf: [4096]u8 = undefined; + switch (r.verb) { + .is => return if (field) |f| std.mem.eql(u8, f.*, r.qarg) else false, + .set => { + const f = field orelse return true; + const value = (expand(&s.rules, e, r.arg, &buf) catch return false)[0]; + f.* = try s.arena.dupe(u8, value); + if (r.obj == .data) { + e.span = null; + e.setdata = false; + } + return true; + }, + .add, .delete => { + if (r.obj != .attr) return false; + const value = (expand(&s.rules, e, r.arg, &buf) catch return false)[0]; + if (r.verb == .add) { + m.attr = try repack(s.arena, m.attr, null, value); + return true; + } + // The code's, not the man page's: an absent one fails. + var vbuf: [4096]u8 = undefined; + if (attrValue(m.attr, value, &vbuf) == null) return false; + m.attr = try repack(s.arena, m.attr, value, ""); + return true; + }, + .isfile, .isdir => { + const name = switch (r.obj) { + .arg => (expand(&s.rules, e, r.arg, &buf) catch return false)[0], + .data => m.data, + .wdir => m.wdir, + else => return false, + }; + const found = s.resolve(m.wdir, name) orelse return false; + if (found.dir != (r.verb == .isdir)) return false; + const path = try s.arena.dupe(u8, found.path); + if (r.verb == .isdir) e.dir = path else e.file = path; + return true; + }, + .matches => { + const text = (field orelse return false).*; + var pat: [4096 + 4]u8 = undefined; + var click_buf: [4096]u8 = undefined; + const click = if (r.obj == .data) attrValue(m.attr, "click", &click_buf) else null; + if (click == null) { + // The whole of it, as match.c asks of regexec's answer. + var rx = Regex.compile(anchored(r.qarg, &pat)) catch return false; + const hit = (rx.find(text, 0, 0, text.len) catch return false) orelse return false; + if (hit.start != 0 or hit.end != text.len) return false; + e.match0 = text; + return true; + } + // clickmatch: the first match from each start up to the + // click that holds it, the click counted in runes. + const runes = std.fmt.parseInt(usize, std.mem.trim(u8, click.?, " \t"), 10) catch 0; + var at: usize = 0; + var n: usize = 0; + while (n < runes and at < text.len) : (n += 1) at += std.unicode.utf8ByteSequenceLength(text[at]) catch 1; + at = @min(at, text.len); + var rx = Regex.compile(r.qarg) catch return false; + var from: usize = 0; + const hit = while (from <= at) { + const h = (rx.find(text, from, at, text.len) catch return false) orelse return false; + if (h.start <= at and at <= h.end) break h; + // Every start before the next match finds this one. + from = h.start + 1; + while (from < text.len and text[from] & 0xC0 == 0x80) from += 1; + } else return false; + if (e.span) |sp| if (sp[0] != hit.start or sp[1] != hit.end) return false; + e.span = .{ hit.start, hit.end }; + e.clearclick = true; + e.setdata = true; + e.match0 = text[hit.start..hit.end]; + return true; + }, + .client, .start, .to => return false, + } + } +}; + +/// The ports pardes reads itself, as acme reads `edit`; and every loaded +/// kind by its name. +const Port = enum { + /// A file or directory opened as Look opens one, at the place written + /// after its name or given as `addr=`. + edit, + /// A URL given to the host's browser (xdg-open, open on macOS). + web, +}; + +/// What a look found of the name it sends (look.zig's resolveLookTarget: +/// in its pane's directory, the jump list's, Incl's), which `isfile` and +/// `isdir` take as found rather than ask the disk again: the same answer, +/// and Look's own readings of a name kept (a URL, `//`: no file). +pub const Seen = struct { name: []const u8, found: ?fs.Resolved }; + +/// Where a send went. +pub const Sent = union(enum) { + /// Taken: started, or given to the port that reads it. + done, + /// To `edit` as the look sent it (`Seen`): Look opens what it found, + /// as acme's own look opens a file. + look, + /// Taken by nothing, in Plan 9's words; or what a rule started + /// declined it (`declined`). + refused: []const u8, +}; + +/// What a send a rule's started word declined says (Pardes.plumb_declined): +/// fsys.c's words for a message nothing takes. +pub const e_declined = "no matching plumb rule"; + +/// A message matched against the rules and sent where they say (fsys.c's +/// write of `send`, then dispose), from pane `from` (a look's) or from +/// plumb/send (null: the pane with the keyboard runs what it starts). +/// `seen` is a look's, what it found of the name it sends. A refusal is in +/// the step's scratch. +pub fn send(p: *Pardes, from: ?usize, msg: Msg, seen: ?Seen) Sent { + const arena = p.scratch.allocator(); + var s: Send = .{ .p = p, .from = from, .arena = arena, .rules = inForceRules(p) catch return .{ .refused = "plumb/rules: the rules in force do not read" } }; + if (seen) |look_seen| { + s.looked = msg.data; + s.memo_name = look_seen.name; + s.memo_wdir = msg.wdir; + s.memo = look_seen.found; + } + var m = msg; + var e: Exec = .{ .m = &m }; + const set: ?Set = for (s.rules.items.items) |item| { + const candidate = switch (item) { + .set => |x| x, + else => continue, + }; + e = .{ .m = &m }; + if (s.matchSet(candidate, &e) catch return .{ .refused = "out of memory" }) break candidate; + } else null; + const id = from orelse p.view().active; + // dispose. + if (m.dst.len == 0) return startup(&s, id, set orelse return .{ .refused = e_no_port }, &e); + const port = portIndex(p, m.dst); + // A port pardes reads itself: its readers' copies (a program reading + // plumb/edit sees every open, plumber(4)'s fan-out), the authority's + // alone to hand out, so asked of nobody; then pardes's own. + if (std.meta.stringToEnum(Port, m.dst)) |own| { + if (port) |i| fanOut(p, i, &m); + return deliver(&s, id, own, &m); + } + if (p.kinds.byName(m.dst)) |k| { + if (port) |i| fanOut(p, i, &m); + openInKind(&s, id, k, &m); + return .done; + } + // One no rule ever named is none, and the message goes nowhere, as + // fsys.c's dispose finds no Dirtab for it. Another goes to its readers, + // whom only the authority knows (its 9P opens); with none, what the + // rule set starts. + const i = port orelse return .done; + if (tape.authority(portRead, .{ p, i })) { + fanOut(p, i, &m); + return .done; + } + return startup(&s, id, set orelse return .{ .refused = e_no_start }, &e); +} + +/// match.c's startup: the rule set's `start` or `client`, its words +/// expanded, run. +fn startup(s: *Send, id: usize, set: Set, e: *const Exec) Sent { + const act = for (set.acts) |a| { + if (a.verb == .start) break a; + if (a.verb == .client) { + if (e.m.dst.len == 0) return .{ .refused = e_client }; + break a; + } + } else return .{ .refused = e_no_start }; + // buildargv: one expansion a word. + var argv: std.ArrayList([]const u8) = .empty; + var rest = act.arg; + while (true) { + rest = std.mem.trimStart(u8, rest, " \t"); + if (rest.len == 0) break; + var buf: [4096]u8 = undefined; + const word, const took = expand(&s.rules, e, rest, &buf) catch return .{ .refused = "string-too-long" }; + argv.append(s.arena, s.arena.dupe(u8, word) catch return .{ .refused = "out of memory" }) catch return .{ .refused = "out of memory" }; + rest = rest[took..]; + } + if (argv.items.len == 0) return .{ .refused = e_empty }; + if (run(s.p, id, e.m.wdir, argv.items)) |why| return .{ .refused = why }; + // `client`: the message waits for the port's first reader, the program + // it started perhaps (plumber(4)'s hold); held messages past what the + // queue keeps push out the oldest. + if (act.verb == .client) if (portIndex(s.p, e.m.dst)) |i| { + if (!enqueue(s.p, &s.p.fs.plumb_held, &.{i}, e.m)) return .{ .refused = "plumb: message too big to hold for a client" }; + }; + return .done; +} + +/// What a `plumb start` or a `plumb client` runs: +/// the one place that decides it (question 4 of docs/next-plumber.md). +/// A builtin or a kind's word runs in place, from the message's pane, as +/// a line of it would; one that cannot do what the message asks declines +/// (Pardes.plumb_declined), saying nothing, and the send is refused, so a +/// look looks itself. Any other is a program, started as Plan 9's plumber +/// starts one (match.c's startup): detached, no pane, its argv exec'd in +/// `wdir` with no shell (a rule that wants one says `sh -c`), by the host +/// (Effect.start), which says a failure to start in the log. Null when it +/// ran, else why not. +fn run(p: *Pardes, id: usize, wdir: []const u8, argv: []const []const u8) ?[]const u8 { + const arena = p.scratch.allocator(); + const line = std.mem.join(arena, " ", argv) catch return "out of memory"; + const outer = p.plumb_declined; + p.plumb_declined = false; + defer p.plumb_declined = outer; + // Started, not clicked: no name said for it under Verbose. + const announce = p.announce; + p.announce = false; + defer p.announce = announce; + if (p.executeBuiltinLine(id, line)) return if (p.plumb_declined.?) e_declined else null; + // Its directory, then its words, each ended by a NUL. + var start: pardes.Effect.Buf(pardes.effect_path_cap) = .{}; + for ([_][]const []const u8{ &.{wdir}, argv }) |words| for (words) |w| { + if (std.mem.indexOfScalar(u8, w, 0) != null) return "plumb start: a NUL in a word"; + if (start.len + w.len + 1 > start.data.len) return std.fmt.comptimePrint("plumb start: over {d} bytes", .{pardes.effect_path_cap}); + @memcpy(start.data[start.len..][0..w.len], w); + start.data[start.len + w.len] = 0; + start.len += @intCast(w.len + 1); + }; + p.emit(.{ .start = .{ .pane = @intCast(id), .line = start } }); + return null; +} + +/// What pardes does with a message to a port it reads. Like a message +/// queued to a reader in Plan 9, the send is done: what goes wrong after +/// is said as a look's failure is. +fn deliver(s: *Send, id: usize, port: Port, m: *const Msg) Sent { + const p = s.p; + switch (port) { + .web => { + if (m.data.len > 256) p.reportFailure(id, "plumb: web: a URL is at most 256 bytes") else p.emit(.{ .open_link = .from(m.data) }); + }, + .edit => { + // acme's plumbshow, for `plumb -i`: the data shown, not a name. + var action_buf: [4096]u8 = undefined; + const action = attrValue(m.attr, "action", &action_buf) orelse ""; + if (std.mem.eql(u8, action, "showdata") or std.mem.eql(u8, action, "showdiff")) { + show(s, id, m, std.mem.eql(u8, action, "showdiff")); + return .done; + } + var buf: [4096]u8 = undefined; + const addr = attrValue(m.attr, "addr", &buf) orelse ""; + // A look's own name, as it sent it: its own look opens it. + if (s.looked) |data| if (addr.len == 0 and std.mem.eql(u8, data, m.data)) return .look; + // acme's plumblook: the data a name in wdir, at its addr, + // opened as Look opens one and not sent again. + const relative = m.data.len > 0 and m.data[0] != '/' and m.data[0] != '~' and m.wdir.len > 0; + const text = std.fmt.allocPrint(s.arena, "{s}{s}{s}{s}{s}", .{ + if (relative) m.wdir else "", if (relative) "/" else "", m.data, + if (addr.len > 0) ":" else "", addr, + }) catch { + p.reportError(id, "plumb", error.OutOfMemory); + return .done; + }; + const was = p.look_text; + p.look_text = true; + defer p.look_text = was; + look.lookAt(p, id, text); + }, + } + return .done; +} + +/// The edit port's `showdata` and `showdiff` (acme's plumbshow): the data +/// in the pane `filename` names, the pane that sent it first (a +Pager's +/// own text), else a new one so named (`+Plumbed` with none), clean; +/// `showdiff` then stacks it in a +Diff in that pane's place (hunks.paged), +/// as a diff paged always was. +fn show(s: *Send, id: usize, m: *const Msg, diff: bool) void { + const p = s.p; + var buf: [4096]u8 = undefined; + const filename = attrValue(m.attr, "filename", &buf) orelse ""; + const named = std.mem.eql(u8, filename, if (p.panes[id]) |pn| (if (pn.file) |f| f.path else "") else ""); + const shown: usize = if (named) id else shown: { + const name = if (filename.len > 0) filename else "+Plumbed"; + const free = p.freeSlot() orelse return p.reportError(id, "plumb", error.NoPaneSlots); + pardes.panes.newScratchFor(p, id, .scratch); + const made = p.panes[free] orelse return; + @import("ninep/pane.zig").nameBuffer(p, free, name, false) catch |err| return p.reportError(id, "plumb", err); + const f = &made.file.?; + _ = pardes.panes.File.replace(p, f, 0, f.content.len, m.data); + f.saved_revision = f.revision; + break :shown free; + }; + if (diff) @import("hunks.zig").paged(p, shown); +} + +/// A +Pager filled (ninep/ctl.zig fillPager) with a diff (File.looksLikeDiff: +/// `git show`, a mailed patch): sent to `edit`, as acme's `plumb -i` +/// sends what it shows, `type text/x-diff`, `action=showdata` and the +/// +Pager's name; the default rules make it `showdiff`, stacked in a +Diff +/// in the +Pager's place. Other text paged is not sent: the look rules +/// would read it whole (a `matches` over a MiB of output, up to the +/// regular expressions' budget, at each page). +pub fn paged(p: *Pardes, id: usize) void { + const pane = p.panes[id] orelse return; + const f = pane.file orelse return; + if (!f.pager_diff) return; + var attr: std.Io.Writer.Allocating = .init(p.scratch.allocator()); + attr.writer.writeAll("action=showdata filename=") catch return; + // mesg.c's quote, for a name with a blank, a quote, `=` or a tab. + const quote = std.mem.indexOfAny(u8, f.path, " '=\t") != null; + if (quote) attr.writer.writeByte('\'') catch return; + for (f.path) |c| { + if (c == '\'') attr.writer.writeByte('\'') catch return; + attr.writer.writeByte(c) catch return; + } + if (quote) attr.writer.writeByte('\'') catch return; + switch (send(p, id, .{ .src = "pager", .dst = "edit", .wdir = Pardes.paneDir(pane), .type = "text/x-diff", .attr = attr.written(), .data = f.content }, null)) { + .done, .look => {}, + .refused => |why| p.reportFailure(id, why), + } +} + +/// A message to a loaded kind's port: its data, a file, opened in that kind +/// (or its pane given the keyboard, when one shows it). +fn openInKind(s: *Send, id: usize, k: u8, m: *const Msg) void { + const p = s.p; + const found = s.resolve(m.wdir, m.data) orelse return p.reportFailure(id, "plumb: no such file"); + if (found.dir) return p.reportFailure(id, "plumb: a directory is no kind's"); + const path = s.arena.dupe(u8, found.path) catch return; + for (p.panes, 0..) |slot, i| if (slot) |pn| if (pn.addon) |a| if (std.mem.eql(u8, a.path, path)) { + p.view().active = i; + return; + }; + const free = p.freeSlot() orelse return p.reportError(id, "plumb", error.NoPaneSlots); + const made = Kind.openFile(p, free, k, path) catch |err| return p.reportError(id, path, err); + if (made.addon.?.refused.len > 0) { + made.vweight = 0; + p.unplaced.set(free); + return p.reportFailure(id, s.arena.dupe(u8, made.addon.?.refused.slice()) catch "plumb: refused"); + } + layout.placeNew(p, id, id, free, .doc); +} + +/// Where rule text written in pieces is whole: through its last blank line +/// (rules.c's morerules), 0 when none is. +pub fn wholeSets(text: []const u8) usize { + return if (std.mem.lastIndexOf(u8, text, "\n\n")) |at| at + 2 else 0; +} + +// ---- tests ---- + +const testing = std.testing; + +/// The rules `text` read as written ones are, printed; or the refusal. +fn reread(arena: std.mem.Allocator, text: []const u8) ![]const u8 { + var ps: Parser = .{ .arena = arena, .p = null, .check = true }; + ps.feed("t", text) catch return ps.why; + ps.finish() catch return ps.why; + var out: std.Io.Writer.Allocating = .init(arena); + try ps.rules.print(&out.writer); + return out.written(); +} + +test "plumb: a message packs as plumb(6)'s six lines and its data, and unpacks whole, short of its data, or malformed" { + var buf: [256]u8 = undefined; + var w = std.Io.Writer.fixed(&buf); + const m: Msg = .{ .src = "pardes", .wdir = "/tmp", .type = "text", .attr = "click=3 addr=12", .data = "a b\nc" }; + try m.pack(&w); + try testing.expectEqualStrings("pardes\n\n/tmp\ntext\nclick=3 addr=12\n5\na b\nc", w.buffered()); + const back = unpack(w.buffered()).msg; + inline for (.{ "src", "dst", "wdir", "type", "attr", "data" }) |f| try testing.expectEqualStrings(@field(m, f), @field(back, f)); + try testing.expectEqual(@as(usize, 2), unpack(w.buffered()[0 .. w.buffered().len - 2]).more); + // A header line short is no message at all, as is data past its count. + try testing.expect(unpack("pardes\n\n/tmp\ntext\n") == .bad); + try testing.expect(unpack("a\nb\nc\nd\ne\n1\nxy") == .bad); + try testing.expect(unpack("a\nb\nc\nd\ne\nzz\n") == .msg); +} + +test "plumb: attributes read rc's quotes, a value that needs them is quoted again, delete takes the first, add appends" { + var arena: std.heap.ArenaAllocator = .init(testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var buf: [4096]u8 = undefined; + const attr = "action=showdata filename='/a b/it''s' click=4"; + try testing.expectEqualStrings("/a b/it's", attrValue(attr, "filename", &buf).?); + try testing.expectEqualStrings("4", attrValue(attr, "click", &buf).?); + try testing.expect(attrValue(attr, "addr", &buf) == null); + try testing.expectEqualStrings("action=showdata filename='/a b/it''s'", try repack(a, attr, "click", "")); + try testing.expectEqualStrings("action=showdata filename='/a b/it''s' click=4 addr='x=1'", try repack(a, attr, null, "addr='x=1'")); + // One with no `=` ends them, as plumbunpackattr stops there. + try testing.expect(attrValue("a=1 bogus b=2", "b", &buf) == null); +} + +test "plumb: every parse error in rules.c's words, with its line" { + var arena: std.heap.ArenaAllocator = .init(testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + for ([_][2][]const u8{ + .{ "type is text\nbogus\n", "t:2: malformed rule" }, + .{ "type is\n", "t:1: malformed rule" }, + .{ "type \n", "t:1: malformed rule" }, + .{ "colour is red\n", "t:1: unknown object colour" }, + .{ "type equals text\n", "t:1: unknown verb equals" }, + .{ "data to edit\n", "t:1: to not valid verb for object data" }, + .{ "type start x\n", "t:1: start not valid verb for object type" }, + .{ "data add x=1\n", "t:1: add not valid verb for object data" }, + .{ "plumb is edit\n", "t:1: is not valid verb for object plumb" }, + .{ "type is text\nplumb to a\nplumb to b\n", "t:3: too many ports" }, + .{ "type is text\nplumb to send\n", "t:2: illegal port name send" }, + .{ "plumb to ..\n", "t:1: illegal port name .." }, + .{ "plumb to rules\n", "t:1: illegal port name rules" }, + .{ "type is text\nplumb start a\nplumb client b\n", "t:3: ruleset has more than one client or start action" }, + .{ "type is text\n\n", "t:2: ruleset must have patterns and actions" }, + .{ "plumb start x\n", "t:1: ruleset must have patterns and actions" }, + .{ "plumb to a\nplumb start x\n\n", "t:3: ruleset must have actions" }, + .{ "include\n", "t:1: malformed include statement" }, + .{ "include a b\n", "t:1: malformed include statement" }, + .{ "includes x\n", "t:1: malformed include statement" }, + .{ "include nowhere\n", "t:1: can't open nowhere for inclusion" }, + .{ "data matches '[a-'\nplumb to edit\n", "t:1: bad regular expression" }, + .{ "data matches '([a-z]+)\\.c'\narg isfile $1\nplumb to edit\n", "t:2: $1: no submatches (the regular expressions have no capture groups): use $0 and several matches" }, + }) |c| try testing.expectEqualStrings(c[1], try reread(a, c[0])); + // Inside quotes a `$1` is the text `$1`. + try testing.expectEqualStrings("data\tis\t'$1'\nplumb\tto\tedit\n\n", try reread(a, "data is '$1'\nplumb to edit\n")); + // The most variables, and ports, are bounded. + var many: std.Io.Writer.Allocating = .init(a); + for (0..max_vars + 1) |i| try many.writer.print("v{d}=x\n", .{i}); + try testing.expectEqualStrings("t:33: too many variables; max 32", try reread(a, many.written())); + many.clearRetainingCapacity(); + for (0..max_ports + 1) |i| try many.writer.print("plumb to p{d}\n", .{i}); + try testing.expectEqualStrings("t:33: too many ports; max 32", try reread(a, many.written())); +} + +test "plumb: rules print as rule sets of tab-separated lines, variables where they were set, and read back the same" { + var arena: std.heap.ArenaAllocator = .init(testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const text = + \\# a comment ends nothing it is not in + \\x = '[a-z]+' + \\plumb to seemail + \\plumb to showmail + \\ + \\kind is text + \\data matches $x + \\plumb to edit + \\x=other + \\type is text + \\data set $x + \\plumb start Msg $data + ; + const printed = try reread(a, text); + try testing.expectEqualStrings("x='[a-z]+'\n\nplumb\tto\tseemail\nplumb\tto\tshowmail\n\ntype\tis\ttext\ndata\tmatches\t$x\nplumb\tto\tedit\n\nx=other\n\ntype\tis\ttext\ndata\tset\t$x\nplumb\tstart\tMsg $data\n\n", printed); + try testing.expectEqualStrings(printed, try reread(a, printed)); + // The default rules read, and print as they read. + const defaults = try reread(a, "include basic\n"); + try testing.expect(std.mem.indexOf(u8, defaults, "data\tmatches\t'https?://.*'\nplumb\tto\tweb\n") != null); + try testing.expectEqualStrings(defaults, try reread(a, defaults)); +} + +test "plumb: rc's quoting, variables and the message's in an expansion, the first word alone" { + var arena: std.heap.ArenaAllocator = .init(testing.allocator); + defer arena.deinit(); + var ps: Parser = .{ .arena = arena.allocator(), .p = null, .check = true }; + try ps.feed("t", "v='a b'\nw=x$v'y'\n"); + var m: Msg = .{ .src = "pardes", .wdir = "/w", .data = "f.c" }; + var e: Exec = .{ .m = &m, .match0 = "zero" }; + var buf: [4096]u8 = undefined; + for ([_][2][]const u8{ + .{ "'it''s' rest", "it's" }, + .{ "pre$v.post", "prea b.post" }, + .{ "$w", "xa by" }, + .{ "'$v'", "$v" }, + .{ "$nothere$", "$nothere$" }, + .{ "$src:$wdir:$data:$0:$file", "pardes:/w:f.c:zero:/w/f.c" }, + }) |c| try testing.expectEqualStrings(c[1], (try expand(&ps.rules, &e, c[0], &buf))[0]); + e.file = "/real/f.c"; + try testing.expectEqualStrings("/real/f.c", (try expand(&ps.rules, &e, "$file", &buf))[0]); + // Past 4 KiB: too long, never cut. + const long = try arena.allocator().alloc(u8, 5000); + @memset(long, 'a'); + m.data = long; + try testing.expectError(error.TooLong, expand(&ps.rules, &e, "$data", &buf)); +} + +/// A send against `text`'s rules on a session of its own: the message +/// after its match, the rule set that took it (its index among the sets, +/// null for none) and what dispose said. +const Tried = struct { m: Msg, set: ?usize }; + +fn tryRules(p: *Pardes, text: []const u8, msg: Msg) !Tried { + try testing.expect(apply(p, false, "plumb/rules", text) == null); + const arena = p.scratch.allocator(); + var s: Send = .{ .p = p, .from = null, .arena = arena, .rules = try rulesOf(p, arena) }; + var m = msg; + var e: Exec = .{ .m = &m }; + var n: usize = 0; + for (s.rules.items.items) |item| { + const set = switch (item) { + .set => |x| x, + else => continue, + }; + e = .{ .m = &m }; + if (try s.matchSet(set, &e)) return .{ .m = m, .set = n }; + n += 1; + } + return .{ .m = m, .set = null }; +} + +test "plumb: matches takes the whole text, or with a click the run around it: Pike's horse.gift is no gif" { + const p = try Pardes.init(testing.allocator, .{ .cols = 80, .rows = 24 }); + defer p.deinit(); + const rules = + \\type is text + \\data matches '[a-zA-Z0-9_\-./]+' + \\data matches '([a-zA-Z0-9_\-./]+)\.(gif|jpe?g)' + \\plumb to image + \\ + ; + try testing.expectEqual(@as(?usize, 0), (try tryRules(p, rules, .{ .type = "text", .data = "horse.gif" })).set); + try testing.expect((try tryRules(p, rules, .{ .type = "text", .data = "horse.gift" })).set == null); + try testing.expect((try tryRules(p, rules, .{ .type = "text", .data = "see horse.gif" })).set == null); + // A click inside the name: the run of file characters around it, the + // data cut to it and the click gone. + const hit = try tryRules(p, rules, .{ .type = "text", .attr = "click=7", .data = "see horse.gif now" }); + try testing.expectEqual(@as(?usize, 0), hit.set); + try testing.expectEqualStrings("horse.gif", hit.m.data); + try testing.expectEqualStrings("", hit.m.attr); + try testing.expectEqualStrings("image", hit.m.dst); + try testing.expect((try tryRules(p, rules, .{ .type = "text", .attr = "click=7", .data = "see horse.gift now" })).set == null); + // The click counts runes: two bytes of é before it. + try testing.expectEqualStrings("horse.gif", (try tryRules(p, rules, .{ .type = "text", .attr = "click=3", .data = "é horse.gif" })).m.data); + // Each object a rule matches whole. + const src = "src\tmatches\t'par.*'\ntype\tmatches\t'te(x|y)t'\nplumb\tto\tedit\n"; + try testing.expectEqual(@as(?usize, 0), (try tryRules(p, src, .{ .src = "pardes", .type = "text" })).set); + try testing.expect((try tryRules(p, src, .{ .src = "pardes", .type = "texts" })).set == null); + // The default rules' URL: http and https, whole. + try testing.expectEqual(@as(?usize, 0), (try tryRules(p, basic, .{ .type = "text", .data = "https://ziglang.org/x?y" })).set); + try testing.expect((try tryRules(p, basic, .{ .type = "text", .data = "see https://ziglang.org" })).set == null); +} + +test "plumb: a set rewrites the message for good, attr delete of one absent fails, a message to a port tries only rule sets to it" { + const p = try Pardes.init(testing.allocator, .{ .cols = 80, .rows = 24 }); + defer p.deinit(); + const rules = + \\data set changed + \\type is never + \\plumb to a + \\ + \\attr delete action + \\attr add 'action=showdiff filename=x' + \\plumb to b + \\ + \\data is changed + \\plumb to c + \\ + ; + // The first set fails after its `set`: the data stays changed; the + // second fails at its delete; the third sees the changed data. + const t = try tryRules(p, rules, .{ .type = "text", .data = "orig" }); + try testing.expectEqual(@as(?usize, 2), t.set); + try testing.expectEqualStrings("changed", t.m.data); + try testing.expectEqualStrings("c", t.m.dst); + const d = try tryRules(p, rules, .{ .type = "text", .attr = "action=showdata", .data = "x" }); + try testing.expectEqual(@as(?usize, 1), d.set); + try testing.expectEqualStrings("action=showdiff filename=x", d.m.attr); + // dst names a port: rule sets to another are passed over. + const to_a = try tryRules(p, "data\tis\tx\nplumb\tto\ta\n\ndata\tis\tx\nplumb\tto\tb\n\n", .{ .dst = "b", .data = "x" }); + try testing.expectEqual(@as(?usize, 1), to_a.set); +} + +test "plumb: isfile and isdir find a name as Look does, past its place, in the message's directory then Incl's; $file is where" { + if (!fs.platform_has_fs) return; + var tmp = testing.tmpDir(.{}); + defer tmp.cleanup(); + try tmp.dir.writeFile(testing.io, .{ .sub_path = "it.zig", .data = "x\n" }); + try tmp.dir.createDir(testing.io, "sub", .default_dir); + var dir_buf: [4096]u8 = undefined; + const root = dir_buf[0..try tmp.dir.realPath(testing.io, &dir_buf)]; + const p = try Pardes.init(testing.allocator, .{ .cols = 80, .rows = 24 }); + defer p.deinit(); + const rules = "arg\tisfile\t$data\ndata\tset\t$file\nplumb\tto\tedit\n\narg\tisdir\t$data\ndata\tset\t$dir\nplumb\tto\tedit\n\n"; + const file = try tryRules(p, rules, .{ .wdir = root, .data = "it.zig:3:2" }); + try testing.expectEqual(@as(?usize, 0), file.set); + try testing.expect(std.mem.endsWith(u8, file.m.data, "/it.zig")); + const dir = try tryRules(p, rules, .{ .wdir = root, .data = "sub" }); + try testing.expectEqual(@as(?usize, 1), dir.set); + try testing.expect(std.mem.endsWith(u8, dir.m.data, "/sub")); + try testing.expect((try tryRules(p, rules, .{ .wdir = root, .data = "nothere.zig" })).set == null); + // Not in wdir: Incl's directories, as acme's includename. + try p.incl.append(p.gpa, try p.gpa.dupe(u8, root)); + try testing.expectEqual(@as(?usize, 0), (try tryRules(p, rules, .{ .wdir = "/", .data = "it.zig" })).set); + try testing.expect((try tryRules(p, rules, .{ .wdir = "/", .data = "./it.zig" })).set == null); +} + +test "plumb: dispose: no rule and no dst, a start, the web port, a port no rule names" { + const p = try Pardes.init(testing.allocator, .{ .cols = 80, .rows = 24 }); + defer p.deinit(); + _ = try p.setTestFile("x\n"); + try testing.expect(apply(p, false, "plumb/rules", "include basic\n\ntype\tis\tmsg\nplumb\tstart\tMsg $data\n\ntype\tis\tnone\nplumb\tto\tnobody\n\ntype\tis\tclient\nplumb\tclient\tMsg x\n\n") == null); + try testing.expectEqualStrings(e_no_port, send(p, null, .{ .type = "text", .data = "no such thing" }, null).refused); + // A start of a builtin runs it in place. + try testing.expect(send(p, null, .{ .type = "msg", .data = "hello" }, null) == .done); + const pane = p.panes[p.view().active].?; + try testing.expectEqualStrings("hello", pane.msg[0..pane.msg_len]); + try testing.expectEqualStrings(e_client, send(p, null, .{ .type = "client" }, null).refused); + try testing.expectEqualStrings(e_no_start, send(p, null, .{ .type = "none" }, null).refused); + try testing.expectEqualStrings(e_no_start, send(p, null, .{ .dst = "nobody", .type = "x" }, null).refused); + // A port no rule names goes nowhere, said nothing (fsys.c's dispose). + try testing.expect(send(p, null, .{ .dst = "elsewhere", .data = "x" }, null) == .done); + // A URL to the web port: the host's opener. + while (p.nextEffect()) |_| {} + try testing.expect(send(p, null, .{ .type = "text", .data = "https://ziglang.org" }, null) == .done); + var linked = false; + while (p.nextEffect()) |e| switch (e) { + .open_link => |u| { + try testing.expectEqualStrings("https://ziglang.org", u.slice()); + linked = true; + }, + else => {}, + }; + try testing.expect(linked); +} + +test "plumb: rules written replace or add, a refusal keeps them as they were, and a dump keeps them" { + const p = try Pardes.init(testing.allocator, .{ .cols = 80, .rows = 24 }); + defer p.deinit(); + // Every session starts with the defaults. + try testing.expect(std.mem.indexOf(u8, inForce(p), "plumb\tto\tweb") != null); + try testing.expect(!p.plumber.written); + try testing.expect(apply(p, false, "plumb/rules", "type is a\nplumb to edit\n") == null); + try testing.expect(apply(p, true, "plumb/rules", "type is b\nplumb to edit\n") == null); + try testing.expectEqualStrings("type\tis\ta\nplumb\tto\tedit\n\ntype\tis\tb\nplumb\tto\tedit\n\n", p.plumber.text.items); + try testing.expectEqualStrings("plumb/rules:1: unknown verb isnt", apply(p, true, "plumb/rules", "type isnt c\n").?); + try testing.expectEqualStrings("type\tis\ta\nplumb\tto\tedit\n\ntype\tis\tb\nplumb\tto\tedit\n\n", p.plumber.text.items); + try pardes.dump.dumpState(p); + const restored = try pardes.dump.restore(p, p.dump_out.?, "/tmp/pardes.dump.zon"); + defer restored.deinit(); + try testing.expectEqualStrings(p.plumber.text.items, restored.plumber.text.items); + try testing.expect(restored.plumber.written); +} + +test "plumb: plan9port's basic parses, its ¡- classes UTF-8's bytes and its submatch rule sets left out, and its rules match" { + var arena: std.heap.ArenaAllocator = .init(testing.allocator); + defer arena.deinit(); + // plan9port's plumb/basic and fileaddr; `¡-` is `\x80-\xf4`, the bytes + // of UTF-8's multi-byte runes (a run of them is whole runes: UTF-8 is + // self-synchronising), and the rule sets that need `$1`-`$5` are gone. + const p9p = + \\addrelem='((#?[0-9]+)|(/[A-Za-z0-9_\^]+/?)|[.$])' + \\addr=:($addrelem([,;+\-]$addrelem)*) + \\ + \\plumb to seemail + \\plumb to showmail + \\ + \\type is text + \\data matches '(https?|ftp|file|gopher|mailto|news|nntp|telnet|wais|prospero)://[a-zA-Z0-9_@\-]+([.:][a-zA-Z0-9_@\-]+)*/?[a-zA-Z0-9_?,%#~&/\-+=]+([:.][a-zA-Z0-9_?,%#~&/\-+=]+)*' + \\plumb to web + \\plumb start web $0 + \\ + \\type is text + \\data matches '[a-zA-Z\x80-\xf40-9_\-./]+' + \\data matches '([a-zA-Z\x80-\xf40-9_\-./]+)\.(doc|rtf)' + \\arg isfile $0 + \\plumb to msword + \\plumb start wdoc2txt $file + \\ + \\type is text + \\dst is msword + \\plumb to msword + \\plumb start wdoc2txt $file + \\ + \\type is text + \\data matches '[a-zA-Z\x80-\xf40-9_\-./@]+' + \\data matches '([a-zA-Z\x80-\xf40-9_\-./@]+)\.(jpe?g|JPE?G|gif|GIF|tiff?|TIFF?|ppm|bit|png|PNG)' + \\arg isfile $0 + \\plumb to image + \\plumb start 9 page $file + \\ + \\type is text + \\data matches '[a-zA-Z\x80-\xf40-9_\-./@]+' + \\data matches '([a-zA-Z\x80-\xf40-9_\-./@]+)\.(ps|PS|eps|EPS|pdf|PDF|dvi|DVI)' + \\arg isfile $0 + \\plumb to postscript + \\plumb start 9 page $file + \\ + \\data matches '[a-zA-Z\x80-\xf40-9_\-./@]+' + \\data matches '([a-zA-Z\x80-\xf40-9_\-./@]+)\.([Ss][XxTt][CcDdIiGgMmWw]|[Dd][Oo][Cc]|[Xx][Ll][Ss]|[Pp][Pp][Tt])' + \\arg isfile $0 + \\plumb to openoffice + \\plumb start openoffice $file + \\ + \\type is text + \\data matches '[a-zA-Z\x80-\xf40-9_\-./]+' + \\data matches '/mail/fs/[a-zA-Z\x80-\xf40-9/]+/[0-9]+' + \\plumb to showmail + \\plumb start window -r 4 120 750 600 upas/nedmail -s $0 + \\ + \\type is text + \\data matches '[a-zA-Z0-9_+.\-]+@[a-zA-Z0-9_+.\-]*' + \\plumb to sendmail + \\plumb start wmail $0 + \\ + \\dst is image + \\arg isfile $data + \\plumb to image + \\plumb start 9 page $data + \\ + \\dst is postscript + \\arg isfile $data + \\plumb start 9 page $data + \\ + ; + const printed = try reread(arena.allocator(), p9p); + try testing.expect(std.mem.startsWith(u8, printed, "addrelem='((#?[0-9]+)|(/[A-Za-z0-9_\\^]+/?)|[.$])'\n\naddr=:($addrelem([,;+\\-]$addrelem)*)\n\nplumb\tto\tseemail\n")); + try testing.expectEqualStrings(printed, try reread(arena.allocator(), printed)); + const p = try Pardes.init(testing.allocator, .{ .cols = 80, .rows = 24 }); + defer p.deinit(); + // Clicked in a line: the URL's run, the mail address's, and the + // faces' path, whole runes of a name that is not ASCII. + const url = try tryRules(p, p9p, .{ .type = "text", .attr = "click=10", .data = "see https://9fans.github.io/plan9port/ now" }); + try testing.expectEqual(@as(?usize, 0), url.set); + try testing.expectEqualStrings("https://9fans.github.io/plan9port/", url.m.data); + try testing.expectEqualStrings("web", url.m.dst); + const mail = try tryRules(p, p9p, .{ .type = "text", .attr = "click=12", .data = "write to [email protected]." }); + try testing.expectEqualStrings("sendmail", mail.m.dst); + try testing.expectEqualStrings("[email protected].", mail.m.data); + const face = try tryRules(p, p9p, .{ .type = "text", .attr = "click=3", .data = "x /mail/fs/café/12 y" }); + try testing.expectEqualStrings("showmail", face.m.dst); + try testing.expectEqualStrings("/mail/fs/café/12", face.m.data); + // An image named in UTF-8, and Pike's horse.gift, by the image set's + // two patterns alone. + const pics = "data matches '[a-zA-Z\\x80-\\xf40-9_\\-./@]+'\ndata matches '([a-zA-Z\\x80-\\xf40-9_\\-./@]+)\\.(jpe?g|gif|png)'\nplumb to image\n"; + try testing.expectEqualStrings("Ångström.png", (try tryRules(p, pics, .{ .attr = "click=2", .data = "Ångström.png" })).m.data); + try testing.expect((try tryRules(p, pics, .{ .attr = "click=2", .data = "horse.gift" })).set == null); + // The rune range as written is refused, in regexp.zig's words. + try testing.expectEqualStrings("t:1: bad regular expression: a range of runes wider than 256 in [...] is not supported", try reread(arena.allocator(), "data matches '[a-zA-Z¡-0-9_\\-./]+'\nplumb to edit\n")); +} + +test "plumb: the Plumb word opens the plumbing file, include basic until one is saved; saved, or read at boot, its rules are in force, a bad one said with its line" { + if (!fs.platform_has_fs) return; + var tmp = testing.tmpDir(.{}); + defer tmp.cleanup(); + var dir_buf: [4096]u8 = undefined; + const root = dir_buf[0..try tmp.dir.realPath(testing.io, &dir_buf)]; + const p = try Pardes.init(testing.allocator, .{ .cols = 100, .rows = 30, .config_dir = root }); + defer p.deinit(); + _ = try p.setTestFile("x\n"); + var path_buf: [4096]u8 = undefined; + const path = filePath(p, &path_buf).?; + try testing.expect(std.mem.endsWith(u8, path, "/plumbing")); + // Not there yet: a pane of its name holding `include basic`. + try testing.expect(p.executeBuiltinLine(0, "Plumb")); + const made = p.panes[p.view().active].?; + try testing.expectEqualStrings(path, made.file.?.path); + try testing.expectEqualStrings("include basic\n", made.file.?.content); + // A rule after the word is refused, in words. + try testing.expect(p.executeBuiltinLine(0, "Plumb suffix .svg to image")); + const first = p.panes[0].?; + try testing.expectEqualStrings(e_word, first.msg[0..first.msg_len]); + // Saved: its rules, or why not, the rules as they were. + saved(p, 0, path, "type is text\ndata matches 'x.*'\nplumb to web\n"); + try testing.expectEqualStrings("type\tis\ttext\ndata\tmatches\t'x.*'\nplumb\tto\tweb\n\n", inForce(p)); + saved(p, 0, path, "type is text\ndata isnt x\nplumb to web\n"); + try testing.expectEqualStrings("plumbing:2: unknown verb isnt", first.msg[0..first.msg_len]); + try testing.expectEqualStrings("type\tis\ttext\ndata\tmatches\t'x.*'\nplumb\tto\tweb\n\n", inForce(p)); + // Another file saved is no plumbing. + saved(p, 0, "/elsewhere/plumbing", "type is text\nplumb to edit\n"); + try testing.expect(std.mem.indexOf(u8, inForce(p), "'x.*'") != null); + // At boot: the file's rules. + try tmp.dir.writeFile(testing.io, .{ .sub_path = "plumbing", .data = "type is text\ndata matches 'y.*'\nplumb to web\n" }); + const q = try Pardes.init(testing.allocator, .{ .cols = 100, .rows = 30, .config_dir = root }); + defer q.deinit(); + try testing.expectEqualStrings("type\tis\ttext\ndata\tmatches\t'y.*'\nplumb\tto\tweb\n\n", inForce(q)); +} + +test "plumb: a diff paged is sent to edit, stacked in a +Diff by the default rule; without it the +Pager stays, and a reader of plumb/edit gets it" { + const p = try Pardes.init(testing.allocator, .{ .tty_only = true }); + defer p.deinit(); + const page = "commit 0123456789abcdef0123456789abcdef01234567\ndiff --git a/x b/x\n--- a/x\n+++ b/x\n@@ -1 +1 @@\n-old\n+new\n"; + const Page = struct { + fn fill(pp: *Pardes, text: []const u8) !usize { + const id = try pardes.panes.Output.openPager(pp, 0, "/pardes-plumb-page"); + var held: std.ArrayList(u8) = .empty; + defer held.deinit(pp.gpa); + try held.appendSlice(pp.gpa, text); + try @import("ninep/ctl.zig").fillPager(pp, pp.panes[id].?.serial, &held); + return id; + } + fn diffs(pp: *Pardes) usize { + var n: usize = 0; + for (pp.panes) |slot| if (slot) |pn| if (pn.file) |f| { + n += @intFromBool(std.mem.indexOf(u8, f.path, "/+Diff") != null); + }; + return n; + } + }; + // The defaults: the +Pager stacked into a +Diff, and gone. + const stacked = try Page.fill(p, page); + try testing.expect(p.panes[stacked] == null or !std.mem.endsWith(u8, p.panes[stacked].?.file.?.path, "+Pager")); + try testing.expectEqual(@as(usize, 1), Page.diffs(p)); + // Text that is no diff is not sent: its +Pager stays, as ever. + const plain = try Page.fill(p, "just text\n"); + try testing.expect(std.mem.endsWith(u8, p.panes[plain].?.file.?.path, "+Pager")); + // The paged-diff rule taken out: the edit port shows the data where + // it is, and the +Pager stays as text. + try testing.expect(apply(p, false, "plumb/rules", "type is text\narg isfile $data\nplumb to edit\n") == null); + const kept = try Page.fill(p, page); + try testing.expect(std.mem.endsWith(u8, p.panes[kept].?.file.?.path, "+Pager")); + try testing.expectEqualStrings(page, p.panes[kept].?.file.?.content); + try testing.expectEqual(@as(usize, 1), Page.diffs(p)); + // From another sender: shown in a pane of its filename's, clean, and + // with showdiff stacked. + try testing.expect(send(p, 0, .{ .src = "test", .dst = "edit", .type = "text", .attr = "action=showdata filename=/elsewhere/notes", .data = "a note\n" }, null) == .done); + const shown = p.panes[p.view().active].?; + try testing.expectEqualStrings("/elsewhere/notes", shown.file.?.path); + try testing.expectEqualStrings("a note\n", shown.file.?.content); + try testing.expectEqual(shown.file.?.revision, shown.file.?.saved_revision); + try testing.expect(send(p, 0, .{ .src = "test", .dst = "edit", .type = "text/x-diff", .attr = "action=showdiff filename=/elsewhere/change", .data = page }, null) == .done); + try testing.expectEqual(@as(usize, 2), Page.diffs(p)); +} diff --git a/src/Query.zig b/src/Query.zig index caf64d54..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 }; @@ -859,19 +859,14 @@ fn setRows(p: *Pardes, rp: *Pane, out: *std.ArrayList(u8), rows: *std.ArrayList( if (std.mem.eql(u8, content, f.content)) { // Same text: the metadata alone, no undo step, no syntax pass. p.gpa.free(content); - if (locations.equalRows(f.location_rows, meta)) { - locations.freeRows(p.gpa, meta); - } else { - locations.freeRows(p.gpa, f.location_rows); - f.location_rows = meta; - dropHighlights(p, f); - } } else { File.setContent(p, f, content); - locations.freeRows(p.gpa, f.location_rows); - f.location_rows = meta; f.saved_revision = f.revision; } + File.setRows(p, f, meta) catch |err| { + locations.freeRows(p.gpa, meta); + if (p.paneBySerial(rp.serial)) |id| p.reportError(id, "rows", err); + }; if (f.pager_spans.len > 0) p.gpa.free(f.pager_spans); f.pager_spans = &.{}; // The cursor stays where it was typing; on a row that went, the last. @@ -996,24 +991,10 @@ pub fn recolor(p: *Pardes) void { fresh = rows; @memcpy(rows[i].colors[0..got.len], got); } - if (fresh) |rows| { - locations.freeRows(p.gpa, f.location_rows); - f.location_rows = rows; - dropHighlights(p, f); - } + if (fresh) |rows| File.setRows(p, f, rows) catch locations.freeRows(p.gpa, rows); } } -/// The pane's painted colours let go, so the next frame paints them from -/// its rows again: with its text the same, a frame would keep the old ones -/// (refreshHighlights keeps a painting that covers the view). -fn dropHighlights(p: *Pardes, f: *File.State) void { - if (f.highlights.len > 0) p.tree_sitter_gpa.free(f.highlights); - f.highlights = &.{}; - f.highlight_start = 0; - f.syntax_dirty = true; -} - /// The path a row of pane `tp`'s text says: its file's, or `@pN` for a /// text that is no file (a list, a scratch). fn addressOf(arena: std.mem.Allocator, tp: *const Pane) []const u8 { @@ -1910,8 +1891,10 @@ pub fn cancel(p: *Pardes, id: usize) void { } const f = &rp.file.?; File.setContent(p, f, s.content); - locations.freeRows(p.gpa, f.location_rows); - f.location_rows = s.rows; + File.setRows(p, f, s.rows) catch |err| { + locations.freeRows(p.gpa, s.rows); + p.reportError(id, "query", err); + }; p.gpa.free(q.asked); q.asked = s.asked; q.source = s.source; @@ -2745,3 +2728,30 @@ test "a row's address is the shortest path a Look from the query pane resolves: } else return error.TestUnexpectedResult; } } + +test "a query row's address reaches every way a look arrives: an empty look written back to event and the whole row written to look, as the mouse on it" { + if (!filesystem.platform_has_fs) return; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 120, .rows = 48 }); + defer p.deinit(); + const a = try testFileIn(p, &tmp, "a.txt", "zero\none needle\ntwo\nthree needle here\n"); + leader(p, "fg"); + typeKeys(p, "needle"); + settle(p); + const qid = queryPane(p).?; + const qp = p.panes[qid].?; + const f = &qp.file.?; + const at = std.mem.indexOf(u8, f.content, "\na.txt:4:7").? + 1; + const line = f.content[at..std.mem.indexOfScalarPos(u8, f.content, at, '\n').?]; + // an empty look written back, on the address: the row's address whole, + // its path as the row keeps it + try std.testing.expect(std.mem.endsWith(u8, @import("ninep/events.zig").expandAt(p, qp, f.content, at + 3, true, true), "/a.txt:4:7")); + // on its code: the word there + try std.testing.expectEqualStrings("three", @import("ninep/events.zig").expandAt(p, qp, f.content, at + line.len - "three needle here".len + 1, true, true)); + // the whole row written to the pane's look: the place + a.body.cur_row = 0; + const tree = @import("ninep/tree.zig"); + try std.testing.expectEqual(tree.Status.ok, @import("ninep/testing.zig").wr(p, tree.Node.of(qp.serial, .look), line).reply.status); + try std.testing.expectEqual(@as(i32, 3), a.body.cur_row); +} diff --git a/src/Term.zig b/src/Term.zig new file mode 100644 index 00000000..cf94c6d5 --- /dev/null +++ b/src/Term.zig @@ -0,0 +1,497 @@ +//! The terminal as the core sees it (docs/next-terminal.md, Phase 1): the +//! entries of the terminal module (src/term/, its own module: ghostty-vt, +//! wuffs and zstbi are its, not the core's) and the plain records they take +//! and give (src/plain/term.zig). A terminal pane holds a `*State` the core +//! never looks into: what it knows of one it is told here, as numbers, +//! bytes, text and cells. A core built without the module (a test +//! configuration: core-test) has `ops` null, and no terminal at all. +const std = @import("std"); +const builtin = @import("builtin"); +const plain = @import("plain"); +const walk = @import("walk.zig"); +const tape = @import("tape.zig"); +const dump = @import("dump.zig"); +const File = @import("File.zig"); +const iface = plain.term; + +/// The terminal module's entries; null in a core built without it. +pub const ops: ?*const iface.Ops = if (@import("term_options").terminal) &@import("term").ops else null; + +/// What a core without a terminal says, once, where one would have been. +pub const none = "no terminal in this build"; + +pub const Grid = iface.Grid; +pub const Told = iface.Told; +pub const Modes = iface.Modes; +pub const Prompt = iface.Prompt; +pub const CommandOutput = iface.CommandOutput; +pub const Rows = iface.Rows; +pub const Moves = iface.Moves; +pub const MouseMods = iface.MouseMods; +pub const MouseButton = iface.MouseButton; +pub const MouseAction = iface.MouseAction; +pub const Page = iface.Page; +pub const Span = iface.Span; +pub const Ink = iface.Ink; +pub const FilterPalette = iface.FilterPalette; +pub const Filter = iface.Filter; +pub const Painted = iface.Painted; +pub const PaintedRow = iface.PaintedRow; +pub const ImagesAt = iface.ImagesAt; +pub const EchoCell = iface.EchoCell; +pub const Peer = iface.Peer; +pub const Applied = iface.Applied; +pub const Encoder = iface.Encoder; +pub const Track = iface.Track; +pub const Replica = iface.Replica; + +fn the() *const iface.Ops { + return ops orelse unreachable; // no State, Encoder or Replica is made without it +} + +/// A terminal pane's terminal: the module's handle, and the walk's hooks +/// (src/walk.zig) for it: the replay digest, and the dump, which keeps it +/// as it always has (`Parts` by name, then ghostty's snapshot). +pub const State = struct { + impl: *iface.State, + + /// The emulator as its program has made it, for the replay digest. + /// Under screen-state terminals the emulator is the authority's, and a + /// replica's is what the last delta made it: compared as screens + /// (test/replicas.zig), not step by step. + pub fn digest(s: *const State, h: *walk.Hasher) void { + if (tape.screenState()) return; + s.digestScreen(h, true); + } + + /// `view`: where its view is too (a replica's speculation may move it). + pub fn digestScreen(s: *const State, h: *walk.Hasher, view: bool) void { + the().digest(s.impl, h, view); + } + + pub fn dumpWrite(s: *const State, gpa: std.mem.Allocator, w: *std.Io.Writer) !void { + const parts = the().parts(s.impl); + const bytes = try walk.save(iface.Parts, gpa, &parts); + defer gpa.free(bytes); + try w.writeAll(std.mem.asBytes(&@as(u64, bytes.len))); + try w.writeAll(bytes); + try the().snapshot(s.impl, gpa, w, dump.slim_terminals); + } + + /// What `dumpRead` made, freed: a load that failed after it. + pub fn dumpFree(s: *State, gpa: std.mem.Allocator) void { + the().close(s.impl, gpa); + } + + pub fn dumpRead(out: *State, gpa: std.mem.Allocator, bytes: []const u8) !void { + const o = ops orelse return error.NoTerminal; + if (bytes.len < 8) return error.EndOfDump; + const n = std.math.cast(usize, std.mem.bytesToValue(u64, bytes[0..8])) orelse return error.EndOfDump; + if (bytes.len - 8 < n) return error.EndOfDump; + var arena: std.heap.ArenaAllocator = .init(gpa); + defer arena.deinit(); + const parts = try walk.load(iface.Parts, arena.allocator(), bytes[8..][0..n], null); + out.* = .{ .impl = try o.load(gpa, bytes[8 + n ..], &parts) }; + } +}; + +/// The module's own state behind a handle: for a test that reads the +/// emulator itself, in a core with the module (a test in one without skips +/// before it gets here: `ops == null` is known at compile time). +pub fn emulatorOf(s: *State) *@import("term").terminal.State { + return @ptrCast(@alignCast(s.impl)); +} + +// ---- lifecycle ---- + +/// A new terminal, `cols` by `rows`, allocated with `gpa` (its own from +/// then on). Refused in a core without one: `error.NoTerminal`, which a +/// word reports as `none` says it. +pub fn open(gpa: std.mem.Allocator, cols: u16, rows: u16) !*State { + const o = ops orelse return error.NoTerminal; + const s = try gpa.create(State); + errdefer gpa.destroy(s); + s.* = .{ .impl = try o.open(gpa, cols, rows) }; + return s; +} + +/// It and what it holds, freed; the kitty images' caches were `gpa`'s. +pub fn close(s: *State, gpa: std.mem.Allocator) void { + const own = the().gpa(s.impl); + the().close(s.impl, gpa); + own.destroy(s); +} + +/// 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 fn due(s: *const State) ?u64 { + return the().due(s.impl); +} + +/// Loaded from a dump without its shell: its program's modes reset, its +/// history marked off from what the next shell prints. +pub fn revive(s: *State) void { + the().revive(s.impl); +} + +/// The PNG resize workers kitty images are decoded with, started and +/// stopped with the host. +pub fn start(gpa: std.mem.Allocator) void { + if (ops) |o| o.start(gpa); +} + +pub fn stop() void { + if (ops) |o| o.stop(); +} + +// ---- output and view ---- + +/// One read of its program's output (`Told` says where the tracked rows +/// went). +pub fn feed(s: *State, bytes: []const u8, tracked: []const i32, rows: []i32, erased: []bool) Told { + return the().feed(s.impl, bytes, tracked, rows, erased); +} + +/// Where the view and the cursor are; all zero without a terminal. +pub fn grid(s: ?*const State) Grid { + const o = ops orelse return .{}; + return o.grid(if (s) |state| state.impl else null); +} + +/// Its view to a row of its history, or onto its output (null). +pub fn viewTo(s: *State, at: ?usize) void { + the().viewTo(s.impl, at); +} + +/// Its view moved by a number of rows (negative scrolls back). +pub fn scroll(s: *State, delta: i32) void { + the().scroll(s.impl, delta); +} + +/// Its view back onto its output. +pub fn follow(s: *State) void { + the().follow(s.impl); +} + +/// Its grid reflowed, now or when `resizeDeferred` makes it. +pub fn resize(s: *State, cols: u16, rows: u16, later: bool) void { + the().resize(s.impl, cols, rows, later); +} + +pub fn resizeDeferred(s: *State) bool { + return the().resizeDeferred(s.impl); +} + +/// Its cells' size in pixels (kitty graphics, CSI 14/16 t). +pub fn cellPixels(s: *State, w: u32, h: u32) void { + the().cellPixels(s.impl, w, h); +} + +/// What it answered its program since the last call, to be written to its +/// pty. +pub fn replies(s: *State) []const u8 { + return the().replies(s.impl); +} + +// ---- input ---- + +/// One key for its program, as the program's keyboard protocol and modes +/// ask for it, written out. +pub fn key(s: *State, k: plain.Key, out: *std.Io.Writer) !void { + return the().key(s.impl, k, out); +} + +/// 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 fn mouse(s: *State, buf: *[64]u8, action: MouseAction, button: ?MouseButton, mods: MouseMods, col: i32, row: i32, any_pressed: bool) []const u8 { + return the().mouse(s.impl, buf, action, button, mods, col, row, any_pressed); +} + +/// A wheel turn for its program; null when the wheel is not the program's. +pub fn wheel(s: *State, buf: *[64]u8, turn: MouseButton, col: u16, row: u16, mods: MouseMods) ?[]const u8 { + return the().wheel(s.impl, buf, turn, col, row, mods); +} + +/// A paste as xterm makes one: three parts, the text between the brackets +/// when the program set 2004. +pub fn paste(s: ?*const State, text: []u8) [3][]const u8 { + const o = ops orelse return .{ "", text, "" }; + return o.paste(if (s) |state| state.impl else null, text); +} + +/// The modes its program set that the core decides by. +pub fn modes(s: ?*const State) Modes { + const o = ops orelse return .{}; + return o.modes(if (s) |state| state.impl else null); +} + +/// How far left or right a click on the prompt line moves the shell's +/// cursor, at the prompt the cursor is at. +pub fn promptMoves(s: *State, row: i32, col: i32) ?Moves { + return the().promptMoves(s.impl, row, col); +} + +// ---- prompt and commands ---- + +/// Where its shell is in its command cycle; all zero without a terminal. +pub fn prompt(s: ?*State) Prompt { + const o = ops orelse return .{}; + return o.prompt(if (s) |state| state.impl else null); +} + +/// What the newest finished command printed, read from at most so many +/// rows above its end. +pub fn commandOutput(s: ?*State, gpa: std.mem.Allocator, max_rows: usize) !CommandOutput { + const o = ops orelse return .{ .text = try gpa.dupeSentinel(u8, "", 0), .whole = true }; + return o.commandOutput(if (s) |state| state.impl else null, gpa, max_rows); +} + +/// The shell exited in the middle of a command: its output ends at the +/// cursor. +pub fn endOutputHere(s: *State) void { + the().endOutputHere(s.impl); +} + +// ---- 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; empty without a terminal. +pub fn scrollback(s: ?*State, gpa: std.mem.Allocator) ![]const u8 { + const o = ops orelse return gpa.dupe(u8, ""); + return o.scrollback(if (s) |state| state.impl else null, gpa); +} + +/// How long `scrollback` would be, counted without keeping it. +pub fn scrollbackLen(s: ?*State) usize { + const o = ops orelse return 0; + return o.scrollbackLen(if (s) |state| state.impl else null); +} + +/// Its rows from the top of its history as text, a prompt's own cells cut +/// off (`Rows`). +pub fn textRows(s: *State, alloc: std.mem.Allocator, scratch: std.mem.Allocator) iface.TextError!Rows { + return the().textRows(s.impl, alloc, scratch); +} + +/// The rows its view shows as text, prompts cut off or not. +pub fn viewport(s: *State, arena: std.mem.Allocator, cut: bool) iface.TextError![]const []const u8 { + return the().viewport(s.impl, arena, cut); +} + +/// Its rows `first` and the `count` after it as text, prompts cut off (the +/// edit copy's rows, as they were). +pub fn editRows(s: *State, arena: std.mem.Allocator, first: usize, count: usize) ![]const []const u8 { + return the().editRows(s.impl, arena, first, count); +} + +/// How many bytes of one of its rows, as `viewport` and `textRows` give it +/// uncut, are the prompt it starts with: the prompt's columns, measured in +/// the row's text as the core measures a display. +pub fn promptPrefix(s: ?*State, row: i32, raw: []const u8) usize { + const state = s orelse return 0; + if (row < 0) return 0; + const cut = the().promptCut(state.impl, row) orelse return 0; + return switch (cut) { + .keep => 0, + .blank => raw.len, + .cut => |cols| @min(raw.len, File.rawAtDisplay(raw, cols)), + }; +} + +/// A step read its rows: its replicas must hold them for the step's +/// replay. +pub fn markRead(s: *State) void { + the().markRead(s.impl); +} + +/// What a predicted echo reads of a cell of its active area. +pub fn echoCell(s: *const State, x: u16, y: u16) ?EchoCell { + return the().echoCell(s.impl, x, y); +} + +// ---- 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, +/// every other control dropped. The emulator's own parse, so a +Pager +/// pages what a terminal pane would print. Without a terminal the bytes +/// are paged as they are: plain text, no colours (nothing in the core +/// parses an escape). +pub fn page(gpa: std.mem.Allocator, raw: []const u8) error{OutOfMemory}!Page { + if (ops) |o| return o.page(gpa, raw); + const text = try gpa.dupe(u8, raw); + errdefer gpa.free(text); + return .{ .text = text, .spans = try gpa.alloc(Span, 0) }; +} + +/// The filter a +Pager's spans are drawn through, and a span's colour +/// through it. +pub fn filter(ink: *const Ink, palette: *FilterPalette) Filter { + return the().filter(ink, palette); +} + +pub fn spanColor(f: *Filter, color: plain.Color, is_bg: bool) plain.Color { + return the().spanColor(f, color, is_bg); +} + +// ---- draw ---- +// +// Plain data both ways: the core hands the theme's colours (`Ink`) and a +// buffer, and is given its view's cells (`Painted`, `PaintedRow`) and its +// images as placements; which of the body's rows they stand under is the +// core's (src/ansi.zig). + +/// Its view's rows as cells in the theme's colours, through the theme's +/// filter when the pane has it on. +pub fn paint(s: *State, ink: *const Ink, palette: *FilterPalette, filtered: bool, cols: u16, cells: []Painted, rows: []PaintedRow) void { + the().paint(s.impl, ink, palette, filtered, cols, cells, rows); +} + +/// Its kitty graphics over the body's rows, as placements. +pub fn images(s: *State, gpa: std.mem.Allocator, at: ImagesAt, out: *std.ArrayList(plain.Placement), frame: []plain.Cell, frame_cols: u16) void { + the().images(s.impl, gpa, at, out, frame, frame_cols); +} + +/// The Petscii builtin on it: its kitty graphics as glyph art, or back to +/// pixels; null for none. +pub fn petscii(s: ?*const State) ?bool { + const o = ops orelse return null; + return o.petscii(if (s) |state| state.impl else null); +} + +pub fn togglePetscii(s: *State) void { + the().togglePetscii(s.impl); +} + +/// Whether the screen showing holds any kitty graphics image. +pub fn hasImages(s: ?*const State) bool { + const o = ops orelse return false; + return o.hasImages(if (s) |state| state.impl else null); +} + +// ---- its replicas ---- + +pub fn encoder(gpa: std.mem.Allocator) !*Encoder { + return the().encoder(gpa); +} + +pub fn encoderFree(e: *Encoder) void { + the().encoderFree(e); +} + +pub fn track(gpa: std.mem.Allocator) !*Track { + return the().track(gpa); +} + +/// A peer's track of it let go (`s` null: it is gone). +pub fn untrack(t: *Track, gpa: std.mem.Allocator, s: ?*State) void { + the().untrack(t, gpa, if (s) |state| state.impl else null); +} + +/// What a peer is owed of it, a delta against what the peer was sent. +pub fn encode(s: *State, e: *Encoder, t: *Track, peer: *Peer, out: *std.Io.Writer) !bool { + return the().encode(s.impl, e, t, peer, out); +} + +/// Rows of it a replica holds as holes. +pub fn encodeRows(s: *State, e: *Encoder, t: *Track, lo: u64, hi: u64, out: *std.Io.Writer) !void { + return the().encodeRows(s.impl, e, t, lo, hi, out); +} + +/// Whether a step read its rows since `clearRead`. +pub fn wasRead(s: *const State) bool { + return the().wasRead(s.impl); +} + +pub fn clearRead(s: *State) void { + the().clearRead(s.impl); +} + +/// A replica's side of one terminal: made, freed, where its active area +/// begins, and the history rows it does not hold. +pub fn replica(gpa: std.mem.Allocator) !*Replica { + return the().replica(gpa); +} + +pub fn replicaFree(r: *Replica, gpa: std.mem.Allocator) void { + the().replicaFree(r, gpa); +} + +pub fn replicaTop(r: *const Replica) u64 { + return the().replicaTop(r); +} + +pub fn missing(r: *const Replica, lo: u64, hi: u64, out: *std.ArrayList([2]u64), gpa: std.mem.Allocator) !void { + return the().missing(r, lo, hi, out, gpa); +} + +/// A replica's side: a delta applied, rows applied, the rows its view +/// shows, rows blank until they come. +pub fn apply(s: *State, r: *Replica, bytes: []const u8) !Applied { + return the().apply(s.impl, r, bytes); +} + +pub fn applyRows(s: *State, r: *Replica, bytes: []const u8) !void { + return the().applyRows(s.impl, r, bytes); +} + +pub fn shown(s: *State, r: *const Replica) [2]u64 { + return the().shown(s.impl, r); +} + +pub fn blank(s: *State, r: *const Replica, lo: u64, hi: u64) void { + the().blank(s.impl, r, lo, hi); +} + +pub fn dumpScreen(s: *State, w: *std.Io.Writer) !void { + return the().dumpScreen(s.impl, w); +} + +// ---- a core without a terminal (core-test's) ---- + +test "a core without a terminal boots to a scratch pane" { + if (ops != null) return error.SkipZigTest; + const pardes = @import("pardes.zig"); + for ([_]pardes.Options{ .{}, .{ .tty_only = true }, .{ .boot = .tty }, .{ .shells = 3 } }) |opts| { + const p = try pardes.Pardes.init(std.testing.allocator, opts); + defer p.deinit(); + const pane = p.panes[0].?; + try std.testing.expect(pane.terminal == null); + try std.testing.expect(pane.file != null); + try std.testing.expectEqual(null, p.panes[1]); + } +} + +test "a core without a terminal: Term refuses in words, and no line is typed at a shell" { + if (ops != null) return error.SkipZigTest; + const pardes = @import("pardes.zig"); + const p = try pardes.Pardes.init(std.testing.allocator, .{ .file = "mise.toml" }); + defer p.deinit(); + try std.testing.expectError(error.NoTerminal, p.newShell(p.freeSlot().?, "")); + try std.testing.expect(p.executeBuiltinLine(0, "Term")); + const pane = p.panes[0].?; + try std.testing.expectEqualStrings("Term: " ++ none, pane.msg[0..pane.msg_len]); + // A line no shell can take runs in a command pane, a terminal: refused. + try std.testing.expectEqual(null, pardes.exec.execute(p, 0, "make")); + try std.testing.expectEqualStrings("exec: " ++ none, pane.msg[0..pane.msg_len]); + for (p.panes, 0..) |slot, id| if (slot) |_| try std.testing.expect(!pardes.exec.takesCommandLine(p, id)); +} + +test "a core without a terminal pages a program's output as plain text" { + if (ops != null) return error.SkipZigTest; + const pardes = @import("pardes.zig"); + const raw = "one\n\x1b[31mtwo\x1b[0m\n"; + const paged = try page(std.testing.allocator, raw); + defer paged.deinit(std.testing.allocator); + try std.testing.expectEqualStrings(raw, paged.text); + try std.testing.expectEqual(0, paged.spans.len); + const p = try pardes.Pardes.init(std.testing.allocator, .{ .stdin_text = "one\ntwo\n" }); + defer p.deinit(); + for (p.panes) |slot| if (slot) |pane| if (pane.file) |f| if (f.pager) { + try std.testing.expectEqualStrings("one\ntwo\n", f.content); + try std.testing.expectEqual(0, f.pager_spans.len); + return; + }; + return error.NoPager; +} diff --git a/src/Text.zig b/src/Text.zig index 43a515e1..271269ab 100644 --- a/src/Text.zig +++ b/src/Text.zig @@ -14,7 +14,6 @@ const config = @import("config.zig"); const memory = @import("memory.zig"); const Pane = panes.Pane; const File = panes.File; -const terminal = panes.terminal; const Text = @This(); pub const Mode = enum { normal, insert, tty }; @@ -30,6 +29,25 @@ pub const CharSel = struct { explicit: bool = false, }; +/// The owned text standing in for `rows` live terminal rows, beginning at +/// absolute surface row `row`. The emulator grid remains untouched underneath. +pub const EditBuffer = struct { + row: i32 = 0, + rows: i32 = 1, + text: []u8 = &.{}, +}; + +/// One whole-state terminal edit boundary. Null means the pane has not yet +/// materialized an edit buffer; non-null snapshots own their text. +pub const Snapshot = struct { + ovl: ?EditBuffer, + cur_row: i32, + cur_col: i32, + vsel: CharSel, +}; + +pub const history_max = 64; + pub const max_selections = memory.limits.selections; pub const SelRange = struct { @@ -80,9 +98,9 @@ normal: modal.Normal.State = .{}, /// last f/F/t/T motion, for Alt-. repeat find_op: ?modal.Normal.Find = null, find_ch: u21 = 0, -ed_undo: [terminal.history_max]terminal.Snapshot = undefined, +ed_undo: [history_max]Snapshot = undefined, ed_undo_len: usize = 0, -ed_redo: [terminal.history_max]terminal.Snapshot = undefined, +ed_redo: [history_max]Snapshot = undefined, ed_redo_len: usize = 0, /// Set when an edit would have changed characters this text does not own /// (a tag's computed prefix) and was refused; the key that tried it puts @@ -604,10 +622,10 @@ fn unchanged(gpa: std.mem.Allocator, entries: []const Entry, text: []const u8) e return std.mem.eql(u8, window.items, text[lo..hi]); } -fn pushHistory(gpa: std.mem.Allocator, slots: []terminal.Snapshot, len: *usize, value: terminal.Snapshot) void { +fn pushHistory(gpa: std.mem.Allocator, slots: []Snapshot, len: *usize, value: Snapshot) void { if (len.* == slots.len) { if (slots[0].ovl) |overlay| gpa.free(overlay.text); - std.mem.copyForwards(terminal.Snapshot, slots[0 .. slots.len - 1], slots[1..]); + std.mem.copyForwards(Snapshot, slots[0 .. slots.len - 1], slots[1..]); len.* -= 1; } slots[len.*] = value; @@ -617,14 +635,14 @@ fn pushHistory(gpa: std.mem.Allocator, slots: []terminal.Snapshot, len: *usize, /// Record an edit buffer (a terminal's overlay, a tag's own text) as it /// stands before an edit, once per change of it, and forget what could have /// been redone. Null is a buffer not made yet. -pub fn remember(t: *Text, gpa: std.mem.Allocator, current: ?terminal.EditBuffer) error{OutOfMemory}!void { +pub fn remember(t: *Text, gpa: std.mem.Allocator, current: ?EditBuffer) error{OutOfMemory}!void { if (t.ed_undo_len > 0) { const top = t.ed_undo[t.ed_undo_len - 1]; const same = if (top.ovl) |overlay| if (current) |now| overlay.row == now.row and overlay.rows == now.rows and std.mem.eql(u8, overlay.text, now.text) else false else current == null; if (same) return; } - const copy: ?terminal.EditBuffer = if (current) |now| .{ .row = now.row, .rows = now.rows, .text = try gpa.dupe(u8, now.text) } else null; + const copy: ?EditBuffer = if (current) |now| .{ .row = now.row, .rows = now.rows, .text = try gpa.dupe(u8, now.text) } else null; pushHistory(gpa, &t.ed_undo, &t.ed_undo_len, .{ .ovl = copy, .cur_row = t.cur_row, .cur_col = t.cur_col, .vsel = t.vsel }); for (t.ed_redo[0..t.ed_redo_len]) |item| if (item.ovl) |overlay| gpa.free(overlay.text); t.ed_redo_len = 0; @@ -634,13 +652,13 @@ pub fn remember(t: *Text, gpa: std.mem.Allocator, current: ?terminal.EditBuffer) /// other history and the state to return to comes back, its cursor and /// selection already restored here. The caller installs its buffer, which /// it then owns. Null when there is nothing to step to. -pub fn step(t: *Text, gpa: std.mem.Allocator, current: ?terminal.EditBuffer, back: bool) error{OutOfMemory}!?terminal.Snapshot { +pub fn step(t: *Text, gpa: std.mem.Allocator, current: ?EditBuffer, back: bool) error{OutOfMemory}!?Snapshot { const from, const from_len, const to, const to_len = if (back) .{ &t.ed_undo, &t.ed_undo_len, &t.ed_redo, &t.ed_redo_len } else .{ &t.ed_redo, &t.ed_redo_len, &t.ed_undo, &t.ed_undo_len }; if (from_len.* == 0) return null; - const copy: ?terminal.EditBuffer = if (current) |now| .{ .row = now.row, .rows = now.rows, .text = try gpa.dupe(u8, now.text) } else null; + const copy: ?EditBuffer = if (current) |now| .{ .row = now.row, .rows = now.rows, .text = try gpa.dupe(u8, now.text) } else null; pushHistory(gpa, to, to_len, .{ .ovl = copy, .cur_row = t.cur_row, .cur_col = t.cur_col, .vsel = t.vsel }); from_len.* -= 1; const back_to = from[from_len.*]; diff --git a/src/ansi.zig b/src/ansi.zig new file mode 100644 index 00000000..ad74dabb --- /dev/null +++ b/src/ansi.zig @@ -0,0 +1,473 @@ +//! A program's colours on a pane's body: a terminal's cells over the rows +//! the body shows (its paint, handed over as plain cells: Term.paint), and +//! its kitty images over them (Term.images). The terminal gives its view's +//! cells in the theme's colours; which of them stand under which of the +//! body's rows, the edit copy's among them, is worked out here. And a +//! finished command pane's diff, coloured over those cells as a .diff +//! file's lines are (DiffOutput, recolorDiffOutput). +const std = @import("std"); +const pardes = @import("pardes.zig"); +const panes = @import("panes.zig"); +const modal = @import("modal.zig"); +const tracy = @import("tracy.zig"); +const syntax = @import("syntax.zig"); +const diff = @import("diff.zig"); +const Colors = @import("colors.zig"); +const Term = @import("Term.zig"); +const Pardes = pardes.Pardes; +const Pane = panes.Pane; +const Surface = pardes.Surface; +const BodyWalk = @import("body_layer.zig").BodyWalk; +const EditBuffer = panes.Text.EditBuffer; + +/// The theme's colours as a terminal's paint takes them. +pub fn inkOf(theme: *const pardes.Theme) Term.Ink { + return .{ + .fg = theme.fg, + .bg = theme.bg, + .tag_fg = theme.tag_fg, + .tag_bg = theme.tag_bg, + .palette = theme.palette, + .base = theme.palette orelse .{ + theme.bg orelse theme.tag_bg, + theme.kw, + theme.str, + theme.num, + theme.box, + theme.sel_bg, + theme.comment, + theme.fg orelse theme.tag_fg, + theme.lineno, + theme.kw, + theme.str, + theme.num, + theme.scroll_thumb, + theme.sel_fg, + theme.tag_fg, + theme.fg orelse theme.tag_fg, + }, + }; +} + +/// Its program's colours over the body's rows, through the theme's filter +/// when the pane has it on. +pub fn recolor(p: *Pardes, s: *Surface, pane: *Pane, r: pardes.Rect, tx: u16, tw: u16, body_h: u16, body: []const u8) void { + const state = pane.terminal orelse return; + const body_y = p.bodyTop(pane, r); + const g = Term.grid(state); + const cols = g.cols; + const arena = p.scratch.allocator(); + const cells = arena.alloc(Term.Painted, g.len * @as(usize, cols)) catch return; + const rows = arena.alloc(Term.PaintedRow, g.len) catch return; + { + const tz_paint = tracy.zone(@src(), "termPaint"); + defer tz_paint.end(); + const ink = inkOf(p.theme()); + Term.paint(state, &ink, &p.tty_filter_palette, pane.tty_filter, cols, cells, rows); + } + const filtered = pane.tty_filter; + const vp_rows: i32 = @intCast(g.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; + var walk: BodyWalk = .init(pane); + var lines = std.mem.splitScalar(u8, body, '\n'); + var vr: u16 = 0; + while (walk.next()) |row| : (vr += 1) { + if (vr >= body_h) break; + // Before any early exit below, or the lines fall out of step with rows. + const text = lines.next() orelse ""; + const anchor: Anchor = switch (row) { + .edit => |e| blk: { + if (anchors == null) anchors = .init(p, pane, pane.ovl.?); + var an = anchors.?.shellRow(e.idx) orelse continue; + an.row -= walk.goff; + break :blk an; + }, + .grid => |v| .{ .row = v }, + }; + const vi = anchor.row; + if (vi < 0 or vi >= vp_rows) continue; + const prow = rows[@intCast(vi)]; + const grid_row = cells[@as(usize, @intCast(vi)) * cols ..][0..prow.len]; + const cut: u16 = if (pane.body.mode == .tty) 0 else cut: { + const prompt = prow.prompt orelse break :cut 0; + break :cut switch (prompt) { + .keep => 0, + // Blanked end to end: the row shows nothing of the grid, so + // projecting the prompt's own colours onto it would be a lie. + .blank => continue, + .cut => |n| std.math.cast(u16, n) orelse continue, + }; + }; + if (cut > 0 and text.len == 0) continue; + var at: usize = 0; + var sc: u16 = 0; + var gc: u16 = cut; + var sb: usize = 0; + const mine_from = @min(anchor.prefix, text.len); + const mine_to = text.len - @min(anchor.suffix, text.len); + var crossed = false; + while (at < text.len and sc < tw) { + const stop = modal.nextGrapheme(text, at); + if (stop <= at) break; + const span: u16 = if (sc + 1 < tw and s.at(tx + sc + 1, body_y + vr).len == 0) 2 else 1; + if (at >= mine_from and at < mine_to) { + sc += span; + at = stop; + continue; + } + if (at >= mine_to and !crossed) { + crossed = true; + const upto = anchor.shell_len - @min(anchor.suffix, anchor.shell_len); + while (sb < upto) { + if (gc >= grid_row.len) break; + sb += grid_row[gc].bytes; + gc = std.math.add(u16, gc, 1) catch break; + } + } + const want = stop - at; + // Consume every cell that contributed to this grapheme. A cluster + // ghostty split across several cells is still ONE printed glyph. + var covered: usize = 0; + var style: ?pardes.CellStyle = null; + while (covered < want) { + if (gc >= grid_row.len) break; + const c = &grid_row[gc]; + if (style == null and c.wide != .spacer_tail and c.wide != .spacer_head) + style = c.style; + covered += c.bytes; + gc = std.math.add(u16, gc, 1) catch break; + // A spacer contributes no bytes; without this the loop would + // spin on a row that ends in one. + if (covered == 0 and gc >= pane.cols) break; + } + while (gc < grid_row.len and grid_row[gc].wide == .spacer_tail) + gc = std.math.add(u16, gc, 1) catch break; + if (style) |st| for (0..span) |k| { + const cell = s.at(tx + sc + @as(u16, @intCast(k)), body_y + vr); + if (cell.default and !filtered) continue; + cell.default = false; + cell.style = st; + }; + sb += covered; + sc += span; + at = stop; + } + var tail: ?pardes.CellStyle = null; + if (anchor.whole() or anchor.suffix > 0) { + while (sc < tw) { + if (gc >= grid_row.len) break; + const c = &grid_row[gc]; + gc = std.math.add(u16, gc, 1) catch break; + if (c.wide == .spacer_tail) continue; + const cell = s.at(tx + sc, body_y + vr); + sc += 1; + tail = c.style; + if (cell.default and !filtered) continue; + cell.default = false; + cell.style = c.style; + } + if (tail) |style| while (sc < tw) : (sc += 1) { + const cell = s.at(tx + sc, body_y + vr); + if (cell.default and !filtered) continue; + cell.default = false; + cell.style = style; + }; + } + } +} + +/// Its kitty images over the body's rows, as placements (after the rows +/// and their colours: placeholder cells are blanked by it). +pub fn images(p: *Pardes, s: *Surface, pane: *Pane, id: usize, tx: u16, tw: u16, body_y: u16, body_h: u16) void { + const state = pane.terminal orelse return; + Term.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(Term.grid(state).len, rows_of.len); + @memset(rows_of[0..vp_rows], null); + var walk: BodyWalk = .init(pane); + var vr: u16 = 0; + while (walk.next()) |row| : (vr += 1) { + if (vr >= body_h) break; + const vi = switch (row) { + .grid => |v| v, + .edit => continue, + }; + if (vi < 0 or vi >= vp_rows) continue; + rows_of[@intCast(vi)] = vr; + } + Term.images(state, p.gpa, .{ + .pane = @intCast(id), + .serial = pane.serial, + .tx = tx, + .body_y = body_y, + .cols = @min(tw, pane.cols), + .rows_of = rows_of[0..vp_rows], + .tty_mode = pane.body.mode == .tty, + .now_ms = p.clock.stepped_ns / std.time.ns_per_ms, + .cell_w = @max(1, p.view().cell_pixels.w), + .cell_h = @max(1, p.view().cell_pixels.h), + }, &p.surface.placements, s.cells, s.cols); +} + +// Match surviving edit-buffer rows to their original terminal styles. +const EditAnchors = struct { + /// the buffer's own text, walked in order: a line the VIEWPORT skipped still + /// consumes the row it came from, so the lines below it stay aligned + text: []const u8 = &.{}, + at: usize = 0, + shell: []const []const u8 = &.{}, + /// the covered span, absolute grid rows, as `[first, end)` + first: usize = 0, + end: usize = 0, + lines: usize = 0, + /// the line `at` names, and the first row still unclaimed + idx: usize = 0, + cursor: usize = 0, + budget: usize = 0, + active: bool = false, + + fn init(p: *Pardes, pane: *Pane, o: EditBuffer) EditAnchors { + if (o.rows <= 0 or o.row < 0) return .{}; + const first: usize = @intCast(o.row); + const total = Term.grid(pane.terminal).total; + if (first >= total) return .{}; + const covered: usize = @intCast(o.rows); + const count = @min(covered, total - first); + const shell = Term.editRows(pane.terminal.?, p.scratch.allocator(), first, count) catch return .{}; + const lines = std.mem.count(u8, o.text, "\n") + 1; + return .{ + .text = o.text, + .shell = shell, + .first = first, + .end = first + count, + .lines = lines, + .cursor = first, + .budget = covered + 4 * lines, + .active = true, + }; + } + fn shellRow(a: *EditAnchors, idx: usize) ?Anchor { + if (!a.active or idx >= a.lines) return null; + var found: ?Anchor = null; + while (a.idx <= idx) : (a.idx += 1) found = a.claim(a.nextLine() orelse return null); + return found; + } + + fn nextLine(a: *EditAnchors) ?[]const u8 { + if (a.at > a.text.len) return null; + const rest = a.text[a.at..]; + if (std.mem.indexOfScalar(u8, rest, '\n')) |n| { + a.at += n + 1; + return rest[0..n]; + } + // The last line has no terminator; one past the end ends the walk. + a.at = a.text.len + 1; + return rest; + } + + /// Where this line still stands over the grid, if anywhere. + fn claim(a: *EditAnchors, line: []const u8) ?Anchor { + const end = if (line.len == 0) @min(a.cursor + 1, a.end) else a.end; + var k = a.cursor; + while (k < end) : (k += 1) { + if (a.budget == 0) return null; + a.budget -= 1; + if (!std.mem.eql(u8, line, a.shell[k - a.first])) continue; + a.cursor = k + 1; + return .{ .row = @intCast(k) }; + } + if (a.cursor >= a.end) return null; + const shell = a.shell[a.cursor - a.first]; + var p: usize = 0; + while (p < line.len and p < shell.len and line[p] == shell[p]) p += 1; + var s: usize = 0; + const room = @min(line.len, shell.len) - p; + while (s < room and line[line.len - 1 - s] == shell[shell.len - 1 - s]) s += 1; + if (p + s == 0) return null; + if (line.len != p + s and shell.len - (p + s) > shell.len / 2) return null; + const row = a.cursor; + if (s > 0 or p >= shell.len) a.cursor += 1; + return .{ .row = @intCast(row), .prefix = p, .suffix = s, .shell_len = shell.len }; + } +}; + +const Anchor = struct { + /// the row, absolute while it comes from `EditAnchors`, viewport once + /// `recolorAnsi` has subtracted the walk's offset + row: i32, + prefix: usize = std.math.maxInt(usize), + suffix: usize = 0, + /// the row's own dumped length — what the suffix is measured from on the + /// GRID side, where the edit may have changed the byte count + shell_len: usize = 0, + + fn whole(an: Anchor) bool { + return an.prefix == std.math.maxInt(usize); + } +}; + +/// What finished command panes printed, kept while it cannot change: a +/// copy of the terminal's rows, and whether they are a diff. Taken once +/// when a finished pane is first drawn, so neither a frame nor a look dumps +/// the whole scrollback again; a still running command is shown as it +/// printed. Keyed by the pane and its width (a resize rewraps every row); +/// a rerun in the pane drops it (exec.runCommand). +pub const DiffOutput = struct { + const Entry = struct { + serial: u32, + cols: u16, + is_diff: bool, + /// The rows joined by '\n'; `rows` are slices of it. + text: []u8, + rows: [][]const u8, + used: u64, + }; + slots: [4]?Entry = @splat(null), + clock: u64 = 0, + + pub fn reset(o: *DiffOutput, gpa: std.mem.Allocator) void { + for (&o.slots) |*slot| { + if (slot.*) |e| { + gpa.free(e.text); + gpa.free(e.rows); + } + slot.* = null; + } + } + + /// A pane's command runs again: what it printed before is gone. + pub fn drop(o: *DiffOutput, gpa: std.mem.Allocator, serial: u32) void { + for (&o.slots) |*slot| if (slot.*) |e| if (e.serial == serial) { + gpa.free(e.text); + gpa.free(e.rows); + slot.* = null; + }; + } + + /// A finished command pane's rows when they are a diff, else null. + pub fn lines(o: *DiffOutput, p: *Pardes, pane: *Pane) ?[]const []const u8 { + if (pane.command == null or !pane.command_done or pane.command_pty or pane.terminal == null) return null; + o.clock += 1; + for (&o.slots) |*slot| if (slot.*) |*e| if (e.serial == pane.serial and e.cols == pane.cols) { + e.used = o.clock; + return if (e.is_diff) e.rows else 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| { + total += row.len + 1; + }; + const text = p.gpa.alloc(u8, total) catch return null; + const rows = p.gpa.alloc([]const u8, if (is_diff) shown.len else 0) catch { + p.gpa.free(text); + return null; + }; + var at: usize = 0; + for (rows, 0..) |*row, i| { + @memcpy(text[at..][0..shown[i].len], shown[i]); + row.* = text[at..][0..shown[i].len]; + at += shown[i].len; + text[at] = '\n'; + at += 1; + } + // An empty slot, else the least recently used. + var oldest: usize = 0; + for (&o.slots, 0..) |*slot, i| { + const e = slot.* orelse { + oldest = i; + break; + }; + if (e.used < o.slots[oldest].?.used) oldest = i; + } + if (o.slots[oldest]) |old| { + p.gpa.free(old.text); + p.gpa.free(old.rows); + } + o.slots[oldest] = .{ .serial = pane.serial, .cols = pane.cols, .is_diff = is_diff, .text = text, .rows = rows, .used = o.clock }; + return if (is_diff) rows else null; + } +}; + +/// A command pane whose output is a diff (`git diff`, `diff -u`): its +/// rows coloured as a .diff file's are, over what the program printed. +/// The rows are the terminal's own, so a line it wrapped goes on in the +/// row below (syntax.highlightDiffRows). +pub fn recolorDiffOutput(p: *Pardes, s: *Surface, pane: *Pane, r: pardes.Rect, tx: u16, tw: u16, body_h: u16, body: []const u8) void { + if (pane.command == null) return; + const tz = tracy.zone(@src(), "diffRecolor"); + defer tz.end(); + const rows = p.diff_output.lines(p, pane) orelse return; + // The copy's rows are one text, joined as a file's lines are. + const flat_start = @intFromPtr(rows[0].ptr); + const last = rows[rows.len - 1]; + const flat = rows[0].ptr[0 .. @intFromPtr(last.ptr) + last.len - flat_start]; + const raw = pane.body.mode == .tty; + const View = struct { row: usize, at: usize }; + const arena = p.scratch.allocator(); + const views = arena.alloc(?View, body_h) catch return; + var lo: usize = std.math.maxInt(usize); + var hi: usize = 0; + var shown = std.mem.splitScalar(u8, body, '\n'); + for (views, 0..) |*view, vi| { + view.* = null; + const line = shown.next() orelse continue; + const vr: i32 = @intCast(vi); + const w = pane.wrapAt(vr); + 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)); + if (from > rows[row].len or !std.mem.startsWith(u8, rows[row][from..], line)) continue; + view.* = .{ .row = row, .at = from }; + const start = @intFromPtr(rows[row].ptr) - flat_start; + lo = @min(lo, start); + hi = @max(hi, start + rows[row].len); + } + if (lo > hi) return; + const styles = syntax.highlightDiffRows(arena, flat, lo, hi, true) catch return; + const tints: Colors.Grounds = .of(p.theme()); + const ink = p.theme().fg orelse p.theme().tag_fg; + const body_y = p.bodyTop(pane, r); + shown = std.mem.splitScalar(u8, body, '\n'); + for (views, 0..) |maybe, vr| { + const line = shown.next() orelse break; + const view = maybe orelse continue; + const base = @intFromPtr(rows[view.row].ptr) - flat_start - lo; + const tint = if (base < styles.len) tints.forStyle(styles[base]) else null; + if (tint) |t| s.tint(tx, body_y + @as(u16, @intCast(vr)), tw, t.row, null); + var c: usize = 0; + var screen_c: usize = 0; + while (c < line.len and screen_c < tw) { + const grapheme_end = modal.nextGrapheme(line, c); + if (grapheme_end <= c) break; + const cells = panes.File.graphemeDisplayWidth(line[c..grapheme_end]); + const style = styles[base + view.at + c]; + const prefix = view.at + c == 0 and (line[0] == '+' or line[0] == '-'); + // On an added or removed line, what the program coloured red or + // green is the tint's to say now: its code takes the page's ink. + const paint: ?panes.File.SynStyle = if (tint != null and prefix) + .{ .fg = tint.?.ink, .bold = true } + else if (panes.File.synStyle(p, @fromBackingInt(@intCast(style & syntax.syn_bits)))) |ss| + ss + else if (tint != null) + .{ .fg = ink, .bold = false } + else + null; + if (paint) |ss| { + var fill: usize = 0; + while (fill < cells and screen_c + fill < tw) : (fill += 1) { + const cell = s.at(tx + @as(u16, @intCast(screen_c + fill)), body_y + @as(u16, @intCast(vr))); + if (cell.default) continue; + cell.style.fg = .{ .rgb = ss.fg }; + cell.style.bold = ss.bold; + } + } + screen_c += cells; + c = grapheme_end; + } + } +} diff --git a/src/body_layer.zig b/src/body_layer.zig index 76aec179..26513b93 100644 --- a/src/body_layer.zig +++ b/src/body_layer.zig @@ -11,6 +11,7 @@ const modal = @import("modal.zig"); const tracy = @import("tracy.zig"); const panes = @import("panes.zig"); const colors = @import("colors.zig"); +const ansi = @import("ansi.zig"); const Color = @import("surface.zig").Color; const CellStyle = @import("surface.zig").CellStyle; const Cell = @import("surface.zig").Cell; @@ -37,7 +38,7 @@ fn paintTerminalSelection(p: *Pardes, s: *Surface, pane: *Pane, r: Rect, rows: [ var visible: i32 = 0; while (lines.next()) |line| : (visible += 1) { if (visible >= r.h -| pane.tag_rows) break; - const source_row = if (raw) 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 +51,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 +80,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); @@ -195,7 +196,7 @@ pub fn joinBody(p: *Pardes, s: *Surface, arena: std.mem.Allocator, pane: *Pane, layer.id = @intCast(id); layer.serial = pane.serial; const body = s.region(.body, id).?; - layer.viewport = .{ .x = body.rect.x, .y = body.rect.y, .w = body.rect.w - body.clip, .h = body.rect.h }; + layer.viewport = .{ .x = body.rect.x, .y = body.rect.y, .w = body.rect.w, .h = body.rect.h }; layer.cols = width; layer.rows = @intCast(logical_rows); layer.context_rows = pane.context_rows; @@ -230,8 +231,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 +345,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.File.recolorDiffOutput(p, s, pane, r, tx, tw, body_h, body); + ansi.recolor(p, s, pane, r, tx, tw, body_h, body); + ansi.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()) ansi.images(p, s, pane, id, tx, tw, body_y, body_h); const sel_btn = buttonTints(th); if (p.look_hover_preview) |preview| { @@ -491,10 +491,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 +514,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 +547,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 85bb6e44..e9c91fd8 100644 --- a/src/builtins.zig +++ b/src/builtins.zig @@ -5,6 +5,7 @@ const tagline = @import("tagline.zig"); const dump = @import("dump.zig"); const exec = @import("exec.zig"); const look = @import("look.zig"); +const PlumbRules = @import("Plumb.zig"); const edit = @import("edit.zig"); const colors = @import("colors.zig"); const Pardes = pardes.Pardes; @@ -65,8 +66,6 @@ pub const PaneKind = enum { picture, /// A terminal, or a +Pager: a program's colours. program_colors, - /// A text pane showing a diff: a .diff, a .patch, a +Pager holding one. - diff, pub fn has(kind: PaneKind, pane: *const panes.Pane) bool { return switch (kind) { @@ -74,8 +73,6 @@ pub const PaneKind = enum { .image => pane.addon != null, .picture => pane.addon != null or pane.isTerminal(), .program_colors => pane.isTerminal() or (pane.file != null and pane.file.?.pager), - .diff => if (pane.file) |f| pane.colorAlgo() == .diff or - (f.output != null and std.meta.eql(f.output.?.from, panes.Output.Origin{ .cmd = .Diff })) else false, }; } @@ -85,7 +82,6 @@ pub const PaneKind = enum { .image => "an image", .picture => "an image or a terminal", .program_colors => "a terminal or a +Pager", - .diff => "a diff or a +Diff", }; } }; @@ -428,7 +424,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"); @@ -748,13 +749,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); } }; @@ -938,43 +939,18 @@ pub const Incl = struct { } }; -/// The plumber's rules, for the session, one a line as plumb(6) orders a -/// rule: `Plumb suffix .svg to image` makes a look at an existing `.svg` -/// file an image pane. The user's rules are tried in the order given, -/// before the built-in ones, and the first that matches takes the look. -/// Bare, it lists them; `Plumb -` empties the list. +/// Open the plumbing file, the plumber's rules (plumb(6)'s rule sets) in +/// the configuration directory beside `init`: saved, they are the rules in +/// force. Not there yet, it holds `include basic`, the default rules. pub const Plumb = struct { pub const scope: Scope = .session; pub const takes_arg = true; pub fn run(c: Ctx) void { - const p = c.p; - const typed = std.mem.trim(u8, c.arg orelse "", " \t\r\n"); - if (std.mem.eql(u8, typed, "-")) { - for (p.plumb.items) |rule| p.gpa.free(rule); - p.plumb.clearRetainingCapacity(); - return p.setMessage(c.id, "Plumb: none"); - } - if (typed.len > 0) { - var said: [320]u8 = undefined; - if (look.plumbRuleError(&p.kinds, typed)) |why| - return p.reportFailure(c.id, std.fmt.bufPrint(&said, "Plumb: {s}", .{why}) catch "Plumb: invalid rule"); - // One blank between words, as the list shows it. - var rule: std.ArrayList(u8) = .empty; - defer rule.deinit(p.gpa); - var words = std.mem.tokenizeAny(u8, typed, " \t"); - while (words.next()) |w| { - if (rule.items.len > 0) rule.append(p.gpa, ' ') catch |err| return p.reportError(c.id, "Plumb", err); - rule.appendSlice(p.gpa, w) catch |err| return p.reportError(c.id, "Plumb", err); - } - p.plumb.ensureUnusedCapacity(p.gpa, 1) catch |err| return p.reportError(c.id, "Plumb", err); - p.plumb.appendAssumeCapacity(rule.toOwnedSlice(p.gpa) catch |err| return p.reportError(c.id, "Plumb", err)); - return; - } - var list: std.Io.Writer.Allocating = .init(p.scratch.allocator()); - list.writer.writeAll("Plumb:") catch |err| return p.reportError(c.id, "Plumb", err); - for (p.plumb.items, 0..) |rule, i| list.writer.print("{s} {s}", .{ if (i == 0) "" else ";", rule }) catch |err| return p.reportError(c.id, "Plumb", err); - if (p.plumb.items.len == 0) list.writer.writeAll(" none") catch |err| return p.reportError(c.id, "Plumb", err); - p.setMessage(c.id, list.written()); + if (std.mem.trim(u8, c.arg orelse "", " \t\r\n").len > 0) return c.p.reportFailure(c.id, PlumbRules.e_word); + var buf: [4096]u8 = undefined; + const path = PlumbRules.filePath(c.p, &buf) orelse + return c.p.reportFailure(c.id, "Plumb: no plumbing file here: no configuration directory"); + openConfigFile(c, "Plumb", path, "include basic\n"); } }; @@ -1088,18 +1064,13 @@ pub const Filter = struct { } }; -/// Stack a diff's hunks as a diff viewer shows them, each under its place and the declarations around it, in a +Diff; on a +Diff, show the diff itself as text. +/// Stack a diff's hunks as a diff viewer shows them, each under its place and the declarations around it, in a +Diff; on a +Diff, show the diff itself as text. `Diff <file>` stacks that diff's, `Diff <revision>` git show's. +/// The diff viewer's one registration: its word and traits here, all else +/// its own (hunks.zig). pub const Diff = struct { - pub const needs: PaneKind = .diff; + pub const takes_arg = true; pub const output: OutputTraits = .{ .name = config.diff_buffer, .steps = true, .locations = true }; - pub fn run(c: Ctx) void { - const f = &c.pane.file.?; - if (panes.Output.diffSource(c.p, f)) |source| return panes.Output.showDiffText(c.p, c.id, source); - _ = panes.Output.openDiff(c.p, c.id, f.path, f.content) catch |err| switch (err) { - error.NoHunks => c.p.reportFailure(c.id, "Diff: no hunk in it"), - else => c.p.reportError(c.id, "hunks", err), - }; - } + pub const run = @import("hunks.zig").word; }; /// Cycle the pane's input modes: terminals add raw tty mode to normal/insert. @@ -1340,25 +1311,36 @@ pub const Config = struct { pub fn run(c: Ctx) void { const path = c.p.startupPath() orelse return c.p.reportFailure(c.id, "Config: no startup file here: no configuration directory"); - var real_buf: [4096]u8 = undefined; - const real = if (pardes.filesystem.resolveOs(path, &real_buf)) |r| r.path else null; - for (c.p.panes, 0..) |slot, id| { - const pane = slot orelse continue; - const f = pane.file orelse continue; - if (f.output != null) continue; - if (!std.mem.eql(u8, f.path, path) and !(if (real) |r| std.mem.eql(u8, f.path, r) else false)) continue; - return look.focusPaneLine(c.p, id, .{}, .keep); - } - if (real != null) return look.lookAt(c.p, c.id, path); - // Not there yet: a pane named for it, which Save makes. - const free = c.p.freeSlot() orelse return c.p.reportError(c.id, "Config", error.NoPaneSlots); - panes.newScratchFor(c.p, c.id, .scratch); - if (c.p.panes[free] == null) return; - @import("ninep/pane.zig").nameBuffer(c.p, free, path, false) catch |err| return c.p.reportError(c.id, "Config", err); - c.p.view().active = free; + openConfigFile(c, "Config", path, ""); } }; +/// A file of the configuration directory's (Config's init, Plumb's +/// plumbing) in a pane: its pane when it is open, else the file, else a +/// pane of that name holding `initial`, for Save to make it and its +/// directory. +fn openConfigFile(c: Ctx, name: []const u8, path: []const u8, initial: []const u8) void { + var real_buf: [4096]u8 = undefined; + const real = if (pardes.filesystem.resolveOs(path, &real_buf)) |r| r.path else null; + for (c.p.panes, 0..) |slot, id| { + const pane = slot orelse continue; + const f = pane.file orelse continue; + if (f.output != null) continue; + if (!std.mem.eql(u8, f.path, path) and !(if (real) |r| std.mem.eql(u8, f.path, r) else false)) continue; + return look.focusPaneLine(c.p, id, .{}, .keep); + } + if (real != null) return look.lookAt(c.p, c.id, path); + // Not there yet: a pane named for it, which Save makes. + const free = c.p.freeSlot() orelse return c.p.reportError(c.id, name, error.NoPaneSlots); + panes.newScratchFor(c.p, c.id, .scratch); + const made = c.p.panes[free] orelse return; + @import("ninep/pane.zig").nameBuffer(c.p, free, path, false) catch |err| return c.p.reportError(c.id, name, err); + if (initial.len > 0) if (made.file) |*f| { + _ = panes.File.replace(c.p, f, 0, f.content.len, initial); + }; + c.p.view().active = free; +} + /// Open the settings in effect, each a word to click, and the startup /// file's path. pub const DumpConfig = struct { @@ -2022,6 +2004,7 @@ test "a Restore's warning is not an Exit's: each word is warned on its own" { } test "Kill stops the commands pardes typed, bare all and by name those that match, and never quits" { + if (pardes.Term.ops == null) return error.SkipZigTest; // a command pane const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 80, .rows = 24 }); defer p.deinit(); while (p.nextEffect()) |_| {} diff --git a/src/colors.zig b/src/colors.zig index e679f4a5..d3ab82e2 100644 --- a/src/colors.zig +++ b/src/colors.zig @@ -12,6 +12,36 @@ const MAX_PANES = pardes.MAX_PANES; const BOX_H = pardes.BOX_H; const Pardes = pardes.Pardes; +/// 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: { + var p: [256][3]u8 = undefined; + p[0..16].* = .{ + .{ 0x1D, 0x1F, 0x21 }, // black + .{ 0xCC, 0x66, 0x66 }, // red + .{ 0xB5, 0xBD, 0x68 }, // green + .{ 0xF0, 0xC6, 0x74 }, // yellow + .{ 0x81, 0xA2, 0xBE }, // blue + .{ 0xB2, 0x94, 0xBB }, // magenta + .{ 0x8A, 0xBE, 0xB7 }, // cyan + .{ 0xC5, 0xC8, 0xC6 }, // white + .{ 0x66, 0x66, 0x66 }, // bright black + .{ 0xD5, 0x4E, 0x53 }, // bright red + .{ 0xB9, 0xCA, 0x4A }, // bright green + .{ 0xE7, 0xC5, 0x47 }, // bright yellow + .{ 0x7A, 0xA6, 0xDA }, // bright blue + .{ 0xC3, 0x97, 0xD8 }, // bright magenta + .{ 0x70, 0xC0, 0xB1 }, // bright cyan + .{ 0xEA, 0xEA, 0xEA }, // bright white + }; + for (0..216) |i| { + for (0..3, [3]usize{ i / 36, i / 6 % 6, i % 6 }) |c, v| p[16 + i][c] = if (v == 0) 0 else 55 + 40 * v; + } + for (0..24) |i| p[232 + i] = @splat(8 + 10 * i); + break :blk p; +}; + /// sRGB channel to linear light. pub const to_linear: [256]f32 = blk: { @setEvalBranchQuota(100_000); @@ -292,6 +322,43 @@ pub fn synInk(th: *const Theme, sy: @import("syntax.zig").Syn) ?[3]u8 { }; } +/// The grounds a style byte's high bits name (syntax.ground_add and the +/// rest) in a theme: a row added or removed on a ground a little way from +/// the page toward the theme's green or red (its own ANSI ones where it has +/// a palette), a stronger one, a faint one, and the row's marker in that +/// hue, pushed toward the ink until it reads on the row's ground. Syntax +/// colours are drawn over a ground unchanged. +pub const Grounds = struct { + add: Ground, + del: Ground, + + pub const Ground = struct { row: [3]u8, emph: [3]u8, line: [3]u8, ink: [3]u8 }; + + pub fn of(th: *const Theme) Grounds { + const page = th.bg orelse th.tag_bg; + const ink = th.fg orelse th.tag_fg; + const green: [3]u8 = if (th.palette) |pal| pal[2] else .{ 0x2e, 0xa0, 0x43 }; + const red: [3]u8 = if (th.palette) |pal| pal[1] else .{ 0xcf, 0x22, 0x2e }; + return .{ .add = ground(page, ink, green), .del = ground(page, ink, red) }; + } + + fn ground(page: [3]u8, ink: [3]u8, hue: [3]u8) Ground { + const row = mixOklab(page, hue, 0.18); + var marker = hue; + var step: usize = 0; + while (step < 4 and contrast(marker, row) < 3) : (step += 1) marker = mixOklab(marker, ink, 0.4); + return .{ .row = row, .emph = mixOklab(page, hue, 0.28), .line = mixOklab(page, hue, 0.07), .ink = marker }; + } + + /// The ground of a byte's hue, if it has one. + pub fn forStyle(g: *const Grounds, style: u8) ?Ground { + const syntax = @import("syntax.zig"); + if (style & syntax.ground_add != 0) return g.add; + if (style & syntax.ground_del != 0) return g.del; + return null; + } +}; + /// One family, its twelve backgrounds a theme each (`curated`). const seoul256 = @import("themes/seoul256.zig"); diff --git a/src/config.zig b/src/config.zig index 3a846206..c7078d8e 100644 --- a/src/config.zig +++ b/src/config.zig @@ -217,9 +217,6 @@ pub const back_out: []const Chord = &.{.{ .cp = Key.escape, .shift = true }}; pub const tty_toggle_default: u21 = 'b'; -// Projected colors below this contrast use the theme's more legible anchor. -pub const tty_filter_min_contrast: f64 = 1.5; - // What a pty child is told it is talking to. Every pane is emulated by the // bundled VT, so this describes pardes and never the terminal pardes itself // was launched from — the child inherits the launcher's TERM otherwise, which @@ -1818,6 +1815,7 @@ test "reference.typ's #fstree is the tree the session serves, file for file" { for (std.enums.values(tree.TopFile)) |f| switch (f) { .root => {}, .new => try served.put(gpa, "pane/new", {}), + .rules, .send => try served.put(gpa, try std.fmt.allocPrint(gpa, "plumb/{s}", .{f.fileName()}), {}), else => try served.put(gpa, if (f.dir()) try std.fmt.allocPrint(gpa, "{s}/", .{f.fileName()}) else f.fileName(), {}), }; try served.put(gpa, "os/", {}); @@ -1827,6 +1825,7 @@ test "reference.typ's #fstree is the tree the session serves, file for file" { const under = if (f.inPty() and f != .pty) "pane/<n>/pty/" else "pane/<n>/"; try served.put(gpa, try std.fmt.allocPrint(gpa, "{s}{s}{s}", .{ under, f.fileName(), if (f.isDir()) "/" else "" }), {}); }; + try served.put(gpa, "plumb/<port>", {}); try served.put(gpa, "col/<n>/", {}); for (std.enums.values(tree.ColFile)) |f| if (f != .dir) try served.put(gpa, try std.fmt.allocPrint(gpa, "col/<n>/{s}", .{f.fileName()}), {}); diff --git a/src/draw.zig b/src/draw.zig index 7d199155..92bcc592 100644 --- a/src/draw.zig +++ b/src/draw.zig @@ -59,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. @@ -74,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; @@ -116,24 +116,6 @@ pub fn place(p: *Pardes, s: *Surface) void { } if (p.settings.workspace_tag) s.addRegion(.{ .kind = .workspace_tag, .rect = .{ .x = 0, .y = 0, .w = s.cols, .h = p.topBarHeight() } }); - // A column carried to the window's right edge shows where it lands as a - // rail in the last cell: the layers under it stop a cell short. - if (v.drag == .column_move) rail: { - const d = v.drag.column_move; - const source = layout.columnBySerial(p, d.serial) orelse break :rail; - const edge: u16 = switch (layout.columnDrop(p, source, d.cur_x, d.grab)) { - .stay => break :rail, - .reorder => |target| if (target < source) v.col_x[target] else v.col_x[target] + v.col_w[target], - .edge => |x| x, - }; - if (edge != s.cols) break :rail; - for (s.regions[0..s.nregions]) |*region| switch (region.kind) { - .body, .tag, .notice, .column_tag => if (region.rect.x + region.rect.w == s.cols) { - region.clip = 1; - }, - else => {}, - }; - } } /// A pane's grip in the grid: `box` focused, else halfway between its ring @@ -252,16 +234,14 @@ fn joinNotice(p: *Pardes, s: *Surface, arena: std.mem.Allocator, region: Region) if (layer.cursor) |caret| { if (caret.x >= skip) s.cursor = .{ .x = region.rect.x + caret.x - @as(u16, @intCast(skip)), .y = region.rect.y, .bar = caret.bar }; } - // Laid out at its full width; only shown short of the rail. - layer.viewport.w -|= region.clip; } 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; @@ -328,77 +308,6 @@ pub fn render(p: *Pardes, arena: std.mem.Allocator) !*Surface { try paintHeaders(p, s); - switch (v.drag) { - .border_v => |d| { - if (d.cur_x < s.cols) { - var row: u16 = p.topBarHeight(); - while (row < s.rows) : (row += 1) s.overlayDash(d.cur_x, row, "╎"); - s.addRegion(.{ .kind = .guide, .rect = .{ .x = d.cur_x, .y = p.topBarHeight(), .w = 1, .h = s.rows -| p.topBarHeight() } }); - } - if (d.corner) |k| if (d.cur_y < s.rows) { - const first = if (k.col == d.left_col) v.col_x[k.col] else d.cur_x +| 1; - const end = if (k.col == d.left_col) d.cur_x else v.col_x[k.col] +| v.col_w[k.col] -| 1; - var col = first; - while (col <= end and col < s.cols) : (col += 1) s.overlayDash(col, d.cur_y, "╌"); - if (col > first) s.addRegion(.{ .kind = .guide, .rect = .{ .x = first, .y = d.cur_y, .w = col - first, .h = 1 } }); - }; - }, - // A column that went away mid-drag has nothing to guide. - .border_h => |d| if (d.cur_y < s.rows and d.col < v.ncol and v.col_x[d.col] < s.cols) { - const end = @min(s.cols, v.col_x[d.col] + v.col_w[d.col]); - var col = v.col_x[d.col]; - while (col < end) : (col += 1) s.overlayDash(col, d.cur_y, "╌"); - s.addRegion(.{ .kind = .guide, .rect = .{ .x = v.col_x[d.col], .y = d.cur_y, .w = end - v.col_x[d.col], .h = 1 } }); - }, - .column_move => |d| rail: { - const source = layout.columnBySerial(p, d.serial) orelse break :rail; - if (s.cols == 0) break :rail; - // Where the column's left edge would land, reordered or not. - const edge: u16 = switch (layout.columnDrop(p, source, d.cur_x, d.grab)) { - .stay => break :rail, - .reorder => |target| if (target < source) v.col_x[target] else v.col_x[target] + v.col_w[target], - .edge => |x| x, - }; - // The layers under an outside rail stop a cell short of it: - // `place` clipped them. - // The rail runs in the seam cell left of the edge, where a - // border drag's does: the edge cell itself is a gutter, which - // the GUI paints as a scroll rail that swallowed the dashes. - // At the window's left edge there is no seam, so it runs just - // past that scroll rail instead. It takes the lit grip's - // color: this is where the grabbed column lands. - const x = @min(if (edge == 0) config.GUTTER - 1 else edge - 1, s.cols -| 1); - var row: u16 = p.topBarHeight(); - // A guide region for each run of it the tags do not break. - var run: u16 = row; - while (row < s.rows) : (row += 1) { - // Past the left edge's scroll rail the rail would cut - // through column 0's grip and pane boxes: leave them whole. - if (edge == 0 and s.at(x, row).style.font_role == .tagline) { - if (row > run) s.addRegion(.{ .kind = .guide, .rect = .{ .x = x, .y = run, .w = 1, .h = row - run } }); - run = row + 1; - continue; - } - s.overlayDash(x, row, "╎"); - s.at(x, row).style.fg = .{ .rgb = chrome.column_box }; - } - if (row > run) s.addRegion(.{ .kind = .guide, .rect = .{ .x = x, .y = run, .w = 1, .h = row - run } }); - }, - .move => |d| if (d.cur_x < s.cols) { - if (layout.movePlacement(p, d.id, d.cur_x, d.cur_y)) |placement| if (placement.row < s.rows and v.col_x[placement.preview_col] + v.col_w[placement.preview_col] <= s.cols) { - var col: u16 = v.col_x[placement.preview_col]; - while (col < v.col_x[placement.preview_col] + v.col_w[placement.preview_col]) : (col += 1) { - s.set(col, placement.row, "╌", .{ .fg = .{ .rgb = chrome.lineno } }); - } - s.set(d.cur_x, placement.row, "▌", .{ .fg = .{ .rgb = chrome.lineno } }); - s.addRegion(.{ .kind = .guide, .rect = .{ .x = v.col_x[placement.preview_col], .y = placement.row, .w = v.col_w[placement.preview_col], .h = 1 } }); - s.addRegion(.{ .kind = .guide, .rect = .{ .x = d.cur_x, .y = placement.row, .w = 1, .h = 1 } }); - }; - }, - // A hover draws no hint: columns resize by their grips. - .none, .select => {}, - } - // debug overlay: a small stats box drawn last, top-right ("Debug") if (p.settings.debug) if (p.panes[v.active]) |at| { var nlive: usize = 0; @@ -414,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; @@ -607,8 +516,6 @@ fn paintHeaders(p: *Pardes, s: *Surface) !void { const layer = &s.tag_layers[MAX_PANES + c]; try renderHeaderLayer(p, layer, .column, @intCast(c), region.rect, tagline.columnTag(p, c), top, bg, fg); if (v.col_x[c] < s.cols) joinHeaderRows(s, layer, fg); - // Laid out at its full width; only shown short of the rail. - layer.viewport.w -|= region.clip; }; } @@ -810,7 +717,7 @@ fn joinPaneTag(p: *Pardes, s: *Surface, arena: std.mem.Allocator, pane: *Pane, r layer.kind = .pane; layer.id = @intCast(id); layer.serial = pane.serial; - layer.viewport = .{ .x = region.rect.x, .y = region.rect.y, .w = region.rect.w - region.clip, .h = rows }; + layer.viewport = .{ .x = region.rect.x, .y = region.rect.y, .w = region.rect.w, .h = rows }; layer.cols = columns; layer.rows = rows; layer.context_rows = 0; @@ -1017,6 +924,7 @@ test "a grip's four states, focused or not and clean or dirty, are each its own } test "every theme draws a file's name, a +Errors and a Term word in a tint, never the tag's plain ink" { + if (pardes.Term.ops == null) return error.SkipZigTest; // a shell's Term word const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .cols = 120, .rows = 40, .tty_only = true }); defer p.deinit(); diff --git a/src/dump.zig b/src/dump.zig index a880c7e1..d1662e24 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(); @@ -987,34 +996,35 @@ 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 (pardes.Term.ops == null) return error.SkipZigTest; // it reads the emulator 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").?); } test "an upgraded session's dump keeps its views and its running terminal as they were, and settings the startup config would change" { + if (pardes.Term.ops == null) return error.SkipZigTest; // a shell, dumped and loaded 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 +1036,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/echo.zig b/src/echo.zig index 3d2ee060..6a18f5dd 100644 --- a/src/echo.zig +++ b/src/echo.zig @@ -29,7 +29,7 @@ //! there is ever shown. const std = @import("std"); const pardes = @import("pardes.zig"); -const terminal = pardes.panes.terminal; +const Term = pardes.Term; const Pardes = pardes.Pardes; const Pane = pardes.Pane; const Surface = pardes.Surface; @@ -235,12 +235,11 @@ pub const Echo = struct { /// Whether a key `kind` into terminal `pane` was predicted. 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 g = Term.grid(state); + if (Term.modes(state).alternate or g.offset + g.len < g.total or !g.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 }; - if (cur.row < top or cur.row - top >= vt.rows or e.n == max) return false; + const cur: Cursor = e.cursor orelse .{ .x = g.cursor_x, .row = top + g.cursor_y, .seq = 0 }; + if (cur.row < top or cur.row - top >= g.len or e.n == max) return false; var next: Cursor = .{ .x = cur.x, .row = cur.row, .seq = seq }; var cell: ?Cell = null; switch (kind) { @@ -250,7 +249,7 @@ pub const Echo = struct { // or a suggestion (fish's) being left: the shell redraws // what is right of it. ponytail: mosh's shift of the rest // would cover bash's middle, and mispredict fish's. - if (cur.x + 1 >= vt.cols) return false; + if (cur.x + 1 >= g.cols) return false; const under = e.cpAt(state, cur.x, cur.row); if (!blank(under) and under != cp) return false; cell = .{ .x = cur.x, .row = cur.row, .cp = cp, .was = under, .seq = seq }; @@ -270,7 +269,7 @@ pub const Echo = struct { // Over typed text only: past its end, fish takes the right // arrow for its suggestion (another colour). .right => { - if (cur.x + 1 >= vt.cols or !e.isText(state, cur.x, cur.row)) return false; + if (cur.x + 1 >= g.cols or !e.isText(state, cur.x, cur.row)) return false; next.x += 1; }, } @@ -297,40 +296,40 @@ pub const Echo = struct { } /// What the screen shows at a cell as predicted so far. - fn cpAt(e: *const Echo, state: *terminal.State, x: u16, row: u64) u21 { + fn cpAt(e: *const Echo, state: *Term.State, x: u16, row: u64) u21 { if (e.mine(x, row)) |have| return have.cp; return e.screenCp(state, x, row); } /// What the screen itself shows there; off its active area, a /// codepoint no key types. - fn screenCp(e: *const Echo, state: *terminal.State, x: u16, row: u64) u21 { - const ci = e.screenCell(state, x, row) orelse return 0x10ffff; - return ci.cell.codepoint(); + fn screenCp(e: *const Echo, state: *Term.State, x: u16, row: u64) u21 { + const c = e.screenCell(state, x, row) orelse return 0x10ffff; + return c.cp; } - fn screenCell(e: *const Echo, state: *terminal.State, x: u16, row: u64) ?terminal.PageCell { + fn screenCell(e: *const Echo, state: *Term.State, x: u16, row: u64) ?Term.EchoCell { const top = e.tops[e.pane]; - if (row < top or row - top >= state.vt.rows) return null; - return state.vt.screens.active.pages.getCell(.{ .active = .{ .x = x, .y = @intCast(row - top) } }); + if (row < top or row - top >= Term.grid(state).len) return null; + return Term.echoCell(state, x, @intCast(row - top)); } /// A prompt's input there, or a character predicted. - fn isInput(e: *const Echo, state: *terminal.State, x: u16, row: u64) bool { + fn isInput(e: *const Echo, state: *Term.State, x: u16, row: u64) bool { if (e.mine(x, row)) |have| return !blank(have.cp); - const ci = e.screenCell(state, x, row) orelse return false; - return ci.cell.semantic_content == .input; + const c = e.screenCell(state, x, row) orelse return false; + return c.input; } /// Typed text there: a character predicted, or a prompt's input in the /// colour of the cell before it. - fn isText(e: *const Echo, state: *terminal.State, x: u16, row: u64) bool { + fn isText(e: *const Echo, state: *Term.State, x: u16, row: u64) bool { if (e.mine(x, row)) |have| return !blank(have.cp); - const ci = e.screenCell(state, x, row) orelse return false; - if (ci.cell.semantic_content != .input or blank(ci.cell.codepoint())) return false; + const c = e.screenCell(state, x, row) orelse return false; + if (!c.input or blank(c.cp)) return false; if (x == 0) return true; const before = e.screenCell(state, x - 1, row) orelse return false; - return before.cell.style_id == ci.cell.style_id; + return before.style == c.style; } /// The authority confirmed its client's input `seq`. @@ -383,7 +382,7 @@ pub const Echo = struct { const pane = c.panes[e.pane] orelse return e.drop(); if (pane.serial != e.serial) return e.drop(); const state = pane.terminal orelse return e.drop(); - if (state.vt.screens.active_key != .primary) return e.drop(); + if (Term.modes(state).alternate) return e.drop(); const shown = e.visible(c); var i: usize = 0; while (i < e.n) { @@ -399,8 +398,8 @@ pub const Echo = struct { } e.stats.mispredicted += 1; if (std.c.getenv("PARDES_REPLICA_TRACE") != null) { - const cur = state.vt.screens.active.cursor; - std.debug.print("echo: key {d}'s {u} at {d},{d} not shown ({u} there) {d} ms past due; top {d}, the screen's cursor {d},{d}, acked {d}\n", .{ cell.seq, cell.cp, cell.x, cell.row, e.screenCp(state, cell.x, cell.row), (now - cell.due) / ms, e.tops[e.pane], cur.x, cur.y, e.acked }); + const cur = Term.grid(state); + std.debug.print("echo: key {d}'s {u} at {d},{d} not shown ({u} there) {d} ms past due; top {d}, the screen's cursor {d},{d}, acked {d}\n", .{ cell.seq, cell.cp, cell.x, cell.row, e.screenCp(state, cell.x, cell.row), (now - cell.due) / ms, e.tops[e.pane], cur.cursor_x, cur.cursor_y, e.acked }); } if (shown) e.doubt = true; e.trusted = false; @@ -423,8 +422,8 @@ pub const Echo = struct { } const cur = e.cursor orelse return; if (now < cur.due) return; - const screen = state.vt.screens.active; - if (screen.cursor.x == cur.x and e.tops[e.pane] + screen.cursor.y == cur.row) { + const g = Term.grid(state); + if (g.cursor_x == cur.x and e.tops[e.pane] + g.cursor_y == cur.row) { e.cursor = null; e.changed = true; } else if (now >= cur.due + slack) { @@ -448,7 +447,7 @@ pub const Echo = struct { if (id != e.pane or pane.serial != e.serial or p.live != e.view or pane.body.mode != .tty) return; if (!e.visible(p)) return; const state = pane.terminal orelse return; - const sb = state.vt.screens.active.pages.scrollbar(); + const sb = Term.grid(state); const top = e.tops[id]; // Off a prompt, the trust is inferred: underlined, as mosh does. const flag = !atPrompt(pane); @@ -532,7 +531,8 @@ 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); + const at = Term.prompt(state); + return !Term.modes(state).alternate and at.phase == .input and at.input_ready; } /// The terminal view `view`'s keys go to, in tty mode: none when they go @@ -642,7 +642,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 }; } @@ -651,6 +651,7 @@ const Rig = struct { const prompt = "\x1b]133;A;cl=line;aid=pardes\x07$ \x1b]133;B;aid=pardes\x07"; test "keys typed at a shell's prompt are drawn at once, and the authority's echo takes their place" { + if (pardes.Term.ops == null) return error.SkipZigTest; // it reads the emulator var g: Rig = undefined; try g.init(); defer g.deinit(); @@ -698,13 +699,14 @@ test "keys typed at a shell's prompt are drawn at once, and the authority's echo } test "a password prompt shows nothing typed, and a full-screen program is not predicted" { + if (pardes.Term.ops == null) return error.SkipZigTest; // it reads the emulator var g: Rig = undefined; try g.init(); defer g.deinit(); 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); @@ -729,6 +731,7 @@ test "a password prompt shows nothing typed, and a full-screen program is not pr } test "keys still on their way when their predictions go: the next waits for their echo, never predicted where it is about to land" { + if (pardes.Term.ops == null) return error.SkipZigTest; // it reads the emulator var g: Rig = undefined; try g.init(); defer g.deinit(); @@ -766,6 +769,7 @@ test "keys still on their way when their predictions go: the next waits for thei } test "a misprediction takes every prediction back and shows none until an echo is confirmed; after Tab nothing is predicted until its echo" { + if (pardes.Term.ops == null) return error.SkipZigTest; // it reads the emulator var g: Rig = undefined; try g.init(); defer g.deinit(); diff --git a/src/edit.zig b/src/edit.zig index c5466531..23c223d9 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 @@ -2114,6 +2311,7 @@ test "insert and normal modes edit complete Unicode graphemes" { } test "flat text replacement preserves a terminal fragment origin and direction" { + if (pardes.Term.ops == null) return error.SkipZigTest; // a shell const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 60, .rows = 12 }); defer p.deinit(); p.update(.{ .output = .{ .pane = 0, .bytes = "first\r\nsecond\r\nthird\r\n界a\r\n" } }); @@ -2241,6 +2439,7 @@ test "a typed edit's known end is where the texts' comparison would find it" { } test "a paste into a terminal is xterm's: bracketed when the program asked, control bytes spaces, so no ESC[201~ ends the brackets early" { + if (pardes.Term.ops == null) return error.SkipZigTest; // a shell const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .cols = 60, .rows = 16, .tty_only = true }); defer p.deinit(); diff --git a/src/exec.zig b/src/exec.zig index df578d08..5f5a2206 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; } @@ -165,44 +165,30 @@ pub fn operandAt(p: *Pardes, pane: *Pane, clicked: Pane.Sel, borrow: bool, for_l return result; } } - // In a diff, a file or hunk header, and a hunk line pointed at on its - // `+`/`-`/` ` prefix, expand to the whole line (the hover shows it) and - // the look is of the address it names (look.diffAddress), a regular - // look from there. A hunk line's code is words, looked at as ever: - // the code's, the prefix never one of them. - // A query pane's row pointed at on its gutter (its line number): the - // look is of the row's address (Query.rowAddress), as a +Diff line's - // prefix is its place; the row's code is words, looked at as ever. - if (for_look and pane.query != null and clicked.r0 >= pane.tag_rows and clicked.r0 == clicked.r1 and clicked.c0 == clicked.c1 and row >= 0 and col >= 0) gutter: { - var address_buf: [4096 + 32]u8 = undefined; - const address = panes.Query.rowAddress(pane, @intCast(row), @intCast(col), &address_buf) orelse break :gutter; - const meta = pane.file.?.location_rows[@intCast(row)]; - result.text = p.scratch.allocator().dupe(u8, address) catch break :gutter; - result.file_word = .{ .row = row, .lo = 0, .hi = @intCast(meta.location_end) }; - const expanded = fileWordCells(pane, clicked, row, 0, @intCast(meta.location_end)) orelse return result; - result.preview = expanded; - result.expanded = expanded; - return result; - } + // A row that names an address (look.rowAddressAt), pointed at on it: a + // query pane's row on its address (its gutter), a diff's file or hunk + // header anywhere, a hunk line on its `+`/`-`/` ` prefix. It expands + // to the address's text (the hover shows it) and the look is of the + // address, a regular look from there. A row's code is words, looked at + // as ever: the code's, the prefix never one of them. A click left of a + // query pane's text is no part of its row. var word_from: usize = 0; - if (for_look and clicked.r0 >= pane.tag_rows and clicked.r0 == clicked.r1 and clicked.c0 == clicked.c1 and row >= 0) diff: { + if (for_look and clicked.r0 >= pane.tag_rows and clicked.r0 == clicked.r1 and clicked.c0 == clicked.c1 and row >= 0 and (col >= 0 or pane.query == null)) row_address: { var address_buf: [4096 + 32]u8 = undefined; - const at: usize = @intCast(row); - const click = look.diffClick(p, pane, at, @intCast(@max(0, col)), &address_buf) orelse break :diff; - const address = click.address orelse { - word_from = click.word_from; - break :diff; + const got = look.rowAddressAt(p, pane, @intCast(row), @intCast(@max(0, col)), &address_buf) orelse break :row_address; + const address = got.address orelse { + word_from = got.word_from; + break :row_address; }; - const line = (look.diffLines(p, pane) orelse break :diff)[at]; - result.text = p.scratch.allocator().dupe(u8, address) catch break :diff; - const hi = std.math.cast(i32, line.len) orelse return result; + result.text = p.scratch.allocator().dupe(u8, address) catch break :row_address; + const hi = std.math.cast(i32, got.end) orelse return result; if (hi == 0) return result; var expanded = clicked; if (pane.file != null) { result.file_word = .{ .row = row, .lo = 0, .hi = hi }; expanded = fileWordCells(pane, clicked, row, 0, hi) orelse return result; } else { - const shown = if (raw) raw_line else line; + const shown = if (raw) raw_line else got.line; expanded.c0 = 0; expanded.c1 = @as(i32, @intCast(panes.File.rawDisplayCol(shown, shown.len))) - 1; } @@ -601,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: @@ -624,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; @@ -669,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); } @@ -710,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; @@ -726,7 +723,7 @@ pub fn executeFrom(p: *Pardes, id: usize, txt: []const u8, from_body: bool) ?usi /// is done, else a new one, placed as layout.placeNew places a command pane. /// A pane reused keeps what it showed: the new command runs below a line /// naming it, as acme appends to +Errors and never clears it (util.c:213). -fn runCommand(p: *Pardes, from: usize, line: []const u8) ?usize { +pub fn runCommand(p: *Pardes, from: usize, line: []const u8) ?usize { if (line.len > command_max) { p.reportFailure(from, "exec: a command line is at most 1024 bytes"); return null; @@ -770,10 +767,10 @@ 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()); @@ -823,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 @@ -906,6 +903,7 @@ pub fn executeBuiltinLine(p: *Pardes, id: usize, txt: []const u8) bool { } pub fn applyStartupConfig(p: *Pardes) void { + @import("Plumb.zig").boot(p); applyInitText(p, p.opts.startup_config orelse return, false); } diff --git a/src/fs-help.txt b/src/fs-help.txt index bc699418..9a87843d 100644 --- a/src/fs-help.txt +++ b/src/fs-help.txt @@ -19,13 +19,13 @@ recent files opened lately, closed ones too: open|closed <path> dumps the dumps the state file keeps, the newest first: <label> <date> <size> <panes> layout a line per column: serial index x width current|notcurrent empty|full pane-serials; then active <serial> tag the workspace tag, tagexec a word as a click in it; col/<serial>/ a column's tag, ctl, exec; rmdir: empty only +plumb/ rules: the plumber's rules, plumb(6)'s (a write adds rule sets, > replaces); send: write a message, six lines then data; <port>: read the messages sent to it pane/new open it to make a pane (<session dir>/+New) in the active column; the read answers its serial -pane/<n>/ name body tag ctl addr dot limit data xdata sel dirty mark scroll errors event look exec tagexec; rmdir closes +pane/<n>/ name body tag ctl addr dot limit data xdata sel dirty mark scroll errors event look exec tagexec rows; rmdir closes + rows: a line a row, kind (m c p; d decl, u unmarked) line col end_line end_col source_column location_end code_start styles path; styles - or N:start+len=role,... (keyword string number comment, add del emph line, joined by .); a write at 0 replaces on terminals pty/data (keys in, output out), pty/status, pty/ctl (winsize, sig, exec), pty/run (a line, its exit and output) os/, src/ the host filesystem; the editor's own sources - $m below: $PARDES_MOUNT (set under 9ns --mntgen); without it, 9p -a "unix!$PARDES_9P". - cat $m/index which panes exist n=$(cat $m/pane/new) make a pane of your own (each open makes one), take its serial exec 3<>$m/pane/$n/look; echo /etc/hosts:3 >&3; cat <&3 open a file through it, see the pane it went to @@ -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") }, @@ -948,6 +948,10 @@ pub const Namespace = struct { /// The editor-wide event ring: panes made, renamed, saved and closed, and /// what the editor said. Recorded whether or not anyone reads /log. log: tree.events.Queue = .{ .cap = limits.log_bytes }, + /// Messages a plumbing rule's `client` holds for a port no one reads + /// yet (Plumb.zig), each its port's index then the message packed: the + /// port's first reader takes them (plumber(4)'s queueheld). + plumb_held: tree.events.Queue = .{}, /// What the last look or exec created or touched, answered by reading /// either of those files. results: [MAX_PANES]u32 = undefined, @@ -969,6 +973,7 @@ pub const Namespace = struct { for (st.closed_lines.items) |*line| line.bytes.deinit(gpa); st.closed_lines.deinit(gpa); st.log.deinit(gpa); + st.plumb_held.deinit(gpa); st.out.deinit(gpa); } @@ -1088,6 +1093,7 @@ test "mount allocation failures preserve prior mounts and release partial copies } test "unmount refuses pane paths inherited directories and queued save targets" { + if (pardes.Term.ops == null) return error.SkipZigTest; // a shell const gpa = std.testing.allocator; const p = try pardes.Pardes.init(gpa, .{ .tty_only = true }); defer p.deinit(); diff --git a/src/grammar_manifest.zig b/src/grammar_manifest.zig index 38c54916..711c31a4 100644 --- a/src/grammar_manifest.zig +++ b/src/grammar_manifest.zig @@ -1,6 +1,7 @@ //! Dependency-free tree-sitter grammar metadata shared by build.zig and the -//! runtime syntax registry. Keep target symbols and query values out of this -//! file: the build runner imports it as host code. +//! runtime syntax registry, and the highlight-query filter the build runs. +//! Keep target symbols and query values out of this file: the build runner +//! imports it as host code. const std = @import("std"); @@ -14,6 +15,8 @@ pub const Grammar = struct { src: []const u8 = "src", scanner: bool = false, query: []const u8 = "queries/highlights.scm", + /// Patterns appended to the highlights query before it is filtered. + highlights_extra: []const u8 = "", }; pub const all = [_]Grammar{ @@ -48,7 +51,13 @@ pub const all = [_]Grammar{ .{ .name = "ruby", .dep = "ts_ruby", .exts = &.{ ".rb", ".rake" }, .tier = .full, .scanner = true }, .{ .name = "rust", .dep = "ts_rust", .exts = &.{".rs"}, .tier = .full, .scanner = true }, .{ .name = "scala", .dep = "ts_scala", .exts = &.{ ".scala", ".sc" }, .tier = .full, .scanner = true }, - .{ .name = "typst", .dep = "ts_typst", .exts = &.{ ".typ", ".typst" }, .tier = .full, .scanner = true, .query = "queries/typst/highlights.scm" }, + .{ .name = "typst", .dep = "ts_typst", .exts = &.{ ".typ", ".typst" }, .tier = .full, .scanner = true, .query = "queries/typst/highlights.scm", .highlights_extra = + \\ + \\(call item: (ident) @keyword) + \\(call item: (field field: (ident) @keyword)) + \\"#" @keyword + \\ + }, .{ .name = "zig", .dep = "ts_zig", .exts = &.{ ".zig", ".zon" }, .tier = .zig }, }; @@ -92,3 +101,96 @@ pub fn byPath(path: []const u8) ?usize { for (all, 0..) |g, i| for (g.exts) |e| if (std.ascii.eqlIgnoreCase(ext, e)) return i; return null; } + +/// pardes's syntax classes: what a capture colours a byte as. +pub const Syn = enum(u8) { none, keyword, string, number, comment }; + +pub fn synFor(name: []const u8) Syn { + for ([_]struct { []const u8, Syn }{ + .{ "comment", .comment }, + .{ "string", .string }, + .{ "character", .string }, + .{ "number", .number }, + .{ "numeric", .number }, + .{ "float", .number }, + .{ "boolean", .number }, + .{ "keyword", .keyword }, + .{ "include", .keyword }, + .{ "conditional", .keyword }, + .{ "repeat", .keyword }, + .{ "title", .keyword }, + .{ "uri", .string }, + .{ "reference", .number }, + .{ "heading", .keyword }, + .{ "strong", .comment }, + .{ "bold", .comment }, + .{ "emphasis", .number }, + .{ "italic", .number }, + .{ "literal", .string }, + .{ "raw", .string }, + }) |m| { + if (std.mem.indexOf(u8, name, m[0]) != null) return m[1]; + } + return .none; +} + +/// The patterns of highlights query `source` that capture a class (synFor), +/// written to `out` (source.len bytes): what a grammar's query compiles to. +/// build.zig filters each one with it, ts_queries' `<name>_highlights`. +pub fn colorQuery(source: []const u8, out: []u8) []u8 { + var written: usize = 0; + var at: usize = 0; + while (at < source.len) { + while (at < source.len) { + if (std.ascii.isWhitespace(source[at])) { + at += 1; + } else if (source[at] == ';') { + while (at < source.len and source[at] != '\n') at += 1; + } else break; + } + const begin = at; + var depth: usize = 0; + var colored = false; + var complete = false; + while (at < source.len) { + const byte = source[at]; + if (complete and (byte == '(' or byte == '[' or byte == '"')) break; + if (byte == ';') { + while (at < source.len and source[at] != '\n') at += 1; + continue; + } + if (byte == '"') { + at += 1; + while (at < source.len) : (at += 1) { + if (source[at] == '\\') { + at += 1; + } else if (source[at] == '"') { + at += 1; + break; + } + } + if (depth == 0) complete = true; + continue; + } + if (byte == '(' or byte == '[') depth += 1; + if (byte == ')' or byte == ']') { + depth -= 1; + if (depth == 0) complete = true; + } + if (byte == '@') { + const name = at + 1; + at = name; + while (at < source.len and (std.ascii.isAlphanumeric(source[at]) or + source[at] == '_' or source[at] == '.' or source[at] == '-')) at += 1; + colored = colored or synFor(source[name..at]) != .none; + continue; + } + at += 1; + } + if (colored) { + @memcpy(out[written..][0 .. at - begin], source[begin..at]); + written += at - begin; + } + } + return out[0..written]; +} diff --git a/src/gui/gui.zig b/src/gui/gui.zig index 98527842..aa6fc92b 100644 --- a/src/gui/gui.zig +++ b/src/gui/gui.zig @@ -10,7 +10,6 @@ const posix = std.posix; /// libc: pipes and fcntl for the window's wakes, and a test harness's capture files written from the render thread. const libc = std.c; const vaxis = @import("vaxis"); // test modes only: the stdin escape-seq parser -const ghostty_vt = @import("ghostty-vt"); // 256-color palette for .index cells const pardes = @import("../pardes.zig"); const vaxis_input = @import("../vaxis_input.zig"); const dump = @import("../dump.zig"); @@ -184,7 +183,6 @@ const opaque_bg_bit = Cells.opaque_bg_bit; const OverlayColor = struct { r: f32, g: f32, b: f32, a: f32 }; - const PreparedImage = struct { premultiplied: bool = false, place: pardes.Placement, @@ -498,7 +496,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, @@ -676,12 +674,12 @@ fn fixedCellLayout(g: *const Gui) CellLayout { const Group = Cells.Group; /// The frame's draw groups, bottom to top: the page and the panes, the -/// notices floating over them, the guides and the debug box the core paints -/// over those, and ink (the bar cursors; the cursor's glide draws after it). +/// notices floating over them, the debug box the core paints over those, +/// and ink (the bar cursors; the cursor's glide draws after it). const Groups = struct { items: [4]Group = @splat(.{}), notices: usize = 1, - guides: usize = 2, + debug: usize = 2, ink: usize = 3, len: usize = 4, }; @@ -691,7 +689,7 @@ const Groups = struct { const Cover = packed struct(u16) { /// A layer draws it; the grid's copy is not drawn. layer: bool = false, - /// Under a guide or the debug box: drawn from the grid over the panes. + /// Under the debug box: drawn from the grid over the panes. floating: bool = false, /// In a pane's grip, `grip_offset` cells from its left: the grip's /// glyph is the cell that far to the left. @@ -758,7 +756,7 @@ fn coverFrame(cover: []Cover, cols: u16, rows: u16, body_layers: []const pardes. mark.rect(cover, cols, rows, .{ .x = region.rect.x, .y = 0, .w = 1, .h = rows }, "anchor", true); if (region.active) if (bar) |b| mark.rect(cover, cols, rows, .{ .x = region.rect.x, .y = b.y, .w = region.rect.w, .h = b.h }, "focus", true); }, - .guide, .debug => mark.rect(cover, cols, rows, region.rect, "floating", true), + .debug => mark.rect(cover, cols, rows, region.rect, "floating", true), else => {}, }; } @@ -1350,11 +1348,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; @@ -2135,7 +2133,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. @@ -2658,6 +2656,7 @@ const Shell = struct { .set_clipboard = setClipboard, .read_clipboard = readClipboard, .open_link = openLink, + .start = host_io.startDetached, .lsp = lsp, .pipe = pipe, .search = search, @@ -4137,7 +4136,7 @@ fn renderFrame( while (col < surface.cols) : (col += 1) { const at = @as(usize, row) * surface.cols + col; if (covered[at].layer and !covered[at].floating) continue; - const group_index = if (covered[at].floating) groups.guides else 0; + const group_index = if (covered[at].floating) groups.debug else 0; groups.items[group_index].cell_count = std.math.add(u32, groups.items[group_index].cell_count, cellInstanceCount(&surface.cells[at])) catch return error.GpuCapacity; } } @@ -4183,7 +4182,7 @@ fn renderFrame( while (col < surface.cols) : (col += 1) { const at = @as(usize, row) * surface.cols + col; if (covered[at].layer and !covered[at].floating) continue; - const group_index = if (covered[at].floating) groups.guides else 0; + const group_index = if (covered[at].floating) groups.debug else 0; emitSurfaceCell( g, chrome, @@ -4274,12 +4273,12 @@ fn resolveCell(g: *Gui, line: []const pardes.Cell, at: usize, cursor: ?usize, ro const st = cell.style; fg = switch (st.fg) { .default => fg_default, - .index => |i| palColor(i), + .index => |i| pardes.colors.xterm[i], .rgb => |rgb| rgb, }; switch (st.bg) { .default => {}, - .index => |i| bg = palColor(i), + .index => |i| bg = pardes.colors.xterm[i], .rgb => |rgb| bg = rgb, } if (st.reverse) reverse = !reverse; @@ -4651,11 +4650,6 @@ fn cellCodepoint(cell: *const pardes.Cell) u32 { return if (cell.default or grapheme.len == 0) ' ' else firstCp(grapheme); } -fn palColor(idx: u8) [3]u8 { - const p = ghostty_vt.color.default[idx]; - return .{ p.r, p.g, p.b }; -} - fn firstCp(s: []const u8) u32 { if (s.len == 0) return ' '; const n = std.unicode.utf8ByteSequenceLength(s[0]) catch return ' '; @@ -4802,7 +4796,7 @@ fn cellSlot(g: *Gui, line: []const pardes.Cell, at: usize, cursor: ?usize, role: // An underlined or struck-out space is a glyph of its own: it draws its line. if (here.cp == ' ' and !here.decoration.drawsBlank()) return g.atlas.space_slot; if (ruleArms(here.cp) != null) - return cachedGlyph(g, .{ .face = 0, .glyph = here.cp, .role = @enumFromInt(@intFromEnum(role)), .rule = true }) orelse g.atlas.space_slot; + return cachedGlyph(g, .{ .face = 0, .glyph = here.cp, .role = @fromBackingInt(@intCast(@backingInt(role))), .rule = true }) orelse g.atlas.space_slot; const gpa = g.atlas.glyphs.allocator; const cell_key: Words.CellKey = .{ .cp = @intCast(here.cp), .role = role, .decoration = here.decoration }; const known = words.cells.getOrPut(gpa, cell_key) catch return g.atlas.space_slot; @@ -4811,7 +4805,7 @@ fn cellSlot(g: *Gui, line: []const pardes.Cell, at: usize, cursor: ?usize, role: known.value_ptr.* = if (role == .body and g.atlas.substitutes(drawn.face, drawn.glyph)) Words.shape_slot else - cachedGlyph(g, .{ .face = drawn.face, .glyph = drawn.glyph, .role = @enumFromInt(@intFromEnum(role)), .decoration = @bitCast(here.decoration) }) orelse g.atlas.space_slot; + cachedGlyph(g, .{ .face = drawn.face, .glyph = drawn.glyph, .role = @fromBackingInt(@intCast(@backingInt(role))), .decoration = @bitCast(here.decoration) }) orelse g.atlas.space_slot; } const plain = known.value_ptr.*; if (!std.meta.eql(plain, Words.shape_slot)) return plain; @@ -6145,7 +6139,6 @@ test "installed Nerd Symbols fallback covers Yazi directory icons" { try std.testing.expect(atlas.glyphForCodepoint(0xe5ff).glyph != 0); } - test "GUI PTY reader delivers a real shell tail before EOF and joins on close" { const gpa = std.testing.allocator; const core = try pardes.Pardes.init(gpa, .{ .tty_only = true }); @@ -6440,7 +6433,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..b086b5fe 100644 --- a/src/host_io.zig +++ b/src/host_io.zig @@ -59,6 +59,9 @@ pub const Host = struct { set_clipboard: ?*const fn (ctx: ?*anyopaque, text: []const u8) void = null, read_clipboard: ?*const fn (ctx: ?*anyopaque) void = null, open_link: ?*const fn (ctx: ?*anyopaque, url: []const u8) void = null, + /// A plumbing rule's program (Effect.start): every host's is + /// startDetached. Null once it runs, else why not. + start: ?*const fn (ctx: ?*anyopaque, line: []const u8, why: []u8) ?[]const u8 = null, lsp: ?*const fn (ctx: ?*anyopaque, req: Lsp.Request) void = null, pipe: ?*const fn (ctx: ?*anyopaque, id: u32) void = null, /// Start the streaming search of this generation on a worker @@ -173,13 +176,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(); } @@ -268,6 +271,9 @@ pub const Fallback = struct { files: std.StringHashMapUnmanaged([]u8) = .empty, clipboard: std.ArrayListUnmanaged(u8) = .empty, link: std.ArrayListUnmanaged(u8) = .empty, + /// The programs plumbing rules started, as Effect.start packs them, + /// one a line. + started: std.ArrayListUnmanaged(u8) = .empty, spawned: [pardes.MAX_PANES]bool = @splat(false), watched: [pardes.MAX_PANES]bool = @splat(false), @@ -280,6 +286,7 @@ pub const Fallback = struct { f.files.deinit(f.gpa); f.clipboard.deinit(f.gpa); f.link.deinit(f.gpa); + f.started.deinit(f.gpa); } pub fn writeFile(f: *Fallback, path: []const u8, bytes: []const u8) bool { @@ -315,6 +322,12 @@ pub const Fallback = struct { f.link.clearRetainingCapacity(); f.link.appendSlice(f.gpa, url) catch {}; } + + pub fn start(f: *Fallback, line: []const u8) ?[]const u8 { + f.started.appendSlice(f.gpa, line) catch return "out of memory"; + f.started.append(f.gpa, '\n') catch return "out of memory"; + return null; + } }; /// What a pixel host's loop takes from its workers, in order: each pane's @@ -855,6 +868,7 @@ pub const Lsp = struct { } test "a snapshot owns every byte the backend will read" { + if (pardes.Term.ops == null) return error.SkipZigTest; // a terminal pane's snapshot const gpa = std.testing.allocator; const core = try pardes.Pardes.init(gpa, .{ .tty_only = true }); defer core.deinit(); @@ -2456,6 +2470,108 @@ const darwin = struct { } }; +/// A program a plumbing rule starts (Effect.start), as Plan 9's plumber +/// starts one (match.c's startup): out of the editor's way, a session of +/// its own reaped by init, stdin, stdout and stderr /dev/null and no other +/// fd of the editor's, its argv exec'd (no shell: a rule that wants one +/// says `sh -c`) in its directory. `line` is its directory, then its argv, +/// each ended by a NUL. Null once it runs, else why not, as errno says it, +/// in `why` (as the tape replays a host's words): a pipe closed at the +/// exec carries the child's errno back. +pub fn startDetached(_: ?*anyopaque, line: []const u8, why: []u8) ?[]const u8 { + const words = startWords(line) orelse return null; + const n = @min(words.len, why.len); + @memcpy(why[0..n], words[0..n]); + return why[0..n]; +} + +fn startWords(line: []const u8) ?[]const u8 { + var buf: [pardes.effect_path_cap]u8 = undefined; + if (line.len == 0 or line.len > buf.len or line[line.len - 1] != 0) return "malformed"; + @memcpy(buf[0..line.len], line); + var argv: [64:null]?[*:0]const u8 = @splat(null); + var n: usize = 0; + var at: usize = 0; + var dir: [*:0]const u8 = undefined; + while (at < line.len) { + const end = std.mem.indexOfScalarPos(u8, line, at, 0).?; + const word: [*:0]const u8 = @ptrCast(&buf[at]); + if (at == 0) dir = word else if (n < argv.len) { + argv[n] = word; + n += 1; + } else return "more than 64 words"; + at = end + 1; + } + if (n == 0) return "no program"; + var fds: [2]c_int = undefined; + if (libc.pipe(&fds) != 0) return "no pipe"; + for (fds) |fd| _ = libc.fcntl(fd, libc.F.SETFD, @as(c_int, libc.FD_CLOEXEC)); + const first = libc.fork(); + if (first < 0) { + _ = libc.close(fds[0]); + _ = libc.close(fds[1]); + return "no fork"; + } + if (first == 0) { + // Only async-signal-safe calls between fork and exec. + _ = libc.setsid(); + if (libc.fork() != 0) libc._exit(0); + resetChildSignals(); + // What failed, then errno: 'd' the directory, 'x' the exec. + const Fail = struct { + fn say(fd: c_int, what: u8) noreturn { + var said: [5]u8 = undefined; + said[0] = what; + std.mem.writeInt(u32, said[1..5], @intFromEnum(libc.errno(-1)), .little); + _ = libc.write(fd, &said, said.len); + libc._exit(127); + } + }; + const err_fd = libc.fcntl(fds[1], libc.F.DUPFD_CLOEXEC, @as(c_int, 3)); + if (err_fd < 0) libc._exit(127); + if (dir[0] != 0 and libc.chdir(dir) != 0) Fail.say(err_fd, 'd'); + const null_fd = libc.open("/dev/null", .{ .ACCMODE = .RDWR }, @as(libc.mode_t, 0)); + if (null_fd >= 0) for (0..3) |i| { + _ = libc.dup2(null_fd, @intCast(i)); + }; + // Every fd of the editor's but the errno pipe's gone: a pty's + // master held open would keep its terminal alive. + if (libc.dup2(err_fd, 3) < 0) libc._exit(127); + _ = libc.fcntl(3, libc.F.SETFD, @as(c_int, libc.FD_CLOEXEC)); + const shut = if (comptime builtin.os.tag == .linux) + std.os.linux.close_range(4, std.math.maxInt(i32), .{ .UNSHARE = false, .CLOEXEC = false }) == 0 + else + false; + if (!shut) { + var fd: c_int = 4; + while (fd < 1024) : (fd += 1) _ = libc.close(fd); + } + _ = execvp(argv[0].?, &argv); + Fail.say(3, 'x'); + } + _ = libc.close(fds[1]); + while (libc.waitpid(first, null, 0) < 0 and libc.errno(-1) == .INTR) {} + var said: [5]u8 = undefined; + var got: usize = 0; + while (got < said.len) { + const r = libc.read(fds[0], said[got..].ptr, said.len - got); + if (r < 0 and libc.errno(r) == .INTR) continue; + if (r <= 0) break; + got += @intCast(r); + } + _ = libc.close(fds[0]); + if (got < said.len) return null; + const code = std.mem.readInt(u32, said[1..5], .little); + const E = libc.E; + if (code == @intFromEnum(E.NOENT)) return if (said[0] == 'd') "its directory: no such directory" else "not found"; + if (code == @intFromEnum(E.ACCES)) return "permission denied"; + if (code == @intFromEnum(E.NOTDIR)) return "not a directory"; + if (code == @intFromEnum(E.NOEXEC)) return "not an executable"; + return if (said[0] == 'd') "its directory: cannot go there" else "cannot start it"; +} + +extern "c" fn execvp(file: [*:0]const u8, argv: [*:null]const ?[*:0]const u8) c_int; + /// A terminal pane's shell is done with (its pane gone, its pty closed or at /// end of file): say hangup, for a shell that ignores the tty's, and see it /// reaped, killed if it is still there 100 ms on. A thread does the waiting @@ -3004,6 +3120,8 @@ pub fn writeFile(core: *pardes.Pardes, watches: *file_watch.Table, pane: u8, pat core.setMessage(pane, pardes.Messages.Message.stamp(&mbuf, "saved", path)); // The init file, saved here (Config): its settings take effect now. pardes.exec.reapplyInitFile(core, path, bytes); + // The plumbing file (Plumb): its rules in force now. + pardes.Plumb.saved(core, pane, path, bytes); } /// A Dump's write: into the state file under a label of its own @@ -3446,6 +3564,7 @@ test "Kill stops the foreground job, never the shell, and finds none with job co } test "a command pane's child is its shell running the one line, and its exit status is read at the end" { + if (pardes.Term.ops == null) return error.SkipZigTest; // a command pane if (comptime !tty_probe_platform) return error.SkipZigTest; const core = try pardes.Pardes.init(std.testing.allocator, .{ .tty_only = true }); defer core.deinit(); @@ -3468,6 +3587,7 @@ test "a command pane's child is its shell running the one line, and its exit sta } test "a command's exit is its process's, told by its watcher, whether or not its pty has ended" { + if (pardes.Term.ops == null) return error.SkipZigTest; // a command pane if (comptime !tty_probe_platform) return error.SkipZigTest; const core = try pardes.Pardes.init(std.testing.allocator, .{ .tty_only = true }); defer core.deinit(); @@ -3501,6 +3621,7 @@ test "a command's exit is its process's, told by its watcher, whether or not its } test "a command's background job outlives it and its pty, and Kill stops its whole line, its & jobs too" { + if (pardes.Term.ops == null) return error.SkipZigTest; // a command pane if (comptime !tty_probe_platform) return error.SkipZigTest; if (!haveFile("/bin/sh")) return error.SkipZigTest; const core = try pardes.Pardes.init(std.testing.allocator, .{ .tty_only = true }); @@ -3863,3 +3984,12 @@ test "LSP query answers, and a newer one cancels it" { core.update(.{ .lsp_resp = .{ .id = last, .rows = batch.items[0].lsp.rows } }); try std.testing.expect(core.lsp_ask.wait == null); } + +test "a plumbing rule's program starts detached, or says why not: a program not found, a directory not there" { + if (comptime builtin.os.tag != .linux) return; + var why: [64]u8 = undefined; + try std.testing.expect(startDetached(null, "/\x00true\x00", &why) == null); + try std.testing.expectEqualStrings("not found", startDetached(null, "/\x00no-such-program-x\x00", &why).?); + try std.testing.expectEqualStrings("its directory: no such directory", startDetached(null, "/no/such/dir\x00true\x00", &why).?); + try std.testing.expectEqualStrings("malformed", startDetached(null, "/\x00true", &why).?); +} diff --git a/src/hunks.zig b/src/hunks.zig index 8f4b4233..2fa86ccd 100644 --- a/src/hunks.zig +++ b/src/hunks.zig @@ -6,21 +6,48 @@ //! a tinted ground as delta emphasises them (its edits.rs and align.rs, here as `inferEdits` //! and `Alignment`). const std = @import("std"); -const pardes = @import("pardes.zig"); const diff = @import("diff.zig"); const syntax = @import("syntax.zig"); const locations = @import("locations.zig"); +const pardes = @import("pardes.zig"); const Pardes = pardes.Pardes; +const Pane = pardes.Pane; +const Output = pardes.panes.Output; + const Row = locations.Row; +/// What `format` takes of the editor it stacks for: its allocators, the +/// files a diff names read as the editor reads them (in pardes an open +/// pane's text, else the disk's, each read a site of the step's tape: +/// openDiff), their declarations, and one setting. +pub const Ctx = struct { + /// The text and rows made, the caller's. + gpa: std.mem.Allocator, + /// All else, the call's. + arena: std.mem.Allocator, + /// `path` as a look from `dir` finds it, its text the arena's (or the + /// editor's, good for the call); null when it is not there. + source: *const fn (ctx: *const Ctx, dir: []const u8, path: []const u8) ?Source, + /// The declarations of `bytes`, the file at `path`, outermost first + /// (syntax.analyzeSource's), the arena's. + declarations: *const fn (ctx: *const Ctx, path: []const u8, bytes: []const u8) error{OutOfMemory}![]const syntax.ContextDeclaration, + /// The two above's own. + host: *anyopaque, + /// A declaration above a hunk gets its `path:line` row too + /// (LocationsConfig's tslocations). + tslocations: bool, +}; + +/// A file's text, and its path as `dir` and the path named resolve. +pub const Source = struct { path: []const u8, bytes: []const u8 }; + /// The rows `content`, a diff, stacks to, for a pane in `dir`, with each -/// row's metadata (Output.fillRows). Text and rows are `p.gpa`'s; all else -/// is the step's scratch. -pub fn format(p: *Pardes, dir: []const u8, content: []const u8) !locations.Result { - const arena = p.scratch.allocator(); +/// row's metadata (Output.fillRows). Text and rows are `ctx.gpa`'s. +pub fn format(ctx: *const Ctx, dir: []const u8, content: []const u8) !locations.Result { + const arena = ctx.arena; const styles = try syntax.highlightDiff(arena, content, 0, content.len); - var out: Out = .{ .p = p, .text = .init(p.gpa) }; + var out: Out = .{ .gpa = ctx.gpa, .text = .init(ctx.gpa) }; errdefer out.deinit(); var walk: diff.Walk = .{}; var hunk: Hunk = .{}; @@ -46,7 +73,7 @@ pub fn format(p: *Pardes, dir: []const u8, content: []const u8) !locations.Resul // A `\ No newline` belongs to the line above, as delta shows it. .no_newline => {}, else => { - try flush(&out, &hunk, &source, dir); + try flush(ctx, &out, &hunk, &source, dir); switch (got.kind) { .hunk => hunk = .{ .path = walk.path(), @@ -69,9 +96,9 @@ pub fn format(p: *Pardes, dir: []const u8, content: []const u8) !locations.Resul } at = nl + 1; } - try flush(&out, &hunk, &source, dir); - const rows = try out.rows.toOwnedSlice(p.gpa); - errdefer locations.freeRows(p.gpa, rows); + try flush(ctx, &out, &hunk, &source, dir); + const rows = try out.rows.toOwnedSlice(ctx.gpa); + errdefer locations.freeRows(ctx.gpa, rows); return .{ .content = try out.text.toOwnedSlice(), .rows = rows, .anchor = null }; } @@ -105,13 +132,13 @@ fn gitContext(line: []const u8) []const u8 { } const Out = struct { - p: *Pardes, + gpa: std.mem.Allocator, text: std.Io.Writer.Allocating, rows: std.ArrayList(Row) = .empty, fn deinit(out: *Out) void { out.text.deinit(); - locations.freeRowList(out.p.gpa, &out.rows); + locations.freeRowList(out.gpa, &out.rows); } const Meta = struct { @@ -127,7 +154,7 @@ const Out = struct { fn row(out: *Out, text: []const u8, path: []const u8, meta: Meta) !void { try out.text.writer.writeAll(text); try out.text.writer.writeByte('\n'); - try locations.appendRow(out.p.gpa, &out.rows, .{ + try locations.appendRow(out.gpa, &out.rows, .{ .kind = meta.kind, .declaration = meta.declaration, .path = @constCast(path), @@ -153,7 +180,7 @@ const SourceMemo = struct { /// Where a +Diff of `content`, a diff in `dir`, stands: the directory its /// first file is found from (`dir` or one above it, as `findSource` looks), /// so its rows name their files as the diff does; `dir` when none is found. -pub fn sourceRoot(p: *Pardes, dir: []const u8, content: []const u8) []const u8 { +pub fn sourceRoot(ctx: *const Ctx, dir: []const u8, content: []const u8) []const u8 { var walk: diff.Walk = .{}; var lines = std.mem.splitScalar(u8, content, '\n'); const path = while (lines.next()) |line| { @@ -161,31 +188,27 @@ pub fn sourceRoot(p: *Pardes, dir: []const u8, content: []const u8) []const u8 { } else return dir; var base: []const u8 = dir; for (0..8) |_| { - if (locations.sourceText(p, p.scratch.allocator(), base, path) != null) return base; + if (ctx.source(ctx, base, path) != null) return base; base = std.Io.Dir.path.dirname(base) orelse return dir; } return dir; } -fn findSource(p: *Pardes, memo: *SourceMemo, dir: []const u8, path: []const u8) !void { +fn findSource(ctx: *const Ctx, memo: *SourceMemo, dir: []const u8, path: []const u8) !void { if (std.mem.eql(u8, memo.path, path)) return; - const arena = p.scratch.allocator(); + const arena = ctx.arena; memo.* = .{ .path = path }; // ponytail: eight directories up; a repository deeper than that under // its patch is looked for from the patch's own directory only. var base: []const u8 = dir; for (0..8) |_| { - if (locations.sourceText(p, arena, base, path)) |text| { + if (ctx.source(ctx, base, path)) |text| { memo.shown = if (base.ptr == dir.ptr) path else try std.Io.Dir.path.relativePosix(arena, "/", dir, text.path); var lines: std.ArrayList([]const u8) = .empty; var split = std.mem.splitScalar(u8, text.bytes, '\n'); while (split.next()) |line| try lines.append(arena, std.mem.trimEnd(u8, line, "\r")); memo.lines = lines.items; - var hit = p.locations_cache.get(p.tree_sitter_gpa, text.path, text.bytes, true, false) catch - locations.Cache.Hit{ .analysis = syntax.analyzeSource(arena, text.path, text.bytes, true, false) catch .{} }; - defer hit.deinit(p.tree_sitter_gpa); - // The cache's may go at its next use: kept for the section. - memo.declarations = try arena.dupe(syntax.ContextDeclaration, hit.analysis.declarations); + memo.declarations = try ctx.declarations(ctx, text.path, text.bytes); return; } base = std.Io.Dir.path.dirname(base) orelse return; @@ -251,12 +274,11 @@ fn heldAt(memo: *const SourceMemo, hunk: *const Hunk, comptime side: Side, start return .{ .held = held, .of = @max(of, 1) }; } -fn flush(out: *Out, hunk: *Hunk, memo: *SourceMemo, dir: []const u8) !void { +fn flush(ctx: *const Ctx, out: *Out, hunk: *Hunk, memo: *SourceMemo, dir: []const u8) !void { defer hunk.* = .{}; if (hunk.path.len == 0 or hunk.lines.items.len == 0) return; - const p = out.p; - const arena = p.scratch.allocator(); - try findSource(p, memo, dir, hunk.path); + const arena = ctx.arena; + try findSource(ctx, memo, dir, hunk.path); const disk = sideOnDisk(memo, hunk); const side = disk.side; // A line number of the hunk's, where the file has it now. @@ -287,7 +309,7 @@ fn flush(out: *Out, hunk: *Hunk, memo: *SourceMemo, dir: []const u8) !void { var row = declaration.start_line; while (row <= declaration.header_end_line and row < start_row) : (row += 1) { const at: @FieldType(Row, "at") = .{ .line = row + 1 }; - if (row == declaration.start_line and p.locations_config.tslocations) { + if (row == declaration.start_line and ctx.tslocations) { const label = try std.fmt.allocPrint(arena, "{s}:{d}", .{ shown, row + 1 }); try out.row(label, shown, .{ .kind = .context, .declaration = true, .at = at, .location_end = label.len, .code_start = label.len }); } @@ -331,10 +353,10 @@ fn flush(out: *Out, hunk: *Hunk, memo: *SourceMemo, dir: []const u8) !void { // has it: the marker coloured, the line as its file's. for (lines) |line| { const flag: u8 = switch (line.kind) { - .added => syntax.diff_added, - .removed => syntax.diff_removed, + .added => syntax.ground_add, + .removed => syntax.ground_del, else => 0, - } | @as(u8, if (line.kind != .context and !line.paired) syntax.diff_whole else 0); + } | @as(u8, if (line.kind != .context and !line.paired) syntax.ground_line else 0); const text = try std.fmt.allocPrint(arena, "{c}{s}", .{ @as(u8, switch (line.kind) { .added => '+', .removed => '-', @@ -389,10 +411,10 @@ fn inferEdits(arena: std.mem.Allocator, minus: []HunkLine, plus: []HunkLine) !vo const marks = annotate(pair, &alignment, m.code, plus[j].code) catch continue; if (marks.distance > max_line_distance) continue; for (marks.minus) |r| for (m.styles[r[0]..r[1]]) |*b| { - b.* |= syntax.diff_emph; + b.* |= syntax.ground_emph; }; for (marks.plus) |r| for (plus[j].styles[r[0]..r[1]]) |*b| { - b.* |= syntax.diff_emph; + b.* |= syntax.ground_emph; }; m.paired = true; plus[j].paired = true; @@ -574,16 +596,226 @@ fn annotate(arena: std.mem.Allocator, a: *const Alignment, minus_line: []const u } fn trimmedWidth(section: []const u8) usize { - return pardes.panes.File.displayWidth(std.mem.trim(u8, section, " \t")); + return @import("File.zig").displayWidth(std.mem.trim(u8, section, " \t")); +} + +// ---- the +Diff in the editor ---- +// +// Its word (Diff), the open and the text it goes back to, and the +// restack of a paged diff. A bare look at a .diff, a commit hash and a +// paged diff are plumbing rules (src/plumbing) that start Diff or ask the +// edit port to show the diff (Plumb.show). + +/// The `Diff` word (builtins.zig registers it). Bare, on a +Diff, the diff +/// it stacks as text; on a diff, its hunks stacked in a +Diff. With a file +/// (a .diff, a .patch: relative to the pane's directory), its hunks +/// stacked so; with a revision (7 to 40 lowercase hex digits, a letter and +/// a digit among them), `git show` of it, paged into a +Pager that stacks +/// its hunks (ctl.fillPager), run in the pane's git work tree. A plumbing +/// rule's Diff that cannot (no hunk, no work tree) declines, saying +/// nothing (Pardes.plumb_declined), and the look looks itself. +pub fn word(c: pardes.builtins.Ctx) void { + const p = c.p; + const arg = std.mem.trim(u8, c.arg orelse "", " \t\r\n"); + if (arg.len == 0) { + if (!shows(c.pane)) return p.reportFailure(c.id, "Diff: only a diff or a +Diff pane takes it"); + const f = &c.pane.file.?; + if (diffSource(p, f)) |source| return showDiffText(p, c.id, source); + _ = openDiff(p, c.id, f.path, f.content) catch |err| switch (err) { + error.NoHunks => p.reportFailure(c.id, "Diff: no hunk in it"), + else => p.reportError(c.id, "hunks", err), + }; + return; + } + if (isCommitHash(arg)) { + var dir = pardes.filesystem.localPath(Pardes.paneDir(c.pane)) orelse return declined(p, c.id, "Diff: not in a git work tree"); + while (true) { + var buf: [4096]u8 = undefined; + const dot_git = std.fmt.bufPrint(&buf, "{s}/.git", .{dir}) catch return declined(p, c.id, "Diff: not in a git work tree"); + if (pardes.exec.kindOf(dot_git) != null) break; + dir = std.Io.Dir.path.dirname(dir) orelse return declined(p, c.id, "Diff: not in a git work tree"); + } + // ponytail: a hex word that names no commit leaves git's error in a command pane, not a search; check the object first if that bites. + var line: [64]u8 = undefined; + const dst = pardes.exec.execute(p, c.id, std.fmt.bufPrint(&line, "git show {s}", .{arg}) catch unreachable) orelse return; + if (p.panes[dst]) |cp| cp.command_pages = true; + return; + } + var buf: [4096]u8 = undefined; + const path = if (arg[0] == '/') arg else std.fmt.bufPrint(&buf, "{s}/{s}", .{ std.mem.trimEnd(u8, Pardes.paneDir(c.pane), "/"), arg }) catch arg; + const bytes = pardes.filesystem.read(p, path) catch |err| { + if (p.plumb_declined != null) return declined(p, c.id, ""); + return p.reportError(c.id, path, err); + }; + defer p.gpa.free(bytes); + p.view().active = openDiff(p, c.id, path, bytes) catch |err| switch (err) { + error.NoHunks => return declined(p, c.id, "Diff: no hunk in it"), + else => { + if (p.plumb_declined != null) return declined(p, c.id, ""); + return p.reportError(c.id, "hunks", err); + }, + }; +} + +/// A Diff that cannot do what it was asked: a plumbing rule's declines, +/// saying nothing; one typed says `why`. +fn declined(p: *Pardes, id: usize, why: []const u8) void { + if (p.plumb_declined) |*d| { + d.* = true; + return; + } + p.reportFailure(id, why); +} + +/// A pane the bare word works on: a diff (a .diff, a .patch, a +Pager +/// holding one) or a +Diff. +fn shows(pane: *const Pane) bool { + const f = pane.file orelse return false; + return pane.colorAlgo() == .diff or (f.output != null and std.meta.eql(f.output.?.from, Output.Origin{ .cmd = .Diff })); +} + +/// A pane holding a diff (a +Pager filled with one: `git show`, difftui's +/// patches; the edit port's `showdiff`, Plumb.show): its hunks stacked in +/// a +Diff in its place, the pane closed. The keyboard stays where it was, +/// as a page's. +pub fn paged(p: *Pardes, id: usize) void { + const f = &p.panes[id].?.file.?; + const keyboard = p.view().active; + if (openDiff(p, id, f.path, f.content)) |hid| { + // ponytail: the text is gone with it; Diff on the +Diff says no such file. + p.removePane(id, hid) catch |err| p.reportError(id, "pager", err); + } else |_| {} + if (p.panes[keyboard] != null) p.view().active = keyboard; +} + +fn isCommitHash(hex: []const u8) bool { + if (hex.len < 7 or hex.len > 40) return false; + var digit = false; + var letter = false; + for (hex) |c| switch (c) { + '0'...'9' => digit = true, + 'a'...'f' => letter = true, + else => return false, + }; + return digit and letter; +} + +/// Diff: `content`, the diff at `path` (a file, a +Pager), stacked as a +/// diff viewer shows it (format), in a +Diff where its files are found +/// (sourceRoot), placed by pane `id`, refilled when it is there. Its +/// arg names the diff (its base name, or its whole path when the +Diff +/// stands elsewhere), for Diff to go back to it; a commit's (`git show`, a +/// mailed patch) is named for it too, `+Diff-<12 hex>`, so each commit +/// keeps a +Diff of its own. The +Diff's id; NoHunks when there is none in +/// it. +pub fn openDiff(p: *Pardes, id: usize, path: []const u8, content: []const u8) !usize { + const dir = std.Io.Dir.path.dirname(path) orelse p.sessionDir(); + // Each file read is a site of the step's tape (fs.zig): a replica + // replays the authority's bytes and reads no disk of its own. + const Read = struct { + fn source(ctx: *const Ctx, from: []const u8, name: []const u8) ?Source { + const pp: *Pardes = @ptrCast(@alignCast(ctx.host)); + const text = locations.sourceText(pp, ctx.arena, from, name) orelse return null; + return .{ .path = text.path, .bytes = text.bytes }; + } + fn declarations(ctx: *const Ctx, name: []const u8, bytes: []const u8) error{OutOfMemory}![]const syntax.ContextDeclaration { + const pp: *Pardes = @ptrCast(@alignCast(ctx.host)); + var hit = pp.locations_cache.get(pp.tree_sitter_gpa, name, bytes, true, false) catch + locations.Cache.Hit{ .analysis = syntax.analyzeSource(ctx.arena, name, bytes, true, false) catch .{} }; + defer hit.deinit(pp.tree_sitter_gpa); + // The cache's may go at its next use: kept for the call. + return ctx.arena.dupe(syntax.ContextDeclaration, hit.analysis.declarations); + } + }; + const ctx: Ctx = .{ + .gpa = p.gpa, + .arena = p.scratch.allocator(), + .source = Read.source, + .declarations = Read.declarations, + .host = p, + .tslocations = p.locations_config.tslocations, + }; + const root = sourceRoot(&ctx, dir, content); + const result = try format(&ctx, root, content); + errdefer { + p.gpa.free(result.content); + locations.freeRows(p.gpa, result.rows); + } + var has_hunk = false; + for (result.rows) |row| has_hunk = has_hunk or row.kind == .match; + if (!has_hunk) return error.NoHunks; + const arg = if (std.mem.eql(u8, root, dir) or path.len > Output.max_arg) std.Io.Dir.path.basename(path) else path; + var name_buf: [pardes.config.diff_buffer.len + 13]u8 = undefined; + const name = if (diff.commitHash(content)) |hash| + std.fmt.bufPrint(&name_buf, "{s}-{s}", .{ pardes.config.diff_buffer, hash[0..@min(hash.len, 12)] }) catch unreachable + else + null; + return Output.fillRows(p, id, root, .{ .cmd = .Diff }, name, arg, result.content, result.rows, null); +} + +/// Diff on a +Diff: the diff it stacks, as text. A pane holding it +/// already (the newest: a +Pager folded under its +Diff unfolds) is +/// shown; else the file is opened as text. +pub fn showDiffText(p: *Pardes, id: usize, source: []const u8) void { + var newest: ?usize = null; + for (p.panes, 0..) |slot, i| { + const f = (slot orelse continue).file orelse continue; + if (!std.mem.eql(u8, f.path, source)) continue; + if (newest == null or p.panes[newest.?].?.serial < slot.?.serial) newest = i; + } + if (newest) |i| { + if (p.panes[i].?.collapsed) pardes.layout.toggleCollapse(p, i); + p.view().active = i; + return; + } + p.look_text = true; + defer p.look_text = false; + pardes.look.lookAt(p, id, source); +} + +/// The diff a +Diff stacks (openDiff's arg): its path. +pub fn diffSource(p: *Pardes, f: *const pardes.panes.File.State) ?[]const u8 { + const o = f.output orelse return null; + if (!std.meta.eql(o.from, Output.Origin{ .cmd = .Diff })) return null; + const arg = o.arg(); + if (arg.len > 0 and arg[0] == '/') return arg; + return std.Io.Dir.path.join(p.scratch.allocator(), &.{ std.Io.Dir.path.dirname(f.path) orelse "", arg }) catch null; } // ---- tests ---- const testing = std.testing; +/// A Ctx over the disk, as the editor's is without panes or a cache. +const TestCtx = struct { + arena_state: std.heap.ArenaAllocator, + ctx: Ctx, + + fn init(t: *TestCtx) void { + t.arena_state = .init(testing.allocator); + t.ctx = .{ .gpa = testing.allocator, .arena = t.arena_state.allocator(), .source = source, .declarations = declarations, .host = t, .tslocations = true }; + syntax.start(testing.allocator); + } + + fn deinit(t: *TestCtx) void { + syntax.stop(); + t.arena_state.deinit(); + } + + fn source(ctx: *const Ctx, dir: []const u8, path: []const u8) ?Source { + const full = std.Io.Dir.path.resolvePosix(ctx.arena, &.{ dir, path }) catch return null; + const bytes = std.Io.Dir.cwd().readFileAlloc(testing.io, full, ctx.arena, .limited(1 << 20)) catch return null; + return .{ .path = full, .bytes = bytes }; + } + + fn declarations(ctx: *const Ctx, path: []const u8, bytes: []const u8) error{OutOfMemory}![]const syntax.ContextDeclaration { + return (syntax.analyzeSource(ctx.arena, path, bytes, true, false) catch return &.{}).declarations; + } +}; + fn emphasised(line: HunkLine) ![]const u8 { var out: std.ArrayList(u8) = .empty; - for (line.code, line.styles) |c, s| try out.append(testing.allocator, if (s & syntax.diff_emph != 0) c else '.'); + for (line.code, line.styles) |c, s| try out.append(testing.allocator, if (s & syntax.ground_emph != 0) c else '.'); return out.toOwnedSlice(testing.allocator); } @@ -631,8 +863,9 @@ test "delta's alignment: kitten to sitting, as align.rs has it" { } test "a diff stacks to a label a hunk and its lines, markers gone, tinted and stepped" { - const p = try Pardes.init(testing.allocator, .{ .tty_only = true }); - defer p.deinit(); + var t: TestCtx = undefined; + t.init(); + defer t.deinit(); const patch = \\diff --git a/nowhere/x.txt b/nowhere/x.txt \\--- a/nowhere/x.txt @@ -644,28 +877,29 @@ test "a diff stacks to a label a hunk and its lines, markers gone, tinted and st \\ tail \\ ; - const result = try format(p, "/pardes-surely-missing-dir", patch); - defer p.gpa.free(result.content); - defer locations.freeRows(p.gpa, result.rows); + const result = try format(&t.ctx, "/pardes-surely-missing-dir", patch); + defer testing.allocator.free(result.content); + defer locations.freeRows(testing.allocator, result.rows); try testing.expectEqualStrings("nowhere/x.txt:2\n section one\n keep\n-old value\n+new value\n tail\n", result.content); try testing.expectEqual(@as(usize, 6), result.rows.len); try testing.expectEqual(.match, result.rows[0].kind); try testing.expectEqual(@as(usize, "nowhere/x.txt:2".len), result.rows[0].location_end); try testing.expect(result.rows[1].declaration); const removed = result.rows[3]; - try testing.expect(removed.colors[0] & syntax.diff_removed != 0); + try testing.expect(removed.colors[0] & syntax.ground_del != 0); // Paired with the line it changed: no whole-line tint. - try testing.expect(removed.colors[0] & syntax.diff_whole == 0); - try testing.expect(removed.colors[1] & syntax.diff_emph != 0); - try testing.expect(removed.colors[5] & syntax.diff_emph == 0); - try testing.expect(result.rows[4].colors[0] & syntax.diff_added != 0); - try testing.expect(result.rows[2].colors[0] & (syntax.diff_added | syntax.diff_removed) == 0); + try testing.expect(removed.colors[0] & syntax.ground_line == 0); + try testing.expect(removed.colors[1] & syntax.ground_emph != 0); + try testing.expect(removed.colors[5] & syntax.ground_emph == 0); + try testing.expect(result.rows[4].colors[0] & syntax.ground_add != 0); + try testing.expect(result.rows[2].colors[0] & (syntax.ground_add | syntax.ground_del) == 0); } test "a hunk the file has moved since is found where it went, inside its declaration" { if (!syntax.supportsPath("a.zig")) return error.SkipZigTest; - const p = try Pardes.init(testing.allocator, .{ .tty_only = true }); - defer p.deinit(); + var t: TestCtx = undefined; + t.init(); + defer t.deinit(); var tmp = testing.tmpDir(.{}); defer tmp.cleanup(); // Two lines more above it than the patch knows of. @@ -682,16 +916,17 @@ test "a hunk the file has moved since is found where it went, inside its declara \\ b(); \\ ; - const result = try format(p, dir, patch); - defer p.gpa.free(result.content); - defer locations.freeRows(p.gpa, result.rows); + const result = try format(&t.ctx, dir, patch); + defer testing.allocator.free(result.content); + defer locations.freeRows(testing.allocator, result.rows); try testing.expect(std.mem.indexOf(u8, result.content, "a.zig:3\n const S = struct {\na.zig:5 *\n") != null); try testing.expect(std.mem.indexOf(u8, result.content, "git's guess") == null); } test "a mailed patch keeps its headers, message and diffstat above its hunks" { - const p = try Pardes.init(testing.allocator, .{ .tty_only = true }); - defer p.deinit(); + var t: TestCtx = undefined; + t.init(); + defer t.deinit(); const patch = \\From 0123 Mon Sep 17 00:00:00 2001 \\Subject: [PATCH] change x @@ -709,9 +944,9 @@ test "a mailed patch keeps its headers, message and diffstat above its hunks" { \\+b \\ ; - const result = try format(p, "/pardes-surely-missing-dir", patch); - defer p.gpa.free(result.content); - defer locations.freeRows(p.gpa, result.rows); + const result = try format(&t.ctx, "/pardes-surely-missing-dir", patch); + defer testing.allocator.free(result.content); + defer locations.freeRows(testing.allocator, result.rows); try testing.expectEqualStrings("From 0123 Mon Sep 17 00:00:00 2001\nSubject: [PATCH] change x\n\nWhy it changed.\n---\n x.txt | 2 +-\n\nx.txt:1\n-a\n+b\n", result.content); } @@ -755,8 +990,9 @@ test "a .patch looked at opens its +Diff, and Diff goes to the text and back" { test "a hunk edited since, beside siblings with its signature's tail, is found in its own function" { if (!syntax.supportsPath("a.rs")) return error.SkipZigTest; - const p = try Pardes.init(testing.allocator, .{ .tty_only = true }); - defer p.deinit(); + var t: TestCtx = undefined; + t.init(); + defer t.deinit(); var tmp = testing.tmpDir(.{}); defer tmp.cleanup(); // Three functions ending in one signature's tail; the patch is for the @@ -799,9 +1035,9 @@ test "a hunk edited since, beside siblings with its signature's tail, is found i \\ c \\ ; - const result = try format(p, dir, patch); - defer p.gpa.free(result.content); - defer locations.freeRows(p.gpa, result.rows); + const result = try format(&t.ctx, dir, patch); + defer testing.allocator.free(result.content); + defer locations.freeRows(testing.allocator, result.rows); try testing.expect(std.mem.indexOf(u8, result.content, "a.rs:12\n fn three(\na.rs:15 *\n") != null); } @@ -837,3 +1073,13 @@ test "patch panes keep different commits and reuse only the same commit" { try testing.expectEqual(first, try Page.open(p, a)); try testing.expectEqualStrings(original, p.panes[first].?.file.?.content); } + +test "a commit hash is 7 to 40 lowercase hex digits with a letter and a digit" { + try std.testing.expect(isCommitHash("9bffa7041c")); + try std.testing.expect(isCommitHash("9bffa7041cd2e8a0b6b1f7c3e4d5a6b7c8d9e0f1")); + try std.testing.expect(!isCommitHash("9bffa7")); + try std.testing.expect(!isCommitHash("defaced")); + try std.testing.expect(!isCommitHash("1234567")); + try std.testing.expect(!isCommitHash("0x9bffa7041c")); + try std.testing.expect(!isCommitHash("9BFFA7041C")); +} diff --git a/src/keys.zig b/src/keys.zig index 49ed00c0..8b67a9d1 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 @@ -482,6 +523,7 @@ fn leaderKey(p: *Pardes, key: Key) void { } test "Esc back into a tty leaves its view at the prompt" { + if (pardes.Term.ops == null) return error.SkipZigTest; // a shell, opened by a key const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }); defer p.deinit(); @@ -508,7 +550,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 +559,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" { @@ -637,6 +679,7 @@ test "Del from a key asks which neighbour takes the rows; nothing else asks" { } test "raw tty Esc backs out and Shift-Esc is the program's Esc" { + if (pardes.Term.ops == null) return error.SkipZigTest; // a shell, opened by a key const p = try Pardes.init(std.testing.allocator, .{ .cols = 80, .rows = 24, .file = "mise.toml" }); defer p.deinit(); _ = exec.spawnTty(p, 0); @@ -723,6 +766,7 @@ test "raw tty Ctrl-B switches to editor mode without sending child input" { } test "raw tty forwards Ctrl letters and former global shortcuts to the child" { + if (pardes.Term.ops == null) return error.SkipZigTest; // a shell const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true }); defer p.deinit(); var buf: [256]u8 = undefined; @@ -762,7 +806,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 fca4c846..7719af38 100644 --- a/src/layout.zig +++ b/src/layout.zig @@ -180,8 +180,8 @@ pub fn columnDrop(p: *const Pardes, source: usize, x: u16, grab: u16) ColumnDrop } /// Share out the width of columns `left` and `left + 1` so the left one is -/// `left_width` cells, neither below MINW. A border drag and a column grip -/// dropped inside its own place both end here. +/// `left_width` cells, neither below MINW. A column grip dropped inside its +/// own place ends here. pub fn setColumnPairWidth(p: *Pardes, left: usize, left_width: u64) void { const v = p.view(); if (left + 1 >= v.ncol) return; @@ -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 @@ -1650,6 +1650,7 @@ fn weightsOf(p: *const Pardes) [MAX_COLS]u64 { } test "collapse transfers height upward and restores the original layout" { + if (pardes.Term.ops == null) return error.SkipZigTest; // a shell const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 80, .rows = 32 }); defer p.deinit(); _ = try p.newShell(1, ""); @@ -1674,6 +1675,7 @@ test "collapse transfers height upward and restores the original layout" { } test "collapse changes only one neighbor at the top middle and bottom" { + if (pardes.Term.ops == null) return error.SkipZigTest; // a shell for (0..4) |target| { const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 80, .rows = 58 }); defer p.deinit(); @@ -1698,6 +1700,7 @@ test "collapse changes only one neighbor at the top middle and bottom" { } test "collapse skips folded neighbors and expansion reclaims only its neighbor" { + if (pardes.Term.ops == null) return error.SkipZigTest; // a shell const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 80, .rows = 62 }); defer p.deinit(); for (1..5) |id| { @@ -1725,6 +1728,7 @@ test "collapse skips folded neighbors and expansion reclaims only its neighbor" } test "collapse local transfers remain bounded through repeated tiny window resizes" { + if (pardes.Term.ops == null) return error.SkipZigTest; // a shell const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 80, .rows = 58 }); defer p.deinit(); for (1..5) |id| { @@ -1772,6 +1776,7 @@ test "collapse expansion is limited to space available in one neighbor" { } test "collapse single and all panes leave unused column space" { + if (pardes.Term.ops == null) return error.SkipZigTest; // a shell const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 80, .rows = 32 }); defer p.deinit(); toggleCollapse(p, 0); @@ -1788,6 +1793,7 @@ test "collapse single and all panes leave unused column space" { } test "collapse survives tiny resizes" { + if (pardes.Term.ops == null) return error.SkipZigTest; // a shell const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 80, .rows = 32 }); defer p.deinit(); _ = try p.newShell(1, ""); @@ -1813,6 +1819,7 @@ test "collapse survives tiny resizes" { } test "collapse can be expanded by dragging its boundary" { + if (pardes.Term.ops == null) return error.SkipZigTest; // a shell const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 80, .rows = 32 }); defer p.deinit(); _ = try p.newShell(1, ""); @@ -1998,6 +2005,7 @@ test "an attachment survives Dump and Restore, and one left away from its owner } test "a new column takes width only from the column that created it" { + if (pardes.Term.ops == null) return error.SkipZigTest; // a shell const p = try Pardes.init(std.testing.allocator, .{ .cols = 124, .rows = 24 }); defer p.deinit(); @@ -2061,6 +2069,7 @@ test "a new column takes width only from the column that created it" { } test "Newcol refuses an unsplittable restored weight before spawning" { + if (pardes.Term.ops == null) return error.SkipZigTest; // a shell const p = try Pardes.init(std.testing.allocator, .{ .cols = 200, .rows = 20 }); defer p.deinit(); @@ -2092,6 +2101,7 @@ test "Newcol refuses an unsplittable restored weight before spawning" { } test "repeated non-dyadic column splits preserve every unrelated boundary" { + if (pardes.Term.ops == null) return error.SkipZigTest; // a shell const p = try Pardes.init(std.testing.allocator, .{ .cols = 979, .rows = 20 }); defer p.deinit(); @@ -2099,15 +2109,7 @@ test "repeated non-dyadic column splits preserve every unrelated boundary" { try std.testing.expect(splitColumn(p, 0, 1, false)); p.sync(); - const handle = p.view().col_x[0] + p.view().col_w[0] - 1; - const untouched = weightsOf(p); - p.update(.{ .mouse = .{ .button = .left, .kind = .press, .col = handle, .row = TOPBAR_H + 1 } }); - p.update(.{ .mouse = .{ .button = .left, .kind = .release, .col = handle, .row = TOPBAR_H + 1 } }); - try std.testing.expectEqual(untouched, weightsOf(p)); - - p.update(.{ .mouse = .{ .button = .left, .kind = .press, .col = handle, .row = TOPBAR_H + 1 } }); - p.update(.{ .mouse = .{ .button = .left, .kind = .drag, .col = 417, .row = TOPBAR_H + 1 } }); - p.update(.{ .mouse = .{ .button = .left, .kind = .release, .col = 417, .row = TOPBAR_H + 1 } }); + setColumnPairWidth(p, 0, 418); p.sync(); try std.testing.expectEqual(@as(u16, 418), p.view().rects[0].w); diff --git a/src/lib_syntax.zig b/src/lib_syntax.zig index 395a02f0..a25af884 100644 --- a/src/lib_syntax.zig +++ b/src/lib_syntax.zig @@ -51,6 +51,25 @@ pub const SourceAnalysis = syntax.SourceAnalysis; pub const ContextDeclaration = syntax.ContextDeclaration; pub const analyzeSource = syntax.analyzeSource; +/// A unified diff as a language: `diff` walks one a line at a time +/// (`Walk`: a line's kind, the file its section names, the hunk's line +/// numbers) and says what a row of it points at (`targetAt`); +/// `highlightDiff` is a style byte for each byte of `content[start..end]`, +/// the caller's to free: headers as comments, `@@` lines as keywords, each +/// hunk's code in the language of the file its section names (old and new +/// side each parsed whole), and over that an added or removed line's +/// grounds (`ground_add`, `ground_del`; its first byte `ground_emph`, the +/// strong row). A byte's low bits (`syn_bits`) are a `Syn`; `Grounds` are +/// a theme's colours for the rest. +pub const diff = @import("diff.zig"); +pub const highlightDiff = syntax.highlightDiff; +pub const syn_bits = syntax.syn_bits; +pub const ground_add = syntax.ground_add; +pub const ground_del = syntax.ground_del; +pub const ground_emph = syntax.ground_emph; +pub const ground_line = syntax.ground_line; +pub const Grounds = colors.Grounds; + /// The tree-sitter bindings a tree is read through: `tree.rootNode()`, and /// a node's `kind()`, `startByte()`, `endByte()`, `child(i)`, `parent()`. pub const ts = syntax.ts; diff --git a/src/locations.zig b/src/locations.zig index fc39f92d..ca6b7a7d 100644 --- a/src/locations.zig +++ b/src/locations.zig @@ -103,6 +103,135 @@ pub fn equalRows(a: []const Row, b: []const Row) bool { return true; } +// ---- rows as text: a pane's `rows` file (ninep/pane.zig) ---- + +/// Rows as text, a line a row, its fields one blank apart and its path +/// last (a path may hold blanks): its kind (`m` a match n/N step to, `c` +/// context, `p` a preview of source; then `d` when it is a declaration and +/// `u` when its occurrence is not marked), its place (line, col, end_line, +/// end_col; 0 for none), source_column, location_end and code_start (byte +/// offsets in its line), its styles and its path. Styles are `-` for none, +/// else how many bytes they cover from code_start, a colon and the runs +/// that are not plain, `start+len=role`, comma-separated: a role is a +/// syntax class (keyword string number comment) and grounds (add del emph +/// line, syntax.ground_add's), joined by dots. `p 12 0 0 0 0 0 0 +/// 9:0+1=add.line,5+3=keyword.add src/a.zig`. +pub fn formatRows(rows: []const Row, w: *std.Io.Writer) std.Io.Writer.Error!void { + for (rows) |r| { + try w.writeByte(switch (r.kind) { + .match => 'm', + .context => 'c', + .preview => 'p', + }); + if (r.declaration) try w.writeByte('d'); + if (!r.mark_occurrence) try w.writeByte('u'); + try w.print(" {d} {d} {d} {d} {d} {d} {d} ", .{ r.at.line, r.at.col, r.at.end_line, r.at.end_col, r.source_column, r.location_end, r.code_start }); + if (r.colors.len == 0) try w.writeByte('-') else try w.print("{d}:", .{r.colors.len}); + var sep = false; + var at: usize = 0; + while (at < r.colors.len) { + const style = r.colors[at]; + var end = at + 1; + while (end < r.colors.len and r.colors[end] == style) end += 1; + defer at = end; + if (style == 0) continue; + if (sep) try w.writeByte(','); + sep = true; + try w.print("{d}+{d}=", .{ at, end - at }); + var dot = false; + const syn = style & syntax.syn_bits; + if (syn != 0) { + if (std.enums.fromInt(syntax.Syn, syn)) |known| try w.writeAll(@tagName(known)) else try w.print("{d}", .{syn}); + dot = true; + } + for (grounds) |g| if (style & g[0] != 0) { + if (dot) try w.writeByte('.'); + try w.writeAll(g[1]); + dot = true; + }; + } + try w.print(" {s}\n", .{r.path}); + } +} + +const grounds = [_]struct { u8, []const u8 }{ .{ syntax.ground_add, "add" }, .{ syntax.ground_del, "del" }, .{ syntax.ground_emph, "emph" }, .{ syntax.ground_line, "line" } }; + +/// formatRows' text read back, the rows and all they own `arena`'s. +/// BadRows for a line that is not one; a last newline ends the last row. +pub fn parseRows(arena: std.mem.Allocator, text: []const u8) error{ OutOfMemory, BadRows }![]Row { + const body = if (std.mem.endsWith(u8, text, "\n")) text[0 .. text.len - 1] else text; + if (body.len == 0) return &.{}; + var rows: std.ArrayList(Row) = .empty; + var lines = std.mem.splitScalar(u8, body, '\n'); + while (lines.next()) |line| { + var fields: [9][]const u8 = undefined; + var at: usize = 0; + for (&fields) |*field| { + const blank = std.mem.indexOfScalarPos(u8, line, at, ' ') orelse return error.BadRows; + field.* = line[at..blank]; + at = blank + 1; + } + const kind = fields[0]; + if (kind.len == 0) return error.BadRows; + var row: Row = .{ + .kind = switch (kind[0]) { + 'm' => .match, + 'c' => .context, + 'p' => .preview, + else => return error.BadRows, + }, + .path = try arena.dupe(u8, line[at..]), + .at = .{}, + .location_end = 0, + .code_start = 0, + }; + for (kind[1..]) |flag| switch (flag) { + 'd' => row.declaration = true, + 'u' => row.mark_occurrence = false, + else => return error.BadRows, + }; + var numbers: [7]usize = undefined; + for (&numbers, fields[1..8]) |*n, field| n.* = std.fmt.parseInt(usize, field, 10) catch return error.BadRows; + row.at = .{ .line = numbers[0], .col = numbers[1], .end_line = numbers[2], .end_col = numbers[3] }; + row.source_column = numbers[4]; + row.location_end = numbers[5]; + row.code_start = numbers[6]; + const styles = fields[8]; + if (!std.mem.eql(u8, styles, "-")) { + const colon = std.mem.indexOfScalar(u8, styles, ':') orelse return error.BadRows; + const len = std.fmt.parseInt(usize, styles[0..colon], 10) catch return error.BadRows; + // A line is never longer than a file: bounded before it is made. + if (len > @import("memory.zig").limits.max_file_bytes) return error.BadRows; + row.colors = try arena.alloc(u8, len); + @memset(row.colors, 0); + var runs = std.mem.splitScalar(u8, styles[colon + 1 ..], ','); + while (runs.next()) |run| { + if (run.len == 0) continue; + const plus = std.mem.indexOfScalar(u8, run, '+') orelse return error.BadRows; + const eq = std.mem.indexOfScalarPos(u8, run, plus, '=') orelse return error.BadRows; + const start = std.fmt.parseInt(usize, run[0..plus], 10) catch return error.BadRows; + const n = std.fmt.parseInt(usize, run[plus + 1 .. eq], 10) catch return error.BadRows; + if (start > len or n > len - start) return error.BadRows; + var style: u8 = 0; + var names = std.mem.splitScalar(u8, run[eq + 1 ..], '.'); + names: while (names.next()) |name| { + for (grounds) |g| if (std.mem.eql(u8, name, g[1])) { + style |= g[0]; + continue :names; + }; + if (style & syntax.syn_bits != 0) return error.BadRows; + const syn: u8 = if (std.meta.stringToEnum(syntax.Syn, name)) |known| @backingInt(known) else std.fmt.parseInt(u4, name, 10) catch return error.BadRows; + if (syn == 0) return error.BadRows; + style |= syn; + } + @memset(row.colors[start..][0..n], style); + } + } + try rows.append(arena, row); + } + return rows.items; +} + /// Compare native producer rows with an already formatted, context-free view. /// Identical refreshes retain allocations, syntax and selection state. pub fn sameInput(input: []const u8, rendered: []const u8, rows: []const Row, layout: Config.Layout) bool { @@ -984,3 +1113,50 @@ test "locations cache transfers oversized completed analysis without reparsing" try std.testing.expectEqual(@as(usize, 0), cache.len); try std.testing.expectEqual(@as(usize, 0), cache.bytes); } + +test "rows read back from their text are the rows: +Search's, +Callstack's and +Diff's" { + const testing = std.testing; + const p = try pardes.Pardes.init(testing.allocator, .{ .tty_only = true }); + defer p.deinit(); + var tmp = testing.tmpDir(.{}); + defer tmp.cleanup(); + try tmp.dir.writeFile(testing.io, .{ .sub_path = "a.zig", .data = "const S = struct {\n fn f() void {\n a(\"x y\");\n b();\n }\n};\n" }); + var buf: [std.Io.Dir.max_path_bytes]u8 = undefined; + const dir = buf[0..try tmp.dir.realPath(testing.io, &buf)]; + const patch = try std.Io.Dir.path.join(testing.allocator, &.{ dir, "c.patch" }); + defer testing.allocator.free(patch); + const search = try format(p, dir, "a.zig:3:9 a(\"x y\");\na.zig:4:9 b();\n", null, true); + defer p.gpa.free(search.content); + defer freeRows(p.gpa, search.rows); + const callstack = try formatCallstack(p, dir, "a.zig:2:8 f\n└─ a.zig:3:9 a\n"); + defer p.gpa.free(callstack.content); + defer freeRows(p.gpa, callstack.rows); + const hid = try @import("hunks.zig").openDiff(p, 0, patch, "--- a.zig\n+++ a.zig\n@@ -2,3 +2,4 @@\n fn f() void {\n- a(\"x\");\n+ a(\"x y\");\n+ b();\n }\n"); + const stacked = p.panes[hid].?.file.?.location_rows; + // A +Diff's rows carry styles with grounds: the codec is tried on them. + var grounded = false; + for (stacked) |row| for (row.colors) |c| { + grounded = grounded or c & syntax.ground_add != 0; + }; + try testing.expect(grounded and search.rows.len > 0 and callstack.rows.len > 0); + var arena_state: std.heap.ArenaAllocator = .init(testing.allocator); + defer arena_state.deinit(); + const arena = arena_state.allocator(); + for ([_][]const Row{ search.rows, callstack.rows, stacked }) |rows| { + var text: std.Io.Writer.Allocating = .init(arena); + try formatRows(rows, &text.writer); + const back = try parseRows(arena, text.written()); + try testing.expect(equalRows(rows, back)); + var again: std.Io.Writer.Allocating = .init(arena); + try formatRows(back, &again.writer); + try testing.expectEqualStrings(text.written(), again.written()); + } + try testing.expectError(error.BadRows, parseRows(arena, "x 1 0 0 0 0 0 0 - a\n")); + try testing.expectError(error.BadRows, parseRows(arena, "m 1 0 0 0 0 0 0 2:0+3=keyword a\n")); + try testing.expectError(error.BadRows, parseRows(arena, "m 1 0 0 0 0 0 0 2:0+1=keyword.string a\n")); + try testing.expectError(error.BadRows, parseRows(arena, "m 1 0 0\n")); + const one = try parseRows(arena, "pd 12 3 0 0 0 0 0 4:0+1=add.line,1+2=keyword.add src/a b.zig\n"); + try testing.expectEqualStrings("src/a b.zig", one[0].path); + try testing.expect(one[0].declaration and one[0].kind == .preview and one[0].at.line == 12 and one[0].at.col == 3); + try testing.expectEqualSlices(u8, &.{ syntax.ground_add | syntax.ground_line, @backingInt(syntax.Syn.keyword) | syntax.ground_add, @backingInt(syntax.Syn.keyword) | syntax.ground_add, 0 }, one[0].colors); +} diff --git a/src/look.zig b/src/look.zig index 082565ed..136a7a9c 100644 --- a/src/look.zig +++ b/src/look.zig @@ -4,6 +4,7 @@ const builtin = @import("builtin"); const libc = std.c; const pardes = @import("pardes.zig"); const exec = @import("exec.zig"); +const Plumb = @import("Plumb.zig"); const config = @import("config.zig"); const diff = @import("diff.zig"); const platform_has_fs = filesystem.platform_has_fs; @@ -152,56 +153,6 @@ pub fn lineSpan(p: ?*pardes.Pardes, line: []const u8, cwd: []const u8, realbuf: return null; } -/// Where a `Plumb` rule sends what it matched: the targets the built-in -/// rules below make (url: the browser, through `xdg-open`), or a loaded -/// kind by its name (`image`, `pdf`). -pub const Port = enum { url, dir, file }; - -/// A rule as `Plumb` takes it, plumb(6)'s order on one line: `<test> -/// [word ...] to <port>`, the test `prefix` (the text starts so), `suffix` -/// (an existing file's name ends so, any case), `isdir` or `isfile`; the -/// port `url`, `dir`, `file` or a kind `kinds` has. -/// Null when it is one; otherwise what is wrong with it, said. -pub fn plumbRuleError(kinds: *const Kind.Registry, rule: []const u8) ?[]const u8 { - var words = std.mem.tokenizeAny(u8, rule, " \t"); - const how = words.next() orelse return "a rule: <test> [word ...] to <port>"; - const takes = if (std.mem.eql(u8, how, "prefix") or std.mem.eql(u8, how, "suffix")) - true - else if (std.mem.eql(u8, how, "isdir") or std.mem.eql(u8, how, "isfile")) - false - else - return "invalid test: prefix, suffix, isdir or isfile"; - var n: usize = 0; - while (words.next()) |w| : (n += 1) { - if (!std.mem.eql(u8, w, "to")) continue; - if (takes and n == 0) return "invalid rule: prefix and suffix take a word"; - if (!takes and n > 0) return "invalid rule: isdir and isfile take no word"; - const port = words.next() orelse return "invalid rule: to names no port"; - if (std.meta.stringToEnum(Port, port) == null and kinds.byName(port) == null) - return "invalid port: url, dir, file or a loaded kind"; - if (words.next() != null) return "invalid rule: a word after the port"; - return null; - } - return "invalid rule: no `to <port>`"; -} - -/// What a rule's port makes of what it matched; null when it cannot (no -/// such file, a directory to `file`, a kind gone since): the next rule tries. -fn plumbTarget(p: *pardes.Pardes, port: []const u8, text: []const u8, found: ?filesystem.Resolved, at: Spot) ?Target { - const to = std.meta.stringToEnum(Port, port); - if (to == .url) return .{ .url = if (found) |f| f.path else text }; - const f = found orelse return null; - if (to == null) { - const k = p.kinds.byName(port) orelse return null; - return if (f.dir) null else .{ .kind = .{ .path = f.path, .kind = k, .at = at } }; - } - return switch (to.?) { - .url => unreachable, - .dir => if (f.dir) .{ .dir = f.path } else null, - .file => if (f.dir) null else .{ .file = .{ .path = f.path, .at = at } }, - }; -} - pub fn resolve(p: ?*pardes.Pardes, word_raw: []const u8, cwd: []const u8, realbuf: *[4096]u8) Target { const trimmed = std.mem.trim(u8, word_raw, " \t\r\n"); const pl = parsePathLine(trimmed); @@ -224,42 +175,6 @@ pub fn resolve(p: ?*pardes.Pardes, word_raw: []const u8, cwd: []const u8, realbu } } - if (p) |pp| if (pp.plumb.items.len > 0) { - var found: ?filesystem.Resolved = null; - var looked = false; - for (pp.plumb.items) |rule| { - var words = std.mem.tokenizeAny(u8, rule, " \t"); - const how = words.next() orelse continue; - // The file is asked about once, and only by a rule that needs it. - const prefix = std.mem.eql(u8, how, "prefix"); - if (!looked and !prefix) { - found = filesystem.resolve(p, word, cwd, realbuf); - looked = true; - } - const file = if (found) |f| !f.dir else false; - var hit = std.mem.eql(u8, how, "isfile") and file or - std.mem.eql(u8, how, "isdir") and found != null and !file; - var port: []const u8 = ""; - while (words.next()) |w| { - if (std.mem.eql(u8, w, "to")) { - port = words.next() orelse ""; - break; - } - if (prefix and std.mem.startsWith(u8, trimmed, w)) hit = true; - // A suffix is a file's: plumb's basic pairs each with `arg isfile`. - if (std.mem.eql(u8, how, "suffix") and file and std.ascii.endsWithIgnoreCase(found.?.path, w)) hit = true; - } - if (!hit) continue; - const url = std.mem.eql(u8, port, "url"); - if (!looked and !url) { - found = filesystem.resolve(p, word, cwd, realbuf); - looked = true; - } - // A prefix rule's url is the text, never a file it also names. - if (plumbTarget(pp, port, trimmed, if (prefix and url) null else found, pl.at)) |t| return t; - } - }; - for (config.url_schemes) |scheme| { if (std.mem.startsWith(u8, trimmed, scheme)) return .{ .url = trimmed }; } @@ -872,25 +787,59 @@ pub fn clearNavigationSelection(p: *Pardes, pane: *Pane) void { if (v.drag == .select and p.panes[v.drag.select.id] == pane) v.drag = .none; } +/// The directories a relative name is looked for in, in order, as acme's +/// look tries its window's and then the other windows' (Incl's come +/// after, the caller's, as includename's): `first` (the pane's own, a +/// plumb message's wdir), then the directory of each pane of the jump list +/// but `from`, newest first, each once. +pub const Dirs = struct { + p: *Pardes, + from: ?usize, + seen: [MAX_PANES + 1][]const u8 = undefined, + nseen: usize = 0, + /// The next of the jump list's, counted from its newest. + n: usize = 1, + + pub fn init(p: *Pardes, from: ?usize, first: ?[]const u8) Dirs { + var d: Dirs = .{ .p = p, .from = from }; + if (first) |dir| { + d.seen[0] = dir; + d.nseen = 1; + d.n = 0; + } + return d; + } + + pub fn next(d: *Dirs) ?[]const u8 { + if (d.n == 0) { + d.n = 1; + return d.seen[0]; + } + const id = d.from orelse return null; + const jumps = &d.p.view().jumps; + cand: while (d.n <= jumps.n) { + const k = jumps.list[jumps.n - d.n].pane; + d.n += 1; + if (k == id) continue; + const dir = Pardes.paneDir(d.p.panes[k] orelse continue); + for (d.seen[0..d.nseen]) |s| if (std.mem.eql(u8, s, dir)) continue :cand; + d.seen[d.nseen] = dir; + d.nseen += 1; + return dir; + } + return null; + } +}; + /// Resolve without changing focus or falling back to search. PDF links use /// the same location rules as an ordinary Look before offering a choice. fn resolveLookTarget(p: *Pardes, id: usize, txt: []const u8, realbuf: *[4096]u8) Target { - const v = p.view(); const trimmed = std.mem.trim(u8, txt, " \t\r\n"); const pl = parsePathLine(trimmed); if (pl.path.len > 0) if (openPaneTarget(p, pl.path, pl.at)) |target| return target; var found: Target = .none; - var seen: [MAX_PANES][]const u8 = undefined; - var nseen: usize = 0; - var n: usize = 0; - cand: while (n <= v.jumps.n) : (n += 1) { - const k: usize = if (n == 0) id else v.jumps.list[v.jumps.n - n].pane; - if (n > 0 and k == id) continue; // tried first, skip the rerun - const op = p.panes[k] orelse continue; - const dir = Pardes.paneDir(op); - for (seen[0..nseen]) |s| if (std.mem.eql(u8, s, dir)) continue :cand; - seen[nseen] = dir; - nseen += 1; + var dirs: Dirs = .init(p, id, if (p.panes[id]) |op| Pardes.paneDir(op) else null); + while (dirs.next()) |dir| { if (pl.path.len > 0 and pl.path[0] != '/') { var joinbuf: [2048]u8 = undefined; if (std.fmt.bufPrint(&joinbuf, "{s}/{s}", .{ dir, pl.path }) catch null) |j| @@ -1089,7 +1038,6 @@ fn lookUnresolved(p: *Pardes, id: usize, pane: *Pane, trimmed: []const u8, text: // 9P is no keyboard input, and searches whatever the key mode. if (pane.addon != null or (pane.body.mode == .tty and !p.fs.serving)) return; if (text.len == 0) return; - if (lookCommit(p, id, pane, trimmed)) return; if (pane.file != null) return lookWord(p, id, pane, text); p.word_look = true; defer p.word_look = false; @@ -1110,38 +1058,6 @@ fn lookUnresolved(p: *Pardes, id: usize, pane: *Pane, trimmed: []const u8, text: } } -/// A commit hash (7 to 40 hex digits, a letter and a digit among them) -/// looked at inside a git repository: `git show` it, paged into a +Pager, -/// which stacks its hunks in a +Diff (ctl.fillPager); the command pane -/// goes when it succeeds (Pane.commandDone). -// ponytail: a hex word that names no commit leaves git's error in a command pane, not a search; check the object first if that bites. -fn lookCommit(p: *Pardes, id: usize, pane: *Pane, word: []const u8) bool { - if (!isCommitHash(word)) return false; - var dir = filesystem.localPath(Pardes.paneDir(pane)) orelse return false; - while (true) { - var buf: [4096]u8 = undefined; - const dot_git = std.fmt.bufPrint(&buf, "{s}/.git", .{dir}) catch return false; - if (exec.kindOf(dot_git) != null) break; - dir = std.Io.Dir.path.dirname(dir) orelse return false; - } - var line: [64]u8 = undefined; - const dst = exec.execute(p, id, std.fmt.bufPrint(&line, "git show {s}", .{word}) catch return false) orelse return true; - if (p.panes[dst]) |c| c.command_pages = true; - return true; -} - -fn isCommitHash(word: []const u8) bool { - if (word.len < 7 or word.len > 40) return false; - var digit = false; - var letter = false; - for (word) |c| switch (c) { - '0'...'9' => digit = true, - 'a'...'f' => letter = true, - else => return false, - }; - return digit and letter; -} - /// Opens (or finds) `path` as Look would, `id`'s own pane when it is empty, /// and selects what `expr` addresses there from its dot. An address that /// does not evaluate moves nothing and says why (acme: no jump). @@ -1369,7 +1285,7 @@ pub fn isHistoryList(pane: *const Pane) bool { // ---- a look on a diff line ---- /// The lines of a pane showing a diff, a .diff or .patch file or a -/// finished command pane whose output is one (File.DiffOutput); null for +/// finished command pane whose output is one (ansi.DiffOutput); null for /// any other pane. Good until the next step. pub fn diffLines(p: *Pardes, pane: *Pane) ?[]const []const u8 { if (pane.file) |*f| { @@ -1390,18 +1306,32 @@ pub fn diffAddress(pane: *const Pane, lines: []const []const u8, row: usize, buf return target.address(buf); } -/// What a click at byte `col` of line `row` of a diff pane takes, the one -/// answer for every way a click arrives (a mouse click, a 9P look of the -/// whole line, an empty look or exec written back to `event`): a file or -/// hunk header anywhere, or a hunk line on its `+`/`-`/` ` prefix, is the -/// address the line names (diffAddress); a hunk line's code is words, from -/// `word_from` on, the prefix never one of them. Null when the pane shows -/// no diff or the line is no part of one. -pub const DiffClick = struct { address: ?[]const u8 = null, word_from: usize = 0 }; +/// What a click at byte `col` of line `row` of a diff pane takes: a file +/// or hunk header anywhere, or a hunk line on its `+`/`-`/` ` prefix, is +/// the address the line names (diffAddress); a hunk line's code is words, +/// from `word_from` on, the prefix never one of them. Null when the line is +/// no part of a diff. +const DiffClick = struct { address: ?[]const u8 = null, word_from: usize = 0 }; -pub fn diffClick(p: *Pardes, pane: *Pane, row: usize, col: usize, buf: []u8) ?DiffClick { +/// What a click at byte `col` of row `row` takes, the one answer for every +/// way a click arrives (the mouse, exec.operandAt; an empty look written +/// back to `event`, events.expandAt; a whole line written to `look`): the +/// address a row's producer gave it (a query pane's row on its address, +/// Query.rowAddress), else the one the pane's language reads in the line (a +/// diff's: diffClickIn); or where its words start, the address no part of +/// them. `line` is the row's text it was read from, and the address's text +/// in it ends at `end`. Null for a row that names no address. +pub const RowAddress = struct { address: ?[]const u8 = null, word_from: usize = 0, line: []const u8, end: usize }; + +pub fn rowAddressAt(p: *Pardes, pane: *Pane, row: usize, col: usize, buf: []u8) ?RowAddress { + if (panes.Query.rowAddress(pane, row, col, buf)) |address| { + const f = &pane.file.?; + return .{ .address = address, .line = modal.lineSlice(f.content, row), .end = f.location_rows[row].location_end }; + } const lines = diffLines(p, pane) orelse return null; - return diffClickIn(pane, lines, row, col, buf); + if (row >= lines.len) return null; + const click = diffClickIn(pane, lines, row, col, buf) orelse return null; + return .{ .address = click.address, .word_from = click.word_from, .line = lines[row], .end = lines[row].len }; } fn diffClickIn(pane: *const Pane, lines: []const []const u8, row: usize, col: usize, buf: []u8) ?DiffClick { @@ -1417,18 +1347,19 @@ fn diffClickIn(pane: *const Pane, lines: []const []const u8, row: usize, col: us return .{ .address = address }; } -/// A look written over 9P of a whole line of a diff pane (the cursor's line -/// first, then the first after it): what a click on its first column takes. +/// A look written over 9P of a whole line of a pane whose rows name +/// addresses (a diff's, a query pane's: rowAddressAt), the cursor's line +/// first, then the first after it: what a click on its first column takes. /// A blank context line (` `) is a line too. -fn diffLineAddress(p: *Pardes, pane: *Pane, operand: []const u8, buf: []u8) ?[]const u8 { +fn lineAddress(p: *Pardes, pane: *Pane, operand: []const u8, buf: []u8) ?[]const u8 { const text = std.mem.trimEnd(u8, operand, "\r\n"); if (text.len == 0) return null; - const lines = diffLines(p, pane) orelse return null; + const lines = (if (pane.query != null) panes.File.cursorLines(p.scratch.allocator(), pane, &pane.file.?) catch null else diffLines(p, pane)) orelse return null; const cur: usize = @intCast(@max(0, pane.body.cur_row)); for (0..lines.len) |k| { const i = (cur + k) % lines.len; if (std.mem.eql(u8, std.mem.trimEnd(u8, lines[i], "\r"), text)) - return (diffClickIn(pane, lines, i, 0, buf) orelse return null).address; + return (rowAddressAt(p, pane, i, 0, buf) orelse return null).address; } return null; } @@ -1524,7 +1455,7 @@ pub fn lookAt(p: *Pardes, id: usize, operand_raw: []const u8) void { // A whole line of a diff written over 9P (a context line ` Del` // included) is a look at the address it names, never the word run. var diff_buf: [4096 + 32]u8 = undefined; - const looked: []const u8 = diffLineAddress(p, pane, operand_raw, &diff_buf) orelse looked: { + const looked: []const u8 = lineAddress(p, pane, operand_raw, &diff_buf) orelse looked: { if (config.commandWord(command)) |cmd| { if (exec.execute(p, id, cmd)) |dst| v.active = dst; return; @@ -1574,6 +1505,36 @@ pub fn lookAt(p: *Pardes, id: usize, operand_raw: []const u8) void { for (0..pane.sel.len) |slot| pane.clearPointerSelection(slot); pane.sel = @splat(.{}); } + // The plumber, asked before Look's own look as acme asks it (look.c's + // look3): what is looked at, sent from this pane. A name already open + // in a pane is focused first, never sent; nor is a look that opens + // as text (look_text), or the edit port's open of what was. A message + // the rules give back to `edit` as sent is Look's own to open, on what + // it found; one nothing takes, Look's too. + const shown = switch (found) { + .pane => true, + .file => |f| openPaneTarget(p, f.path, f.at) != null, + .kind => |k| openPaneTarget(p, k.path, .{}) != null, + .none, .dir, .url => false, + }; + if (!shown and !p.look_text) { + const msg: Plumb.Msg = .{ + .src = if (pane.addon) |k| k.nameOf() else if (pane.body.mode == .tty and !p.fs.serving) "term" else "pardes", + .wdir = Pardes.paneDir(pane), + .type = "text", + .data = trimmed, + }; + const seen: Plumb.Seen = .{ .name = pl.path, .found = switch (found) { + .file => |f| .{ .path = f.path }, + .kind => |k| .{ .path = k.path }, + .dir => |d| .{ .path = d, .dir = true }, + .none, .url, .pane => null, + } }; + switch (Plumb.send(p, id, msg, seen)) { + .done => return, + .look, .refused => {}, + } + } switch (found) { .none => lookUnresolved(p, id, pane, trimmed, std.mem.trimEnd(u8, txt, "\r\n")), .pane => |t| { @@ -1598,7 +1559,8 @@ pub fn lookAt(p: *Pardes, id: usize, operand_raw: []const u8) void { focusPaneLine(p, t.id, t.at, .center); settleLine(p, id, trimmed, t.at, before, null); }, - .url => |u| if (u.len <= 256) p.emit(.{ .open_link = .from(u) }), + // acme's own look opens no URL: the plumber's web port does. + .url => lookUnresolved(p, id, pane, trimmed, std.mem.trimEnd(u8, txt, "\r\n")), .dir => |dir| { // A directory that is not there (the pane's own, gone): said, // ENOENT, no terminal made in it. @@ -1619,18 +1581,6 @@ pub fn lookAt(p: *Pardes, id: usize, operand_raw: []const u8) void { const before = v.active; var opened: ?usize = null; if (!focusPaneByPath(p, target.path, target.at)) { - // A .diff or .patch looked at bare: its hunks stacked in a - // +Diff, which takes the keyboard as the file would; one - // with none in it opens as text. - if (!p.look_text and target.at.line == 0 and - (std.mem.endsWith(u8, target.path, ".diff") or std.mem.endsWith(u8, target.path, ".patch"))) - if (filesystem.read(p, target.path)) |bytes| { - defer p.gpa.free(bytes); - if (panes.Output.openDiff(p, id, target.path, bytes)) |hid| { - v.active = hid; - return; - } else |_| {} - } else |_| {}; const free = p.freeSlot() orelse return p.reportError(id, "look", error.NoPaneSlots); const nt = panes.File.open(p, free, target.path, target.at.line) catch |err| return lookOpenFailed(p, id, target.path, err); @@ -1900,17 +1850,9 @@ test "a zero column after a path is found, in every spelling a look takes" { for ([_][]const u8{ "", ":3", ":3:1", ":3:2-5", ":3:2-5:7", ":30:10" }) |rest| try std.testing.expect(!zeroColumn(rest)); } -test "a commit hash is 7 to 40 lowercase hex digits with a letter and a digit" { - try std.testing.expect(isCommitHash("9bffa7041c")); - try std.testing.expect(isCommitHash("9bffa7041cd2e8a0b6b1f7c3e4d5a6b7c8d9e0f1")); - try std.testing.expect(!isCommitHash("9bffa7")); - try std.testing.expect(!isCommitHash("defaced")); - try std.testing.expect(!isCommitHash("1234567")); - try std.testing.expect(!isCommitHash("0x9bffa7041c")); - try std.testing.expect(!isCommitHash("9BFFA7041C")); -} test "Look hover waits without mutating the pane and input cancels it" { + if (pardes.Term.ops == null) return error.SkipZigTest; // a shell const delay = config.look_preview_delay_frames; const gpa = std.testing.allocator; @@ -2021,6 +1963,7 @@ test "Look hover waits without mutating the pane and input cancels it" { } test "cwd changes cancel only the affected pane's Look hover" { + if (pardes.Term.ops == null) return error.SkipZigTest; // the classic boot's three shells const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .shells = 3 }); defer p.deinit(); @@ -2331,7 +2274,7 @@ test "a click, a 9P whole-line look and an empty event write-back take one expan if (at.whole_line) { const lines = diffLines(p, pane).?; var buf: [4096 + 32]u8 = undefined; - const whole = diffLineAddress(p, pane, lines[at.row], &buf) orelse return error.NoWholeLineAddress; + const whole = lineAddress(p, pane, lines[at.row], &buf) orelse return error.NoWholeLineAddress; try std.testing.expectEqualStrings(at.want, whole); } } @@ -2540,6 +2483,7 @@ test "Incl's directories find a name found nowhere else, <name> too; bare Incl l } test "LookNext in a command pane walks its own file:line places, whoever walked last" { + if (pardes.Term.ops == null) return error.SkipZigTest; // a command pane if (!platform_has_fs) return; var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); @@ -2685,51 +2629,84 @@ test "Look on a diff line is the look of the address it names, selected by hand: try std.testing.expectEqual(@as(i32, 1), seen[0].row); } -test "Plumb: the user's rules come before the built-in ones, the first that matches wins, a bad rule is refused, a dump keeps them" { +test "Plumb: a look sends what it looks at, the rules written first: a rule's word or port takes it, a name open in a pane is focused unsent, one nothing takes is Look's own" { if (!platform_has_fs) return; var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "pic.svg", .data = "<svg/>" }); - try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "shot.PNG", .data = "x" }); var dir_buf: [4096]u8 = undefined; const root = dir_buf[0..try tmp.dir.realPath(std.testing.io, &dir_buf)]; + var pic_buf: [4200]u8 = undefined; + const pic = try std.fmt.bufPrint(&pic_buf, "{s}/pic.svg", .{root}); const p = try Pardes.init(std.testing.allocator, .{ .cols = 100, .rows = 30 }); defer p.deinit(); - // A kind as a library brings it, its name and extension (no code: a - // look only names it). - try std.testing.expect(p.kinds.take(.{ .name = "image", .exts = ".png" }, "") == null); + const pane = try p.setTestFile("see https://ziglang.org here\n"); + // The defaults: a URL to the web port, the host's opener; the hover + // asks resolve, as before. + lookAt(p, 0, "https://ziglang.org"); + var linked = false; + while (p.nextEffect()) |e| if (e == .open_link) { + try std.testing.expectEqualStrings("https://ziglang.org", e.open_link.slice()); + linked = true; + }; + try std.testing.expect(linked); var real: [4096]u8 = undefined; - // None by default: today's ladder. - try std.testing.expect(resolve(p, "pic.svg", root, &real) == .file); - try std.testing.expect(resolve(p, "shot.PNG", root, &real) == .kind); try std.testing.expect(resolve(p, "https://ziglang.org", root, &real) == .url); - try std.testing.expect(p.executeBuiltinLine(0, "Plumb suffix .svg .SVGZ to image")); - try std.testing.expect(p.executeBuiltinLine(0, "Plumb suffix .png to file")); - try std.testing.expect(p.executeBuiltinLine(0, "Plumb prefix https:// to file")); - try std.testing.expect(p.executeBuiltinLine(0, "Plumb prefix gopher:// to url")); - try std.testing.expect(resolve(p, "pic.svg", root, &real) == .kind); - // Any case, as the kinds' extensions are. - try std.testing.expect(resolve(p, "shot.PNG", root, &real) == .file); - // A rule that cannot make its target (no such file) lets the next try. - try std.testing.expect(resolve(p, "https://ziglang.org", root, &real) == .url); - try std.testing.expectEqualStrings("gopher://x", resolve(p, "gopher://x", root, &real).url); - // A suffix is a file's: a word naming no file matches none. - try std.testing.expect(resolve(p, "nothere.svg", root, &real) == .none); - // Refused, in words, the list as it was: a kind not loaded too. - for ([_][]const u8{ "Plumb matches x to image", "Plumb suffix to image", "Plumb isdir .x to dir", "Plumb suffix .x to nowhere", "Plumb suffix .x to pdf", "Plumb suffix .x", "Plumb suffix .x to image extra" }) |bad| - try std.testing.expect(p.executeBuiltinLine(0, bad)); - try std.testing.expectEqual(@as(usize, 4), p.plumb.items.len); - try std.testing.expectEqualStrings("suffix .svg .SVGZ to image", p.plumb.items[0]); - try std.testing.expect(p.executeBuiltinLine(0, "Plumb")); - const pane = p.panes[0].?; - try std.testing.expect(std.mem.indexOf(u8, pane.msg[0..pane.msg_len], "; suffix .png to file") != null); - 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(usize, 4), restored.plumb.items.len); - // The kind gone, its rule is tried like any that cannot: the ladder's. - p.kinds.drop(p.kinds.byName("image").?); - try std.testing.expect(resolve(p, "pic.svg", root, &real) == .file); - try std.testing.expect(p.executeBuiltinLine(0, "Plumb -")); - try std.testing.expectEqual(@as(usize, 0), p.plumb.items.len); + // A rule set written first takes what it matches: its word started in + // place, from the looking pane, and no pane opened. + try std.testing.expect(Plumb.apply(p, false, "plumb/rules", "type is text\ndata matches '.*\\.svg'\narg isfile $data\nplumb start Msg svg $file\n\ninclude basic\n") == null); + lookAt(p, 0, pic); + try std.testing.expectEqual(@as(usize, 0), p.view().active); + var said_buf: [4300]u8 = undefined; + try std.testing.expectEqualStrings(try std.fmt.bufPrint(&said_buf, "svg {s}", .{pic}), pane.msg[0..pane.msg_len]); + // A name open in a pane is focused, never sent. + p.look_text = true; + lookAt(p, 0, pic); + p.look_text = false; + const opened = p.view().active; + try std.testing.expect(opened != 0); + p.view().active = 0; + p.setMessage(0, "before"); + lookAt(p, 0, pic); + try std.testing.expectEqual(opened, p.view().active); + try std.testing.expectEqualStrings("before", pane.msg[0..pane.msg_len]); + // With no web rule, a URL is a word Look searches for. + p.view().active = 0; + try std.testing.expect(Plumb.apply(p, false, "plumb/rules", "type is text\narg isfile $data\nplumb to edit\n") == null); + while (p.nextEffect()) |_| {} + lookAt(p, 0, "https://ziglang.org"); + while (p.nextEffect()) |e| try std.testing.expect(e != .open_link); + const dot = @import("ninep/pane.zig").dotOf(pane); + try std.testing.expectEqualStrings("https://ziglang.org", pane.file.?.content[dot.q0..dot.q1]); +} + +test "Plumb: a commit hash looked at in a git work tree is git show's, paged; outside one Diff declines, and the word is searched for" { + if (pardes.Term.ops == null) return error.SkipZigTest; // a command pane + if (!platform_has_fs) return; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + try tmp.dir.createDir(std.testing.io, ".git", .default_dir); + try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "notes.txt", .data = "fixed in 3f2a9c1\n" }); + var dir_buf: [4096]u8 = undefined; + const root = dir_buf[0..try tmp.dir.realPath(std.testing.io, &dir_buf)]; + const p = try Pardes.init(std.testing.allocator, .{ .cols = 100, .rows = 30 }); + defer p.deinit(); + // /test.txt: its directory, /, is in no work tree. + const pane = try p.setTestFile("fixed in 3f2a9c1\n"); + lookAt(p, 0, "3f2a9c1"); + const dot = @import("ninep/pane.zig").dotOf(pane); + try std.testing.expectEqualStrings("3f2a9c1", pane.file.?.content[dot.q0..dot.q1]); + for (p.panes) |slot| if (slot) |pn| try std.testing.expect(pn.command == null); + var notes_buf: [4200]u8 = undefined; + lookAt(p, 0, try std.fmt.bufPrint(¬es_buf, "{s}/notes.txt", .{root})); + const notes = p.view().active; + try std.testing.expect(notes != 0); + lookAt(p, notes, "3f2a9c1"); + var paged = false; + for (p.panes) |slot| if (slot) |pn| if (pn.command) |cmd| { + try std.testing.expect(std.mem.endsWith(u8, cmd, "git show 3f2a9c1")); + try std.testing.expect(pn.command_pages); + paged = true; + }; + try std.testing.expect(paged); } diff --git a/src/macos.zig b/src/macos.zig index 254cf2a7..389a4b4a 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(); @@ -1624,6 +1624,7 @@ const vtable: pardes.Host.VTable = .{ .set_clipboard = setClipboard, .read_clipboard = readClipboard, .open_link = openLink, + .start = host_io.startDetached, .lsp = lspRequest, .pipe = pipeRequest, }; 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/memory.zig b/src/memory.zig index 31b04b99..ae340bff 100644 --- a/src/memory.zig +++ b/src/memory.zig @@ -23,9 +23,6 @@ pub const limits = struct { /// /log's ring, which records whether or not anyone reads it. pub const log_bytes: usize = 64 * KiB; pub const max_tag_tail: usize = 4096; - /// Pixels one image may decode to (RGBA, 4 bytes each): checked from its - /// header before stb_image allocates them. - pub const image_decode_pixels: usize = 64 * 1024 * 1024; /// What the core's per-step scratch arena and the frame arena keep /// between steps: a step that needed more (a huge Callstack's sources) /// gives the rest back instead of holding its high-water mark. diff --git a/src/mouse.zig b/src/mouse.zig index 783b12b7..8867982c 100644 --- a/src/mouse.zig +++ b/src/mouse.zig @@ -1,6 +1,5 @@ //! The mouse: what a pointer is over, the three buttons' presses, drags and -//! releases (acme's chords, border and seam drags, gestures), and the -//! chrome targets a shell asks about. +//! releases (acme's chords, grip and seam drags, gestures). const pardes = @import("pardes.zig"); const tagline = @import("tagline.zig"); const exec = @import("exec.zig"); @@ -19,7 +18,6 @@ const Pane = panes.Pane; const MAX_PANES = pardes.MAX_PANES; const Layer = @import("Layer.zig"); const Jump = @import("Jump.zig"); -const TOPBAR_H = pardes.TOPBAR_H; const BOX_H = pardes.BOX_H; const TAG_TEXT_INSET = pardes.TAG_TEXT_INSET; const Builtin = pardes.Builtin; @@ -29,7 +27,6 @@ const Pardes = pardes.Pardes; pub const Drag = union(enum) { none, - border_v: struct { left_col: usize, cur_x: u16, corner: ?struct { col: usize, idx: usize } = null, cur_y: u16 = 0 }, border_h: struct { col: usize, top_idx: usize, cur_y: u16 }, move: struct { id: usize, cur_x: u16, cur_y: u16 }, /// `grab`: how far into the grip it was pressed, so the column's left @@ -58,7 +55,7 @@ pub const Drag = union(enum) { fn button(drag: Drag) ?Mouse.Button { return switch (drag) { .none => null, - .border_v, .border_h, .move, .column_move => config.select_button, + .border_h, .move, .column_move => config.select_button, .select => |selection| selection.button, }; } @@ -126,38 +123,6 @@ fn seamRowOf(p: *const Pardes, c: usize, k: usize) u16 { return r.y + r.h -| 1; } -pub const ChromeTarget = struct { col: u16, row: u16 }; - -/// The chrome a press at `col`, `row` takes: the tag rows; then, -/// on the cell, a pane's grip, a column's handle or a seam; then a cell -/// away, any of a pane's tag, a handle or a seam. -pub fn chromeTarget(p: *const Pardes, col: u16, row: u16) ?ChromeTarget { - const v = p.view(); - if (row < p.topBarHeight() + layout.columnBarHeight(p)) return .{ .col = col, .row = row }; - for ([_]u16{ 0, 1 }) |slack| { - for (p.panes, 0..) |slot, id| { - const pane = slot orelse continue; - const rect = v.rects[id]; - const tag = p.tagTop(pane, rect); - const edge = if (slack == 0) rect.x + config.GUTTER else rect.x + rect.w; - if (row >= tag and row < tag + pane.tag_rows and col >= rect.x and col < rect.x + rect.w and col < edge) - return .{ .col = col, .row = row }; - } - for (0..p.view().ncol -| 1) |column| { - const handle = v.col_x[column] + v.col_w[column] -| 1; - if (@max(col, handle) - @min(col, handle) == slack) return .{ .col = handle, .row = row }; - } - for (0..p.view().ncol) |column| { - if (col < v.col_x[column] or col >= v.col_x[column] + v.col_w[column]) continue; - for (0..p.view().cols[column].n -| 1) |index| { - const seam = seamRowOf(p, column, index); - if (@max(row, seam) - @min(row, seam) == slack) return .{ .col = col, .row = seam }; - } - } - } - return null; -} - pub fn paneAt(p: *const Pardes, col: u16, row: u16) ?usize { for (p.panes, 0..) |slot, id| { if (slot == null) continue; @@ -199,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 @@ -207,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; } @@ -249,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 @@ -300,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, @@ -309,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; @@ -326,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; @@ -357,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; }, @@ -365,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; }, } } @@ -461,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); } } @@ -781,18 +746,6 @@ pub fn handleMouse(p: *Pardes, event: Mouse) void { return; } } - for (0..p.view().ncol -| 1) |c| { - if (mcol == v.col_x[c] + v.col_w[c] -| 1) { - const corner: @FieldType(@FieldType(Drag, "border_v"), "corner") = if (seamIdxAt(p, c, mrow)) |k| - .{ .col = c, .idx = k } - else if (seamIdxAt(p, c + 1, mrow)) |k| - .{ .col = c + 1, .idx = k } - else - null; - v.drag = .{ .border_v = .{ .left_col = c, .cur_x = mcol, .corner = corner, .cur_y = mrow } }; - return; - } - } // Two panes are resized on the rule between them, never on a // row of text; with no rule, by the grip, as acme moves a // window by its button. @@ -923,12 +876,6 @@ fn seamIdxAt(p: *const Pardes, c: usize, mrow: u16) ?usize { return null; } -fn clampBorderCol(lx: u16, lw: u16, rw: u16, mcol: u16) u16 { - const lo = lx + config.MINW; - const hi = lx +| lw +| rw -| config.MINW; - return if (lo <= hi) std.math.clamp(mcol, lo, hi) else mcol; -} - fn clampBorderRow(ay: u16, ah: u16, bh: u16, mrow: u16) u16 { const lo = ay + BOX_H - 1; const hi = ay +| ah +| bh -| (BOX_H + 1); @@ -938,20 +885,6 @@ fn clampBorderRow(ay: u16, ah: u16, bh: u16, mrow: u16) u16 { pub fn dragUpdate(p: *Pardes, mcol: u16, mrow: u16, body_hit: ?Mouse.BodyHit) void { const v = p.view(); switch (v.drag) { - .border_v => |*d| { - const c = d.left_col; - d.cur_x = if (c + 1 < v.ncol) - clampBorderCol(v.col_x[c], v.col_w[c], v.col_w[c + 1], mcol) - else - mcol; - if (d.corner) |k| if (k.idx + 1 < v.cols[k.col].n) { - const a = v.rects[v.cols[k.col].panes[k.idx]]; - const b = v.rects[v.cols[k.col].panes[k.idx + 1]]; - d.cur_y = clampBorderRow(a.y, a.h, b.h, mrow); - } else { - d.cur_y = mrow; - }; - }, .border_h => |*d| { const cc = d.col; const k = d.top_idx; @@ -1157,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"); @@ -1239,18 +1172,6 @@ fn dragRelease(p: *Pardes, button: Mouse.Button) void { defer v.drag = .none; defer v.chord_hold = false; switch (v.drag) { - .border_v => |d| { - const c = d.left_col; - const old_seam = v.col_x[c] + v.col_w[c] -| 1; - // the handle is the left pane's LAST column (inclusive), so - // the new width includes it — a no-drag click changes nothing - if (c + 1 < v.ncol and d.cur_x != old_seam) - layout.setColumnPairWidth(p, c, (d.cur_x + 1) -| v.col_x[c]); - if (d.corner) |k| { - if (d.cur_y != seamRowOf(p, k.col, k.idx)) - layout.applyRowSplit(p, k.col, k.idx, d.cur_y); - } - }, .border_h => |d| if (d.cur_y != seamRowOf(p, d.col, d.top_idx)) layout.applyRowSplit(p, d.col, d.top_idx, d.cur_y), .column_move => |d| if (layout.columnBySerial(p, d.serial)) |column| switch (layout.columnDrop(p, column, d.cur_x, d.grab)) { @@ -1391,7 +1312,7 @@ fn dragRelease(p: *Pardes, button: Mouse.Button) void { const test_metrics: pardes.RowMetrics = .{ .body_w = 10, .body_h = 20, .tagline_w = 6, .tagline_h = 12 }; -fn cornerFixture(gpa: std.mem.Allocator) !*Pardes { +fn twoColumns(gpa: std.mem.Allocator) !*Pardes { const p = try Pardes.init(gpa, .{ .cols = 100, .rows = 30, .shells = 3 }); p.update(.{ .resize = .{ .cols = 100, .rows = 30 } }); p.view().active = p.view().cols[1].panes[0]; @@ -1463,7 +1384,8 @@ fn layerCenter(layer: *const Layer, col: u16, comptime tag: bool) [2]f32 { } test "a pane's last row of text is no resize handle; the rule over the next pane is" { - const p = try cornerFixture(std.testing.allocator); + if (pardes.Term.ops == null) return error.SkipZigTest; // the classic boot's three shells + const p = try twoColumns(std.testing.allocator); defer p.deinit(); const seam = seamRowOf(p, 1, 0); const inside = p.view().col_x[1] + p.view().col_w[1] / 2; @@ -1473,8 +1395,23 @@ test "a pane's last row of text is no resize handle; the rule over the next pane try std.testing.expect(nudgeRightSeam(p, 2) == seam + 2); } +test "the line between two columns is no resize handle: a press there is a sweep in the pane" { + const p = try twoColumns(std.testing.allocator); + defer p.deinit(); + const line = p.view().col_x[0] + p.view().col_w[0] - 1; + const row = p.view().rects[p.view().cols[0].panes[0]].y + BOX_H + 1; + const weight = p.view().cols[0].weight; + p.update(.{ .mouse = .{ .button = .left, .kind = .press, .col = line, .row = row } }); + try std.testing.expect(p.view().drag == .select); + p.update(.{ .mouse = .{ .button = .left, .kind = .drag, .col = line + 8, .row = row } }); + p.update(.{ .mouse = .{ .button = .left, .kind = .release, .col = line + 8, .row = row } }); + p.sync(); + try std.testing.expectEqual(weight, p.view().cols[0].weight); +} + test "a pane's grip dragged up or down its own column moves its top, down to the floor of the pane above" { - const p = try cornerFixture(std.testing.allocator); + if (pardes.Term.ops == null) return error.SkipZigTest; // a shell + const p = try twoColumns(std.testing.allocator); defer p.deinit(); const upper = p.view().cols[1].panes[0]; const lower = p.view().cols[1].panes[1]; @@ -1499,26 +1436,6 @@ test "a pane's grip dragged up or down its own column moves its top, down to the try std.testing.expectEqual(to, p.view().rects[lower].y); } -test "a press near chrome takes it: the tag rows, a column's handle or a seam on its cell or a cell away, a pane's tag; nothing in a body" { - const p = try cornerFixture(std.testing.allocator); - defer p.deinit(); - // Column 0's two panes share its rows evenly; column 1's lower one is - // tall, its middle a body row. - const handle = p.view().col_x[0] + p.view().col_w[0] - 1; - const seam = seamRowOf(p, 0, 0); - const mid = p.view().col_x[0] + p.view().col_w[0] / 2; - const top = p.view().rects[p.view().cols[0].panes[0]].y; - const low = p.view().rects[p.view().cols[1].panes[1]]; - const body = low.y + low.h / 2; - try std.testing.expectEqual(ChromeTarget{ .col = 5, .row = 0 }, chromeTarget(p, 5, 0).?); - try std.testing.expectEqual(ChromeTarget{ .col = handle, .row = body }, chromeTarget(p, handle, body).?); - try std.testing.expectEqual(ChromeTarget{ .col = handle, .row = body }, chromeTarget(p, handle + 1, body).?); - try std.testing.expectEqual(ChromeTarget{ .col = mid, .row = seam }, chromeTarget(p, mid, seam).?); - try std.testing.expectEqual(ChromeTarget{ .col = mid, .row = seam }, chromeTarget(p, mid, seam - 1).?); - try std.testing.expectEqual(ChromeTarget{ .col = mid, .row = top }, chromeTarget(p, mid, top).?); - try std.testing.expect(chromeTarget(p, mid, seam - 3) == null); -} - test "plain left click clears explicit modal selection" { const gpa = std.testing.allocator; // Wide enough for the tag on one row: the body starts under it. @@ -1558,144 +1475,6 @@ test "a selection drag and its release leave the selection done" { try std.testing.expectEqual(.done, pane.sel[sel_slot].state); } -test "a corner drag's two axes clamp independently" { - // a 100-wide window split 50/50, and a 30-row column split 15/14 under the - // topbar: the shape windowops.snap drives - const lx: u16 = 0; - const lw: u16 = 50; - const rw: u16 = 50; - const ay: u16 = TOPBAR_H; - const ah: u16 = 15; - const bh: u16 = 14; - const row_lo: u16 = ay + BOX_H - 1; - const row_hi: u16 = ay + ah + bh - (BOX_H + 1); - - // each axis alone, at both walls - try std.testing.expectEqual(@as(u16, config.MINW), clampBorderCol(lx, lw, rw, 0)); - try std.testing.expectEqual(@as(u16, 100 - config.MINW), clampBorderCol(lx, lw, rw, 999)); - try std.testing.expectEqual(row_lo, clampBorderRow(ay, ah, bh, 0)); - try std.testing.expectEqual(row_hi, clampBorderRow(ay, ah, bh, 999)); - - // THE corner property: drag off the right edge while staying mid-height — - // x sits at its wall, y still tracks the mouse row exactly - try std.testing.expectEqual(@as(u16, 100 - config.MINW), clampBorderCol(lx, lw, rw, 999)); - try std.testing.expectEqual(@as(u16, 12), clampBorderRow(ay, ah, bh, 12)); - // and the mirror: pinned at the bottom, x still free - try std.testing.expectEqual(row_hi, clampBorderRow(ay, ah, bh, 999)); - try std.testing.expectEqual(@as(u16, 40), clampBorderCol(lx, lw, rw, 40)); - // both pinned at once is just both walls, not a stuck gesture - try std.testing.expectEqual(@as(u16, config.MINW), clampBorderCol(lx, lw, rw, 0)); - try std.testing.expectEqual(row_hi, clampBorderRow(ay, ah, bh, 999)); - - // degenerate pairs pass through untouched, each on its own terms: a pane - // pair with no room stays draggable even when the column pair has room - try std.testing.expectEqual(@as(u16, 7), clampBorderCol(0, 5, 5, 7)); - try std.testing.expectEqual(@as(u16, 40), clampBorderCol(lx, lw, rw, 40)); - try std.testing.expectEqual(@as(u16, 9), clampBorderRow(TOPBAR_H, 1, 0, 9)); -} - -test "a v-handle press at the RIGHT column's seam drags both boundaries" { - const p = try cornerFixture(std.testing.allocator); - defer p.deinit(); - try std.testing.expectEqual(@as(usize, 2), p.view().cols[1].n); - - const handle = p.view().col_x[0] + p.view().col_w[0] - 1; - const right_seam = nudgeRightSeam(p, 3); - try std.testing.expect(right_seam != seamRowOf(p, 0, 0)); - - const w0 = p.view().cols[0].weight; - const v_left = p.panes[p.view().cols[0].panes[0]].?.vweight; - const v_right = p.panes[p.view().cols[1].panes[0]].?.vweight; - - p.update(.{ .mouse = .{ .button = .left, .kind = .press, .col = handle, .row = right_seam } }); - try std.testing.expect(p.view().drag == .border_v); - const corner = p.view().drag.border_v.corner orelse return error.NoCorner; - try std.testing.expectEqual(@as(usize, 1), corner.col); - try std.testing.expectEqual(@as(usize, 0), corner.idx); - - p.update(.{ .mouse = .{ .button = .left, .kind = .drag, .col = handle + 8, .row = right_seam - 4 } }); - p.update(.{ .mouse = .{ .button = .left, .kind = .release, .col = handle + 8, .row = right_seam - 4 } }); - p.sync(); - - // both halves committed: the column pair widened, and the RIGHT column's - // pane pair reweighted — while the left column's panes stayed put - try std.testing.expect(p.view().cols[0].weight > w0); - try std.testing.expect(p.panes[p.view().cols[1].panes[0]].?.vweight != v_right); - try std.testing.expectEqual(v_left, p.panes[p.view().cols[0].panes[0]].?.vweight); -} - -test "a tie row still moves the LEFT column's pane pair only" { - const p = try cornerFixture(std.testing.allocator); - defer p.deinit(); - - // put column 1's seam exactly on column 0's, the row the eye reads as one - // line across the whole window - const left_seam = seamRowOf(p, 0, 0); - _ = nudgeRightSeam(p, @as(i32, left_seam) - @as(i32, seamRowOf(p, 1, 0))); - try std.testing.expectEqual(left_seam, seamRowOf(p, 1, 0)); - - const handle = p.view().col_x[0] + p.view().col_w[0] - 1; - const v_left = p.panes[p.view().cols[0].panes[0]].?.vweight; - const v_right = p.panes[p.view().cols[1].panes[0]].?.vweight; - - p.update(.{ .mouse = .{ .button = .left, .kind = .press, .col = handle, .row = left_seam } }); - const corner = p.view().drag.border_v.corner orelse return error.NoCorner; - try std.testing.expectEqual(@as(usize, 0), corner.col); - - p.update(.{ .mouse = .{ .button = .left, .kind = .drag, .col = handle, .row = left_seam - 4 } }); - p.update(.{ .mouse = .{ .button = .left, .kind = .release, .col = handle, .row = left_seam - 4 } }); - p.sync(); - try std.testing.expect(p.panes[p.view().cols[0].panes[0]].?.vweight != v_left); - try std.testing.expectEqual(v_right, p.panes[p.view().cols[1].panes[0]].?.vweight); -} - -test "a v-handle press at nobody's seam is still a plain edge drag" { - const p = try cornerFixture(std.testing.allocator); - defer p.deinit(); - const right_seam = nudgeRightSeam(p, 3); - const left_seam = seamRowOf(p, 0, 0); - - const handle = p.view().col_x[0] + p.view().col_w[0] - 1; - var row: u16 = TOPBAR_H + 1; - while (row == left_seam or row == right_seam) row += 1; - - const w0 = p.view().cols[0].weight; - const v_left = p.panes[p.view().cols[0].panes[0]].?.vweight; - const v_right = p.panes[p.view().cols[1].panes[0]].?.vweight; - p.update(.{ .mouse = .{ .button = .left, .kind = .press, .col = handle, .row = row } }); - try std.testing.expect(p.view().drag == .border_v); - try std.testing.expect(p.view().drag.border_v.corner == null); - p.update(.{ .mouse = .{ .button = .left, .kind = .drag, .col = handle + 8, .row = row + 5 } }); - p.update(.{ .mouse = .{ .button = .left, .kind = .release, .col = handle + 8, .row = row + 5 } }); - p.sync(); - // exactly ONE boundary moved - try std.testing.expect(p.view().cols[0].weight > w0); - try std.testing.expectEqual(v_left, p.panes[p.view().cols[0].panes[0]].?.vweight); - try std.testing.expectEqual(v_right, p.panes[p.view().cols[1].panes[0]].?.vweight); -} - -test "a RIGHT-column corner's two axes clamp independently" { - const p = try cornerFixture(std.testing.allocator); - defer p.deinit(); - const right_seam = nudgeRightSeam(p, 3); - const handle = p.view().col_x[0] + p.view().col_w[0] - 1; - p.update(.{ .mouse = .{ .button = .left, .kind = .press, .col = handle, .row = right_seam } }); - try std.testing.expectEqual(@as(usize, 1), (p.view().drag.border_v.corner orelse return error.NoCorner).col); - - // off the right edge at mid-height: x parks at its MINW wall, y is the mouse - p.update(.{ .mouse = .{ .button = .left, .kind = .drag, .col = 999, .row = right_seam } }); - try std.testing.expectEqual(@as(u16, 100 - config.MINW), p.view().drag.border_v.cur_x); - try std.testing.expectEqual(right_seam, p.view().drag.border_v.cur_y); - - // and the mirror: below the bottom at mid-width. y parks, x tracks again - p.update(.{ .mouse = .{ .button = .left, .kind = .drag, .col = handle, .row = 999 } }); - try std.testing.expectEqual(handle, p.view().drag.border_v.cur_x); - const a = p.view().rects[p.view().cols[1].panes[0]]; - const b = p.view().rects[p.view().cols[1].panes[1]]; - try std.testing.expectEqual(clampBorderRow(a.y, a.h, b.h, 999), p.view().drag.border_v.cur_y); - p.update(.{ .mouse = .{ .button = .left, .kind = .release, .col = handle, .row = 999 } }); -} - test "mouse thumb buttons navigate once and clear selection gestures" { const p = try Pardes.init(std.testing.allocator, .{ .cols = 60, .rows = 12 }); defer p.deinit(); @@ -1765,6 +1544,7 @@ test "a chorded exec an event reader holds is told with its argument, and writte } test "a wheel over a program that owns it is the program's, in the form it asked for; a shell's scrolls" { + if (pardes.Term.ops == null) return error.SkipZigTest; // a shell const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .cols = 60, .rows = 16, .tty_only = true }); defer p.deinit(); @@ -1860,6 +1640,7 @@ test "Alt-click is B2 and Super-click B3, kept from the press through the releas } test "a program tracking the mouse gets its clicks, drags and moves over its grid as xterm reports them; Shift and chrome stay pardes's" { + if (pardes.Term.ops == null) return error.SkipZigTest; // a shell const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .cols = 60, .rows = 16, .tty_only = true }); defer p.deinit(); diff --git a/src/ninep/cols.zig b/src/ninep/cols.zig index c8d84e5d..d953bcc7 100644 --- a/src/ninep/cols.zig +++ b/src/ninep/cols.zig @@ -435,6 +435,7 @@ test "Help and Find at /tagexec act in the session's directory, not the keyboard } test "a shell command at /tagexec or a column's exec is a command pane in the session's directory, never typed into the keyboard's terminal" { + if (pardes.Term.ops == null) return error.SkipZigTest; // a command pane const p = try Pardes.init(testing.allocator, .{ .tty_only = true, .cols = 80, .rows = 30 }); defer p.deinit(); while (p.nextEffect()) |_| {} @@ -455,6 +456,7 @@ test "a shell command at /tagexec or a column's exec is a command pane in the se } test "New and Term run at /tagexec and a column's exec, with no pane at all too" { + if (pardes.Term.ops == null) return error.SkipZigTest; // a shell const p = try th.withFile(testing.allocator, "x\n"); defer p.deinit(); const tagexec = @backingInt(tree.TopFile.tagexec); @@ -671,6 +673,7 @@ test "tagexec runs a word as a click in the workspace tag; exec files read back } test "a word run from the workspace's or a column's tag runs in the session's directory, a pane's in its own" { + if (pardes.Term.ops == null) return error.SkipZigTest; // a command pane const p = try th.withFile(testing.allocator, "x\n"); defer p.deinit(); const session = p.sessionDir(); @@ -689,6 +692,7 @@ test "a word run from the workspace's or a column's tag runs in the session's di } test "a command run from a column's tag gets its pane in that column, not the last" { + if (pardes.Term.ops == null) return error.SkipZigTest; // a command pane const p = try th.withFile(testing.allocator, "x\n"); defer p.deinit(); layout.newColumn(p, p.view().active); diff --git a/src/ninep/ctl.zig b/src/ninep/ctl.zig index 699b7833..49fe661d 100644 --- a/src/ninep/ctl.zig +++ b/src/ninep/ctl.zig @@ -366,7 +366,7 @@ pub fn readResults(p: *Pardes, req: Req) Reply { const looking = if (tree.Node.target(req.node)) |t| switch (t) { .top => |f| f == .look, .pane => |pt| pt.file == .look, - .col => false, + .col, .port => false, } else false; for (kept) |serial| if (!looking or p.paneBySerial(serial) != null) out.print(p.gpa, "{d}\n", .{serial}) catch return Reply.fail(req.tag, E.NOMEM); @@ -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 ghostty-vt (pager.zig), 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| { @@ -718,17 +718,7 @@ pub fn fillPager(p: *Pardes, serial: u32, held: *std.ArrayList(u8)) error{OutOfM panes.File.setContent(p, f, page.text); f.pager_spans = page.spans; f.saved_revision = f.revision; - // A diff paged (`git show`, difftui's patches): its hunks stacked in a - // +Diff in the +Pager's place, the +Pager closed. The keyboard stays - // where it was, as a page's. - if (f.pager_diff) { - const keyboard = p.view().active; - if (panes.Output.openDiff(p, id, f.path, f.content)) |hid| { - // ponytail: the text is gone with it; Diff on the +Diff says no such file. - p.removePane(id, hid) catch |err| p.reportError(id, "pager", err); - } else |_| {} - if (p.panes[keyboard] != null) p.view().active = keyboard; - } + pardes.Plumb.paged(p, id); } /// The editor's step: the text of /pager opens closed unread goes in. @@ -1889,6 +1879,7 @@ test "Mount dials its peer and fails, mounting nothing, when none answers; a loo } test "Term in a directory that is not there fails and makes no pane; a shell that never started answers a run" { + if (pardes.Term.ops == null) return error.SkipZigTest; // a shell const p = try withFile(testing.allocator, "x\n"); defer p.deinit(); const serial = serialOf(p); @@ -1981,6 +1972,7 @@ test "a script's Grep and Find fill the pane's one query pane, a row a line unde } test "a terminal told the directory it already goes by logs no rename" { + if (pardes.Term.ops == null) return error.SkipZigTest; // a shell const p = try withFile(testing.allocator, "x\n"); defer p.deinit(); _ = wr(p, Node.of(serialOf(p), .name), "/tmp/f.txt\n"); @@ -2029,6 +2021,7 @@ test "a terminal with text typed at its prompt is never typed into: a look at it } test "a command line from a missing directory fails ENOENT and makes no pane; a command whose shell never started ends 127" { + if (pardes.Term.ops == null) return error.SkipZigTest; // a command pane const p = try withFile(testing.allocator, "x\n"); defer p.deinit(); p.host = .{ .vtable = &th.starting }; @@ -2188,6 +2181,7 @@ test "a failure said while a 9P write waits on it posts no msg, only the write's } test "with no pane at all, the root look opens its file and the root exec runs in the session's directory" { + if (pardes.Term.ops == null) return error.SkipZigTest; // a command pane const p = try withFile(testing.allocator, "x\n"); defer p.deinit(); var tmp = testing.tmpDir(.{}); @@ -2248,6 +2242,7 @@ test "a restored pane whose file is gone from disk comes back dirty, and Del ask test "a focus moved over 9P tells the programs that asked for focus reports, as a click does" { + if (pardes.Term.ops == null) return error.SkipZigTest; // a shell const p = try Pardes.init(testing.allocator, .{ .cols = 90, .rows = 30, .shells = 2 }); defer p.deinit(); while (p.nextEffect()) |_| {} @@ -2376,6 +2371,7 @@ test "/recent shows a name as /index does, a newline in it escaped" { } test "size is monotonic: growing is never refused, and a size once taken is taken again" { + if (pardes.Term.ops == null) return error.SkipZigTest; // a shell const p = try Pardes.init(testing.allocator, .{ .tty_only = true, .cols = 160, .rows = 60 }); defer p.deinit(); while (p.nextEffect()) |_| {} @@ -2612,6 +2608,7 @@ test "@p<terminal>:<address> takes any address over the terminal's lines, select } test "what a /pager open writes after its directory is the text: plain in the body, its colours the pane's, clean, in by the read" { + if (pardes.Term.ops == null) return error.SkipZigTest; // the emulator's parse of colours const p = try withFile(testing.allocator, "x\n"); defer p.deinit(); const pager = @backingInt(tree.TopFile.pager); @@ -2648,7 +2645,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 @@ -2680,6 +2677,7 @@ test "what a /pager open writes after its directory is the text: plain in the bo } test "a command pane an exec open was answered is leased to it while it stays open: another client's command gets a pane of its own" { + if (pardes.Term.ops == null) return error.SkipZigTest; // a command pane const p = try withFile(testing.allocator, "x\n"); defer p.deinit(); const exec = Node.of(serialOf(p), .exec); @@ -2727,6 +2725,7 @@ test "a body write to an image pane says its body takes none, not that terminals } test "Term+bash on a pane ctl is Term with its argument, as exec and the tag take it" { + if (pardes.Term.ops == null) return error.SkipZigTest; // a shell const p = try withFile(testing.allocator, "x\n"); defer p.deinit(); // Tty+sh too: Term's old name, as a saved tag holds it. diff --git a/src/ninep/events.zig b/src/ninep/events.zig index 77a4e35f..9e6df93d 100644 --- a/src/ninep/events.zig +++ b/src/ninep/events.zig @@ -233,6 +233,10 @@ pub fn noteError(p: *Pardes, req: Req, reply: Reply) void { if ((f == .exec or f == .look) and p.fs.ran_at != 0) serial = name.print("{d}", .{p.fs.ran_at}); }, + .port => |i| { + serial = "-"; + file = name.print("plumb/{s}", .{pardes.Plumb.portName(p, i) orelse "?"}); + }, .col => |c| { serial = "-"; file = if (c.file == .dir) @@ -677,22 +681,21 @@ fn scanNumber(data: []const u8, i: *usize, overflow: *bool) ?u32 { /// What a click at `at` takes, as the mouse's does (exec.operandAt), /// for an empty range written back: the file name or word under it on its -/// line (look.expandedWord), else nothing; in a diff pane's body, for a -/// look alone (`for_look`, exec.operandAt), look.diffClick's answer, the -/// line's address or its code's words. +/// line (look.expandedWord), else nothing; in a body whose rows name +/// addresses, for a look alone (`for_look`, exec.operandAt), +/// look.rowAddressAt's answer, the row's address or its code's words. pub fn expandAt(p: *Pardes, pane: *Pane, whole: []const u8, at: usize, in_body: bool, for_look: bool) []const u8 { const start = if (std.mem.lastIndexOfScalar(u8, whole[0..at], '\n')) |nl| nl + 1 else 0; const end = std.mem.indexOfScalarPos(u8, whole, at, '\n') orelse whole.len; var word_from: usize = 0; - if (in_body and for_look) diff: { + if (in_body and for_look) row_address: { const row = std.mem.count(u8, whole[0..start], "\n"); - // Only when the served line is the one the diff reads there. - const lines = look.diffLines(p, pane) orelse break :diff; - if (row >= lines.len or !std.mem.eql(u8, std.mem.trimEnd(u8, lines[row], "\r"), std.mem.trimEnd(u8, whole[start..end], "\r"))) break :diff; var buf: [4096 + 32]u8 = undefined; - const click = look.diffClick(p, pane, row, at - start, &buf) orelse break :diff; - if (click.address) |address| return p.scratch.allocator().dupe(u8, address) catch ""; - word_from = click.word_from; + const got = look.rowAddressAt(p, pane, row, at - start, &buf) orelse break :row_address; + // Only when the served line is the one the address was read from. + if (!std.mem.eql(u8, std.mem.trimEnd(u8, got.line, "\r"), std.mem.trimEnd(u8, whole[start..end], "\r"))) break :row_address; + if (got.address) |address| return p.scratch.allocator().dupe(u8, address) catch ""; + word_from = got.word_from; } const line = whole[start..end]; if (at - start < word_from or word_from > line.len) return ""; @@ -1303,6 +1306,7 @@ test "after a Restore a new pane or column takes a serial past every one the old } test "a pane named before it is announced has its new under that name, and no rename before it" { + if (pardes.Term.ops == null) return error.SkipZigTest; // a shell const p = try withFile(testing.allocator, "one\n"); defer p.deinit(); const pane = p.panes[0].?; diff --git a/src/ninep/pane.zig b/src/ninep/pane.zig index 3fa45404..93759aa5 100644 --- a/src/ninep/pane.zig +++ b/src/ninep/pane.zig @@ -12,6 +12,7 @@ const modal = @import("../modal.zig"); const config = @import("../config.zig"); const fs = @import("../fs.zig"); const tree = @import("tree.zig"); +const locations = @import("../locations.zig"); const events = @import("events.zig"); const addressing = @import("addr.zig"); const ctl = @import("ctl.zig"); @@ -317,10 +318,10 @@ 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. - .data, .xdata => 0, + // data and xdata have none; and rows, made by each read. + .data, .xdata, .rows => 0, .tag => if (tagOf(p, pane)) |tag| tag.len else |_| 0, // a stat's length is a hint: none when the tag cannot be made .name => nameOf(p, pane).len + 1, .ctl => ctl: { @@ -396,6 +397,12 @@ pub fn read(p: *Pardes, req: Req, id: usize, pane: *Pane, file: PaneFile) Reply .mark => readFlag(p, req, !pf.nomark), .scroll => readFlag(p, req, !pf.noscroll), .look, .exec, .tagexec => ctl.readResults(p, req), + .rows => rows: { + const f = fileOf(pane) orelse break :rows tree.window(p, req, ""); + var text: std.Io.Writer.Allocating = .init(p.scratch.allocator()); + locations.formatRows(f.location_rows, &text.writer) catch break :rows Reply.fail(req.tag, E.NOMEM); + break :rows tree.window(p, req, text.written()); + }, .event => events.readQueue(p, req, &pf.events), .pty_status => pty.readStatus(p, req, id, pane), .pty_data => pty.readData(p, req, pf), @@ -441,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); @@ -498,6 +505,7 @@ pub fn write(p: *Pardes, req: Req, id: usize, pane: *Pane, file: PaneFile) Reply // A click in its tag: an event reader holding the pane hears it as // an `x` record (ctl.run), as acme's tag clicks are. .tagexec => ctl.command(p, req, pane.serial, true, true), + .rows => writeRows(p, req, pane), .event => events.writeEvent(p, req, id), .errors => if (appendErrors(p, id, req.data)) |took| .{ .tag = req.tag, .written = @intCast(took) } @@ -510,6 +518,36 @@ pub fn write(p: *Pardes, req: Req, id: usize, pane: *Pane, file: PaneFile) Reply }; } +pub const e_rows_line = "invalid rows: a row is a line, ending in a newline"; +pub const e_rows_text = "invalid rows: a line is no row (the README's rows line says what one is)"; +pub const e_rows_fit = "invalid rows: more rows than the text has lines, or one past its line's end"; + +/// Rows, whole lines of them (a write through a mount is cut anywhere: the +/// rest of a line waits for the open's next write, tree.writeLines): at +/// offset 0 they replace the pane's, at a later one they follow those it +/// holds. Parsed (locations.parseRows) and handed to File.setRows, which +/// refuses what the text cannot hold. +fn writeRows(p: *Pardes, req: Req, pane: *Pane) Reply { + const f = fileOf(pane) orelse return Reply.fail(req.tag, E.PERM); + if (req.data.len == 0) return .{ .tag = req.tag, .written = 0 }; + if (req.data[req.data.len - 1] != '\n') return tree.failText(req.tag, E.INVAL, e_rows_line); + const arena = p.scratch.allocator(); + const written = locations.parseRows(arena, req.data) catch |err| return switch (err) { + error.OutOfMemory => Reply.fail(req.tag, E.NOMEM), + error.BadRows => tree.failText(req.tag, E.INVAL, e_rows_text), + }; + const kept = if (req.off == 0) 0 else f.location_rows.len; + const all = arena.alloc(locations.Row, kept + written.len) catch return Reply.fail(req.tag, E.NOMEM); + @memcpy(all[0..kept], f.location_rows[0..kept]); + @memcpy(all[kept..], written); + const rows = locations.cloneRows(p.gpa, all) catch return Reply.fail(req.tag, E.NOMEM); + panes.File.setRows(p, f, rows) catch { + locations.freeRows(p.gpa, rows); + return tree.failText(req.tag, E.INVAL, e_rows_fit); + }; + return .{ .tag = req.tag, .written = @intCast(req.data.len) }; +} + /// spliceBody for a write of the open `handle`, in the undo step its open /// is making: it joins the step being made only when it is the same open's /// (or the step is anyone's, `joined_by` 0), another open's starting its @@ -981,6 +1019,8 @@ pub fn truncate(p: *Pardes, pane: *Pane, file: PaneFile) tree.Status { pf.limit = null; }, .dot => pf.dot_truncated = fileOf(pane) != null, + // `>` starts the rows over, as a write at 0 does. + .rows => if (fileOf(pane)) |f| panes.File.setRows(p, f, &.{}) catch unreachable, else => {}, } return .ok; @@ -1016,6 +1056,7 @@ test "rows through the line index are the ones counting newlines gives, at every } test "a terminal's body stats as long as it reads" { + if (pardes.Term.ops == null) return error.SkipZigTest; // a shell const gpa = testing.allocator; const p = try pardes.Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24 }); defer p.deinit(); @@ -1030,6 +1071,7 @@ test "a terminal's body stats as long as it reads" { } test "a body write to a terminal pane types at its shell" { + if (pardes.Term.ops == null) return error.SkipZigTest; // a shell const gpa = testing.allocator; const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 40, .rows = 10 }); defer p.deinit(); @@ -1240,6 +1282,7 @@ test "a limit write that fails keeps the limit a truncation cleared before it" { } test "index names a command's pane cmd, a shell's term" { + if (pardes.Term.ops == null) return error.SkipZigTest; // a command pane const p = try withFile(testing.allocator, "x\n"); defer p.deinit(); try testing.expectEqual(Status.ok, wr(p, Node.of(serialOf(p), .exec), "true\n").reply.status); @@ -1248,3 +1291,52 @@ test "index names a command's pane cmd, a shell's term" { const shell = try p.newShell(p.freeSlot().?, "/tmp"); try testing.expectEqualStrings("term", kindOf(shell)); } + +test "rows: a pane's rows read as lines, written whole or across writes, refused when its text cannot hold them" { + const gpa = testing.allocator; + const p = try withFile(gpa, "a.txt:3 one\n two\n"); + defer p.deinit(); + const rows = Node.of(serialOf(p), .rows); + try testing.expectEqualStrings("", rd(p, rows, 0, 4096).bytes); + const text = "m 3 0 0 0 0 7 8 3:0+3=keyword.add a.txt\ncd 0 0 0 0 0 0 0 - \n"; + try testing.expectEqual(Status.ok, wr(p, rows, text).reply.status); + try testing.expectEqualStrings(text, rd(p, rows, 0, 4096).bytes); + const f = &p.panes[0].?.file.?; + try testing.expectEqual(@as(usize, 2), f.location_rows.len); + try testing.expectEqualStrings("a.txt", f.location_rows[0].path); + try testing.expect(f.location_rows[1].declaration and f.location_rows[1].kind == .context); + // A write at 0 starts them over; one open's writes, cut mid-line, + // make one set of rows, its later writes following its first. + const h = call(p, .{ .tag = 1, .op = .open, .node = rows, .omode = 1 }).reply.handle; + try testing.expectEqual(Status.ok, call(p, .{ .tag = 2, .op = .write, .node = rows, .handle = h, .off = 0, .data = "m 3 0 0 0 0 7 8 - a.t" }).reply.status); + try testing.expectEqual(Status.ok, call(p, .{ .tag = 3, .op = .write, .node = rows, .handle = h, .off = 21, .data = "xt\np 4 0 0 0 0 0 0 - a.txt\n" }).reply.status); + _ = call(p, .{ .tag = 4, .op = .release, .node = rows, .handle = h }); + try testing.expectEqualStrings("m 3 0 0 0 0 7 8 - a.txt\np 4 0 0 0 0 0 0 - a.txt\n", rd(p, rows, 0, 4096).bytes); + // More rows than lines, an offset or styles past a line's end, a line + // that is no row: refused, the rows as they were. + for ([_][]const u8{ "m 1 0 0 0 0 0 0 - a\nm 1 0 0 0 0 0 0 - a\nm 1 0 0 0 0 0 0 - a\nm 1 0 0 0 0 0 0 - a\n", "m 1 0 0 0 0 12 0 - a\n", "m 1 0 0 0 0 0 8 9:0+1=add a\n", "q 1 0 0 0 0 0 0 - a\n", "m 1 0 0 0 0 0 0 - a" }) |bad| + try testing.expectEqual(Status.err, wr(p, rows, bad).reply.status); + try testing.expectEqual(@as(usize, 2), f.location_rows.len); + // `>` truncates: no rows. + _ = call(p, .{ .tag = 5, .op = .setattr, .node = rows, .truncate = true }); + try testing.expectEqualStrings("", rd(p, rows, 0, 4096).bytes); + // An edit drops them. + try testing.expectEqual(Status.ok, wr(p, rows, text).reply.status); + try testing.expectEqual(Status.ok, wr(p, Node.of(serialOf(p), .body), "more\n").reply.status); + try testing.expectEqual(@as(usize, 0), f.location_rows.len); +} + +test "rows: a +Search's rows read back as the addresses its text shows" { + const gpa = testing.allocator; + const p = try withFile(gpa, "x\n"); + defer p.deinit(); + try panes.Output.fillResults(p, 0, "/tmp", .search, "foo", try p.gpa.dupe(u8, "a.txt:1:1 foo\nb.txt:2:3 foo\n"), null); + const serial = for (p.panes) |slot| { + const pane = slot orelse continue; + const f = pane.file orelse continue; + if (f.output != null and f.location_rows.len > 0) break pane.serial; + } else return error.NoSearch; + const text = rd(p, Node.of(serial, .rows), 0, 4096).bytes; + try testing.expect(std.mem.indexOf(u8, text, "m 1 1 ") == 0); + try testing.expect(std.mem.indexOf(u8, text, " a.txt\n") != null and std.mem.indexOf(u8, text, "\nm 2 3 ") != null and std.mem.endsWith(u8, text, " b.txt\n")); +} diff --git a/src/ninep/pty.zig b/src/ninep/pty.zig index 7333fac7..be85a497 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; @@ -507,7 +507,7 @@ test "a pane that is not a terminal has no pty/ at all" { var buf: [32]th.Dirent = undefined; const files = th.dirents(rdir(p, dir, 0).bytes, &buf); - try testing.expectEqual(@as(usize, 18), files.len); + try testing.expectEqual(@as(usize, 19), files.len); try testing.expect(th.nameAt(files, "pty") == null); try testing.expectEqual(E.NOENT, look_up(p, dir, "pty_ctl").errno()); @@ -528,7 +528,7 @@ test "a terminal pane's pty/ holds exactly ctl, status and data" { var buf: [32]th.Dirent = undefined; const files = th.dirents(rdir(p, dir, 0).bytes, &buf); - try testing.expectEqual(@as(usize, 19), files.len); + try testing.expectEqual(@as(usize, 20), files.len); try testing.expect(th.nameAt(files, "pty").?.dir); const inside = th.dirents(rdir(p, Node.of(serial, .pty), 0).bytes, &buf); @@ -962,6 +962,7 @@ test "run on a command pane says no shell is there" { test "a run's answer says cut when its output's start is gone, and reads a bounded tail" { const gpa = testing.allocator; + if (pardes.Term.ops == null) return error.SkipZigTest; // it reads the emulator const p = try withTerm(gpa); defer p.deinit(); const node = Node.of(serialOf(p), .pty_run); @@ -1005,10 +1006,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 +1024,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); @@ -1048,7 +1049,7 @@ test "a run's answer says cut when its output's start is gone, and reads a bound _ = std.fmt.bufPrint(&line, "{d:0>8}", .{i}) catch unreachable; sh.put(p, &line); } - try testing.expect(!pane.terminal.?.stream.handler.out_start.?.garbage); + try testing.expect(!pardes.Term.emulatorOf(pane.terminal.?).stream.handler.out_start.?.garbage); sh.put(p, d ++ prompt); got = sh.answered(p, node, h, into); try testing.expect(std.mem.startsWith(u8, got, "exit 0 cut\n")); @@ -1061,14 +1062,14 @@ test "a run's answer says cut when its output's start is gone, and reads a bound const q = try withTerm(gpa); defer q.deinit(); const kept = q.panes[0].?; - kept.terminal.?.vt.screens.get(.primary).?.pages.limits.set(.bytes, 1); + pardes.Term.emulatorOf(kept.terminal.?).vt.screens.get(.primary).?.pages.limits.set(.bytes, 1); const run = Node.of(serialOf(q), .pty_run); sh.put(q, prompt); h = sh.send(q, run); sh.put(q, c); const lines = std.mem.asBytes(&@as([64][8]u8, @splat("pruned\r\n".*))); var fed: usize = 0; - while (!kept.terminal.?.stream.handler.out_start.?.garbage) : (fed += 1) { + while (!pardes.Term.emulatorOf(kept.terminal.?).stream.handler.out_start.?.garbage) : (fed += 1) { if (fed == 1000) return error.TestUnexpectedResult; sh.put(q, lines); } 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/ninep/testing.zig b/src/ninep/testing.zig index 14aeffea..a9f6d5de 100644 --- a/src/ninep/testing.zig +++ b/src/ninep/testing.zig @@ -114,6 +114,7 @@ pub fn withFile(gpa: std.mem.Allocator, text: []const u8) !*Pardes { } pub fn withTerm(gpa: std.mem.Allocator) !*Pardes { + if (pardes.Term.ops == null) return error.SkipZigTest; // a shell const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24 }); errdefer p.deinit(); while (p.nextEffect()) |_| {} diff --git a/src/ninep/tree.zig b/src/ninep/tree.zig index bca89466..73468ef8 100644 --- a/src/ninep/tree.zig +++ b/src/ninep/tree.zig @@ -25,6 +25,7 @@ pub const sources = @import("sources.zig"); pub const screen = @import("screen.zig"); const daemon = @import("../daemon.zig"); const panes = @import("../panes.zig"); +const Plumb = @import("../Plumb.zig"); const Pardes = pardes.Pardes; const Pane = pardes.Pane; @@ -99,7 +100,8 @@ fn truncates(req: Req) bool { return switch (Node.target(req.node) orelse return false) { .pane => true, .col => |c| c.file == .tag, - .top => |f| f == .tag, + .top => |f| f == .tag or f == .rules, + .port => false, }; } @@ -151,6 +153,13 @@ pub const Open = struct { /// text after that line held in `pending` until its read puts it /// in (ctl.fillPager), or its close hands it to the editor's step. pager: u32, + /// An open writing plumb/rules or plumb/send: `pending` holds what + /// is not whole yet (rule sets with no blank line after them, a + /// message short of its data). + plumb, + /// An open reading a plumb port (Plumb.zig's ports, plumber(4)'s): + /// the messages sent to it since the open, packed, a read each. + port: struct { index: u8, queue: events.Queue = .{} }, } = .{ .snapshot = null }, /// What a write to a file of command lines left unfinished: a last line /// with no newline yet, or an Edit block still open. A write through a @@ -207,7 +216,8 @@ pub const Open = struct { gpa.free(run.line); }, .frozen => |bytes| gpa.free(bytes), - .event, .pty_data, .ctl, .lines, .writes, .pager => {}, + .port => |*port| port.queue.deinit(gpa), + .event, .pty_data, .ctl, .lines, .writes, .pager, .plumb => {}, } o.pending.deinit(gpa); if (o.replay) |r| gpa.free(r.bytes); @@ -269,6 +279,13 @@ pub const TopFile = enum(u5) { /// the addons refused, a line each: `<kind> <version> <abi> /// static|loaded|refused: why [path]`. addons, + /// The plumber's (Plumb.zig, Plan 9's plumber(4)): `rules` and `send`. + plumb, + /// plumb/rules: the rules in force, plumb(6)'s; a write adds rule + /// sets, a `>` replaces them. + rules, + /// plumb/send: a write is a message, plumb(6)'s six lines and data. + send, pub fn fileName(f: TopFile) []const u8 { return if (f == .root) "/" else @tagName(f); @@ -276,15 +293,15 @@ pub const TopFile = enum(u5) { pub fn mode(f: TopFile) u16 { return switch (f) { - .root, .pane, .col => 0o755, - .look, .exec, .log, .focus, .ctl, .tag, .tagexec, .pager => 0o666, + .root, .pane, .col, .plumb => 0o755, + .look, .exec, .log, .focus, .ctl, .tag, .tagexec, .pager, .rules => 0o666, .README, .index, .status, .screen, .listeners, .new, .commands, .layout, .recent, .dumps, .sessions, .addons => 0o444, - .kbdin, .mousein => 0o222, + .kbdin, .mousein, .send => 0o222, }; } pub fn dir(f: TopFile) bool { - return f == .root or f == .pane or f == .col; + return f == .root or f == .pane or f == .col or f == .plumb; } }; @@ -313,6 +330,9 @@ pub const PaneFile = enum(u5) { /// A word run as a click in the pane's tag, as /tagexec is in the /// workspace's and col/<n>/exec in a column's. tagexec, + /// A line a body row: where it points and how it is coloured + /// (locations.formatRows), a results pane's; written, the pane's. + rows, pty, pty_ctl, pty_status, @@ -365,6 +385,10 @@ pub const ColFile = enum(u5) { } }; const col_bit: u59 = 1 << 58; +/// plumb/<port>: a port by its place in Plumb's list, which only grows; +/// past a pane serial's 32 bits and clear of the host tree's and the +/// archive's high bits (fs.os_node, sources.archive_node). +const port_bit: u59 = 1 << 40; pub const Node = packed struct(u64) { file: u5 = 0, @@ -379,11 +403,16 @@ pub const Node = packed struct(u64) { return @bitCast(Node{ .file = @backingInt(file), .serial = col_bit | @as(u59, serial) }); } + pub fn ofPort(index: u8) u64 { + return @bitCast(Node{ .serial = port_bit | @as(u59, index) }); + } + pub fn target(node: u64) ?Target { const n: Node = @bitCast(node); if (n.serial == 0) { return .{ .top = std.enums.fromInt(TopFile, n.file) orelse return null }; } + if (n.serial & port_bit != 0) return .{ .port = std.math.cast(u8, n.serial & ~port_bit) orelse return null }; if (n.serial & col_bit != 0) return .{ .col = .{ .serial = std.math.cast(u32, n.serial & ~col_bit) orelse return null, .file = std.enums.fromInt(ColFile, n.file) orelse return null, @@ -399,6 +428,7 @@ pub const Target = union(enum) { top: TopFile, pane: struct { serial: u32, file: PaneFile }, col: struct { serial: u32, file: ColFile }, + port: u8, }; /// Opening /pane/new makes a pane and reading the open fid answers its @@ -559,7 +589,7 @@ fn serve(p: *Pardes, req: Req) Reply { const target = Node.target(req.node) orelse return Reply.fail(req.tag, E.NOENT); if (req.op == .write or req.op == .setattr) p.fs.origin = switch (target) { .pane => |t| @as(u8, if (t.file == .body or t.file == .tag) 'E' else 'F'), - .top, .col => 'F', + .top, .col, .port => 'F', }; return switch (req.op) { .lookup => lookup(p, req, target), @@ -581,7 +611,7 @@ fn serve(p: *Pardes, req: Req) Reply { fn runAttr(p: *Pardes, req: Req, target: Target) ?Reply.Attr { const t = switch (target) { .pane => |t| t, - .top, .col => return null, + .top, .col, .port => return null, }; if (t.file != .pty_run) return null; const run = if (req.handle != 0) openOf(p, req) else for (&p.fs.opens) |*o| { @@ -593,6 +623,12 @@ fn runAttr(p: *Pardes, req: Req, target: Target) ?Reply.Attr { fn attrOf(p: *Pardes, target: Target) ?Reply.Attr { switch (target) { + .port => |i| return .{ + .name = Plumb.portName(p, i) orelse return null, + .node = Node.ofPort(i), + .mode = 0o444, + .mtime = p.fs.started, + }, .top => |f| return .{ .name = f.fileName(), .node = @backingInt(f), @@ -658,7 +694,7 @@ fn topSize(p: *Pardes, f: TopFile) u64 { // frame, /pane/new until an open has a pane to name, and the index, // layout, recent list and listeners, which a stat would otherwise // have to build to count. - .root, .pane, .col, .screen, .new, .layout, .index, .recent, .dumps, .addons, .listeners, .sessions, .kbdin, .mousein => 0, + .root, .pane, .col, .screen, .new, .layout, .index, .recent, .dumps, .addons, .listeners, .sessions, .kbdin, .mousein, .plumb, .rules, .send => 0, .tag => cols.headerText(p, null).?.len, .README => fs.help.len, .status => if (ctl.statusText(p)) |text| text.len else |_| 0, @@ -689,6 +725,7 @@ fn lookup(p: *Pardes, req: Req, target: Target) Reply { else => return Reply.fail(req.tag, E.NOTDIR), }, .col => |c| if (c.file == .dir) @backingInt(TopFile.col) else return Reply.fail(req.tag, E.NOTDIR), + .port => return Reply.fail(req.tag, E.NOTDIR), }; return handle(p, .{ .tag = req.tag, .op = .getattr, .node = parent }); } @@ -697,8 +734,9 @@ fn lookup(p: *Pardes, req: Req, target: Target) Reply { .top => |f| switch (f) { .root => root: { if (std.mem.eql(u8, name, "os")) return fs.osHandle(p, .{ .tag = req.tag, .op = .getattr, .node = fs.os_root }); - // `new` is reached in /pane, where the panes it makes are. - if (std.meta.stringToEnum(TopFile, name)) |t| if (t != .root and t != .new) break :root @backingInt(t); + // `new` is reached in /pane, where the panes it makes are, + // `rules` and `send` in /plumb. + if (std.meta.stringToEnum(TopFile, name)) |t| if (t != .root and t != .new and t != .rules and t != .send) break :root @backingInt(t); if (sources.node(name)) |n| return sources.handle(p, .{ .tag = req.tag, .op = .getattr, .node = n }); return Reply.fail(req.tag, E.NOENT); }, @@ -712,8 +750,10 @@ fn lookup(p: *Pardes, req: Req, target: Target) Reply { if (serial == 0) return Reply.fail(req.tag, E.NOENT); break :dir if (f == .pane) Node.of(serial, .dir) else Node.ofCol(serial, .dir); }, + .plumb => if (std.mem.eql(u8, name, "rules")) @backingInt(TopFile.rules) else if (std.mem.eql(u8, name, "send")) @backingInt(TopFile.send) else if (Plumb.portIndex(p, name)) |i| Node.ofPort(i) else return Reply.fail(req.tag, E.NOENT), else => return Reply.fail(req.tag, E.NOTDIR), }, + .port => return Reply.fail(req.tag, E.NOTDIR), .col => |c| col: { if (c.file != .dir) return Reply.fail(req.tag, E.NOTDIR); const f = std.meta.stringToEnum(ColFile, name) orelse return Reply.fail(req.tag, E.NOENT); @@ -752,7 +792,7 @@ fn stageDir(p: *Pardes, out: *std.ArrayList(u8), target: Target, off: u64) error .root => { // The guide, then what describes the session, then the // files that act, then the directories. - inline for (.{ TopFile.README, TopFile.index, TopFile.status, TopFile.focus, TopFile.ctl, TopFile.commands, TopFile.recent, TopFile.dumps, TopFile.addons, TopFile.look, TopFile.exec, TopFile.pager, TopFile.log, TopFile.screen, TopFile.listeners, TopFile.sessions, TopFile.layout, TopFile.tag, TopFile.tagexec, TopFile.kbdin, TopFile.mousein, TopFile.pane, TopFile.col }) |t| { + inline for (.{ TopFile.README, TopFile.index, TopFile.status, TopFile.focus, TopFile.ctl, TopFile.commands, TopFile.recent, TopFile.dumps, TopFile.addons, TopFile.look, TopFile.exec, TopFile.pager, TopFile.log, TopFile.screen, TopFile.listeners, TopFile.sessions, TopFile.layout, TopFile.tag, TopFile.tagexec, TopFile.kbdin, TopFile.mousein, TopFile.plumb, TopFile.pane, TopFile.col }) |t| { if (skip > 0) skip -= 1 else try stageDirent(out, p.gpa, @backingInt(t), t.dir(), t.fileName()); } if (skip > 0) skip -= 1 else try stageDirent(out, p.gpa, fs.os_root, true, "os"); @@ -773,6 +813,16 @@ fn stageDir(p: *Pardes, out: *std.ArrayList(u8), target: Target, off: u64) error try stageDirent(out, p.gpa, Node.of(serial, .dir), true, name); } }, + // plumber(4)'s order: rules, send, then the ports as rules + // named them. + .plumb => { + inline for (.{ TopFile.rules, TopFile.send }) |t| { + if (skip > 0) skip -= 1 else try stageDirent(out, p.gpa, @backingInt(t), false, t.fileName()); + } + for (p.plumber.ports.items, 0..) |name, i| { + if (skip > 0) skip -= 1 else try stageDirent(out, p.gpa, Node.ofPort(@intCast(i)), false, name); + } + }, .col => for (0..p.view().ncol) |c| { if (skip > 0) { skip -= 1; @@ -792,6 +842,7 @@ fn stageDir(p: *Pardes, out: *std.ArrayList(u8), target: Target, off: u64) error if (skip > 0) skip -= 1 else try stageDirent(out, p.gpa, Node.ofCol(c.serial, f), false, f.fileName()); } }, + .port => return error.NotDir, .pane => |t| { const id = p.paneBySerial(t.serial) orelse return error.FileNotFound; const terminal = p.panes[id].?.isTerminal(); @@ -842,11 +893,19 @@ fn open(p: *Pardes, req: Req, target: Target) Reply { .index, .layout, .recent, .dumps, .addons, .commands, .status, .listeners, .sessions => .{ .frozen = &.{} }, // The root's ctl opened only to read: its settings, frozen. .ctl => if (linesOpen(target, req)) .lines else .{ .frozen = &.{} }, + // One writer of the rules at a time, as plumber(4)'s. + .rules, .send => if (req.omode & 3 == 0) return .{ .tag = req.tag } else plumb: { + if (f == .rules) for (p.fs.opens) |o| if (o.node == req.node and o.what == .plumb) return failText(req.tag, E.BUSY, e_in_use); + break :plumb .plumb; + }, else => if (linesOpen(target, req)) .lines else return .{ .tag = req.tag }, }, .col => |c| if (layout.columnBySerial(p, c.serial) == null) return Reply.fail(req.tag, E.NOENT) else if (linesOpen(target, req)) .lines else if (c.file == .ctl) .{ .frozen = &.{} } else return .{ .tag = req.tag }, + // A reader of the port: what is sent to it from now on, and what a + // `client` rule held for its first. + .port => |i| if (req.omode & 3 != 0) return Reply.fail(req.tag, E.PERM) else .{ .port = .{ .index = i } }, .pane => |t| what: { const pn = p.panes[p.paneBySerial(t.serial) orelse return Reply.fail(req.tag, E.NOENT)].?; if (t.file.inPty() and !pn.isTerminal()) return Reply.fail(req.tag, E.NOENT); @@ -904,7 +963,8 @@ fn open(p: *Pardes, req: Req, target: Target) Reply { pn.fs.event_reader = pn.fs.event_reader or reader; }, .pty_data => pane_of.?.fs.pty_reader = true, - .run, .ctl, .lines, .writes, .pager => {}, + .port => |*port| Plumb.opened(p, port.index, &port.queue), + .run, .ctl, .lines, .writes, .pager, .plumb => {}, } return .{ .tag = req.tag, .handle = @intCast(i + 1) }; } @@ -915,7 +975,7 @@ fn remove(p: *Pardes, req: Req) Reply { const target = Node.target(req.node) orelse return Reply.fail(req.tag, E.NOENT); const t = switch (target) { .pane => |t| t, - .top => return Reply.fail(req.tag, E.PERM), + .top, .port => return Reply.fail(req.tag, E.PERM), .col => |c| return cols.remove(p, req, c.serial, c.file), }; if (t.file != .dir) return Reply.fail(req.tag, E.PERM); @@ -967,6 +1027,9 @@ fn releaseHandle(p: *Pardes, req: Req) void { if (t == .col and t.col.file == .tag) cols.released(p, t.col.serial); if (t == .top and t.top == .tag) cols.released(p, null); const o = openOf(p, req) orelse return; + // A message short of its data is dropped with its open, as plumber(4) + // drops a fid's writebuf; rule text left goes in at the editor's step. + if (o.what == .plumb and req.node == @backingInt(TopFile.send)) o.pending.clearRetainingCapacity(); // A /pager open's text, not read for, goes in at the editor's next // step (ctl.fillClosedPagers): this close need not wait for quiet. if (o.what == .pager and o.pending.items.len > 0) { @@ -999,7 +1062,7 @@ fn releaseHandle(p: *Pardes, req: Req) void { .ctl => if (pn.fs.lock == req.handle) { pn.fs.lock = null; }, - .snapshot, .log, .lines, .writes, .frozen, .pager => {}, + .snapshot, .log, .lines, .writes, .frozen, .pager, .plumb, .port => {}, }; o.deinit(p.gpa); } @@ -1017,7 +1080,8 @@ fn setattr(p: *Pardes, req: Req, target: Target) Reply { if (pane.truncate(p, p.panes[id].?, t.file) != .ok) return Reply.fail(req.tag, E.NOMEM); }, .col => |c| if (c.file == .tag and cols.truncate(p, c.serial) != .ok) return Reply.fail(req.tag, E.NOENT), - .top => |f| if (f == .tag and cols.truncate(p, null) != .ok) return Reply.fail(req.tag, E.NOMEM), + .top => |f| if (f == .tag and cols.truncate(p, null) != .ok) return Reply.fail(req.tag, E.NOMEM) else if (f == .rules) Plumb.clear(p), + .port => return Reply.fail(req.tag, E.PERM), }; return .{ .tag = req.tag, .attr = attrOf(p, target) orelse return Reply.fail(req.tag, E.NOENT) }; } @@ -1028,6 +1092,8 @@ fn read(p: *Pardes, req: Req, target: Target) Reply { if (open_record) |o| if (o.what == .pager) ctl.fillPager(p, o.what.pager, &o.pending) catch return Reply.fail(req.tag, E.NOMEM); // A listing reads what it was at the open. if (open_record) |o| if (o.what == .frozen) return window(p, req, o.what.frozen); + // A port: a message a read, held until one is sent. + if (open_record) |o| if (o.what == .port) return events.readQueue(p, req, &o.what.port.queue); const stream = if (open_record) |o| switch (o.what) { .log => o, .event => |reader| if (reader) o else null, @@ -1055,8 +1121,9 @@ fn read(p: *Pardes, req: Req, target: Target) Reply { fn readFile(p: *Pardes, req: Req, target: Target) Reply { switch (target) { .top => |f| return switch (f) { - .kbdin, .mousein => Reply.fail(req.tag, E.PERM), + .kbdin, .mousein, .send => Reply.fail(req.tag, E.PERM), .README => window(p, req, fs.help), + .rules => window(p, req, Plumb.inForce(p)), .index => index: { const out = p.fs.stage(p.gpa); var last: u32 = 0; @@ -1128,7 +1195,7 @@ fn readFile(p: *Pardes, req: Req, target: Target) Reply { break :serial Reply.fail(req.tag, E.NOMEM); break :serial stagedReply(p, req); }, - .root, .pane, .col => Reply.fail(req.tag, E.PERM), + .root, .pane, .col, .plumb => Reply.fail(req.tag, E.PERM), }, .pane => |t| { // A run's answer outlives the pane it ran in. @@ -1153,6 +1220,8 @@ fn readFile(p: *Pardes, req: Req, target: Target) Reply { .exec => ctl.readResults(p, req), else => Reply.fail(req.tag, E.PERM), }, + // Read through its open (read), never without one. + .port => return Reply.fail(req.tag, E.PERM), } } @@ -1163,7 +1232,8 @@ fn linesFile(target: Target) bool { .col => |c| c.file == .ctl or c.file == .exec, // `name` too: one name, however its writes cut it, applied once // its newline comes, or with its write when that is whole. - .pane => |t| t.file == .look or t.file == .exec or t.file == .ctl or t.file == .tagexec or t.file == .name, + .pane => |t| t.file == .look or t.file == .exec or t.file == .ctl or t.file == .tagexec or t.file == .name or t.file == .rows, + .port => false, }; } @@ -1173,6 +1243,7 @@ fn resultsFile(target: Target) bool { .top => |f| f == .look or f == .exec or f == .tagexec or f == .pager, .col => |c| c.file == .exec, .pane => |t| t.file == .look or t.file == .exec or t.file == .tagexec, + .port => false, }; } @@ -1219,6 +1290,7 @@ fn ctlFile(target: Target) bool { .top => |f| f == .ctl, .col => |c| c.file == .ctl, .pane => |t| t.file == .ctl, + .port => false, }; } @@ -1326,6 +1398,9 @@ fn writeLines(p: *Pardes, req: Req, target: Target) Reply { o.pending.shrinkRetainingCapacity(rest); var w = req; w.data = whole; + // At the offset its first byte was written at, an earlier write's + // held line included (a rows write at 0 starts the rows over). + w.off = (req.off + (req.data.len - data.len)) -| (end + rest - data.len); // The command pane this open was answered holds no lease against its // own next command (exec.leased): that one may run there again. if (resultsFile(target)) o.results.len = 0; @@ -1350,6 +1425,8 @@ fn writeNow(p: *Pardes, req: Req, target: Target) Reply { .pager => ctl.writePager(p, req), .tag => cols.write(p, req, null), .tagexec => cols.writeExec(p, req, null), + .rules => writeRules(p, req), + .send => writeSend(p, req), else => Reply.fail(req.tag, E.PERM), }, .pane => |t| { @@ -1364,6 +1441,64 @@ fn writeNow(p: *Pardes, req: Req, target: Target) Reply { .exec => cols.writeExec(p, req, c.serial), .dir => Reply.fail(req.tag, E.PERM), }, + .port => return Reply.fail(req.tag, E.PERM), + } +} + +/// plumb/rules: rule text added to the rules in force a rule set at a time, +/// as each is whole (a blank line after it, rules.c's morerules), the rest +/// at the open's close; a refusal is the write's, in plumb(6)'s words, the +/// rules as they were and the text it held dropped. +fn writeRules(p: *Pardes, req: Req) Reply { + const done: Reply = .{ .tag = req.tag, .written = @intCast(req.data.len) }; + // A close's rest (runClosedLines), or a write with no open: whole. + const o = openOf(p, req) orelse return if (Plumb.apply(p, true, "plumb/rules", req.data)) |why| failText(req.tag, E.INVAL, why) else done; + if (o.pending.items.len + req.data.len > Plumb.max_text) { + o.pending.clearRetainingCapacity(); + return failText(req.tag, E.INVAL, std.fmt.comptimePrint("rules too long; max {d} KiB", .{Plumb.max_text / 1024})); + } + o.pending.appendSlice(p.gpa, req.data) catch return Reply.fail(req.tag, E.NOMEM); + const end = Plumb.wholeSets(o.pending.items); + if (end == 0) return done; + const why = Plumb.apply(p, true, "plumb/rules", o.pending.items[0..end]); + if (why != null) o.pending.clearRetainingCapacity() else { + const rest = o.pending.items.len - end; + std.mem.copyForwards(u8, o.pending.items[0..rest], o.pending.items[end..]); + o.pending.shrinkRetainingCapacity(rest); + } + return if (why) |w| failText(req.tag, E.INVAL, w) else done; +} + +/// plumb/send: a message, its writes put together until its data is all +/// there (plumber(4)), then matched and sent: the write is answered when it +/// has gone where the rules say, or with why not, in Plan 9's words. +fn writeSend(p: *Pardes, req: Req) Reply { + const o = openOf(p, req); + const held = if (o) |op| op.pending.items.len > 0 else false; + if (held) o.?.pending.appendSlice(p.gpa, req.data) catch return Reply.fail(req.tag, E.NOMEM); + defer if (o) |op| if (op.pending.items.len > pending_cap) op.pending.clearRetainingCapacity(); + switch (Plumb.unpack(if (held) o.?.pending.items else req.data)) { + .bad => { + if (o) |op| op.pending.clearRetainingCapacity(); + return failText(req.tag, E.INVAL, Plumb.e_bad_msg); + }, + .more => |n| { + const op = o orelse return failText(req.tag, E.INVAL, Plumb.e_bad_msg); + if (op.pending.items.len + n > pending_cap) { + op.pending.clearRetainingCapacity(); + return failText(req.tag, E.INVAL, Plumb.e_bad_msg ++ ": over 1 MiB"); + } + if (!held) op.pending.appendSlice(p.gpa, req.data) catch return Reply.fail(req.tag, E.NOMEM); + return .{ .tag = req.tag, .written = @intCast(req.data.len) }; + }, + .msg => |m| { + defer if (o) |op| op.pending.clearRetainingCapacity(); + switch (Plumb.send(p, null, m, null)) { + .refused => |why| return failText(req.tag, E.IO, why), + .done, .look => {}, + } + return .{ .tag = req.tag, .written = @intCast(req.data.len) }; + }, } } @@ -1566,13 +1701,23 @@ test "readdir lists the root and a pane directory without creating anything" { @memcpy(top_bytes[0..top_reply.bytes.len], top_reply.bytes); const top = th.dirents(top_bytes[0..top_reply.bytes.len], &buf); try testing.expect(top.len >= 10); - for ([_][]const u8{ "README", "index", "status", "focus", "ctl", "commands", "recent", "dumps", "addons", "look", "exec", "pager", "log", "screen", "listeners", "sessions", "layout", "tag", "tagexec", "kbdin", "mousein", "pane", "col", "os" }, 0..) |name, i| { + for ([_][]const u8{ "README", "index", "status", "focus", "ctl", "commands", "recent", "dumps", "addons", "look", "exec", "pager", "log", "screen", "listeners", "sessions", "layout", "tag", "tagexec", "kbdin", "mousein", "plumb", "pane", "col", "os" }, 0..) |name, i| { try testing.expectEqualStrings(name, top[i].name); try testing.expectEqual(i >= 21, top[i].dir); } - try testing.expectEqual(@backingInt(TopFile.pane), top[21].node); - try testing.expectEqual(@backingInt(TopFile.col), top[22].node); - try testing.expectEqual(fs.os_root, top[23].node); + try testing.expectEqual(@backingInt(TopFile.plumb), top[21].node); + try testing.expectEqual(@backingInt(TopFile.pane), top[22].node); + try testing.expectEqual(@backingInt(TopFile.col), top[23].node); + try testing.expectEqual(fs.os_root, top[24].node); + // The plumber's directory: its rules, then send. + const plumb_reply = rdir(p, @backingInt(TopFile.plumb), 0); + var plumb_bytes: [256]u8 = undefined; + @memcpy(plumb_bytes[0..plumb_reply.bytes.len], plumb_reply.bytes); + var plumb_buf: [4]th.Dirent = undefined; + const plumb = th.dirents(plumb_bytes[0..plumb_reply.bytes.len], &plumb_buf); + // Then the ports the default rules name, in their order. + try testing.expectEqual(@as(usize, 4), plumb.len); + for ([_][]const u8{ "rules", "send", "web", "edit" }, plumb) |want, got| try testing.expectEqualStrings(want, got.name); var idbuf: [16]u8 = undefined; try testing.expect(th.nameAt(top, try std.fmt.bufPrint(&idbuf, "{d}", .{serial})) == null); try testing.expect(th.nameAt(top, "self") == null); @@ -1611,10 +1756,10 @@ test "readdir lists the root and a pane directory without creating anything" { const dir = rdir(p, Node.of(serial, .dir), 0); const files = th.dirents(dir.bytes, &buf); - try testing.expectEqual(@as(usize, 18), files.len); + try testing.expectEqual(@as(usize, 19), files.len); for ([_][]const u8{ - "name", "body", "tag", "ctl", "addr", "dot", "limit", "data", "xdata", - "sel", "dirty", "mark", "scroll", "errors", "event", "look", "exec", "tagexec", + "name", "body", "tag", "ctl", "addr", "dot", "limit", "data", "xdata", "sel", + "dirty", "mark", "scroll", "errors", "event", "look", "exec", "tagexec", "rows", }, 0..) |name, i| try testing.expectEqualStrings(name, files[i].name); try testing.expect(th.nameAt(files, ".") == null); @@ -2001,6 +2146,7 @@ test "a write with no newline waits for its newline or the close, whatever its s } test "look and exec read back what their own open's write touched; a fresh open reads the session's last" { + if (pardes.Term.ops == null) return error.SkipZigTest; // a shell, by Term const p = try th.withFile(testing.allocator, "x\n"); defer p.deinit(); const exec = @backingInt(TopFile.exec); diff --git a/src/panes.zig b/src/panes.zig index 99652b04..237693fa 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. @@ -171,7 +176,7 @@ pub const Pane = struct { /// be printing to it, and a reuse would hang it up. command_pty: bool = false, /// Its child pages as a terminal's does (`pardes -`, a +Pager), not - /// through cat: Look's `git show` of a commit (look.lookCommit). + /// through cat: Look's `git show` of a commit (hunks.lookedAtCommit). command_pages: bool = false, /// The shell a terminal runs when it is not the configured one (`Term /// fish`), owned. @@ -292,7 +297,7 @@ pub const Pane = struct { next_pointer_selection: u64 = 0, /// terminals only: the typed-text buffer standing in for shell rows - ovl: ?terminal.EditBuffer = null, + ovl: ?Text.EditBuffer = null, tty_filter: bool = false, msg: [256]u8 = undefined, msg_len: u16 = 0, @@ -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,10 +1556,10 @@ test { _ = Dir; _ = mini; _ = @import("Kind.zig"); - _ = terminal; } test "owned cwd preserves long paths aliases and failed updates" { + if (pardes.Term.ops == null) return error.SkipZigTest; // a shell var allocator = std.testing.FailingAllocator.init(std.testing.allocator, .{}); const p = try Pardes.init(allocator.allocator(), .{ .tty_only = true }); defer p.deinit(); @@ -1246,6 +1657,7 @@ test "owned cwd close copies are transactional across inherited chains" { } test "owned cwd column close allocates every copy before removing any pane" { + if (pardes.Term.ops == null) return error.SkipZigTest; // the classic boot's three shells var allocator = std.testing.FailingAllocator.init(std.testing.allocator, .{}); const p = try Pardes.init(allocator.allocator(), .{ .shells = 3, .cols = 100, .rows = 30 }); defer p.deinit(); @@ -1299,7 +1711,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, .{}); @@ -1365,6 +1777,7 @@ test "the Tutor pane is named +Tutor in the session's directory, never a bare pa } test "New opens an empty scratch below the caller, inheriting its directory" { + if (pardes.Term.ops == null) return error.SkipZigTest; // the classic boot's three shells const p = try Pardes.init(std.testing.allocator, .{ .shells = 3, .cols = 100, .rows = 30 }); defer p.deinit(); while (p.nextEffect()) |_| {} diff --git a/src/pardes.zig b/src/pardes.zig index 9f5c36ff..07e612e5 100644 --- a/src/pardes.zig +++ b/src/pardes.zig @@ -8,14 +8,18 @@ pub const glide = @import("glide.zig"); pub const FrameStats = @import("FrameStats.zig"); pub const modal = @import("modal.zig"); pub const look = @import("look.zig"); +pub const Plumb = @import("Plumb.zig"); pub const filesystem = @import("fs.zig"); 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"); +/// A program's colours on a pane's body (a terminal's cells, its images). +pub const ansi = @import("ansi.zig"); +/// Predicted echo for a replica's terminal panes (`Pardes.echo`). +pub const Echo = @import("echo.zig").Echo; pub const exec = @import("exec.zig"); const recent_files = @import("recent.zig"); const Store = @import("Store.zig"); @@ -72,14 +76,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 +287,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"; @@ -326,6 +329,7 @@ pub const Boot = Pardes.Boot; pub const Haptic = Pardes.Haptic; test "a compact tagline anchors at its own pane, and both shells step from the same origin" { + if (Term.ops == null) return error.SkipZigTest; // a shell const p = try Pardes.init(std.testing.allocator, .{ .cols = 120, .rows = 24 }); defer p.deinit(); _ = try p.newShell(1, ""); @@ -385,6 +389,7 @@ test { _ = @import("Addon.zig"); _ = @import("rollback.zig"); _ = @import("Core.zig"); + _ = @import("Plumb.zig"); _ = @import("lsp/Ask.zig"); _ = @import("lsp/lsp_client.zig"); _ = @import("Jump.zig"); @@ -392,7 +397,9 @@ test { _ = @import("Effect.zig"); _ = @import("tape.zig"); _ = @import("replica.zig"); + _ = Term; _ = @import("echo.zig"); + _ = @import("ansi.zig"); _ = @import("modal.zig"); _ = @import("tagline.zig"); _ = @import("hunks.zig"); @@ -420,7 +427,6 @@ test { _ = @import("recent.zig"); _ = @import("Store.zig"); _ = @import("Db.zig"); - _ = @import("pager.zig"); _ = @import("Places.zig"); _ = @import("FrameStats.zig"); _ = @import("Query.zig"); @@ -429,6 +435,5 @@ test { _ = @import("Tables.zig"); _ = @import("Handover.zig"); _ = @import("walk.zig"); - _ = screen_state; _ = @import("views.zig"); } diff --git a/src/plain/plain.zig b/src/plain/plain.zig new file mode 100644 index 00000000..6ca96fe9 --- /dev/null +++ b/src/plain/plain.zig @@ -0,0 +1,161 @@ +//! The plain records the core and the terminal both name +//! (docs/next-terminal.md, Phase 1): a frame's cells, their styles and +//! colours, the pictures over them and a key read. Data that needs +//! nothing else, in a module of its own: the core (surface.zig and +//! Event.zig, under their old names) and the terminal (src/term/) both +//! import it, and neither imports the other. +const std = @import("std"); +/// The terminal as the core sees it: its entries and the records they +/// take and give. +pub const term = @import("term.zig"); + +pub const Color = union(enum) { default, index: u8, rgb: [3]u8 }; + +pub const FontRole = enum(u8) { body, tagline }; + +pub const CellStyle = struct { + fg: Color = .default, + bg: Color = .default, + bold: bool = false, + dim: bool = false, + italic: bool = false, + blink: bool = false, + reverse: bool = false, + invisible: bool = false, + strikethrough: bool = false, + ul: enum(u3) { off, single, double, curly, dotted, dashed } = .off, + font_role: FontRole = .body, +}; + +pub const Cell = struct { + text: [7]u8 = @splat(' '), + len: u8 = 1, + style: CellStyle = .{}, + default: bool = true, + + pub fn grapheme(c: *const Cell) []const u8 { + return c.text[0..c.len]; + } + + pub fn visuallyEqual(a: *const Cell, b: *const Cell) bool { + if (a.default or b.default) return a.default and b.default; + return a.len == b.len and + std.mem.eql(u8, a.grapheme(), b.grapheme()) and + std.meta.eql(a.style, b.style); + } + + pub fn printableAscii(c: *const Cell) ?u8 { + if (c.default) return ' '; + if (c.len != 1) return null; + const byte = c.text[0]; + return if (byte >= ' ' and byte <= '~') byte else null; + } +}; + +/// A rectangle in pixels. +pub const RectPx = struct { + x: u32 = 0, + y: u32 = 0, + w: u32 = 0, + h: u32 = 0, +}; + +/// A rectangle in the frame's cells. +pub const RectCell = struct { x: u16 = 0, y: u16 = 0, w: u16 = 0, h: u16 = 0 }; + +/// The pixels a placement shows: RGBA, straight alpha, `stride` bytes a +/// row. They are the pane's, and stay put until its next frame. +pub const Raster = struct { + ptr: [*]const u8, + w: u32, + h: u32, + stride: u32, + + pub fn of(rgba: []const u8, w: usize, h: usize) Raster { + return .{ .ptr = rgba.ptr, .w = @intCast(w), .h = @intCast(h), .stride = @intCast(w * 4) }; + } + + pub fn bytes(r: Raster) []const u8 { + return r.ptr[0 .. @as(usize, r.stride) * r.h]; + } +}; + +/// A picture over the frame's cells, which a frontend realises: the window +/// as a texture kept by `key`, the tty as a kitty image, or either as glyph +/// art in `dst`'s cells (Art.zig, the frontends' own) where it cannot show +/// pixels or the pane asks for art. The frame lists them a pane at a time, +/// lowest first. +pub const Placement = struct { + pane: u8, + raster: Raster, + /// The part of `raster` shown. + src: RectPx, + /// The cells it lies over, which clip it. + dst: RectCell, + /// Where it goes in `dst`, in pixels from `dst`'s top left corner; + /// null: the frontend fits `src` there, no larger than it is, at the + /// top left (as glyph art, centred). + at: ?RectPx = null, + /// The pixels' identity (`keyOf`): one key is one picture, so a + /// frontend keeps what it uploaded under it. + key: u64, + /// A terminal program's kitty `z=`: below 0 it is under the text, + /// which a tty passes on to the terminal outside. + z: i32 = 0, + /// Rows of `raster` that alone differ from the picture under the key + /// `from`: a frontend still holding that one updates those rows. + dirty: ?Dirty = null, + art: Art = .{}, + + pub const Dirty = struct { from: u64, y: u32, h: u32 }; + + /// How the pane wants it drawn as glyph art: the Petscii, Palette and + /// Ascii words on an image pane, Petscii and TermImages on a terminal. + pub const Art = struct { + /// Glyph art even where pixels could be shown (Petscii on). + glyph: bool = false, + palette: Palette = .commodore, + /// Letters and signs among the glyphs, not only blocks and lines. + ascii: bool = true, + + pub const Palette = enum { commodore, terminal }; + }; + + /// A pane's picture `page` (a PDF's page, a terminal's image id; 0 for + /// an image) as of `revision`. + pub fn keyOf(serial: u32, page: u32, revision: u32) u64 { + return std.hash.Wyhash.hash(0, std.mem.asBytes(&[3]u32{ serial, page, revision })); + } +}; + +/// A key a frontend read (Event.zig). +pub const Key = struct { + cp: u21, // codepoint or one of the specials below + text: []const u8 = "", + ctrl: bool = false, + alt: bool = false, + shift: bool = false, + + pub const enter: u21 = 0x0D; + pub const escape: u21 = 0x1B; + pub const tab: u21 = 0x09; + pub const backspace: u21 = 0x7F; + // private-use plane for non-text keys, matching no real codepoint + pub const up: u21 = 0xF0001; + pub const down: u21 = 0xF0002; + pub const left: u21 = 0xF0003; + pub const right: u21 = 0xF0004; + pub const home: u21 = 0xF0005; + pub const end: u21 = 0xF0006; + pub const page_up: u21 = 0xF0007; + pub const page_down: u21 = 0xF0008; + pub const delete: u21 = 0xF0009; + pub const insert: u21 = 0xF000A; + pub const print_screen: u21 = 0xF000B; + pub const scroll_lock: u21 = 0xF000C; + pub const pause: u21 = 0xF000D; + pub const menu: u21 = 0xF000E; + /// F1 to F25, in order: Fn is `f1 + n - 1`. + pub const f1: u21 = 0xF0011; + pub const f25: u21 = f1 + 24; +}; diff --git a/src/plain/term.zig b/src/plain/term.zig new file mode 100644 index 00000000..dbc4fc87 --- /dev/null +++ b/src/plain/term.zig @@ -0,0 +1,432 @@ +//! The terminal as the core sees it (docs/next-terminal.md, Phase 1): the +//! entries (`Ops`) a terminal module gives the core, and the records they +//! take and give. A terminal's state, its replicas' encoder and tracks are +//! handles the core holds and never looks into; what it knows of them it is +//! told here, as numbers, bytes, text and cells. src/term/term.zig is the +//! one implementation (ghostty-vt behind it); src/Term.zig is the core's +//! side of it. +const std = @import("std"); +const plain = @import("plain.zig"); +const Color = plain.Color; +const CellStyle = plain.CellStyle; + +/// A terminal: its emulator, its parse and what is kept beside it. +pub const State = opaque {}; +/// What a session's authority keeps to encode its terminals for its peers +/// (one for all of them), and what it keeps of one terminal for them. +pub const Encoder = opaque {}; +pub const Track = opaque {}; +/// A replica's side of one terminal: what it was sent. +pub const Replica = opaque {}; + +/// Where the view and the cursor are, in rows counted from the top of the +/// history: `total` rows, the view's top at `offset`, `len` of them shown. +/// All zero without a terminal. +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, + /// Its grid's width (a pane's may differ while a resize is deferred). + cols: u16 = 0, +}; + +/// 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 }; + +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, +}; + +/// 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: Phase = .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: ?Finished = 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, + + pub const Phase = enum { none, prompt, input, running }; + pub const Finished = struct { seq: u32, status: ?i32 }; +}; + +/// 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, +}; + +/// 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, +}; + +/// How much of a row the prompt it starts with is. +pub const PromptCut = union(enum) { + /// no prompt: the row as the emulator dumps it + keep, + /// all prompt, nothing typed yet: show nothing of it + blank, + /// this many leading COLUMNS are the prompt; the rest is what was typed + /// at it + cut: usize, +}; + +/// 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. +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); + } +}; +/// Bytes `start..end` of a page's text, drawn in `style`. +pub const Span = struct { start: u32, end: u32, style: CellStyle }; + +// ---- its colours on the body ---- + +/// A theme's colours as a terminal's paint takes them. +pub const Ink = struct { + fg: ?[3]u8, + bg: ?[3]u8, + tag_fg: [3]u8, + tag_bg: [3]u8, + /// The theme's own sixteen, when it has them. + palette: ?[16][3]u8, + /// The sixteen the filter keys a program's colours to: `palette`, else + /// made of the theme's roles. + base: [16][3]u8, + + /// A palette index as the theme draws it: its own sixteen, else the + /// index. + pub fn palColor(ink: *const Ink, idx: u8) Color { + if (ink.palette) |pal| if (idx < 16) return .{ .rgb = pal[idx] }; + return .{ .index = idx }; + } +}; + +/// 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 = struct { + key: ?Key = null, + colors: [256][3]u8 = undefined, + + pub const Key = struct { bg: [3]u8, fg: [3]u8, base: [16][3]u8 }; +}; + +/// A program's colours mapped to the theme, once a frame: what a +Pager's +/// spans are drawn through (`spanColor`), as a terminal's cells are. +pub const Filter = struct { + target: *const [256][3]u8, + /// The theme's page and ink, and the page a program's colours are + /// drawn on (its OSC 11, keyed to the theme, else the theme's). + theme_bg: [3]u8, + theme_fg: [3]u8, + default_bg: [3]u8, + /// What a foreground too near the page's background becomes instead. + fallback_fg: [3]u8, + default_bg_luminance: f64, + fg_for_palette: [256]Color, + bg_for_palette: [256]Color, + /// The two answers for a cell that names no colour of its own. + fg_default: Color, + bg_default: Color, + cache_rgb: [256][3]u8 = undefined, + cache_key: [256]u8 = undefined, + cache_valid: [256]bool = @splat(false), +}; + +/// One cell of a terminal's view as its paint gives it: its style (its +/// colours the theme's already), the bytes it spells in the view's text, +/// and whether it is half of a wide one. +pub const Painted = struct { + style: CellStyle, + bytes: u16, + wide: enum(u2) { narrow, wide, spacer_tail, spacer_head }, +}; + +/// One row of a terminal's view as its paint gives it. +pub const PaintedRow = struct { + /// The shell marked it a prompt's: how much of it the prompt is. + prompt: ?PromptCut, + /// It holds kitty placeholder cells. + placeholder: bool, + /// Its cells given, from its first: the grid's past them are none. + len: u16, +}; + +/// Where a terminal's kitty images go, as the body lays out its rows: +/// `rows_of[v]` is the body row its view's row `v` shows on, null for one +/// not shown. +pub const ImagesAt = struct { + pane: u8, + serial: u32, + tx: u16, + body_y: u16, + cols: u16, + rows_of: []const ?u16, + /// The pane shows its terminal's rows as they are (tty mode): a prompt + /// row is the grid's then, and its images show. + tty_mode: bool, + /// The core's clock (animations step on it), and a cell's size in + /// pixels. + now_ms: u64, + cell_w: u32, + cell_h: u32, +}; + +/// What a predicted echo reads of a cell: its codepoint, whether the shell +/// marked it input, and its style's identity. +pub const EchoCell = struct { cp: u21, input: bool, style: u32 }; + +// ---- its replicas ---- + +/// Deltas a peer may have in flight. At 207 ms and 60 frames a second about +/// 13 are; past the bound a peer gets nothing until an acknowledgement, and +/// then the newest state, the ones between skipped. +pub const flight_bound = 32; + +/// What the authority knows of one peer of one terminal. +pub const Peer = struct { + /// The version last sent, which the next delta is against; 0: none, so + /// the next starts the replica afresh. + sent: u32 = 0, + /// The versions in flight, oldest first. + flight: [flight_bound]u32 = undefined, + n: u8 = 0, + /// The history rows its replica holds as holes, absolute, as the + /// replica keeps them (Replica.apply's rule, from what it was sent): + /// what `fill` sends before a step reads them. + top: u64 = 0, + holes: std.ArrayListUnmanaged([2]u64) = .empty, + + pub fn deinit(peer: *Peer, gpa: std.mem.Allocator) void { + peer.holes.deinit(gpa); + } + + /// Every version up to `seq` has landed. + pub fn ack(peer: *Peer, seq: u32) void { + var i: u8 = 0; + while (i < peer.n and peer.flight[i] <= seq) i += 1; + std.mem.copyForwards(u32, peer.flight[0 .. peer.n - i], peer.flight[i..peer.n]); + peer.n -= i; + } + + /// Start the peer afresh: it lost its state, or never had one. + pub fn reset(peer: *Peer) void { + var holes = peer.holes; + holes.clearRetainingCapacity(); + peer.* = .{ .holes = holes }; + } +}; + +/// A delta applied: its version, and what its authority sent beside it. +pub const Applied = struct { seq: u32, extra: []const u8 }; + +/// What the dump keeps of a terminal beside its emulator, by name as every +/// dump is (src/walk.zig, through the core's `Term.State`). +pub const Parts = struct { + reply: []const u8 = "", + reply_dropped: u32 = 0, + mouse_cell: ?Coordinate = null, + petscii: bool = false, + /// The view's top row, counted from the top of the history. + view: usize = 0, + phase: Prompt.Phase = .none, + started: u32 = 0, + prompts: u32 = 0, + declined: u32 = 0, + continuation: bool = false, + lost: bool = false, + finished: ?Prompt.Finished = null, + out_start: ?Coordinate = null, + out_end: ?Coordinate = null, + + /// A cell's place on a screen (ghostty's `Coordinate`, as it dumps). + pub const Coordinate = extern struct { x: u16 = 0, y: u32 = 0 }; +}; + +/// What reading its text can fail with. +pub const TextError = error{ OutOfMemory, WriteFailed, UnknownPoint }; + +/// The entries, as `term.ops` gives them. An error set named here is what +/// the core's callers name (the tape's `Failure` reads `open`'s, the text +/// readers' are edit.zig's); `anyerror` where the core only passes one on +/// or reports it. Each takes the handles above +/// (none is made without a terminal module: the core asks `Term.ops` +/// first). +pub const Ops = struct { + // ---- lifecycle ---- + /// A new terminal, `cols` by `rows`, allocated with `gpa` (its own from + /// then on). + open: *const fn (gpa: std.mem.Allocator, cols: u16, rows: u16) error{ OutOfMemory, InvalidValue }!*State, + /// It and what it holds, freed. + close: *const fn (s: *State, gpa: std.mem.Allocator) void, + /// 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. + due: *const fn (s: *const State) ?u64, + /// Loaded from a dump without its shell: its program's modes reset, its + /// history marked off from what the next shell prints. + revive: *const fn (s: *State) void, + /// The PNG resize workers kitty images are decoded with, started and + /// stopped with the host. + start: *const fn (gpa: std.mem.Allocator) void, + stop: *const fn () void, + /// The allocator it was opened with. + gpa: *const fn (s: *const State) std.mem.Allocator, + + // ---- the dump and the digest (`Term.State`'s walk hooks) ---- + /// Its screen into the replay digest (`view`: where its view is too). + digest: *const fn (s: *const State, h: *std.hash.Wyhash, view: bool) void, + /// What the dump keeps of it beside its emulator. + parts: *const fn (s: *const State) Parts, + /// Its emulator as the dump keeps it (ghostty's snapshot); `slim`: its + /// size alone (a join's dump, its first delta replaces it). + snapshot: *const fn (s: *const State, gpa: std.mem.Allocator, w: *std.Io.Writer, slim: bool) anyerror!void, + /// `snapshot`'s bytes and `parts` back into a new terminal. + load: *const fn (gpa: std.mem.Allocator, snapshot: []const u8, parts: *const Parts) anyerror!*State, + + // ---- output and view ---- + /// One read of its program's output (`Told` says where the tracked + /// rows went). + feed: *const fn (s: *State, bytes: []const u8, track: []const i32, rows: []i32, erased: []bool) Told, + // A null handle: what a pane without a terminal is told (all zero). + grid: *const fn (s: ?*const State) Grid, + viewTo: *const fn (s: *State, at: ?usize) void, + scroll: *const fn (s: *State, delta: i32) void, + follow: *const fn (s: *State) void, + resize: *const fn (s: *State, cols: u16, rows: u16, later: bool) void, + resizeDeferred: *const fn (s: *State) bool, + cellPixels: *const fn (s: *State, w: u32, h: u32) void, + replies: *const fn (s: *State) []const u8, + + // ---- input ---- + key: *const fn (s: *State, k: plain.Key, out: *std.Io.Writer) error{WriteFailed}!void, + mouse: *const fn (s: *State, buf: *[64]u8, action: MouseAction, button: ?MouseButton, mods: MouseMods, col: i32, row: i32, any_pressed: bool) []const u8, + wheel: *const fn (s: *State, buf: *[64]u8, turn: MouseButton, col: u16, row: u16, mods: MouseMods) ?[]const u8, + paste: *const fn (s: ?*const State, text: []u8) [3][]const u8, + modes: *const fn (s: ?*const State) Modes, + promptMoves: *const fn (s: *State, row: i32, col: i32) ?Moves, + + // ---- prompt and commands ---- + prompt: *const fn (s: ?*State) Prompt, + commandOutput: *const fn (s: ?*State, gpa: std.mem.Allocator, max_rows: usize) error{OutOfMemory}!CommandOutput, + endOutputHere: *const fn (s: *State) void, + + // ---- text ---- + scrollback: *const fn (s: ?*State, gpa: std.mem.Allocator) error{ OutOfMemory, WriteFailed }![]const u8, + scrollbackLen: *const fn (s: ?*State) usize, + textRows: *const fn (s: *State, alloc: std.mem.Allocator, scratch: std.mem.Allocator) TextError!Rows, + viewport: *const fn (s: *State, arena: std.mem.Allocator, cut: bool) TextError![]const []const u8, + /// Its rows `first` and the `count` after it (from the top of its + /// history) as text, a prompt's own cells cut off: `arena`'s. + editRows: *const fn (s: *State, arena: std.mem.Allocator, first: usize, count: usize) (TextError || error{ NoRow })![]const []const u8, + /// How much of its row `row` (from the top of its history) the prompt + /// it starts with is; null for a row no prompt starts. + promptCut: *const fn (s: *State, row: i32) ?PromptCut, + markRead: *const fn (s: *State) void, + /// What a predicted echo reads of cell `x`, `y` of its active area. + echoCell: *const fn (s: *const State, x: u16, y: u16) ?EchoCell, + + // ---- the pager ---- + /// `raw`, a program's output, as a terminal reads it: its text and its + /// SGR spans, every other control dropped. `gpa`'s. + page: *const fn (gpa: std.mem.Allocator, raw: []const u8) error{OutOfMemory}!Page, + /// The filter a +Pager's spans are drawn through (`spanColor`). + filter: *const fn (ink: *const Ink, palette: *FilterPalette) Filter, + spanColor: *const fn (f: *Filter, color: Color, is_bg: bool) Color, + + // ---- draw ---- + /// Its view's rows, `rows.len` of them, `cols` cells each, into + /// `cells`: each cell's style in the theme's colours (through the + /// filter when `filtered`), its bytes and width. + paint: *const fn (s: *State, ink: *const Ink, palette: *FilterPalette, filtered: bool, cols: u16, cells: []Painted, rows: []PaintedRow) void, + /// Its kitty images over the body's rows, appended to `out`, and their + /// placeholder cells blanked in `frame` (`frame_cols` wide). + images: *const fn (s: *State, gpa: std.mem.Allocator, at: ImagesAt, out: *std.ArrayList(plain.Placement), frame: []plain.Cell, frame_cols: u16) void, + petscii: *const fn (s: ?*const State) ?bool, + togglePetscii: *const fn (s: *State) void, + hasImages: *const fn (s: ?*const State) bool, + + // ---- its replicas ---- + encoder: *const fn (gpa: std.mem.Allocator) error{OutOfMemory}!*Encoder, + encoderFree: *const fn (e: *Encoder) void, + track: *const fn (gpa: std.mem.Allocator) error{OutOfMemory}!*Track, + /// A peer's track of it let go (`s` null: it is gone). + untrack: *const fn (t: *Track, gpa: std.mem.Allocator, s: ?*State) void, + /// What a peer is owed of it, a delta against what the peer was sent. + encode: *const fn (s: *State, e: *Encoder, t: *Track, peer: *Peer, out: *std.Io.Writer) anyerror!bool, + /// Rows of it a replica holds as holes. + encodeRows: *const fn (s: *State, e: *Encoder, t: *Track, lo: u64, hi: u64, out: *std.Io.Writer) anyerror!void, + wasRead: *const fn (s: *const State) bool, + clearRead: *const fn (s: *State) void, + replica: *const fn (gpa: std.mem.Allocator) error{OutOfMemory}!*Replica, + replicaFree: *const fn (r: *Replica, gpa: std.mem.Allocator) void, + /// The absolute row its replica's active area begins at. + replicaTop: *const fn (r: *const Replica) u64, + /// History rows `lo..hi` it does not hold. + missing: *const fn (r: *const Replica, lo: u64, hi: u64, out: *std.ArrayList([2]u64), gpa: std.mem.Allocator) error{OutOfMemory}!void, + apply: *const fn (s: *State, r: *Replica, bytes: []const u8) anyerror!Applied, + applyRows: *const fn (s: *State, r: *Replica, bytes: []const u8) anyerror!void, + shown: *const fn (s: *State, r: *const Replica) [2]u64, + blank: *const fn (s: *State, r: *const Replica, lo: u64, hi: u64) void, + dumpScreen: *const fn (s: *State, w: *std.Io.Writer) error{WriteFailed}!void, +}; diff --git a/src/plumbing b/src/plumbing new file mode 100644 index 00000000..4e8cd702 --- /dev/null +++ b/src/plumbing @@ -0,0 +1,51 @@ +# pardes's plumbing rules, in plumb(6)'s language: a plumbing file of +# your own names this one as `include basic`. A message (plumb/send) is +# matched against the rule sets in order; the first whose patterns all +# hold takes it, and its actions say where it goes: a port pardes reads +# itself (edit: a file or directory opened as Look opens one; web: the +# host's browser; a loaded kind by its name, `image`, `pdf`), another +# port a program reads, or a word or program started. One that none +# takes is Look's own: a file or directory opened, else the word +# searched for. A look sends what it looks at: type text, src pardes +# (term from a terminal's raw mode, a kind's name from its pane), wdir +# its pane's directory, data the name as Look reads it. + +# urls go to the web browser (the host's: xdg-open, open on macOS) +type is text +data matches 'https?://.*' +plumb to web + +# a diff or patch looked at bare is stacked in a +Diff; one with no +# hunk in it opens as text +type is text +data matches '.*\.(diff|patch)' +arg isfile $data +plumb start Diff $file + +# existing directories, and existing files at the place written after +# them, go to the editor; a file a kind shows (a picture, a PDF) to +# that kind +type is text +arg isdir $data +plumb to edit + +type is text +arg isfile $data +plumb to edit + +# a commit hash looked at in the editor, in a git work tree: git show, +# stacked in a +Diff (outside one, Diff declines and the word is +# searched for) +type is text +src is pardes +data matches '[0-9a-f]{7,40}' +data matches '[0-9a-f]*[0-9][0-9a-f]*' +data matches '[0-9a-f]*[a-f][0-9a-f]*' +plumb start Diff $0 + +# a diff paged (git show, git log -p) is shown stacked in a +Diff in +# its +Pager's place +type is text/x-diff +attr delete action +attr add action=showdiff +plumb to edit diff --git a/src/regexp.zig b/src/regexp.zig index 7bcbceff..87fc51d6 100644 --- a/src/regexp.zig +++ b/src/regexp.zig @@ -595,6 +595,14 @@ test "a \\x without two hex digits is refused, not handed to mvzr to panic on" { try std.testing.expectEqual(@as(usize, 1), (try rx.find("xA", 0, 1, 2)).?.start); } +test "a class's range may end at \\xff: UTF-8's high bytes as one class" { + var rx = try Regex.compile("[a-z\\x80-\\xff]+"); + const text = "-- café --"; + const m = (try rx.find(text, 0, text.len, text.len)).?; + try std.testing.expectEqualStrings("café", text[m.start..m.end]); + _ = try Regex.compile("[\\xff-\\xff]"); +} + test "a repeat inside a group gives back to what follows the group" { const Case = struct { pat: []const u8, text: []const u8, start: usize, end: usize }; for ([_]Case{ diff --git a/src/replica.zig b/src/replica.zig index dd6f34bc..5513b2d9 100644 --- a/src/replica.zig +++ b/src/replica.zig @@ -30,9 +30,9 @@ 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 Echo = @import("echo.zig").Echo; const Allocator = std.mem.Allocator; const Pardes = pardes.Pardes; @@ -169,6 +169,7 @@ pub const Authority = struct { const a = try gpa.create(Authority); errdefer gpa.destroy(a); a.* = .{ .gpa = gpa, .t = tape.memory(gpa), .core = undefined, .host = host }; + errdefer tape.release(&a.t); a.t.screen_state = screens; // One word a digest: every pty read is a unit. a.t.whole_digest = screens and std.c.getenv("PARDES_REPLICA_TRACE") == null; @@ -281,7 +282,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 +331,8 @@ 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, + /// Made the first time a terminal is encoded (`encoder`). + enc: ?*Term.Encoder = null, tracks: [pardes.MAX_PANES]?Tracked = @splat(null), peers: std.ArrayListUnmanaged(*[pardes.MAX_PANES]PeerOf) = .empty, free_peers: std.ArrayListUnmanaged(u16) = .empty, @@ -338,16 +340,16 @@ 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) }; + return .{ .gpa = gpa }; } /// `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); @@ -358,7 +360,7 @@ pub const Screens = struct { s.peers.deinit(s.gpa); s.free_peers.deinit(s.gpa); s.out.deinit(s.gpa); - s.enc.deinit(); + if (s.enc) |e| Term.encoderFree(e); } fn live(_: *const Screens, core: *Pardes, id: usize, tr: *const Tracked) bool { @@ -402,12 +404,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, try s.encoder(), tr.track, &pp.peer, &w.writer)) continue; try out.append(s.gpa, try s.gpa.dupe(u8, w.written())); } } @@ -440,14 +441,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 +456,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 +474,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 +486,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, try s.encoder(), tr.track, lo, hi, &w.writer); try out.append(s.gpa, try s.gpa.dupe(u8, w.written())); lo = hi; } @@ -497,7 +498,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,12 +507,20 @@ 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] = null; } - s.tracks[id] = .{ .serial = pane.serial, .state = pane.terminal.?, .track = .init(s.gpa) }; + s.tracks[id] = .{ .serial = pane.serial, .state = pane.terminal.?, .track = try Term.track(s.gpa) }; return &s.tracks[id].?; } + /// The encoder, made the first time a terminal is encoded. + fn encoder(s: *Screens) !*Term.Encoder { + if (s.enc) |e| return e; + s.enc = try Term.encoder(s.gpa); + return s.enc.?; + } + /// A peer's message (`Replica.screen`'s, `Replica.screenRequest`'s): /// an answer for it (owned), or null. pub fn take(s: *Screens, core: *Pardes, peer: u16, msg: []const u8) !?[]u8 { @@ -533,7 +542,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, try s.encoder(), 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 +682,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: 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 +748,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 +763,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| Term.replicaFree(sc.rep, 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 +1099,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 +1153,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,8 +1167,13 @@ 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); - slot.* = .{ .serial = m.serial }; + if (slot.*) |*old| Term.replicaFree(old.rep, pardes.panes.emulator_gpa); + slot.* = null; + const rep = Term.replica(pardes.panes.emulator_gpa) catch { + r.fail("no memory for a terminal's replica"); + return null; + }; + slot.* = .{ .serial = m.serial, .rep = rep }; } const sc = &slot.*.?; // The emulator is the authority's: on the C heap, outside the @@ -1168,7 +1182,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 +1190,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); + r.echo.delta(c, m.pane, Term.replicaTop(sc.rep)); // 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 +1203,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 +1238,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; + Term.missing(sc.rep, 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 +1865,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 +1916,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 +2232,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 +3106,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; @@ -3386,6 +3399,7 @@ test "another client's input first: a replica rolls back, replays it and applies } test "a delta applied under a speculation outlives its rollback: the terminal stays the authority's newest" { + if (pardes.Term.ops == null) return error.SkipZigTest; // a shell const gpa = std.testing.allocator; const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .boot = .tty }, TestHost.host(), true); defer a.deinit(); @@ -3422,7 +3436,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 +3450,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 +3459,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 +3474,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. @@ -3474,6 +3488,7 @@ test "a delta applied under a speculation outlives its rollback: the terminal st } test "a closed terminal brought back on a screen-state replica: its emulator on the C heap, never the rollback epoch's" { + if (pardes.Term.ops == null) return error.SkipZigTest; // a shell const gpa = std.testing.allocator; const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .boot = .tty }, TestHost.host(), true); defer a.deinit(); @@ -3498,6 +3513,7 @@ test "a closed terminal brought back on a screen-state replica: its emulator on } test "a view that sized a terminal closing leaves nothing queued: the others' replicas copy, type and agree" { + if (pardes.Term.ops == null) return error.SkipZigTest; // a shell const gpa = std.testing.allocator; const a = try Authority.init(gpa, .{ .cols = 100, .rows = 30, .boot = .tty }, TestHost.host(), true); defer a.deinit(); @@ -3544,6 +3560,7 @@ test "a view that sized a terminal closing leaves nothing queued: the others' re } test "a terminal sized again by a client's key: the step reads the grid it had, on both sides" { + if (pardes.Term.ops == null) return error.SkipZigTest; // a shell const gpa = std.testing.allocator; const a = try Authority.init(gpa, .{ .cols = 50, .rows = 20, .boot = .tty }, TestHost.host(), true); defer a.deinit(); @@ -3583,7 +3600,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 +3626,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); @@ -3623,6 +3640,7 @@ test "a terminal sized again by a client's key: the step reads the grid it had, } test "pardes's own keys over a terminal's history apply at once: its view moves here, a delta while they wait puts them on top again, the authority's ends the same" { + if (pardes.Term.ops == null) return error.SkipZigTest; // a shell const gpa = std.testing.allocator; const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .boot = .tty }, TestHost.host(), true); defer a.deinit(); @@ -3656,7 +3674,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 +3684,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 +3702,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 +3725,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" { @@ -3775,6 +3793,7 @@ test "a replica joined from a themed dump paints its taglines in the restored th } test "a host's Adopt and a terminal reader's failure are inputs: a replica makes the same pane" { + if (pardes.Term.ops == null) return error.SkipZigTest; // a shell, opened by a key const gpa = std.testing.allocator; // Its terminals as screen state, as a session's for its clients are. const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host(), true); @@ -4226,6 +4245,7 @@ test "a client joined from a dump makes a `/` query's rows as the session does, } test "a step that reads a terminal's rows as the core keeps them sends a new client the ones it holds as holes" { + if (pardes.Term.ops == null) return error.SkipZigTest; // a shell const gpa = std.testing.allocator; const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .boot = .tty }, PtyHost.host(), true); defer a.deinit(); 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 a5dbea8e..73789dce 100644 --- a/src/surface.zig +++ b/src/surface.zig @@ -2,6 +2,7 @@ //! the image placements laid over them, and the Surface that holds a frame. const pardes = @import("pardes.zig"); const std = @import("std"); +const plain = @import("plain"); const layout = @import("layout.zig"); const uucode = @import("uucode"); const vaxis = @import("vaxis"); @@ -11,56 +12,16 @@ const MAX_PANES = pardes.MAX_PANES; const Layer = @import("Layer.zig"); const MAX_TAG_LAYERS = pardes.MAX_TAG_LAYERS; -pub const Color = union(enum) { default, index: u8, rgb: [3]u8 }; - -pub const FontRole = enum(u8) { body, tagline }; - -pub const CellStyle = struct { - fg: Color = .default, - bg: Color = .default, - bold: bool = false, - dim: bool = false, - italic: bool = false, - blink: bool = false, - reverse: bool = false, - invisible: bool = false, - strikethrough: bool = false, - ul: enum(u3) { off, single, double, curly, dotted, dashed } = .off, - font_role: FontRole = .body, -}; - -pub const Cell = struct { - text: [7]u8 = @splat(' '), - len: u8 = 1, - style: CellStyle = .{}, - default: bool = true, - - pub fn grapheme(c: *const Cell) []const u8 { - return c.text[0..c.len]; - } - - pub fn visuallyEqual(a: *const Cell, b: *const Cell) bool { - if (a.default or b.default) return a.default and b.default; - return a.len == b.len and - std.mem.eql(u8, a.grapheme(), b.grapheme()) and - std.meta.eql(a.style, b.style); - } - - pub fn printableAscii(c: *const Cell) ?u8 { - if (c.default) return ' '; - if (c.len != 1) return null; - const byte = c.text[0]; - return if (byte >= ' ' and byte <= '~') byte else null; - } -}; - -/// A rectangle in pixels. -pub const RectPx = struct { - x: u32 = 0, - y: u32 = 0, - w: u32 = 0, - h: u32 = 0, -}; +// The plain records (src/plain/plain.zig) both the core and the terminal +// name, under the names the core has always called them. +pub const Color = plain.Color; +pub const FontRole = plain.FontRole; +pub const CellStyle = plain.CellStyle; +pub const Cell = plain.Cell; +pub const RectPx = plain.RectPx; +pub const RectCell = plain.RectCell; +pub const Raster = plain.Raster; +pub const Placement = plain.Placement; pub const PixelPoint = struct { x: u32, y: u32 }; @@ -113,73 +74,8 @@ pub fn containGeometry(iw: usize, ih: usize, max_w: u32, max_h: u32) ?NativeGeom return .{ .src = .{ .w = src_w, .h = src_h }, .dst = dst }; } -/// A rectangle in the frame's cells. -pub const RectCell = struct { x: u16 = 0, y: u16 = 0, w: u16 = 0, h: u16 = 0 }; - -/// The pixels a placement shows: RGBA, straight alpha, `stride` bytes a -/// row. They are the pane's, and stay put until its next frame. -pub const Raster = struct { - ptr: [*]const u8, - w: u32, - h: u32, - stride: u32, - - pub fn of(rgba: []const u8, w: usize, h: usize) Raster { - return .{ .ptr = rgba.ptr, .w = @intCast(w), .h = @intCast(h), .stride = @intCast(w * 4) }; - } - - pub fn bytes(r: Raster) []const u8 { - return r.ptr[0 .. @as(usize, r.stride) * r.h]; - } -}; -/// A picture over the frame's cells, which a frontend realises: the window -/// as a texture kept by `key`, the tty as a kitty image, or either as glyph -/// art in `dst`'s cells (Art.zig, the frontends' own) where it cannot show -/// pixels or the pane asks for art. The frame lists them a pane at a time, -/// lowest first. -pub const Placement = struct { - pane: u8, - raster: Raster, - /// The part of `raster` shown. - src: RectPx, - /// The cells it lies over, which clip it. - dst: RectCell, - /// Where it goes in `dst`, in pixels from `dst`'s top left corner; - /// null: the frontend fits `src` there, no larger than it is, at the - /// top left (as glyph art, centred). - at: ?RectPx = null, - /// The pixels' identity (`keyOf`): one key is one picture, so a - /// frontend keeps what it uploaded under it. - key: u64, - /// A terminal program's kitty `z=`: below 0 it is under the text, - /// which a tty passes on to the terminal outside. - z: i32 = 0, - /// Rows of `raster` that alone differ from the picture under the key - /// `from`: a frontend still holding that one updates those rows. - dirty: ?Dirty = null, - art: Art = .{}, - - pub const Dirty = struct { from: u64, y: u32, h: u32 }; - /// How the pane wants it drawn as glyph art: the Petscii, Palette and - /// Ascii words on an image pane, Petscii and TermImages on a terminal. - pub const Art = struct { - /// Glyph art even where pixels could be shown (Petscii on). - glyph: bool = false, - palette: Palette = .commodore, - /// Letters and signs among the glyphs, not only blocks and lines. - ascii: bool = true, - - pub const Palette = enum { commodore, terminal }; - }; - - /// A pane's picture `page` (a PDF's page, a terminal's image id; 0 for - /// an image) as of `revision`. - pub fn keyOf(serial: u32, page: u32, revision: u32) u64 { - return std.hash.Wyhash.hash(0, std.mem.asBytes(&[3]u32{ serial, page, revision })); - } -}; /// One part of the frame and where it is, placed once by `draw.place` /// before anything is painted: every painter and every shell reads the @@ -205,8 +101,6 @@ pub const Region = struct { /// A column below the workspace tag, its bar and panes: its left /// edge is the spine a pixel shell rules down it. column, - /// A drag's guide or a seam's hover hint, drawn over the panes. - guide, /// The debug stats box, drawn over the panes. debug, }; @@ -244,15 +138,9 @@ pub const Region = struct { /// it shows, in pixels. Its placements are laid at the whole pixel; a /// pixel frontend draws them the fraction higher. scroll_px: f64 = 0, - /// Cells the column-move rail takes off the right edge while it runs - /// there: layers and pixel shells stop short of them, the grid does not. - clip: u16 = 0, }; -/// Guides a frame can draw: a run of a column-move rail per pane it skips -/// the tags of, and a handful of border and hover dashes. -pub const MAX_GUIDES = MAX_PANES + 4; -pub const MAX_REGIONS = 1 + MAX_PANES * (4 + panes.Pane.Notices.max) + pardes.MAX_COLS * 3 + 1 + MAX_GUIDES + 1; +pub const MAX_REGIONS = 1 + MAX_PANES * (4 + panes.Pane.Notices.max) + pardes.MAX_COLS * 3 + 1 + 1; /// The colours a pixel shell draws its chrome in (rules, rails, grips, the /// tag underlay), resolved by the core each frame, so a frontend attached @@ -472,14 +360,6 @@ pub const Surface = struct { while (xx < x + w) : (xx += 1) s.at(xx, yy).* = .{}; } } - - /// swap ONLY the glyph, keeping the cell's colors — the resize-handle hint - pub fn overlayDash(s: *Surface, x: u16, y: u16, glyph: []const u8) void { - const c = s.at(x, y); - @memcpy(c.text[0..glyph.len], glyph); - c.len = @intCast(glyph.len); - c.default = false; - } }; test "cell visual equality ignores dead grapheme tail bytes" { diff --git a/src/syntax.zig b/src/syntax.zig index 2526e113..70399bf7 100644 --- a/src/syntax.zig +++ b/src/syntax.zig @@ -22,7 +22,7 @@ const ts_queries = if (enabled) @import("ts_queries") else struct {}; const LanguageFn = *const fn () callconv(.c) *const ts.Language; -pub const Syn = enum(u8) { none, keyword, string, number, comment }; +pub const Syn = grammar_manifest.Syn; /// A query compiled when first asked for: "" for none, null when it fails. const Lazy = struct { src: []const u8 = "", query: ?*ts.Query = null, failed: bool = false }; @@ -55,81 +55,6 @@ fn specCount() comptime_int { } return count; } -const typst_supplement = - \\ - \\(call item: (ident) @keyword) - \\(call item: (field field: (ident) @keyword)) - \\"#" @keyword - \\ -; - -fn querySrc(comptime g: grammar_manifest.Grammar) []const u8 { - const base = @field(ts_queries, g.name ++ "_highlights"); - const source = if (comptime std.mem.eql(u8, g.name, "typst")) base ++ typst_supplement else base; - return comptime colorQuery(source); -} - -fn colorQuery(comptime source: []const u8) []const u8 { - @setEvalBranchQuota(2_000_000); - var result: [source.len]u8 = undefined; - var written: usize = 0; - var at: usize = 0; - while (at < source.len) { - while (at < source.len) { - if (std.ascii.isWhitespace(source[at])) { - at += 1; - } else if (source[at] == ';') { - while (at < source.len and source[at] != '\n') at += 1; - } else break; - } - const begin = at; - var depth: usize = 0; - var colored = false; - var complete = false; - while (at < source.len) { - const byte = source[at]; - if (complete and (byte == '(' or byte == '[' or byte == '"')) break; - if (byte == ';') { - while (at < source.len and source[at] != '\n') at += 1; - continue; - } - if (byte == '"') { - at += 1; - while (at < source.len) : (at += 1) { - if (source[at] == '\\') { - at += 1; - } else if (source[at] == '"') { - at += 1; - break; - } - } - if (depth == 0) complete = true; - continue; - } - if (byte == '(' or byte == '[') depth += 1; - if (byte == ')' or byte == ']') { - depth -= 1; - if (depth == 0) complete = true; - } - if (byte == '@') { - const name = at + 1; - at = name; - while (at < source.len and (std.ascii.isAlphanumeric(source[at]) or - source[at] == '_' or source[at] == '.' or source[at] == '-')) at += 1; - colored = colored or synFor(source[name..at]) != .none; - continue; - } - at += 1; - } - if (colored) { - @memcpy(result[written..][0 .. at - begin], source[begin..at]); - written += at - begin; - } - } - const filtered = result[0..written].*; - return &filtered; -} - fn initSpecs() [specCount()]Spec { var out: [specCount()]Spec = undefined; var i = 0; @@ -139,7 +64,7 @@ fn initSpecs() [specCount()]Spec { .name = g.name, .exts = g.exts, .language = @extern(LanguageFn, .{ .name = "tree_sitter_" ++ g.name }), - .query_src = querySrc(g), + .query_src = @field(ts_queries, g.name ++ "_highlights"), .objects = .{ .src = @field(ts_queries, g.name ++ "_textobjects") }, .indents = .{ .src = @field(ts_queries, g.name ++ "_indents") }, }; @@ -219,7 +144,7 @@ fn ensure(spec: *Spec) !Selected { const capture_styles = spec.capture_styles[0..query.captureCount()]; for (capture_styles, 0..) |*style, id| { const name = query.captureNameForId(@intCast(id)) orelse ""; - style.* = @backingInt(synFor(name)); + style.* = @backingInt(grammar_manifest.synFor(name)); if (style.* == 0) query.disableCapture(name); } const parser = ts.Parser.create(); @@ -260,34 +185,6 @@ fn runQuery(styles: []u8, sel: Selected, tree: *ts.Tree, base: usize) void { } } -fn synFor(name: []const u8) Syn { - for ([_]struct { []const u8, Syn }{ - .{ "comment", .comment }, - .{ "string", .string }, - .{ "character", .string }, - .{ "number", .number }, - .{ "numeric", .number }, - .{ "float", .number }, - .{ "boolean", .number }, - .{ "keyword", .keyword }, - .{ "include", .keyword }, - .{ "conditional", .keyword }, - .{ "repeat", .keyword }, - .{ "title", .keyword }, - .{ "uri", .string }, - .{ "reference", .number }, - .{ "heading", .keyword }, - .{ "strong", .comment }, - .{ "bold", .comment }, - .{ "emphasis", .number }, - .{ "italic", .number }, - .{ "literal", .string }, - .{ "raw", .string }, - }) |m| { - if (std.mem.indexOf(u8, name, m[0]) != null) return m[1]; - } - return .none; -} pub fn highlightFileRange(gpa: std.mem.Allocator, path: []const u8, content: []const u8, start_raw: usize, end_raw: usize) ![]u8 { const zone = tracy.zone(@src(), "highlightFileRange"); defer zone.end(); @@ -1036,16 +933,17 @@ fn childOfKind(node: ts.Node, kind: []const u8) ?ts.Node { return null; } -/// A diff line's style byte carries whether the line was added or removed -/// over its syntax style (the low bits), so the painter can tint its row -/// and mark its prefix; Diff marks the words a changed line changed -/// (hunks.zig), drawn on a stronger tint. -pub const diff_added: u8 = 0x80; -pub const diff_removed: u8 = 0x40; -pub const diff_emph: u8 = 0x20; -/// A +Diff line added or removed whole, paired with no line it changed: -/// its row takes a faint tint, on its marker's byte. -pub const diff_whole: u8 = 0x10; +/// A style byte: a Syn in its low bits (syn_bits), and over them the +/// grounds a theme resolves (colors.Grounds): `ground_add` or `ground_del`, +/// a row added or removed (its hue); `ground_emph`, the stronger ground; +/// `ground_line`, the faint one. A row's first byte says its row's ground: +/// emph the stronger to the pane's edge, line the faint one, neither none +/// (only its marker in the hue). Any later byte's emph is its own cell's +/// ground: the words a changed line changed (hunks.zig). +pub const ground_add: u8 = 0x80; +pub const ground_del: u8 = 0x40; +pub const ground_emph: u8 = 0x20; +pub const ground_line: u8 = 0x10; pub const syn_bits: u8 = 0x0f; /// A file section's hunks are parsed together, each side as one text, in @@ -1070,7 +968,8 @@ var diff_clock: u64 = 0; /// the file its section names. A hunk's old side (context and removed /// lines) and new side (context and added lines) are each parsed whole, so /// a string or comment that spans lines colours as it does in the file. -/// Added and removed lines carry `diff_added`/`diff_removed`. A file in no +/// Added and removed lines carry `ground_add`/`ground_del`, the first byte +/// the strong row ground too (`ground_emph`). A file in no /// language pardes knows keeps the plain colours: added lines as strings, /// removed ones as numbers. pub fn highlightDiff(gpa: std.mem.Allocator, content: []const u8, start_raw: usize, end_raw: usize) ![]u8 { @@ -1185,13 +1084,14 @@ fn paintDiffPiece(gpa: std.mem.Allocator, window: DiffWindow, bytes: []const u8, for (kinds) |kind| { const line = lines.next() orelse break; const style: u8 = switch (kind) { - .added => @backingInt(Syn.string) | diff_added, - .removed => @backingInt(Syn.number) | diff_removed, + .added => @backingInt(Syn.string) | ground_add, + .removed => @backingInt(Syn.number) | ground_del, .no_newline => @backingInt(Syn.comment), .hunk => @backingInt(Syn.keyword), else => 0, }; if (style != 0) window.fill(at + offset, line.len, style); + if (style & (ground_add | ground_del) != 0 and line.len > 0) window.fill(at + offset, 1, style | ground_emph); offset += line.len + 1; } } @@ -1273,13 +1173,14 @@ fn paintHunk(gpa: std.mem.Allocator, out: []u8, bytes: []const u8, kinds: []cons if (kind == .context or kind == .removed) old_at += code_len + 1; if (kind == .context or kind == .added) new_at += code_len + 1; const flag: u8 = switch (kind) { - .added => diff_added, - .removed => diff_removed, + .added => ground_add, + .removed => ground_del, else => 0, }; if (flag != 0) for (out[offset..][0..line.len]) |*b| { b.* |= flag; }; + if (flag != 0 and line.len > 0) out[offset] |= ground_emph; } } @@ -1680,9 +1581,12 @@ test "syntax highlightDiff colors unified diff lines by prefix" { // A file in no known language: each line in one colour, and tinted. try std.testing.expectEqual(Syn.number, diffSynAt(styles, diff_text, "-old line", 0)); try std.testing.expectEqual(Syn.string, diffSynAt(styles, diff_text, "+new line", 0)); - try std.testing.expect(styles[std.mem.indexOf(u8, diff_text, "-old line").?] & diff_removed != 0); - try std.testing.expect(styles[std.mem.indexOf(u8, diff_text, "+new line").? + 4] & diff_added != 0); - try std.testing.expect(styles[std.mem.indexOf(u8, diff_text, " context").?] & (diff_added | diff_removed) == 0); + try std.testing.expect(styles[std.mem.indexOf(u8, diff_text, "-old line").?] & ground_del != 0); + try std.testing.expect(styles[std.mem.indexOf(u8, diff_text, "+new line").? + 4] & ground_add != 0); + try std.testing.expect(styles[std.mem.indexOf(u8, diff_text, " context").?] & (ground_add | ground_del) == 0); + // The row's ground on its first byte: the strong one, its other bytes none. + try std.testing.expect(styles[std.mem.indexOf(u8, diff_text, "-old line").?] & ground_emph != 0); + try std.testing.expect(styles[std.mem.indexOf(u8, diff_text, "+new line").? + 4] & (ground_emph | ground_line) == 0); } test "syntax a Zig hunk is coloured as Zig, each side parsed whole" { @@ -1714,9 +1618,9 @@ test "syntax a Zig hunk is coloured as Zig, each side parsed whole" { try std.testing.expectEqual(Syn.string, diffSynAt(styles, diff_text, "new words defer", 10)); // The prefix is no code: it carries the tint alone. const added = std.mem.indexOf(u8, diff_text, "+ side").?; - try std.testing.expectEqual(diff_added, styles[added]); - try std.testing.expect(styles[std.mem.indexOf(u8, diff_text, "42").?] & diff_added != 0); - try std.testing.expect(styles[std.mem.indexOf(u8, diff_text, "7,").?] & diff_removed != 0); + try std.testing.expectEqual(ground_add | ground_emph, styles[added]); + try std.testing.expect(styles[std.mem.indexOf(u8, diff_text, "42").?] & ground_add != 0); + try std.testing.expect(styles[std.mem.indexOf(u8, diff_text, "7,").?] & ground_del != 0); try std.testing.expectEqual(Syn.comment, diffSynAt(styles, diff_text, "index 111", 0)); // A window in the middle is coloured as the whole is. @@ -1763,7 +1667,7 @@ test "syntax a deleted file's lines are coloured in its language" { defer std.testing.allocator.free(styles); try std.testing.expectEqual(Syn.keyword, diffSynAt(styles, diff_text, "enum", 0)); try std.testing.expectEqual(Syn.comment, diffSynAt(styles, diff_text, "// the end", 3)); - try std.testing.expect(styles[std.mem.indexOf(u8, diff_text, "enum").?] & diff_removed != 0); + try std.testing.expect(styles[std.mem.indexOf(u8, diff_text, "enum").?] & ground_del != 0); try std.testing.expectEqual(Syn.comment, diffSynAt(styles, diff_text, "deleted file", 0)); } @@ -1812,9 +1716,9 @@ test "syntax git diff output in a command pane is told and coloured by its rows" try std.testing.expectEqual(Syn.keyword, diffSynAt(styles, text, "fn main", 0)); try std.testing.expectEqual(Syn.number, diffSynAt(styles, text, "42", 0)); // The wrapped row stays an added line, and inside the comment. - try std.testing.expect(styles[std.mem.indexOf(u8, text, "wrapped rest").?] & diff_added != 0); + try std.testing.expect(styles[std.mem.indexOf(u8, text, "wrapped rest").?] & ground_add != 0); try std.testing.expectEqual(Syn.comment, diffSynAt(styles, text, "wrapped rest", 0)); - try std.testing.expect(styles[std.mem.indexOf(u8, text, "return").?] & diff_removed != 0); + try std.testing.expect(styles[std.mem.indexOf(u8, text, "return").?] & ground_del != 0); } test "syntax a section's small hunks share one parse" { @@ -1836,7 +1740,7 @@ test "syntax a section's small hunks share one parse" { try std.testing.expectEqual(@as(usize, 2), cached); // x.zig's three hunks, and y.zig's try std.testing.expectEqual(Syn.keyword, diffSynAt(styles, diff_text, "@@ -10", 0)); try std.testing.expectEqual(Syn.number, diffSynAt(styles, diff_text, "2;\n@@ -20", 0)); - try std.testing.expect(styles[std.mem.indexOf(u8, diff_text, "@@ -10").?] & (diff_added | diff_removed) == 0); + try std.testing.expect(styles[std.mem.indexOf(u8, diff_text, "@@ -10").?] & (ground_add | ground_del) == 0); } test "syntax a hunk painted once is kept, and a long one is parsed in pieces" { @@ -1909,8 +1813,7 @@ test "syntax query filtering preserves upstream colors" { inline for (grammar_manifest.all) |grammar| { if (comptime grammarSelected(grammar)) { const selected = (try forLang(grammar.name)).?; - const raw_source = @field(ts_queries, grammar.name ++ "_highlights") ++ - (if (comptime std.mem.eql(u8, grammar.name, "typst")) typst_supplement else ""); + const raw_source = @field(ts_queries, grammar.name ++ "_highlights_unfiltered"); var error_offset: u32 = 0; const raw_query = try ts.Query.create(selected.lang, raw_source, &error_offset); defer raw_query.destroy(); @@ -1918,7 +1821,7 @@ test "syntax query filtering preserves upstream colors" { reference.query = raw_query; reference.capture_styles = try std.testing.allocator.alloc(u8, raw_query.captureCount()); defer std.testing.allocator.free(reference.capture_styles); - for (reference.capture_styles, 0..) |*style, id| style.* = @backingInt(synFor(raw_query.captureNameForId(@intCast(id)) orelse "")); + for (reference.capture_styles, 0..) |*style, id| style.* = @backingInt(grammar_manifest.synFor(raw_query.captureNameForId(@intCast(id)) orelse "")); const tree = selected.parser.parseString(source, null) orelse return error.ParseFailed; defer tree.destroy(); var expected: [source.len]u8 = @splat(0); 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..1420d9e3 100644 --- a/src/TerminalImages.zig +++ b/src/term/TerminalImages.zig @@ -8,14 +8,17 @@ //! moves with the text it was put on, and a virtual one (`U=1`) shown //! through the U+10EEEE placeholder cells the program prints. const std = @import("std"); +const plain = @import("plain"); const ghostty_vt = @import("ghostty-vt"); -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 = plain.RectPx; +/// Pixels one image may decode to (RGBA, 4 bytes each): checked from its +/// header before it is decoded. +const image_decode_pixels: usize = 64 * 1024 * 1024; /// 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. @@ -140,7 +143,7 @@ fn decodePng(gpa: std.mem.Allocator, bytes: []const u8) ghostty_vt.sys.DecodeErr if (bytes.len < 24 or !std.mem.startsWith(u8, bytes, "\x89PNG\r\n\x1a\n") or !std.mem.eql(u8, bytes[12..16], "IHDR")) return error.InvalidData; const w = std.mem.readInt(u32, bytes[16..20], .big); const h = std.mem.readInt(u32, bytes[20..24], .big); - if (@as(u64, w) * h > pardes.memory.limits.image_decode_pixels) return error.InvalidData; + if (@as(u64, w) * h > image_decode_pixels) return error.InvalidData; const got = wuffs.png.decode(gpa, bytes) catch return error.InvalidData; if (got.data.len != @as(usize, got.width) * got.height * 4) { gpa.free(got.data); @@ -160,38 +163,36 @@ fn decodePng(gpa: std.mem.Allocator, bytes: []const u8) ghostty_vt.sys.DecodeErr /// columns the body shows, from `tx`. pub fn draw( ti: *TerminalImages, - p: *pardes.Pardes, - s: *pardes.Surface, + gpa: std.mem.Allocator, vt: *ghostty_vt.Terminal, - pane_id: u8, - serial: u32, - tx: u16, - body_y: u16, - cols: u16, + where: plain.term.ImagesAt, rows_of: []const ?u16, + out: *std.ArrayList(plain.Placement), + frame: []plain.Cell, + frame_cols: u16, ) void { var conv = ti.converted.valueIterator(); while (conv.next()) |c| c.used = false; - defer ti.prune(p.gpa); + defer ti.prune(gpa); const screen = vt.screens.active; const storage = &screen.kitty_images; // Animations step on the core's clock, as this frame shows them; the // shown frame is `renderData()` (a new `generation` each step, which // the caches key on). - const now_ms = p.clock.stepped_ns / std.time.ns_per_ms; + const now_ms = where.now_ms; ti.animation_due_ms = if (storage.animationTick(vt.io(), now_ms)) |delay| now_ms +| delay else null; const pages = &screen.pages; const top = pages.getTopLeft(.viewport); const bottom = pages.getBottomRight(.viewport) orelse return; - const cw: u32 = @max(1, p.view().cell_pixels.w); - const ch: u32 = @max(1, p.view().cell_pixels.h); - const ctx: Ctx = .{ .ti = ti, .p = p, .pane = pane_id, .serial = serial, .tx = tx, .body_y = body_y, .cols = cols, .rows_of = rows_of, .cw = cw, .ch = ch }; + const cw: u32 = @max(1, where.cell_w); + const ch: u32 = @max(1, where.cell_h); + const ctx: Ctx = .{ .ti = ti, .gpa = gpa, .out = out, .pane = where.pane, .serial = where.serial, .tx = where.tx, .body_y = where.body_y, .cols = where.cols, .rows_of = rows_of, .cw = cw, .ch = ch }; // Handed on lowest z first (the storage's order is a hash map's), the // order a shell draws them in; equal z keeps the order they came in. - const first = s.placements.items.len; - defer std.sort.insertion(pardes.Placement, s.placements.items[first..], {}, struct { - fn lessThan(_: void, a: pardes.Placement, b: pardes.Placement) bool { + const first = out.items.len; + defer std.sort.insertion(plain.Placement, out.items[first..], {}, struct { + fn lessThan(_: void, a: plain.Placement, b: plain.Placement) bool { return a.z < b.z; } }.lessThan); @@ -205,8 +206,8 @@ pub fn draw( if (v >= rows_of.len) continue; const row = rows_of[v] orelse continue; for (@as(usize, at.viewport.x)..@as(usize, at.viewport.x) + run.width) |x| { - if (x >= cols) break; - const cell = s.at(tx + @as(u16, @intCast(x)), body_y + row); + if (x >= where.cols) break; + const cell = &frame[@as(usize, where.body_y + row) * frame_cols + where.tx + x]; cell.text[0] = ' '; cell.len = 1; } @@ -267,7 +268,8 @@ pub fn draw( const Ctx = struct { ti: *TerminalImages, - p: *pardes.Pardes, + gpa: std.mem.Allocator, + out: *std.ArrayList(plain.Placement), pane: u8, serial: u32, tx: u16, @@ -285,7 +287,7 @@ const Ctx = struct { const x0 = @max(dst.x, 0); const x1 = @min(dst.x + dst.w, @as(i64, ctx.cols) * cw); if (x1 <= x0) return; - const rgba = ctx.ti.pixelsOf(ctx.p.gpa, img) orelse return; + const rgba = ctx.ti.pixelsOf(ctx.gpa, img) orelse return; const first_row = @divFloor(@max(dst.y, 0), ch); const last_row = @min(@divFloor(dst.y + dst.h - 1, ch), @as(i64, @intCast(ctx.rows_of.len)) - 1); var v = first_row; @@ -303,7 +305,7 @@ const Ctx = struct { }; const c0: u16 = @intCast(@divFloor(x0, cw)); const c1: u16 = @intCast(@divFloor(x1 + cw - 1, cw)); - _ = ctx.p.appendPlacement(.{ + ctx.out.append(ctx.gpa, .{ .pane = ctx.pane, .raster = .of(rgba, img.width, img.height), .src = piece, @@ -314,10 +316,10 @@ const Ctx = struct { .w = @intCast(x1 - x0), .h = @intCast(y1 - y0), }, - .key = pardes.Placement.keyOf(ctx.serial, img.id, @truncate(img.generation)), + .key = plain.Placement.keyOf(ctx.serial, img.id, @truncate(img.generation)), .z = z, .art = .{ .glyph = ctx.ti.petscii }, - }); + }) catch {}; } } }; diff --git a/src/pager.zig b/src/term/pager.zig index e4ccbab4..0cf2ee21 100644 --- a/src/pager.zig +++ b/src/term/pager.zig @@ -5,28 +5,20 @@ //! 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 plain = @import("plain"); +const CellStyle = plain.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 }; +pub const Span = plain.term.Span; /// 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); - } -}; +pub const Page = plain.term.Page; /// `raw`, a program's output for a terminal, as text and its spans. Both /// are `gpa`'s. @@ -352,3 +344,20 @@ test "bytes that are not UTF-8 page as U+FFFD, the text around them kept" { 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..59085578 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 @@ -32,6 +32,7 @@ //! `applyRows`). const std = @import("std"); const vt = @import("ghostty-vt"); +const plain = @import("plain"); const snapshot = vt.snapshot; pub const Terminal = vt.Terminal; const Page = vt.page.Page; @@ -198,7 +199,7 @@ fn clampHoles(holes: *std.ArrayList([2]u64), oldest: u64) void { /// Deltas a peer may have in flight. At 207 ms and 60 frames a second about /// 13 are; past the bound a peer gets nothing until an acknowledgement, and /// then the newest state, the ones between skipped. -pub const bound = 32; +pub const bound = plain.term.flight_bound; /// What a peer holds once it has a version: the addresses of its active /// rows and its meta. A delta against it sends no blob for these. @@ -290,60 +291,30 @@ pub const Track = struct { } }; -/// What the authority knows of one peer of one terminal. -pub const Peer = struct { - /// The version last sent, which the next delta is against; 0: none, so - /// the next starts the replica afresh. - sent: u32 = 0, - /// The versions in flight, oldest first. - flight: [bound]u32 = undefined, - n: u8 = 0, - /// The history rows its replica holds as holes, absolute, as the - /// replica keeps them (Replica.apply's rule, from what it was sent): - /// what `fill` sends before a step reads them. - top: u64 = 0, - holes: std.ArrayListUnmanaged([2]u64) = .empty, - - pub fn deinit(peer: *Peer, gpa: std.mem.Allocator) void { - peer.holes.deinit(gpa); - } +/// What the authority knows of one peer of one terminal: a plain record +/// both sides name (src/plain/term.zig), the core keeping one a peer. +pub const Peer = plain.term.Peer; - /// Every version up to `seq` has landed. - pub fn ack(peer: *Peer, seq: u32) void { - var i: u8 = 0; - while (i < peer.n and peer.flight[i] <= seq) i += 1; - std.mem.copyForwards(u32, peer.flight[0 .. peer.n - i], peer.flight[i..peer.n]); - peer.n -= i; - } - - /// Start the peer afresh: it lost its state, or never had one. - pub fn reset(peer: *Peer) void { - var holes = peer.holes; - holes.clearRetainingCapacity(); - peer.* = .{ .holes = holes }; - } - - /// Its replica's holes once it applies a delta to `tr`'s newest version - /// against `base`, as Replica.apply makes them. - fn noteSent(peer: *Peer, gpa: std.mem.Allocator, tr: *const Track, base: ?*const Known, rows: u16) !void { - const top = tr.rows.top; - const history = tr.history; - if (base) |b| { - if (top > peer.top) { - const tail = @min(top -| b.top, rows, history); - if (top - peer.top >= @as(u64, rows) + history) { - peer.holes.clearRetainingCapacity(); - if (history > tail) try peer.holes.append(gpa, .{ top - history, top - tail }); - } else if (top - tail > peer.top) try peer.holes.append(gpa, .{ peer.top, top - tail }); - } - } else { - peer.holes.clearRetainingCapacity(); - if (history > 0) try peer.holes.append(gpa, .{ top - history, top }); +/// Its replica's holes once it applies a delta to `tr`'s newest version +/// against `base`, as Replica.apply makes them. +fn noteSent(peer: *Peer, gpa: std.mem.Allocator, tr: *const Track, base: ?*const Known, rows: u16) !void { + const top = tr.rows.top; + const history = tr.history; + if (base) |b| { + if (top > peer.top) { + const tail = @min(top -| b.top, rows, history); + if (top - peer.top >= @as(u64, rows) + history) { + peer.holes.clearRetainingCapacity(); + if (history > tail) try peer.holes.append(gpa, .{ top - history, top - tail }); + } else if (top - tail > peer.top) try peer.holes.append(gpa, .{ peer.top, top - tail }); } - peer.top = top; - clampHoles(&peer.holes, top -| history); + } else { + peer.holes.clearRetainingCapacity(); + if (history > 0) try peer.holes.append(gpa, .{ top - history, top }); } -}; + peer.top = top; + clampHoles(&peer.holes, top -| history); +} /// The delta's fixed header: u32 seq, u32 base (0: none, the replica /// starts afresh), u8 flags, u32 epoch, u64 meta, u16 cursor x and y, u8 @@ -376,7 +347,7 @@ pub fn encode(e: *Encoder, tr: *Track, peer: *Peer, t: *Terminal, changes: u32, tr.cache_base = base_version; } try out.writeAll(tr.cache.written()); - try peer.noteSent(e.gpa, tr, base, t.rows); + try noteSent(peer, e.gpa, tr, base, t.rows); peer.sent = tr.version; peer.flight[peer.n] = tr.version; peer.n += 1; @@ -513,7 +484,7 @@ pub const Replica = struct { if (r.scratch) |*s| s.deinit(); } - pub const Applied = struct { seq: u32, extra: []const u8 }; + pub const Applied = plain.term.Applied; /// Write one delta into `t`: the seq to acknowledge, and the caller's /// extra bytes (borrowed from `bytes`). error.BaseMismatch: the delta @@ -1135,282 +1106,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; @@ -1516,149 +1211,3 @@ test "several deltas in flight land in order, and a peer at the bound waits for try testing.expectEqual(@as(u64, 0), s.stats.refused); } -test "a replica's terminal pane draws as its authority's does" { - 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(); - const b = try pardes.Pardes.init(gpa, .{ .tty_only = true, .cols = 60, .rows = 16 }); - defer b.deinit(); - while (a.nextEffect()) |_| {} - while (b.nextEffect()) |_| {} - var fa = std.heap.ArenaAllocator.init(gpa); - defer fa.deinit(); - var fb = std.heap.ArenaAllocator.init(gpa); - defer fb.deinit(); - // Laid out once, so both panes have their size before the first delta. - _ = try a.render(fa.allocator()); - _ = try b.render(fb.allocator()); - const ta = &a.panes[0].?.terminal.?.vt; - const tb = &b.panes[0].?.terminal.?.vt; - var enc: Encoder = .init(gpa); - defer enc.deinit(); - var peer: Peer = .{}; - defer peer.deinit(gpa); - var tr: Track = .init(gpa); - defer tr.deinit(gpa, ta); - var rep: Replica = .{}; - defer rep.deinit(gpa); - var delta: std.Io.Writer.Allocating = .init(gpa); - defer delta.deinit(); - var line: [256]u8 = undefined; - for (0..60) |i| { - const bytes = try std.fmt.bufPrint(&line, "\x1b[1;3{d}m{d}\x1b[0m 漢字 e\u{301} \x1b[48;2;{d};40;60mbg\x1b[0m and then some text that wraps past the width of the pane\r\n", .{ i % 8, i, i * 4 % 256 }); - a.update(.{ .output = .{ .pane = 0, .bytes = bytes } }); - delta.clearRetainingCapacity(); - try testing.expect(try encode(&enc, &tr, &peer, ta, @intCast(i + 1), "", &delta.writer)); - peer.ack((try rep.apply(gpa, std.Io.Threaded.global_single_threaded.io(), tb, delta.written())).seq); - b.needs_frame = true; - _ = fa.reset(.retain_capacity); - _ = fb.reset(.retain_capacity); - const sa = try a.render(fa.allocator()); - const sb = try b.render(fb.allocator()); - const r = a.view().rects[0]; - // The body: below the pane's tag row. - for (r.y + 1..r.y + r.h) |y| for (r.x..r.x + r.w) |x| { - const ca = sa.at(@intCast(x), @intCast(y)); - const cb = sb.at(@intCast(x), @intCast(y)); - if (!ca.visuallyEqual(cb)) { - std.debug.print("step {d}: cell {d},{d}: '{s}' vs '{s}'\n", .{ i, x, y, ca.grapheme(), cb.grapheme() }); - return error.ReplicaDrawsDifferently; - } - }; - } -} - -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/term/term.zig b/src/term/term.zig new file mode 100644 index 00000000..87c06611 --- /dev/null +++ b/src/term/term.zig @@ -0,0 +1,164 @@ +//! The terminal, a module of its own (docs/next-terminal.md, Phase 1): +//! ghostty-vt's emulator and what pardes keeps beside it (terminal.zig), +//! the screen state its replicas are sent (screen_state.zig), the kitty +//! images it draws (TerminalImages.zig) and the pager's parse (pager.zig). +//! It imports std, ghostty-vt, wuffs, zstbi and `plain`, never the core: +//! the core reaches it through `ops` (src/Term.zig), the records of +//! src/plain/term.zig in and out. +const std = @import("std"); +const plain = @import("plain"); +const iface = plain.term; +const terminal_ = @import("terminal.zig"); +const pager = @import("pager.zig"); +const screen_state_ = @import("screen_state.zig"); +const TerminalImages = terminal_.TerminalImages; + +/// The screen state replicas are sent, its streams and soak (test/replicas.zig). +pub const screen_state = screen_state_; +/// The emulator itself, for the tests that read it through a core +/// (test/terminal.zig). +pub const terminal = terminal_; + +pub const ops: iface.Ops = .{ + .open = cast(iface.Ops, "open", terminal_.open), + .close = cast(iface.Ops, "close", terminal_.close), + .due = cast(iface.Ops, "due", terminal_.due), + .revive = cast(iface.Ops, "revive", terminal_.revive), + .start = TerminalImages.start, + .stop = TerminalImages.stop, + .gpa = cast(iface.Ops, "gpa", terminal_.gpaOf), + .digest = cast(iface.Ops, "digest", terminal_.digest), + .parts = cast(iface.Ops, "parts", terminal_.parts), + .snapshot = cast(iface.Ops, "snapshot", terminal_.snapshot), + .load = cast(iface.Ops, "load", terminal_.load), + .feed = cast(iface.Ops, "feed", terminal_.feed), + .grid = cast(iface.Ops, "grid", terminal_.grid), + .viewTo = cast(iface.Ops, "viewTo", terminal_.viewTo), + .scroll = cast(iface.Ops, "scroll", terminal_.scroll), + .follow = cast(iface.Ops, "follow", terminal_.follow), + .resize = cast(iface.Ops, "resize", terminal_.resize), + .resizeDeferred = cast(iface.Ops, "resizeDeferred", terminal_.resizeDeferred), + .cellPixels = cast(iface.Ops, "cellPixels", terminal_.cellPixels), + .replies = cast(iface.Ops, "replies", terminal_.replies), + .key = cast(iface.Ops, "key", terminal_.key), + .mouse = cast(iface.Ops, "mouse", terminal_.mouse), + .wheel = cast(iface.Ops, "wheel", terminal_.wheel), + .paste = cast(iface.Ops, "paste", terminal_.paste), + .modes = cast(iface.Ops, "modes", terminal_.modes), + .promptMoves = cast(iface.Ops, "promptMoves", terminal_.promptMoves), + .prompt = cast(iface.Ops, "prompt", terminal_.prompt), + .commandOutput = cast(iface.Ops, "commandOutput", terminal_.commandOutput), + .endOutputHere = cast(iface.Ops, "endOutputHere", terminal_.endOutputHere), + .scrollback = cast(iface.Ops, "scrollback", terminal_.scrollback), + .scrollbackLen = cast(iface.Ops, "scrollbackLen", terminal_.scrollbackLen), + .textRows = cast(iface.Ops, "textRows", terminal_.textRows), + .viewport = cast(iface.Ops, "viewport", terminal_.viewport), + .editRows = cast(iface.Ops, "editRows", terminal_.editRows), + .promptCut = cast(iface.Ops, "promptCut", terminal_.promptCutAt), + .markRead = cast(iface.Ops, "markRead", terminal_.markRead), + .echoCell = cast(iface.Ops, "echoCell", terminal_.echoCell), + .page = pager.parse, + .filter = terminal_.pagerFilter, + .spanColor = terminal_.spanColor, + .paint = cast(iface.Ops, "paint", terminal_.paint), + .images = cast(iface.Ops, "images", terminal_.images), + .petscii = cast(iface.Ops, "petscii", terminal_.petscii), + .togglePetscii = cast(iface.Ops, "togglePetscii", terminal_.togglePetscii), + .hasImages = cast(iface.Ops, "hasImages", terminal_.hasImages), + .encoder = cast(iface.Ops, "encoder", terminal_.encoder), + .encoderFree = cast(iface.Ops, "encoderFree", terminal_.encoderFree), + .track = cast(iface.Ops, "track", terminal_.track), + .untrack = cast(iface.Ops, "untrack", terminal_.untrack), + .encode = cast(iface.Ops, "encode", terminal_.encode), + .encodeRows = cast(iface.Ops, "encodeRows", terminal_.encodeRows), + .wasRead = cast(iface.Ops, "wasRead", terminal_.wasRead), + .clearRead = cast(iface.Ops, "clearRead", terminal_.clearRead), + .replica = cast(iface.Ops, "replica", terminal_.replica), + .replicaFree = cast(iface.Ops, "replicaFree", terminal_.replicaFree), + .replicaTop = cast(iface.Ops, "replicaTop", terminal_.replicaTop), + .missing = cast(iface.Ops, "missing", terminal_.missing), + .apply = cast(iface.Ops, "apply", terminal_.apply), + .applyRows = cast(iface.Ops, "applyRows", terminal_.applyRows), + .shown = cast(iface.Ops, "shown", terminal_.shown), + .blank = cast(iface.Ops, "blank", terminal_.blank), + .dumpScreen = cast(iface.Ops, "dumpScreen", terminal_.dumpScreen), +}; + +/// The term's handle types as the interface names them, and the module's +/// own behind each: a pointer to one is a pointer to the other. +const handles = .{ + .{ iface.State, terminal_.State }, + .{ iface.Encoder, screen_state_.Encoder }, + .{ iface.Track, screen_state_.Track }, + .{ iface.Replica, screen_state_.Replica }, +}; + +/// The interface's handle for one of this module's own types, or the type +/// itself. +fn handleOf(comptime T: type) type { + inline for (handles) |pair| if (T == pair[1]) return pair[0]; + return switch (@typeInfo(T)) { + .pointer => |p| if (p.size != .one) T else if (p.attrs.@"const") *const handleOf(p.child) else *handleOf(p.child), + .optional => |o| ?handleOf(o.child), + else => T, + }; +} + +/// Every error of `Have` is one of `Want`'s (anyerror holds them all). +fn within(comptime Have: type, comptime Want: type) bool { + const want = @typeInfo(Want).error_set.error_names orelse return true; + const have = @typeInfo(Have).error_set.error_names orelse return false; + outer: for (have) |h| { + for (want) |w| if (std.mem.eql(u8, h, w)) continue :outer; + return false; + } + return true; +} + +/// The errors of result `H` that result `W` has not, named. +fn missingFrom(comptime H: type, comptime W: type) []const u8 { + if (@typeInfo(H) != .error_union or @typeInfo(W) != .error_union) return ""; + const want = @typeInfo(@typeInfo(W).error_union.error_set).error_set.error_names orelse return ""; + const have = @typeInfo(@typeInfo(H).error_union.error_set).error_set.error_names orelse return " (anyerror)"; + var out: []const u8 = ": not"; + outer: for (have) |h| { + for (want) |w| if (std.mem.eql(u8, h, w)) continue :outer; + out = out ++ " " ++ h; + } + return out; +} + +/// `f`, one of this module's own entries, as the `Ops` field `name`: the +/// same function, its handles the interface's opaque ones. Refused at +/// compile time unless every parameter and the result match but for them. +fn cast(comptime O: type, comptime name: []const u8, comptime f: anytype) @FieldType(O, name) { + @setEvalBranchQuota(100_000); + const Want = @typeInfo(@FieldType(O, name)).pointer.child; + const want = @typeInfo(Want).@"fn"; + const have = @typeInfo(@TypeOf(f)).@"fn"; + if (want.param_types.len != have.param_types.len) @compileError(name ++ ": not as many parameters as Ops says"); + inline for (want.param_types, have.param_types, 0..) |w, h, i| { + if (w.? != handleOf(h.?)) @compileError(std.fmt.comptimePrint("{s}: parameter {d} is {s}, Ops says {s}", .{ name, i, @typeName(h.?), @typeName(w.?) })); + } + // A narrower error set is the same function pointer: an error is its + // number whatever set names it. + const W = want.return_type.?; + const H = have.return_type.?; + const same_result = switch (@typeInfo(W)) { + // Ops says anyerror: any error set of the same payload. + .error_union => |we| switch (@typeInfo(H)) { + .error_union => |he| we.payload == handleOf(he.payload) and within(he.error_set, we.error_set), + else => false, + }, + else => W == handleOf(H), + }; + if (!same_result) @compileError(name ++ ": returns " ++ @typeName(H) ++ ", Ops says " ++ @typeName(W) ++ missingFrom(H, W)); + return @ptrCast(&f); +} + +test { + _ = &ops; + _ = terminal_; + _ = pager; + _ = screen_state_; +} diff --git a/src/term/terminal.zig b/src/term/terminal.zig new file mode 100644 index 00000000..71a2f3de --- /dev/null +++ b/src/term/terminal.zig @@ -0,0 +1,1524 @@ +//! A terminal: its VT emulator, the OSC 133 cycle its shell marks, its +//! text, its view as cells, and the Filter that recolours output to the +//! theme. The core reaches it through src/term/term.zig's `ops`. +const std = @import("std"); +const plain = @import("plain"); +const Key = plain.Key; +const Term = plain.term; +const screen_state = @import("screen_state.zig"); + +const ghostty_vt = @import("ghostty-vt"); +const Ink = plain.term.Ink; +const FilterPalette = plain.term.FilterPalette; +const Filter = plain.term.Filter; +const Painted = plain.term.Painted; +const PaintedRow = plain.term.PaintedRow; +const ImagesAt = plain.term.ImagesAt; +const PromptCut = plain.term.PromptCut; + +pub const VtSlot = ghostty_vt.Terminal; +/// 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; +pub const TerminalImages = if (images_enabled) @import("TerminalImages.zig") else void; +pub const StreamSlot = ghostty_vt.Stream(MarkedHandler); + +/// The `aid` pardes's injected bash and fish marks carry (host_io.zig). +pub const prompt_aid = "pardes"; + +/// ghostty's handler, plus where the shell is in its command cycle as +/// its OSC 133 marks tell it: ghostty parses D's exit status and drops +/// it, and /pane/<n>/pty/run waits on exactly that. Only marks carrying +/// pardes's own `aid` move it, so fish's native marks, a nested shell's +/// and a stray `133;D` in some file being printed all pass it by. +pub const MarkedHandler = struct { + inner: ghostty_vt.TerminalStream.Handler, + phase: Term.Prompt.Phase = .none, + /// Counts commands started (C at the input phase). + started: u32 = 0, + /// Counts prompts drawn (B), so a line the shell refused without + /// running (a fish syntax error: no C, no D, a new prompt) shows. + prompts: u32 = 0, + /// D marks outside a running command: the shell handled a line + /// without starting it (bash on a syntax error prints no C). + declined: u32 = 0, + /// The newest prompt continues an unfinished line (bash's PS2, marked + /// `k=c`): the shell still holds the start of the command. + continuation: bool = false, + /// Where the newest command's output began (its C) and ended (its + /// D) on the primary screen, pinned so scrolling keeps them. + out_start: ?*ghostty_vt.Pin = null, + out_end: ?*ghostty_vt.Pin = null, + /// The running command's output was erased under it -- a clear, ED 3, + /// a reset -- so the pins no longer span what it printed. ED 3 flags a + /// pin on an erased history row `garbage` (ghostty 1.4), but `pinTop` + /// re-pins the start at the screen's top, so the flag is gone with the + /// old pin: this remembers it, as it does for a reset or a pin that + /// could not be made. + lost: bool = false, + + /// The newest command to end: which one, and its status if given. + finished: ?Term.Prompt.Finished = null, + + const Action = ghostty_vt.TerminalStream.Action; + + /// Move one of the output pins to the cursor. Only the primary screen + /// is pinned: a command's own full-screen display is not its output. + fn pinCursor(self: *@This(), slot: *?*ghostty_vt.Pin, now: bool) void { + const screen = self.inner.terminal.screens.get(.primary) orelse return; + if (slot.*) |old| screen.pages.untrackPin(old); + slot.* = null; + if (!now or self.inner.terminal.screens.active_key != .primary) return; + slot.* = screen.pages.trackPin(screen.cursor.page_pin.*) catch null; + } + + pub fn vt(self: *@This(), comptime action: Action.Tag, value: Action.Value(action)) void { + if (comptime action == .semantic_prompt) mark: { + const aid = value.readOption(.aid) orelse break :mark; + if (!std.mem.eql(u8, aid, prompt_aid)) break :mark; + switch (value.action) { + .fresh_line_new_prompt => { + self.phase = .prompt; + self.continuation = value.readOption(.prompt_kind) == .continuation; + }, + .end_prompt_start_input => { + self.phase = .input; + self.prompts +%= 1; + }, + // bash's DEBUG trap also fires on its own PROMPT_COMMAND, + // outside the input phase; only a C that ends input counts + .end_input_start_output => if (self.phase == .input) { + self.phase = .running; + self.started +%= 1; + self.lost = false; + self.pinCursor(&self.out_start, true); + self.pinCursor(&self.out_end, false); + }, + .end_command => if (self.phase == .running) { + self.phase = .none; + self.finished = .{ .seq = self.started, .status = value.readOption(.exit_code) }; + self.pinCursor(&self.out_end, true); + } else { + self.declined +%= 1; + }, + else => {}, + } + } + if (comptime action == .erase_display_complete or action == .erase_display_scrollback or + action == .erase_display_scroll_complete or action == .full_reset) + { + self.inner.vt(action, value); + // A `clear` under a running command: its output is what it + // prints from here, the screen's top, not lost. Only what the + // scrollback later loses is (the pin goes `garbage`). + if (self.phase == .running) self.pinTop(&self.out_start); + return; + } + self.inner.vt(action, value); + } + + /// Pins `slot` to the primary screen's top-left; lost when it cannot be. + fn pinTop(self: *@This(), slot: *?*ghostty_vt.Pin) void { + const screen = self.inner.terminal.screens.get(.primary) orelse return; + if (slot.*) |old| screen.pages.untrackPin(old); + slot.* = null; + if (self.inner.terminal.screens.active_key != .primary) { + self.lost = true; + return; + } + const top = screen.pages.pin(.{ .active = .{} }) orelse { + self.lost = true; + return; + }; + slot.* = screen.pages.trackPin(top) catch null; + if (slot.* == null) self.lost = true; + } + + pub fn deinit(self: *@This()) void { + self.inner.deinit(); + } +}; + +fn ptyReport(handler: *ghostty_vt.TerminalStream.Handler, data: []const u8) void { + const state: *State = @alignCast(@fieldParentPtr("vt", handler.terminal)); + const room = state.reply.len - state.reply_len; + // A cut answer is worse than none: the program would read the start of + // a sequence and wait, or misparse what follows. + if (data.len > room) { + state.reply_dropped +|= 1; + return; + } + @memcpy(state.reply[state.reply_len..][0..data.len], data); + state.reply_len += @intCast(data.len); +} + +fn ptyDeviceAttrs(_: *ghostty_vt.TerminalStream.Handler) ghostty_vt.device_attributes.Attributes { + return .{}; +} + +/// CSI 14/16/18 t: the pane's size, and its cells' in pixels, which a +/// program sizes its kitty graphics by (yazi asks 16 t). Unknown, not asked. +fn ptySize(handler: *ghostty_vt.TerminalStream.Handler) ?ghostty_vt.size_report.Size { + const t = handler.terminal; + if (t.width_px == 0 or t.height_px == 0 or t.cols == 0 or t.rows == 0) return null; + return .{ .rows = t.rows, .columns = t.cols, .cell_width = t.width_px / t.cols, .cell_height = t.height_px / t.rows }; +} + +pub const State = struct { + /// What the emulator and this struct are allocated with: the core's, + /// but on a screen-state replica the C heap (`emulator_gpa`), 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. + gpa: std.mem.Allocator, + vt: VtSlot, + stream: StreamSlot, + /// The emulator's answers to its program (DSR, DA, kitty graphics, ...) + /// from one read of its output, written to its pty after it. Room for + /// a read's worth of kitty answers (yazi or `kitten icat` asking about + /// a batch of images in one write); an answer that does not fit whole + /// is dropped whole, never cut short (`reply_dropped` counts them). + reply: [4096]u8 = undefined, + reply_len: u16 = 0, + reply_dropped: u32 = 0, + /// The grid cell the program last heard the mouse at, so motion is + /// reported once per cell. + mouse_cell: ?ghostty_vt.Coordinate = null, + /// The kitty graphics its program placed, as drawn (TerminalImages.zig). + images: TerminalImages = if (images_enabled) .{} else {}, + /// Counts the emulator's writes (output, a resize, its view scrolled): + /// a new count is a new state for its replicas (screen_state.Track). + changes: u32 = 0, + /// A step read its rows (its history too): a replica replaying that + /// step must hold them, so its authority sends the ones it does not + /// before the step's unit (replica.Screens.fill). + read: bool = false, + /// The size a step gave it, on an authority with screen-state replicas: + /// made after the step's unit (`resizeDeferred`), so that the rest of + /// the step reads the grid it had, as its replicas' replays do, and the + /// rows sent them for it (Screens.fill) are of that grid's numbering. + resize_to: ?struct { cols: u16, rows: u16 } = null, + + /// The stream over the emulator, its answers to the program and its + /// size reports routed here, PNG decoded: what `create` and a dump's + /// load both do once the emulator is in place. + fn wire(s: *State) void { + s.stream = .init(.{ .handler = .{ .inner = s.vt.vtHandler() }, .allocator = s.gpa }); + s.stream.handler.inner.effects.write_pty = ptyReport; + s.stream.handler.inner.effects.device_attributes = ptyDeviceAttrs; + s.stream.handler.inner.effects.size = ptySize; + if (comptime images_enabled) TerminalImages.installPngDecoder(); + } +}; + +/// The emulator as its program has made it, for the replay digest (the +/// core's Term.State.digest, src/walk.zig): the active screen's text, how +/// much history is above it and, with `view`, where the view is, the +/// cursor, the answers not yet written. Not its pages (their addresses are +/// its own), nor the history's text (the screen's was all of it once, and +/// a session's digest is taken every step), nor the kitty images, whose +/// media is read off the host. +pub fn digest(s: *const State, h: *std.hash.Wyhash, view: bool) void { + const screen = s.vt.screens.active; + const sb = screen.pages.scrollbar(); + const cur = screen.cursor; + const offset = if (view) sb.offset else 0; + const facts = .{ sb.total, offset, sb.len, cur.x, cur.y, s.vt.modes.get(.cursor_visible), s.vt.screens.active_key, s.reply_dropped }; + inline for (facts) |fact| h.update(std.mem.asBytes(&fact)); + h.update(s.reply[0..s.reply_len]); + var buf: [4096]u8 = undefined; + var text: std.Io.Writer.Hashing(std.hash.Wyhash) = .initHasher(h.*, &buf); + if (screen.pages.getBottomRight(.active)) |br| + screen.dumpString(&text.writer, .{ .tl = screen.pages.getTopLeft(.active), .br = br, .unwrap = false }) catch unreachable; // a hashing writer never fails + text.writer.flush() catch unreachable; // a hashing writer never fails + h.* = text.hasher; + } + +fn pinAt(s: *const State, slot: ?*ghostty_vt.Pin) ?Term.Parts.Coordinate { + const pin = slot orelse return null; + const screen = s.vt.screens.get(.primary) orelse return null; + const at = (screen.pages.pointFromPin(.screen, pin.*) orelse return null).screen; + return .{ .x = at.x, .y = at.y }; +} + +fn coordinate(at: ?Term.Parts.Coordinate) ?ghostty_vt.Coordinate { + const c = at orelse return null; + return .{ .x = c.x, .y = c.y }; +} + +/// What the dump keeps of it beside its emulator (the core's +/// Term.State.dumpWrite writes it by name, as every dump is). +pub fn parts(s: *const State) Term.Parts { + const h = &s.stream.handler; + return .{ + .reply = s.reply[0..s.reply_len], + .reply_dropped = s.reply_dropped, + .mouse_cell = if (s.mouse_cell) |c| .{ .x = c.x, .y = c.y } else null, + .petscii = if (comptime images_enabled) s.images.petscii else false, + .view = s.vt.screens.active.pages.scrollbar().offset, + .phase = h.phase, + .started = h.started, + .prompts = h.prompts, + .declined = h.declined, + .continuation = h.continuation, + .lost = h.lost, + .finished = h.finished, + .out_start = pinAt(s, h.out_start), + .out_end = pinAt(s, h.out_end), + }; +} + +/// Its emulator as the dump keeps it: ghostty's snapshot (both screens, +/// their history, styles, links and kitty images). A sequence its program +/// had begun and not ended is not kept: the snapshot is at the ground +/// state. `slim`, a join's dump (dump.zig `dumpJoin`): its size alone, an +/// emulator made afresh there, which its first delta replaces. +pub fn snapshot(s: *const State, gpa: std.mem.Allocator, w: *std.Io.Writer, slim: bool) !void { + if (slim) return w.writeAll(std.mem.asBytes(&[2]u16{ s.vt.cols, s.vt.rows })); + try ghostty_vt.snapshot.encode(gpa, w, &s.vt, .{ .continuation = .ground }); +} + +/// `snapshot`'s bytes and `parts` back into a new terminal, as `open` +/// makes one. +pub fn load(gpa: std.mem.Allocator, bytes: []const u8, saved: *const Term.Parts) !*State { + const out = try gpa.create(State); + errdefer gpa.destroy(out); + var reader: std.Io.Reader = .fixed(bytes); + if (reader.buffer.len == 4) { + const size = std.mem.bytesToValue([2]u16, bytes[0..4]); + out.* = .{ .gpa = gpa, .vt = try emulator(gpa, @max(1, size[0]), @max(1, size[1])), .stream = undefined }; + } else { + var decoded = try ghostty_vt.snapshot.decodeExact(gpa, terminalIo(), &reader, .{ + .max_continuation_bytes = 0, + .kitty_image_storage_limit = if (images_enabled) TerminalImages.storage_limit else 0, + }); + defer decoded.deinit(gpa); + out.* = .{ .gpa = gpa, .vt = decoded.toOwned(), .stream = undefined }; + } + 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 = saved.reply[0..@min(saved.reply.len, out.reply.len)]; + @memcpy(out.reply[0..reply.len], reply); + out.reply_len = @intCast(reply.len); + out.reply_dropped = saved.reply_dropped; + out.mouse_cell = coordinate(saved.mouse_cell); + out.images = if (images_enabled) .{ .petscii = saved.petscii } else {}; + const h = &out.stream.handler; + h.phase = saved.phase; + h.started = saved.started; + h.prompts = saved.prompts; + h.declined = saved.declined; + h.continuation = saved.continuation; + h.lost = saved.lost; + h.finished = saved.finished; + if (out.vt.screens.get(.primary)) |screen| { + inline for (.{ .{ "out_start", saved.out_start }, .{ "out_end", saved.out_end } }) |pair| if (coordinate(pair[1])) |at| { + if (screen.pages.pin(.{ .screen = at })) |pin| @field(h, pair[0]) = screen.pages.trackPin(pin) catch null; + }; + } + const screen = out.vt.screens.active; + const bottom = screen.pages.scrollbar().offset; + screen.scroll(.{ .delta_row = @as(isize, @intCast(saved.view)) - @as(isize, @intCast(bottom)) }); + return out; +} + +/// The allocator it was opened with, its own from then on. +pub fn gpaOf(s: *const State) std.mem.Allocator { + return s.gpa; +} + +const GColor = ghostty_vt.color; + +// Projected colors below this contrast use the theme's more legible anchor. +pub const min_contrast: f64 = 1.5; + +/// The theme's 256 colours as the filter maps onto them (ghostty's +/// `generate256Color` over the theme's sixteen), made again only when the +/// theme's are not the ones `cache` was made of. +pub fn filterPalette(cache: *FilterPalette, ink: *const Ink) *const [256][3]u8 { + const wanted: FilterPalette.Key = .{ .bg = ink.bg orelse ink.tag_bg, .fg = ink.fg orelse ink.tag_fg, .base = ink.base }; + if (cache.key) |old| if (std.meta.eql(old, wanted)) return &cache.colors; + var seed = GColor.default; + for (ink.base, 0..) |rgb, i| seed[i] = asGhostRgb(rgb); + const colors = GColor.generate256Color(seed, .empty, asGhostRgb(wanted.bg), asGhostRgb(wanted.fg), false); + for (&cache.colors, colors) |*dst, src| dst.* = asTriple(src); + cache.key = wanted; + return &cache.colors; +} + +pub fn asGhostRgb(rgb: [3]u8) GColor.RGB { + return .{ .r = rgb[0], .g = rgb[1], .b = rgb[2] }; +} + +/// 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). +fn tempDir() []const u8 { + const dir = std.c.getenv("TMPDIR") orelse return "/tmp"; + const path = std.mem.span(dir); + return if (path.len > 0 and path[0] == '/') path else "/tmp"; +} + +pub fn terminalIo() std.Io { + return std.Io.Threaded.global_single_threaded.io(); +} + +/// Where the view and the cursor are (`Term.Grid`); all zero without an +/// emulator. +pub fn grid(state: ?*const State) Term.Grid { + const s = state orelse return .{}; + const screen = s.vt.screens.active; + const sb = screen.pages.scrollbar(); + return .{ + .total = sb.total, + .offset = sb.offset, + .len = sb.len, + .cursor_x = @intCast(screen.cursor.x), + .cursor_y = @intCast(screen.cursor.y), + .cursor_visible = s.vt.modes.get(.cursor_visible), + .view = if (screen.pages.viewport == .active) null else sb.offset, + .cols = screen.pages.cols, + }; +} + +/// What pardes made of a terminal's stream that its emulator does not hold +/// (the OSC 133 cycle, MarkedHandler), for a replica's delta: phase u8, +/// started, prompts, declined u32, continuation and lost u8, a finished +/// command's seq u32 and status i32 (all ones: none; i32 min: no status). +// ponytail: the output pins stay the authority's (its 9P pty/run reads them). +pub const marks_len = 1 + 4 * 3 + 2 + 4 + 4; + +pub fn marksOf(state: *const State, buf: *[marks_len]u8) []const u8 { + const m = &state.stream.handler; + var w: std.Io.Writer = .fixed(buf); + w.writeByte(@backingInt(m.phase)) catch unreachable; + inline for (.{ m.started, m.prompts, m.declined }) |n| w.writeInt(u32, n, .little) catch unreachable; + w.writeAll(&.{ @intFromBool(m.continuation), @intFromBool(m.lost) }) catch unreachable; + w.writeInt(u32, if (m.finished) |f| f.seq else std.math.maxInt(u32), .little) catch unreachable; + w.writeInt(i32, if (m.finished) |f| f.status orelse std.math.minInt(i32) else 0, .little) catch unreachable; + return w.buffered(); +} + +/// A replica's terminal takes its authority's marks (`marksOf`). +pub fn takeMarks(state: *State, bytes: []const u8) void { + if (bytes.len != marks_len) return; + const m = &state.stream.handler; + m.phase = @fromBackingInt(@intCast(bytes[0])); + m.started = std.mem.readInt(u32, bytes[1..5], .little); + m.prompts = std.mem.readInt(u32, bytes[5..9], .little); + m.declined = std.mem.readInt(u32, bytes[9..13], .little); + m.continuation = bytes[13] != 0; + m.lost = bytes[14] != 0; + const seq = std.mem.readInt(u32, bytes[15..19], .little); + const status = std.mem.readInt(i32, bytes[19..23], .little); + m.finished = if (seq == std.math.maxInt(u32)) null else .{ .seq = seq, .status = if (status == std.math.minInt(i32)) null else status }; +} + +// ---- its replicas: the screen state they are sent (screen_state.zig) ---- + +/// 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, tr: *screen_state.Track, peer: *screen_state.Peer, out: *std.Io.Writer) !bool { + var marks: [marks_len]u8 = undefined; + return screen_state.encode(enc, tr, peer, &state.vt, state.changes, marksOf(state, &marks), out); +} + +/// 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, tr: *screen_state.Track, lo: u64, hi: u64, out: *std.Io.Writer) !void { + return screen_state.encodeRows(enc, tr, &state.vt, lo, hi, out); +} + +/// What a session's authority keeps to encode its terminals for its +/// peers, and what it keeps of one terminal for them: made and freed. +pub fn encoder(gpa: std.mem.Allocator) !*screen_state.Encoder { + const e = try gpa.create(screen_state.Encoder); + e.* = .init(gpa); + return e; +} + +pub fn encoderFree(e: *screen_state.Encoder) void { + const gpa = e.gpa; + e.deinit(); + gpa.destroy(e); +} + +pub fn track(gpa: std.mem.Allocator) !*screen_state.Track { + const t = try gpa.create(screen_state.Track); + t.* = .init(gpa); + return t; +} + +/// A replica's side of one terminal: made, freed, where its active area +/// begins, and the history rows `lo..hi` it does not hold. +pub fn replica(gpa: std.mem.Allocator) !*screen_state.Replica { + const r = try gpa.create(screen_state.Replica); + r.* = .{}; + return r; +} + +pub fn replicaFree(r: *screen_state.Replica, gpa: std.mem.Allocator) void { + r.deinit(gpa); + gpa.destroy(r); +} + +pub fn replicaTop(r: *const screen_state.Replica) u64 { + return r.top; +} + +pub fn missing(r: *const screen_state.Replica, lo: u64, hi: u64, out: *std.ArrayList([2]u64), gpa: std.mem.Allocator) !void { + return r.missing(lo, hi, out, gpa); +} + +/// What `track` kept of its versions, freed; `state` null when its pane is +/// gone with the emulator. +/// A peer's track of it let go, and freed (`state` null: it is gone). +pub fn untrack(t: *screen_state.Track, gpa: std.mem.Allocator, state: ?*State) void { + t.deinit(gpa, if (state) |s| &s.vt else null); + gpa.destroy(t); +} + +/// Whether a step read its rows since `clearRead` (`markRead`). +pub fn wasRead(state: *const State) bool { + return state.read; +} + +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) !Term.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); +} + +/// Its view to row `at` of its history (from the top), or onto its output. +pub fn viewTo(state: *State, at: ?usize) void { + state.vt.screens.active.scroll(if (at) |row| .{ .row = row } else .active); +} + +/// Its view moved by `delta` rows (negative scrolls back). +pub fn scroll(state: *State, delta: i32) void { + state.vt.screens.active.scroll(.{ .delta_row = delta }); + state.changes +%= 1; +} + +/// 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); +} + +/// 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; + } + state.changes +%= 1; + state.vt.resize(state.gpa, .{ .cols = cols, .rows = rows }) catch {}; +} + +/// The size `resize` left for later, made; whether there was one. +pub fn resizeDeferred(state: *State) bool { + const size = state.resize_to orelse return false; + state.resize_to = null; + state.changes +%= 1; + state.vt.resize(state.gpa, .{ .cols = size.cols, .rows = size.rows }) catch {}; + return true; +} + +/// The emulator's size in pixels follows the core's cells: kitty graphics +/// placements are sized by it, and CSI 14/16 t report it. +pub fn cellPixels(state: *State, w: u32, h: u32) void { + if (comptime !images_enabled) return; + const vt = &state.vt; + vt.width_px = @as(u32, vt.cols) * w; + vt.height_px = @as(u32, vt.rows) * h; +} + +/// What it answered its program (a cursor report, its attributes) since +/// the last call, to be written to its pty behind whatever is queued +/// there; valid until it is fed again. +pub fn replies(state: *State) []const u8 { + defer state.reply_len = 0; + return state.reply[0..state.reply_len]; +} + +/// 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 +/// paste could smuggle a command in by (ESC, so no ESC[201~ can end +/// 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 paste(state: ?*const State, text: []u8) [3][]const u8 { + return ghostty_vt.input.encodePaste(text, .{ .bracketed = modes(state).bracketed_paste }); +} + +/// 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, +/// 1015 urxvt, 1005 UTF-8, else X10) how, modifiers as shift+4, meta+8, +/// 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 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 = .{ + .event = state.vt.flags.mouse_event, + .format = state.vt.flags.mouse_format, + .size = .{ + .screen = .{ .width = state.vt.cols, .height = state.vt.rows }, + .cell = .{ .width = 1, .height = 1 }, + .padding = .{}, + }, + .any_button_pressed = any_pressed, + .last_cell = &state.mouse_cell, + }; + // A release is always reported; the rest only over the grid, or held. + if (action == .release) opts.any_button_pressed = true; + input.encodeMouse(&writer, .{ + .action = switch (action) { + .press => .press, + .release => .release, + .motion => .motion, + }, + .button = if (button) |b| switch (b) { + .left => .left, + .middle => .middle, + .right => .right, + .wheel_up => .four, + .wheel_down => .five, + .wheel_left => .six, + .wheel_right => .seven, + } else null, + .mods = .{ .shift = mods.shift, .alt = mods.alt, .ctrl = mods.ctrl }, + .pos = .{ .x = @as(f32, @floatFromInt(col)) + 0.5, .y = @as(f32, @floatFromInt(row)) + 0.5 }, + }, opts) catch return &.{}; // no report rather than half of one + return writer.buffered(); +} + +/// 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 (`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 (!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 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 scrollback(state: ?*State, gpa: std.mem.Allocator) ![]const u8 { + var out: std.Io.Writer.Allocating = .init(gpa); + errdefer out.deinit(); + try writeBody(state, &out.writer); + return out.toOwnedSlice(); +} + +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 }; + try screen.dumpString(&both.writer, .{ .tl = screen.pages.getTopLeft(.screen), .br = br, .unwrap = true }); + if (both.count > 0 and both.final != '\n') try w.writeByte('\n'); +} + +/// Passes bytes through, remembering how many and the last one. +const TeeWriter = struct { + a: *std.Io.Writer, + count: usize = 0, + final: u8 = 0, + writer: std.Io.Writer = .{ .vtable = &.{ .drain = drain }, .buffer = &.{} }, + + fn drain(w: *std.Io.Writer, data: []const []const u8, splat: usize) std.Io.Writer.Error!usize { + const t: *TeeWriter = @alignCast(@fieldParentPtr("writer", w)); + var n: usize = 0; + for (data[0 .. data.len - 1]) |bytes| { + try t.a.writeAll(bytes); + t.note(bytes); + n += bytes.len; + } + const pattern = data[data.len - 1]; + for (0..splat) |_| { + try t.a.writeAll(pattern); + t.note(pattern); + n += pattern.len; + } + return n; + } + + fn note(t: *TeeWriter, bytes: []const u8) void { + if (bytes.len == 0) return; + t.count += bytes.len; + t.final = bytes[bytes.len - 1]; + } +}; + +/// 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); + writeBody(state, &counting.writer) catch unreachable; // a discarding writer never fails + return @intCast(counting.fullCount()); +} + +/// 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); +} + +/// 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, + .rows = rows, + .max_scrollback_bytes = 16 * 1024 * 1024, + .kitty_image_storage_limit = if (images_enabled) TerminalImages.storage_limit else 0, + // Every kitty medium, as ghostty and kitty take them: a file (t=f), + // a temporary file it then deletes (t=t, in the temp directory and + // named as one) and shared memory (t=s), beside direct data. libghostty + // defaults to direct alone, which `kitten icat` and timg detect and + // fall back from, base64 through the pty. What the program can read + // it could send itself: it runs as the user, under pardes. + .kitty_image_loading_limits = if (images_enabled) .allWithTempDir(tempDir()) else if (@FieldType(ghostty_vt.Terminal.Options, "kitty_image_loading_limits") == void) {} else .direct, + }); +} + +/// 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 = gpa, .vt = try emulator(gpa, cols, rows), .stream = undefined }; + state.wire(); + 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) 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 (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(state: *State, bytes: []const u8) void { + state.stream.nextSlice(bytes); + state.changes +%= 1; +} + +const RowPin = struct { pin: ?*ghostty_vt.Pin = null, offset: i32 = 0 }; + +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; + var node = pages.pages.last.?; + while (left >= node.rows()) { + left -= node.rows(); + node = node.prev.?; + } + const pin = pages.trackPin(.{ .node = node, .y = @intCast(node.rows() - 1 - left) }) catch { + failed.* = true; + return .{}; + }; + return .{ .pin = pin, .offset = row - @as(i32, @intCast(bounded)) }; +} + +fn pinnedRow(pages: ?*ghostty_vt.PageList, row: RowPin) i32 { + const pin = row.pin orelse return row.offset; + const alive = pages orelse return 0; + if (pin.garbage) return 0; + var after: usize = 0; + var node = alive.pages.last; + while (node) |item| : (node = item.prev) { + if (item == pin.node) + return @as(i32, @intCast(alive.total_rows - after - item.rows() + pin.y)) +| row.offset; + after += item.rows(); + } + return 0; +} + +/// One read of its program's output. `track` are rows (absolute, from the +/// top of the history) the core keeps positions on; each is told in +/// `rows` where it is after the read and in `erased` whether the program +/// erased it (a negative row passes through untouched). With nothing +/// tracked the read is parsed and nothing more. +pub fn feed(state: *State, bytes: []const u8, tracked: []const i32, rows: []i32, erased: []bool) Term.Told { + if (tracked.len == 0) { + ingest(state, bytes); + return .{ .rows = rows[0..0], .erased = erased[0..0], .cleared = false, .alive = true, .failed = false }; + } + const screens = &state.vt.screens; + const active = screens.active_key; + const generation = screens.generation(active); + const pages = &screens.active.pages; + var failed = false; + var room: [512]RowPin = undefined; + const pins = if (tracked.len <= room.len) room[0..tracked.len] else state.gpa.alloc(RowPin, tracked.len) catch { + ingest(state, bytes); + @memcpy(rows[0..tracked.len], tracked); + @memset(erased[0..tracked.len], false); + return .{ .rows = rows[0..tracked.len], .erased = erased[0..tracked.len], .cleared = false, .alive = true, .failed = true }; + }; + defer if (tracked.len > room.len) state.gpa.free(pins); + for (pins, tracked) |*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..tracked.len], erased[0..tracked.len]) |pin, *row, *gone| { + row.* = pinnedRow(alive, pin); + gone.* = alive != null and pin.pin != null and pin.pin.?.garbage; + if (alive) |owner| if (pin.pin) |held| owner.untrackPin(held); + } + return .{ .rows = rows[0..tracked.len], .erased = erased[0..tracked.len], .cleared = cleared, .alive = alive != null, .failed = failed }; +} + +/// 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(), + }; +} + +/// 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(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(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 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 = 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. + if (start.eql(end.*)) break :printed whole; + // D is where the next prompt begins: the output ends a cell before. + // An end at the very top, or before the start, is output a redraw + // moved (a prompt drawn over it in a window two rows high): how + // much is not known, so it is not called whole. + const last = end.leftWrap(1) orelse break :printed false; + if (last.before(start.*)) break :printed false; + var from = start.*; + if (last.up(max_rows)) |floor| if (from.before(floor)) { + from = floor; + from.x = 0; + whole = false; + }; + return .{ + .text = try screen.selectionString(gpa, .{ .sel = ghostty_vt.Selection.init(from, last, false) }), + .whole = whole, + }; + }; + return .{ .text = try gpa.dupeSentinel(u8, "", 0), .whole = whole }; +} + +/// 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 = [Key.f25 - Key.f1 + 1]input.Key{ .f1, .f2, .f3, .f4, .f5, .f6, .f7, .f8, .f9, .f10, .f11, .f12, .f13, .f14, .f15, .f16, .f17, .f18, .f19, .f20, .f21, .f22, .f23, .f24, .f25 }; + const physical: input.Key = switch (k.cp) { + Key.enter => .enter, + Key.backspace => .backspace, + Key.tab => .tab, + Key.escape => .escape, + Key.up => .arrow_up, + Key.down => .arrow_down, + Key.left => .arrow_left, + Key.right => .arrow_right, + Key.home => .home, + Key.end => .end, + Key.page_up => .page_up, + Key.page_down => .page_down, + Key.delete => .delete, + Key.insert => .insert, + Key.print_screen => .print_screen, + Key.scroll_lock => .scroll_lock, + Key.pause => .pause, + Key.menu => .context_menu, + 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 (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 (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 + ""; + try input.encodeKey(out, .{ + .key = physical, + .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 (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 + // "option is not alt" — right for an app that lets macOS do the + // unicode translation and hands the encoder the composed text. + // Every pardes shell resolves the modifier itself and hands the + // core the BASE key with the alt bit and no text at all (see + // PardesView.keyDown, and app.mjs doing the same with the same + // two bits), so by the time this runs alt already means alt. + // Left at the default, a macOS build drops the ESC prefix on + // the floor and forwards Alt-n to the child as a bare `n`. + opts.macos_option_as_alt = .true; + break :options opts; + }); +} + +/// 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 => {}, + }; + } + 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 }; +} + +/// 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. +fn promptCut(pin: ghostty_vt.Pin) PromptCut { + const cells = pin.cells(.all); + var cols: usize = 0; + while (cols < cells.len and cells[cols].semantic_content == .prompt) cols += 1; + // Flagged, but with no prompt cells at the FRONT: a right-side prompt, or + // a repaint that has moved on. Nothing here is the prompt, so hide nothing. + if (cols == 0) return .keep; + // ...and all prompt, nothing typed yet: the row is chrome end to end. + if (cols >= cells.len) return .blank; + return .{ .cut = cols }; +} + +/// How much of its row `row` (from the top of the history) the prompt it +/// starts with is; null for a row no prompt starts (the core measures the +/// cut columns in the row's text, Term.promptPrefix). +pub fn promptCutAt(state: *State, row: i32) ?PromptCut { + if (row < 0) return null; + const pin = state.vt.screens.active.pages.pin(.{ .screen = .{ .x = 0, .y = @intCast(row) } }) orelse return null; + if (pin.rowAndCell().row.semantic_prompt == .none) return null; + return promptCut(pin); +} + +/// What a predicted echo reads of cell `x`, `y` of its active area +/// (src/echo.zig): null off it. +pub fn echoCell(state: *const State, x: u16, y: u16) ?Term.EchoCell { + if (y >= state.vt.rows) return null; + const ci = state.vt.screens.active.pages.getCell(.{ .active = .{ .x = x, .y = y } }) orelse return null; + return .{ .cp = ci.cell.codepoint(), .input = ci.cell.semantic_content == .input, .style = ci.cell.style_id }; +} + +fn promptRow(pin: ghostty_vt.Pin, raw: []const u8) []const u8 { + const cols = switch (promptCut(pin)) { + .keep => return raw, + .blank => return "", + .cut => |n| n, + }; + const cells = pin.cells(.all); + var at: usize = 0; + var col: usize = 0; + while (col < cols and at < raw.len) { + const cell = &cells[col]; + at = @min(raw.len, at + dumpedBytes(pin, cell)); + // the tail cell of a wide glyph spells nothing of its own + col += if (cell.wide == .wide) @as(usize, 2) else 1; + } + return std.mem.trimEnd(u8, raw[at..], " \t"); +} + +fn dumpedBytes(pin: ghostty_vt.Pin, cell: *const ghostty_vt.Cell) usize { + switch (cell.wide) { + .spacer_head, .spacer_tail => return 0, + .narrow, .wide => {}, + } + var n: usize = switch (cell.content_tag) { + .codepoint, .codepoint_grapheme => std.unicode.utf8CodepointSequenceLength( + cell.codepoint(), + ) catch 1, + // A cell carrying only a colour still spells one blank in the dump. + else => 1, + }; + if (cell.content_tag == .codepoint_grapheme) { + if (pin.grapheme(cell)) |extra| for (extra) |cp| { + n += std.unicode.utf8CodepointSequenceLength(cp) catch 1; + }; + } + return n; +} + +/// Its rows `first` and the `count` after it (from the top of its +/// history) as text, a prompt's own cells cut off the rows it starts: +/// `arena`'s. An edit copy's rows as they were (src/ansi.zig). +pub fn editRows(state: *State, arena: std.mem.Allocator, first: usize, count: usize) ![]const []const u8 { + const screen = state.vt.screens.active; + const tl = screen.pages.pin(.{ .screen = .{ .y = @intCast(first) } }) orelse return error.NoRow; + const br = screen.pages.pin(.{ .screen = .{ + .x = screen.pages.cols - 1, + .y = @intCast(first + count - 1), + } }) orelse return error.NoRow; + var output: std.Io.Writer.Allocating = .init(arena); + try screen.dumpString(&output.writer, .{ .tl = tl, .br = br, .unwrap = false }); + const shell = try arena.alloc([]const u8, count); + var raw = std.mem.splitScalar(u8, output.written(), '\n'); + var pins = tl.rowIterator(.right_down, br); + for (shell) |*row| { + const text = raw.next() orelse ""; + row.* = if (pins.next()) |pin| + if (pin.rowAndCell().row.semantic_prompt != .none) promptRow(pin, text) else text + else + text; + } + return shell; +} + +/// 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; +} + +/// 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 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); + errdefer alloc.free(text); + var at: usize = 0; + var n: usize = 0; + var it = std.mem.splitScalar(u8, full, '\n'); + while (it.next()) |raw| { + const kept = if (pit.next()) |pin| + if (pin.rowAndCell().row.semantic_prompt != .none) promptRow(pin, raw) else raw + else + raw; + if (n > 0) { + text[at] = '\n'; + at += 1; + } + @memcpy(text[at..][0..kept.len], kept); + lines[n] = text[at..][0..kept.len]; + at += kept.len; + n += 1; + } + text[at] = '\n'; + at += 1; + lines[n] = text[at..][0..0]; + n += 1; + std.debug.assert(n == n_rows); + return .{ .text_alloc = text, .text = text[0..at], .rows = lines }; +} + +/// The rows its view shows as text, a prompt's own cells cut off the rows +/// it starts when `cut` (as the core shows them outside raw mode): `arena`'s. +pub fn viewport(state: *State, arena: std.mem.Allocator, cut: bool) ![]const []const u8 { + 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 + ln + else + ln; + n += 1; + } + std.debug.assert(n == vp.len); + return vp; +} + +/// Its view's rows as cells, for the core's paint (Term.paint, the core's +/// src/ansi.zig): `rows.len` rows of `cols` cells into `cells`, each its +/// style in the theme's colours (through the filter when `filtered`), the +/// bytes it spells in the view's text and its width; each row whether a +/// prompt starts it, and how much of it that is. +pub fn paint(state: *State, ink: *const Ink, palette: *FilterPalette, filtered: bool, cols: u16, cells: []Painted, rows: []PaintedRow) void { + var filter_storage: Filter = undefined; + const filter: ?*Filter = if (filtered) blk: { + filter_storage = filterOf(ink, palette, &state.vt); + break :blk &filter_storage; + } else null; + // DECSCNM, read once: the filtered palette folds it in itself, the raw + // path needs it per cell. + const scnm = state.vt.modes.get(.reverse_colors); + const pages = &state.vt.screens.active.pages; + for (rows, 0..) |*row, vi| { + row.* = .{ .prompt = null, .placeholder = false, .len = 0 }; + const row_pin = pages.pin(.{ .viewport = .{ .y = @intCast(vi) } }) orelse continue; + const flags = row_pin.rowAndCell().row; + if (flags.semantic_prompt != .none) row.prompt = promptCut(row_pin); + row.placeholder = flags.kitty_virtual_placeholder; + const out = cells[vi * cols ..][0..cols]; + var x: u16 = 0; + while (x < cols) : (x += 1) { + const ci = cellAt(pages, row_pin, x) orelse break; + out[x] = .{ + .style = cellStyle(ink, ci, filter, scnm), + .bytes = @intCast(@min(dumpedBytes(row_pin, ci.cell), std.math.maxInt(u16))), + .wide = switch (ci.cell.wide) { + .narrow => .narrow, + .wide => .wide, + .spacer_tail => .spacer_tail, + .spacer_head => .spacer_head, + }, + }; + } + row.len = x; + } +} + +/// The cell at column `x` of the row `row` pins, as `pages.getCell` reads +/// it, without walking from the viewport's top down to the row again: that +/// walk, once a cell, was most of a terminal's paint (once getCell was no +/// longer inlined, a frame of a 120x40 shell took 75 µs more). +fn cellAt(pages: *const ghostty_vt.PageList, row: ghostty_vt.Pin, x: u16) ?ghostty_vt.PageList.Cell { + if (x >= pages.cols or x >= row.node.cols()) return null; + const rac = row.node.page().getRowAndCell(x, row.y); + return .{ .node = row.node, .row = rac.row, .cell = rac.cell, .row_idx = row.y, .col_idx = x }; +} + +// A cell's underline styles are SGR's, in SGR's order (`off` its `none`): a +// cast takes one to the other (cellStyle, and pager.zig's attribute). +comptime { + for (@typeInfo(@FieldType(plain.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"); +} + +fn cellStyle(ink: *const Ink, ci: ghostty_vt.PageList.Cell, filtered: ?*Filter, scnm: bool) plain.CellStyle { + const style = ci.style(); + var cs: plain.CellStyle = .{ + .fg = if (filtered) |colors| filterFg(colors, style) else ghostColor(ink, style.fg_color, scnm), + .bg = if (filtered) |colors| filterBg(colors, style, ci.cell) else ghostColor(ink, style.bg_color, !scnm), + .bold = style.flags.bold, + .dim = style.flags.faint, + .italic = style.flags.italic, + .blink = style.flags.blink, + .reverse = style.flags.inverse, + .invisible = style.flags.invisible, + .strikethrough = style.flags.strikethrough, + .ul = @fromBackingInt(@intCast(@backingInt(style.flags.underline))), + }; + if (filtered == null) switch (ci.cell.content_tag) { + .bg_color_palette => cs.bg = ink.palColor(ci.cell.content.color_palette.data), + .bg_color_rgb => { + const rgb = ci.cell.content.color_rgb; + cs.bg = .{ .rgb = .{ rgb.r, rgb.g, rgb.b } }; + }, + else => {}, + }; + return cs; +} + +pub fn asPardesColor(rgb: GColor.RGB) plain.Color { + return .{ .rgb = .{ rgb.r, rgb.g, rgb.b } }; +} + +fn asTriple(rgb: GColor.RGB) [3]u8 { + return .{ rgb.r, rgb.g, rgb.b }; +} + +/// A program's colours mapped to the theme (Term.Filter): for a terminal's +/// cells (`vt`), or a +Pager's spans (`vt` null, the program's palette +/// xterm's own). +pub fn filterOf(ink: *const Ink, palette: *FilterPalette, vt: ?*const ghostty_vt.Terminal) Filter { + var source = GColor.default; + if (vt) |t| { + for (&source, 0..) |*rgb, i| + rgb.* = t.colorForXterm(.{ .palette = @intCast(i) }) orelse rgb.*; + } + var theme_bg = asGhostRgb(ink.bg orelse ink.tag_bg); + var theme_fg = asGhostRgb(ink.fg orelse ink.tag_fg); + var dynamic_bg = if (vt) |t| t.colorForXterm(.{ .dynamic = .background }) else null; + var dynamic_fg = if (vt) |t| t.colorForXterm(.{ .dynamic = .foreground }) else null; + if (vt != null and vt.?.modes.get(.reverse_colors)) { + std.mem.swap(GColor.RGB, &theme_bg, &theme_fg); + std.mem.swap(?GColor.RGB, &dynamic_bg, &dynamic_fg); + } + var self: Filter = .{ + .target = filterPalette(palette, ink), + .theme_bg = asTriple(theme_bg), + .theme_fg = asTriple(theme_fg), + .default_bg = asTriple(theme_bg), + .fallback_fg = asTriple(theme_fg), + .default_bg_luminance = luminanceOf(theme_bg), + .fg_for_palette = undefined, + .bg_for_palette = undefined, + .fg_default = undefined, + .bg_default = undefined, + }; + var default_bg = theme_bg; + if (dynamic_bg) |rgb| default_bg = keyedRgb(&self, rgb); + self.default_bg = asTriple(default_bg); + self.default_bg_luminance = luminanceOf(default_bg); + if (theme_bg.contrast(default_bg) > theme_fg.contrast(default_bg)) + self.fallback_fg = asTriple(theme_bg); + + self.fg_default = asPardesColor(legible(&self, if (dynamic_fg) |rgb| keyedRgb(&self, rgb) else theme_fg)); + self.bg_default = asPardesColor(default_bg); + for (&source, 0..) |current, i| { + const idx: u8 = @intCast(i); + const mapped = paletteRgb(&self, idx, current); + self.fg_for_palette[idx] = asPardesColor(legible(&self, mapped)); + self.bg_for_palette[idx] = asPardesColor(mapped); + } + return self; +} + +/// The filter a +Pager's spans are drawn through (Term.filter). +pub fn pagerFilter(ink: *const Ink, palette: *FilterPalette) Filter { + return filterOf(ink, palette, null); +} + +fn filterFg(self: *Filter, style: ghostty_vt.Style) plain.Color { + return switch (style.fg_color) { + .none => self.fg_default, + .palette => |idx| self.fg_for_palette[idx], + .rgb => |rgb| asPardesColor(legible(self, keyedRgb(self, rgb))), + }; +} + +fn filterBg(self: *Filter, style: ghostty_vt.Style, cell: *const ghostty_vt.Cell) plain.Color { + switch (cell.content_tag) { + .bg_color_palette => return self.bg_for_palette[cell.content.color_palette.data], + .bg_color_rgb => {}, + else => switch (style.bg_color) { + .none => return self.bg_default, + .palette => |idx| return self.bg_for_palette[idx], + .rgb => {}, + }, + } + // Truecolour, from either the cell or its style. + return asPardesColor(keyedRgb(self, style.bg(cell, &GColor.default).?)); +} + +/// A +Pager span's colour (Term.page), as `filterFg` and `filterBg` map a +/// cell's. +pub fn spanColor(self: *Filter, color: plain.Color, is_bg: bool) plain.Color { + return switch (color) { + .default => color, + .index => |idx| if (is_bg) self.bg_for_palette[idx] else self.fg_for_palette[idx], + .rgb => |rgb| blk: { + const keyed = keyedRgb(self, asGhostRgb(rgb)); + break :blk asPardesColor(if (is_bg) keyed else legible(self, keyed)); + }, + }; +} + +pub fn legible(self: *const Filter, rgb: GColor.RGB) GColor.RGB { + if (contrastOf(luminanceOf(rgb), self.default_bg_luminance) >= + min_contrast) return rgb; + return asGhostRgb(self.fallback_fg); +} + +pub fn paletteRgb(self: *Filter, idx: u8, current: GColor.RGB) GColor.RGB { + if (current.eql(GColor.default[idx])) return asGhostRgb(self.target[idx]); + return keyedRgb(self, current); +} + +pub fn keyedRgb(self: *Filter, rgb: GColor.RGB) GColor.RGB { + return asGhostRgb(self.target[nearestKey(self, rgb)]); +} + +pub fn nearestKey(self: *Filter, rgb: GColor.RGB) u8 { + const rgb24 = (@as(u32, rgb.r) << 16) | (@as(u32, rgb.g) << 8) | rgb.b; + const slot: u8 = @truncate((rgb24 *% 0x9e3779b1) >> 24); + if (self.cache_valid[slot] and asGhostRgb(self.cache_rgb[slot]).eql(rgb)) + return self.cache_key[slot]; + + var best: u8 = 0; + var best_distance: u32 = std.math.maxInt(u32); + for (GColor.default, 0..) |candidate, i| { + const distance = colorDistance(rgb, candidate); + // Strict comparison makes duplicate-colour ties stable at the + // lowest canonical xterm key. + if (distance < best_distance) { + best_distance = distance; + best = @intCast(i); + } + } + self.cache_rgb[slot] = asTriple(rgb); + self.cache_key[slot] = best; + self.cache_valid[slot] = true; + return best; +} + +const channel_luminance: [256]f64 = blk: { + @setEvalBranchQuota(20000); + var table: [256]f64 = undefined; + for (&table, 0..) |*slot, c| { + const normalized: f64 = @as(f64, @floatFromInt(c)) / 255; + slot.* = if (normalized <= 0.03928) + normalized / 12.92 + else + std.math.pow(f64, (normalized + 0.055) / 1.055, 2.4); + } + break :blk table; +}; + +pub fn luminanceOf(rgb: GColor.RGB) f64 { + return 0.2126 * channel_luminance[rgb.r] + + 0.7152 * channel_luminance[rgb.g] + + 0.0722 * channel_luminance[rgb.b]; +} + +/// ghostty's `RGB.contrast` with both luminances already in hand. +fn contrastOf(a_luminance: f64, b_luminance: f64) f64 { + const lighter = @max(a_luminance, b_luminance); + const darker = @min(a_luminance, b_luminance); + return (lighter + 0.05) / (darker + 0.05); +} + +fn colorDistance(a: GColor.RGB, b: GColor.RGB) u32 { + const dr = @as(i32, a.r) - @as(i32, b.r); + const dg = @as(i32, a.g) - @as(i32, b.g); + const db = @as(i32, a.b) - @as(i32, b.b); + return @intCast(dr * dr + dg * dg + db * db); +} + +fn ghostColor(ink: *const Ink, color: ghostty_vt.Style.Color, is_bg: bool) plain.Color { + return switch (color) { + .none => blk: { + const t = if (is_bg) ink.bg else ink.fg; + break :blk if (t) |c| .{ .rgb = c } else .default; + }, + .palette => |idx| ink.palColor(idx), + .rgb => |rgb| .{ .rgb = .{ rgb.r, rgb.g, rgb.b } }, + }; +} + +/// When the pane's next kitty animation frame is due (ms on the core's +/// clock), as its last drawn frame left it; null when nothing plays. +pub fn due(state: *const State) ?u64 { + if (comptime !images_enabled) 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(state: *State) void { + if (comptime !images_enabled) 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(maybe: ?*const State) ?bool { + if (comptime !images_enabled) return null; + const state = maybe orelse return null; + return state.images.petscii; +} + +/// Whether the screen showing holds any kitty graphics image. +pub fn hasImages(maybe: ?*const State) bool { + if (comptime !images_enabled) return false; + const state = maybe orelse return false; + return state.vt.screens.active.kitty_images.images.count() > 0; +} + +/// Its kitty graphics over the body's rows, as placements appended to +/// `out` (after the rows and their colours: placeholder cells are blanked +/// in `frame`, `frame_cols` wide). `at.rows_of` maps its view's rows to +/// the body's; a prompt row outside tty mode is cut or hidden, its columns +/// not the grid's, and shows none. +pub fn images(state: *State, gpa: std.mem.Allocator, at: ImagesAt, out: *std.ArrayList(plain.Placement), frame: []plain.Cell, frame_cols: u16) void { + if (comptime !images_enabled) return; + const screen = state.vt.screens.active; + var rows_of: [1024]?u16 = undefined; + const vp_rows = @min(at.rows_of.len, rows_of.len); + var any_placeholder = false; + for (rows_of[0..vp_rows], at.rows_of[0..vp_rows], 0..) |*slot, body_row, vi| { + slot.* = null; + const vr = body_row orelse continue; + const row_pin = screen.pages.pin(.{ .viewport = .{ .y = @intCast(vi) } }) orelse continue; + const flags = row_pin.rowAndCell().row; + if (!at.tty_mode and flags.semantic_prompt != .none) continue; + any_placeholder = any_placeholder or flags.kitty_virtual_placeholder; + slot.* = vr; + } + // Nothing to draw, no placeholder to blank and nothing cached to let + // go: the common case costs the rows' flags. + if (!any_placeholder and screen.kitty_images.placements.count() == 0 and state.images.converted.count() == 0) return; + state.images.draw(gpa, &state.vt, at, rows_of[0..vp_rows], out, frame, frame_cols); +} + +test "the luminance table answers exactly what ghostty computes" { + for (0..256) |i| { + const c: u8 = @intCast(i); + const grey: GColor.RGB = .{ .r = c, .g = c, .b = c }; + try std.testing.expectEqual(grey.luminance(), luminanceOf(grey)); + } + // Channel weights are asymmetric, so a grey ramp alone would not catch a + // transposed coefficient. The palette is what the tables enumerate. + for (GColor.default) |candidate| { + try std.testing.expectEqual(candidate.luminance(), luminanceOf(candidate)); + for (GColor.default) |page| { + try std.testing.expectEqual( + candidate.contrast(page), + contrastOf(luminanceOf(candidate), luminanceOf(page)), + ); + } + } +} diff --git a/src/terminal.zig b/src/terminal.zig deleted file mode 100644 index 68b3adde..00000000 --- a/src/terminal.zig +++ /dev/null @@ -1,3422 +0,0 @@ -//! 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 std = @import("std"); -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 Key = pardes.Key; -const Pane = panes.Pane; -const EditText = panes.EditText; -const File = panes.File; - -const ghostty_vt = @import("ghostty-vt"); - -pub const history_max = 64; - -pub const VtSlot = ghostty_vt.Terminal; -/// A cell of an emulator's pages, as `getCell` reads it (src/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; -pub const TerminalImages = if (images_enabled) @import("TerminalImages.zig") else void; -pub const StreamSlot = ghostty_vt.Stream(MarkedHandler); - -/// The `aid` pardes's injected bash and fish marks carry (host_io.zig). -pub const prompt_aid = "pardes"; - -/// ghostty's handler, plus where the shell is in its command cycle as -/// its OSC 133 marks tell it: ghostty parses D's exit status and drops -/// it, and /pane/<n>/pty/run waits on exactly that. Only marks carrying -/// pardes's own `aid` move it, so fish's native marks, a nested shell's -/// and a stray `133;D` in some file being printed all pass it by. -pub const MarkedHandler = struct { - inner: ghostty_vt.TerminalStream.Handler, - phase: enum { none, prompt, input, running } = .none, - /// Counts commands started (C at the input phase). - started: u32 = 0, - /// Counts prompts drawn (B), so a line the shell refused without - /// running (a fish syntax error: no C, no D, a new prompt) shows. - prompts: u32 = 0, - /// D marks outside a running command: the shell handled a line - /// without starting it (bash on a syntax error prints no C). - declined: u32 = 0, - /// The newest prompt continues an unfinished line (bash's PS2, marked - /// `k=c`): the shell still holds the start of the command. - continuation: bool = false, - /// Where the newest command's output began (its C) and ended (its - /// D) on the primary screen, pinned so scrolling keeps them. - out_start: ?*ghostty_vt.Pin = null, - out_end: ?*ghostty_vt.Pin = null, - /// The running command's output was erased under it -- a clear, ED 3, - /// a reset -- so the pins no longer span what it printed. ED 3 flags a - /// pin on an erased history row `garbage` (ghostty 1.4), but `pinTop` - /// re-pins the start at the screen's top, so the flag is gone with the - /// old pin: this remembers it, as it does for a reset or a pin that - /// could not be made. - lost: bool = false, - - /// The newest command to end: which one, and its status if given. - finished: ?struct { seq: u32, status: ?i32 } = null, - - const Action = ghostty_vt.TerminalStream.Action; - - /// Move one of the output pins to the cursor. Only the primary screen - /// is pinned: a command's own full-screen display is not its output. - fn pinCursor(self: *@This(), slot: *?*ghostty_vt.Pin, now: bool) void { - const screen = self.inner.terminal.screens.get(.primary) orelse return; - if (slot.*) |old| screen.pages.untrackPin(old); - slot.* = null; - if (!now or self.inner.terminal.screens.active_key != .primary) return; - slot.* = screen.pages.trackPin(screen.cursor.page_pin.*) catch null; - } - - pub fn vt(self: *@This(), comptime action: Action.Tag, value: Action.Value(action)) void { - if (comptime action == .semantic_prompt) mark: { - const aid = value.readOption(.aid) orelse break :mark; - if (!std.mem.eql(u8, aid, prompt_aid)) break :mark; - switch (value.action) { - .fresh_line_new_prompt => { - self.phase = .prompt; - self.continuation = value.readOption(.prompt_kind) == .continuation; - }, - .end_prompt_start_input => { - self.phase = .input; - self.prompts +%= 1; - }, - // bash's DEBUG trap also fires on its own PROMPT_COMMAND, - // outside the input phase; only a C that ends input counts - .end_input_start_output => if (self.phase == .input) { - self.phase = .running; - self.started +%= 1; - self.lost = false; - self.pinCursor(&self.out_start, true); - self.pinCursor(&self.out_end, false); - }, - .end_command => if (self.phase == .running) { - self.phase = .none; - self.finished = .{ .seq = self.started, .status = value.readOption(.exit_code) }; - self.pinCursor(&self.out_end, true); - } else { - self.declined +%= 1; - }, - else => {}, - } - } - if (comptime action == .erase_display_complete or action == .erase_display_scrollback or - action == .erase_display_scroll_complete or action == .full_reset) - { - self.inner.vt(action, value); - // A `clear` under a running command: its output is what it - // prints from here, the screen's top, not lost. Only what the - // scrollback later loses is (the pin goes `garbage`). - if (self.phase == .running) self.pinTop(&self.out_start); - return; - } - self.inner.vt(action, value); - } - - /// Pins `slot` to the primary screen's top-left; lost when it cannot be. - fn pinTop(self: *@This(), slot: *?*ghostty_vt.Pin) void { - const screen = self.inner.terminal.screens.get(.primary) orelse return; - if (slot.*) |old| screen.pages.untrackPin(old); - slot.* = null; - if (self.inner.terminal.screens.active_key != .primary) { - self.lost = true; - return; - } - const top = screen.pages.pin(.{ .active = .{} }) orelse { - self.lost = true; - return; - }; - slot.* = screen.pages.trackPin(top) catch null; - if (slot.* == null) self.lost = true; - } - - pub fn deinit(self: *@This()) void { - self.inner.deinit(); - } -}; - -fn ptyReport(handler: *ghostty_vt.TerminalStream.Handler, data: []const u8) void { - const state: *State = @alignCast(@fieldParentPtr("vt", handler.terminal)); - const room = state.reply.len - state.reply_len; - // A cut answer is worse than none: the program would read the start of - // a sequence and wait, or misparse what follows. - if (data.len > room) { - state.reply_dropped +|= 1; - return; - } - @memcpy(state.reply[state.reply_len..][0..data.len], data); - state.reply_len += @intCast(data.len); -} - -fn ptyDeviceAttrs(_: *ghostty_vt.TerminalStream.Handler) ghostty_vt.device_attributes.Attributes { - return .{}; -} - -/// CSI 14/16/18 t: the pane's size, and its cells' in pixels, which a -/// program sizes its kitty graphics by (yazi asks 16 t). Unknown, not asked. -fn ptySize(handler: *ghostty_vt.TerminalStream.Handler) ?ghostty_vt.size_report.Size { - const t = handler.terminal; - if (t.width_px == 0 or t.height_px == 0 or t.cols == 0 or t.rows == 0) return null; - return .{ .rows = t.rows, .columns = t.cols, .cell_width = t.width_px / t.cols, .cell_height = t.height_px / t.rows }; -} - -pub const State = struct { - /// What the emulator and this struct are allocated with: the core's, - /// but on a screen-state replica the C heap (`emulator_gpa`), 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. - gpa: std.mem.Allocator, - vt: VtSlot, - stream: StreamSlot, - /// The emulator's answers to its program (DSR, DA, kitty graphics, ...) - /// from one read of its output, written to its pty after it. Room for - /// a read's worth of kitty answers (yazi or `kitten icat` asking about - /// a batch of images in one write); an answer that does not fit whole - /// is dropped whole, never cut short (`reply_dropped` counts them). - reply: [4096]u8 = undefined, - reply_len: u16 = 0, - reply_dropped: u32 = 0, - /// The grid cell the program last heard the mouse at, so motion is - /// reported once per cell. - mouse_cell: ?ghostty_vt.Coordinate = null, - /// The kitty graphics its program placed, as drawn (TerminalImages.zig). - images: TerminalImages = if (images_enabled) .{} else {}, - /// Counts the emulator's writes (output, a resize, its view scrolled): - /// a new count is a new state for its replicas (screen_state.Track). - changes: u32 = 0, - /// A step read its rows (its history too): a replica replaying that - /// step must hold them, so its authority sends the ones it does not - /// before the step's unit (replica.Screens.fill). - read: bool = false, - /// The size a step gave it, on an authority with screen-state replicas: - /// made after the step's unit (`resizeDeferred`), so that the rest of - /// the step reads the grid it had, as its replicas' replays do, and the - /// rows sent them for it (Screens.fill) are of that grid's numbering. - resize_to: ?struct { cols: u16, rows: u16 } = null, - - /// The emulator as its program has made it, for the replay digest - /// (src/walk.zig): the active screen's text, how much history is above - /// it and where the view is, the cursor, the answers not yet written. - /// Not its pages (their addresses are its own), nor the history's text - /// (the screen's was all of it once, and a session's digest is taken - /// every step), nor the kitty images, whose media is read off the host: - /// a replica's terminal is the authority's screen state from phase 5 - /// on (docs/next-daemon.md). - pub fn digest(s: *const State, h: *pardes.walk.Hasher) void { - // Under screen-state terminals the emulator is the authority's, and - // a replica's is what the last delta made it: compared as screens - // (test/replicas.zig), not step by step. - if (pardes.tape.screenState()) return; - s.digestScreen(h, true); - } - - /// `view`: where its view is too (a replica's speculation may move it). - pub fn digestScreen(s: *const State, h: *pardes.walk.Hasher, view: bool) void { - const screen = s.vt.screens.active; - const sb = screen.pages.scrollbar(); - const cur = screen.cursor; - const offset = if (view) sb.offset else 0; - const facts = .{ sb.total, offset, sb.len, cur.x, cur.y, s.vt.modes.get(.cursor_visible), s.vt.screens.active_key, s.reply_dropped }; - inline for (facts) |fact| h.update(std.mem.asBytes(&fact)); - h.update(s.reply[0..s.reply_len]); - var buf: [4096]u8 = undefined; - var text: std.Io.Writer.Hashing(pardes.walk.Hasher) = .initHasher(h.*, &buf); - if (screen.pages.getBottomRight(.active)) |br| - screen.dumpString(&text.writer, .{ .tl = screen.pages.getTopLeft(.active), .br = br, .unwrap = false }) catch unreachable; // a hashing writer never fails - text.writer.flush() catch unreachable; // a hashing writer never fails - h.* = text.hasher; - } - - /// What the dump keeps of a terminal beside its emulator, by name as - /// every dump is (src/walk.zig). - const Parts = struct { - reply: []const u8 = "", - reply_dropped: u32 = 0, - mouse_cell: ?ghostty_vt.Coordinate = null, - petscii: bool = false, - /// The view's top row, counted from the top of the history. - view: usize = 0, - phase: @FieldType(MarkedHandler, "phase") = .none, - started: u32 = 0, - prompts: u32 = 0, - declined: u32 = 0, - continuation: bool = false, - lost: bool = false, - finished: @FieldType(MarkedHandler, "finished") = null, - out_start: ?ghostty_vt.Coordinate = null, - out_end: ?ghostty_vt.Coordinate = null, - }; - - fn pinAt(s: *const State, slot: ?*ghostty_vt.Pin) ?ghostty_vt.Coordinate { - const pin = slot orelse return null; - const screen = s.vt.screens.get(.primary) orelse return null; - return (screen.pages.pointFromPin(.screen, pin.*) orelse return null).screen; - } - - /// The dump's: ghostty's snapshot of the emulator (both screens, their - /// history, styles, links and kitty images), then `Parts`. A sequence - /// its program had begun and not ended is not kept: the snapshot is at - /// the ground state. - pub fn dumpWrite(s: *const State, gpa: std.mem.Allocator, w: *std.Io.Writer) !void { - const h = &s.stream.handler; - const parts: Parts = .{ - .reply = s.reply[0..s.reply_len], - .reply_dropped = s.reply_dropped, - .mouse_cell = s.mouse_cell, - .petscii = if (comptime images_enabled) s.images.petscii else false, - .view = s.vt.screens.active.pages.scrollbar().offset, - .phase = h.phase, - .started = h.started, - .prompts = h.prompts, - .declined = h.declined, - .continuation = h.continuation, - .lost = h.lost, - .finished = h.finished, - .out_start = s.pinAt(h.out_start), - .out_end = s.pinAt(h.out_end), - }; - const bytes = try pardes.walk.save(Parts, gpa, &parts); - defer gpa.free(bytes); - try w.writeAll(std.mem.asBytes(&@as(u64, bytes.len))); - try w.writeAll(bytes); - // A join's (dump.zig `dumpJoin`): its size alone, an emulator made - // afresh there, which its first delta replaces. - if (pardes.dump.slim_terminals) return w.writeAll(std.mem.asBytes(&[2]u16{ s.vt.cols, s.vt.rows })); - try ghostty_vt.snapshot.encode(gpa, w, &s.vt, .{ .continuation = .ground }); - } - - /// What `dumpRead` made, freed: a load that failed after it. - pub fn dumpFree(s: *State, gpa: std.mem.Allocator) void { - if (comptime images_enabled) s.images.deinit(gpa); - s.stream.deinit(); - s.vt.deinit(gpa); - } - - /// `dumpWrite`'s back into `out`, a new State, as `create` makes one. - pub fn dumpRead(out: *State, gpa: std.mem.Allocator, bytes: []const u8) !void { - if (bytes.len < 8) return error.EndOfDump; - const n = std.math.cast(usize, std.mem.bytesToValue(u64, bytes[0..8])) orelse return error.EndOfDump; - if (bytes.len - 8 < n) return error.EndOfDump; - var arena: std.heap.ArenaAllocator = .init(gpa); - defer arena.deinit(); - const parts = try pardes.walk.load(Parts, arena.allocator(), bytes[8..][0..n], null); - var reader: std.Io.Reader = .fixed(bytes[8 + n ..]); - if (reader.buffer.len == 4) { - const size = std.mem.bytesToValue([2]u16, bytes[8 + n ..][0..4]); - out.* = .{ .gpa = gpa, .vt = try emulator(gpa, @max(1, size[0]), @max(1, size[1])), .stream = undefined }; - } else { - var decoded = try ghostty_vt.snapshot.decodeExact(gpa, terminalIo(), &reader, .{ - .max_continuation_bytes = 0, - .kitty_image_storage_limit = if (images_enabled) TerminalImages.storage_limit else 0, - }); - 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()); - }; - out.wire(); - const reply = parts.reply[0..@min(parts.reply.len, out.reply.len)]; - @memcpy(out.reply[0..reply.len], reply); - out.reply_len = @intCast(reply.len); - out.reply_dropped = parts.reply_dropped; - out.mouse_cell = parts.mouse_cell; - out.images = if (images_enabled) .{ .petscii = parts.petscii } else {}; - const h = &out.stream.handler; - h.phase = parts.phase; - h.started = parts.started; - h.prompts = parts.prompts; - h.declined = parts.declined; - h.continuation = parts.continuation; - h.lost = parts.lost; - h.finished = parts.finished; - if (out.vt.screens.get(.primary)) |screen| { - inline for (.{ .{ "out_start", parts.out_start }, .{ "out_end", parts.out_end } }) |pair| if (pair[1]) |at| { - if (screen.pages.pin(.{ .screen = at })) |pin| @field(h, pair[0]) = screen.pages.trackPin(pin) catch null; - }; - } - const screen = out.vt.screens.active; - const bottom = screen.pages.scrollbar().offset; - screen.scroll(.{ .delta_row = @as(isize, @intCast(parts.view)) - @as(isize, @intCast(bottom)) }); - } - - /// The stream over the emulator, its answers to the program and its - /// size reports routed here, PNG decoded: what `create` and a dump's - /// load both do once the emulator is in place. - fn wire(s: *State) void { - s.stream = .init(.{ .handler = .{ .inner = s.vt.vtHandler() }, .allocator = s.gpa }); - s.stream.handler.inner.effects.write_pty = ptyReport; - s.stream.handler.inner.effects.device_attributes = ptyDeviceAttrs; - s.stream.handler.inner.effects.size = ptySize; - if (comptime images_enabled) TerminalImages.installPngDecoder(); - } -}; - -const GColor = ghostty_vt.color; - -const FilterPaletteKey = struct { - bg: GColor.RGB, - fg: GColor.RGB, - base: [16]GColor.RGB, -}; - -pub const FilterPalette = LivePalette; - -const LivePalette = struct { - key: ?FilterPaletteKey = null, - colors: GColor.Palette = GColor.default, - - fn get(self: *LivePalette, theme: *const pardes.Theme) *const GColor.Palette { - const bg = asGhostRgb(theme.bg orelse theme.tag_bg); - const fg = asGhostRgb(theme.fg orelse theme.tag_fg); - var base: [16]GColor.RGB = undefined; - if (theme.palette) |palette| { - for (&base, palette) |*dst, src| dst.* = asGhostRgb(src); - } else { - const synthesized = [16][3]u8{ - theme.bg orelse theme.tag_bg, - theme.kw, - theme.str, - theme.num, - theme.box, - theme.sel_bg, - theme.comment, - theme.fg orelse theme.tag_fg, - theme.lineno, - theme.kw, - theme.str, - theme.num, - theme.scroll_thumb, - theme.sel_fg, - theme.tag_fg, - theme.fg orelse theme.tag_fg, - }; - 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; - - var seed = GColor.default; - for (base, 0..) |rgb, i| seed[i] = rgb; - self.colors = GColor.generate256Color(seed, .empty, bg, fg, false); - self.key = key; - return &self.colors; - } -}; - -fn asGhostRgb(rgb: [3]u8) GColor.RGB { - return .{ .r = rgb[0], .g = rgb[1], .b = rgb[2] }; -} - -/// The owned text standing in for `rows` live terminal rows, beginning at -/// absolute surface row `row`. The emulator grid remains untouched underneath. -pub const EditBuffer = struct { - row: i32 = 0, - rows: i32 = 1, - text: []u8 = &.{}, -}; - -/// One whole-state terminal edit boundary. Null means the pane has not yet -/// materialized an edit buffer; non-null snapshots own their text. -pub const Snapshot = struct { - ovl: ?EditBuffer, - cur_row: i32, - cur_col: i32, - vsel: panes.Text.CharSel, -}; - -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). -fn tempDir() []const u8 { - const dir = std.c.getenv("TMPDIR") orelse return "/tmp"; - const path = std.mem.span(dir); - return if (path.len > 0 and path[0] == '/') path else "/tmp"; -} - -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)); -} - -/// What pardes made of a terminal's stream that its emulator does not hold -/// (the OSC 133 cycle, MarkedHandler), for a replica's delta: phase u8, -/// started, prompts, declined u32, continuation and lost u8, a finished -/// command's seq u32 and status i32 (all ones: none; i32 min: no status). -// ponytail: the output pins stay the authority's (its 9P pty/run reads them). -pub const marks_len = 1 + 4 * 3 + 2 + 4 + 4; - -pub fn marksOf(state: *const State, buf: *[marks_len]u8) []const u8 { - const m = &state.stream.handler; - var w: std.Io.Writer = .fixed(buf); - w.writeByte(@backingInt(m.phase)) catch unreachable; - inline for (.{ m.started, m.prompts, m.declined }) |n| w.writeInt(u32, n, .little) catch unreachable; - w.writeAll(&.{ @intFromBool(m.continuation), @intFromBool(m.lost) }) catch unreachable; - w.writeInt(u32, if (m.finished) |f| f.seq else std.math.maxInt(u32), .little) catch unreachable; - w.writeInt(i32, if (m.finished) |f| f.status orelse std.math.minInt(i32) else 0, .little) catch unreachable; - return w.buffered(); -} - -/// A replica's terminal takes its authority's marks (`marksOf`). -pub fn takeMarks(state: *State, bytes: []const u8) void { - if (bytes.len != marks_len) return; - const m = &state.stream.handler; - m.phase = @fromBackingInt(@intCast(bytes[0])); - m.started = std.mem.readInt(u32, bytes[1..5], .little); - m.prompts = std.mem.readInt(u32, bytes[5..9], .little); - m.declined = std.mem.readInt(u32, bytes[9..13], .little); - m.continuation = bytes[13] != 0; - m.lost = bytes[14] != 0; - const seq = std.mem.readInt(u32, bytes[15..19], .little); - const status = std.mem.readInt(i32, bytes[19..23], .little); - 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; - -/// 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; -} - -/// 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; -} - -/// A speculation that moves a terminal's view: a screen-state replica's -/// may (its rollback puts the view back, replica.zig `views`, and a delta -/// sets it), any other stops (`authorityOnly`). -fn viewOnly(comptime why: []const u8) bool { - if (!pardes.tape.speculating()) return false; - if (pardes.tape.screenState()) { - pardes.tape.touchTerminal(); - return false; - } - pardes.tape.poison(why); - return true; -} - -/// Where a terminal's view is: its top row counted from the top of its -/// history, or null following its output (a replica's rollback copy, -/// which holds no emulator, keeps it so). -pub fn viewOf(pane: *const Pane) ?usize { - const state = pane.terminal orelse return null; - const pages = &state.vt.screens.active.pages; - if (pages.viewport == .active) return null; - return pages.scrollbar().offset; -} - -pub fn viewTo(pane: *Pane, at: ?usize) void { - const state = pane.terminal orelse return; - 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; - 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; - 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()) { - state.resize_to = .{ .cols = cols, .rows = rows }; - return; - } - state.changes +%= 1; - 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 {}; - }; -} - -/// 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 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; -} - -/// A paste as xterm makes one (ghostty's encoder): the control bytes a -/// paste could smuggle a command in by (ESC, so no ESC[201~ can end -/// 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); -} - -/// ...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, -/// 1015 urxvt, 1005 UTF-8, else X10) how, modifiers as shift+4, meta+8, -/// 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 &.{}; - const input = ghostty_vt.input; - var writer = std.Io.Writer.fixed(buf); - var opts: input.MouseEncodeOptions = .{ - .event = state.vt.flags.mouse_event, - .format = state.vt.flags.mouse_format, - .size = .{ - .screen = .{ .width = state.vt.cols, .height = state.vt.rows }, - .cell = .{ .width = 1, .height = 1 }, - .padding = .{}, - }, - .any_button_pressed = any_pressed, - .last_cell = &state.mouse_cell, - }; - // A release is always reported; the rest only over the grid, or held. - if (action == .release) opts.any_button_pressed = true; - input.encodeMouse(&writer, .{ - .action = switch (action) { - .press => .press, - .release => .release, - .motion => .motion, - }, - .button = if (button) |b| switch (b) { - .left => .left, - .middle => .middle, - .right => .right, - .wheel_up => .four, - .wheel_down => .five, - .wheel_left => .six, - .wheel_right => .seven, - } else null, - .mods = .{ .shift = mods.shift, .alt = mods.alt, .ctrl = mods.ctrl }, - .pos = .{ .x = @as(f32, @floatFromInt(col)) + 0.5, .y = @as(f32, @floatFromInt(row)) + 0.5 }, - }, opts) catch return &.{}; // no report rather than half of one - return writer.buffered(); -} - -/// 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; - const m = &state.vt.modes; - if (!reportsMouse(pane)) return switch (wheel) { - .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); -} - -/// 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 { - var out: std.Io.Writer.Allocating = .init(gpa); - errdefer out.deinit(); - try writeScreenText(pane, &out.writer); - return out.toOwnedSlice(); -} - -fn writeScreenText(pane: *Pane, w: *std.Io.Writer) !void { - const state = pane.terminal orelse return; - const screen = state.vt.screens.active; - const br = screen.pages.getBottomRight(.screen) orelse return; - var both: TeeWriter = .{ .a = w }; - try screen.dumpString(&both.writer, .{ .tl = screen.pages.getTopLeft(.screen), .br = br, .unwrap = true }); - if (both.count > 0 and both.final != '\n') try w.writeByte('\n'); -} - -/// Passes bytes through, remembering how many and the last one. -const TeeWriter = struct { - a: *std.Io.Writer, - count: usize = 0, - final: u8 = 0, - writer: std.Io.Writer = .{ .vtable = &.{ .drain = drain }, .buffer = &.{} }, - - fn drain(w: *std.Io.Writer, data: []const []const u8, splat: usize) std.Io.Writer.Error!usize { - const t: *TeeWriter = @alignCast(@fieldParentPtr("writer", w)); - var n: usize = 0; - for (data[0 .. data.len - 1]) |bytes| { - try t.a.writeAll(bytes); - t.note(bytes); - n += bytes.len; - } - const pattern = data[data.len - 1]; - for (0..splat) |_| { - try t.a.writeAll(pattern); - t.note(pattern); - n += pattern.len; - } - return n; - } - - fn note(t: *TeeWriter, bytes: []const u8) void { - if (bytes.len == 0) return; - t.count += bytes.len; - t.final = bytes[bytes.len - 1]; - } -}; - -/// 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 { - var buf: [256]u8 = undefined; - var counting: std.Io.Writer.Discarding = .init(&buf); - writeScreenText(pane, &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; - 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. -fn emulator(gpa: std.mem.Allocator, cols: u16, rows: u16) !ghostty_vt.Terminal { - return ghostty_vt.Terminal.init(terminalIo(), gpa, .{ - .cols = cols, - .rows = rows, - .max_scrollback_bytes = 16 * 1024 * 1024, - .kitty_image_storage_limit = if (images_enabled) TerminalImages.storage_limit else 0, - // Every kitty medium, as ghostty and kitty take them: a file (t=f), - // a temporary file it then deletes (t=t, in the temp directory and - // named as one) and shared memory (t=s), beside direct data. libghostty - // defaults to direct alone, which `kitten icat` and timg detect and - // fall back from, base64 through the pty. What the program can read - // it could send itself: it runs as the user, under pardes. - .kitty_image_loading_limits = if (images_enabled) .allWithTempDir(tempDir()) else if (@FieldType(ghostty_vt.Terminal.Options, "kitty_image_loading_limits") == void) {} else .direct, - }); -} - -/// 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); - // 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.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; -} - -/// 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; - // 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; -} - -/// 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); -} - -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 }; - 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; - var node = pages.pages.last.?; - while (left >= node.rows()) { - left -= node.rows(); - node = node.prev.?; - } - const pin = pages.trackPin(.{ .node = node, .y = @intCast(node.rows() - 1 - left) }) catch { - failed.* = true; - return .{}; - }; - return .{ .pin = pin, .offset = row - @as(i32, @intCast(bounded)) }; -} - -fn pinnedRow(pages: ?*ghostty_vt.PageList, row: RowPin) i32 { - const pin = row.pin orelse return row.offset; - const alive = pages orelse return 0; - if (pin.garbage) return 0; - var after: usize = 0; - var node = alive.pages.last; - while (node) |item| : (node = item.prev) { - if (item == pin.node) - return @as(i32, @intCast(alive.total_rows - after - item.rows() + pin.y)) +| row.offset; - after += item.rows(); - } - 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; - } - 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; - 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; - }; - // The program cleared the screen, or the rows the live copy stood on are - // gone (pruned, a reset): the copy goes with them, as what the program - // drew next. Kept, ghostty would move its rows to the top of what is - // left, over the program's new text. - var copy_lost = after.cleared or !after.alive; - for (spans[0..nspans], 0..) |span, i| { - if (span.overlay == overlay and after.erased[2 * i]) copy_lost = true; - const start = after.rows[2 * i]; - const rows = @max(1, after.rows[2 * i + 1] -| start +| 1); - moved = moved or start != span.overlay.row or rows != span.overlay.rows; - span.overlay.row = start; - span.overlay.rows = rows; - if (alive) |owner| { - if (span.start.pin) |pin| owner.untrackPin(pin); - if (span.end.pin) |pin| owner.untrackPin(pin); - } - } - // The rule above for the copy holds for the selections: one whose row - // is gone (ED 3 erased its history row, which ghostty flags `garbage`) - // goes too, rather than being clamped to the top. - const erased = after.erased[at_position..]; - const vsel_lost = if (vsel_at) |i| - erased[i] or (copy_lost and positions[i].edit_row != null) - else - false; - var sels_keep: [panes.Text.max_selections]bool = undefined; - for (0..pane.body.nsel) |i| sels_keep[i] = !(erased[sels_at + 2 * i] or erased[sels_at + 2 * i + 1]); - for ([_][]PositionPin{ positions[0..npositions], pointers }, [_]usize{ at_position, at_pointer }) |batch, first| for (batch, first..) |position, k| { - var row = after.rows[k]; - if (position.overlay) |edit| { - if (position.edit_row) |relative| { - row = edit.row +| relative; - } else if (row > edit.row) { - row = if (row < edit.row +| edit.rows) - edit.row - else - row -| edit.rows +| @as(i32, @intCast(modal.lineCount(edit.text))); - } - } - moved = moved or row != position.target.*; - position.target.* = row; - if (alive) |owner| if (position.row.pin) |pin| owner.untrackPin(pin); - }; - if (pointer_rows_lost) for (0..pane.sel.len) |button| { - pane.clearPointerSelection(button); - pane.sel[button].state = .none; - }; - 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; -} - -/// 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; -} - -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; - 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 { - // 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 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; - if (end.garbage) break :printed false; - var whole = !marks.lost and !start.garbage; - // Nothing printed: the whole of it. - if (start.eql(end.*)) break :printed whole; - // D is where the next prompt begins: the output ends a cell before. - // An end at the very top, or before the start, is output a redraw - // moved (a prompt drawn over it in a window two rows high): how - // much is not known, so it is not called whole. - const last = end.leftWrap(1) orelse break :printed false; - if (last.before(start.*)) break :printed false; - var from = start.*; - if (last.up(max_rows)) |floor| if (from.before(floor)) { - from = floor; - from.x = 0; - whole = false; - }; - return .{ - .text = try screen.selectionString(gpa, .{ .sel = ghostty_vt.Selection.init(from, last, false) }), - .whole = whole, - }; - }; - 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; - 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})); - break :keys keys; - }; - const physical: input.Key = switch (key.cp) { - Key.enter => .enter, - Key.backspace => .backspace, - Key.tab => .tab, - Key.escape => .escape, - Key.up => .arrow_up, - Key.down => .arrow_down, - Key.left => .arrow_left, - Key.right => .arrow_right, - Key.home => .home, - Key.end => .end, - Key.page_up => .page_up, - Key.page_down => .page_down, - Key.delete => .delete, - Key.insert => .insert, - Key.print_screen => .print_screen, - 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, - }; - 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; - // 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)) - 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, .{ - .key = physical, - .mods = .{ .ctrl = key.ctrl, .alt = key.alt, .shift = key.shift }, - .consumed_mods = .{ .shift = key.text.len > 0 and key.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, - }, options: { - var opts = input.KeyEncodeOptions.fromTerminal(&state.vt); - // fromTerminal cannot know this one and says so, defaulting to - // "option is not alt" — right for an app that lets macOS do the - // unicode translation and hands the encoder the composed text. - // Every pardes shell resolves the modifier itself and hands the - // core the BASE key with the alt bit and no text at all (see - // PardesView.keyDown, and app.mjs doing the same with the same - // two bits), so by the time this runs alt already means alt. - // Left at the default, a macOS build drops the ESC prefix on - // 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"); - } - - 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(); -} - -// 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. -const PromptCut = union(enum) { - /// show the row exactly as ghostty dumped it - keep, - /// show nothing at all - blank, - /// drop this many leading COLUMNS — the prompt — and keep the rest, which - /// is what was typed at it - cut: usize, -}; - -fn promptCut(pin: ghostty_vt.Pin) PromptCut { - const cells = pin.cells(.all); - var cols: usize = 0; - while (cols < cells.len and cells[cols].semantic_content == .prompt) cols += 1; - // Flagged, but with no prompt cells at the FRONT: a right-side prompt, or - // a repaint that has moved on. Nothing here is the prompt, so hide nothing. - if (cols == 0) return .keep; - // ...and all prompt, nothing typed yet: the row is chrome end to end. - if (cols >= cells.len) return .blank; - return .{ .cut = cols }; -} - -pub fn promptPrefixBytes(pane: *Pane, 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; - if (pin.rowAndCell().row.semantic_prompt == .none) return 0; - return switch (promptCut(pin)) { - .keep => 0, - .blank => raw.len, - .cut => |cols| @min(raw.len, File.rawAtDisplay(raw, cols)), - }; -} - -fn promptRow(pin: ghostty_vt.Pin, raw: []const u8) []const u8 { - const cols = switch (promptCut(pin)) { - .keep => return raw, - .blank => return "", - .cut => |n| n, - }; - const cells = pin.cells(.all); - var at: usize = 0; - var col: usize = 0; - while (col < cols and at < raw.len) { - const cell = &cells[col]; - at = @min(raw.len, at + dumpedBytes(pin, cell)); - // the tail cell of a wide glyph spells nothing of its own - col += if (cell.wide == .wide) @as(usize, 2) else 1; - } - return std.mem.trimEnd(u8, raw[at..], " \t"); -} - -fn dumpedBytes(pin: ghostty_vt.Pin, cell: *const ghostty_vt.Cell) usize { - switch (cell.wide) { - .spacer_head, .spacer_tail => return 0, - .narrow, .wide => {}, - } - var n: usize = switch (cell.content_tag) { - .codepoint, .codepoint_grapheme => std.unicode.utf8CodepointSequenceLength( - cell.codepoint(), - ) catch 1, - // A cell carrying only a colour still spells one blank in the dump. - else => 1, - }; - if (cell.content_tag == .codepoint_grapheme) { - if (pin.grapheme(cell)) |extra| for (extra) |cp| { - n += std.unicode.utf8CodepointSequenceLength(cp) catch 1; - }; - } - 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]; -} - -/// 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); - // 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); - // 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); - errdefer alloc.free(text); - var at: usize = 0; - var n: usize = 0; - var it = std.mem.splitScalar(u8, full, '\n'); - while (it.next()) |raw| { - const shown = if (pit.next()) |pin| - if (pin.rowAndCell().row.semantic_prompt != .none) promptRow(pin, raw) else raw - else - raw; - if (n > 0) { - text[at] = '\n'; - at += 1; - } - @memcpy(text[at..][0..shown.len], shown); - rows[n] = text[at..][0..shown.len]; - at += shown.len; - n += 1; - } - text[at] = '\n'; - at += 1; - rows[n] = text[at..][0..0]; - n += 1; - std.debug.assert(n == n_rows); - return .{ .text_alloc = text, .text = text[0..at], .rows = rows }; -} - -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)] - else - "", - }; - if (dst) |out| @memcpy(out[written..][0..bytes.len], bytes); - written += bytes.len; - } - return written; -} - -// Match surviving edit-buffer rows to their original terminal styles. -const EditAnchors = struct { - /// the buffer's own text, walked in order: a line the VIEWPORT skipped still - /// consumes the row it came from, so the lines below it stay aligned - text: []const u8 = &.{}, - at: usize = 0, - shell: []const []const u8 = &.{}, - /// the covered span, absolute grid rows, as `[first, end)` - first: usize = 0, - end: usize = 0, - lines: usize = 0, - /// the line `at` names, and the first row still unclaimed - idx: usize = 0, - cursor: usize = 0, - budget: usize = 0, - active: bool = false, - - fn init(p: *Pardes, pane: *Pane, o: EditBuffer) EditAnchors { - if (o.rows <= 0 or o.row < 0) return .{}; - const first: usize = @intCast(o.row); - const screen = pane.terminal.?.vt.screens.active; - const total = screen.pages.scrollbar().total; - if (first >= total) return .{}; - const covered: usize = @intCast(o.rows); - const count = @min(covered, total - first); - const tl = screen.pages.pin(.{ .screen = .{ .y = @intCast(first) } }) orelse return .{}; - const br = screen.pages.pin(.{ .screen = .{ - .x = screen.pages.cols - 1, - .y = @intCast(first + count - 1), - } }) orelse return .{}; - const arena = p.scratch.allocator(); - var output: std.Io.Writer.Allocating = .init(arena); - screen.dumpString(&output.writer, .{ .tl = tl, .br = br, .unwrap = false }) catch return .{}; - const shell = arena.alloc([]const u8, count) catch return .{}; - var raw = std.mem.splitScalar(u8, output.written(), '\n'); - var pins = tl.rowIterator(.right_down, br); - for (shell) |*row| { - const text = raw.next() orelse ""; - row.* = if (pins.next()) |pin| - if (pin.rowAndCell().row.semantic_prompt != .none) promptRow(pin, text) else text - else - text; - } - const lines = std.mem.count(u8, o.text, "\n") + 1; - return .{ - .text = o.text, - .shell = shell, - .first = first, - .end = first + count, - .lines = lines, - .cursor = first, - .budget = covered + 4 * lines, - .active = true, - }; - } - - fn shellRow(a: *EditAnchors, idx: usize) ?Anchor { - if (!a.active or idx >= a.lines) return null; - var found: ?Anchor = null; - while (a.idx <= idx) : (a.idx += 1) found = a.claim(a.nextLine() orelse return null); - return found; - } - - fn nextLine(a: *EditAnchors) ?[]const u8 { - if (a.at > a.text.len) return null; - const rest = a.text[a.at..]; - if (std.mem.indexOfScalar(u8, rest, '\n')) |n| { - a.at += n + 1; - return rest[0..n]; - } - // The last line has no terminator; one past the end ends the walk. - a.at = a.text.len + 1; - return rest; - } - - /// Where this line still stands over the grid, if anywhere. - fn claim(a: *EditAnchors, line: []const u8) ?Anchor { - const end = if (line.len == 0) @min(a.cursor + 1, a.end) else a.end; - var k = a.cursor; - while (k < end) : (k += 1) { - if (a.budget == 0) return null; - a.budget -= 1; - if (!std.mem.eql(u8, line, a.shell[k - a.first])) continue; - a.cursor = k + 1; - return .{ .row = @intCast(k) }; - } - if (a.cursor >= a.end) return null; - const shell = a.shell[a.cursor - a.first]; - var p: usize = 0; - while (p < line.len and p < shell.len and line[p] == shell[p]) p += 1; - var s: usize = 0; - const room = @min(line.len, shell.len) - p; - while (s < room and line[line.len - 1 - s] == shell[shell.len - 1 - s]) s += 1; - if (p + s == 0) return null; - if (line.len != p + s and shell.len - (p + s) > shell.len / 2) return null; - const row = a.cursor; - if (s > 0 or p >= shell.len) a.cursor += 1; - return .{ .row = @intCast(row), .prefix = p, .suffix = s, .shell_len = shell.len }; - } -}; - -const Anchor = struct { - /// the row, absolute while it comes from `EditAnchors`, viewport once - /// `recolorAnsi` has subtracted the walk's offset - row: i32, - prefix: usize = std.math.maxInt(usize), - suffix: usize = 0, - /// the row's own dumped length — what the suffix is measured from on the - /// GRID side, where the edit may have changed the byte count - shell_len: usize = 0, - - fn whole(an: Anchor) bool { - return an.prefix == std.math.maxInt(usize); - } -}; - -pub fn recolorAnsi(p: *Pardes, s: *Surface, pane: *Pane, r: pardes.Rect, tx: u16, tw: u16, body_h: u16, body: []const u8) void { - // No emulator, no ANSI cells: the whole pass — and the 256-colour theme - // projection behind it — is compiled out. - if (pane.terminal == null) return; - const body_y = p.bodyTop(pane, r); - var filtered_storage: FilteredColors = undefined; - const filtered: ?*FilteredColors = if (pane.tty_filter) blk: { - const tz_filter = tracy.zone(@src(), "filterInit"); - defer tz_filter.end(); - filtered_storage = FilteredColors.init(p, &pane.terminal.?.vt); - break :blk &filtered_storage; - } else null; - // DECSCNM, read once: the filtered palette folds it in itself, the raw - // 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); - // 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; - var walk: BodyWalk = .init(pane); - var lines = std.mem.splitScalar(u8, body, '\n'); - var vr: u16 = 0; - while (walk.next()) |row| : (vr += 1) { - if (vr >= body_h) break; - // Before any early exit below, or the lines fall out of step with rows. - const text = lines.next() orelse ""; - const anchor: Anchor = switch (row) { - .edit => |e| blk: { - if (anchors == null) anchors = .init(p, pane, pane.ovl.?); - var an = anchors.?.shellRow(e.idx) orelse continue; - an.row -= walk.goff; - break :blk an; - }, - .grid => |v| .{ .row = v }, - }; - const vi = anchor.row; - if (vi < 0 or vi >= vp_rows) continue; - const row_pin = pages.pin(.{ .viewport = .{ .y = @intCast(vi) } }) orelse continue; - const cut: u16 = if (pane.body.mode == .tty) 0 else cut: { - if (row_pin.rowAndCell().row.semantic_prompt == .none) break :cut 0; - break :cut switch (promptCut(row_pin)) { - .keep => 0, - // Blanked end to end: the row shows nothing of the grid, so - // projecting the prompt's own colours onto it would be a lie. - .blank => continue, - .cut => |n| std.math.cast(u16, n) orelse continue, - }; - }; - if (cut > 0 and text.len == 0) continue; - var at: usize = 0; - var sc: u16 = 0; - var gc: u16 = cut; - var sb: usize = 0; - const mine_from = @min(anchor.prefix, text.len); - const mine_to = text.len - @min(anchor.suffix, text.len); - var crossed = false; - while (at < text.len and sc < tw) { - const stop = modal.nextGrapheme(text, at); - if (stop <= at) break; - const span: u16 = if (sc + 1 < tw and s.at(tx + sc + 1, body_y + vr).len == 0) 2 else 1; - if (at >= mine_from and at < mine_to) { - sc += span; - at = stop; - continue; - } - if (at >= mine_to and !crossed) { - crossed = true; - const upto = anchor.shell_len - @min(anchor.suffix, anchor.shell_len); - while (sb < upto) { - const ci = cellAt(pages, row_pin, gc) orelse break; - sb += dumpedBytes(row_pin, ci.cell); - gc = std.math.add(u16, gc, 1) catch break; - } - } - const want = stop - at; - // Consume every cell that contributed to this grapheme. A cluster - // ghostty split across several cells is still ONE printed glyph. - var covered: usize = 0; - var style: ?pardes.CellStyle = null; - while (covered < want) { - const ci = cellAt(pages, row_pin, gc) orelse break; - if (style == null and ci.cell.wide != .spacer_tail and ci.cell.wide != .spacer_head) - style = cellStyle(p, ci, filtered, scnm); - covered += dumpedBytes(row_pin, ci.cell); - gc = std.math.add(u16, gc, 1) catch break; - // A spacer contributes no bytes; without this the loop would - // spin on a row that ends in one. - if (covered == 0 and gc >= pane.cols) break; - } - while (cellAt(pages, row_pin, gc)) |t| { - if (t.cell.wide != .spacer_tail) break; - gc = std.math.add(u16, gc, 1) catch break; - } - if (style) |st| for (0..span) |k| { - const cell = s.at(tx + sc + @as(u16, @intCast(k)), body_y + vr); - if (cell.default and filtered == null) continue; - cell.default = false; - cell.style = st; - }; - sb += covered; - sc += span; - at = stop; - } - var tail: ?pardes.CellStyle = null; - if (anchor.whole() or anchor.suffix > 0) { - while (sc < tw) { - const ci = cellAt(pages, row_pin, gc) orelse break; - gc = std.math.add(u16, gc, 1) catch break; - if (ci.cell.wide == .spacer_tail) continue; - const cell = s.at(tx + sc, body_y + vr); - sc += 1; - const style = cellStyle(p, ci, filtered, scnm); - tail = style; - if (cell.default and filtered == null) continue; - cell.default = false; - cell.style = style; - } - if (tail) |style| while (sc < tw) : (sc += 1) { - const cell = s.at(tx + sc, body_y + vr); - if (cell.default and filtered == null) continue; - cell.default = false; - cell.style = style; - }; - } - } -} - -/// The cell at column `x` of the row `row` pins, as `pages.getCell` reads -/// it, without walking from the viewport's top down to the row again: that -/// walk, once a cell, was most of a terminal's paint (once getCell was no -/// longer inlined, a frame of a 120x40 shell took 75 µs more). -fn cellAt(pages: *const ghostty_vt.PageList, row: ghostty_vt.Pin, x: u16) ?ghostty_vt.PageList.Cell { - if (x >= pages.cols or x >= row.node.cols()) return null; - const rac = row.node.page().getRowAndCell(x, row.y); - return .{ .node = row.node, .row = rac.row, .cell = rac.cell, .row_idx = row.y, .col_idx = x }; -} - -// 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). -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"); -} - -fn cellStyle(p: *Pardes, ci: ghostty_vt.PageList.Cell, filtered: ?*FilteredColors, scnm: bool) pardes.CellStyle { - const style = ci.style(); - var cs: pardes.CellStyle = .{ - .fg = if (filtered) |colors| colors.fg(style) else ghostColor(p, style.fg_color, scnm), - .bg = if (filtered) |colors| colors.bg(style, ci.cell) else ghostColor(p, style.bg_color, !scnm), - .bold = style.flags.bold, - .dim = style.flags.faint, - .italic = style.flags.italic, - .blink = style.flags.blink, - .reverse = style.flags.inverse, - .invisible = style.flags.invisible, - .strikethrough = style.flags.strikethrough, - .ul = @fromBackingInt(@intCast(@backingInt(style.flags.underline))), - }; - if (filtered == null) switch (ci.cell.content_tag) { - .bg_color_palette => cs.bg = palColor(p, ci.cell.content.color_palette.data), - .bg_color_rgb => { - const rgb = ci.cell.content.color_rgb; - cs.bg = .{ .rgb = .{ rgb.r, rgb.g, rgb.b } }; - }, - else => {}, - }; - return cs; -} - -fn asPardesColor(rgb: GColor.RGB) pardes.Color { - return .{ .rgb = .{ rgb.r, rgb.g, rgb.b } }; -} - -/// A program's colours mapped to the theme (Filter): a terminal's cells, or -/// a +Pager's spans (`vt` null, the program's palette xterm's own). -pub const FilteredColors = struct { - source: GColor.Palette, - target: *const GColor.Palette, - theme_bg: GColor.RGB, - theme_fg: GColor.RGB, - dynamic_bg: ?GColor.RGB, - dynamic_fg: ?GColor.RGB, - default_bg: GColor.RGB, - /// What a foreground too near `default_bg` becomes instead. - fallback_fg: GColor.RGB, - default_bg_luminance: f64, - fg_for_palette: [256]pardes.Color = undefined, - bg_for_palette: [256]pardes.Color = undefined, - /// The two answers for a cell that names no colour of its own. - fg_default: pardes.Color = undefined, - bg_default: pardes.Color = undefined, - cache_rgb: [256]GColor.RGB = undefined, - cache_key: [256]u8 = undefined, - cache_valid: [256]bool = @splat(false), - - pub fn init(p: *Pardes, vt: ?*const ghostty_vt.Terminal) FilteredColors { - var source = GColor.default; - if (vt) |t| { - for (&source, 0..) |*rgb, i| - rgb.* = t.colorForXterm(.{ .palette = @intCast(i) }) orelse rgb.*; - } - const theme = p.theme(); - var theme_bg = asGhostRgb(theme.bg orelse theme.tag_bg); - var theme_fg = asGhostRgb(theme.fg orelse theme.tag_fg); - var dynamic_bg = if (vt) |t| t.colorForXterm(.{ .dynamic = .background }) else null; - var dynamic_fg = if (vt) |t| t.colorForXterm(.{ .dynamic = .foreground }) else null; - if (vt != null and vt.?.modes.get(.reverse_colors)) { - std.mem.swap(GColor.RGB, &theme_bg, &theme_fg); - std.mem.swap(?GColor.RGB, &dynamic_bg, &dynamic_fg); - } - var self: FilteredColors = .{ - .source = source, - .target = p.tty_filter_palette.get(theme), - .theme_bg = theme_bg, - .theme_fg = theme_fg, - .dynamic_bg = dynamic_bg, - .dynamic_fg = dynamic_fg, - .default_bg = theme_bg, - .fallback_fg = theme_fg, - .default_bg_luminance = luminanceOf(theme_bg), - }; - if (dynamic_bg) |rgb| self.default_bg = self.keyedRgb(rgb); - self.default_bg_luminance = luminanceOf(self.default_bg); - if (self.theme_bg.contrast(self.default_bg) > self.theme_fg.contrast(self.default_bg)) - self.fallback_fg = self.theme_bg; - - self.fg_default = asPardesColor(self.legible( - if (self.dynamic_fg) |rgb| self.keyedRgb(rgb) else self.theme_fg, - )); - self.bg_default = asPardesColor(self.default_bg); - for (&self.source, 0..) |current, i| { - const idx: u8 = @intCast(i); - const mapped = self.paletteRgb(idx, current); - self.fg_for_palette[idx] = asPardesColor(self.legible(mapped)); - self.bg_for_palette[idx] = asPardesColor(mapped); - } - return self; - } - - fn fg(self: *FilteredColors, style: ghostty_vt.Style) pardes.Color { - return switch (style.fg_color) { - .none => self.fg_default, - .palette => |idx| self.fg_for_palette[idx], - .rgb => asPardesColor(self.legible(self.keyedRgb(style.fg(.{ - .default = self.dynamic_fg orelse self.theme_fg, - .palette = &self.source, - .bold = null, - })))), - }; - } - - fn bg(self: *FilteredColors, style: ghostty_vt.Style, cell: *const ghostty_vt.Cell) pardes.Color { - switch (cell.content_tag) { - .bg_color_palette => return self.bg_for_palette[cell.content.color_palette.data], - .bg_color_rgb => {}, - else => switch (style.bg_color) { - .none => return self.bg_default, - .palette => |idx| return self.bg_for_palette[idx], - .rgb => {}, - }, - } - // Truecolour, from either the cell or its style. - return asPardesColor(self.keyedRgb(style.bg(cell, &self.source).?)); - } - - /// A +Pager span's colour (pager.zig), 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, - .index => |idx| if (is_bg) self.bg_for_palette[idx] else self.fg_for_palette[idx], - .rgb => |rgb| blk: { - const keyed = self.keyedRgb(asGhostRgb(rgb)); - break :blk asPardesColor(if (is_bg) keyed else self.legible(keyed)); - }, - }; - } - - fn legible(self: *const FilteredColors, rgb: GColor.RGB) GColor.RGB { - if (contrastOf(luminanceOf(rgb), self.default_bg_luminance) >= - config.tty_filter_min_contrast) return rgb; - return self.fallback_fg; - } - - fn paletteRgb(self: *FilteredColors, idx: u8, current: GColor.RGB) GColor.RGB { - if (current.eql(GColor.default[idx])) return self.target[idx]; - return self.keyedRgb(current); - } - - fn keyedRgb(self: *FilteredColors, rgb: GColor.RGB) GColor.RGB { - return self.target[self.nearestKey(rgb)]; - } - - fn nearestKey(self: *FilteredColors, rgb: GColor.RGB) u8 { - const rgb24 = (@as(u32, rgb.r) << 16) | (@as(u32, rgb.g) << 8) | rgb.b; - const slot: u8 = @truncate((rgb24 *% 0x9e3779b1) >> 24); - if (self.cache_valid[slot] and self.cache_rgb[slot].eql(rgb)) - return self.cache_key[slot]; - - var best: u8 = 0; - var best_distance: u32 = std.math.maxInt(u32); - for (GColor.default, 0..) |candidate, i| { - const distance = colorDistance(rgb, candidate); - // Strict comparison makes duplicate-colour ties stable at the - // lowest canonical xterm key. - if (distance < best_distance) { - best_distance = distance; - best = @intCast(i); - } - } - self.cache_rgb[slot] = rgb; - self.cache_key[slot] = best; - self.cache_valid[slot] = true; - return best; - } -}; - -const channel_luminance: [256]f64 = blk: { - @setEvalBranchQuota(20000); - var table: [256]f64 = undefined; - for (&table, 0..) |*slot, c| { - const normalized: f64 = @as(f64, @floatFromInt(c)) / 255; - slot.* = if (normalized <= 0.03928) - normalized / 12.92 - else - std.math.pow(f64, (normalized + 0.055) / 1.055, 2.4); - } - break :blk table; -}; - -fn luminanceOf(rgb: GColor.RGB) f64 { - return 0.2126 * channel_luminance[rgb.r] + - 0.7152 * channel_luminance[rgb.g] + - 0.0722 * channel_luminance[rgb.b]; -} - -/// ghostty's `RGB.contrast` with both luminances already in hand. -fn contrastOf(a_luminance: f64, b_luminance: f64) f64 { - const lighter = @max(a_luminance, b_luminance); - const darker = @min(a_luminance, b_luminance); - return (lighter + 0.05) / (darker + 0.05); -} - -fn colorDistance(a: GColor.RGB, b: GColor.RGB) u32 { - const dr = @as(i32, a.r) - @as(i32, b.r); - const dg = @as(i32, a.g) - @as(i32, b.g); - const db = @as(i32, a.b) - @as(i32, b.b); - return @intCast(dr * dr + dg * dg + db * db); -} - -pub fn palColor(p: *Pardes, idx: u8) pardes.Color { - if (p.theme().palette) |pal| if (idx < 16) return .{ .rgb = pal[idx] }; - return .{ .index = idx }; -} - -fn ghostColor(p: *Pardes, color: ghostty_vt.Style.Color, is_bg: bool) pardes.Color { - return switch (color) { - .none => blk: { - const t = if (is_bg) p.theme().bg else p.theme().fg; - break :blk if (t) |c| .{ .rgb = c } else .default; - }, - .palette => |idx| palColor(p, idx), - .rgb => |rgb| .{ .rgb = .{ rgb.r, rgb.g, rgb.b } }, - }; -} - -/// 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 { - 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 { - 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 { - if (comptime !images_enabled) return null; - const state = pane.terminal orelse return null; - return state.images.petscii; -} - -/// Whether the screen showing holds any kitty graphics image. -pub fn hasImages(pane: *const Pane) bool { - if (comptime !images_enabled) return false; - const state = pane.terminal orelse return false; - return state.vt.screens.active.kitty_images.images.count() > 0; -} - -/// Draw the pane's kitty graphics images over its body rows (after the -/// rows and their colours: placeholder cells are blanked here). -pub fn drawImages(p: *Pardes, s: *Surface, pane: *Pane, id: usize, tx: u16, tw: u16, body_y: u16, body_h: u16) void { - if (comptime !images_enabled) return; - const state = pane.terminal orelse return; - const screen = state.vt.screens.active; - syncPixels(p, pane); - // 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); - @memset(rows_of[0..vp_rows], null); - var any_placeholder = false; - var walk: BodyWalk = .init(pane); - var vr: u16 = 0; - while (walk.next()) |row| : (vr += 1) { - if (vr >= body_h) break; - const vi = switch (row) { - .grid => |v| v, - .edit => continue, - }; - if (vi < 0 or vi >= vp_rows) continue; - const row_pin = screen.pages.pin(.{ .viewport = .{ .y = @intCast(vi) } }) orelse continue; - const flags = row_pin.rowAndCell().row; - // A prompt row outside tty mode is cut or hidden: its columns are - // not the grid's. - if (pane.body.mode != .tty and flags.semantic_prompt != .none) continue; - any_placeholder = any_placeholder or flags.kitty_virtual_placeholder; - rows_of[@intCast(vi)] = vr; - } - // Nothing to draw, no placeholder to blank and nothing cached to let - // go: the common case costs the rows' flags. - if (!any_placeholder and screen.kitty_images.placements.count() == 0 and state.images.converted.count() == 0) return; - state.images.draw(p, s, &state.vt, @intCast(id), pane.serial, tx, body_y, @min(tw, pane.cols), rows_of[0..vp_rows]); -} - -/// Every byte the core wrote to each pane's pty since the last call, `\n` -/// between panes' shares: "0:<bytes>\n1:<bytes>\n" for panes that got any. -fn ptyWritesByPane(p: *Pardes, out: *std.ArrayList(u8)) ![]const u8 { - out.clearRetainingCapacity(); - var per: [pardes.MAX_PANES]std.ArrayList(u8) = @splat(.empty); - defer for (&per) |*b| b.deinit(p.gpa); - while (p.nextEffect()) |effect| { - if (effect == .write) try per[effect.write.pane].appendSlice(p.gpa, effect.write.bytes.slice()); - } - for (per, 0..) |b, id| if (b.items.len > 0) try out.print(p.gpa, "{d}:{s}\n", .{ id, b.items }); - return out.items; -} - -/// `a=T` of a 4x2 RGB image, `i=7`, red on the left half, blue on the -/// right, with the rest of the control data `extra` (`c=2,r=1` places it -/// over two cells). -inline fn kittyTransmit(comptime extra: []const u8) []const u8 { - return comptime blk: { - const row = [_]u8{ 255, 0, 0, 255, 0, 0, 0, 0, 255, 0, 0, 255 }; - const pixels = row ++ row; - var buf: [std.base64.standard.Encoder.calcSize(pixels.len)]u8 = undefined; - const b64 = std.base64.standard.Encoder.encode(&buf, &pixels)[0..buf.len].*; - break :blk "\x1b_Ga=T,f=24,s=4,v=2,i=7," ++ extra ++ ";" ++ b64 ++ "\x1b\\"; - }; -} - -fn imagePlaces(s: *const Surface) []const pardes.Placement { - return s.placements.items; -} - -/// `n` line breaks: enough of them push the screen's rows into history. -fn lineBreaks(comptime n: usize) [2 * n]u8 { - var out: [2 * n]u8 = undefined; - for (0..n) |i| out[2 * i ..][0..2].* = "\r\n".*; - return out; -} - -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); - defer gpa.destroy(pane); - defer deinitEmulator(pane, gpa); - try std.testing.expectEqual(terminal, pane.terminal != null); - } - }; - try std.testing.expect(@sizeOf(Pane) < 128 * 1024); - try std.testing.checkAllAllocationFailures(std.testing.allocator, Case.run, .{false}); - try std.testing.checkAllAllocationFailures(std.testing.allocator, Case.run, .{true}); -} - -test "a terminal made fresh has no size waiting: one never resized keeps its grid when a unit is cut" { - // Fresh memory as a Debug build's allocator hands it out: 0xAA. A field - // `create` left unset read a size of 43690x43690 (fixer 2's, 2026-10-30). - const Filling = struct { - child: std.mem.Allocator, - fn alloc(ctx: *anyopaque, len: usize, a: std.mem.Alignment, ra: usize) ?[*]u8 { - const self: *@This() = @ptrCast(@alignCast(ctx)); - const ptr = self.child.rawAlloc(len, a, ra) orelse return null; - @memset(ptr[0..len], 0xAA); - return ptr; - } - fn resize(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); - } - fn remap(ctx: *anyopaque, buf: []u8, a: std.mem.Alignment, n: usize, ra: usize) ?[*]u8 { - const self: *@This() = @ptrCast(@alignCast(ctx)); - return self.child.rawRemap(buf, a, n, ra); - } - fn free(ctx: *anyopaque, buf: []u8, a: std.mem.Alignment, ra: usize) void { - 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 }; - }; - var filling: Filling = .{ .child = std.testing.allocator }; - const gpa: std.mem.Allocator = .{ .ptr = &filling, .vtable = &Filling.vtable }; - const pane = try create(gpa, 40, 12); - defer gpa.destroy(pane); - defer deinitEmulator(pane, 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); - defer allocator.destroy(pane); - defer deinitEmulator(pane, 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.expect(!failing.has_induced_failure); -} - -test "terminal state keeps parser fragments and sends emulator replies through its owner" { - const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 40, .rows = 12 }); - defer p.deinit(); - while (p.nextEffect()) |_| {} - const pane = p.panes[0].?; - const state = pane.terminal.?; - try std.testing.expect(state.stream.handler.inner.terminal == &state.vt); - p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[" } }); - while (p.nextEffect()) |effect| { - if (effect == .write) return error.PrematureTerminalReply; - } - p.update(.{ .output = .{ .pane = 0, .bytes = "6n" } }); - var replies: 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; - } - try std.testing.expectEqual(@as(usize, 1), replies); - try std.testing.expectEqual(@as(u16, 0), state.reply_len); -} - -test "a terminal's dump restores the cells it drew, its history and where its view was" { - const gpa = std.testing.allocator; - const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 40, .rows = 12 }); - defer p.deinit(); - while (p.nextEffect()) |_| {} - const pane = p.panes[0].?; - feedOutput(p, pane, "\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); - } - scrollGrid(pane, -5); - const bytes = try pardes.walk.save(State, gpa, pane.terminal.?); - defer gpa.free(bytes); - var arena: std.heap.ArenaAllocator = .init(gpa); - defer arena.deinit(); - const state = try gpa.create(State); - defer gpa.destroy(state); - state.* = try pardes.walk.load(State, gpa, bytes, null); - defer { - state.stream.deinit(); - state.vt.deinit(gpa); - } - try std.testing.expectEqual(pardes.walk.digest(State, pane.terminal.?), pardes.walk.digest(State, state)); - try std.testing.expectEqual(pane.terminal.?.vt.screens.active.pages.scrollbar(), state.vt.screens.active.pages.scrollbar()); -} - -test "a restored command pane comes back finished, its command not run again" { - if (comptime pardes.isolated) return error.SkipZigTest; - const gpa = std.testing.allocator; - const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 60, .rows = 16 }); - defer p.deinit(); - while (p.nextEffect()) |_| {} - const cmd = p.freeSlot().?; - _ = try panes.newCommand(p, cmd, "/tmp", "make test"); - feedOutput(p, p.panes[cmd].?, "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.?); - defer restored.deinit(); - var spawns: usize = 0; - while (restored.nextEffect()) |effect| switch (effect) { - .spawn => spawns += 1, - else => {}, - }; - try std.testing.expectEqual(@as(usize, 1), spawns); // the shell, not the command - const again = for (restored.panes) |slot| { - if (slot) |pane| if (pane.command != null) break pane; - } else return error.CommandPaneLost; - 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); - defer gpa.free(text); - try std.testing.expect(std.mem.indexOf(u8, text, "ok") != null); -} - -test "a restored terminal keeps its history above a marker and gets a shell where it was" { - if (comptime pardes.isolated) return error.SkipZigTest; - const gpa = std.testing.allocator; - const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 40, .rows = 12 }); - defer p.deinit(); - while (p.nextEffect()) |_| {} - const pane = p.panes[0].?; - feedOutput(p, pane, "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); - const restored = try pardes.dump.initFromDump(gpa, .{ .tty_only = true, .cols = 40, .rows = 12 }, p.dump_out.?); - defer restored.deinit(); - var spawned = false; - while (restored.nextEffect()) |effect| switch (effect) { - .spawn => |sp| spawned = sp.pane == 0 and std.mem.eql(u8, sp.cwd.slice(), "/tmp"), - else => {}, - }; - try std.testing.expect(spawned); - const again = restored.panes[0].?; - 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); - 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; - try std.testing.expect(old_at < mark_at); -} - -test "a position that cannot follow the output for want of memory is said on the message row, and logged" { - var failing = std.testing.FailingAllocator.init(std.testing.allocator, .{}); - 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"); - // 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"); - 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]); - const logged = p.messages.at(p.messages.len -| 1) orelse return error.NothingLogged; - try std.testing.expectEqualStrings(positions_lost, logged.slice()); -} - -test "raw terminal output needs no position tracking allocations" { - var failing = std.testing.FailingAllocator.init(std.testing.allocator, .{}); - const p = try Pardes.init(failing.allocator(), .{ .tty_only = true, .cols = 80, .rows = 24 }); - defer p.deinit(); - const pane = p.panes[0].?; - pane.body.mode = .tty; - feedOutput(p, pane, "warm"); - const allocations = failing.alloc_index; - failing.fail_index = allocations; - const pins = pane.terminal.?.vt.screens.active.pages.countTrackedPins(); - feedOutput(p, pane, " 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()); -} - -test "rows asked for after a pane's cached rows were dropped, before the sweep, leak nothing" { - const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true }); - defer p.deinit(); - const pane = p.panes[0].?; - try std.testing.expect(pane.terminal != null); - _ = try 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); -} - -test "the luminance table answers exactly what ghostty computes" { - for (0..256) |i| { - const c: u8 = @intCast(i); - const grey: GColor.RGB = .{ .r = c, .g = c, .b = c }; - try std.testing.expectEqual(grey.luminance(), luminanceOf(grey)); - } - // Channel weights are asymmetric, so a grey ramp alone would not catch a - // transposed coefficient. The palette is what the tables enumerate. - for (GColor.default) |candidate| { - try std.testing.expectEqual(candidate.luminance(), luminanceOf(candidate)); - for (GColor.default) |page| { - try std.testing.expectEqual( - candidate.contrast(page), - contrastOf(luminanceOf(candidate), luminanceOf(page)), - ); - } - } -} - -test "terminal Filter keys indexed truecolor OSC and background-only cells through the theme" { - const testing = std.testing; - // Raw index assertions require a theme that inherits the ANSI palette. - const p = try Pardes.init(testing.allocator, .{ .startup_config = "Theme helix\n", .tty_only = true, .cols = 18, .rows = 6 }); - defer p.deinit(); - while (p.nextEffect()) |_| {} - const pane = p.panes[0].?; - pane.tag_expanded = false; // a one-row tag keeps this small screen's rows - p.sync(); - try testing.expect(pane.tty_filter); - pane.tty_filter = false; - - p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[31mA" ++ - "\x1b[38;5;196mB" ++ - "\x1b[38;2;255;0;0mC" ++ - "\x1b[0;48;5;25mD" ++ - "\x1b[0;48;2;0;95;175mE" ++ - "\x1b[0;1;2;3;4;5;7;8;9mF" ++ - "\x1b[0;48;5;25m\x1b[K" ++ - "\r\n\x1b[0;38;5;2m界" } }); - - var frame = std.heap.ArenaAllocator.init(testing.allocator); - defer frame.deinit(); - const r = p.view().rects[0]; - const tx = r.x + config.GUTTER; - const body_y = p.bodyTop(pane, r); - - const raw = try p.render(frame.allocator()); - try testing.expectEqual(pardes.Color{ .index = 1 }, raw.at(tx, body_y).style.fg); - try testing.expectEqual(pardes.Color{ .index = 196 }, raw.at(tx + 1, body_y).style.fg); - try testing.expectEqual(pardes.Color{ .rgb = .{ 255, 0, 0 } }, raw.at(tx + 2, body_y).style.fg); - - pane.tty_filter = true; - _ = frame.reset(.retain_capacity); - const filtered = try p.render(frame.allocator()); - var expected_cache: FilterPalette = .{}; - const expected = expected_cache.get(p.theme()); - try testing.expectEqual(asPardesColor(expected[1]), filtered.at(tx, body_y).style.fg); - try testing.expectEqual(asPardesColor(expected[196]), filtered.at(tx + 1, body_y).style.fg); - try testing.expectEqual(filtered.at(tx + 1, body_y).style.fg, filtered.at(tx + 2, body_y).style.fg); - try testing.expectEqual(asPardesColor(expected[25]), filtered.at(tx + 3, body_y).style.bg); - try testing.expectEqual(filtered.at(tx + 3, body_y).style.bg, filtered.at(tx + 4, body_y).style.bg); - - const attrs = filtered.at(tx + 5, body_y).style; - try testing.expect(attrs.bold); - try testing.expect(attrs.dim); - try testing.expect(attrs.italic); - try testing.expect(attrs.blink); - try testing.expect(attrs.reverse); - try testing.expect(attrs.invisible); - try testing.expect(attrs.strikethrough); - try testing.expectEqual(.single, attrs.ul); - - const erased = pane.terminal.?.vt.screens.active.pages.getCell(.{ .viewport = .{ .x = 6, .y = 0 } }).?; - try testing.expectEqual(.bg_color_palette, erased.cell.content_tag); - try testing.expectEqual(asPardesColor(expected[25]), filtered.at(tx + 6, body_y).style.bg); - try testing.expectEqual(asPardesColor(expected[2]), filtered.at(tx, body_y + 1).style.fg); - try testing.expectEqual(filtered.at(tx, body_y + 1).style, filtered.at(tx + 1, body_y + 1).style); - // A filtered terminal never delegates either colour to a backend palette, - // including cells which were empty/default before the pass. - for (0..r.w - config.GUTTER) |col| { - const cell = filtered.at(tx + @as(u16, @intCast(col)), body_y); - try testing.expect(!cell.default); - switch (cell.style.fg) { - .rgb => {}, - else => return error.FilteredForegroundWasNotRgb, - } - switch (cell.style.bg) { - .rgb => {}, - else => return error.FilteredBackgroundWasNotRgb, - } - } - - p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b]4;1;#ff0000\x1b\\" } }); - const osc_red = pane.terminal.?.vt.colorForXterm(.{ .palette = 1 }).?; - try testing.expect(osc_red.eql(.{ .r = 255, .g = 0, .b = 0 })); - pane.tty_filter = false; - pane.tty_filter = true; - try testing.expect(osc_red.eql(pane.terminal.?.vt.colorForXterm(.{ .palette = 1 }).?)); - _ = frame.reset(.retain_capacity); - const osc_palette = try p.render(frame.allocator()); - try testing.expectEqual(asPardesColor(expected[196]), osc_palette.at(tx, body_y).style.fg); - - // Dynamic default foreground/background colours key every default cell, - // including the otherwise blank end of the row. - p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b]10;#ff0000\x1b\\" ++ - "\x1b]11;#5f5f5f\x1b\\" } }); - const dyn_fg = pane.terminal.?.vt.colorForXterm(.{ .dynamic = .foreground }).?; - const dyn_bg = pane.terminal.?.vt.colorForXterm(.{ .dynamic = .background }).?; - try testing.expect(dyn_fg.eql(.{ .r = 255, .g = 0, .b = 0 })); - 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 explicit_before_reverse = dynamic.at(tx, body_y).style.fg; - try testing.expectEqual(asPardesColor(expected[196]), explicit_before_reverse); - p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[?5h" } }); - _ = frame.reset(.retain_capacity); - const reversed = try p.render(frame.allocator()); - const reversed_blank = reversed.at(tx + r.w - config.GUTTER - 1, body_y + 2).style; - try testing.expectEqual(asPardesColor(expected[59]), reversed_blank.fg); - try testing.expectEqual(asPardesColor(expected[196]), reversed_blank.bg); - const reversed_explicit = reversed.at(tx, body_y).style; - try testing.expectEqual(asPardesColor(expected[196]), reversed_explicit.bg); - try testing.expectEqual(pardes.Color{ .rgb = p.theme().bg.? }, reversed_explicit.fg); - try testing.expect(!std.meta.eql(reversed_explicit.fg, reversed_explicit.bg)); - - p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[?5l" } }); - _ = frame.reset(.retain_capacity); - const unreversed = try p.render(frame.allocator()); - const unreversed_blank = unreversed.at(tx + r.w - config.GUTTER - 1, body_y + 2).style; - try testing.expectEqual(asPardesColor(expected[196]), unreversed_blank.fg); - try testing.expectEqual(asPardesColor(expected[59]), unreversed_blank.bg); - - // The cache is keyed by values, not a theme name. Replacing a custom - // theme in place immediately recolours already-rendered indexed cells. - p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b]104;1\x1b\\" } }); - var custom = p.theme().*; - custom.name = try p.gpa.dupe(u8, "same-name"); - custom.palette = null; - custom.kw = .{ 1, 2, 3 }; - p.custom_theme = custom; - _ = frame.reset(.retain_capacity); - const custom_first = try p.render(frame.allocator()); - try testing.expectEqual(pardes.Color{ .rgb = .{ 1, 2, 3 } }, custom_first.at(tx, body_y).style.fg); - if (p.custom_theme) |*theme| theme.kw = .{ 4, 5, 6 }; - _ = frame.reset(.retain_capacity); - const custom_second = try p.render(frame.allocator()); - try testing.expectEqual(pardes.Color{ .rgb = .{ 4, 5, 6 } }, custom_second.at(tx, body_y).style.fg); -} - -test "terminal Filter keeps extended keys dark-to-light on a light theme" { - const p = try Pardes.init(std.testing.allocator, .{ .startup_config = "Theme acme\n", .tty_only = true }); - defer p.deinit(); - try std.testing.expectEqualStrings("acme", p.theme().name); - var cache: FilterPalette = .{}; - const palette = cache.get(p.theme()); - try std.testing.expect(palette[16].eql(asGhostRgb(p.theme().fg.?))); - try std.testing.expect(palette[231].eql(asGhostRgb(p.theme().bg.?))); -} - -test "terminal Filter preserves exact palette-null light theme default roles" { - const testing = std.testing; - const p = try Pardes.init(testing.allocator, .{ .tty_only = true, .cols = 12, .rows = 5 }); - defer p.deinit(); - while (p.nextEffect()) |_| {} - - var light = p.theme().*; - light.name = try p.gpa.dupe(u8, "filter-light-defaults"); - light.bg = .{ 0xf8, 0xf8, 0xf8 }; - light.fg = .{ 0x38, 0x38, 0x38 }; - light.palette = null; - p.custom_theme = light; - - const pane = p.panes[0].?; - try testing.expectEqual(@as(?GColor.RGB, null), pane.terminal.?.vt.colorForXterm(.{ .dynamic = .foreground })); - try testing.expectEqual(@as(?GColor.RGB, null), pane.terminal.?.vt.colorForXterm(.{ .dynamic = .background })); - pane.tty_filter = true; - - var frame = std.heap.ArenaAllocator.init(testing.allocator); - defer frame.deinit(); - const r = p.view().rects[0]; - const tx = r.x + config.GUTTER; - const body_y = p.bodyTop(pane, r); - const ordinary = try p.render(frame.allocator()); - try testing.expectEqual(pardes.Color{ .rgb = light.fg.? }, ordinary.at(tx, body_y).style.fg); - try testing.expectEqual(pardes.Color{ .rgb = light.bg.? }, ordinary.at(tx, body_y).style.bg); - - p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[?5h" } }); - _ = frame.reset(.retain_capacity); - const reversed = try p.render(frame.allocator()); - try testing.expectEqual(pardes.Color{ .rgb = light.bg.? }, reversed.at(tx, body_y).style.fg); - try testing.expectEqual(pardes.Color{ .rgb = light.fg.? }, reversed.at(tx, body_y).style.bg); -} - -test "terminal Filter maps the default roles before it maps anything else" { - const testing = std.testing; - const p = try Pardes.init(testing.allocator, .{ .tty_only = true, .cols = 18, .rows = 6 }); - defer p.deinit(); - while (p.nextEffect()) |_| {} - const pane = p.panes[0].?; - try testing.expect(pane.tty_filter); - - // Native dark/light palettes plus legacy helix/dark/acme, including - // the null-page fallback that only the legacy dark theme exercises. - for (0..9) |t| { - p.settings.theme = @intCast(t); - const stage_one = FilteredColors.init(p, &pane.terminal.?.vt); - // `dark` declares no background of its own, which is exactly why the - // resolver reads the tag colours as the fallback rather than `.?`. - const theme = p.theme(); - try testing.expect(stage_one.theme_bg.eql(asGhostRgb(theme.bg orelse theme.tag_bg))); - try testing.expect(stage_one.theme_fg.eql(asGhostRgb(theme.fg orelse theme.tag_fg))); - // With no OSC 11 in play the mapped page IS that anchor, and the - // fallback is the other one: a background never contrasts with itself. - try testing.expect(stage_one.default_bg.eql(stage_one.theme_bg)); - try testing.expect(stage_one.fallback_fg.eql(stage_one.theme_fg)); - } - - p.settings.theme = 0; - p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b]11;#5f5f5f\x1b\\" } }); - var moved = FilteredColors.init(p, &pane.terminal.?.vt); - try testing.expect(!moved.default_bg.eql(moved.theme_bg)); - try testing.expect(moved.default_bg.eql(moved.keyedRgb(.{ .r = 0x5f, .g = 0x5f, .b = 0x5f }))); -} - -test "terminal Filter refuses a foreground that would collapse onto the page" { - const testing = std.testing; - const p = try Pardes.init(testing.allocator, .{ .tty_only = true, .cols = 18, .rows = 6 }); - defer p.deinit(); - while (p.nextEffect()) |_| {} - const pane = p.panes[0].?; - try testing.expect(pane.tty_filter); - - p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[38;2;255;255;255mW" ++ - "\x1b[0;30mB" ++ - "\x1b[0;31mR" } }); - - var frame = std.heap.ArenaAllocator.init(testing.allocator); - defer frame.deinit(); - const r = p.view().rects[0]; - const tx = r.x + config.GUTTER; - const body_y = p.bodyTop(pane, r); - - for (0..9) |t| { - p.settings.theme = @intCast(t); - var fc = FilteredColors.init(p, &pane.terminal.?.vt); - const page = asPardesColor(fc.default_bg); - const rescued = asPardesColor(fc.fallback_fg); - _ = frame.reset(.retain_capacity); - const g = try p.render(frame.allocator()); - - // The colour each of the three would have been given with no floor. - const raw_white = fc.keyedRgb(.{ .r = 255, .g = 255, .b = 255 }); - const raw_black = fc.paletteRgb(0, GColor.default[0]); - const raw_red = fc.paletteRgb(1, GColor.default[1]); - - for ([_]struct { at: u16, raw: GColor.RGB }{ - .{ .at = 0, .raw = raw_white }, - .{ .at = 1, .raw = raw_black }, - .{ .at = 2, .raw = raw_red }, - }) |case| { - const cell = g.at(tx + case.at, body_y).style; - try testing.expectEqual(page, cell.bg); - if (case.raw.contrast(fc.default_bg) < config.tty_filter_min_contrast) { - // Refused: the projection's answer is not painted, the anchor is. - try testing.expectEqual(rescued, cell.fg); - try testing.expect(!std.meta.eql(cell.fg, cell.bg)); - } else { - // Cleared the floor, so stage two leaves it exactly alone. - try testing.expectEqual(asPardesColor(case.raw), cell.fg); - } - // Either way a filtered cell delegates neither colour to a backend. - switch (cell.fg) { - .rgb => |ink| try testing.expect(asGhostRgb(ink).contrast(fc.default_bg) >= - config.tty_filter_min_contrast), - else => return error.FilteredForegroundWasNotRgb, - } - } - - // At least one of the three has to have been a real collapse, or this - // theme proved nothing: white on the light theme, black on the dark. - try testing.expect(raw_white.contrast(fc.default_bg) < config.tty_filter_min_contrast or - raw_black.contrast(fc.default_bg) < config.tty_filter_min_contrast); - // A saturated red is never the page on any curated theme. - try testing.expect(raw_red.contrast(fc.default_bg) >= config.tty_filter_min_contrast); - } -} - -test "terminal Filter holds every projected foreground off the page" { - const testing = std.testing; - const p = try Pardes.init(testing.allocator, .{ .tty_only = true, .cols = 18, .rows = 6 }); - defer p.deinit(); - while (p.nextEffect()) |_| {} - const pane = p.panes[0].?; - - for (0..9) |t| { - p.settings.theme = @intCast(t); - var fc = FilteredColors.init(p, &pane.terminal.?.vt); - var refused: usize = 0; - for (fc.target, 0..) |projected, key| { - const ink = fc.legible(projected); - try testing.expect(ink.contrast(fc.default_bg) >= config.tty_filter_min_contrast); - if (!ink.eql(projected)) { - refused += 1; - try testing.expect(ink.eql(fc.fallback_fg)); - // Only ever refused for being too near the page. - try testing.expect(projected.contrast(fc.default_bg) < config.tty_filter_min_contrast); - } - // 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])])); - } - // Every curated theme owns at least one collapsing key — that is why - // the floor exists — and the floor must not be flattening the palette. - try testing.expect(refused > 0); - try testing.expect(refused < fc.target.len / 8); - } -} - -test "tty ansi colors follow the prompt hug into normal mode" { - const testing = std.testing; - const p = try Pardes.init(testing.allocator, .{ .tty_only = true, .cols = 18, .rows = 6 }); - defer p.deinit(); - while (p.nextEffect()) |_| {} - const pane = p.panes[0].?; - pane.tty_filter = false; - - p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b]133;A\x1b\\\x1b[32mPP\x1b]133;B\x1b\\\x1b[31mR\x1b[34mB\x1b[0m out" } }); - - var frame = std.heap.ArenaAllocator.init(testing.allocator); - defer frame.deinit(); - const r = p.view().rects[0]; - const tx = r.x + config.GUTTER; - const body_y = p.bodyTop(pane, r); - const red: pardes.Color = .{ .rgb = p.theme().palette.?[1] }; - const blue: pardes.Color = .{ .rgb = p.theme().palette.?[4] }; - - // tty mode projects the emulator's ansi colours cell for cell. - pane.body.mode = .tty; - p.shell_rows.stale = true; - const tty = try p.render(frame.allocator()); - try testing.expectEqual(red, tty.at(tx + 2, body_y).style.fg); - try testing.expectEqual(blue, tty.at(tx + 3, body_y).style.fg); - - pane.body.mode = .normal; - p.shell_rows.stale = true; - _ = frame.reset(.retain_capacity); - const norm = try p.render(frame.allocator()); - try testing.expectEqualStrings("R", norm.at(tx, body_y).grapheme()); - try testing.expectEqualStrings("B", norm.at(tx + 1, body_y).grapheme()); - try testing.expectEqual(red, norm.at(tx, body_y).style.fg); - try testing.expectEqual(blue, norm.at(tx + 1, body_y).style.fg); -} - -test "a prompt row hidden end to end paints nothing at all" { - const testing = std.testing; - const p = try Pardes.init(testing.allocator, .{ .tty_only = true, .cols = 12, .rows = 8 }); - defer p.deinit(); - while (p.nextEffect()) |_| {} - const pane = p.panes[0].?; - pane.tag_expanded = false; // a 12x8 screen: the body, not the tag - p.sync(); - pane.tty_filter = false; - pane.body.mode = .normal; - p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b]133;A\x1b\\\x1b[32maaaaaaaaa\x1b]133;B\x1b\\\x1b[41;36m\u{754C}\x1b[0m\r\n" } }); - - var frame = std.heap.ArenaAllocator.init(testing.allocator); - defer frame.deinit(); - const r = p.view().rects[0]; - const tx = r.x + config.GUTTER; - const body_y = p.bodyTop(pane, r); - p.shell_rows.stale = true; - const s = try p.render(frame.allocator()); - - try testing.expectEqualStrings(" ", s.at(tx, body_y).grapheme()); - try testing.expect(!std.meta.eql(pardes.Color{ .rgb = p.theme().palette.?[1] }, s.at(tx, body_y).style.bg)); -} - -test "a program that asked for focus reports hears CSI I and CSI O as its pane takes and gives up the keyboard, and as the window does" { - const gpa = std.testing.allocator; - const p = try Pardes.init(gpa, .{ .cols = 90, .rows = 30, .shells = 3 }); - defer p.deinit(); - var frame = std.heap.ArenaAllocator.init(gpa); - defer frame.deinit(); - _ = try p.render(frame.allocator()); - var out: std.ArrayList(u8) = .empty; - defer out.deinit(gpa); - _ = try ptyWritesByPane(p, &out); - p.view().active = 0; - // Asking while its pane has the keyboard: told at once that it has. - p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[?1004h" } }); - try std.testing.expectEqualStrings("0:\x1b[I\n", try ptyWritesByPane(p, &out)); - p.update(.{ .output = .{ .pane = 1, .bytes = "\x1b[?1004h" } }); - try std.testing.expectEqualStrings("", try ptyWritesByPane(p, &out)); - // A click into the other pane moves the keyboard: out of one, into the - // other. - const r = p.view().rects[1]; - const at_col = r.x + config.GUTTER + 2; - const at_row = p.bodyTop(p.panes[1].?, r) + 1; - p.update(.{ .mouse = .{ .button = .left, .kind = .press, .col = at_col, .row = at_row } }); - p.update(.{ .mouse = .{ .button = .left, .kind = .release, .col = at_col, .row = at_row } }); - try std.testing.expectEqual(@as(usize, 1), p.view().active); - try std.testing.expectEqualStrings("0:\x1b[O\n1:\x1b[I\n", try ptyWritesByPane(p, &out)); - // The window: away and back. - p.update(.{ .focus = false }); - try std.testing.expectEqualStrings("1:\x1b[O\n", try ptyWritesByPane(p, &out)); - p.update(.{ .focus = false }); - try std.testing.expectEqualStrings("", try ptyWritesByPane(p, &out)); - p.update(.{ .focus = true }); - try std.testing.expectEqualStrings("1:\x1b[I\n", try ptyWritesByPane(p, &out)); - // A program that did not ask hears nothing: pane 2. - p.view().active = 2; - p.update(.tick); - try std.testing.expectEqualStrings("1:\x1b[O\n", try ptyWritesByPane(p, &out)); -} - -test "a terminal's kitty graphics image is drawn where its program placed it, and a delete takes it away" { - if (comptime !images_enabled) return error.SkipZigTest; - const gpa = std.testing.allocator; - const p = try Pardes.init(gpa, .{ .cols = 80, .rows = 24, .shells = 1 }); - defer p.deinit(); - p.view().frontend.native_images = true; - p.view().active = 0; - p.update(.{ .resize = .{ .cols = 80, .rows = 24, .cell_pixels = .{ .w = 10, .h = 20 } } }); - var frame = std.heap.ArenaAllocator.init(gpa); - defer frame.deinit(); - const pane = p.panes[0].?; - pane.body.mode = .tty; - p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[3;5H" ++ kittyTransmit("c=2,r=1") } }); - var s = try p.render(frame.allocator()); - const places = imagePlaces(s); - try std.testing.expectEqual(@as(usize, 1), places.len); - const place = places[0]; - const r = p.view().rects[0]; - const img = pane.terminal.?.vt.screens.active.kitty_images.imageById(7).?; - try std.testing.expectEqual(pardes.Placement.keyOf(pane.serial, 7, @truncate(img.generation)), place.key); - try std.testing.expectEqual(pardes.RectCell{ .x = r.x + config.GUTTER + 4, .y = p.bodyTop(pane, r) + 2, .w = 2, .h = 1 }, place.dst); - try std.testing.expectEqual(@as(u32, 4), place.raster.w); - try std.testing.expectEqual(@as(u32, 2), place.raster.h); - try std.testing.expectEqualSlices(u8, &.{ 255, 0, 0, 255 }, place.raster.bytes()[0..4]); - try std.testing.expectEqual(pardes.RectPx{ .x = 0, .y = 0, .w = 4, .h = 2 }, place.src); - try std.testing.expectEqual(pardes.RectPx{ .x = 0, .y = 0, .w = 20, .h = 20 }, place.at.?); - - // Scrolled up by the shell's output, it goes up with the text. - p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[24;1H\n\n" } }); - _ = frame.reset(.retain_capacity); - s = try p.render(frame.allocator()); - try std.testing.expectEqual(p.bodyTop(pane, r), imagePlaces(s)[0].dst.y); - p.update(.{ .output = .{ .pane = 0, .bytes = "\n" } }); - _ = frame.reset(.retain_capacity); - s = try p.render(frame.allocator()); - try std.testing.expectEqual(@as(usize, 0), imagePlaces(s).len); - - p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[1;1H" ++ kittyTransmit("c=2,r=1") } }); - _ = frame.reset(.retain_capacity); - s = try p.render(frame.allocator()); - try std.testing.expectEqual(@as(usize, 1), imagePlaces(s).len); - p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b_Ga=d,d=A\x1b\\" } }); - _ = frame.reset(.retain_capacity); - s = try p.render(frame.allocator()); - try std.testing.expectEqual(@as(usize, 0), imagePlaces(s).len); -} - -test "ED 3 takes away a kitty placement whose row it erased: it never comes back at the top" { - if (comptime !images_enabled) return error.SkipZigTest; - const gpa = std.testing.allocator; - const p = try Pardes.init(gpa, .{ .cols = 80, .rows = 24, .shells = 1 }); - defer p.deinit(); - p.view().frontend.native_images = true; - p.update(.{ .resize = .{ .cols = 80, .rows = 24, .cell_pixels = .{ .w = 10, .h = 20 } } }); - var frame = std.heap.ArenaAllocator.init(gpa); - defer frame.deinit(); - const pane = p.panes[0].?; - pane.body.mode = .tty; - p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[1;1H" ++ kittyTransmit("c=2,r=1") } }); - const storage = &pane.terminal.?.vt.screens.active.kitty_images; - try std.testing.expectEqual(@as(usize, 1), storage.placements.count()); - // Scrolled into the history, it is not on screen; `clear` (ED 2 then - // ED 3) erases that history and the placement with it. - p.update(.{ .output = .{ .pane = 0, .bytes = &lineBreaks(40) } }); - var s = try p.render(frame.allocator()); - try std.testing.expectEqual(@as(usize, 0), imagePlaces(s).len); - p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[H\x1b[2J\x1b[3J" } }); - try std.testing.expectEqual(@as(usize, 0), storage.placements.count()); - _ = frame.reset(.retain_capacity); - s = try p.render(frame.allocator()); - try std.testing.expectEqual(@as(usize, 0), imagePlaces(s).len); -} - -test "a finished command's output erased by a later ED 3 is not called whole, and no rows stand in for it" { - const gpa = std.testing.allocator; - 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); - defer gpa.free(before.text); - try std.testing.expect(before.whole); - try std.testing.expect(std.mem.startsWith(u8, before.text, "printed")); - // The command's rows go into the history, and ED 3 erases them: its - // pins are `garbage` now (ghostty 1.4), not moved to the screen's top, - // 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); - defer gpa.free(after.text); - try std.testing.expect(!after.whole); - try std.testing.expectEqualStrings("", after.text); -} - -test "a selection whose row ED 3 erased goes; one on the screen stays" { - const gpa = std.testing.allocator; - for ([_]bool{ true, false }) |in_history| { - const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 40, .rows = 6 }); - defer p.deinit(); - const pane = p.panes[0].?; - pane.body.mode = .tty; - p.update(.{ .output = .{ .pane = 0, .bytes = &lineBreaks(20) } }); - pane.body.mode = .normal; - const pages = &pane.terminal.?.vt.screens.active.pages; - const top: i32 = @intCast(pages.total_rows - pane.rows); - const row: i32 = if (in_history) top - 3 else top + 2; - pane.body.vsel = .{ .active = true, .row = row, .col = 1 }; - p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[3J" } }); - try std.testing.expectEqual(!in_history, pane.body.vsel.active); - if (!in_history) try std.testing.expectEqual(@as(i32, 2), pane.body.vsel.row); - } -} - -test "a virtual kitty placement shows through its placeholder cells, which draw no text" { - if (comptime !images_enabled) return error.SkipZigTest; - const gpa = std.testing.allocator; - const p = try Pardes.init(gpa, .{ .cols = 80, .rows = 24, .shells = 1 }); - defer p.deinit(); - p.view().frontend.native_images = true; - p.update(.{ .resize = .{ .cols = 80, .rows = 24, .cell_pixels = .{ .w = 10, .h = 20 } } }); - var frame = std.heap.ArenaAllocator.init(gpa); - defer frame.deinit(); - const pane = p.panes[0].?; - pane.body.mode = .tty; - // yazi's way: a virtual placement two cells by one, then the two - // placeholders, the image's id in their colour, row and column in - // their diacritics. - p.update(.{ .output = .{ .pane = 0, .bytes = kittyTransmit("U=1,c=2,r=1,q=2") ++ - "\x1b[2;3H\x1b[38;2;0;0;7m\u{10EEEE}\u{0305}\u{0305}\u{10EEEE}\u{0305}\u{030D}\x1b[39mX" } }); - const s = try p.render(frame.allocator()); - const places = imagePlaces(s); - try std.testing.expectEqual(@as(usize, 1), places.len); - const r = p.view().rects[0]; - const tx = r.x + config.GUTTER; - const y = p.bodyTop(pane, r) + 1; - try std.testing.expectEqual(pardes.RectCell{ .x = tx + 2, .y = y, .w = 2, .h = 1 }, places[0].dst); - try std.testing.expectEqualStrings(" ", s.at(tx + 2, y).grapheme()); - try std.testing.expectEqualStrings(" ", s.at(tx + 3, y).grapheme()); - try std.testing.expectEqualStrings("X", s.at(tx + 4, y).grapheme()); -} - -test "a terminal's image is a placement whatever the frontend draws, and the Petscii builtin asks for it as glyph art" { - if (comptime !images_enabled) return error.SkipZigTest; - const gpa = std.testing.allocator; - const p = try Pardes.init(gpa, .{ .cols = 80, .rows = 24, .shells = 1 }); - defer p.deinit(); - p.update(.{ .resize = .{ .cols = 80, .rows = 24, .cell_pixels = .{ .w = 10, .h = 20 } } }); - var frame = std.heap.ArenaAllocator.init(gpa); - defer frame.deinit(); - const pane = p.panes[0].?; - pane.body.mode = .tty; - p.update(.{ .output = .{ .pane = 0, .bytes = kittyTransmit("c=2,r=1") } }); - const r = p.view().rects[0]; - const tx = r.x + config.GUTTER; - const y = p.bodyTop(pane, r); - - // A frontend that draws no pixels (a tty under no kitty graphics) is - // handed the picture all the same, and the cells under it are its. - p.view().frontend.native_images = false; - var s = try p.render(frame.allocator()); - try std.testing.expectEqual(@as(usize, 1), imagePlaces(s).len); - try std.testing.expect(!imagePlaces(s)[0].art.glyph); - try std.testing.expectEqualStrings(" ", s.at(tx, y).grapheme()); - try std.testing.expectEqualStrings(" ", s.at(tx + 1, y).grapheme()); - // The tag says what that frontend draws, glyph art, as an image pane's does. - try std.testing.expect(std.mem.indexOf(u8, try tagline.tagPrefix(p, pane), " petscii:on") != null); - - // The builtin flips the pane to glyph art and back. - p.view().frontend.native_images = true; - try std.testing.expect(p.executeBuiltinLine(0, "Petscii")); - _ = frame.reset(.retain_capacity); - s = try p.render(frame.allocator()); - try std.testing.expectEqual(@as(usize, 1), imagePlaces(s).len); - try std.testing.expect(imagePlaces(s)[0].art.glyph); - try std.testing.expect(std.mem.indexOf(u8, try tagline.tagPrefix(p, pane), " petscii:on") != null); - // Dumped and restored, it still asks for glyph art. - 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.expect(p.executeBuiltinLine(0, "Petscii")); - _ = frame.reset(.retain_capacity); - s = try p.render(frame.allocator()); - try std.testing.expect(!imagePlaces(s)[0].art.glyph); -} - -test "a new terminal draws its program's images as pixels, and one without images says nothing of them" { - if (comptime !images_enabled) return error.SkipZigTest; - 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].?).?); - // 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).?); -} - -test "a program asking the cell size in pixels (CSI 16 t) is told the shell's" { - if (comptime !images_enabled) return error.SkipZigTest; - const gpa = std.testing.allocator; - const p = try Pardes.init(gpa, .{ .cols = 80, .rows = 24, .shells = 1 }); - defer p.deinit(); - p.update(.{ .resize = .{ .cols = 80, .rows = 24, .cell_pixels = .{ .w = 10, .h = 20 } } }); - var out: std.ArrayList(u8) = .empty; - defer out.deinit(gpa); - _ = try ptyWritesByPane(p, &out); - p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[16t" } }); - try std.testing.expectEqualStrings("0:\x1b[6;20;10t\n", try ptyWritesByPane(p, &out)); -} diff --git a/src/tui/tui.zig b/src/tui/tui.zig index 0daac14b..ce2dc84a 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; @@ -1311,6 +1311,7 @@ const Shell = struct { .set_clipboard = setClipboard, .read_clipboard = readClipboard, .open_link = openLink, + .start = host_io.startDetached, .lsp = lsp, .pipe = pipe, .search = search, @@ -2983,7 +2984,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); diff --git a/src/views.zig b/src/views.zig index 953b39a4..3cdbc8aa 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]); }; } @@ -642,6 +642,7 @@ test "registers are the session's: yanked in one view, put in another" { } test "a terminal shown at two sizes takes the size of the view that typed into it last" { + if (pardes.Term.ops == null) return error.SkipZigTest; // a shell const gpa = testing.allocator; const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24 }); defer p.deinit(); @@ -837,6 +838,7 @@ test "a view not live keeps its place in a text another view edits" { } test "a terminal shown in a view shorter than it keeps its cursor in sight" { + if (pardes.Term.ops == null) return error.SkipZigTest; // a shell const gpa = testing.allocator; const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 20 }); defer p.deinit(); diff --git a/src/walk.zig b/src/walk.zig index 3641d327..0f181cfa 100644 --- a/src/walk.zig +++ b/src/walk.zig @@ -367,7 +367,7 @@ pub fn shape(comptime types: []const type) []const u8 { comptime { @setEvalBranchQuota(10_000_000); var out: []const u8 = ""; - for (types) |T| out = out ++ shapeOf(T, 0) ++ "\n"; + for (types) |T| out = out ++ (shapeOf(T, 0) ++ "\n"); return out; } } @@ -378,15 +378,15 @@ fn shapeOf(comptime T: type, comptime depth: u8) []const u8 { return switch (@typeInfo(T)) { .void, .null, .undefined => "v", .bool => "b", - .int => |i| std.fmt.comptimePrint("{t}{d}", .{ i.signedness, i.bits }), - .float => |f| std.fmt.comptimePrint("f{d}", .{f.bits}), + .int => |i| @tagName(i.signedness) ++ decimal(i.bits), + .float => |f| "f" ++ decimal(f.bits), .@"enum" => |e| blk: { var out: []const u8 = shapeOf(e.tag_type, depth + 1) ++ "{"; - for (e.field_names, e.field_values) |n, v| out = out ++ std.fmt.comptimePrint("{s}={d},", .{ n, v }); + for (e.field_names, e.field_values) |n, v| out = out ++ (n ++ "=" ++ decimal(v) ++ ","); break :blk out ++ "}"; }, .optional => |o| if (machinery(o.child)) "0" else "?" ++ shapeOf(o.child, depth + 1), - .array => |a| std.fmt.comptimePrint("[{d}]", .{a.len}) ++ shapeOf(a.child, depth + 1), + .array => |a| "[" ++ decimal(a.len) ++ "]" ++ shapeOf(a.child, depth + 1), .pointer => |p| switch (p.size) { .one => shapeOf(p.child, depth + 1), .slice => "[]" ++ shapeOf(p.child, depth + 1), @@ -397,13 +397,13 @@ fn shapeOf(comptime T: type, comptime depth: u8) []const u8 { var out: []const u8 = if (s.layout == .@"packed") "p{" else "{"; for (s.field_names, s.field_types, s.field_attrs) |name, F, attr| { if (attr.@"comptime" or excluded(T, name)) continue; - out = out ++ name ++ ":" ++ shapeOf(F, depth + 1) ++ ","; + out = out ++ (name ++ ":" ++ shapeOf(F, depth + 1) ++ ","); } break :blk out ++ "}"; }, .@"union" => |u| blk: { var out: []const u8 = shapeOf(u.tag_type.?, depth + 1) ++ "("; - for (u.field_names, u.field_types) |name, F| out = out ++ name ++ ":" ++ shapeOf(F, depth + 1) ++ ","; + for (u.field_names, u.field_types) |name, F| out = out ++ (name ++ ":" ++ shapeOf(F, depth + 1) ++ ","); break :blk out ++ ")"; }, .error_set => "error", @@ -413,6 +413,15 @@ fn shapeOf(comptime T: type, comptime depth: u8) []const u8 { } } +/// `n` in decimal, as `{d}` writes it: memoized, where comptimePrint (an +/// inline function) formats again at every call, 5e6 of the compiler's +/// instructions each. +fn decimal(comptime n: comptime_int) []const u8 { + if (n < 0) return "-" ++ decimal(-n); + if (n < 10) return &.{'0' + n}; + return decimal(n / 10) ++ &[_]u8{'0' + n % 10}; +} + /// An error by its name. An `anyerror` must be one `decode` can read back /// (`errorNamed`): a Debug build stops at one that is not, as it is taped. fn encodeError(comptime E: type, err: E, w: *std.Io.Writer) std.Io.Writer.Error!void { @@ -1006,540 +1015,555 @@ const SrcType = struct { }; const SrcField = struct { name: []const u8, ty: u32 = 0, value: i128 = 0 }; -/// Reads a dump of `roots`, one `into` or `get` each in order. +/// Reads a dump of `roots`, one `into` or `get` each in order: a `Loader` +/// told this build's table of them. pub fn Load(comptime roots: []const type) type { return struct { - const Self = @This(); - const types = graph(roots); + pub fn init(gpa: std.mem.Allocator, bytes: []const u8) DecodeError!Loader { + return Loader.init(gpa, bytes, tableOf(graph(roots))); + } + }; +} - /// Where what is read is made (a `replica.alloc` field's own - /// allocator while it is read). - gpa: std.mem.Allocator, - /// The loader's own lists'. - own: std.mem.Allocator, - bytes: []const u8, - at: usize = 0, - arena: std.heap.ArenaAllocator, - src: []SrcType = &.{}, - /// Its table is this build's: no name is asked. - same: bool = false, - /// Each pointer and slice made so far: what a reference finds, and - /// what `rollback` frees. - shared: std.ArrayList(Made) = .empty, - /// What a type's `dumpRead` made, freed by its `dumpFree` too. - customs: std.ArrayList(struct { ptr: *anyopaque, gpa: std.mem.Allocator, free: *const fn (*anyopaque, std.mem.Allocator) void }) = .empty, - /// What was let go, for the person whose session it is. - notes: std.ArrayList(u8) = .empty, - /// The field being read, for a note. - field: []const u8 = "", - /// Where a field's annotation (`replica.alloc`) says its values are - /// made instead of `gpa`. - allocs: Allocators = .{}, +/// `Load`'s reader, one for every root set: it reads by the dump's own +/// table, and this build's (`table`) only says whether the two are one. +pub const Loader = struct { + const Self = @This(); - pub fn init(gpa: std.mem.Allocator, bytes: []const u8) DecodeError!Self { - var l: Self = .{ .gpa = gpa, .own = gpa, .bytes = bytes, .arena = .init(gpa) }; - errdefer l.arena.deinit(); - if (!std.mem.startsWith(u8, bytes, dump_magic)) return error.BadDump; - l.at = dump_magic.len; - const table_at = l.at; - try l.readTable(); - l.same = std.mem.eql(u8, tableOf(types), bytes[table_at..l.at]); - return l; - } + /// Where what is read is made (a `replica.alloc` field's own + /// allocator while it is read). + gpa: std.mem.Allocator, + /// The loader's own lists'. + own: std.mem.Allocator, + bytes: []const u8, + at: usize = 0, + arena: std.heap.ArenaAllocator, + src: []SrcType = &.{}, + /// Its table is this build's: no name is asked. + same: bool = false, + /// Each pointer and slice made so far: what a reference finds, and + /// what `rollback` frees. + shared: std.ArrayList(Made) = .empty, + /// What a type's `dumpRead` made, freed by its `dumpFree` too. + customs: std.ArrayList(struct { ptr: *anyopaque, gpa: std.mem.Allocator, free: *const fn (*anyopaque, std.mem.Allocator) void }) = .empty, + /// What was let go, for the person whose session it is. + notes: std.ArrayList(u8) = .empty, + /// The field being read, for a note. + field: []const u8 = "", + /// Where a field's annotation (`replica.alloc`) says its values are + /// made instead of `gpa`. + allocs: Allocators = .{}, - pub fn deinit(l: *Self) void { - l.shared.deinit(l.own); - l.customs.deinit(l.own); - l.notes.deinit(l.own); - l.arena.deinit(); - } + pub fn init(gpa: std.mem.Allocator, bytes: []const u8, table: []const u8) DecodeError!Self { + var l: Self = .{ .gpa = gpa, .own = gpa, .bytes = bytes, .arena = .init(gpa) }; + errdefer l.arena.deinit(); + if (!std.mem.startsWith(u8, bytes, dump_magic)) return error.BadDump; + l.at = dump_magic.len; + const table_at = l.at; + try l.readTable(); + l.same = std.mem.eql(u8, table, bytes[table_at..l.at]); + return l; + } - /// Everything read so far freed: a load that fails leaves nothing. - /// What it was read into must not be used after (nor freed). - pub fn rollback(l: *Self) void { - for (l.customs.items) |c| c.free(c.ptr, c.gpa); - for (l.shared.items) |m| if (m.bytes.len > 0) m.gpa.rawFree(m.bytes, m.alignment, @returnAddress()); - l.customs.clearRetainingCapacity(); - l.shared.clearRetainingCapacity(); - } + pub fn deinit(l: *Self) void { + l.shared.deinit(l.own); + l.customs.deinit(l.own); + l.notes.deinit(l.own); + l.arena.deinit(); + } - fn made(l: *Self, bytes: []u8, alignment: std.mem.Alignment) DecodeError!usize { - try l.shared.append(l.own, .{ .bytes = bytes, .alignment = alignment, .gpa = l.gpa }); - return l.shared.items.len - 1; - } + /// Everything read so far freed: a load that fails leaves nothing. + /// What it was read into must not be used after (nor freed). + pub fn rollback(l: *Self) void { + for (l.customs.items) |c| c.free(c.ptr, c.gpa); + for (l.shared.items) |m| if (m.bytes.len > 0) m.gpa.rawFree(m.bytes, m.alignment, @returnAddress()); + l.customs.clearRetainingCapacity(); + l.shared.clearRetainingCapacity(); + } - fn take(l: *Self, n: usize) DecodeError![]const u8 { - if (l.bytes.len - l.at < n) return error.EndOfDump; - defer l.at += n; - return l.bytes[l.at..][0..n]; - } + fn made(l: *Self, bytes: []u8, alignment: std.mem.Alignment) DecodeError!usize { + try l.shared.append(l.own, .{ .bytes = bytes, .alignment = alignment, .gpa = l.gpa }); + return l.shared.items.len - 1; + } - fn scalar(l: *Self, comptime T: type) DecodeError!T { - return std.mem.bytesToValue(T, try l.take(@sizeOf(T))); - } + fn take(l: *Self, n: usize) DecodeError![]const u8 { + if (l.bytes.len - l.at < n) return error.EndOfDump; + defer l.at += n; + return l.bytes[l.at..][0..n]; + } - /// A count, as this machine counts (a wasm32 one has 32 bits). - fn count(l: *Self) DecodeError!usize { - return countOf(try l.scalar(u64)); - } + fn scalar(l: *Self, comptime T: type) DecodeError!T { + return std.mem.bytesToValue(T, try l.take(@sizeOf(T))); + } - fn name(l: *Self) DecodeError![]const u8 { - return l.take(try l.scalar(u16)); - } + /// A count, as this machine counts (a wasm32 one has 32 bits). + fn count(l: *Self) DecodeError!usize { + return countOf(try l.scalar(u64)); + } - fn readTable(l: *Self) DecodeError!void { - const a = l.arena.allocator(); - const n = try l.scalar(u32); - if (n > l.bytes.len) return error.BadDump; - l.src = try a.alloc(SrcType, n); - for (l.src) |*t| { - const k = std.enums.fromInt(Kind, (try l.take(1))[0]) orelse return error.BadDump; - t.* = .{ .kind = k }; - switch (k) { - .int => { - t.signed = (try l.take(1))[0] != 0; - t.bits = try l.scalar(u16); - }, - .float => t.bits = try l.scalar(u16), - .@"enum" => { - t.signed = (try l.take(1))[0] != 0; - t.bits = try l.scalar(u16); - const list = try a.alloc(SrcField, try l.scalar(u32)); - for (list) |*f| f.* = .{ .name = try l.name(), .value = try l.scalar(i128) }; - t.fields = list; - }, - .array => { - t.len = try l.scalar(u64); - t.child = try l.scalar(u32); - }, - .optional, .one, .slice, .prefix, .error_union => t.child = try l.scalar(u32), - .@"struct", .@"union" => { - const nfields = try l.scalar(u32); - if (nfields > l.bytes.len) return error.BadDump; - const list = try a.alloc(SrcField, nfields); - for (list) |*f| f.* = .{ .name = try l.name(), .ty = try l.scalar(u32) }; - t.fields = list; - }, - .custom => _ = try l.name(), - .skip, .void, .bool, .err, .bitset => {}, - } - } - for (l.src) |t| { - if (t.child >= n) return error.BadDump; - for (t.fields) |f| if (f.ty >= n) return error.BadDump; + fn name(l: *Self) DecodeError![]const u8 { + return l.take(try l.scalar(u16)); + } + + fn readTable(l: *Self) DecodeError!void { + const a = l.arena.allocator(); + const n = try l.scalar(u32); + if (n > l.bytes.len) return error.BadDump; + l.src = try a.alloc(SrcType, n); + for (l.src) |*t| { + const k = std.enums.fromInt(Kind, (try l.take(1))[0]) orelse return error.BadDump; + t.* = .{ .kind = k }; + switch (k) { + .int => { + t.signed = (try l.take(1))[0] != 0; + t.bits = try l.scalar(u16); + }, + .float => t.bits = try l.scalar(u16), + .@"enum" => { + t.signed = (try l.take(1))[0] != 0; + t.bits = try l.scalar(u16); + const list = try a.alloc(SrcField, try l.scalar(u32)); + for (list) |*f| f.* = .{ .name = try l.name(), .value = try l.scalar(i128) }; + t.fields = list; + }, + .array => { + t.len = try l.scalar(u64); + t.child = try l.scalar(u32); + }, + .optional, .one, .slice, .prefix, .error_union => t.child = try l.scalar(u32), + .@"struct", .@"union" => { + const nfields = try l.scalar(u32); + if (nfields > l.bytes.len) return error.BadDump; + const list = try a.alloc(SrcField, nfields); + for (list) |*f| f.* = .{ .name = try l.name(), .ty = try l.scalar(u32) }; + t.fields = list; + }, + .custom => _ = try l.name(), + .skip, .void, .bool, .err, .bitset => {}, } } - - pub fn note(l: *Self, comptime fmt: []const u8, args: anytype) void { - if (l.notes.items.len > 4096) return; - l.notes.print(l.own, fmt ++ "\n", args) catch {}; + for (l.src) |t| { + if (t.child >= n) return error.BadDump; + for (t.fields) |f| if (f.ty >= n) return error.BadDump; } + } - fn root(l: *Self) DecodeError!u32 { - const ty = try l.scalar(u32); - if (ty >= l.src.len) return error.BadDump; - return ty; - } + pub fn note(l: *Self, comptime fmt: []const u8, args: anytype) void { + if (l.notes.items.len > 4096) return; + l.notes.print(l.own, fmt ++ "\n", args) catch {}; + } - /// The next root, made: what it points at is `gpa`'s. - pub fn get(l: *Self, comptime T: type) DecodeError!T { - var out: T = undefined; - try l.fresh(T, &out); - try l.value(T, try l.root(), &out); - return out; - } + /// A note on a type's field, its names given as run-time strings: + /// one instance of `note` (and of std's `print`) a message, where + /// a tuple of the comptime names made one a type, field and message. + fn noteField(l: *Self, comptime what: []const u8, type_name: []const u8, field: []const u8) void { + l.note("{s}.{s}: " ++ what, .{ type_name, field }); + } - /// The next root read into `out` as it stands: a field the dump - /// holds is replaced (what it held is not freed), every other one - /// is left as it is. A field another build cannot give is left too, - /// and noted. - pub fn into(l: *Self, comptime T: type, out: *T) DecodeError!void { - const ty = try l.root(); - const s = l.src[ty]; - if (s.kind != .@"struct") return error.BadDump; - try l.fields(T, s, out, true); - } + fn root(l: *Self) DecodeError!u32 { + const ty = try l.scalar(u32); + if (ty >= l.src.len) return error.BadDump; + return ty; + } - fn fresh(l: *Self, comptime T: type, out: *T) DecodeError!void { - freshOf(T, out, l.gpa); - } + /// The next root, made: what it points at is `gpa`'s. + pub fn get(l: *Self, comptime T: type) DecodeError!T { + var out: T = undefined; + try l.fresh(T, &out); + try l.value(T, try l.root(), &out); + return out; + } - /// Whether the source's `ty` and `T` are of one kind, else the - /// source's value passed over. - fn kindMatches(l: *Self, comptime T: type, ty: u32) DecodeError!bool { - if (l.same) return true; - const want = comptime kindOf(Canon(T)); - const got = l.src[ty].kind; - if (got == want) return true; - // A field that came to hold a count and so many, or stopped. - if ((want == .array and got == .prefix) or (want == .prefix and got == .array)) return true; - try l.skip(ty); - return false; - } + /// The next root read into `out` as it stands: a field the dump + /// holds is replaced (what it held is not freed), every other one + /// is left as it is. A field another build cannot give is left too, + /// and noted. + pub fn into(l: *Self, comptime T: type, out: *T) DecodeError!void { + const ty = try l.root(); + const s = l.src[ty]; + if (s.kind != .@"struct") return error.BadDump; + try l.fields(T, s, out, true); + } - fn readInt(l: *Self, comptime I: type, s: SrcType) DecodeError!I { - if (l.same) { - const info = @typeInfo(I).int; - const W = @Int(info.signedness, intBytes(info.bits) * 8); - return @intCast(try l.scalar(W)); - } - const n = intBytes(s.bits); - const raw = try l.take(n); - var wide: u128 = 0; - for (raw, 0..) |b, i| wide |= @as(u128, b) << @intCast(i * 8); - if (s.signed and n > 0) { - const shift: u7 = @intCast(128 - n * 8); - const signed: i128 = @as(i128, @bitCast(wide << shift)) >> shift; - return std.math.cast(I, signed) orelse error.Incompatible; - } - return std.math.cast(I, wide) orelse error.Incompatible; + fn fresh(l: *Self, comptime T: type, out: *T) DecodeError!void { + freshOf(T, out, l.gpa); + } + + /// Whether the source's `ty` and `T` are of one kind, else the + /// source's value passed over. + fn kindMatches(l: *Self, comptime T: type, ty: u32) DecodeError!bool { + if (l.same) return true; + const want = comptime kindOf(Canon(T)); + const got = l.src[ty].kind; + if (got == want) return true; + // A field that came to hold a count and so many, or stopped. + if ((want == .array and got == .prefix) or (want == .prefix and got == .array)) return true; + try l.skip(ty); + return false; + } + + fn readInt(l: *Self, comptime I: type, s: SrcType) DecodeError!I { + if (l.same) { + const info = @typeInfo(I).int; + const W = @Int(info.signedness, intBytes(info.bits) * 8); + return @intCast(try l.scalar(W)); + } + const n = intBytes(s.bits); + const raw = try l.take(n); + var wide: u128 = 0; + for (raw, 0..) |b, i| wide |= @as(u128, b) << @intCast(i * 8); + if (s.signed and n > 0) { + const shift: u7 = @intCast(128 - n * 8); + const signed: i128 = @as(i128, @bitCast(wide << shift)) >> shift; + return std.math.cast(I, signed) orelse error.Incompatible; } + return std.math.cast(I, wide) orelse error.Incompatible; + } - /// `T` read from the source's type `ty` into `out`, which `fresh` - /// has made ready. - fn value(l: *Self, comptime T: type, ty: u32, out: *T) DecodeError!void { - if (comptime isAtomic(T)) { - const R = @FieldType(T, "raw"); - var raw: R = undefined; - try l.fresh(R, &raw); - try l.value(R, ty, &raw); - out.* = .{ .raw = raw }; - return; - } - // A field this build compiles out (a void field): passed over, - // said only when it held something. - if (comptime kindOf(Canon(T)) == .void) if (!l.same and l.src[ty].kind != .void) { - const held = l.src[ty].kind != .optional or (l.at < l.bytes.len and l.bytes[l.at] != 0); - try l.skip(ty); - if (held) l.note("{s}: not in this build", .{l.field}); - return; - }; - if (!try l.kindMatches(T, ty)) return error.Incompatible; - const s = l.src[ty]; - if (comptime isList(T)) { - const E = @typeInfo(@FieldType(T, "items")).pointer.child; - const got = try l.slice(E, s); - out.* = .empty; - out.items = got; - out.capacity = got.len; - return; - } - switch (comptime kindOf(T)) { - .skip, .void => {}, - .bool => out.* = (try l.take(1))[0] != 0, - .int => out.* = try l.readInt(T, s), - .float => out.* = if (l.same or s.bits == @typeInfo(T).float.bits) try l.scalar(T) else return error.Incompatible, - .@"enum" => { - const e = @typeInfo(T).@"enum"; - if (l.same) { - out.* = @fromBackingInt(@intCast(try l.readInt(e.tag_type, s))); - return; - } - const n = try l.readInt(i128, s); - const was = for (s.fields) |f| { - if (f.value == n) break f.name; - } else null; - if (was) |w| inline for (e.field_names) |field| if (std.mem.eql(u8, w, field)) { - out.* = @field(T, field); - return; - }; - if (e.mode == .nonexhaustive and was == null) - if (std.math.cast(e.tag_type, n)) |tag| { - out.* = @fromBackingInt(@intCast(tag)); - return; - }; - l.note("{s}: no {s} here", .{ l.field, was orelse "such value" }); - return error.Incompatible; - }, - .optional => { - const C = @typeInfo(T).optional.child; - if ((try l.take(1))[0] == 0) { - out.* = null; - return; - } - if (comptime kindOf(Canon(C)) == .skip) { - out.* = if (comptime C == std.mem.Allocator) l.gpa else null; - return; - } - // A slice's or a pointer's null is its address: set to - // an undefined payload, the optional itself is undefined, - // and ReleaseSafe's optimizer read it as null (a pane's - // `?[]u8` command one byte long, every field after it out - // of step). Read through a local and set it from that. - if (comptime @typeInfo(C) == .pointer) { - var payload: C = undefined; - try l.value(C, s.child, &payload); - out.* = payload; - return; - } - out.* = @as(C, undefined); - try l.fresh(C, &out.*.?); - l.value(C, s.child, &out.*.?) catch |err| { - out.* = null; - return err; - }; - }, - .one => { - const C = @typeInfo(T).pointer.child; - if (try l.ref()) |again| { - out.* = @ptrCast(@alignCast(again.ptr)); + /// `T` read from the source's type `ty` into `out`, which `fresh` + /// has made ready. + fn value(l: *Self, comptime T: type, ty: u32, out: *T) DecodeError!void { + if (comptime isAtomic(T)) { + const R = @FieldType(T, "raw"); + var raw: R = undefined; + try l.fresh(R, &raw); + try l.value(R, ty, &raw); + out.* = .{ .raw = raw }; + return; + } + // A field this build compiles out (a void field): passed over, + // said only when it held something. + if (comptime kindOf(Canon(T)) == .void) if (!l.same and l.src[ty].kind != .void) { + const held = l.src[ty].kind != .optional or (l.at < l.bytes.len and l.bytes[l.at] != 0); + try l.skip(ty); + if (held) l.note("{s}: not in this build", .{l.field}); + return; + }; + if (!try l.kindMatches(T, ty)) return error.Incompatible; + const s = l.src[ty]; + if (comptime isList(T)) { + const E = @typeInfo(@FieldType(T, "items")).pointer.child; + const got = try l.slice(E, s); + out.* = .empty; + out.items = got; + out.capacity = got.len; + return; + } + switch (comptime kindOf(T)) { + .skip, .void => {}, + .bool => out.* = (try l.take(1))[0] != 0, + .int => out.* = try l.readInt(T, s), + .float => out.* = if (l.same or s.bits == @typeInfo(T).float.bits) try l.scalar(T) else return error.Incompatible, + .@"enum" => { + const e = @typeInfo(T).@"enum"; + if (l.same) { + out.* = @fromBackingInt(@intCast(try l.readInt(e.tag_type, s))); + return; + } + const n = try l.readInt(i128, s); + const was = for (s.fields) |f| { + if (f.value == n) break f.name; + } else null; + if (was) |w| inline for (e.field_names) |field| if (std.mem.eql(u8, w, field)) { + out.* = @field(T, field); + return; + }; + if (e.mode == .nonexhaustive and was == null) + if (std.math.cast(e.tag_type, n)) |tag| { + out.* = @fromBackingInt(@intCast(tag)); return; - } - const one = try l.gpa.create(C); - const at = l.made(std.mem.asBytes(one), .of(C)) catch |err| { - l.gpa.destroy(one); - return err; }; - try l.fresh(C, one); - l.value(C, s.child, one) catch |err| { - // Left half made: no later reference may find it. - l.shared.items[at].dead = true; - return err; - }; - out.* = one; - }, - .slice => { - const E = @typeInfo(T).pointer.child; - const got = try l.slice(E, s); - if (comptime @typeInfo(T).pointer.sentinel_ptr != null) @compileError("walk: a sentinel slice: " ++ @typeName(T)); - out.* = got; - }, - .array => { - const E = @typeInfo(T).array.child; - const n: u64 = if (s.kind == .prefix) try l.scalar(u64) else s.len; - try l.elements(E, s.child, n, out); - }, - .prefix => unreachable, - .@"struct" => try l.fields(T, s, out, false), - .@"union" => { - const u = @typeInfo(T).@"union"; - const ordinal = try l.scalar(u16); - if (ordinal >= s.fields.len) return error.BadDump; - const was = s.fields[ordinal]; - inline for (u.field_names, u.field_types, 0..) |field, F, i| { - if (if (l.same) ordinal == i else std.mem.eql(u8, was.name, field)) { - out.* = @unionInit(T, field, undefined); - try l.fresh(F, &@field(out.*, field)); - return l.value(F, was.ty, &@field(out.*, field)); - } + l.note("{s}: no {s} here", .{ l.field, was orelse "such value" }); + return error.Incompatible; + }, + .optional => { + const C = @typeInfo(T).optional.child; + if ((try l.take(1))[0] == 0) { + out.* = null; + return; + } + if (comptime kindOf(Canon(C)) == .skip) { + out.* = if (comptime C == std.mem.Allocator) l.gpa else null; + return; + } + // A slice's or a pointer's null is its address: set to + // an undefined payload, the optional itself is undefined, + // and ReleaseSafe's optimizer read it as null (a pane's + // `?[]u8` command one byte long, every field after it out + // of step). Read through a local and set it from that. + if (comptime @typeInfo(C) == .pointer) { + var payload: C = undefined; + try l.value(C, s.child, &payload); + out.* = payload; + return; + } + out.* = @as(C, undefined); + try l.fresh(C, &out.*.?); + l.value(C, s.child, &out.*.?) catch |err| { + out.* = null; + return err; + }; + }, + .one => { + const C = @typeInfo(T).pointer.child; + if (try l.ref()) |again| { + out.* = @ptrCast(@alignCast(again.ptr)); + return; + } + const one = try l.gpa.create(C); + const at = l.made(std.mem.asBytes(one), .of(C)) catch |err| { + l.gpa.destroy(one); + return err; + }; + try l.fresh(C, one); + l.value(C, s.child, one) catch |err| { + // Left half made: no later reference may find it. + l.shared.items[at].dead = true; + return err; + }; + out.* = one; + }, + .slice => { + const E = @typeInfo(T).pointer.child; + const got = try l.slice(E, s); + if (comptime @typeInfo(T).pointer.sentinel_ptr != null) @compileError("walk: a sentinel slice: " ++ @typeName(T)); + out.* = got; + }, + .array => { + const E = @typeInfo(T).array.child; + const n: u64 = if (s.kind == .prefix) try l.scalar(u64) else s.len; + try l.elements(E, s.child, n, out); + }, + .prefix => unreachable, + .@"struct" => try l.fields(T, s, out, false), + .@"union" => { + const u = @typeInfo(T).@"union"; + const ordinal = try l.scalar(u16); + if (ordinal >= s.fields.len) return error.BadDump; + const was = s.fields[ordinal]; + inline for (u.field_names, u.field_types, 0..) |field, F, i| { + if (if (l.same) ordinal == i else std.mem.eql(u8, was.name, field)) { + out.* = @unionInit(T, field, undefined); + try l.fresh(F, &@field(out.*, field)); + return l.value(F, was.ty, &@field(out.*, field)); } - try l.skip(was.ty); - l.note("{s}: no {s} here", .{ l.field, was.name }); + } + try l.skip(was.ty); + l.note("{s}: no {s} here", .{ l.field, was.name }); + return error.Incompatible; + }, + .err, .error_union => unreachable, + .custom => { + const bytes = try l.take(try l.count()); + T.dumpRead(out, l.gpa, bytes) catch |err| { + if (err == error.OutOfMemory) return error.OutOfMemory; + l.note("{s}: {t}", .{ l.field, err }); return error.Incompatible; - }, - .err, .error_union => unreachable, - .custom => { - const bytes = try l.take(try l.count()); - T.dumpRead(out, l.gpa, bytes) catch |err| { - if (err == error.OutOfMemory) return error.OutOfMemory; - l.note("{s}: {t}", .{ l.field, err }); - return error.Incompatible; - }; - if (comptime @hasDecl(T, "dumpFree")) try l.customs.append(l.own, .{ .ptr = out, .gpa = l.gpa, .free = @ptrCast(&T.dumpFree) }); - }, - .bitset => { - const bits = try l.count(); - out.* = try .initEmpty(l.gpa, bits); - const words = (bits + @bitSizeOf(usize) - 1) / @bitSizeOf(usize); - if (words > 0) @memcpy(std.mem.sliceAsBytes(out.masks[0..words]), try l.take(words * @sizeOf(usize))); - }, - } + }; + if (comptime @hasDecl(T, "dumpFree")) try l.customs.append(l.own, .{ .ptr = out, .gpa = l.gpa, .free = @ptrCast(&T.dumpFree) }); + }, + .bitset => { + const bits = try l.count(); + out.* = try .initEmpty(l.gpa, bits); + const words = (bits + @bitSizeOf(usize) - 1) / @bitSizeOf(usize); + if (words > 0) @memcpy(std.mem.sliceAsBytes(out.masks[0..words]), try l.take(words * @sizeOf(usize))); + }, } + } - /// A reference to a pointer or slice made before, or null for a - /// new one (its length then read). - fn ref(l: *Self) DecodeError!?[]u8 { - const n = try l.scalar(u32); - if (n == 0) return null; - if (n > l.shared.items.len) return error.BadDump; - const got = l.shared.items[n - 1]; - if (got.dead) return error.Incompatible; - return got.bytes; - } + /// A reference to a pointer or slice made before, or null for a + /// new one (its length then read). + fn ref(l: *Self) DecodeError!?[]u8 { + const n = try l.scalar(u32); + if (n == 0) return null; + if (n > l.shared.items.len) return error.BadDump; + const got = l.shared.items[n - 1]; + if (got.dead) return error.Incompatible; + return got.bytes; + } - fn slice(l: *Self, comptime E: type, s: SrcType) DecodeError![]E { - if (try l.ref()) |again| return @as([*]E, @ptrCast(@alignCast(again.ptr)))[0 .. again.len / @max(1, @sizeOf(E))]; - const n = try l.count(); - if (n == 0) return &.{}; - if (n > l.bytes.len) return error.BadDump; - const many = try l.gpa.alloc(E, n); - const at = l.made(std.mem.sliceAsBytes(many), .of(E)) catch |err| { - l.gpa.free(many); - return err; - }; - l.elements(E, s.child, n, many) catch |err| { - l.shared.items[at].dead = true; - return err; + fn slice(l: *Self, comptime E: type, s: SrcType) DecodeError![]E { + if (try l.ref()) |again| return @as([*]E, @ptrCast(@alignCast(again.ptr)))[0 .. again.len / @max(1, @sizeOf(E))]; + const n = try l.count(); + if (n == 0) return &.{}; + if (n > l.bytes.len) return error.BadDump; + const many = try l.gpa.alloc(E, n); + const at = l.made(std.mem.sliceAsBytes(many), .of(E)) catch |err| { + l.gpa.free(many); + return err; + }; + l.elements(E, s.child, n, many) catch |err| { + l.shared.items[at].dead = true; + return err; + }; + return many; + } + + /// `n` elements of the source's type `ty` into `out` (an array or + /// a slice), as many as it holds, the rest passed over. + fn elements(l: *Self, comptime E: type, ty: u32, n: u64, out: []E) DecodeError!void { + const keep: usize = @intCast(@min(n, out.len)); + const s = l.src[ty]; + // Bytes copied whole between builds when both sides agree on + // them: integers and bools (an enum's numbers may not be the other's). + const bulk = if (comptime flat(E)) l.same or (comptime flatHash(E)) and s.kind == (comptime kindOf(E)) and + (s.kind == .bool or (s.bits == @bitSizeOf(E) and s.signed == (@typeInfo(E) == .int and @typeInfo(E).int.signedness == .signed))) else false; + if (bulk) { + if (n > l.bytes.len) return error.EndOfDump; + @memcpy(std.mem.sliceAsBytes(out[0..keep]), try l.take(keep * @sizeOf(E))); + _ = try l.take(@intCast((n - keep) * @sizeOf(E))); + return; + } + // An array of optional pointers (a session's panes): one that + // cannot be read is left out, not the array. + const droppable = comptime @typeInfo(E) == .optional and @typeInfo(@typeInfo(E).optional.child) == .pointer; + var failed = false; + for (0..try countOf(n)) |i| { + if (i >= keep) { + try l.skip(ty); + continue; + } + try l.fresh(E, &out[i]); + l.value(E, ty, &out[i]) catch |err| { + if (err != error.Incompatible) return err; + if (droppable) { + out[i] = null; + l.note("{s}[{d}] left out", .{ l.field, i }); + } else failed = true; }; - return many; } + if (failed) return error.Incompatible; + } - /// `n` elements of the source's type `ty` into `out` (an array or - /// a slice), as many as it holds, the rest passed over. - fn elements(l: *Self, comptime E: type, ty: u32, n: u64, out: []E) DecodeError!void { - const keep: usize = @intCast(@min(n, out.len)); - const s = l.src[ty]; - // Bytes copied whole between builds when both sides agree on - // them: integers and bools (an enum's numbers may not be the other's). - const bulk = if (comptime flat(E)) l.same or (comptime flatHash(E)) and s.kind == (comptime kindOf(E)) and - (s.kind == .bool or (s.bits == @bitSizeOf(E) and s.signed == (@typeInfo(E) == .int and @typeInfo(E).int.signedness == .signed))) else false; - if (bulk) { - if (n > l.bytes.len) return error.EndOfDump; - @memcpy(std.mem.sliceAsBytes(out[0..keep]), try l.take(keep * @sizeOf(E))); - _ = try l.take(@intCast((n - keep) * @sizeOf(E))); - return; + fn fields(l: *Self, comptime T: type, s: SrcType, out: *T, existing: bool) DecodeError!void { + const names = comptime dumpFields(T); + const packed_struct = comptime @typeInfo(T).@"struct".layout == .@"packed"; + const outer = l.field; + defer l.field = outer; + if (l.same) { + if (s.fields.len != names.len) return error.BadDump; + inline for (names, 0..) |field, k| { + l.field = field; + try l.oneField(T, field, s.fields[k].ty, out, packed_struct, existing); } - // An array of optional pointers (a session's panes): one that - // cannot be read is left out, not the array. - const droppable = comptime @typeInfo(E) == .optional and @typeInfo(@typeInfo(E).optional.child) == .pointer; - var failed = false; - for (0..try countOf(n)) |i| { - if (i >= keep) { - try l.skip(ty); - continue; - } - try l.fresh(E, &out[i]); - l.value(E, ty, &out[i]) catch |err| { + return; + } + var found: std.StaticBitSet(@max(1, names.len)) = .empty; + var failed = false; + for (s.fields) |f| { + const k: ?usize = inline for (names, 0..) |field, k| { + if (std.mem.eql(u8, f.name, field)) break k; + } else null; + const at = k orelse { + try l.skip(f.ty); + continue; + }; + found.set(at); + inline for (names, 0..) |field, i| if (i == at) { + l.field = field; + l.oneField(T, field, f.ty, out, packed_struct, existing) catch |err| { if (err != error.Incompatible) return err; - if (droppable) { - out[i] = null; - l.note("{s}[{d}] left out", .{ l.field, i }); + const attr = comptime @typeInfo(T).@"struct".field_attrs[std.meta.fieldIndex(T, field).?]; + if (comptime attr.default_value_ptr) |dp| { + @field(out, field) = @as(*const @FieldType(T, field), @ptrCast(@alignCast(dp))).*; + l.noteField("its kind changed; its default taken", @typeName(T), field); + } else if (existing) { + l.noteField("its kind changed; left as it was", @typeName(T), field); } else failed = true; }; - } - if (failed) return error.Incompatible; + }; } - - fn fields(l: *Self, comptime T: type, s: SrcType, out: *T, existing: bool) DecodeError!void { - const names = comptime dumpFields(T); - const packed_struct = comptime @typeInfo(T).@"struct".layout == .@"packed"; - const outer = l.field; - defer l.field = outer; - if (l.same) { - if (s.fields.len != names.len) return error.BadDump; - inline for (names, 0..) |field, k| { - l.field = field; - try l.oneField(T, field, s.fields[k].ty, out, packed_struct, existing); + // A field the writer did not have: its default (`fresh`), or + // the value cannot be made. + inline for (names, 0..) |field, i| if (!found.isSet(i)) { + const attr = comptime @typeInfo(T).@"struct".field_attrs[std.meta.fieldIndex(T, field).?]; + if (comptime attr.default_value_ptr == null) { + if (!existing) { + l.noteField("not in the dump", @typeName(T), field); + failed = true; } - return; - } - var found: std.StaticBitSet(@max(1, names.len)) = .empty; - var failed = false; - for (s.fields) |f| { - const k: ?usize = inline for (names, 0..) |field, k| { - if (std.mem.eql(u8, f.name, field)) break k; - } else null; - const at = k orelse { - try l.skip(f.ty); - continue; - }; - found.set(at); - inline for (names, 0..) |field, i| if (i == at) { - l.field = field; - l.oneField(T, field, f.ty, out, packed_struct, existing) catch |err| { - if (err != error.Incompatible) return err; - const attr = comptime @typeInfo(T).@"struct".field_attrs[std.meta.fieldIndex(T, field).?]; - if (comptime attr.default_value_ptr) |dp| { - @field(out, field) = @as(*const @FieldType(T, field), @ptrCast(@alignCast(dp))).*; - l.note("{s}.{s}: its kind changed; its default taken", .{ @typeName(T), field }); - } else if (existing) { - l.note("{s}.{s}: its kind changed; left as it was", .{ @typeName(T), field }); - } else failed = true; - }; - }; } - // A field the writer did not have: its default (`fresh`), or - // the value cannot be made. - inline for (names, 0..) |field, i| if (!found.isSet(i)) { - const attr = comptime @typeInfo(T).@"struct".field_attrs[std.meta.fieldIndex(T, field).?]; - if (comptime attr.default_value_ptr == null) { - if (!existing) { - l.note("{s}.{s}: not in the dump", .{ @typeName(T), field }); - failed = true; - } - } - }; - if (failed) return error.Incompatible; - } + }; + if (failed) return error.Incompatible; + } - fn oneField(l: *Self, comptime T: type, comptime field: []const u8, ty: u32, out: *T, comptime packed_struct: bool, existing: bool) DecodeError!void { - const F = @FieldType(T, field); - const gpa = l.gpa; - defer l.gpa = gpa; - if (comptime allocOf(T, field)) |which| if (@field(l.allocs, which)) |a| { - l.gpa = a; - }; - if (comptime cutArray(T, field)) { - return l.value(F, ty, &@field(out, field)); - } - // A struct held in place in one read as it stands (the root's): - // what it does not hold stays as it is too. - if (comptime kindOf(Canon(F)) == .@"struct" and Canon(F) == F and @typeInfo(F).@"struct".layout != .@"packed") if (existing) { - if (!try l.kindMatches(F, ty)) return error.Incompatible; - return l.fields(F, l.src[ty], &@field(out, field), true); - }; - if (packed_struct) { - var copy: F = undefined; - try l.fresh(F, ©); - try l.value(F, ty, ©); - @field(out, field) = copy; - return; - } - try l.fresh(F, &@field(out, field)); - try l.value(F, ty, &@field(out, field)); + fn oneField(l: *Self, comptime T: type, comptime field: []const u8, ty: u32, out: *T, comptime packed_struct: bool, existing: bool) DecodeError!void { + const F = @FieldType(T, field); + const gpa = l.gpa; + defer l.gpa = gpa; + if (comptime allocOf(T, field)) |which| if (@field(l.allocs, which)) |a| { + l.gpa = a; + }; + if (comptime cutArray(T, field)) { + return l.value(F, ty, &@field(out, field)); } + // A struct held in place in one read as it stands (the root's): + // what it does not hold stays as it is too. + if (comptime kindOf(Canon(F)) == .@"struct" and Canon(F) == F and @typeInfo(F).@"struct".layout != .@"packed") if (existing) { + if (!try l.kindMatches(F, ty)) return error.Incompatible; + return l.fields(F, l.src[ty], &@field(out, field), true); + }; + if (packed_struct) { + var copy: F = undefined; + try l.fresh(F, ©); + try l.value(F, ty, ©); + @field(out, field) = copy; + return; + } + try l.fresh(F, &@field(out, field)); + try l.value(F, ty, &@field(out, field)); + } - /// The source's value of type `ty` passed over. - fn skip(l: *Self, ty: u32) DecodeError!void { - const s = l.src[ty]; - switch (s.kind) { - .skip, .void => {}, - .bool => _ = try l.take(1), - .int, .@"enum" => _ = try l.take(intBytes(s.bits)), - .float => _ = try l.take(s.bits / 8), - .optional => if ((try l.take(1))[0] != 0) try l.skip(s.child), - .one => if (try l.scalar(u32) == 0) { + /// The source's value of type `ty` passed over. + fn skip(l: *Self, ty: u32) DecodeError!void { + const s = l.src[ty]; + switch (s.kind) { + .skip, .void => {}, + .bool => _ = try l.take(1), + .int, .@"enum" => _ = try l.take(intBytes(s.bits)), + .float => _ = try l.take(s.bits / 8), + .optional => if ((try l.take(1))[0] != 0) try l.skip(s.child), + .one => if (try l.scalar(u32) == 0) { + _ = try l.made(&.{}, .@"1"); + l.shared.items[l.shared.items.len - 1].dead = true; + try l.skip(s.child); + }, + .slice => if (try l.scalar(u32) == 0) { + const n = try l.scalar(u64); + if (n > 0) { _ = try l.made(&.{}, .@"1"); l.shared.items[l.shared.items.len - 1].dead = true; - try l.skip(s.child); - }, - .slice => if (try l.scalar(u32) == 0) { - const n = try l.scalar(u64); - if (n > 0) { - _ = try l.made(&.{}, .@"1"); - l.shared.items[l.shared.items.len - 1].dead = true; - } - try l.skipMany(s.child, n); - }, - .prefix => try l.skipMany(s.child, try l.scalar(u64)), - .array => try l.skipMany(s.child, s.len), - .@"struct" => for (s.fields) |f| try l.skip(f.ty), - .@"union" => { - const ordinal = try l.scalar(u16); - if (ordinal >= s.fields.len) return error.BadDump; - try l.skip(s.fields[ordinal].ty); - }, - .err => _ = try l.name(), - .error_union => if ((try l.take(1))[0] != 0) try l.skip(s.child) else { - _ = try l.name(); - }, - .custom => _ = try l.take(try l.count()), - .bitset => _ = try l.take((try l.count() + 63) / 64 * 8), - } + } + try l.skipMany(s.child, n); + }, + .prefix => try l.skipMany(s.child, try l.scalar(u64)), + .array => try l.skipMany(s.child, s.len), + .@"struct" => for (s.fields) |f| try l.skip(f.ty), + .@"union" => { + const ordinal = try l.scalar(u16); + if (ordinal >= s.fields.len) return error.BadDump; + try l.skip(s.fields[ordinal].ty); + }, + .err => _ = try l.name(), + .error_union => if ((try l.take(1))[0] != 0) try l.skip(s.child) else { + _ = try l.name(); + }, + .custom => _ = try l.take(try l.count()), + .bitset => _ = try l.take((try l.count() + 63) / 64 * 8), } + } - fn skipMany(l: *Self, ty: u32, n: u64) DecodeError!void { - const s = l.src[ty]; - if (s.kind == .int or s.kind == .bool) { - const size: u64 = if (s.kind == .bool) 1 else intBytes(s.bits); - if (n > l.bytes.len) return error.EndOfDump; - _ = try l.take(@intCast(n * size)); - return; - } - for (0..try countOf(n)) |_| try l.skip(ty); + fn skipMany(l: *Self, ty: u32, n: u64) DecodeError!void { + const s = l.src[ty]; + if (s.kind == .int or s.kind == .bool) { + const size: u64 = if (s.kind == .bool) 1 else intBytes(s.bits); + if (n > l.bytes.len) return error.EndOfDump; + _ = try l.take(@intCast(n * size)); + return; } - }; -} + for (0..try countOf(n)) |_| try l.skip(ty); + } +}; /// `out` as a new `T` is before a load reads its fields: each field's /// default, an allocator `gpa`. @@ -1854,6 +1878,11 @@ pub const Get = struct { l.notes.print(l.own, fmt ++ "\n", args) catch {}; } + /// A note on a type's field, its names given at run time (Load's). + fn noteField(l: *Get, comptime what: []const u8, type_name: []const u8, field: []const u8) void { + l.note("{s}.{s}: " ++ what, .{ type_name, field }); + } + /// The value at `c`, made: what it points at is `gpa`'s. pub fn get(l: *Get, comptime T: type, c: Cursor) Error!T { var out: T = undefined; @@ -2270,9 +2299,9 @@ pub const Get = struct { const attr = comptime @typeInfo(T).@"struct".field_attrs[std.meta.fieldIndex(T, field).?]; if (comptime attr.default_value_ptr) |dp| { @field(out, field) = @as(*const @FieldType(T, field), @ptrCast(@alignCast(dp))).*; - l.note("{s}.{s}: its kind changed; its default taken", .{ @typeName(T), field }); + l.noteField("its kind changed; its default taken", @typeName(T), field); } else if (existing) { - l.note("{s}.{s}: its kind changed; left as it was", .{ @typeName(T), field }); + l.noteField("its kind changed; left as it was", @typeName(T), field); } else failed = true; }; }; @@ -2284,7 +2313,7 @@ pub const Get = struct { const attr = comptime @typeInfo(T).@"struct".field_attrs[std.meta.fieldIndex(T, field).?]; if (comptime attr.default_value_ptr == null and kindOf(Canon(F)) != .void) { if (!existing) { - l.note("{s}.{s}: not in the dump", .{ @typeName(T), field }); + l.noteField("not in the dump", @typeName(T), field); failed = true; } } else if (comptime @typeInfo(F) == .optional and defaultIsNull(T, field)) if (existing) { @@ -2564,3 +2593,8 @@ test "a blob of 4 KiB and up is digested by its length, what it holds told by it small[1] = 'x'; try std.testing.expect(digest(File, &f) != was); } + +test "a shape's numbers are written as {d} writes them" { + inline for (.{ 0, 7, 10, 65535, -1, -300, std.math.minInt(i128), std.math.maxInt(u128) }) |n| + try std.testing.expectEqualStrings(std.fmt.comptimePrint("{d}", .{n}), comptime decimal(n)); +} diff --git a/src/wire.zig b/src/wire.zig index 3dd08b29..9773d222 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 @@ -61,16 +61,18 @@ const family = switch (config.platform) { /// their options and dependencies; -Dstamp-commit stamps one. pub const semantics: u64 = blk: { @setEvalBranchQuota(1_000_000); + // The two long ones (the dependencies, 2.5 KB, and the tape's shape, + // 11 KB) joined on, not formatted: formatting them at comptime was 5 % + // of a compile of the core. break :blk std.hash.Wyhash.hash(0, std.fmt.comptimePrint( - "wire {d}\npardes {s} {s}\n{s} grammars {} {} {} {} workspace_tag {} sources {}\nusize {d} {t}\n{s}\n{s}", + "wire {d}\npardes {s} {s}\n{s} grammars {} {} {} {} workspace_tag {} sources {}\nusize {d} {t}\n", .{ version, config.version, config.commit orelse "unstamped", family, config.syntax_highlighting, config.syntax_zig_grammar, config.syntax_minimal_grammars, config.syntax_full_grammars, config.workspace_tag, config.embed_sources, @sizeOf(usize), builtin.cpu.arch.endian(), - config.deps, pardes.tape.shape, }, - )); + ) ++ config.deps ++ "\n" ++ pardes.tape.shape); }; /// EndOfStream: the message ends early; WriteFailed: no room for it. @@ -88,7 +90,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 +172,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. |
