diff options
Diffstat (limited to 'src')
| -rw-r--r-- | src/Addon.zig | 50 | ||||
| -rw-r--r-- | src/Art.zig | 32 | ||||
| -rw-r--r-- | src/CHANGELOG.md | 18 | ||||
| -rw-r--r-- | src/File.zig | 118 | ||||
| -rw-r--r-- | src/Kind.zig | 27 | ||||
| -rw-r--r-- | src/Output.zig | 16 | ||||
| -rw-r--r-- | src/Query.zig | 4 | ||||
| -rw-r--r-- | src/Stream.zig | 8 | ||||
| -rw-r--r-- | src/Text.zig | 36 | ||||
| -rw-r--r-- | src/colors.zig | 30 | ||||
| -rw-r--r-- | src/diff.zig | 24 | ||||
| -rw-r--r-- | src/draw.zig | 4 | ||||
| -rw-r--r-- | src/dump.zig | 75 | ||||
| -rw-r--r-- | src/grammar_manifest.zig | 108 | ||||
| -rw-r--r-- | src/gui/gui.zig | 81 | ||||
| -rw-r--r-- | src/hunks.zig | 33 | ||||
| -rw-r--r-- | src/kinds/addon.zig | 18 | ||||
| -rw-r--r-- | src/kinds/pardes_addon.h | 12 | ||||
| -rw-r--r-- | src/lsp/lsp_client.zig | 66 | ||||
| -rw-r--r-- | src/ninep/ctl.zig | 2 | ||||
| -rw-r--r-- | src/ninep/pane.zig | 2 | ||||
| -rw-r--r-- | src/pager.zig | 379 | ||||
| -rw-r--r-- | src/panes.zig | 2 | ||||
| -rw-r--r-- | src/pardes.zig | 1 | ||||
| -rw-r--r-- | src/screen_state.zig | 36 | ||||
| -rw-r--r-- | src/surface.zig | 5 | ||||
| -rw-r--r-- | src/syntax.zig | 114 | ||||
| -rw-r--r-- | src/terminal.zig | 25 | ||||
| -rw-r--r-- | src/tui/tui.zig | 14 |
29 files changed, 1018 insertions, 322 deletions
diff --git a/src/Addon.zig b/src/Addon.zig index cadf28d7..80d8fdd8 100644 --- a/src/Addon.zig +++ b/src/Addon.zig @@ -313,7 +313,6 @@ fn readSmall(path: [*:0]const u8) Kind.Buf(4096) { return out; } - // ---- the tail: what a library brings, and a core's tables of it ---- /// What a library brings, as the host read it off its head (or why it @@ -356,7 +355,12 @@ pub fn loadedOf(ops: *const Kind.Ops, path: []const u8, hash: [32]u8, words: *[6 .words = words[0..head_words.len], .ops = @intFromPtr(ops), .caps = .{ - .tick = ops.tick != null, .key = ops.key != null, .mouse = ops.mouse != null, .ctl = ops.ctl != null, .jobs = ops.job_run != null, .load = ops.load != null, + .tick = ops.tick != null, + .key = ops.key != null, + .mouse = ops.mouse != null, + .ctl = ops.ctl != null, + .jobs = ops.job_run != null, + .load = ops.load != null, .search = ops.search != null, .address = ops.address != null, .view = ops.view != null, @@ -483,7 +487,6 @@ fn coreWord(name: []const u8) bool { return std.meta.stringToEnum(builtins.registry.Builtin(), name) != null or builtins.absentWhy(name) != null; } - // ---- the core's half ---- /// `Addon load <path>` (relative to the pane's directory), `Addon unload @@ -602,7 +605,8 @@ fn swap(p: *Pardes, l: Loaded, why: *Why) bool { }; for (p.panes, 0..) |pslot, id| if (pslot) |pane| if (pane.addon) |s| if (s.live and s.is(name)) { const n = s.gpa.create(Kind.Slot) catch return fail(why, "out of memory", .{}); - n.* = .{ .ops = new_ops, .live = true, .gpa = s.gpa, .arena = .init(s.gpa), .name = s.name, .version = l.version, .gen = gen, .art = s.art, .values = s.values }; + // load receives the record's version, not the replacement library's. + n.* = .{ .ops = new_ops, .live = true, .gpa = s.gpa, .arena = .init(s.gpa), .name = s.name, .version = s.version, .gen = gen, .art = s.art, .values = s.values }; fresh[id] = n; n.path = s.gpa.dupe(u8, s.path) catch return fail(why, "out of memory", .{}); // The old state's record, by the old library. @@ -658,6 +662,44 @@ pub fn list(p: *const Pardes, out: *std.ArrayList(u8), gpa: std.mem.Allocator) ! } } +test "addon reload gives migration the old record version and saves the new version" { + const Fake = struct { + var state: u8 = 7; + fn open(_: [*c]const u8, _: [*c]const u8, _: u64) callconv(.c) ?*anyopaque { + return &state; + } + fn paint(_: ?*anyopaque, _: [*c]const Kind.c.pa_window, _: [*c]Kind.c.pa_paint) callconv(.c) void {} + fn save(_: ?*anyopaque, out: [*c]u8, n: u32) callconv(.c) u32 { + if (n > 0) out[0] = state; + return 1; + } + fn load(_: ?*anyopaque, bytes: [*c]const u8, n: u32, version: u32) callconv(.c) c_int { + return if (version == 1 and n == 1 and bytes[0] == 7) Kind.c.PA_OK else 1; + } + }; + const p = try @import("ninep/testing.zig").withFile(std.testing.allocator, "x\n"); + defer p.deinit(); + var old = std.mem.zeroInit(Kind.Ops, .{ .head = std.mem.zeroInit(Kind.c.pa_head, .{ .size = @sizeOf(Kind.c.pa_head), .abi = Kind.abi, .version = 1 }), .open = Fake.open, .paint = Fake.paint, .dump = Fake.save, .load = Fake.load }); + @memcpy(old.head.name[0..7], "migrate"); + var words: [64]LoadedWord = undefined; + try std.testing.expect(p.kinds.take(loadedOf(&old, "test.so", @splat(0), &words), "") == null); + const pane = try Kind.open(p, 1, p.kinds.byName("migrate").?, null, null); + var new = old; + new.head.version = 2; + var why: Why = .{}; + try std.testing.expect(swap(p, loadedOf(&new, "test.so", @splat(1), &words), &why)); + try std.testing.expectEqual(@as(u32, 2), pane.addon.?.version); + try std.testing.expectEqual(@as(u32, 2), p.kinds.kinds[p.kinds.byName("migrate").?].version); + // A saved v1 placeholder revived by v2 must also save future records as v2. + const slot = pane.addon.?; + slot.version = 1; + slot.live = false; + slot.record = try slot.gpa.dupe(u8, &.{7}); + dump.reviveSlot(p, 1, slot); + try std.testing.expect(slot.live); + try std.testing.expectEqual(@as(u32, 2), slot.version); +} + test "a load that never finished is skipped at the next start, and every start after, until a load asks for it" { var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); 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 afc14a0c..da489b82 100644 --- a/src/CHANGELOG.md +++ b/src/CHANGELOG.md @@ -9,6 +9,24 @@ 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 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 core measures a grapheme's cells over uucode itself + (`File.utf8Width`, libvaxis's `gwidth` to the cell on every scalar + value), so libvaxis is the tui's and the gui's alone, not the core + module's. The 256-colour palette Petscii art and the window draw a + palette colour with is pardes's own (`colors.xterm`), ghostty-vt's + default to the entry. A `+Pager` (`pardes -`) reads its program's colour + codes with a parser of its own, which pages what ghostty-vt's did, byte + for byte, about 10% faster. + +- 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. + - zstbi is upstream's again (zig-gamedev/zstbi, its main): the fork pinned for Zig 0.17 was deleted, and a fresh checkout could not fetch it. diff --git a/src/File.zig b/src/File.zig index dc7b4cf8..5150f1cd 100644 --- a/src/File.zig +++ b/src/File.zig @@ -2,7 +2,7 @@ //! index, syntax highlights and the body it fills. const panes = @import("panes.zig"); const std = @import("std"); -const vaxis = @import("vaxis"); +const uucode = @import("uucode"); const builtin = @import("builtin"); const pardes = @import("pardes.zig"); const config = @import("config.zig"); @@ -59,12 +59,31 @@ pub const History = struct { } }; +/// Owned syntax results. Excluded from dumps as State.context is derived. +pub const ContextCache = struct { + allocator: ?std.mem.Allocator = null, + declarations: []syntax.ContextDeclaration = &.{}, + revision: ?u32 = null, + + pub fn deinit(self: *ContextCache) void { + if (self.allocator) |gpa| gpa.free(self.declarations); + self.* = .{}; + } + + /// Takes ownership of declarations allocated by gpa. + pub fn replace(self: *ContextCache, gpa: std.mem.Allocator, declarations: []syntax.ContextDeclaration, revision: u32) void { + self.deinit(); + self.* = .{ .allocator = gpa, .declarations = declarations, .revision = revision }; + } +}; + /// A file pane's backing: owned content, its derived caches, and undo history. pub const State = struct { /// What the replay digest leaves out (src/walk.zig): what is made again /// from the text whenever it is wanted. + // Syntax caches must not load through the dump loader's core allocator. pub const replica = .{ - .derived = .{ "cap", "line_starts", "line_cap", "highlights", "highlight_start", "syntax_dirty", "node_tree", "node_tree_revision", "node_tree_edits", "node_history", "tables" }, + .derived = .{ "cap", "line_starts", "line_cap", "highlights", "highlight_start", "syntax_dirty", "context", "node_tree", "node_tree_revision", "node_tree_edits", "node_history", "tables" }, // Big texts, dumped and sent by their hash (src/walk.zig). The // text is written in place by `replace`, but never while a join // sends it (memory.zig `pin`): then an edit puts a new buffer in @@ -136,8 +155,7 @@ pub const State = struct { highlight_start: usize = 0, syntax_dirty: bool = true, tree_context: bool = false, - context_declarations: []syntax.ContextDeclaration = &.{}, - context_revision: ?u32 = null, + context: ContextCache = .{}, /// The whole file's parse for the keys that walk its nodes (Alt-o and /// kin), made on the first of them after an edit and kept until the next /// one: `syntax.parseTree`'s, opaque here. @@ -168,10 +186,8 @@ pub const NodeStep = struct { ranges: []modal.Selection, primary: usize }; pub fn graphemeDisplayWidth(grapheme: []const u8) usize { if (std.mem.eql(u8, grapheme, "\t")) return config.tab_now; if (grapheme.len == 1 and grapheme[0] >= 0x20 and grapheme[0] < 0x7f) return 1; - if (std.unicode.utf8ValidateSlice(grapheme)) return @max(1, @as(usize, vaxis.gwidth.gwidth(grapheme, .unicode))); - // vaxis's gwidth counts back a replacement rune's 3 bytes over the one - // invalid byte it stood for (`\xee` before `e\u{301}` overflowed it): - // each invalid byte is a cell, as surface.zig draws it, and each valid + if (std.unicode.utf8ValidateSlice(grapheme)) return @max(1, @as(usize, utf8Width(grapheme))); + // Each invalid byte is a cell, as surface.zig draws it, and each valid // run between is measured alone. var width: usize = 0; var run: usize = 0; @@ -182,15 +198,60 @@ pub fn graphemeDisplayWidth(grapheme: []const u8) usize { i += n; continue; } - if (run < i) width += vaxis.gwidth.gwidth(grapheme[run..i], .unicode); + if (run < i) width += utf8Width(grapheme[run..i]); width += 1; i += 1; run = i; } - if (run < grapheme.len) width += vaxis.gwidth.gwidth(grapheme[run..], .unicode); + if (run < grapheme.len) width += utf8Width(grapheme[run..]); return @max(1, width); } +/// The cells valid UTF-8 takes, summed over its graphemes: a grapheme is +/// as wide as its widest code point (a control, a nonspacing or enclosing +/// mark and the joiners, selectors and other format characters below add +/// none; East Asian wide and fullwidth two, the rest one), then at least +/// one under the text selector U+FE0E, else at least two under the emoji +/// selector U+FE0F, with an emoji-presentation code point, or as a flag's +/// two regional indicators. It is libvaxis's `gwidth(.unicode)` over the +/// same uucode tables, which the tui renders with in mode 2027. +pub fn utf8Width(valid: []const u8) u16 { + var total: u16 = 0; + var widest: u16 = 0; + var text_vs = false; + var emoji = false; + var flags: u8 = 0; + var it = uucode.grapheme.utf8Iterator(valid); + while (it.nextCodePoint()) |r| { + const cp = r.code_point; + if (cp == 0xfe0e) { + text_vs = true; + } else if (cp == 0xfe0f) { + emoji = true; + } else { + if (uucode.get(.is_emoji_presentation, cp)) emoji = true; + if (cp >= 0x1f1e6 and cp <= 0x1f1ff) flags += 1; + widest = @max(widest, @as(u16, switch (cp) { + 0...0x1f, 0x7f...0x9f, 0xad, 0x34f, 0x180b...0x180d, 0x200b...0x200d, 0x2060, 0xfe00...0xfe0d, 0xfeff, 0xe0100...0xe01ef => 0, + else => switch (uucode.get(.general_category, cp)) { + .mark_nonspacing, .mark_enclosing => 0, + else => switch (uucode.get(.east_asian_width, cp)) { + .fullwidth, .wide => 2, + else => 1, + }, + }, + })); + } + if (!r.is_break) continue; + total += if (text_vs) @max(1, widest) else if (emoji or flags == 2) @max(2, widest) else widest; + widest = 0; + text_vs = false; + emoji = false; + flags = 0; + } + return total; +} + pub fn displayWidth(text: []const u8) usize { var width: usize = 0; var at: usize = 0; @@ -576,7 +637,7 @@ pub fn deinit(p: *Pardes, pane: *Pane, file: *State) void { if (file.highlights.len > 0) p.tree_sitter_gpa.free(file.highlights); p.gpa.free(file.pager_spans); locations.freeRows(p.gpa, file.location_rows); - if (file.context_declarations.len > 0) p.tree_sitter_gpa.free(file.context_declarations); + file.context.deinit(); if (file.node_tree) |tree| syntax.freeTree(tree); for (file.node_history.items) |step| p.gpa.free(step.ranges); file.node_history.deinit(p.gpa); @@ -1463,11 +1524,9 @@ pub fn changed(p: *Pardes, id: u8, bytes: []const u8) void { /// its text as it is now: found in the step (Pardes.sync), never only by a /// render, since the view's geometry is made of them (`geometry`). pub fn refreshContext(p: *Pardes, pane: *Pane, f: *State) void { - if (!f.tree_context or !supportsContext(pane) or f.context_revision == f.revision) return; + if (!f.tree_context or !supportsContext(pane) or f.context.revision == f.revision) return; const declarations = syntax.contextDeclarations(p.tree_sitter_gpa, f.path, f.content) catch return; - if (f.context_declarations.len > 0) p.tree_sitter_gpa.free(f.context_declarations); - f.context_declarations = declarations; - f.context_revision = f.revision; + f.context.replace(p.tree_sitter_gpa, declarations, f.revision); } pub fn refreshHighlights(p: *Pardes) void { @@ -1585,7 +1644,7 @@ fn prepareContextRows(pane: *Pane, file: *State) void { pane.context_rows = 0; if (!file.tree_context or !supportsContext(pane) or pane.rows > pane.wrap_line.len) return; const capacity = @min(pane.rows -| 1, pane.context_row_limit orelse std.math.maxInt(u16)); // retain an ordinary body row - for (file.context_declarations) |declaration| { + for (file.context.declarations) |declaration| { if (declaration.start_line >= file.scroll) break; if (declaration.end_line < file.scroll) continue; var row = declaration.start_line; @@ -1676,8 +1735,8 @@ fn geometryKey(pane: *const Pane, f: *const State) u64 { f.revision, f.content.len, f.scroll, pane.hscroll, pane.rows, pane.cols, pane.tag_rows, pane.collapsed, pane.query != null, f.pager, f.mini != null, f.output != null, - if (f.output) |o| pardes.walk.digest(Output.Origin, &o.from) else 0, std.hash.Wyhash.hash(0, f.path), f.tree_context, f.context_revision orelse 0, - f.context_declarations.len, f.line_starts.len, t.revision orelse 0, t.list.items.len, + if (f.output) |o| pardes.walk.digest(Output.Origin, &o.from) else 0, std.hash.Wyhash.hash(0, f.path), f.tree_context, f.context.revision orelse 0, + f.context.declarations.len, f.line_starts.len, t.revision orelse 0, t.list.items.len, if (t.pending) |r| r.at else std.math.maxInt(usize), pane.view.wrap, pane.view.layered, pane.view.body_h, pane.view.tagline_h, pane.view.rect_h, }; @@ -2190,7 +2249,7 @@ pub fn paintWordSelection( } } -test "an invalid byte in a grapheme is one cell, and never reaches vaxis's width" { +test "an invalid byte in a grapheme is one cell, and never reaches utf8Width" { try std.testing.expectEqual(@as(usize, 2), graphemeDisplayWidth("\xeee\xcc\x81")); try std.testing.expectEqual(@as(usize, 3), graphemeDisplayWidth("\xee\xffe")); try std.testing.expectEqual(@as(usize, 3), graphemeDisplayWidth("\u{4e16}\x80")); @@ -2229,11 +2288,11 @@ test "indexed source rows match uncached scans across content changes" { } } -test "the ASCII arm of graphemeDisplayWidth matches the gwidth it skips" { +test "the ASCII arm of graphemeDisplayWidth matches the utf8Width it skips" { const ref = struct { fn width(grapheme: []const u8) usize { if (std.mem.eql(u8, grapheme, "\t")) return config.tab_now; - return @max(1, @as(usize, vaxis.gwidth.gwidth(grapheme, .unicode))); + return @max(1, @as(usize, utf8Width(grapheme))); } }.width; @@ -2248,7 +2307,7 @@ test "the ASCII arm of graphemeDisplayWidth matches the gwidth it skips" { "\u{1f642}", "\u{1f1e6}\u{1f1e7}", "\xff", }) |g| try std.testing.expectEqual(ref(g), graphemeDisplayWidth(g)); // Two invalid bytes are two cells, as surface.zig draws them, where - // vaxis's own count gives the pair one. + // one U+FFFD for the pair would give one. try std.testing.expectEqual(@as(usize, 2), graphemeDisplayWidth("\xe4\xb8")); } @@ -2640,3 +2699,18 @@ test "undo keeps its steps within a byte bound, the newest always" { try std.testing.expect(std.mem.allEqual(u8, f.content[step / 2 ..][0..step], f.content[step / 2])); } } + +test "context cache frees each allocation with its original allocator" { + var first: std.heap.DebugAllocator(.{}) = .init; + defer std.testing.expect(first.deinit() == .ok) catch @panic("first allocator leaked"); + var second: std.heap.DebugAllocator(.{}) = .init; + defer std.testing.expect(second.deinit() == .ok) catch @panic("second allocator leaked"); + var cache: ContextCache = .{}; + defer cache.deinit(); + cache.replace(first.allocator(), try first.allocator().alloc(syntax.ContextDeclaration, 1), 1); + cache.replace(second.allocator(), try second.allocator().alloc(syntax.ContextDeclaration, 2), 2); + try std.testing.expectEqual(@as(?u32, 2), cache.revision); + cache.deinit(); + try std.testing.expect(cache.allocator == null); + try std.testing.expectEqual(@as(usize, 0), cache.declarations.len); +} diff --git a/src/Kind.zig b/src/Kind.zig index 6d4caec6..250e1144 100644 --- a/src/Kind.zig +++ b/src/Kind.zig @@ -37,10 +37,10 @@ pub const abi: u32 = c.PA_ABI; // records the core reads are the ones addons are built to. comptime { if (@sizeOf(usize) == 8) for (.{ - .{ c.pa_cell, 20 }, .{ c.pa_window, 24 }, .{ c.pa_rect, 16 }, .{ c.pa_cells, 8 }, - .{ c.pa_placement, 80 }, .{ c.pa_paint, 32 }, .{ c.pa_key, 8 }, .{ c.pa_mouse, 16 }, - .{ c.pa_api, 112 }, .{ c.pa_out, 16 }, .{ c.pa_word, 32 }, .{ c.pa_head, 56 }, - .{ c.pa_ops, 208 }, .{ c.pa_view, 32 }, .{ c.pa_tick, 128 }, + .{ c.pa_cell, 20 }, .{ c.pa_window, 24 }, .{ c.pa_rect, 16 }, .{ c.pa_cells, 8 }, + .{ c.pa_placement, 80 }, .{ c.pa_paint, 48 }, .{ c.pa_key, 8 }, .{ c.pa_mouse, 16 }, + .{ c.pa_api, 112 }, .{ c.pa_out, 16 }, .{ c.pa_word, 32 }, .{ c.pa_head, 56 }, + .{ c.pa_ops, 208 }, .{ c.pa_view, 32 }, .{ c.pa_tick, 128 }, }) |r| if (@sizeOf(r[0]) != r[1]) @compileError(std.fmt.comptimePrint("{s} is {d} bytes, the header says {d}", .{ @typeName(r[0]), @sizeOf(r[0]), r[1] })); } @@ -119,7 +119,6 @@ pub const Registry = struct { pub const take = Addon.take; pub const collides = Addon.collides; pub const drop = Addon.drop; - }; // ---- a pane of a kind ---- @@ -389,7 +388,7 @@ pub fn draw(p: *Pardes, s: *surface.Surface, arena: std.mem.Allocator, pane: *Pa var frame: Frame = .{ .cols = cols, .rows = rows }; if (slot.ops == null and slot.live) { const sh = slot.shadow orelse return; - frame = .{ .cells = sh.cells, .cols = sh.cols, .rows = sh.rows, .places = sh.places.items, .n = @intCast(sh.places.items.len) }; + frame = .{ .cells = sh.cells, .cols = sh.cols, .rows = sh.rows, .places = sh.places.items, .n = @intCast(sh.places.items.len), .gpu = sh.gpu }; } else if (slot.ops == null) { var line: [160]u8 = undefined; const why = if (slot.refused.len > 0) slot.refused.slice() else "Addon load <path>"; @@ -398,6 +397,7 @@ pub fn draw(p: *Pardes, s: *surface.Surface, arena: std.mem.Allocator, pane: *Pa _ = s.print(x, y, cols, text, .{ .fg = fg, .bg = bg }); return; } else frame.cells = (paint(p, slot, id, arena, cols, rows, &frame) orelse return); + if (frame.gpu.len != 0) s.gpu_frames[id] = .{ .bytes = frame.gpu, .serial = pane.serial, .dst = .{ .x = x, .y = y, .w = cols, .h = rows } }; for (0..@min(rows, frame.rows)) |r| for (0..@min(cols, frame.cols)) |col| { const cell = &frame.cells[r * frame.cols + col]; if (cell.flags & c.PA_PAINTED == 0) continue; @@ -423,6 +423,7 @@ pub fn draw(p: *Pardes, s: *surface.Surface, arena: std.mem.Allocator, pane: *Pa /// A frame of a kind's pane: its cells, `cols` a row, and its placements. pub const Frame = struct { + gpu: []const u8 = &.{}, cells: []c.pa_cell = &.{}, cols: u16, rows: u16, @@ -438,7 +439,8 @@ pub fn paint(p: *const Pardes, slot: *Slot, id: usize, arena: std.mem.Allocator, const ops = slot.ops orelse return null; const cells = arena.alloc(c.pa_cell, @as(usize, cols) * rows) catch return null; @memset(std.mem.sliceAsBytes(cells), 0); - var out: c.pa_paint = std.mem.zeroInit(c.pa_paint, .{ .placements = &frame.buf, .cap = frame.buf.len }); + var gpu: GpuPaint = .{ .arena = arena, .frame = frame }; + var out: c.pa_paint = std.mem.zeroInit(c.pa_paint, .{ .placements = &frame.buf, .cap = frame.buf.len, .gpu = GpuPaint.emit, .gpu_ctx = &gpu }); const px = p.view().cell_pixels; const win = std.mem.zeroInit(c.pa_window, .{ .cells = cells.ptr, .stride = cols, .rows = rows, .cols = cols, .cell_w = px.w, .cell_h = px.h, .focused = @intFromBool(focusedAnywhere(p, id)), .view = p.live + 1, .glyphs = @intFromBool(!p.view().frontend.native_images) }); var cl: Call = .{ .p = null, .id = 0, .slot = slot, .quiet = true }; @@ -1206,3 +1208,14 @@ test "a kind's head is checked before a core takes it, and a core's kinds are it a.drop(a.byName("zzzab").?); try std.testing.expect(a.byName("zzzab") == null); } + +const GpuPaint = struct { + arena: std.mem.Allocator, + frame: *Frame, + fn emit(ctx: ?*anyopaque, bytes: [*c]const u8, n: u32) callconv(.c) c_int { + const self: *GpuPaint = @ptrCast(@alignCast(ctx orelse return 1)); + if (bytes == null or n > 4 << 20) return 1; + self.frame.gpu = self.arena.dupe(u8, bytes[0..n]) catch return 1; + return 0; + } +}; diff --git a/src/Output.zig b/src/Output.zig index bb75e29f..0c6fdfc2 100644 --- a/src/Output.zig +++ b/src/Output.zig @@ -15,6 +15,7 @@ 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; @@ -439,6 +440,8 @@ 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; o.from = from; p.fs.refilled = rp.serial; try setArg(o, arg); @@ -497,7 +500,18 @@ pub fn openDiff(p: *Pardes, id: usize, path: []const u8, content: []const u8) !u 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; - return fillRows(p, id, root, .{ .cmd = .Diff }, arg, result.content, result.rows, null); + 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 diff --git a/src/Query.zig b/src/Query.zig index 5a66a0a3..caf64d54 100644 --- a/src/Query.zig +++ b/src/Query.zig @@ -789,7 +789,7 @@ fn recentRows(p: *Pardes, out: *std.Io.Writer.Allocating) []const u8 { /// ponytail: no grouping for a big file until the disk engine's worker /// parses it (phase 4). fn ownerDecls(p: *Pardes, f: *File.State, small: bool) ?[]const syntax.ContextDeclaration { - if (f.context_revision) |rev| if (rev == f.revision and f.context_declarations.len > 0) return f.context_declarations; + if (f.context.revision) |rev| if (rev == f.revision and f.context.declarations.len > 0) return f.context.declarations; const cache = &p.locations_cache; for (cache.entries[0..cache.len]) |entry| { if (entry.declarations_ready and std.mem.eql(u8, entry.path, f.path) and std.mem.eql(u8, entry.source, f.content)) return entry.analysis.declarations; @@ -2649,7 +2649,7 @@ test "a query row's place is its text: the match tinted after it, B3 on it opens File.setContent(p, &sp.file.?, try p.gpa.dupe(u8, saved)); try std.testing.expect(sp.query == null and sp.file.?.location_rows.len == 0); const at = std.mem.indexOf(u8, saved, "a.txt:2:5").?; - const line = saved[at .. std.mem.indexOfScalarPos(u8, saved, at, '\n').?]; + const line = saved[at..std.mem.indexOfScalarPos(u8, saved, at, '\n').?]; const word = look.expandedWord(line, 3).?; a.body.cur_row = 0; look.lookAt(p, sid, line[word.lo..word.hi]); diff --git a/src/Stream.zig b/src/Stream.zig index 11fa7a31..abdf9afa 100644 --- a/src/Stream.zig +++ b/src/Stream.zig @@ -716,7 +716,7 @@ pub fn receive(p: *Pardes, b: *const Batch) void { } /// A parse's answer: its task joined; the declarations kept as the pane's -/// (File.State.context_declarations, for its revision) when its text is +/// (File.State.context.declarations, for its revision) when its text is /// still what was parsed; the query panes of that text told; and a parse /// asked for while it ran started. fn receiveParse(p: *Pardes, b: *const Batch, serial: u32, revision: u32) void { @@ -729,9 +729,7 @@ fn receiveParse(p: *Pardes, b: *const Batch, serial: u32, revision: u32) void { s.parse_ns = b.took_ns; if (p.paneBySerial(serial)) |id| if (p.panes[id].?.file) |*f| if (f.revision == revision and b.decls.len > 0) { if (p.tree_sitter_gpa.dupe(syntax.ContextDeclaration, b.decls)) |copy| { - if (f.context_declarations.len > 0) p.tree_sitter_gpa.free(f.context_declarations); - f.context_declarations = copy; - f.context_revision = revision; + f.context.replace(p.tree_sitter_gpa, copy, revision); panes.Query.declsArrived(p, serial); } else |_| {} }; @@ -1303,7 +1301,7 @@ test "Stream: a big text's declarations are parsed on a worker, never the loop, try testing.expect(p.stream.parse != null); try testing.expect(std.mem.indexOf(u8, qp.file.?.content, "fn f") == null); const until = std.Io.Clock.awake.now(testing.io).toMilliseconds() + 60_000; - while (pane.file.?.context_revision == null or pane.file.?.context_revision.? != pane.file.?.revision) { + while (pane.file.?.context.revision == null or pane.file.?.context.revision.? != pane.file.?.revision) { if (std.Io.Clock.awake.now(testing.io).toMilliseconds() > until) return error.Timeout; shell.pump(p); p.update(.tick); 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/colors.zig b/src/colors.zig index e679f4a5..1713ba24 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 (ghostty-vt'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); diff --git a/src/diff.zig b/src/diff.zig index ed54c149..659576d3 100644 --- a/src/diff.zig +++ b/src/diff.zig @@ -8,6 +8,21 @@ //! taken for a file header. const std = @import("std"); +/// The commit named by git show, format-patch or jj show's leading header. +pub fn commitHash(content: []const u8) ?[]const u8 { + const line = content[0 .. std.mem.indexOfScalar(u8, content, '\n') orelse content.len]; + inline for (.{ "commit ", "From ", "Commit ID: " }) |prefix| { + if (std.mem.startsWith(u8, line, prefix)) { + var words = std.mem.tokenizeAny(u8, line[prefix.len..], " \t\r"); + const hash = words.next() orelse return null; + if (hash.len < 7 or hash.len > 64) return null; + for (hash) |c| if (!std.ascii.isHex(c)) return null; + return hash; + } + } + return null; +} + pub const Kind = enum { /// Anything outside a file header and a hunk: a commit message, /// `Only in ...`, a mail's headers. @@ -653,3 +668,12 @@ test "diff a section's paths are the repository's names under every prefix git w try testing.expectEqualStrings("/dev/null", made[0]); try testing.expectEqualStrings("n.zig", made[1]); } + +test "diff commit headers retain the full hash, not message or hunk text" { + const hash = "0123456789abcdef0123456789abcdef01234567"; + try std.testing.expectEqualStrings(hash, commitHash("commit " ++ hash ++ " (HEAD -> main)\nmessage").?); + try std.testing.expectEqualStrings(hash, commitHash("From " ++ hash ++ " Mon Sep 17 00:00:00 2001\n").?); + try std.testing.expectEqualStrings(hash, commitHash("Commit ID: " ++ hash ++ "\nChange ID: xyz").?); + inline for (.{ "commit ", "commit nope123", "From 1234\n", "@@ -1 +1 @@\n+commit " ++ hash }) |text| + try std.testing.expectEqual(@as(?[]const u8, null), commitHash(text)); +} diff --git a/src/draw.zig b/src/draw.zig index 4809ebd4..2fabff06 100644 --- a/src/draw.zig +++ b/src/draw.zig @@ -4,7 +4,6 @@ //! chips, the workspace and column tags, the tag layers, drag overlays, the //! debug box, then the cursor. const std = @import("std"); -const vaxis = @import("vaxis"); const pardes = @import("pardes.zig"); const layout = @import("layout.zig"); const config = @import("config.zig"); @@ -268,6 +267,7 @@ pub fn render(p: *Pardes, arena: std.mem.Allocator) !*Surface { for (&s.body_layers) |*layer| layer.rows = 0; for (&s.tag_layers) |*layer| layer.rows = 0; s.placements.clearRetainingCapacity(); + @memset(&s.gpu_frames, null); const chrome = p.chromeTheme(); s.chrome = .{ .page = p.theme().bg, @@ -1236,7 +1236,7 @@ test "a wide glyph cut by a tag's or a notice's edge is joined into the grid as const head = !cell.default and cell.len > 1 and i + 1 < row.len and !row[i + 1].default and row[i + 1].len == 0; // A spacer has its head before it; a head its spacer after. if (spacer) try std.testing.expect(i > 0 and row[i - 1].len > 1); - if (i + 1 == row.len) try std.testing.expect(!head and !(cell.len > 1 and vaxis.gwidth.gwidth(cell.grapheme(), .unicode) == 2)); + if (i + 1 == row.len) try std.testing.expect(!head and !(cell.len > 1 and panes.File.utf8Width(cell.grapheme()) == 2)); } // The right edge of each is the band, blank where a glyph was cut. try std.testing.expectEqual(FontRole.tagline, row[row.len - 1].style.font_role); diff --git a/src/dump.zig b/src/dump.zig index 517544fa..a880c7e1 100644 --- a/src/dump.zig +++ b/src/dump.zig @@ -747,6 +747,7 @@ pub fn loadPane(p: *Pardes, id: usize, bytes: []const u8) !*pardes.panes.Pane { const SlotRecord = struct { name: []const u8 = "", version: u32 = 0, + gen: u32 = 0, path: []const u8 = "", where: []const u8 = "", art: @import("surface.zig").Placement.Art = .{}, @@ -774,7 +775,7 @@ const SlotRecord = struct { pub fn slotWrite(s: *const Kind.Slot, gpa: std.mem.Allocator, w: *std.Io.Writer) !void { var place: [32]u8 = undefined; - var r: SlotRecord = .{ .name = s.nameOf(), .version = s.version, .path = s.path, .art = s.art, .record = s.record, .where = s.where_text.slice(), .values = s.values.slice(), .live = s.live, .next_tick = s.next_tick, .views = s.views, .focused = s.focused, .cancelled = s.cancelled, .prefix = s.prefix.slice(), .refused = s.refused.slice(), .tail = s.tail.slice(), .selection = s.selection }; + var r: SlotRecord = .{ .name = s.nameOf(), .version = s.version, .gen = s.gen, .path = s.path, .art = s.art, .record = s.record, .where = s.where_text.slice(), .values = s.values.slice(), .live = s.live, .next_tick = s.next_tick, .views = s.views, .focused = s.focused, .cancelled = s.cancelled, .prefix = s.prefix.slice(), .refused = s.refused.slice(), .tail = s.tail.slice(), .selection = s.selection }; var owned: ?[]u8 = null; defer if (owned) |o| s.gpa.free(o); if (s.ops != null) { @@ -806,7 +807,7 @@ pub fn slotRead(out: *Kind.Slot, gpa: std.mem.Allocator, bytes: []const u8) !voi var arena: std.heap.ArenaAllocator = .init(gpa); defer arena.deinit(); const r = try walk.load(SlotRecord, arena.allocator(), bytes, null); - out.* = .{ .gpa = gpa, .arena = .init(gpa), .version = r.version, .art = r.art, .live = r.live, .next_tick = r.next_tick, .views = r.views, .focused = r.focused, .cancelled = r.cancelled }; + out.* = .{ .gpa = gpa, .arena = .init(gpa), .version = r.version, .gen = r.gen, .art = r.art, .live = r.live, .next_tick = r.next_tick, .views = r.views, .focused = r.focused, .cancelled = r.cancelled }; errdefer out.free(); @memcpy(out.name[0..@min(15, r.name.len)], r.name[0..@min(15, r.name.len)]); out.path = try gpa.dupe(u8, r.path); @@ -844,11 +845,14 @@ pub fn reviveSlot(p: *Pardes, id: usize, s: *Kind.Slot) void { if (!Kind.reopen(p, id, s, bytes)) { s.ops = null; s.live = false; - } else if (s.ops == null) { - // A replica's Shadow is the authority's pane as it is: it ticks - // when that one does, not because it was loaded (a kind opened - // here ticks to lay itself out). - s.next_tick, s.views, s.focused = kept; + } else { + s.version = p.kinds.kinds[k].version; + if (s.ops == null) { + // A replica's Shadow is the authority's pane as it is: it ticks + // when that one does, not because it was loaded (a kind opened + // here ticks to lay itself out). + s.next_tick, s.views, s.focused = kept; + } } } @@ -1125,3 +1129,60 @@ test "an old dump's file, a byte dump, is read by -l and by a Restore of its pat defer gpa.free(again); try std.testing.expectEqualSlices(u8, bytes, again); } + +test "restored syntax context caches are rebuilt rather than loaded with the core allocator" { + const gpa = std.testing.allocator; + var syntax_gpa: std.heap.DebugAllocator(.{}) = .init; + defer std.testing.expect(syntax_gpa.deinit() == .ok) catch @panic("syntax allocator leaked"); + const opts: Pardes.Options = .{ .tty_only = true, .tree_sitter_allocator = syntax_gpa.allocator() }; + const p = try Pardes.init(gpa, opts); + defer p.deinit(); + const pane = try p.setTestFile("fn example() void {}\n"); + const f = &pane.file.?; + const declarations = try p.tree_sitter_gpa.alloc(pardes.syntax.ContextDeclaration, 1); + @memset(std.mem.sliceAsBytes(declarations), 0); + f.context.replace(p.tree_sitter_gpa, declarations, f.revision); + // Older builds persisted these two fields; the schema reader must skip them too. + const OldFile = struct { + path: []const u8, + content: []const u8, + history: *pardes.panes.File.History, + context_declarations: []pardes.syntax.ContextDeclaration, + context_revision: ?u32, + }; + const old_bytes = try walk.save(OldFile, gpa, &.{ + .path = f.path, + .content = f.content, + .history = f.history, + .context_declarations = f.context.declarations, + .context_revision = f.context.revision, + }); + defer gpa.free(old_bytes); + var arena: std.heap.ArenaAllocator = .init(gpa); + defer arena.deinit(); + const old = try walk.load(pardes.panes.File.State, arena.allocator(), old_bytes, null); + try std.testing.expectEqual(@as(usize, 0), old.context.declarations.len); + try std.testing.expectEqual(@as(?u32, null), old.context.revision); + const bytes = try dumpBytes(p); + defer gpa.free(bytes); + const q = try load(gpa, opts, bytes, null); + defer q.deinit(); + for (q.panes) |slot| if (slot) |restored| if (restored.file) |file| { + try std.testing.expectEqual(@as(usize, 0), file.context.declarations.len); + try std.testing.expectEqual(@as(?u32, null), file.context.revision); + }; +} + +test "optional GPU addon reload generation survives a replica dump" { + const gpa = std.testing.allocator; + var original: Kind.Slot = .{ .gpa = gpa, .arena = .init(gpa), .gen = 7, .live = true }; + defer original.free(); + var bytes: std.Io.Writer.Allocating = .init(gpa); + defer bytes.deinit(); + try slotWrite(&original, gpa, &bytes.writer); + var restored: Kind.Slot = undefined; + try slotRead(&restored, gpa, bytes.written()); + defer restored.free(); + try std.testing.expectEqual(original.gen, restored.gen); + try std.testing.expectEqual(walk.digest(Kind.Slot, &original), walk.digest(Kind.Slot, &restored)); +} 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 120a4595..45157dd3 100644 --- a/src/gui/gui.zig +++ b/src/gui/gui.zig @@ -1,3 +1,5 @@ +const SketchGpu = @import("sketch_gpu"); +const GpuScene = @import("gpu_scene"); const filesystem = @import("../fs.zig"); const std = @import("std"); const builtin = @import("builtin"); @@ -5,7 +7,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"); @@ -286,6 +287,7 @@ const ImageInstance = extern struct { const opaque_bg_bit: u32 = 0x2000_0000; const PreparedImage = struct { + premultiplied: bool = false, place: pardes.Placement, texture: *c.SDL_GPUTexture, }; @@ -517,6 +519,11 @@ fn watchThread(fd: c_int, stop: c_int, q: *Queue) void { } const Gui = struct { + addon_gpu: ?SketchGpu = null, + addon_hash: [pardes.MAX_PANES]u64 = @splat(0), + addon_serial: [pardes.MAX_PANES]u32 = @splat(0), + addon_failed: [pardes.MAX_PANES]u64 = @splat(0), + addon_pipeline: ?*c.SDL_GPUGraphicsPipeline = null, window: *c.SDL_Window, device: *c.SDL_GPUDevice, swapchain_format: c.SDL_GPUTextureFormat, @@ -1229,6 +1236,8 @@ fn runNative(init: std.process.Init, opts_in: pardes.Options, headless: bool, di defer g.glyphs.deinit(); defer g.words.deinit(gpa); defer { + if (g.addon_gpu) |*gpu| gpu.deinit(); + if (g.addon_pipeline) |pipeline_| c.SDL_ReleaseGPUGraphicsPipeline(device, pipeline_); clearNativeImages(&g); g.native_images.deinit(gpa); g.prepared_images.deinit(gpa); @@ -4378,6 +4387,7 @@ fn prepareNativeImages( // The pictures are the page's: the other groups float over them. for (surface.placements.items) |place| if (texturePlacement(place)) appendPreparedImage(g, gpa, place); + prepareAddonGpu(g, gpa, cmd, surface); groups.items[0].image_start = 0; groups.items[0].image_count = std.math.cast(u32, g.prepared_images.items.len) orelse return false; @@ -4425,6 +4435,7 @@ fn drawNativeImagesGpu( var idx = batch.image_start; const end = batch.image_start + batch.image_count; for (g.prepared_images.items[batch.image_start..end]) |prepared| { + c.SDL_BindGPUGraphicsPipeline(pass, if (prepared.premultiplied) g.addon_pipeline.? else g.image_pipeline); const clip = imageScissor(g, prepared.place); if (clip.w > 0 and clip.h > 0) { c.SDL_SetGPUScissor(pass, &clip); @@ -4750,12 +4761,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; @@ -5127,11 +5138,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 ' '; @@ -9135,3 +9141,62 @@ test "detached trackpad scrolling keeps fractions local and queues whole rows fo core.update(client.pending.items[0]); try std.testing.expectEqual(@as(f32, 1.125), @as(f32, @floatFromInt(core.panes[id].?.scroll() - before)) + g.scroll_lag); } + +/// Render addon scenes to textures on this device, before the page's pass. +/// The fallback cells remain visible if decoding or pipeline creation fails. +fn prepareAddonGpu(g: *Gui, gpa: std.mem.Allocator, cmd: *c.SDL_GPUCommandBuffer, surface: *const pardes.Surface) void { + for (surface.gpu_frames, 0..) |maybe, id| { + const scratch: GpuScene.abi.Image = @fromBackingInt(@intCast(pardes.MAX_PANES + id + 1)); + const frame = maybe orelse { + if (g.addon_gpu) |*gpu| { + gpu.forget(@fromBackingInt(@intCast(id + 1))); + gpu.forget(scratch); + } + g.addon_hash[id] = 0; + g.addon_serial[id] = 0; + g.addon_failed[id] = 0; + continue; + }; + const hash = std.hash.Wyhash.hash(frame.serial, frame.bytes); + if (g.addon_failed[id] == hash) continue; + if (g.addon_gpu == null) g.addon_gpu = .init(gpa, g.device); + const gpu = &g.addon_gpu.?; + const target: GpuScene.abi.Image = @fromBackingInt(@intCast(id + 1)); + if (g.addon_hash[id] != hash or g.addon_serial[id] != frame.serial) { + var arena: std.heap.ArenaAllocator = .init(gpa); + defer arena.deinit(); + var scene = GpuScene.decodeFrame(arena.allocator(), frame.bytes) catch |err| { + log.warn("addon GPU scene: {t}", .{err}); + g.addon_failed[id] = hash; + continue; + }; + scene.pass.image = if (scene.post != null) scratch else target; + gpu.record(cmd, scene.pass) catch |err| { + log.warn("addon GPU render: {t}", .{err}); + g.addon_failed[id] = hash; + continue; + }; + if (scene.post) |post| { + gpu.postProcess(cmd, scratch, target, post) catch |err| { + log.warn("addon GPU postprocess: {t}", .{err}); + g.addon_failed[id] = hash; + continue; + }; + } else gpu.forget(scratch); + g.addon_hash[id] = hash; + g.addon_serial[id] = frame.serial; + } + const out = gpu.output(target) orelse continue; + if (g.addon_pipeline == null) { + var blend = backgroundLayerBlend(); + blend.src_color_blendfactor = c.SDL_GPU_BLENDFACTOR_ONE; + g.addon_pipeline = makePipeline(g.device, g.swapchain_format, image_vert_spv, image_frag_spv, 1, 1, image_input, blend) catch continue; + } + g.prepared_images.append(gpa, .{ + .premultiplied = true, + .texture = out.texture, + .place = .{ .pane = @intCast(id), .raster = .{ .ptr = undefined, .w = out.width, .h = out.height, .stride = out.width * 4 }, .src = .{ .x = 0, .y = 0, .w = out.width, .h = out.height }, .dst = frame.dst, .key = hash }, + }) catch {}; + } + if (g.addon_gpu) |*gpu| gpu.endFrame(); +} diff --git a/src/hunks.zig b/src/hunks.zig index 00fe265b..8f4b4233 100644 --- a/src/hunks.zig +++ b/src/hunks.zig @@ -804,3 +804,36 @@ test "a hunk edited since, beside siblings with its signature's tail, is found i defer locations.freeRows(p.gpa, result.rows); try testing.expect(std.mem.indexOf(u8, result.content, "a.rs:12\n fn three(\na.rs:15 *\n") != null); } + +test "patch panes keep different commits and reuse only the same commit" { + const p = try Pardes.init(testing.allocator, .{ .tty_only = true }); + defer p.deinit(); + const Page = struct { + fn open(pp: *Pardes, hash: []const u8) !usize { + const id = try pardes.panes.Output.openPager(pp, 0, "/pardes-patch-test"); + var held: std.ArrayList(u8) = .empty; + defer held.deinit(pp.gpa); + try held.print(pp.gpa, "commit {s}\ndiff --git a/x b/x\n--- a/x\n+++ b/x\n@@ -1 +1 @@\n-old\n+new\n", .{hash}); + try @import("ninep/ctl.zig").fillPager(pp, pp.panes[id].?.serial, &held); + for (pp.panes, 0..) |slot, i| { + const f = (slot orelse continue).file orelse continue; + const output = f.output orelse continue; + if (std.meta.eql(output.from, pardes.panes.Output.Origin{ .cmd = .Diff }) and + std.mem.indexOf(u8, f.content, hash) != null) return i; + } + return error.MissingDiff; + } + }; + const a = "0123456789abcdef0123456789abcdef01234567"; + const b = "fedcba9876543210fedcba9876543210fedcba98"; + const first = try Page.open(p, a); + const original = try testing.allocator.dupe(u8, p.panes[first].?.file.?.content); + defer testing.allocator.free(original); + const second = try Page.open(p, b); + try testing.expect(first != second); + try testing.expectEqualStrings(original, p.panes[first].?.file.?.content); + try testing.expectEqualStrings("/pardes-patch-test/+Diff-0123456789ab", p.panes[first].?.file.?.path); + try testing.expectEqualStrings("/pardes-patch-test/+Diff-fedcba987654", p.panes[second].?.file.?.path); + try testing.expectEqual(first, try Page.open(p, a)); + try testing.expectEqualStrings(original, p.panes[first].?.file.?.content); +} diff --git a/src/kinds/addon.zig b/src/kinds/addon.zig index 11635f7a..54f26893 100644 --- a/src/kinds/addon.zig +++ b/src/kinds/addon.zig @@ -36,9 +36,9 @@ pub const c = @import("pardes_addon"); const Allocator = std.mem.Allocator; /// The ABI this file speaks: a header of another needs it brought along. -pub const abi = 0x30000; +pub const abi = 0x30001; comptime { - if (c.PA_ABI != abi) @compileError("addon.zig speaks ABI 3.0 and the header another"); + if (c.PA_ABI != abi) @compileError("addon.zig speaks ABI 3.1 and the header another"); } /// A word the kind brings: `opens` a pane of it, else goes to the pane's @@ -157,6 +157,12 @@ pub const Window = struct { /// as the header has them. pub const Paint = struct { out: *c.pa_paint, + /// Optional display data; always paint a text/raster fallback too. + pub fn gpu(p: Paint, bytes: []const u8) bool { + if (api.abi < 0x00030001 or bytes.len > 4 << 20) return false; + const emit = p.out.gpu orelse return false; + return emit(p.out.gpu_ctx, bytes.ptr, @intCast(bytes.len)) == c.PA_OK; + } /// A picture over the cells (pa_placement), lowest first. pub fn place(p: Paint, at: c.pa_placement) void { if (p.out.n == p.out.cap) return; @@ -349,10 +355,10 @@ pub fn ops(comptime T: type) c.pa_ops { var o: c.pa_ops = .{ .init = F.init, .open = F.open, .paint = F.paint, .head = .{ .size = @sizeOf(c.pa_head), .abi = c.PA_ABI, .name = name, .version = T.head.version, .flags = if (T.head.pictures) c.PA_PICTURES else 0, .exts = T.head.exts, .words = &F.words, .nwords = F.words.len } }; // The kind's function, then the pa_ops field its wrapper fills. const fns = .{ - .{ "close", "close" }, .{ "tick", "tick" }, .{ "prefix", "tick" }, .{ "view", "view" }, .{ "key", "key" }, - .{ "mouse", "mouse" }, .{ "body", "body_len" }, .{ "body", "body" }, .{ "address", "address" }, .{ "where", "where" }, - .{ "ctl", "ctl" }, .{ "ctlRead", "ctl_read" }, .{ "jobRun", "job_run" }, .{ "jobDone", "job_done" }, .{ "dump", "dump" }, - .{ "load", "load" }, .{ "search", "search" }, + .{ "close", "close" }, .{ "tick", "tick" }, .{ "prefix", "tick" }, .{ "view", "view" }, .{ "key", "key" }, + .{ "mouse", "mouse" }, .{ "body", "body_len" }, .{ "body", "body" }, .{ "address", "address" }, .{ "where", "where" }, + .{ "ctl", "ctl" }, .{ "ctlRead", "ctl_read" }, .{ "jobRun", "job_run" }, .{ "jobDone", "job_done" }, .{ "dump", "dump" }, + .{ "load", "load" }, .{ "search", "search" }, }; inline for (fns) |m| if (@hasDecl(T, m[0])) { @field(o, m[1]) = @field(F, m[1]); diff --git a/src/kinds/pardes_addon.h b/src/kinds/pardes_addon.h index c3bfb354..9c101fee 100644 --- a/src/kinds/pardes_addon.h +++ b/src/kinds/pardes_addon.h @@ -37,7 +37,7 @@ /* Major in the high half: an addon of another major is refused. */ #define PA_ABI_MAJOR 3u -#define PA_ABI_MINOR 0u +#define PA_ABI_MINOR 1u #define PA_ABI ((PA_ABI_MAJOR << 16) | PA_ABI_MINOR) #define PA_OK 0 #define PA_RASTER_MAX (32u << 20) /* a placement's w*h*4 above this is dropped, said once */ @@ -121,6 +121,14 @@ typedef struct pa_paint { uint32_t cap, n; float at, span; uint32_t pointer, pad; + /* Optional since 3.1: one sketchbook SGPU v1 scene for this pane. + * Check api->abi >= 3.1 BEFORE reading these fields on an older host. + * NULL means unsupported. Copies bytes during the call (stack is OK); + * returns PA_OK or refuses. At most 4 MiB, last successful call wins. + * Keep cells/rasters as fallback: accepting a scene does not promise a + * GPU in every view. GPU scenes are display data, never saved state. */ + int (*gpu)(void *ctx, const uint8_t *bytes, uint32_t n); + void *gpu_ctx; } pa_paint; /* ---- input ---- */ @@ -352,7 +360,7 @@ _Static_assert(sizeof(pa_cell) == 20, "pa_cell"); _Static_assert(sizeof(pa_window) == 24, "pa_window"); _Static_assert(sizeof(pa_rect) == 16 && sizeof(pa_cells) == 8, "pa_rect"); _Static_assert(sizeof(pa_placement) == 80, "pa_placement"); -_Static_assert(sizeof(pa_paint) == 32 && sizeof(pa_view) == 32 && sizeof(pa_tick) == 128, "pa_paint"); +_Static_assert(sizeof(pa_paint) == 48 && sizeof(pa_view) == 32 && sizeof(pa_tick) == 128, "pa_paint"); _Static_assert(sizeof(pa_key) == 8 && sizeof(pa_mouse) == 16, "pa_key"); _Static_assert(sizeof(pa_api) == 112 && sizeof(pa_out) == 16, "pa_api"); _Static_assert(sizeof(pa_word) == 32 && sizeof(pa_head) == 56, "pa_head"); diff --git a/src/lsp/lsp_client.zig b/src/lsp/lsp_client.zig index cad75c57..097bddf2 100644 --- a/src/lsp/lsp_client.zig +++ b/src/lsp/lsp_client.zig @@ -774,16 +774,21 @@ fn answer(io: std.Io, arena: std.mem.Allocator, si: usize, req: lsp.Req, out: *s const g = try ensure(c, io, si, arena, req, tr); const before = out.end; try attempt(c, io, si, arena, req, out, tr, g); - // A server still loading its workspace answers at once, with nothing - // (rust-analyzer before its index): that is no answer. Wait until it says - // it is loaded, the message row saying so, and ask again. + // An empty answer can beat the startup progress notification onto the wire. const answered = out.buffered()[before..]; - if (c.loading and c.gen == g and (answered.len == 0 or std.mem.startsWith(u8, answered, "@none "))) { - tr.note("{s} is still loading: waiting for it, then asking again", .{specs[si].name}); - post(si, .always, "{s} is still loading the workspace; the answer comes when it is done\u{2026}", .{specs[si].name}); - while (c.loading and c.gen == g and c.alive()) _ = try timedWait(c, io, nowMs() + 500); - out.end = before; - try attempt(c, io, si, arena, req, out, tr, g); + if (c.gen == g and (answered.len == 0 or std.mem.startsWith(u8, answered, "@none "))) { + const startup_deadline = c.ready_at_ms + 250; + const starting = nowMs() < startup_deadline; + while (starting and !c.loading and c.progress == 0 and c.gen == g and c.alive()) { + if (!try timedWait(c, io, startup_deadline)) break; + } + if (starting or c.loading or c.progress > 0) { + tr.note("{s} is still loading: waiting for it, then asking again", .{specs[si].name}); + post(si, .always, "{s} is still loading the workspace; the answer comes when it is done\u{2026}", .{specs[si].name}); + while ((c.loading or c.progress > 0) and c.gen == g and c.alive()) _ = try timedWait(c, io, nowMs() + 500); + out.end = before; + try attempt(c, io, si, arena, req, out, tr, g); + } } } @@ -1866,19 +1871,29 @@ fn rootOf(dir: []const u8, markers: []const []const u8) []const u8 { } /// The spec's binary: the env override when set, else `bin`, PATH-searched -/// unless it names a path. +/// unless it names a path, then the standard per-user bin directory. fn binOf(spec: *const Spec, buf: *[4096:0]u8) ?[:0]const u8 { const name = if (libc.getenv(spec.env)) |v| std.mem.span(v) else spec.bin; + const path = if (libc.getenv("PATH")) |p| std.mem.span(p) else "/usr/local/bin:/usr/bin:/bin"; + const home = if (libc.getenv("HOME")) |p| std.mem.span(p) else ""; + return findBin(name, path, home, buf); +} + +fn findBin(name: []const u8, path: []const u8, home: []const u8, buf: *[4096:0]u8) ?[:0]const u8 { if (name.len == 0) return null; if (std.mem.indexOfScalar(u8, name, '/') != null) { const z = std.fmt.bufPrintSentinel(buf, "{s}", .{name}, 0) catch return null; - return if (libc.access(z.ptr, libc.X_OK) == 0) z else null; + return if (libc.access(z.ptr, libc.X_OK) == 0 and !@import("../host_io.zig").Shell.isDirectory(z.ptr)) z else null; } - const path = if (libc.getenv("PATH")) |p| std.mem.span(p) else "/usr/local/bin:/usr/bin:/bin"; var it = std.mem.tokenizeScalar(u8, path, ':'); while (it.next()) |dir| { const cand = std.fmt.bufPrintSentinel(buf, "{s}/{s}", .{ dir, name }, 0) catch continue; - if (libc.access(cand.ptr, libc.X_OK) == 0) return cand; + if (libc.access(cand.ptr, libc.X_OK) == 0 and !@import("../host_io.zig").Shell.isDirectory(cand.ptr)) return cand; + } + // Desktop launchers often omit ~/.local/bin even when shells include it. + if (std.fs.path.isAbsolute(home)) { + const cand = std.fmt.bufPrintSentinel(buf, "{s}/.local/bin/{s}", .{ home, name }, 0) catch return null; + if (libc.access(cand.ptr, libc.X_OK) == 0 and !@import("../host_io.zig").Shell.isDirectory(cand.ptr)) return cand; } return null; } @@ -2495,6 +2510,7 @@ fn notification(c: *Conn, io: std.Io, si: usize, g: u32, raw: []const u8, method } if (std.mem.eql(u8, pkind, "begin")) { c.progress += 1; + c.cond.broadcast(io); const title = str(get(value, "title")) orelse ""; c.title_len = @intCast(@min(title.len, c.title.len)); @memcpy(c.title[0..c.title_len], title[0..c.title_len]); @@ -2521,6 +2537,7 @@ fn notification(c: *Conn, io: std.Io, si: usize, g: u32, raw: []const u8, method c.progress -= 1; const idle = c.progress <= 0; if (idle) c.progress = 0; + c.cond.broadcast(io); c.mu.unlock(io); // the setpoint every burst of progress ends on; `.always` + the // dedupe above means it lands exactly once however the reports raced @@ -2997,6 +3014,29 @@ test "rootOf takes the top-most marker and falls back to git then dir" { try std.testing.expect(std.mem.startsWith(u8, deep, nothing)); } +test "language server discovery honours PATH and overrides before the user bin directory" { + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + const io = std.testing.io; + try tmp.dir.createDirPath(io, ".local/bin"); + try tmp.dir.createDirPath(io, "path-bin"); + for ([_][]const u8{ ".local/bin/zls", "path-bin/zls" }) |path| { + const file = try tmp.dir.createFile(io, path, .{ .permissions = .fromMode(0o700) }); + file.close(io); + } + var home_buf: [4096]u8 = undefined; + const home = home_buf[0..try tmp.dir.realPath(io, &home_buf)]; + var path_buf: [4096]u8 = undefined; + const path = try std.fmt.bufPrint(&path_buf, "{s}/path-bin", .{home}); + var out: [4096:0]u8 = undefined; + try std.testing.expect(std.mem.endsWith(u8, findBin("zls", path, home, &out).?, "/path-bin/zls")); + try std.testing.expect(std.mem.endsWith(u8, findBin("zls", "/no-such-bin", home, &out).?, "/.local/bin/zls")); + try std.testing.expect(findBin("", path, home, &out) == null); + try std.testing.expect(findBin("/no-such-bin/zls", path, home, &out) == null); + try std.testing.expect(findBin("zls", "", "", &out) == null); + try std.testing.expect(findBin(path, "", home, &out) == null); // a directory is not executable code +} + test "specFor routes extensions and honours the disable env" { try std.testing.expect(specFor("/x/main.rs") != null); try std.testing.expect(specFor("/x/README.md") == null); diff --git a/src/ninep/ctl.zig b/src/ninep/ctl.zig index 699b7833..a72e7259 100644 --- a/src/ninep/ctl.zig +++ b/src/ninep/ctl.zig @@ -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 pager.zig's parse, 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 { diff --git a/src/ninep/pane.zig b/src/ninep/pane.zig index bb15b016..3fa45404 100644 --- a/src/ninep/pane.zig +++ b/src/ninep/pane.zig @@ -900,7 +900,7 @@ pub fn nameBuffer(p: *Pardes, id: usize, full: []const u8, preserve_tag: bool) ! f.highlights = &.{}; f.highlight_start = 0; f.syntax_dirty = true; - f.context_revision = null; + f.context.revision = null; pane.geometry_key = 0; look.invalidateLookHover(p, id); p.emit(.{ .watch = .{ .pane = @intCast(id), .on = false } }); diff --git a/src/pager.zig b/src/pager.zig index e4ccbab4..dd7e4032 100644 --- a/src/pager.zig +++ b/src/pager.zig @@ -1,13 +1,16 @@ //! A program's output, paged into a +Pager (`pardes -`): the text it -//! prints, and its SGR colours as spans over that text. ghostty-vt, which -//! terminal panes already drive, parses every escape; this keeps what is -//! printed and how SGR styles it, and drops every other control (cursor -//! motion, OSC titles and hyperlinks, modes). The spans are display state -//! of the pane only: no 9P file reads them (File.recolorSyntax draws them). +//! prints, and its SGR colours as spans over that text. It reads the bytes +//! as a terminal does (ECMA-48's parse as ghostty-vt's table has it, UTF-8 +//! with each ill-formed part one U+FFFD) and keeps what is printed, how SGR +//! styles it and the controls that move along a line (CR, LF, BS, HT and +//! CSI's CHT, REP and the return in CNL and CPL); every other sequence is +//! read to its end and dropped (cursor motion, OSC titles and hyperlinks, +//! DCS, APC, modes). The spans are display state of the pane only: no 9P +//! file reads them (File.recolorSyntax draws them). const std = @import("std"); const pardes = @import("pardes.zig"); const CellStyle = @import("surface.zig").CellStyle; -const ghostty_vt = @import("ghostty-vt"); +const Color = @import("surface.zig").Color; /// Bytes `start..end` of the text, drawn in `style`. A palette colour stays /// `.index`, resolved through the theme as it is drawn (terminal.palColor), @@ -35,15 +38,75 @@ pub fn parse(gpa: std.mem.Allocator, raw: []const u8) !Page { errdefer h.text.deinit(gpa); errdefer h.spans.deinit(gpa); try h.text.ensureTotalCapacity(gpa, raw.len); - var stream: ghostty_vt.Stream(*Handler) = .init(.{ .handler = &h }); - defer stream.deinit(); - stream.nextSlice(raw); + // The printed code points since the last control, printed as one run. + var run: [4096]u32 = undefined; + var n: usize = 0; + var state: State = .ground; + var i: usize = 0; + feed: while (i < raw.len) { + const c = raw[i]; + if (state != .ground or c == 0x1b) { + h.printRun(run[0..n]); + n = 0; + state = h.step(state, c); + i += 1; + continue; + } + // Printable ASCII, most of a page, straight into the run. + if (c >= 0x20 and c < 0x7f) { + const end = @min(raw.len, i + run.len - n); + while (i < end and raw[i] >= 0x20 and raw[i] < 0x7f) : (i += 1) { + run[n] = raw[i]; + n += 1; + } + if (n < run.len) continue; + h.printRun(&run); + n = 0; + continue; + } + // UTF-8: an ill-formed part (a stray byte, or the longest start of + // a sequence that does not go on) is one U+FFFD; one the input ends + // inside may yet go on, and is not printed. + var cp: u21 = c; + var len: usize = 1; + if (c >= 0x80) { + cp = 0xfffd; + if (c >= 0xc2 and c <= 0xf4) { + const want: usize = if (c < 0xe0) 2 else if (c < 0xf0) 3 else 4; + const lo: u8 = if (c == 0xe0) 0xa0 else if (c == 0xf0) 0x90 else 0x80; + const hi: u8 = if (c == 0xed) 0x9f else if (c == 0xf4) 0x8f else 0xbf; + var acc: u21 = c & (@as(u8, 0x7f) >> @intCast(want)); + while (len < want) : (len += 1) { + if (i + len == raw.len) break :feed; + const b = raw[i + len]; + if (b < (if (len == 1) lo else 0x80) or b > (if (len == 1) hi else 0xbf)) break; + acc = acc << 6 | (b & 0x3f); + } + if (len == want) cp = acc; + } + } + i += len; + // A C1 control that came as UTF-8 is dropped, as xterm drops it. + if (cp >= 0x20 and (cp < 0x80 or cp > 0x9f)) { + run[n] = cp; + n += 1; + if (n < run.len) continue; + } + h.printRun(run[0..n]); + n = 0; + if (cp < 0x20) h.execute(@intCast(cp)); + } + h.printRun(run[0..n]); if (h.failed) return error.OutOfMemory; const text = try h.text.toOwnedSlice(gpa); errdefer gpa.free(text); return .{ .text = text, .spans = try h.spans.toOwnedSlice(gpa) }; } +/// Where the parse is in a sequence: ECMA-48's states, the DCS's data and +/// its ignored tail one (`dcs_body`) and SOS, PM and APC one (`apc`). +const State = enum { ground, esc, esc_inter, csi_entry, csi_param, csi_inter, csi_ignore, osc, dcs_entry, dcs_param, dcs_inter, dcs_body, apc }; + const Handler = struct { gpa: std.mem.Allocator, text: std.ArrayList(u8) = .empty, @@ -60,43 +123,240 @@ const Handler = struct { /// A backspace: the next print strikes over the character before it. bs: bool = false, failed: bool = false, + /// The control sequence being read: its parameters as ghostty-vt keeps + /// them (24 at most, each saturating at 65535, a bit in `colons` for + /// each one a colon ends), and whether it has an intermediate or a + /// private marker, which no sequence kept here takes. + csi: struct { + params: [24]u16 = undefined, + n: u8 = 0, + acc: u16 = 0, + digits: bool = false, + colons: u32 = 0, + inter: bool = false, + } = .{}, - const Action = ghostty_vt.StreamAction; - - pub fn vt(h: *Handler, comptime action: Action.Tag, value: Action.Value(action)) void { - switch (action) { - .print => h.print(value.cp), - .print_slice => h.printRun(value.cps), - // CSI b repeats the last character, as a terminal draws it; - // a terminal stops at its edge, and this at a line's worth. - .print_repeat => if (h.text.items.len > h.last) { - const cp = std.unicode.utf8Decode(h.text.items[h.last..]) catch return; - for (0..@min(value, 1024)) |_| h.print(cp); + /// The state after byte `c` in `state` (not ground's printing, which + /// `parse` decodes), acting on the controls and sequences a page keeps. + fn step(h: *Handler, state: State, c: u8) State { + switch (c) { + 0x18, 0x1a => return .ground, + 0x1b => { + h.csi = .{}; + return .esc; + }, + // A C1 control byte, in all but an OSC's or a DCS's data. + 0x80...0x9f => return if (state == .osc or state == .dcs_body) state else switch (c) { + 0x90 => .dcs_entry, + 0x9b => csi: { + h.csi = .{}; + break :csi .csi_entry; + }, + 0x9d => .osc, + 0x98, 0x9e, 0x9f => .apc, + else => .ground, + }, + 0xa0...0xff => return state, + else => {}, + } + switch (state) { + .osc => return if (c == 0x07) .ground else .osc, + .apc, .dcs_body => return state, + .dcs_entry, .dcs_param, .dcs_inter => return switch (c) { + 0...0x1f, 0x7f => state, + 0x20...0x2f => .dcs_inter, + '0'...'9', ';' => if (state == .dcs_inter) .dcs_body else .dcs_param, + '<'...'?' => if (state == .dcs_entry) .dcs_param else .dcs_body, + else => .dcs_body, + }, + else => {}, + } + if (c < 0x20) { + h.execute(c); + return state; + } + if (c == 0x7f) return state; + switch (state) { + .esc => return switch (c) { + '[' => .csi_entry, + ']' => .osc, + 'P' => .dcs_entry, + 'X', '^', '_' => .apc, + 0x20...0x2f => .esc_inter, + else => .ground, + }, + .esc_inter => return if (c < 0x30) state else .ground, + .csi_ignore => return if (c < 0x40) state else .ground, + else => {}, + } + const p = &h.csi; + switch (c) { + 0x20...0x2f => { + p.inter = true; + return .csi_inter; + }, + '0'...'9', ':', ';' => { + if (state == .csi_inter or (c == ':' and state == .csi_entry)) return .csi_ignore; + if (p.n == p.params.len) return .csi_param; + if (c <= '9') { + p.acc = p.acc *| 10 +| (c - '0'); + p.digits = true; + return .csi_param; + } + p.params[p.n] = p.acc; + if (c == ':') p.colons |= @as(u32, 1) << @intCast(p.n); + p.n += 1; + p.acc = 0; + p.digits = false; + return .csi_param; + }, + '<'...'?' => { + if (state != .csi_entry) return .csi_ignore; + p.inter = true; + return .csi_param; + }, + else => { + h.dispatch(c); + return .ground; }, - .set_attribute => h.attribute(value), - .linefeed => { + } + } + + /// A C0 control: the line feeds (LF, VT and FF), CR, BS and HT. + fn execute(h: *Handler, c: u8) void { + switch (c) { + '\n', 0x0b, 0x0c => { h.append("\n"); h.line_start = h.text.items.len; h.last = h.line_start; h.cr = false; h.bs = false; }, - .carriage_return => h.cr = true, - .backspace => h.bs = h.text.items.len > h.line_start, - .horizontal_tab => for (0..@min(value, 64)) |_| h.print('\t'), + '\r' => h.cr = true, + 0x08 => h.bs = h.text.items.len > h.line_start, + '\t' => h.print('\t'), else => {}, } } - pub fn deinit(_: *Handler) void {} + /// The control sequence ending in `f`: SGR, and of the rest what moves + /// along a line, dropped as ghostty-vt drops a malformed one. + fn dispatch(h: *Handler, f: u8) void { + const p = &h.csi; + if (p.n == p.params.len) return; + if (p.digits) { + p.params[p.n] = p.acc; + p.n += 1; + } + if (p.inter or (f != 'm' and p.colons != 0)) return; + if (f == 'm') return h.sgr(p.params[0..p.n], p.colons); + if (p.n > 1) return; + const count: u16 = if (p.n == 0) 1 else p.params[0]; + switch (f) { + // CNL and CPL: down or up, which a page has not, and a return. + 'E', 'F' => h.cr = true, + // CHT; and REP, the last character again, as a terminal draws + // it: a terminal stops at its edge, and this at a line's worth. + 'I' => for (0..@min(count, 64)) |_| h.print('\t'), + 'b' => if (h.text.items.len > h.last) { + const cp = std.unicode.utf8Decode(h.text.items[h.last..]) catch return; + for (0..@min(count, 1024)) |_| h.print(cp); + }, + else => {}, + } + } - // ponytail: bytes that are not UTF-8 reach here as U+FFFD (ghostty's - // decoder replaces them, as a terminal shows them); a raw-byte pass - // through the stream if a +Pager must keep them. + /// SGR's parameters into the style, read as ghostty-vt's sgr.Parser + /// reads them: a colour short of its values leaves them to be read as + /// SGRs of their own, and a colon list it does not know is skipped. + fn sgr(h: *Handler, params: []const u16, colons: u32) void { + const s = &h.style; + if (params.len == 0) s.* = .{}; + var i: usize = 0; + while (i < params.len) { + const p = params[i..]; + const colon = colons >> @intCast(i) & 1 != 0; + i += 1; + // The colons on from p[1], short of the last parameter. + var subs: usize = 0; + while (i + subs < params.len - 1 and colons >> @intCast(i + subs) & 1 != 0) subs += 1; + if (colon and p[0] != 4 and p[0] != 38 and p[0] != 48 and p[0] != 58) { + while (colons >> @intCast(i) & 1 != 0) i += 1; + i += 1; + continue; + } + switch (p[0]) { + 0 => s.* = .{}, + 1 => s.bold = true, + 2 => s.dim = true, + 3 => s.italic = true, + 4 => if (!colon) { + s.ul = .single; + } else if (p.len >= 2) { + if (colons >> @intCast(i) & 1 != 0) { + i += subs + 1; + } else { + i += 1; + s.ul = if (p[1] <= 5) @enumFromInt(p[1]) else .single; + } + }, + 5, 6 => s.blink = true, + 7 => s.reverse = true, + 8 => s.invisible = true, + 9 => s.strikethrough = true, + 21 => s.ul = .double, + // SGR 22 ends faint as well as bold. + 22 => { + s.bold = false; + s.dim = false; + }, + 23 => s.italic = false, + 24 => s.ul = .off, + 25 => s.blink = false, + 27 => s.reverse = false, + 28 => s.invisible = false, + 29 => s.strikethrough = false, + 30...37 => s.fg = .{ .index = @intCast(p[0] - 30) }, + 39 => s.fg = .default, + 40...47 => s.bg = .{ .index = @intCast(p[0] - 40) }, + 49 => s.bg = .default, + 90...97 => s.fg = .{ .index = @intCast(p[0] - 82) }, + 100...107 => s.bg = .{ .index = @intCast(p[0] - 92) }, + // A colour: 5 and an index, or 2 and red, green and blue, + // after a colour space's slot when colons give one. A cell + // has no underline colour (58) to take. + 38, 48, 58 => if (p.len >= 2) { + var color: ?Color = null; + if (p[1] == 5 and p.len >= 3) { + i += 2; + color = .{ .index = @truncate(p[2]) }; + } else if (p[1] == 2 and p.len >= 5) { + if (colon and subs != 3 and subs != 4) { + i += subs + 1; + continue; + } + const at: usize = if (colon and subs == 4) 3 else 2; + i += at + 2; + color = .{ .rgb = .{ @truncate(p[at]), @truncate(p[at + 1]), @truncate(p[at + 2]) } }; + } + if (color) |ink| switch (p[0]) { + 38 => s.fg = ink, + 48 => s.bg = ink, + else => {}, + }; + }, + else => {}, + } + } + } + + // ponytail: bytes that are not UTF-8 reach here as U+FFFD (`parse` + // replaces them, as a terminal shows them); a raw-byte pass if a + // +Pager must keep them. fn print(h: *Handler, cp: u21) void { - // A control a terminal acts on and never draws: ghostty's fast path - // hands those past 0x0f (CAN, DEL, the C1 set) on as printed text. - // A tab is HT's, printed here. + // A control a terminal acts on and never draws: DEL comes in a run + // of printed text, as a terminal's parse hands it on. A tab is + // HT's, printed here. if ((cp < 0x20 and cp != '\t') or (cp >= 0x7f and cp < 0xa0)) return; if (h.cr) { h.text.shrinkRetainingCapacity(h.line_start); @@ -204,42 +464,6 @@ const Handler = struct { _ = h.spans.pop(); } } - - fn attribute(h: *Handler, attr: ghostty_vt.Attribute) void { - const s = &h.style; - switch (attr) { - .unset => s.* = .{}, - .bold => s.bold = true, - // SGR 22 ends faint as well as bold. - .reset_bold => { - s.bold = false; - s.dim = false; - }, - .faint => s.dim = true, - .italic => s.italic = true, - .reset_italic => s.italic = false, - // SGR's styles in a cell's order (terminal.zig checks it). - .underline => |u| s.ul = @enumFromInt(@intFromEnum(u)), - .blink => s.blink = true, - .reset_blink => s.blink = false, - .inverse => s.reverse = true, - .reset_inverse => s.reverse = false, - .invisible => s.invisible = true, - .reset_invisible => s.invisible = false, - .strikethrough => s.strikethrough = true, - .reset_strikethrough => s.strikethrough = false, - .direct_color_fg => |c| s.fg = .{ .rgb = .{ c.r, c.g, c.b } }, - .direct_color_bg => |c| s.bg = .{ .rgb = .{ c.r, c.g, c.b } }, - .@"8_fg", .@"8_bright_fg" => |name| s.fg = .{ .index = @backingInt(name) }, - .@"8_bg", .@"8_bright_bg" => |name| s.bg = .{ .index = @backingInt(name) }, - .@"256_fg" => |i| s.fg = .{ .index = i }, - .@"256_bg" => |i| s.bg = .{ .index = i }, - .reset_fg => s.fg = .default, - .reset_bg => s.bg = .default, - // A cell has no overline and no underline colour to take. - .overline, .reset_overline, .underline_color, .@"256_underline_color", .reset_underline_color, .unknown => {}, - } - } }; // ---- tests ---- @@ -334,7 +558,7 @@ test "every other escape is dropped, and a stray or broken one loses no text aft .{ "a\r\nb\r\n", "a\nb\n" }, .{ "10%\r50%\r\x1b[K100%\ndone\n", "100%\ndone\n" }, .{ "x\x00y\x07z\x0e\x0f\n", "xyz\n" }, - // Controls ghostty's fast path prints: CAN, FS, DEL and a C1. + // Controls that are dropped: CAN, FS, DEL and a C1 as UTF-8. .{ "x\x18y\x1cz\x7f!\u{85}?\n", "xyz!?\n" }, // A broken CSI: its parameter bytes are eaten up to a final byte, as // a terminal eats them; CAN abandons one, and the text goes on. @@ -352,3 +576,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/panes.zig b/src/panes.zig index 99652b04..29a9f051 100644 --- a/src/panes.zig +++ b/src/panes.zig @@ -292,7 +292,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, diff --git a/src/pardes.zig b/src/pardes.zig index 298822bc..9f5c36ff 100644 --- a/src/pardes.zig +++ b/src/pardes.zig @@ -386,6 +386,7 @@ test { _ = @import("rollback.zig"); _ = @import("Core.zig"); _ = @import("lsp/Ask.zig"); + _ = @import("lsp/lsp_client.zig"); _ = @import("Jump.zig"); _ = @import("keys.zig"); _ = @import("Effect.zig"); diff --git a/src/screen_state.zig b/src/screen_state.zig index eeb1c059..8032e79a 100644 --- a/src/screen_state.zig +++ b/src/screen_state.zig @@ -1154,6 +1154,7 @@ 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 = &.{}, @@ -1164,6 +1165,7 @@ pub const Shadow = struct { 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); @@ -1216,6 +1218,12 @@ pub const Shadow = struct { }).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; @@ -1354,6 +1362,7 @@ pub fn encodeShadow(gpa: std.mem.Allocator, sent: *ShadowSent, f: *const Kind.Fr 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); @@ -1384,6 +1393,9 @@ pub fn encodeShadow(gpa: std.mem.Allocator, sent: *ShadowSent, f: *const Kind.Fr 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; @@ -1626,3 +1638,27 @@ test "a pane of a kind crosses as its frame, a row the peer holds as its hash, a 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/surface.zig b/src/surface.zig index ca517d3b..c0f352ee 100644 --- a/src/surface.zig +++ b/src/surface.zig @@ -4,7 +4,6 @@ const pardes = @import("pardes.zig"); const std = @import("std"); const layout = @import("layout.zig"); const uucode = @import("uucode"); -const vaxis = @import("vaxis"); const panes = @import("panes.zig"); const config = @import("config.zig"); const MAX_PANES = pardes.MAX_PANES; @@ -293,9 +292,11 @@ pub const Chrome = struct { /// The canonical interface: what a frame of pardes IS. The tui shell writes /// these cells to vaxis one-to-one; the SDL shells rasterize them. pub const Surface = struct { + pub const GpuFrame = struct { bytes: []const u8, serial: u32, dst: RectCell }; /// `box` is acme's boxcursor, shown while a pane or a column is carried /// by its grip (cols.c:485, rows.c:151). pub const PointerShape = enum(u8) { arrow, link, target, box }; + gpu_frames: [MAX_PANES]?GpuFrame = @splat(null), pointer_shape: PointerShape = .arrow, body_layers: [MAX_PANES]Layer = @splat(.{}), tag_layers: [MAX_TAG_LAYERS]Layer = @splat(.{}), @@ -415,7 +416,7 @@ pub const Surface = struct { const width: u16 = if (decoded == null or (cp < 0x80 and cp_slice.len == 1)) 1 else - @max(1, vaxis.gwidth.gwidth(cp_slice, .unicode)); + @max(1, panes.File.utf8Width(cp_slice)); if (width == 2 and col + 1 >= end) return null; var shown = cp_slice; if (shown.len > @typeInfo(@FieldType(Cell, "text")).array.len) { diff --git a/src/syntax.zig b/src/syntax.zig index 2526e113..8533aaa9 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(); @@ -1909,8 +1806,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 +1814,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/terminal.zig b/src/terminal.zig index 68b3adde..4ee2e9fa 100644 --- a/src/terminal.zig +++ b/src/terminal.zig @@ -16,7 +16,9 @@ const File = panes.File; const ghostty_vt = @import("ghostty-vt"); -pub const history_max = 64; +const EditBuffer = panes.Text.EditBuffer; +const Snapshot = panes.Text.Snapshot; +const history_max = panes.Text.history_max; pub const VtSlot = ghostty_vt.Terminal; /// A cell of an emulator's pages, as `getCell` reads it (src/echo.zig). @@ -416,23 +418,6 @@ 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, @@ -3420,3 +3405,7 @@ test "a program asking the cell size in pixels (CSI 16 t) is told the shell's" { p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[16t" } }); try std.testing.expectEqualStrings("0:\x1b[6;20;10t\n", try ptyWritesByPane(p, &out)); } + +test "colors.xterm is the palette the emulator starts from, all 256" { + for (pardes.colors.xterm, ghostty_vt.color.default) |ours, its| try std.testing.expectEqual(ours, [3]u8{ its.r, its.g, its.b }); +} diff --git a/src/tui/tui.zig b/src/tui/tui.zig index 0daac14b..77c8ce2b 100644 --- a/src/tui/tui.zig +++ b/src/tui/tui.zig @@ -3344,3 +3344,17 @@ test "the tty draws a glide at whole rows: once a flick or a spin slows, its ste try std.testing.expectEqual(row, (shown.cursor orelse return error.NoCursor).y); } } + +test "the tui's vaxis measures a grapheme as wide as the core lays it out" { + // vaxis renders a cell at gwidth(.unicode) in mode 2027; the core's + // File.utf8Width is that function over the same uucode tables. A vaxis + // that measures otherwise would draw past or short of the core's cells. + for ([_][]const u8{ + "a", "\u{4e16}", "e\u{301}", "\u{301}", + "\u{1f642}", "\u{1f44b}\u{1f3ff}", "\u{1f469}\u{200d}\u{1f680}", "\u{1f1fa}\u{1f1f8}", + "\u{1f1fa}", "\u{2764}\u{fe0e}", "\u{2764}\u{fe0f}", "1\u{fe0f}\u{20e3}", + "\u{1100}\u{1161}", "\u{ff21}", "\u{b1}", "\u{200b}", + "\u{ad}", "\u{fffd}", "\u{85}", "\x7f", + "a\u{4e16}\u{1f642}", "\u{e0100}", "\u{231a}", "\u{2600}", + }) |g| try std.testing.expectEqual(vaxis.gwidth.gwidth(g, .unicode), pardes.panes.File.utf8Width(g)); +} |
