diff options
| author | Gabriel Schneider <[email protected]> | 2026-11-12 10:56:42 -0300 |
|---|---|---|
| committer | Gabriel Schneider <[email protected]> | 2026-11-17 12:15:01 -0300 |
| commit | f2b02c455f2bcdfb905a015eefbb630a28b4b12e (patch) | |
| tree | c344c7ad42ec288dd5e1ebd0eb6d25f5aa2fbccc | |
| parent | fc38c73c59f7855a4caad8aa4d3bb8e023309c13 (diff) | |
| download | pardes-f2b02c455f2bcdfb905a015eefbb630a28b4b12e.tar.gz pardes-f2b02c455f2bcdfb905a015eefbb630a28b4b12e.zip | |
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-<short-hash>` 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.
36 files changed, 1838 insertions, 74 deletions
diff --git a/addons/snake_shader/snake.frag b/addons/snake_shader/snake.frag new file mode 100644 index 00000000..14896f2f --- /dev/null +++ b/addons/snake_shader/snake.frag @@ -0,0 +1,52 @@ +#version 450 +layout(location = 0) in vec2 uv; +layout(location = 0) out vec4 color; +layout(std140, set = 3, binding = 0) uniform Board { + vec4 status; // dead, focused, target width, target height + vec4 points; // head xy, food xy + vec4 grid; // board size, hovered cell including walls + vec4 motion; // seconds, tile pixels, board offset xy + uvec4 rows[128]; +} board; +float box(vec2 p, float size, float radius) { + vec2 d = abs(p) - size + radius; + return length(max(d, 0)) + min(max(d.x, d.y), 0) - radius; +} +void main() { + vec2 p = (uv * board.status.zw - board.motion.zw) / board.motion.y; + vec3 bg = vec3(.018, .028, .043); + float dim = board.status.y < .5 ? .6 : 1; + if (any(lessThan(p, vec2(0))) || any(greaterThanEqual(p, board.grid.xy + 2))) { + color = vec4(bg * dim, 1); + return; + } + ivec2 cell = ivec2(floor(p)) - 1; + vec2 local = fract(p) - .5; + vec3 ink = vec3(.10, .16, .23); + float dist = box(local, .43, .10); + bool inside = cell.x >= 0 && cell.x < int(board.grid.x) && cell.y >= 0 && cell.y < int(board.grid.y); + if (inside) { + dist = 1; + if ((board.rows[cell.y][cell.x / 32] & (1u << uint(cell.x % 32))) != 0u) { + ink = board.status.x > .5 ? vec3(.85, .12, .20) : vec3(.12, .78, .43); + dist = box(local, .44, .16); + if (all(equal(cell, ivec2(board.points.xy)))) ink *= 1.18; + } else if (all(equal(cell, ivec2(board.points.zw)))) { + ink = vec3(1, .42, .10) * (1 + .035 * sin(board.motion.x * 1.5707963)); + dist = length(local) - .26; + } else { + bg += vec3(.008, .014, .018) * (1 - smoothstep(.44, .49, max(abs(local.x), abs(local.y)))); + } + } + float aa = max(fwidth(dist), .002); + float coverage = 1 - smoothstep(-aa, aa, dist); + vec3 rgb = mix(bg + ink * .10 * exp(-max(dist, 0) * 8), ink, coverage); + if (board.grid.z >= 0) { + vec2 delta = p - (board.grid.zw + .5); + float halo = exp(-dot(delta, delta) * 2.5); + float rim = 1 - smoothstep(.015, .07, abs(box(local, .45, .09))); + bool hovered = all(equal(ivec2(floor(p)), ivec2(board.grid.zw))); + rgb += vec3(.12, .30, .36) * halo + (hovered ? vec3(.14, .32, .40) * rim : vec3(0)); + } + color = vec4(rgb * dim, 1); +} diff --git a/addons/snake_shader/snake.post.frag b/addons/snake_shader/snake.post.frag new file mode 100644 index 00000000..226e98de --- /dev/null +++ b/addons/snake_shader/snake.post.frag @@ -0,0 +1,34 @@ +#version 450 +layout(location = 0) in vec2 uv; +layout(location = 0) out vec4 color; +layout(set = 2, binding = 0) uniform sampler2D board; +layout(std140, set = 3, binding = 0) uniform Clock { vec4 phase; } clock; + +vec3 bright(vec2 at) { + vec3 rgb = texture(board, at).rgb; + return rgb * smoothstep(.16, .65, max(rgb.r, max(rgb.g, rgb.b))); +} +vec3 mapColor(vec3 rgb) { + // Soft highlights with a cool shadow tint; retain the dark board floor. + rgb *= vec3(.98, 1.02, 1.06); + return clamp((rgb * (2.51 * rgb + .03)) / (rgb * (2.43 * rgb + .59) + .14), 0, 1); +} +void main() { + vec2 size = vec2(textureSize(board, 0)); + vec2 pixel = uv * size; + vec2 pitch = vec2(3, 4); + vec2 sampleUV = (floor(pixel / pitch) + .5) * pitch / size; + vec4 source = texture(board, sampleUV); + vec3 bloom = vec3(0); + vec2 stepUV = vec2(4) / size; + for (int y = -1; y <= 1; y++) for (int x = -1; x <= 1; x++) { + float weight = float((x == 0 ? 2 : 1) * (y == 0 ? 2 : 1)); + bloom += bright(sampleUV + vec2(x, y) * stepUV) * weight / 16; + } + vec3 rgb = mapColor(source.rgb + bloom * .24); + vec3 mask = vec3(.65); + mask[int(mod(floor(pixel.x), 3))] = 1.45; + float scanline = mix(.5, 1, smoothstep(.15, .35, fract(pixel.y / 4))); + float shimmer = 1 + .006 * sin(clock.phase.x * 18.849556 + pixel.y * .12); + color = vec4(rgb * mask * scanline * shimmer, source.a); +} diff --git a/addons/snake_shader/snake.vert b/addons/snake_shader/snake.vert new file mode 100644 index 00000000..5f09493f --- /dev/null +++ b/addons/snake_shader/snake.vert @@ -0,0 +1,6 @@ +#version 450 +layout(location = 0) out vec2 uv; +void main() { + uv = vec2((gl_VertexIndex << 1) & 2, gl_VertexIndex & 2); + gl_Position = vec4(uv * vec2(2, -2) + vec2(-1, 1), 0, 1); +} diff --git a/addons/snake_shader/snake_shader.out b/addons/snake_shader/snake_shader.out new file mode 100644 index 00000000..462a138e --- /dev/null +++ b/addons/snake_shader/snake_shader.out @@ -0,0 +1,147 @@ +> seed 3 +> size 26 14 +window 24x4 +tag SnakeShader 0 22x3 +|######################## +|# # +|# * # +|# oo@ # +> tick 150 +tag SnakeShader 0 22x3 +|######################## +|# # +|# * # +|# oo@ # +> key jk +tag SnakeShader 0 22x3 +|######################## +|# # +|# * # +|# oo@ # +> tick 1 +tag SnakeShader 0 22x3 +|######################## +|# # +|# * # +|# oo@ # +> tick 60 +tag SnakeShader 0 22x3 +|######################## +|# # +|# * # +|# oo@ # +> tick 150 +tag SnakeShader 0 22x3 +|######################## +|# # +|# @ * # +|# oo # +> key jh +tag SnakeShader 0 22x3 +|######################## +|# # +|# @ * # +|# oo # +> tick 150 +tag SnakeShader 0 22x3 +|######################## +|# # +|# @o * # +|# o # +> tick 150 +tag SnakeShader 0 22x3 +|######################## +|# # +|# @oo * # +|# # +> body +=score 0 +=length 3 +=steps 3 +=alive +=board 22x3 +=hover -1 -1 +> click 3 3 +tag SnakeShader 0 22x3 +|######################## +|# # +|# @oo * # +|# # +> body +=score 0 +=length 3 +=steps 3 +=alive +=board 22x3 +=hover 3 3 +> blur +tag SnakeShader 0 22x3 +|######################## +|# # +|# @oo * # +|# # +> tick 500 +tag SnakeShader 0 22x3 +|######################## +|# # +|# @oo * # +|# # +> body +=score 0 +=length 3 +=steps 3 +=alive +=board 22x3 +=hover 3 3 +> size 34 18 +window 32x6 +tag SnakeShader 0 30x4 +|################################ +|# # +|# @oo * # +|# # +|# # +|################################ +> body +=score 0 +=length 3 +=steps 3 +=alive +=board 30x4 +=hover -1 -1 +> size 22 10 +window 20x2 +tag SnakeShader 0 18x3 +|#################### +|# # +> body +=score 0 +=length 3 +=steps 3 +=alive +=board 18x3 +=hover -1 -1 +> dump +dump 34392 bytes +tag SnakeShader 0 18x3 +|#################### +|# # +> body +=score 0 +=length 3 +=steps 3 +=alive +=board 18x3 +=hover -1 -1 +> focus +tag SnakeShader 0 18x3 +|#################### +|# # +> key r +tag SnakeShader 0 18x3 +|#################### +|# * # +> tick 150 +tag SnakeShader 0 18x3 +|#################### +|# * # diff --git a/addons/snake_shader/snake_shader.script b/addons/snake_shader/snake_shader.script new file mode 100644 index 00000000..02dc2c23 --- /dev/null +++ b/addons/snake_shader/snake_shader.script @@ -0,0 +1,26 @@ +# Dynamic board, quick turn correction, resize, hover and record roundtrip. +seed 3 +size 26 14 +tick 150 +key jk +tick 1 +tick 60 +tick 150 +key jh +tick 150 +tick 150 +body +click 3 3 +body +blur +tick 500 +body +size 34 18 +body +size 22 10 +body +dump +body +focus +key r +tick 150 diff --git a/addons/snake_shader/snake_shader.zig b/addons/snake_shader/snake_shader.zig new file mode 100644 index 00000000..d6f803d5 --- /dev/null +++ b/addons/snake_shader/snake_shader.zig @@ -0,0 +1,547 @@ +//! A resizable snake with buffered turns and an optional CRT GPU picture. +//! h j k l or arrows steer; r restarts. Losing focus pauses movement. +const std = @import("std"); +const addon = @import("addon"); +const scene = @import("gpu_scene"); +const shaders = @import("shaders"); + +const max_side = 126; // 4096 pixels / minimum 32-pixel tile, less the walls. +const period = 150 * std.time.ns_per_ms; +const grace = 60 * std.time.ns_per_ms; +const animation_period = 50 * std.time.ns_per_ms; +const Pt = extern struct { x: u8, y: u8 }; +const Dir = [2]i8; +const Size = extern struct { cols: u16 = 0, rows: u16 = 0, cell_w: u16 = 0, cell_h: u16 = 0, glyphs: bool = false }; +const Layout = struct { tile: u32, x: u32, y: u32 }; +const Uniforms = extern struct { status: [4]f32, points: [4]f32, grid: [4]f32, motion: [4]f32, rows: [128][4]u32 }; + +// Version 1's exact record, so a live addon reload keeps the game. +const Legacy = extern struct { + segs: [100]Pt, + len: u16, + food: Pt, + dir: Dir, + turn: Dir, + dead: bool, + score: u32, + steps: u32, + rng: u64, + next: addon.Deadline, +}; + +pub const Snake = extern struct { + segs: [max_side * max_side]Pt, + len: u16, + food: Pt, + dir: Dir, + turns: [2]Dir, + queued: u8, + dead: bool, + score: u32, + steps: u32, + rng: u64, + next: addon.Deadline, + collision_at: u64, + input_pending: bool, + grace_given: bool, + now: u64, + width: u8, + height: u8, + owner: u8, + sizes: [256]Size, + hover_view: u8, + hover_x: i16, + hover_y: i16, + + pub const head: addon.Head = .{ .name = "snake_shader", .version = 2, .words = &.{ + .{ .name = "SnakeShader", .opens = true, .doc = "a resizable game of snake: h j k l steer, r restarts" }, + } }; + + fn rnd(s: *Snake) u64 { + s.rng ^= s.rng << 13; + s.rng ^= s.rng >> 7; + s.rng ^= s.rng << 17; + return s.rng; + } + + fn on(s: *const Snake, x: i32, y: i32, n: usize) bool { + for (s.segs[0..n]) |q| if (q.x == x and q.y == y) return true; + return false; + } + + fn bits(s: *const Snake) [128][4]u32 { + var out: [128][4]u32 = @splat(@splat(0)); + for (s.segs[0..s.len]) |p| out[p.y][p.x / 32] |= @as(u32, 1) << @intCast(p.x % 32); + return out; + } + + fn placeFood(s: *Snake) void { + const area = @as(u32, s.width) * s.height; + if (s.len == area) { + s.dead = true; + return; + } + var k = s.rnd() % (area - s.len); + const occupied = s.bits(); + for (0..area) |i| { + const p: Pt = .{ .x = @intCast(i % s.width), .y = @intCast(i / s.width) }; + if (occupied[p.y][p.x / 32] & (@as(u32, 1) << @intCast(p.x % 32)) != 0) continue; + if (k == 0) { + s.food = p; + return; + } + k -= 1; + } + } + + fn restart(s: *Snake) void { + if (s.width == 0) s.width = 20; + if (s.height == 0) s.height = 5; + s.len = 3; + for (s.segs[0..3], 0..) |*p, i| p.* = .{ .x = @intCast(@max(2, s.width / 2) - i), .y = s.height / 2 }; + s.dir = .{ 1, 0 }; + s.queued = 0; + s.dead = false; + s.score = 0; + s.steps = 0; + s.next = .{}; + s.collision_at = 0; + s.input_pending = false; + s.grace_given = false; + s.placeFood(); + } + + // A rejected move changes no coordinates: a late turn can still save it. + fn step(s: *Snake) bool { + const d = if (s.queued > 0) s.turns[0] else s.dir; + const x = @as(i32, s.segs[0].x) + d[0]; + const y = @as(i32, s.segs[0].y) + d[1]; + const eats = x == s.food.x and y == s.food.y; + if (x < 0 or y < 0 or x >= s.width or y >= s.height or s.on(x, y, if (eats) s.len else s.len - 1)) { + s.queued = 0; + return false; + } + s.dir = d; + if (s.queued > 0) { + s.turns[0] = s.turns[1]; + s.queued -= 1; + } + if (eats) s.len += 1; + std.mem.copyBackwards(Pt, s.segs[1..s.len], s.segs[0 .. s.len - 1]); + s.segs[0] = .{ .x = @intCast(x), .y = @intCast(y) }; + s.steps += 1; + s.collision_at = 0; + s.grace_given = false; + if (eats) { + s.score += 1; + s.placeFood(); + } + return true; + } + + pub fn open(s: *Snake, _: ?[]const u8, _: ?[]const u8) void { + s.rng = addon.seed() | 1; + s.hover_x = -1; + s.hover_y = -1; + s.restart(); + } + + pub fn tick(s: *Snake, now: u64, flags: addon.Flags) u64 { + s.now = now; + // Only visible panes animate; the food and phosphor breathe at 20 Hz. + const visible = for (s.sizes) |v| { + if (v.cols > 0 and v.rows > 0) break true; + } else false; + if (!flags.focused or s.dead or !visible) { + _ = s.next.stop(); + s.collision_at = 0; + s.grace_given = false; + } else { + if (s.next.at == 0) s.next.at = now + period; + if (s.input_pending and s.collision_at == 0 and !s.grace_given) { + s.next.at = @max(s.next.at, now + grace); + s.grace_given = true; + } + if (s.next.due(now) or (s.collision_at != 0 and s.input_pending)) { + if (s.collision_at != 0 and now >= s.collision_at) { + s.dead = true; + _ = s.next.stop(); + } else if (s.step()) { + s.next.at = now + period; + } else if (s.collision_at == 0) { + s.collision_at = now + grace; + s.next.at = s.collision_at; + } + } + } + s.input_pending = false; + const animation = if (visible) now + animation_period else std.math.maxInt(u64); + const next = @min(if (s.next.at == 0) std.math.maxInt(u64) else s.next.at, animation); + return if (next == std.math.maxInt(u64)) 0 else next; + } + + fn resize(s: *Snake, width: u8, height: u8) void { + if (s.width == width and s.height == height) return; + s.width = width; + s.height = height; + var lo = s.segs[0]; + var hi = lo; + var keep: usize = 1; + for (s.segs[1..s.len]) |p| { + const low: Pt = .{ .x = @min(lo.x, p.x), .y = @min(lo.y, p.y) }; + const high: Pt = .{ .x = @max(hi.x, p.x), .y = @max(hi.y, p.y) }; + if (high.x - low.x >= width or high.y - low.y >= height) break; + lo = low; + hi = high; + keep += 1; + } + // Keep the head and score; only an unfit tail is shortened on shrink. + s.len = @intCast(keep); + const dx = @max(@as(i16, hi.x) - width + 1, 0); + const dy = @max(@as(i16, hi.y) - height + 1, 0); + for (s.segs[0..s.len]) |*p| { + p.x = @intCast(@as(i16, p.x) - dx); + p.y = @intCast(@as(i16, p.y) - dy); + } + if (s.food.x >= width or s.food.y >= height or s.on(s.food.x, s.food.y, s.len)) s.placeFood(); + s.collision_at = 0; + s.next = .{}; + s.hover_x = -1; + s.hover_y = -1; + } + + fn useView(s: *Snake, id: u8) void { + const v = s.sizes[id]; + if (id == 0 or v.cols == 0 or v.rows == 0) return; + s.owner = id; + const tile = @max(32, v.cell_h); + const cols = if (v.glyphs) v.cols else @min(4096, @as(u32, v.cols) * v.cell_w) / tile; + const rows = if (v.glyphs) v.rows else @min(4096, @as(u32, v.rows) * v.cell_h) / tile; + s.resize(@intCast(std.math.clamp(cols -| 2, 3, max_side)), @intCast(std.math.clamp(rows -| 2, 3, max_side))); + } + + pub fn view(s: *Snake, v: addon.View) void { + s.sizes[v.id] = .{ .cols = v.cols, .rows = v.rows, .cell_w = v.cell_w, .cell_h = v.cell_h, .glyphs = v.glyphs }; + if (s.hover_view == v.id and (v.cols == 0 or v.rows == 0)) { + s.hover_x = -1; + s.hover_y = -1; + } + if (s.owner == v.id and (v.cols == 0 or v.rows == 0)) s.owner = 0; + if (s.owner == 0) for (s.sizes, 0..) |size, i| { + if (i > 0 and size.cols > 0 and size.rows > 0) { + s.useView(@intCast(i)); + break; + } + }; + if (s.owner == v.id) s.useView(v.id); + } + + fn layout(s: *const Snake, width: u32, height: u32) Layout { + const tile = @max(1, @min(width / (@as(u32, s.width) + 2), height / (@as(u32, s.height) + 2))); + return .{ .tile = tile, .x = (width -| tile * (@as(u32, s.width) + 2)) / 2, .y = (height -| tile * (@as(u32, s.height) + 2)) / 2 }; + } + + pub fn mouse(s: *Snake, m: addon.Mouse) bool { + if (m.action != .motion and m.action != .drag and m.button != .left) return false; + if (m.action == .press) s.useView(m.view); + const v = s.sizes[m.view]; + s.hover_view = m.view; + s.hover_x = -1; + s.hover_y = -1; + if (m.col == 0xffff or m.row == 0xffff or v.cols == 0 or v.rows == 0) return true; + if (v.glyphs) { + if (m.col < @as(u16, s.width) + 2 and m.row < @as(u16, s.height) + 2) { + s.hover_x = @intCast(m.col); + s.hover_y = @intCast(m.row); + } + } else { + const l = s.layout(@min(4096, @as(u32, v.cols) * v.cell_w), @min(4096, @as(u32, v.rows) * v.cell_h)); + const x = @as(u32, m.col) * v.cell_w + v.cell_w / 2; + const y = @as(u32, m.row) * v.cell_h + v.cell_h / 2; + if (x >= l.x and y >= l.y and (x - l.x) / l.tile < @as(u32, s.width) + 2 and (y - l.y) / l.tile < @as(u32, s.height) + 2) { + s.hover_x = @intCast((x - l.x) / l.tile); + s.hover_y = @intCast((y - l.y) / l.tile); + } + } + return true; + } + + fn opposite(a: Dir, b: Dir) bool { + return a[0] == -b[0] and a[1] == -b[1]; + } + fn same(a: Dir, b: Dir) bool { + return a[0] == b[0] and a[1] == b[1]; + } + + pub fn key(s: *Snake, k: addon.Key) bool { + if (k.code == .esc) return false; + s.useView(k.view); + if (s.dead or k.code == addon.char('r')) { + s.restart(); + return true; + } + const d: Dir = switch (k.code) { + .left, addon.char('h') => .{ -1, 0 }, + .right, addon.char('l') => .{ 1, 0 }, + .up, addon.char('k') => .{ 0, -1 }, + .down, addon.char('j') => .{ 0, 1 }, + else => return false, + }; + const last = if (s.queued > 0) s.turns[s.queued - 1] else s.dir; + if (same(d, last)) return true; + if (opposite(d, last)) { + // A quick j/k correction replaces an uncommitted turn, never a move. + const before = if (s.queued > 1) s.turns[s.queued - 2] else s.dir; + if (s.queued == 0 or opposite(d, before)) return true; + s.turns[s.queued - 1] = d; + } else { + if (s.queued == s.turns.len) return true; + s.turns[s.queued] = d; + s.queued += 1; + } + s.input_pending = true; + return true; + } + + pub fn prefix(s: *const Snake, w: *std.Io.Writer) !void { + try w.print("SnakeShader {d} {d}x{d}{s}", .{ s.score, s.width, s.height, if (s.dead) " over" else "" }); + } + + pub fn paint(s: *const Snake, w: addon.Window, out: addon.Paint) void { + const wall: addon.Style = .{ .fg = .index(8) }; + for (0..@as(usize, s.height) + 2) |y| for (0..@as(usize, s.width) + 2) |x| if (x == 0 or x == s.width + 1 or y == 0 or y == s.height + 1) w.put(x, y, "#", wall); + w.put(1 + s.food.x, 1 + s.food.y, "*", .{ .fg = .index(1), .attrs = .{ .bold = true } }); + for (s.segs[0..s.len], 0..) |p, i| w.put(1 + p.x, 1 + p.y, if (i > 0) "o" else if (s.dead) "x" else "@", .{ .fg = .index(2), .attrs = .{ .bold = i == 0 } }); + if (s.dead) w.put(0, s.height + 2, "game over: any key", .{ .fg = .index(1) }) else if (!w.focused) w.put(0, s.height + 2, "paused", wall); + s.gpuPaint(w, out); + } + + fn gpuPaint(s: *const Snake, w: addon.Window, out: addon.Paint) void { + if (addon.api.abi < 0x30001 or out.out.gpu == null) return; + const width: u32 = @min(4096, @max(1, @as(u32, w.cols) * w.cell_w)); + const height: u32 = @min(4096, @max(1, @as(u32, w.rows) * w.cell_h)); + const phase: f32 = @as(f32, @floatFromInt(s.now % (4 * std.time.ns_per_s))) / std.time.ns_per_s; + const l = s.layout(width, height); + const hover = s.hover_view == w.view; + const uniforms: Uniforms = .{ + .status = .{ @floatFromInt(@intFromBool(s.dead)), @floatFromInt(@intFromBool(w.focused)), @floatFromInt(width), @floatFromInt(height) }, + .points = .{ @floatFromInt(s.segs[0].x), @floatFromInt(s.segs[0].y), @floatFromInt(s.food.x), @floatFromInt(s.food.y) }, + .grid = .{ @floatFromInt(s.width), @floatFromInt(s.height), @floatFromInt(if (hover) s.hover_x else @as(i16, -1)), @floatFromInt(if (hover) s.hover_y else @as(i16, -1)) }, + .motion = .{ phase, @floatFromInt(l.tile), @floatFromInt(l.x), @floatFromInt(l.y) }, + .rows = s.bits(), + }; + const post: [4]f32 = .{ phase, 0, 0, 0 }; + const pipelines = [_]scene.abi.gpu.Pipeline{.{ .vertex = .{ .code = shaders.vert }, .fragment = .{ .code = shaders.frag, .uniform_buffers = 1 }, .stride = 0, .attributes = &.{} }}; + var buffer: [32768]u8 = undefined; + var writer: std.Io.Writer = .fixed(&buffer); + scene.encodePostProcess(&writer, .{ .image = .none, .width = width, .height = height, .pipelines = &pipelines, .draws = &.{.{ .pipeline = 0, .vertex_count = 3, .fragment_uniforms = std.mem.asBytes(&uniforms) }} }, .{ .vertex = .{ .code = shaders.vert }, .fragment = .{ .code = shaders.post, .uniform_buffers = 1 }, .fragment_uniforms = std.mem.asBytes(&post) }) catch return; + _ = out.gpu(writer.buffered()); + } + + pub fn body(s: *const Snake, w: *std.Io.Writer) !void { + try w.print("score {d}\nlength {d}\nsteps {d}\n{s}\nboard {d}x{d}\nhover {d} {d}\n", .{ s.score, s.len, s.steps, if (s.dead) "over" else "alive", s.width, s.height, s.hover_x, s.hover_y }); + } + pub fn ctlRead(s: *const Snake, w: *std.Io.Writer) !void { + try s.body(w); + } + pub const dump = addon.dumpBytes; + + pub fn load(s: *Snake, bytes: []const u8, version: u32) bool { + if (version == 1 and bytes.len == @sizeOf(Legacy)) { + const old = std.mem.bytesToValue(Legacy, bytes); + if (old.len == 0 or old.len > old.segs.len) return false; + s.* = std.mem.zeroInit(Snake, .{ .width = 20, .height = 5, .len = old.len, .food = old.food, .dir = old.dir, .dead = old.dead, .score = old.score, .steps = old.steps, .rng = old.rng }); + @memcpy(s.segs[0..old.len], old.segs[0..old.len]); + if (!same(old.dir, old.turn) and !opposite(old.dir, old.turn)) { + s.turns[0] = old.turn; + s.queued = 1; + } + } else if (!addon.loadBytes(s, bytes, version)) return false; + if (s.width < 3 or s.height < 3 or s.width > max_side or s.height > max_side or s.len == 0 or s.len > @as(u32, s.width) * s.height or s.queued > 2) return false; + for (s.segs[0..s.len]) |p| if (p.x >= s.width or p.y >= s.height) return false; + if (s.food.x >= s.width or s.food.y >= s.height or @abs(s.dir[0]) + @as(u16, @abs(s.dir[1])) != 1) return false; + for (s.turns[0..s.queued]) |d| if (@abs(d[0]) + @as(u16, @abs(d[1])) != 1) return false; + s.hover_x = -1; + s.hover_y = -1; + s.next = .{}; + s.collision_at = 0; + s.input_pending = false; + s.grace_given = false; + return true; + } +}; + +pub const pardes_addon = addon.ops(Snake); +comptime { + addon.exportLib(&pardes_addon); +} + +fn testGame() Snake { + var s = std.mem.zeroInit(Snake, .{ .rng = 3, .hover_x = -1, .hover_y = -1 }); + s.restart(); + s.view(testView(44, 7, 1)); + return s; +} +fn testView(cols: u16, rows: u16, id: u8) addon.View { + return .{ .cols = cols, .rows = rows, .cell_w = 16, .cell_h = 32, .fg = .default, .bg = .default, .sel = .default, .link = .default, .dpi = 96, .max_px = 4096, .fill = true, .glyphs = false, .id = id }; +} +const focused: addon.Flags = .{ .focused = true, .framed = true, ._ = 0 }; + +test "quick opposite corrections and consecutive corners retain intent without reversing" { + var s = testGame(); + const start = s.segs[0]; + _ = s.key(.{ .code = addon.char('j') }); + _ = s.key(.{ .code = addon.char('k') }); + try std.testing.expectEqual(@as(u8, 1), s.queued); + try std.testing.expect(s.step()); + try std.testing.expectEqual(start.y - 1, s.segs[0].y); + _ = s.key(.{ .code = addon.char('j') }); + try std.testing.expectEqual(@as(u8, 0), s.queued); + s.restart(); + _ = s.key(.{ .code = addon.char('j') }); + _ = s.key(.{ .code = addon.char('h') }); + try std.testing.expect(s.step()); + try std.testing.expectEqualDeep(Dir{ 0, 1 }, s.dir); + try std.testing.expect(s.step()); + try std.testing.expectEqualDeep(Dir{ -1, 0 }, s.dir); +} + +test "late turn gets sixty milliseconds and repeated keys cannot stall movement" { + var s = testGame(); + _ = s.tick(1, focused); + const due = s.next.at; + _ = s.key(.{ .code = addon.char('j') }); + _ = s.tick(due - std.time.ns_per_ms, focused); + const extended = s.next.at; + try std.testing.expectEqual(due - std.time.ns_per_ms + grace, extended); + _ = s.key(.{ .code = addon.char('k') }); + _ = s.tick(extended - 1, focused); + try std.testing.expectEqual(extended, s.next.at); + try std.testing.expectEqual(@as(u32, 0), s.steps); + _ = s.tick(extended, focused); + try std.testing.expectEqual(@as(u32, 1), s.steps); + try std.testing.expectEqualDeep(Dir{ 0, -1 }, s.dir); +} + +test "a late wall turn recovers during collision grace and missing it ends the round" { + var s = testGame(); + for (s.segs[0..3], 0..) |*p, i| p.* = .{ .x = @intCast(s.width - 1 - i), .y = 2 }; + s.food = .{ .x = 0, .y = 0 }; + _ = s.tick(1, focused); + const due = s.next.at; + _ = s.tick(due, focused); + try std.testing.expect(!s.dead); + try std.testing.expectEqual(due + grace, s.collision_at); + var missed = s; + _ = missed.key(.{ .code = addon.char('k') }); + _ = missed.tick(due + grace, focused); + try std.testing.expect(missed.dead); + _ = s.key(.{ .code = addon.char('k') }); + _ = s.tick(due + grace - 1, focused); + try std.testing.expect(!s.dead); + try std.testing.expectEqual(@as(u32, 1), s.steps); + try std.testing.expectEqual(@as(u8, 1), s.segs[0].y); +} + +test "board uses whole square cells, resizes safely, and a replica does not change it" { + var s = testGame(); + s.view(testView(80, 30, 1)); + try std.testing.expectEqual(@as(u8, 38), s.width); + try std.testing.expectEqual(@as(u8, 28), s.height); + s.view(testView(30, 10, 2)); + try std.testing.expectEqual(@as(u8, 38), s.width); + const old_head = s.segs[0]; + s.view(testView(80, 40, 1)); + try std.testing.expectEqualDeep(old_head, s.segs[0]); + s.score = 7; + s.len = 5; + for (s.segs[0..s.len], 0..) |*p, i| p.* = .{ .x = @intCast(10 - i), .y = 2 }; + s.resize(3, 3); + try std.testing.expectEqual(@as(u32, 7), s.score); + try std.testing.expectEqual(@as(u16, 3), s.len); + for (s.segs[0..s.len]) |p| try std.testing.expect(p.x < 3 and p.y < 3); + try std.testing.expect(!s.on(s.food.x, s.food.y, s.len)); + const l = s.layout(1333, 977); + try std.testing.expect(l.tile * (s.width + @as(u32, 2)) <= 1333); + try std.testing.expect(l.tile * (s.height + @as(u32, 2)) <= 977); + s.width = max_side; + s.height = max_side; + s.len = 1; + s.segs[0] = .{ .x = 125, .y = 125 }; + const occupied = s.bits(); + try std.testing.expectEqual(@as(u32, 1) << 29, occupied[125][3]); +} + +test "hover maps to discrete cells, clears on leave, and idle animation never moves the snake" { + var s = testGame(); + s.view(testView(80, 30, 1)); + const m: addon.Mouse = .{ .button = .left, .action = .motion, .ctrl = false, .alt = false, .shift = false, .view = 1, .col = 4, .row = 3, .amount = 0 }; + try std.testing.expect(s.mouse(m)); + try std.testing.expectEqual(@as(i16, 2), s.hover_x); + try std.testing.expectEqual(@as(i16, 3), s.hover_y); + const before = s.segs[0]; + try std.testing.expectEqual(10 + animation_period, s.tick(10, .{ .focused = false, .framed = true, ._ = 0 })); + _ = s.tick(10 + animation_period, .{ .focused = false, .framed = true, ._ = 0 }); + try std.testing.expectEqualDeep(before, s.segs[0]); + var leave = m; + leave.col = 0xffff; + leave.row = 0xffff; + _ = s.mouse(leave); + try std.testing.expectEqual(@as(i16, -1), s.hover_x); + _ = s.mouse(m); + s.view(testView(0, 0, 1)); + try std.testing.expectEqual(@as(i16, -1), s.hover_x); + try std.testing.expectEqual(@as(u64, 0), s.tick(100, .{ .focused = false, .framed = false, ._ = 0 })); +} + +test "old records migrate and current records retain geometry and game state on reload" { + var old = std.mem.zeroInit(Legacy, .{ .len = 3, .food = .{ .x = 1, .y = 1 }, .dir = .{ 1, 0 }, .turn = .{ 0, -1 }, .score = 4, .steps = 12, .rng = 3 }); + for (old.segs[0..3], 0..) |*p, i| p.* = .{ .x = @intCast(10 - i), .y = 2 }; + var s: Snake = undefined; + try std.testing.expect(Snake.load(&s, std.mem.asBytes(&old), 1)); + try std.testing.expectEqual(@as(u32, 4), s.score); + try std.testing.expectEqual(@as(u32, 12), s.steps); + try std.testing.expectEqualDeep(old.segs[0], s.segs[0]); + s.view(testView(80, 30, 1)); + var record: [@sizeOf(Snake)]u8 = undefined; + var back: Snake = undefined; + try std.testing.expect(Snake.load(&back, record[0..Snake.dump(&s, &record)], 2)); + try std.testing.expectEqualDeep(s.sizes, back.sizes); + try std.testing.expectEqual(s.score, back.score); + try std.testing.expectEqualDeep(s.segs[0..s.len], back.segs[0..back.len]); + try std.testing.expect(!Snake.load(&back, &record, 3)); + old.len = 101; + try std.testing.expect(!Snake.load(&back, std.mem.asBytes(&old), 1)); +} + +test "GPU fallback stays optional and dynamic board and post uniforms encode without mutation" { + var api = std.mem.zeroes(addon.c.pa_api); + api.abi = 0x30000; + addon.api = &api; + var output = std.mem.zeroes(addon.c.pa_paint); + const paint: addon.Paint = .{ .out = &output }; + try std.testing.expect(!paint.gpu("unused")); + api.abi = 0x30001; + try std.testing.expect(!paint.gpu("unused")); + var s = testGame(); + s.view(testView(80, 30, 1)); + const before = s; + const Capture = struct { + called: bool = false, + fn emit(ctx: ?*anyopaque, bytes: [*c]const u8, n: u32) callconv(.c) c_int { + const self: *@This() = @ptrCast(@alignCast(ctx.?)); + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const frame = scene.decodeFrame(arena.allocator(), bytes[0..n]) catch return 1; + self.called = frame.pass.draws[0].fragment_uniforms.len == @sizeOf(Uniforms) and frame.post != null and frame.post.?.fragment_uniforms.len == 16 and frame.pass.width == 1280 and frame.pass.height == 960; + return 0; + } + }; + var capture: Capture = .{}; + output.gpu = Capture.emit; + output.gpu_ctx = &capture; + var cells: [80 * 30]addon.c.pa_cell = @splat(std.mem.zeroes(addon.c.pa_cell)); + s.paint(.{ .cells = &cells, .stride = 80, .cols = 80, .rows = 30, .cell_w = 16, .cell_h = 32, .focused = true, .view = 1, .glyphs = false }, paint); + try std.testing.expect(capture.called); + try std.testing.expectEqualDeep(s, before); +} @@ -68,10 +68,17 @@ pub fn build(b: *std.Build) void { // A bare `zig build` also copies the binaries into ~/.local/bin. Zig // 0.17 keeps the prefix in the maker process, out of this script's // reach, so `--prefix` no longer turns it off: -Dhome-install=false does. - const home_bin: ?[]const u8 = if (also_gui and (b.option(bool, "home-install", "a bare `zig build` also copies the binaries into ~/.local/bin (default: true)") orelse true)) + const home_enabled = b.option(bool, "home-install", "install binaries and addons into the user directories (default: true)") orelse true; + const home_bin: ?[]const u8 = if (also_gui and home_enabled) if (b.graph.environ_map.get("HOME")) |home| b.pathJoin(&.{ home, ".local", "bin" }) else null else null; + const home_addons: ?[]const u8 = if (!home_enabled) null else if (b.graph.environ_map.get("XDG_DATA_HOME")) |data| + b.pathJoin(&.{ data, "pardes", "addons" }) + else if (b.graph.environ_map.get("HOME")) |home| + b.pathJoin(&.{ home, ".local", "share", "pardes", "addons" }) + else + null; const home_install = home_bin != null; const target = b.standardTargetOptions(.{ .default_target = switch (platform) { @@ -438,6 +445,23 @@ pub fn build(b: *std.Build) void { const kind_mod = b.addTranslateC(.{ .root_source_file = b.path("src/kinds/pardes_addon.h"), .target = target, .optimize = optimize }).createModule(); // ...and what an addon in Zig imports over it (src/kinds/addon.zig). const addon_mod = b.createModule(.{ .root_source_file = b.path("src/kinds/addon.zig"), .target = target, .optimize = optimize, .imports = &.{.{ .name = "pardes_addon", .module = kind_mod }} }); + const snake_shader_step = b.step("snake-shader", "build the optional GPU snake addon into zig-out/lib"); + var snake_shader_lib: ?*std.Build.Step.Compile = null; + if (b.lazyDependency("sketchbook", .{ .@"gpu-only" = true })) |sb| { + const files = b.addWriteFiles(); + for ([_][]const u8{ "vert", "frag", "post.frag" }) |stage| { + const compile = b.addSystemCommand(&.{ "glslc", "-O" }); + compile.addFileArg(b.path(b.fmt("addons/snake_shader/snake.{s}", .{stage}))); + compile.addArg("-o"); + _ = files.addCopyFile(compile.addOutputFileArg(b.fmt("snake.{s}.spv", .{stage})), b.fmt("{s}.spv", .{stage})); + } + const shader_module = b.createModule(.{ .root_source_file = files.add("shaders.zig", "const v align(4) = @embedFile(\"vert.spv\").*;\npub const vert: []const u8 = &v;\nconst f align(4) = @embedFile(\"frag.spv\").*;\npub const frag: []const u8 = &f;\nconst p align(4) = @embedFile(\"post.frag.spv\").*;\npub const post: []const u8 = &p;\n") }); + const module = b.createModule(.{ .root_source_file = b.path("addons/snake_shader/snake_shader.zig"), .target = target, .optimize = optimize, .imports = &.{ .{ .name = "addon", .module = addon_mod }, .{ .name = "gpu_scene", .module = sb.module("gpu_scene") }, .{ .name = "shaders", .module = shader_module } } }); + const lib = b.addLibrary(.{ .name = "snake_shader", .linkage = .dynamic, .root_module = module }); + snake_shader_lib = lib; + snake_shader_step.dependOn(&b.addInstallArtifact(lib, .{}).step); + snake_shader_step.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = module })).step); + } // The PDF addon (addons/pdf/pdf.zig over MuPDF through pdf_bridge.c), built // and installed as the image addon is: compiled only for a step that // needs it (`pdf`, the tests). MuPDF is compiled against the build's @@ -894,7 +918,13 @@ pub fn build(b: *std.Build) void { const gui_c = b.addTranslateC(.{ .root_source_file = header, .target = target, .optimize = optimize }); gui_c.addIncludePath(dep.path("include")); gui_c.addIncludePath(b.path("src/gui")); - gm.addImport("gui_c", gui_c.createModule()); + const gui_c_mod = gui_c.createModule(); + gm.addImport("gui_c", gui_c_mod); + if (b.lazyDependency("sketchbook", .{ .@"gpu-only" = true })) |sb| { + const gpu = b.createModule(.{ .root_source_file = sb.path("src/gpu/Executor.zig"), .imports = &.{ .{ .name = "abi", .module = sb.module("abi") }, .{ .name = "c", .module = gui_c_mod } } }); + gm.addImport("sketch_gpu", gpu); + gm.addImport("gpu_scene", sb.module("gpu_scene")); + } sdl_include = dep.path("include"); if (target.result.os.tag == .macos) { const arch = if (target.result.cpu.arch == .aarch64) "arm64" else @tagName(target.result.cpu.arch); @@ -1151,7 +1181,7 @@ pub fn build(b: *std.Build) void { // The addons, a step each: the default install is the binaries // alone, and `zig build image pdf` (or `addons`) puts the libraries // where the start scan finds them, <prefix>/lib/pardes/addons (and - // ~/.local/lib/pardes/addons with the home install). + // $XDG_DATA_HOME/pardes/addons unless -Dhome-install=false). const addons_step = b.step("addons", "install the image and pdf addons"); for ([_]?*std.Build.Step.Compile{ image_addon, pdf_addon }, [_][]const u8{ "image", "pdf" }) |lib, name| { const step = b.step(name, b.fmt("install the {s} addon, <prefix>/lib/pardes/addons/{s}.so", .{ name, name })); @@ -1161,11 +1191,9 @@ pub fn build(b: *std.Build) void { continue; }; step.dependOn(&b.addInstallFileWithDir(l.getEmittedBin(), .lib, b.fmt("pardes/addons/{s}.so", .{name})).step); - if (home_bin) |dir| { - const copy = b.addSystemCommand(&.{ "install", "-Dm755" }); - copy.addFileArg(l.getEmittedBin()); - copy.addArg(b.pathJoin(&.{ dir, "..", "lib", "pardes", "addons", b.fmt("{s}.so", .{name}) })); - copy.has_side_effects = true; + if (home_addons) |dir| { + const copy = b.addUpdateSourceFiles(); + copy.addCopyFileToSource(l.getEmittedBin(), b.pathJoin(&.{ dir, b.fmt("{s}.so", .{name}) })); step.dependOn(©.step); } } @@ -1645,7 +1673,7 @@ pub fn build(b: *std.Build) void { for ([_]*std.Build.Module{ snake_mod, life_mod, image_mod }) |m| addon_test_step.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = m })).step); // ...and the pdf addon's, which mupdf-check runs too (its script // opens docs/design.pdf, from the build root). - const libs = [_]struct { ?*std.Build.Step.Compile, []const u8 }{ .{ fake_addon_lib.?, "addons/fake/fake" }, .{ snake_lib, "addons/snake/snake" }, .{ life_lib, "addons/life/life" }, .{ pdf_addon, "addons/pdf/pdf" } }; + const libs = [_]struct { ?*std.Build.Step.Compile, []const u8 }{ .{ fake_addon_lib.?, "addons/fake/fake" }, .{ snake_lib, "addons/snake/snake" }, .{ snake_shader_lib, "addons/snake_shader/snake_shader" }, .{ life_lib, "addons/life/life" }, .{ pdf_addon, "addons/pdf/pdf" } }; for (libs) |t| if (t[0]) |lib| { const run_addon_test = b.addRunArtifact(exe); run_addon_test.setCwd(b.path(".")); diff --git a/build.zig.zon b/build.zig.zon index 6e0dc973..ab6a693d 100644 --- a/build.zig.zon +++ b/build.zig.zon @@ -2,6 +2,7 @@ .name = .pardes, .version = "0.24.0", .dependencies = .{ + .sketchbook = .{ .path = "../sketchbook", .lazy = true }, // Every dependency but tree_sitter is lazy: a package that depends // on pardes for its library (build.zig's `library`) fetches // tree-sitter and the grammars it asks for, and none of the rest. diff --git a/docs/typ/building.typ b/docs/typ/building.typ index 31019116..6bf7dfce 100644 --- a/docs/typ/building.typ +++ b/docs/typ/building.typ @@ -41,8 +41,10 @@ system takes the SDK SDL needs with `-Dmacos-sdk=<path>`. A bare `zig build` installs into the prefix (`zig-out`, or `--prefix <dir>`) and copies the binaries into `~/.local/bin`; `-Dhome-install=false` leaves that copy out. Zig 0.17 keeps the prefix from the build script, so -`--prefix` alone no longer stops it. With `-Dplatform` nothing is copied, -so always pass `-Dplatform` while developing. Test, benchmark and run steps build what they need +`--prefix` alone no longer stops it. With `-Dplatform` binaries are not copied. The `image`, `pdf` and +`addons` steps also install into `$XDG_DATA_HOME/pardes/addons` (else +`~/.local/share/pardes/addons`); `-Dhome-install=false` skips that copy. +Pass `-Dplatform` and `-Dhome-install=false` while developing. Test, benchmark and run steps build what they need without installing. `pardes --version` prints `pardes <version>` (from `build.zig.zon`), plus the commit for release builds and the `~/.local` install, and on a second line the build's semantics hash, which a replica @@ -183,6 +185,15 @@ zig build cheatsheet render the cheatsheet PDF (needs typst) - `python3 -B test/agent_session.py <pardes> --ready 'text' --min-rows N -- command args` drives an interactive command in a private shell and checks it through 9P. +The optional real-server check +`python3 -B test/real_zls.py GUI_BINARY ZLS_BINARY OUTPUT_DIRECTORY` +uses a private home and a restricted desktop `PATH`. It checks a build-module +import as the first query without retries, standard and relative imports, +paths with spaces, imported symbols, +hover, references, rename previews, diagnostics and completion while editing. +It requires Zig and ZLS; `core-test -Dtest-filter=lsp_client` checks the +protocol client's own tests without installed language servers. + == Release gates A release passes all of these first: `unit-test` with `-Dplatform=tui` and diff --git a/docs/typ/guide.typ b/docs/typ/guide.typ index df53d0b9..c602927d 100644 --- a/docs/typ/guide.typ +++ b/docs/typ/guide.typ @@ -273,7 +273,8 @@ is drawn as a diff, each hunk in its file's language. #btn("B3") on: ) A `.diff` or `.patch` looked at, and a diff paged (`git show`), opens as -a `+Diff`, stacked as delta shows one: each hunk under its `path:line` +a `+Diff` (`+Diff-<short-hash>` for a commit, each commit keeping its own +pane), stacked as delta shows one: each hunk under its `path:line` (`Space j n`/`Space j p` step through them, #btn("B3") opens it) and the declarations around it, a `+`/`-` before each line, the words a changed line changed tinted and a line added or removed whole faintly. A mailed patch keeps its diff --git a/docs/typ/reference.typ b/docs/typ/reference.typ index 030b7c6a..7360179f 100644 --- a/docs/typ/reference.typ +++ b/docs/typ/reference.typ @@ -1375,3 +1375,30 @@ with Client(sys.argv[1]) as c: # a socket path, or (ip, port) [`pty/run` output], [64 KiB], [file name component], [255 bytes], ) + +== Optional GPU scenes + +ABI 3.1 appends an optional `gpu` callback and its context to `pa_paint`. +An addon checks `api->abi >= 0x30001` before reading it; a null callback +means unsupported. `addon.Paint.gpu(bytes)` does both checks. The callback +copies at most 4 MiB during the call, so a stack buffer is valid. It takes +one self-contained sketchbook SGPU v1 scene, not device pointers. Paint +cells or a raster too: terminals, older hosts and frontends without a GPU +scene executor keep that fallback. Acceptance means the host can carry +the scene, not that every view can render it. + +The SDL frontend runs scenes on its own GPU and composites their target +textures; replicas carry the scene alongside the authoritative pane frame. +The scene codec and executor live in sketchbook (`src/gpu/scene.zig` and +`src/gpu/Executor.zig`). GPU support adds no required addon operation. + +`zig build snake-shader` builds `zig-out/lib/libsnake_shader.so` (with +`glslc`). Load it with `Addon load /absolute/path/libsnake_shader.so`, then +run `SnakeShader`: a GPU board with square cells that expands and shrinks +with its pane. `h j k l` or arrows steer, and `r` restarts. Two turns can +be buffered; a late turn gets 60 ms of grace. Losing focus pauses movement. +Hover highlights a cell; bloom, colour mapping, RGB phosphors and scanlines +give it a CRT appearance, with a subtle food pulse and phosphor shimmer +while paused. A severe shrink can shorten the tail, keeping the score. +The text fallback remains available. A running older host must be upgraded +to display the GPU version. diff --git a/docs/typ/setup.typ b/docs/typ/setup.typ index 2a10c52c..c9556c61 100644 --- a/docs/typ/setup.typ +++ b/docs/typ/setup.typ @@ -119,7 +119,8 @@ script on that `PATH` is a word you can click. = Language servers <language-servers> -pardes starts a language server for a file it knows, from `PATH`: +pardes starts a language server for a file it knows, searching `PATH` first +and then `~/.local/bin` (desktop launchers may leave it out of `PATH`): #pairs( [`.zig`], [`zls` (`PARDES_LSP_ZIG`)], 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/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-<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..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 <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/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(.{}), diff --git a/test/gpu_snake.py b/test/gpu_snake.py new file mode 100644 index 00000000..430cabe9 --- /dev/null +++ b/test/gpu_snake.py @@ -0,0 +1,103 @@ +#!/usr/bin/env python3 +"""GPU snake pixels and frame timings in a private GUI session. + +python3 test/gpu_snake.py BINARY ADDON OUTPUT [--text] [--crt] +The output keeps pixels, timings, and logs; no installed session is touched. +""" +import argparse +import json +import os +from pathlib import Path +import statistics +import subprocess +import time +from ninep import Client + +def wait(check, timeout=15): + until = time.monotonic() + timeout + while time.monotonic() < until: + value = check() + if value: + return value + time.sleep(0.02) + raise TimeoutError('GUI did not reach the expected state') + +def run(binary, addon, root, text=False, crt=False): + root.mkdir(parents=True, exist_ok=True, mode=0o700) + root.chmod(0o700) + config = root / 'config/pardes' + config.mkdir(parents=True, exist_ok=True) + (config / 'init').write_text('Shell /bin/sh\nTheme orchard\n') + fixture = root / 'fixture.txt' + fixture.write_text(''.join((f'line {i:05d}: a reproducible scrolling fixture\n' for i in range(10000)))) + demo = root / 'demo.txt' + if text: + demo.write_text('500 phase scroll\n500 120x16 wheel 1\n2600 120x16 wheel -1\n4800 end\n') + else: + demo.write_text(f'100 exec Addon load {addon}\n200 exec SnakeShader\n500 phase snake\n500 180x16 key r\n3600 end\n') + env = {k: v for k, v in os.environ.items() if not k.startswith('PARDES_')} + env.update(HOME=str(root), XDG_RUNTIME_DIR=str(root), XDG_CONFIG_HOME=str(root / 'config'), PARDES_TEST='1', PARDES_TEST_CAPTURE_DIR=str(root), PARDES_TEST_COLS='100', PARDES_TEST_ROWS='30', SDL_VIDEO_DRIVER='offscreen', PARDES_FRAMES=str(root / 'frames.tsv'), PARDES_FRAMES_DEMO=str(demo)) + with (root / 'stderr.log').open('w') as log: + child = subprocess.Popen([str(binary), '--9p=gpu', str(fixture)], env=env, cwd=root, stdin=subprocess.PIPE, stdout=subprocess.DEVNULL, stderr=log, start_new_session=True) + try: + socket = root / '9p/pardes/gpu' + wait(lambda: socket.exists() or child.poll() is not None) + if child.poll() is not None: + raise AssertionError((child.returncode, (root / 'stderr.log').read_text())) + with Client(socket) as client: + wait(lambda: (root / 'latest.ppm').exists()) + if not text: + wait(lambda: b'snake_shader' in client.read('/index')) + time.sleep(0.4) + (root / 'snake.ppm').write_bytes((root / 'latest.ppm').read_bytes()) + (root / 'index.txt').write_bytes(client.read('/index')) + child.wait(timeout=20) + assert child.returncode == 0, (child.returncode, (root / 'stderr.log').read_text()) + finally: + if child.poll() is None: + child.terminate() + child.wait(timeout=10) + child.stdin.close() + rows = [] + for line in (root / 'frames.tsv').read_text().splitlines(): + if not line or line.startswith('#'): + continue + values = list(map(float, line.split())) + if values[0] >= 500: + rows.append(values) + assert len(rows) >= 20, len(rows) + work = sorted((sum(row[1:4]) for row in rows)) + result = {'frames': len(rows), 'median_work_us': statistics.median(work), 'p95_work_us': work[int(len(work) * 0.95)], 'max_work_us': max(work), 'over_16ms': sum((v > 16667 for v in work))} + if not text: + from PIL import Image + im = Image.open(root / 'snake.ppm').convert('RGB') + green = sum((g > 90 and g > r * 1.7 and (g > b * 1.2) for r, g, b in im.get_flattened_data())) + orange = sum((r > 110 and r > g * 1.5 and (g > b * 1.5) for r, g, b in im.get_flattened_data())) + assert green > 300 and orange > 50, (green, orange) + result.update(green_pixels=green, orange_pixels=orange) + if crt: + pixels = list(im.get_flattened_data()) + triads = scanlines = 0 + for y in range(im.height // 2, im.height - 4): + for x in range(im.width - 3): + at = y * im.width + x + r, g, b = pixels[at:at + 3] + if min(r + g + b) < 8: + continue + if r[0] > g[0] * 1.8 and g[1] > r[1] * 1.8 and b[2] > g[2] * 1.8: + triads += 1 + rows = [pixels[at + 1 + dy * im.width][1] for dy in range(4)] + scanlines += max(rows) > min(rows) * 1.3 + assert triads > 100 and scanlines > 100, (triads, scanlines) + result.update(rgb_triads=triads, scanline_patches=scanlines) + (root / 'result.json').write_text(json.dumps(result, indent=2) + '\n') + print(json.dumps(result), flush=True) +if __name__ == '__main__': + p = argparse.ArgumentParser(description=__doc__) + p.add_argument('binary', type=Path) + p.add_argument('addon', type=Path) + p.add_argument('output', type=Path) + p.add_argument('--text', action='store_true') + p.add_argument('--crt', action='store_true', help='also require the RGB triads and scanline modulation') + a = p.parse_args() + run(a.binary.resolve(), a.addon.resolve(), a.output.resolve(), a.text, a.crt) diff --git a/test/gpu_snake_interaction.py b/test/gpu_snake_interaction.py new file mode 100644 index 00000000..a3e5b2b4 --- /dev/null +++ b/test/gpu_snake_interaction.py @@ -0,0 +1,119 @@ +#!/usr/bin/env python3 +"""Check snake v1 migration, resize, hover and idle animation in a private GUI.""" +import argparse +import io +import json +import os +from pathlib import Path +import subprocess +import time +from PIL import Image, ImageChops, ImageStat +from ninep import Client +from gpu_snake import wait +from daemon import install, processes + +parser = argparse.ArgumentParser(description=__doc__) +for name in ['binary', 'old_addon', 'new_addon', 'output']: + parser.add_argument(name, type=Path) +args = parser.parse_args() +root = args.output.resolve() +root.mkdir(parents=True, mode=0o700) +(root / 'config/pardes').mkdir(parents=True) +(root / 'config/pardes/init').write_text('Shell /bin/bash\nMessageLinger 0\n') +addon = root / 'snake.so' +install(args.old_addon.resolve(), addon) +env = {k: v for k, v in os.environ.items() if not k.startswith('PARDES_')} +env.pop('XDG_DATA_HOME', None) +env.update(HOME=str(root), XDG_RUNTIME_DIR=str(root), XDG_CONFIG_HOME=str(root / 'config'), + PARDES_TEST='1', PARDES_TEST_CAPTURE_DIR=str(root), PARDES_TEST_COLS='100', + PARDES_TEST_ROWS='30', SDL_VIDEO_DRIVER='offscreen', PARDES_DAEMON='on') +log = (root / 'stderr.log').open('w') +p = subprocess.Popen([str(args.binary.resolve()), '--9p=snake'], cwd=root, env=env, + stdin=subprocess.PIPE, stdout=subprocess.DEVNULL, stderr=log, start_new_session=True) +client = None +try: + sock = root / '9p/pardes/snake' + wait(sock.exists) + client = Client(sock) + text = int(client.read('/pane/new')) + client.write(f'/pane/{text}/body', b'unsaved text preserved\n') + shells = wait(lambda: [line for line in client.read('/sessions').splitlines() if line.startswith(b'shell ')]) + + def execute(word): + client.write(f'/pane/{text}/exec', (word + '\n').encode()) + + execute(f'Addon load {addon}') + execute('SnakeShader') + client.write('/focus', str(text).encode()) + snake = int(next(line.split()[0] for line in client.read('/index').splitlines() + if line.split()[1] == b'snake_shader')) + + def body(): + return client.read(f'/pane/{snake}/body').splitlines() + + state = body()[:4] + install(args.new_addon.resolve(), addon) + execute('Addon reload snake_shader') + wait(lambda: len(body()) == 6) + assert body()[:4] == state, body() + time.sleep(.2) + board = body()[4] + execute('Addon reload snake_shader') + time.sleep(.2) + assert body()[:4] == state and body()[4] == board, body() + + screen = json.loads(client.read('/screen')) + rows = [''.join(cell[0] for cell in screen['cells'][i:i + screen['cols']]) + for i in range(0, len(screen['cells']), screen['cols'])] + tag = next(i for i, row in enumerate(rows) if 'SnakeShader' in row) + bottom = next((i for i in range(tag + 1, len(rows)) if ' Collapse ' in rows[i]), len(rows)) + + def capture(name): + stamp = (root / 'latest.ppm').stat().st_mtime_ns + wait(lambda: (root / 'latest.ppm').stat().st_mtime_ns > stamp) + im = Image.open(io.BytesIO((root / 'latest.ppm').read_bytes())).convert('RGB') + im.save(root / (name + '.png')) + return im.crop((0, (tag + 1) * im.height // screen['rows'], im.width, bottom * im.height // screen['rows'])) + + a = capture('idle-a') + time.sleep(.25) + b = capture('idle-b') + idle_change = sum(ImageStat.Stat(ImageChops.difference(a, b)).mean) + assert 0 < idle_change < 2, idle_change + assert body()[:4] == state, body() + client.write('/mousein', f'm 10 {tag + 4} 0\n'.encode()) + wait(lambda: body()[5] != b'hover -1 -1') + hovered = capture('hover') + hover_change = sum(ImageStat.Stat(ImageChops.difference(b, hovered)).mean) + assert hover_change > idle_change, (hover_change, idle_change) + client.write('/mousein', b'm 0 0 0\n') + wait(lambda: body()[5] == b'hover -1 -1') + execute('Newcol') + wait(lambda: body()[4] != board) + assert body()[:4] == state, body() + assert client.read(f'/pane/{text}/body') == b'unsaved text preserved\n' + assert [line for line in client.read('/sessions').splitlines() if line.startswith(b'shell ')] == shells + result = {'state': [line.decode() for line in state], 'before': board.decode(), + 'after': body()[4].decode(), 'idle_pixel_change': idle_change, 'hover_pixel_change': hover_change} + (root / 'result.json').write_text(json.dumps(result, indent=2) + '\n') + print('PASS: migration, reload, resize, hover, idle animation, text and shells', result, flush=True) +except Exception: + if client: + for path in ['/addons', '/log', '/index']: + print(path, client.read(path).decode(), flush=True) + if 'snake' in globals(): + print('game', body(), flush=True) + raise +finally: + if client: + client.socket.close() + if p.poll() is None: + p.kill() + p.wait(timeout=10) + for pid in processes(root): + try: + os.kill(pid, 9) + except ProcessLookupError: + pass + p.stdin.close() + log.close() diff --git a/test/gpu_upgrade.py b/test/gpu_upgrade.py new file mode 100644 index 00000000..bb07e29b --- /dev/null +++ b/test/gpu_upgrade.py @@ -0,0 +1,109 @@ +#!/usr/bin/env python3 +"""Check upgrade, reload, multiple GPU panes and a remote view in isolation.""" +import os +import time +import subprocess +from pathlib import Path +from ninep import Client +from gpu_snake import wait +from daemon import install, processes +import argparse +parser = argparse.ArgumentParser(description='Upgrade, addon reload and GPU replica checks in an isolated session') +for name in ['old', 'new', 'legacy', 'shader', 'output']: + parser.add_argument(name, type=Path) +args = parser.parse_args() +root = args.output.resolve() +root.mkdir(parents=True, exist_ok=True, mode=0o700) +root.chmod(0o700) +print(root, flush=True) +(root / 'config/pardes').mkdir(parents=True) +(root / 'bin').mkdir() +(root / 'config/pardes/init').write_text('Shell /bin/bash\nMessageLinger 0\n') +binary = root / 'bin/pardes-gui' +install(args.old.resolve(), binary) +env = {k: v for k, v in os.environ.items() if not k.startswith('PARDES_')} +env.pop('XDG_DATA_HOME', None) +env.update(HOME=str(root), XDG_RUNTIME_DIR=str(root), XDG_CONFIG_HOME=str(root / 'config'), PARDES_TEST='1', PARDES_TEST_CAPTURE_DIR=str(root), SDL_VIDEO_DRIVER='offscreen', PARDES_DAEMON='on') +log = (root / 'stderr.log').open('w') +p = subprocess.Popen([str(binary), '--9p=upgrade'], env=env, cwd=root, stdin=subprocess.PIPE, stdout=subprocess.DEVNULL, stderr=log, start_new_session=True) +c = None +replica = None +try: + sock = root / '9p/pardes/upgrade' + wait(sock.exists) + c = Client(sock) + print('started', p.pid, flush=True) + initial = c.read('/index').decode() + shell = int(next((l.split()[0] for l in initial.splitlines() if l.split()[1] == 'term'))) + term_before = wait(lambda: [l for l in c.read('/sessions').splitlines() if l.startswith(b'shell ')]) + print('shells', term_before, flush=True) + text = int(c.read('/pane/new')) + c.write(f'/pane/{text}/body', b'unsaved text preserved\n') + c.write(f'/pane/{text}/exec', ('Addon load ' + str(args.legacy.resolve()) + '\n').encode()) + c.write(f'/pane/{text}/exec', b'Snake\n') + c.write('/focus', str(text).encode()) + time.sleep(0.1) + snake = int(next((l.split()[0] for l in c.read('/index').decode().splitlines() if l.split()[1] == 'snake'))) + state = c.read(f'/pane/{snake}/body') + install(args.new.resolve(), binary) + mark = time.time() + c.write(f'/pane/{text}/exec', b'Upgrade\n') + c.socket.close() + c = None + + def connect(): + try: + q = Client(sock) + if q.read(f'/pane/{text}/body') == b'unsaved text preserved\n': + return q + q.socket.close() + except (OSError, EOFError): + return None + wait(lambda: os.stat(f'/proc/{p.pid}/exe').st_ino == binary.stat().st_ino, 30) + c = wait(connect, 30) + wait(lambda: (root / 'latest.ppm').stat().st_mtime > mark, 30) + assert c.read('/status').startswith(f'pid {p.pid}\n'.encode()) + assert [l for l in c.read('/sessions').splitlines() if l.startswith(b'shell ')] == term_before + c.write(f'/pane/{text}/exec', ('Addon load ' + str(args.legacy.resolve()) + '\n').encode()) + assert c.read(f'/pane/{snake}/body') == state + c.write(f'/pane/{text}/exec', ('Addon load ' + str(args.shader.resolve()) + '\n').encode()) + c.write(f'/pane/{text}/exec', b'SnakeShader\n') + c.write('/focus', str(text).encode()) + time.sleep(0.1) + shader = int(next((l.split()[0] for l in c.read('/index').decode().splitlines() if l.split()[1] == 'snake_shader'))) + state = c.read(f'/pane/{shader}/body') + c.write(f'/pane/{text}/exec', b'Addon reload snake_shader\n') + assert c.read(f'/pane/{shader}/body') == state + resized = time.time() + c.write(f'/pane/{text}/exec', b'Newcol\n') + c.write(f'/pane/{text}/exec', b'SnakeShader\n') + c.write('/focus', str(text).encode()) + assert sum(line.split()[1] == b'snake_shader' for line in c.read('/index').splitlines()) == 2 + wait(lambda: (root / 'latest.ppm').stat().st_mtime > resized) + c.remove(f'/pane/{shader}') + caps = root / 'replica' + caps.mkdir() + renv = dict(env, PARDES_TEST_CAPTURE_DIR=str(caps)) + rlog = (root / 'replica.log').open('w') + replica = subprocess.Popen([str(binary), '--attach=upgrade'], env=renv, cwd=root, stdin=subprocess.PIPE, stdout=subprocess.DEVNULL, stderr=rlog, start_new_session=True) + wait(lambda: (caps / 'latest.ppm').exists(), 20) + time.sleep(0.4) + from PIL import Image + im = Image.open(caps / 'latest.ppm').convert('RGB') + green = sum((g > 65 and g > r * 1.7 and (g > b * 1.2) for r, g, b in im.get_flattened_data())) + assert green > 300, green + print('PASS: same pid, shell, unsaved text and snake state; shader reload/resize/close; replica GPU pixels', green, flush=True) + (root / 'result.txt').write_text('PASS: upgrade preserves pid, shell, text and snake; shader reload/resize/close; replica GPU pixels=' + str(green) + '\n') +finally: + if c: + c.socket.close() + for child in [replica, p]: + if child and child.poll() is None: + child.kill() + child.wait(timeout=10) + for pid in processes(root): + try: + os.kill(pid, 9) + except ProcessLookupError: + pass + log.close() diff --git a/test/real_zls.py b/test/real_zls.py new file mode 100644 index 00000000..74f7cd04 --- /dev/null +++ b/test/real_zls.py @@ -0,0 +1,168 @@ +#!/usr/bin/env python3 +"""Real ZLS through Pardes: desktop PATH, imports, hover, references and editing. + +python3 -B test/real_zls.py GUI_BINARY ZLS_BINARY OUTPUT_DIRECTORY +Uses a private HOME and a project with spaces in its path; needs Zig on PATH. +""" +import argparse +import json +import os +from pathlib import Path +import shutil +import struct +import subprocess +from ninep import Client +from gpu_snake import wait +from daemon import processes + +parser = argparse.ArgumentParser(description=__doc__) +for arg in ['binary', 'zls', 'output']: + parser.add_argument(arg, type=Path) +args = parser.parse_args() +root = args.output.resolve() +root.mkdir(parents=True, mode=0o700) +(root / '.local/bin').mkdir(parents=True) +(root / '.local/bin/zls').symlink_to(args.zls.resolve()) +(root / 'desktop-bin').mkdir() +zig = shutil.which('zig') +assert zig, 'Zig must be on PATH' +(root / 'desktop-bin/zig').symlink_to(Path(zig).resolve()) +(root / 'config/pardes').mkdir(parents=True) +(root / 'config/pardes/init').write_text('Shell /bin/bash\nMessageLinger 0\n') +project = root / 'project with spaces' +project.mkdir() +(project / 'build.zig').write_text('''const std = @import("std"); +pub fn build(b: *std.Build) void { + const target = b.standardTargetOptions(.{}); + const helper = b.addModule("helper", .{ .root_source_file = b.path("helper.zig"), .target = target }); + const exe = b.addExecutable(.{ .name = "fixture", .root_module = b.createModule(.{ + .root_source_file = b.path("main.zig"), .target = target, + .imports = &.{.{ .name = "helper", .module = helper }}, + }) }); + b.installArtifact(exe); +} +''') +(project / 'helper.zig').write_text('''/// Double a number. +pub fn double(x: u32) u32 { return x * 2; } +pub fn triple(x: u32) u32 { return x * 3; } +''') +(project / 'local file.zig').write_text('pub const answer: u32 = 42;\n') +source = '''const std = @import("std"); +const local = @import("local file.zig"); +const helper = @import("helper"); +pub fn main() void { + _ = std.mem.len("hello"); + _ = local.answer; + _ = helper.double(21); +} +pub fn broken() void { const unused_local: u32 = 7; } +pub fn broken_too() void { const unused_other: u32 = 8; } +''' +(project / 'main.zig').write_text(source) +env = {k: v for k, v in os.environ.items() if not k.startswith('PARDES_')} +env.pop('XDG_DATA_HOME', None) +env.update(HOME=str(root), PATH=str(root / 'desktop-bin') + ':/usr/bin:/bin', XDG_RUNTIME_DIR=str(root), + XDG_CONFIG_HOME=str(root / 'config'), XDG_CACHE_HOME=str(root / 'cache'), + PARDES_TEST='1', PARDES_TEST_ROWS='60', PARDES_TEST_CAPTURE_DIR=str(root), SDL_VIDEO_DRIVER='offscreen', PARDES_DAEMON='on') +log = (root / 'stderr.log').open('w') +p = subprocess.Popen([str(args.binary.resolve()), '--9p=zls', str(project / 'main.zig')], + env=env, cwd=project, stdin=subprocess.PIPE, stdout=subprocess.DEVNULL, + stderr=log, start_new_session=True) +c = None +passed = [] +try: + sock = root / '9p/pardes/zls' + wait(lambda: sock.exists() or p.poll() is not None) + assert p.poll() is None, (root / 'stderr.log').read_text() + c = Client(sock, timeout=40) + main = int(next(line.split()[0] for line in c.read('/index').splitlines() if b'/main.zig ' in line)) + + def execute(word): + fid = c.open(f'/pane/{main}/exec', 2) + try: + data = (word + '\n').encode() + c.rpc(118, struct.pack('<IQI', fid, 0, len(data)) + data) + answer = c.read_fid(fid).decode().strip() + return c.read('/pane/' + answer + '/body').decode() if answer.isdigit() else '' + finally: + c.close(fid) + + def at(needle, offset=0, text=source): + pos = text.index(needle) + offset + c.write('/focus', str(main).encode()) + c.write(f'/pane/{main}/addr', f'#{pos},#{pos}'.encode()) + c.write(f'/pane/{main}/ctl', b'dot=addr\n') + + def result(suffix, contains=''): + for line in reversed(c.read('/index').splitlines()): + if ('/' + suffix + ' ').encode() in line: + body = c.read('/pane/' + line.split()[0].decode() + '/body').decode() + if contains in body: + return body + return '' + + def definition(needle, offset, ending): + at(needle, offset) + execute('Def') + focus = c.read('/focus').decode().strip() + target = c.read('/pane/' + focus + '/name').decode().strip() + assert target.endswith(ending), (needle, target) + passed.append('definition: ' + needle) + + definition('@import("helper")', 11, '/helper.zig') + definition('@import("std")', 10, '/std/std.zig') + definition('@import("local file.zig")', 12, '/local file.zig') + definition('helper.double', 9, '/helper.zig') + definition('std.mem.len', 9, '/std/mem.zig') + at('helper.double', 9) + hover = execute('Hover') + assert 'Double a number' in hover, hover + passed.append('hover: imported function documentation') + refs = execute('Refs') + assert 'main.zig:' in refs and 'helper.zig:' in refs, refs + passed.append('references: across imported files') + at('local.answer', 8) + rename = execute('Rename renamed_answer') + assert 'renamed_answer' in rename and 'local file.zig:' in rename and 'main.zig:' in rename, rename + passed.append('rename: cross-file preview without changing disk files') + + def diagnostics(): + execute('Diagnostics') + rows = result('+Search', 'Diagnostics ') + return 'main.zig:9:' in rows and 'main.zig:10:' in rows + wait(diagnostics, 20) + passed.append('diagnostics: unused local constant') + partial = source.replace('helper.double(21)', 'helper.') + c.write(f'/pane/{main}/body', partial.encode(), truncate=True) + assert c.read(f'/pane/{main}/body').decode() == partial + at('helper.;', len('helper.'), partial) + c.write('/kbdin', b'i\t') + wait(lambda: 'triple' in result('+Search', 'double')) + passed.append('completion: imported module members in unsaved text') + c.write('/kbdin', b'\x1b') + c.write(f'/pane/{main}/body', source.encode(), truncate=True) + info = execute('Lspinfo') + assert 'zls ready' in info and str(project) in info, info + assert (project / 'main.zig').read_text() == source + assert (project / 'local file.zig').read_text() == 'pub const answer: u32 = 42;\n' + (root / 'lspinfo.txt').write_text(info) + (root / 'result.json').write_text(json.dumps(passed, indent=2) + '\n') + print('PASS:', '; '.join(passed), flush=True) +except Exception: + if c: + print(c.read('/log').decode()[-4000:], flush=True) + print('checks passed:', passed, '\nlast results:', result('+Search'), flush=True) + raise +finally: + if c: + c.socket.close() + if p.poll() is None: + p.kill() + p.wait(timeout=10) + for pid in processes(root): + try: + os.kill(pid, 9) + except ProcessLookupError: + pass + p.stdin.close() + log.close() diff --git a/test/snapshots/pagercolor.golden b/test/snapshots/pagercolor.golden index 9f7f0738..4db82eea 100644 --- a/test/snapshots/pagercolor.golden +++ b/test/snapshots/pagercolor.golden @@ -99,7 +99,7 @@ |6: 3[m\n\033[1m+++ b/x\033[m\n\033[36m@@ -1 +1 @@\033[m\n\033[31m-old\033[m\n\033[32m+new\033[m\n' | |7: $(readlink /proc/$PPID/exe) - |8: $ -|9: /tmp/pardes-snap/pagercolor/cwd/+Diff Save Term Diff Collapse LocationsConfig Del +|9: /tmp/pardes-snap/pagercolor/cwd/+Diff-0123abc Save Term Diff Collapse LocationsConfig Del |10: commit 0123abc |11: x:1 |12: -old @@ -116,7 +116,7 @@ |6: 0-0 d,#608269, 1-1 d,#0d1410, 2-99 #e5eee5,#0d1410, |7: 0-0 d,#608269, 1-1 d,#0d1410, 2-99 #e5eee5,#0d1410, |8: 0-0 d,#608269, 1-1 d,#0d1410, 2-99 #e5eee5,#0d1410, -|9: 0-1 d,#496656, 2-33 #b2c3b8,#1d2824, 34-39 #d3b0d9,#1d2824, 40-99 #b2c3b8,#1d2824, +|9: 0-1 d,#496656, 2-33 #b2c3b8,#1d2824, 34-47 #d3b0d9,#1d2824, 48-99 #b2c3b8,#1d2824, |10: 0-0 d,#608269, 1-1 d,#0d1410, 2-99 #e5eee5,#0d1410, |11: 0-0 d,#608269, 1-1 d,#0d1410, 2-99 #59675c,#0d1410, |12: 0-0 d,#608269, 1-1 d,#0d1410, 2-2 #f1a39b,#1a1d18,b 3-99 #f8c082,#1a1d18, |
