From f2b02c455f2bcdfb905a015eefbb630a28b4b12e Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Thu, 12 Nov 2026 10:56:42 -0300 Subject: addons: an addon can hand the frontend a GPU scene (ABI 3.1), and a snake drawn by shaders does; a commit's patch keeps its own +Diff pane; a real ZLS checked through the window build ABI 3.1 appends an optional `gpu` callback and its context to pa_paint: one self-contained sketchbook SGPU v1 scene for the pane, at most 4 MiB, copied during the call, the last successful call winning. The SDL frontend runs it on its own GPU through sketchbook's executor and composites its target texture into the pane; replicas carry the scene beside the authoritative pane frame; cells and rasters stay the fallback for terminals, older hosts and frontends without an executor. addons/snake_shader is such an addon (`zig build snake-shader`, the SnakeShader word: a board that follows its pane, buffered turns, a CRT look), with test/gpu_snake.py, test/gpu_snake_interaction.py and test/gpu_upgrade.py. Commit patches open as `+Diff-` and reuse only their own commit's pane, so another paged patch no longer replaces one already open. The language-server client looks in the standard per-user bin directory, which desktop launchers often leave out of PATH, and takes an empty answer that beats the startup progress notification onto the wire; test/real_zls.py checks imports, hover, references, rename previews, diagnostics and completion against a real ZLS from a private home. The dump's schema reader skips two fields older builds persisted, and a replica's shadow of a kind ticks when the authority's does. The reference, the guide, the building and setup notes and the changelog say so. The working copy as it stood on 2026-11-12; message written by Claude from the diff, at the author's request. --- src/Addon.zig | 50 +++++++++++++++++++++++++++++--- src/CHANGELOG.md | 3 ++ src/File.zig | 53 +++++++++++++++++++++++++++------- src/Kind.zig | 27 ++++++++++++----- src/Output.zig | 16 ++++++++++- src/Query.zig | 4 +-- src/Stream.zig | 8 ++---- src/diff.zig | 24 ++++++++++++++++ src/draw.zig | 1 + src/dump.zig | 75 +++++++++++++++++++++++++++++++++++++++++++----- src/gui/gui.zig | 71 +++++++++++++++++++++++++++++++++++++++++++++ src/hunks.zig | 33 +++++++++++++++++++++ src/kinds/addon.zig | 18 ++++++++---- src/kinds/pardes_addon.h | 12 ++++++-- src/lsp/lsp_client.zig | 66 +++++++++++++++++++++++++++++++++--------- src/ninep/pane.zig | 2 +- src/pardes.zig | 1 + src/screen_state.zig | 36 +++++++++++++++++++++++ src/surface.zig | 2 ++ 19 files changed, 443 insertions(+), 59 deletions(-) (limited to 'src') 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 ` (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/CHANGELOG.md b/src/CHANGELOG.md index 633687e8..dc130be1 100644 --- a/src/CHANGELOG.md +++ b/src/CHANGELOG.md @@ -2,6 +2,9 @@ ## Unreleased +- Commit patches open as `+Diff-` 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..d1cfe088 100644 --- a/src/File.zig +++ b/src/File.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. @@ -576,7 +594,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 +1481,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 +1601,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 +1692,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, }; @@ -2640,3 +2656,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 "; @@ -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/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 fc90586e..7d199155 100644 --- a/src/draw.zig +++ b/src/draw.zig @@ -288,6 +288,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, 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/gui/gui.zig b/src/gui/gui.zig index 537271f1..51ec6bbf 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"); @@ -286,6 +288,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 +520,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 +1237,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 +4388,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 +4436,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); @@ -9135,3 +9147,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/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/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 9333a75e..a5dbea8e 100644 --- a/src/surface.zig +++ b/src/surface.zig @@ -301,9 +301,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(.{}), -- cgit v1.3