From 4a3c5a48224cf542429504e8728e10c802e1fd52 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Tue, 15 Sep 2026 18:27:49 -0300 Subject: Highlight exact source occurrences in LSP references and goto results --- src/main.zig | 2 ++ 1 file changed, 2 insertions(+) (limited to 'src/main.zig') diff --git a/src/main.zig b/src/main.zig index 2d7b6538..2ee295e1 100644 --- a/src/main.zig +++ b/src/main.zig @@ -379,6 +379,8 @@ test { _ = @import("host_io.zig").Shell; _ = @import("host_io.zig").Lsp; _ = @import("lsp/lsp_client.zig"); + _ = @import("lsp/lsp.zig"); + if (comptime @import("pardes_config").zls_backend) _ = @import("lsp/lsp_zls.zig"); if (comptime pardes.platform == .tty) { _ = @import("tty/tty.zig"); _ = @import("tty/panel_compositor.zig"); -- cgit v1.3 From 3f4f26e0e40d06427e72f72e760d01adcdc0326c Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Tue, 15 Sep 2026 18:52:46 -0300 Subject: Reuse bounded source analysis and speed up result context traversal --- build.zig | 17 ++++ docs/config.md | 3 + docs/locations-performance.md | 45 +++++++++ src/locations.zig | 27 ++++-- src/locations_cache.zig | 213 ++++++++++++++++++++++++++++++++++++++++++ src/main.zig | 1 + src/pardes.zig | 2 + src/syntax.zig | 123 +++++++++++++++++++++--- test/locations_bench.zig | 61 ++++++++++++ test/output.zig | 139 +++++++++++++++++++++++++++ 10 files changed, 607 insertions(+), 24 deletions(-) create mode 100644 docs/locations-performance.md create mode 100644 src/locations_cache.zig create mode 100644 test/locations_bench.zig (limited to 'src/main.zig') diff --git a/build.zig b/build.zig index 8a5b4c41..aeae7443 100644 --- a/build.zig +++ b/build.zig @@ -1009,6 +1009,23 @@ pub fn build(b: *std.Build) void { const lspprobe_step = b.step("lspprobe", "one language query against the real seam (-- : [arg] [--reps N])"); lspprobe_step.dependOn(&run_lspprobe.step); + const locations_bench_step = b.step("locations-bench", "measure cold/warm result formatting (-Doptimize=ReleaseFast; CSV on stderr)"); + if (optimize != .ReleaseFast) { + locations_bench_step.dependOn(&b.addFail("locations-bench requires -Doptimize=ReleaseFast").step); + } else { + const locations_bench_module = b.createModule(.{ + .target = target, + .optimize = .ReleaseFast, + .root_source_file = b.path("test/locations_bench.zig"), + .link_libc = true, + }); + locations_bench_module.addImport("pardes", core_module); + const locations_bench = b.addTest(.{ .root_module = locations_bench_module, .filters = &.{"locations benchmark cold and warm formatting"} }); + const run_locations_bench = b.addRunArtifact(locations_bench); + run_locations_bench.has_side_effects = true; + locations_bench_step.dependOn(&run_locations_bench.step); + } + const perf_optimize: std.builtin.OptimizeMode = .ReleaseFast; const perf_options = b.addOptions(); const perf_target = std.Target.Query.fromTarget(&target.result); diff --git a/docs/config.md b/docs/config.md index 6f3273b9..972f9403 100644 --- a/docs/config.md +++ b/docs/config.md @@ -177,6 +177,9 @@ depth (for example, `main.zig:42 ***`). Ordinary neighboring source lines retain syntax colors; declaration headers do not. A declaration context line ends with ` ...` when source lines are omitted before the next displayed row from that file. +Source analysis is reused across result queries while the source bytes stay the +same. The cache retains at most 64 files and 64 MiB; it checks current buffer or +filesystem contents on each refresh. Open file buffers supply context from their current edits. Missing files still leave the original result available. These settings apply to subsequent result generation and survive `Dump`/`Restore`. Invalid fields reject the entire diff --git a/docs/locations-performance.md b/docs/locations-performance.md new file mode 100644 index 00000000..32ee08bd --- /dev/null +++ b/docs/locations-performance.md @@ -0,0 +1,45 @@ +# Location results performance + +Run `zig build locations-bench -Doptimize=ReleaseFast` from the repository root. +CSV measurements are written to stderr. The benchmark covers 100, 500 and +1,500 matches, both layouts, and ordinary/tree-sitter context separately and +together. Each configuration starts with an empty analysis cache and then +repeats twice with unchanged source and producer results. There are no timing +thresholds in the tests. + +The fixtures are open, unsaved Zig buffers: one module containing functions +with 20 local declarations and one match per function. The largest is +1,813,921 bytes. Timings cover `Output.fillResults`, including sorting, +formatting, metadata and refresh comparison. Source generation, input +allocation, filesystem I/O, subprocess startup and GUI drawing are excluded. + +## Measurement on September 15, 2026 + +Milliseconds for 1,500 matches on the development Linux machine: + +| Layout / context | Before optimization, repeated | After, cold | After, warm repeats | +| --- | ---: | ---: | ---: | +| Inline / declaration headers | 1,259 | 224 | 2.32 / 2.14 | +| Inline / headers and two neighboring lines | 1,250 | 291 | 4.80 / 4.66 | +| Stacked / declaration headers | — | 224 | 2.04 / 1.88 | +| Stacked / headers and two neighboring lines | — | 294 | 3.92 / 3.65 | + +The before figures are medians of three runs of the same fixture with the +previous parser/traversal path. After figures are one cold and two warm +samples from the repository benchmark. Stacked layout has no before figure. +These are focused formatter measurements, not end-to-end GUI latency promises. + +## Changes + +- Declaration traversal uses a tree cursor that retains its ancestor stack. +- Declarations and ordinary-context colors share a single parse. +- Muted declaration headers do not request unused source colors. +- Exact source snapshots cache complete analysis across queries. Unsaved + buffers take precedence; filesystem sources are reread to detect changes. +- The cache retains at most 64 entries and 64 MiB, evicting the least recently + used entry. Oversized analysis is used for the current result without being + retained. Pending context owns its selected color bytes so later eviction + cannot invalidate rows already collected. + +Cold parsing remains proportional to source size. Unchanged refreshes still +read/compare source bytes and assemble results, but skip parsing and analysis. diff --git a/src/locations.zig b/src/locations.zig index 97caf1d9..b34f7a6f 100644 --- a/src/locations.zig +++ b/src/locations.zig @@ -158,17 +158,19 @@ const Pending = struct { } }; -fn sourceText(p: *pardes.Pardes, arena: std.mem.Allocator, dir: []const u8, path: []const u8) ?[]const u8 { +const Source = struct { path: []const u8, bytes: []const u8 }; + +fn sourceText(p: *pardes.Pardes, arena: std.mem.Allocator, dir: []const u8, path: []const u8) ?Source { if (std.ascii.eqlIgnoreCase(std.fs.path.extension(path), ".pdf")) return null; const lexical = std.fs.path.resolvePosix(arena, &.{ dir, path }) catch return null; var pathbuf: [4096]u8 = undefined; const full = if (filesystem.resolve(p, path, dir, &pathbuf)) |resolved| resolved.path else lexical; for (p.panes) |slot| if (slot) |pane| { - if (pane.file) |file| if (file.output == null and (std.mem.eql(u8, file.path, full) or std.mem.eql(u8, file.path, lexical))) return file.content; + if (pane.file) |file| if (file.output == null and (std.mem.eql(u8, file.path, full) or std.mem.eql(u8, file.path, lexical))) return .{ .path = lexical, .bytes = file.content }; }; const bytes = filesystem.read(p, full) catch return null; defer p.gpa.free(bytes); - return arena.dupe(u8, bytes) catch null; + return .{ .path = lexical, .bytes = arena.dupe(u8, bytes) catch return null }; } /// Inputs are sorted results. Expand each source group, merge context with @@ -193,18 +195,22 @@ pub fn format(p: *pardes.Pardes, dir: []const u8, input: []const u8, anchor: ?us const group_start = pending.items.len; try pending.appendSlice(arena, matches.items[first..end]); if (expand and (p.locations_config.context > 0 or p.locations_config.tscontext)) { - if (sourceText(p, arena, dir, path)) |source| { + if (sourceText(p, arena, dir, path)) |text| { + const source = text.bytes; var source_lines: std.ArrayList([]const u8) = .empty; var source_split = std.mem.splitScalar(u8, source, '\n'); while (source_split.next()) |line| try source_lines.append(arena, line); const count = source_lines.items.len; const wanted = try arena.alloc(u8, count); @memset(wanted, 0); - const source_colors = syntax.highlightFileRange(arena, path, source, 0, source.len) catch &.{}; - const declarations = if (p.locations_config.tscontext) - syntax.contextDeclarations(arena, path, source) catch &.{} - else - &.{}; + // Muted declaration headers do not need a source-color pass. + // Exact bytes include unsaved edits and virtual/remote sources. + var cached = p.locations_cache.get(p.tree_sitter_gpa, text.path, source, p.locations_config.tscontext, p.locations_config.context > 0) catch + @import("locations_cache.zig").Result{ .analysis = syntax.analyzeSource(arena, text.path, source, p.locations_config.tscontext, p.locations_config.context > 0) catch .{} }; + defer cached.deinit(p.tree_sitter_gpa); + const analysis = cached.analysis; + const source_colors = analysis.colors; + const declarations = if (p.locations_config.tscontext) analysis.declarations else &.{}; for (pending.items[group_start..]) |*match| { const row = match.at.line -| 1; if (row >= count) continue; @@ -235,7 +241,8 @@ pub fn format(p: *pardes.Pardes, dir: []const u8, input: []const u8, anchor: ?us const declaration = kind & declaration_context != 0; const colors = if (!declaration and offset + line.len <= source_colors.len) source_colors[offset..][0..line.len] else &.{}; const hidden = !declaration or !p.locations_config.tslocations or kind & declaration_start == 0; - try appendContext(arena, &pending, path, line, row, declaration, hidden, colors); + // Later source groups may evict this analysis from the cache. + try appendContext(arena, &pending, path, line, row, declaration, hidden, try arena.dupe(u8, colors)); } } } diff --git a/src/locations_cache.zig b/src/locations_cache.zig new file mode 100644 index 00000000..a079226b --- /dev/null +++ b/src/locations_cache.zig @@ -0,0 +1,213 @@ +const std = @import("std"); +const syntax = @import("syntax.zig"); + +/// A cache hit borrows its analysis; an entry too large to retain transfers +/// ownership instead. Call deinit after consuming either result. +pub const Result = struct { + analysis: syntax.SourceAnalysis, + owned: bool = false, + + pub fn deinit(result: *Result, gpa: std.mem.Allocator) void { + if (result.owned) result.analysis.deinit(gpa); + result.* = undefined; + } +}; + +/// Owned source snapshots keep analysis valid across filesystem changes and +/// borrowed editor buffers. Entries are ordered from least to most recent. +pub const Cache = struct { + pub const max_bytes = 64 * 1024 * 1024; + pub const max_entries = 64; + + const Entry = struct { + path: []u8, + source: []u8, + analysis: syntax.SourceAnalysis, + declarations_ready: bool, + colors_ready: bool, + + fn size(entry: Entry) usize { + return entry.path.len + entry.source.len + entry.analysis.colors.len + + entry.analysis.declarations.len * @sizeOf(syntax.ContextDeclaration); + } + + fn deinit(entry: *Entry, gpa: std.mem.Allocator) void { + gpa.free(entry.path); + gpa.free(entry.source); + entry.analysis.deinit(gpa); + } + }; + + entries: [max_entries]Entry = undefined, + len: usize = 0, + bytes: usize = 0, + analyses: usize = 0, + hits: usize = 0, + + pub fn deinit(cache: *Cache, gpa: std.mem.Allocator) void { + for (cache.entries[0..cache.len]) |*entry| entry.deinit(gpa); + cache.* = .{}; + } + + /// Borrowed slices remain valid until the next get or cache deinit; an + /// owned result remains valid until Result.deinit. All calls for this + /// cache must use the same allocator. Unsupported languages + /// are cached too, including their empty analysis arrays. + pub fn get(cache: *Cache, gpa: std.mem.Allocator, path: []const u8, source: []const u8, want_declarations: bool, want_colors: bool) !Result { + return cache.getBounded(gpa, path, source, want_declarations, want_colors, max_bytes); + } + + fn getBounded(cache: *Cache, gpa: std.mem.Allocator, path: []const u8, source: []const u8, want_declarations: bool, want_colors: bool, budget: usize) !Result { + if (source.len > budget or path.len > budget - source.len) return error.SourceTooLarge; + var previous: ?usize = null; + var declarations = want_declarations; + var colors = want_colors; + for (cache.entries[0..cache.len], 0..) |entry, index| { + if (!std.mem.eql(u8, entry.path, path)) continue; + previous = index; + if (!std.mem.eql(u8, entry.source, source)) break; + if ((!want_declarations or entry.declarations_ready) and (!want_colors or entry.colors_ready)) { + // Moving the small ownership record keeps the underlying + // allocations intact and avoids timestamp/overflow state. + std.mem.copyForwards(Entry, cache.entries[index .. cache.len - 1], cache.entries[index + 1 .. cache.len]); + cache.entries[cache.len - 1] = entry; + cache.hits +|= 1; + return .{ .analysis = entry.analysis }; + } + declarations = declarations or entry.declarations_ready; + colors = colors or entry.colors_ready; + break; + } + // A supported full-source color map needs one byte per source byte. + // Reject that known minimum before parsing, so the caller's uncached + // path does not repeat an expensive analysis for oversized inputs. + const input_bytes = path.len + source.len; + if (colors and syntax.supportsPath(path) and source.len > budget - input_bytes) return error.SourceTooLarge; + var analysis = try syntax.analyzeSource(gpa, path, source, declarations, colors); + errdefer analysis.deinit(gpa); + cache.analyses +|= 1; + const analysis_bytes = analysis.colors.len + analysis.declarations.len * @sizeOf(syntax.ContextDeclaration); + if (analysis_bytes > budget - input_bytes) return .{ .analysis = analysis, .owned = true }; + const owned_path = try gpa.dupe(u8, path); + errdefer gpa.free(owned_path); + const owned_source = try gpa.dupe(u8, source); + errdefer gpa.free(owned_source); + const next: Entry = .{ + .path = owned_path, + .source = owned_source, + .analysis = analysis, + .declarations_ready = declarations, + .colors_ready = colors, + }; + // Commit only after every allocation succeeds. A failed refresh leaves + // the previous cached snapshot usable by the next request. + if (previous) |index| cache.remove(gpa, index); + while (cache.len == max_entries or cache.bytes > budget - next.size()) cache.remove(gpa, 0); + cache.entries[cache.len] = next; + cache.len += 1; + cache.bytes += next.size(); + return .{ .analysis = next.analysis }; + } + + fn remove(cache: *Cache, gpa: std.mem.Allocator, index: usize) void { + cache.bytes -= cache.entries[index].size(); + cache.entries[index].deinit(gpa); + std.mem.copyForwards(Entry, cache.entries[index .. cache.len - 1], cache.entries[index + 1 .. cache.len]); + cache.len -= 1; + } +}; + +test "locations cache validates exact source and path and upgrades analysis" { + const gpa = std.testing.allocator; + syntax.start(gpa); + defer syntax.stop(); + var cache: Cache = .{}; + defer cache.deinit(gpa); + const source = "const Thing = struct {\n value: u32,\n};\n"; + _ = try cache.get(gpa, "a.zig", source, true, false); + try std.testing.expectEqual(@as(usize, 1), cache.analyses); + _ = try cache.get(gpa, "a.zig", source, true, false); + try std.testing.expectEqual(@as(usize, 1), cache.analyses); + try std.testing.expectEqual(@as(usize, 1), cache.hits); + _ = try cache.get(gpa, "a.zig", source, false, true); + try std.testing.expectEqual(@as(usize, 2), cache.analyses); + try std.testing.expect(cache.entries[0].declarations_ready and cache.entries[0].colors_ready); + _ = try cache.get(gpa, "a.zig", source, true, true); + try std.testing.expectEqual(@as(usize, 2), cache.analyses); + _ = try cache.get(gpa, "a.zig", "const Thing = struct {\n other: u32,\n};\n", true, true); + try std.testing.expectEqual(@as(usize, 3), cache.analyses); + try std.testing.expectEqual(@as(usize, 1), cache.len); + _ = try cache.get(gpa, "a.txt", source, true, true); + try std.testing.expectEqual(@as(usize, 4), cache.analyses); + try std.testing.expectEqual(@as(usize, 2), cache.len); +} + +test "locations cache bounds memory and entries and evicts least recently used" { + const gpa = std.testing.allocator; + var cache: Cache = .{}; + defer cache.deinit(gpa); + for (0..Cache.max_entries) |index| { + var path: [32]u8 = undefined; + _ = try cache.get(gpa, try std.fmt.bufPrint(&path, "{d}.unknown", .{index}), "source", false, false); + } + _ = try cache.get(gpa, "0.unknown", "source", false, false); + _ = try cache.get(gpa, "new.unknown", "source", false, false); + try std.testing.expectEqual(Cache.max_entries, cache.len); + try std.testing.expectEqualStrings("2.unknown", cache.entries[0].path); + const count = cache.analyses; + _ = try cache.get(gpa, "0.unknown", "source", false, false); + try std.testing.expectEqual(count, cache.analyses); + cache.deinit(gpa); + _ = try cache.getBounded(gpa, "a.unknown", "source", false, false, 40); + _ = try cache.getBounded(gpa, "b.unknown", "source", false, false, 40); + _ = try cache.getBounded(gpa, "c.unknown", "source", false, false, 40); + try std.testing.expectEqual(@as(usize, 2), cache.len); + try std.testing.expect(cache.bytes <= 40); + try std.testing.expectEqualStrings("b.unknown", cache.entries[0].path); + try std.testing.expectError(error.SourceTooLarge, cache.getBounded(gpa, "large.unknown", "x" ** 41, false, false, 40)); + try std.testing.expectEqual(@as(usize, 2), cache.len); + if (syntax.supportsPath("large.zig")) { + const before = cache.analyses; + try std.testing.expectError(error.SourceTooLarge, cache.getBounded(gpa, "large.zig", "x" ** 25, true, true, 40)); + try std.testing.expectEqual(before, cache.analyses); + } + cache.deinit(gpa); + try std.testing.expectEqual(@as(usize, 0), cache.bytes); + try std.testing.expectEqual(@as(usize, 0), cache.len); +} + +test "locations cache keeps its previous snapshot after allocation failure" { + var failing = std.testing.FailingAllocator.init(std.testing.allocator, .{}); + const gpa = failing.allocator(); + var cache: Cache = .{}; + defer cache.deinit(gpa); + _ = try cache.get(gpa, "a.unknown", "old bytes", false, false); + const retained = cache.bytes; + failing.fail_index = failing.alloc_index; + try std.testing.expectError(error.OutOfMemory, cache.get(gpa, "a.unknown", "new bytes", false, false)); + try std.testing.expectEqual(@as(usize, 1), cache.len); + try std.testing.expectEqual(retained, cache.bytes); + try std.testing.expectEqualStrings("old bytes", cache.entries[0].source); + // This succeeds with allocations still disabled because the old entry + // remains valid and the hit path moves ownership records only. + _ = try cache.get(gpa, "a.unknown", "old bytes", false, false); + try std.testing.expectEqual(@as(usize, 1), cache.hits); +} + +test "locations cache transfers oversized completed analysis without reparsing" { + if (!syntax.supportsPath("large.zig")) return error.SkipZigTest; + const gpa = std.testing.allocator; + syntax.start(gpa); + defer syntax.stop(); + var cache: Cache = .{}; + defer cache.deinit(gpa); + const source = "const Thing = struct {\n value: u32,\n};\n"; + const budget = "large.zig".len + source.len; + var result = try cache.getBounded(gpa, "large.zig", source, true, false, budget); + defer result.deinit(gpa); + try std.testing.expect(result.owned); + try std.testing.expect(result.analysis.declarations.len > 0); + try std.testing.expectEqual(@as(usize, 1), cache.analyses); + try std.testing.expectEqual(@as(usize, 0), cache.len); + try std.testing.expectEqual(@as(usize, 0), cache.bytes); +} diff --git a/src/main.zig b/src/main.zig index 2ee295e1..40ec8667 100644 --- a/src/main.zig +++ b/src/main.zig @@ -369,6 +369,7 @@ test { _ = pardes.config.User; _ = @import("crash.zig"); _ = @import("memory.zig"); + _ = @import("locations_cache.zig"); _ = @import("fs.zig"); _ = @import("detached/wire.zig"); _ = @import("detached/server.zig"); diff --git a/src/pardes.zig b/src/pardes.zig index 2729ef93..c78d4702 100644 --- a/src/pardes.zig +++ b/src/pardes.zig @@ -5969,6 +5969,7 @@ pub const Pardes = struct { next_serial: u32 = 0, settings: config.Runtime = .{ .font = .{ .tagline_percent = config.gui_tagline_font_percent } }, locations_config: locations_config.Config = .{}, + locations_cache: @import("locations_cache.zig").Cache = .{}, tty_filter_palette: panes.Terminal.FilterPalette = .{}, font_request_taken: bool = false, custom_theme: ?Theme = null, @@ -6212,6 +6213,7 @@ pub const Pardes = struct { if (p.custom_theme) |theme_value| std.zon.parse.free(gpa, theme_value); if (p.chord_arg) |a| gpa.free(a); if (p.pipe_wait) |*wait| wait.deinit(gpa); + p.locations_cache.deinit(p.tree_sitter_gpa); p.fs.deinit(gpa); p.shell_rows.reset(gpa); p.scratch.deinit(); diff --git a/src/syntax.zig b/src/syntax.zig index 9e31669f..e637bf67 100644 --- a/src/syntax.zig +++ b/src/syntax.zig @@ -376,28 +376,58 @@ pub fn supportsPath(path: []const u8) bool { return false; } -pub fn contextDeclarations(gpa: std.mem.Allocator, path: []const u8, content: []const u8) ![]ContextDeclaration { - if (!enabled or content.len == 0) return &.{}; - const selected = (try forExt(std.fs.path.extension(path))) orelse return &.{}; - const tree = selected.parser.parseString(content, null) orelse return &.{}; +/// Owned source analysis. Both slices use the allocator passed to analyzeSource. +/// The parsed tree is released before returning; callers can cache this result. +pub const SourceAnalysis = struct { + declarations: []ContextDeclaration = &.{}, + colors: []u8 = &.{}, + + pub fn deinit(self: *SourceAnalysis, gpa: std.mem.Allocator) void { + gpa.free(self.declarations); + gpa.free(self.colors); + self.* = .{}; + } +}; + +pub fn analyzeSource(gpa: std.mem.Allocator, path: []const u8, content: []const u8, want_declarations: bool, want_colors: bool) !SourceAnalysis { + if (!enabled or content.len == 0 or (!want_declarations and !want_colors)) return .{}; + const selected = (try forExt(std.fs.path.extension(path))) orelse return .{}; + const tree = selected.parser.parseString(content, null) orelse return .{}; defer tree.destroy(); + var result: SourceAnalysis = .{}; + errdefer result.deinit(gpa); + if (want_declarations) result.declarations = try declarationsFromTree(gpa, content, tree); + if (want_colors) { + result.colors = try gpa.alloc(u8, content.len); + @memset(result.colors, 0); + paintTree(result.colors, content, selected, tree); + } + return result; +} + +pub fn contextDeclarations(gpa: std.mem.Allocator, path: []const u8, content: []const u8) ![]ContextDeclaration { + const analysis = try analyzeSource(gpa, path, content, true, false); + return analysis.declarations; +} + +fn declarationsFromTree(gpa: std.mem.Allocator, content: []const u8, tree: *ts.Tree) ![]ContextDeclaration { var result: std.ArrayList(ContextDeclaration) = .empty; errdefer result.deinit(gpa); - // Iterative preorder keeps declaration order and avoids recursive traversal - // on deeply nested, partly edited source. - var node = tree.rootNode(); + // The cursor retains its ancestor stack: sibling visits do not repeatedly + // reconstruct parents in broad syntax trees. Preorder preserves source order. + var cursor = tree.rootNode().walk(); + defer cursor.destroy(); while (true) { - if (contextSpan(node, content)) |span| { + const node = cursor.node(); + if (node.isNamed()) if (contextSpan(node, content)) |span| { if (result.items.len == 0 or result.items[result.items.len - 1].start_line != span.start_line or result.items[result.items.len - 1].end_line != span.end_line) try result.append(gpa, span); + }; + if (cursor.gotoFirstChild()) continue; + while (!cursor.gotoNextSibling()) { + if (!cursor.gotoParent()) return result.toOwnedSlice(gpa); } - if (node.namedChild(0)) |child| { - node = child; - continue; - } - while (node.nextNamedSibling() == null) node = node.parent() orelse return result.toOwnedSlice(gpa); - node = node.nextNamedSibling().?; } } @@ -492,6 +522,10 @@ fn contextSpan(node: ts.Node, source: []const u8) ?ContextDeclaration { fn paint(styles: []u8, source: []const u8, selected: Selected) void { const tree = selected.parser.parseString(source, null) orelse return; defer tree.destroy(); + paintTree(styles, source, selected, tree); +} + +fn paintTree(styles: []u8, source: []const u8, selected: Selected, tree: *ts.Tree) void { runQuery(styles, selected, tree, 0); if (std.mem.eql(u8, selected.name, "markdown")) { inject(styles, source, tree.rootNode(), true); @@ -1279,3 +1313,64 @@ test "syntax stacked addresses do not split multiline source groups" { for (styles[at..][0..label.len]) |style| try std.testing.expectEqual(@intFromEnum(Syn.none), style); } } + +test "syntax source analysis preserves declarations and injected colors" { + if (!enabled) return; + const gpa = std.testing.allocator; + start(gpa); + defer stop(); + const Fixture = struct { path: []const u8, source: []const u8 }; + for ([_]Fixture{ + .{ .path = "a.zig", .source = "const Outer = struct {\n // comment\n const Inner = struct {\n pub fn run(\n x: u32,\n ) u32 { return x; }\n };\n};\n" }, + .{ .path = "a.cpp", .source = "namespace Outer {\nstruct Inner {\nint run(\n int x\n) { return x; }\n};\n}\n" }, + .{ .path = "a.rs", .source = "mod outer {\nstruct Inner {}\nimpl Inner {\nfn run(\n &self\n) {}\n}\n}\n" }, + .{ .path = "a.js", .source = "function outer() {\nclass Inner {\nrun(\n x\n) { return x; }\n}\n}\n" }, + .{ .path = "a.py", .source = "class Outer:\n class Inner:\n def run(\n self, x\n ):\n return x\n" }, + .{ .path = "a.md", .source = "# Heading\n\n```zig\npub fn run() void {}\n```\n" }, + .{ .path = "a.typst", .source = "= Heading\n\n```zig\npub fn run() void {}\n```\n" }, + }) |fixture| { + if (!supportsPath(fixture.path)) continue; + var analysis = try analyzeSource(gpa, fixture.path, fixture.source, true, true); + defer analysis.deinit(gpa); + const colors = try highlightFileRange(gpa, fixture.path, fixture.source, 0, fixture.source.len); + defer gpa.free(colors); + try std.testing.expectEqualSlices(u8, colors, analysis.colors); + + // Compare the previous named-node walk to the cursor walk, including + // source ordering, wrapper deduplication and inclusive declaration ends. + const selected = (try forExt(std.fs.path.extension(fixture.path))).?; + const tree = selected.parser.parseString(fixture.source, null).?; + defer tree.destroy(); + var reference: std.ArrayList(ContextDeclaration) = .empty; + defer reference.deinit(gpa); + var node = tree.rootNode(); + walk: while (true) { + if (contextSpan(node, fixture.source)) |span| { + if (reference.items.len == 0 or reference.items[reference.items.len - 1].start_line != span.start_line or + reference.items[reference.items.len - 1].end_line != span.end_line) + try reference.append(gpa, span); + } + if (node.namedChild(0)) |child| { + node = child; + continue; + } + while (node.nextNamedSibling() == null) node = node.parent() orelse break :walk; + node = node.nextNamedSibling().?; + } + try std.testing.expectEqual(reference.items.len, analysis.declarations.len); + for (reference.items, analysis.declarations) |old, new| try std.testing.expect(std.meta.eql(old, new)); + + var declarations_only = try analyzeSource(gpa, fixture.path, fixture.source, true, false); + defer declarations_only.deinit(gpa); + try std.testing.expectEqual(@as(usize, 0), declarations_only.colors.len); + try std.testing.expectEqual(analysis.declarations.len, declarations_only.declarations.len); + var colors_only = try analyzeSource(gpa, fixture.path, fixture.source, false, true); + defer colors_only.deinit(gpa); + try std.testing.expectEqual(@as(usize, 0), colors_only.declarations.len); + try std.testing.expectEqualSlices(u8, analysis.colors, colors_only.colors); + } + var unsupported = try analyzeSource(gpa, "a.unknown", "text", true, true); + unsupported.deinit(gpa); + try std.testing.expectEqual(@as(usize, 0), unsupported.declarations.len); + try std.testing.expectEqual(@as(usize, 0), unsupported.colors.len); +} diff --git a/test/locations_bench.zig b/test/locations_bench.zig new file mode 100644 index 00000000..54cebb59 --- /dev/null +++ b/test/locations_bench.zig @@ -0,0 +1,61 @@ +const std = @import("std"); +const pds = @import("pardes"); +const loc = pds.locations_config; +fn now() u64 { + var ts: std.c.timespec = undefined; + _ = std.c.clock_gettime(.MONOTONIC, &ts); + return @as(u64, @intCast(ts.sec)) * 1_000_000_000 + @as(u64, @intCast(ts.nsec)); +} +// Run: zig build locations-bench -Doptimize=ReleaseFast +// Timed work is the real Output.fillResults pipeline. Fixtures are open unsaved +// sources; source generation, input duplication, rendering and subprocesses are +// excluded. Each layout/config starts with an empty source-analysis cache. +// Two repeats retain that cache and existing output. No latency threshold applies. +test "locations benchmark cold and warm formatting" { + if (!pds.syntax.supportsPath("large.zig")) return error.ZigGrammarRequired; + std.debug.print("layout,context,matches,source_bytes,phase,repeat,elapsed_ns\n", .{}); + const gpa = std.heap.smp_allocator; + for ([_]usize{ 100, 500, 1500 }) |functions| { + var source: std.Io.Writer.Allocating = .init(gpa); + defer source.deinit(); + var input: std.Io.Writer.Allocating = .init(gpa); + defer input.deinit(); + try source.writer.writeAll("pub const Module = struct {\n"); + var row: usize = 2; + for (0..functions) |i| { + try source.writer.print(" pub fn f{d}(x: u32) u32 {{\n", .{i}); + row += 1; + for (0..20) |j| { + try source.writer.print(" const v{d} = x + {d}; // explanatory source comment\n", .{ j, j }); + row += 1; + } + const line = " return x; // BENCH_MATCH"; + try source.writer.print("{s}\n }}\n", .{line}); + try input.writer.print("large.zig:{d}:1 {s}\n", .{ row, line }); + row += 2; + } + try source.writer.writeAll("};\n"); + const p = try pds.Pardes.init(gpa, .{ .tty_only = true, .cols = 120, .rows = 40 }); + defer p.deinit(); + const pane = try p.setTestFile(source.written()); + gpa.free(pane.file.?.path); + pane.file.?.path = try gpa.dupe(u8, "/bench/large.zig"); + for ([_]loc.Config.Layout{ .@"inline", .stacked }) |layout| { + for ([_]loc.Config{ .{ .context = 0, .tscontext = false }, .{ .context = 2, .tscontext = false }, .{ .context = 0, .tscontext = true }, .{ .context = 2, .tscontext = true } }, 0..) |config, mode| { + p.locations_config = config; + p.locations_cache.deinit(p.tree_sitter_gpa); + p.locations_cache = .{}; + p.locations_config.layout = layout; + for (0..3) |rep| { + _ = p.scratch.reset(.retain_capacity); + const data = try gpa.dupe(u8, input.written()); + const t = now(); + try pds.panes.Output.fillResults(p, 0, "/bench", .{ .cmd = .Grep }, "BENCH_MATCH", data, null); + const elapsed = now() - t; + const modes = [_][]const u8{ "off", "ordinary", "tree_sitter", "both" }; + std.debug.print("{s},{s},{d},{d},{s},{d},{d}\n", .{ @tagName(layout), modes[mode], functions, source.written().len, if (rep == 0) "cold" else "warm", rep, elapsed }); + } + } + } + } +} diff --git a/test/output.zig b/test/output.zig index c738a661..21e9f04c 100644 --- a/test/output.zig +++ b/test/output.zig @@ -1585,3 +1585,142 @@ test "stacked search and LSP results retain source tint navigation and dump owne } } } + +test "location analysis cache refreshes unsaved ancestry and query context" { + if (!pardes.syntax.enabled) return error.SkipZigTest; + const before = "const Outer = struct {\n" ++ + " fn first() void {\n" ++ + " marker();\n" ++ + " }\n" ++ + " fn second() void {\n" ++ + " marker();\n" ++ + " }\n" ++ + "};\n"; + const after = "pub fn revised() void {\n // new neighbor\n marker();\n}\n"; + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true }); + defer p.deinit(); + const source = try p.setTestFile(before); + p.gpa.free(source.file.?.path); + source.file.?.path = try p.gpa.dupe(u8, "/analysis-cache.zig"); + p.locations_config = .{ .context = 0, .tscontext = true, .tslocations = false }; + const Runner = struct { + fn fill(editor: *Pardes, line: usize) !void { + const path = editor.panes[0].?.file.?.path; + const input = try std.fmt.allocPrint(editor.gpa, "{s}:{d}:9-14 marker();\n", .{ path, line }); + try panes.Output.fillResults(editor, 0, "/", .search, "marker", input, 0); + } + }; + try Runner.fill(p, 3); + const id = source.search_pane.?; + const file = &p.panes[id].?.file.?; + try std.testing.expect(std.mem.indexOf(u8, file.content, "const Outer") != null); + try std.testing.expect(std.mem.indexOf(u8, file.content, "fn first") != null); + try std.testing.expect(std.mem.indexOf(u8, file.content, "fn second") == null); + const original = file.content.ptr; + const revision = file.revision; + const analyses = p.locations_cache.analyses; + const hits = p.locations_cache.hits; + try Runner.fill(p, 3); + try std.testing.expectEqual(id, source.search_pane.?); + try std.testing.expectEqual(original, file.content.ptr); + try std.testing.expectEqual(revision, file.revision); + try std.testing.expectEqual(analyses, p.locations_cache.analyses); + try std.testing.expect(p.locations_cache.hits > hits); + + // Reusing analysis must still choose the ancestry of the current match. + try Runner.fill(p, 6); + try std.testing.expectEqual(analyses, p.locations_cache.analyses); + try std.testing.expect(std.mem.indexOf(u8, file.content, "const Outer") != null); + try std.testing.expect(std.mem.indexOf(u8, file.content, "fn first") == null); + try std.testing.expect(std.mem.indexOf(u8, file.content, "fn second") != null); + const match = file.location_rows[source.search_row.?]; + try std.testing.expectEqual(.match, match.kind); + try std.testing.expectEqual(@as(usize, 6), match.at.line); + + // The path stays identical, but an unsaved replacement changes its tree. + panes.File.setContent(p, &source.file.?, try p.gpa.dupe(u8, after)); + try Runner.fill(p, 3); + try std.testing.expect(p.locations_cache.analyses > analyses); + try std.testing.expect(std.mem.indexOf(u8, file.content, "fn revised") != null); + try std.testing.expect(std.mem.indexOf(u8, file.content, "const Outer") == null); + try std.testing.expect(std.mem.indexOf(u8, file.content, "fn second") == null); + try std.testing.expect(std.mem.indexOf(u8, file.content, "new neighbor") == null); + + p.locations_config.context = 1; + try Runner.fill(p, 3); + try std.testing.expect(std.mem.indexOf(u8, file.content, "fn revised") != null); + try std.testing.expect(std.mem.indexOf(u8, file.content, "new neighbor") != null); + const expanded = try p.gpa.dupe(u8, file.content); + defer p.gpa.free(expanded); + const expanded_analyses = p.locations_cache.analyses; + p.locations_config.context = 0; + try Runner.fill(p, 3); + try std.testing.expect(std.mem.indexOf(u8, file.content, "new neighbor") == null); + p.locations_config.context = 1; + try Runner.fill(p, 3); + try std.testing.expectEqualStrings(expanded, file.content); + try std.testing.expectEqual(expanded_analyses, p.locations_cache.analyses); + p.locations_config.tscontext = false; + try Runner.fill(p, 3); + try std.testing.expect(std.mem.indexOf(u8, file.content, "fn revised") == null); + try std.testing.expect(std.mem.indexOf(u8, file.content, "new neighbor") != null); + try std.testing.expectEqualStrings(after, source.file.?.content); +} + +test "location cache eviction retains early colors and honors disk and unsaved replacements" { + if (!pardes.syntax.enabled) return error.SkipZigTest; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + var dir_buf: [4096]u8 = undefined; + const dir = dir_buf[0..try tmp.dir.realPath(std.testing.io, &dir_buf)]; + const comment = "/* open\nconst int value = 42;\n*/\nneedle();\n"; + const code = "// open\nconst int value = 42;\n//\nneedle();\n"; + try std.testing.expectEqual(comment.len, code.len); + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true }); + defer p.deinit(); + const source = try p.setTestFile("notes\n"); + p.locations_config = .{ .context = 3, .tscontext = false }; + var input: std.Io.Writer.Allocating = .init(p.gpa); + defer input.deinit(); + for (0..65) |index| { + var name_buf: [32]u8 = undefined; + const name = try std.fmt.bufPrint(&name_buf, "f{d:0>2}.c", .{index}); + try tmp.dir.writeFile(std.testing.io, .{ .sub_path = name, .data = if (index == 0) comment else code }); + try input.writer.print("{s}:4:1-6 needle();\n", .{name}); + } + try panes.Output.fillResults(p, 0, dir, .search, "eviction", try p.gpa.dupe(u8, input.written()), null); + const id = source.search_pane.?; + const file = &p.panes[id].?.file.?; + try std.testing.expectEqual(@as(usize, 64), p.locations_cache.len); + try std.testing.expectEqual(@as(usize, 65), p.locations_cache.analyses); + const Color = struct { + fn valueColor(result: *const panes.File.State) !u8 { + for (result.location_rows, 0..) |row, index| { + if (row.kind != .context or row.at.line != 2 or !std.mem.endsWith(u8, row.path, "f00.c")) continue; + const line = modal.lineSlice(result.content, index); + const number = std.mem.indexOf(u8, line[row.code_start..], "42").?; + try std.testing.expectEqualStrings("const int value = 42;", line[row.code_start..]); + try std.testing.expectEqual(line.len - row.code_start, row.colors.len); + return row.colors[number]; + } + return error.MissingEarlyContext; + } + }; + try std.testing.expectEqual(@intFromEnum(pardes.syntax.Syn.comment), try Color.valueColor(file)); + const single = "f00.c:4:1-6 needle();\n"; + // Put the evicted file back before a same-size edit tests exact-byte keys. + try panes.Output.fillResults(p, 0, dir, .search, "eviction", try p.gpa.dupe(u8, single), null); + const analyses = p.locations_cache.analyses; + try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "f00.c", .data = code }); + try panes.Output.fillResults(p, 0, dir, .search, "eviction", try p.gpa.dupe(u8, single), null); + try std.testing.expect(p.locations_cache.analyses > analyses); + try std.testing.expectEqual(@intFromEnum(pardes.syntax.Syn.number), try Color.valueColor(file)); + + // An open buffer has priority over that disk revision, even with equal size. + p.gpa.free(source.file.?.path); + source.file.?.path = try std.fs.path.join(p.gpa, &.{ dir, "f00.c" }); + panes.File.setContent(p, &source.file.?, try p.gpa.dupe(u8, comment)); + try panes.Output.fillResults(p, 0, dir, .search, "eviction", try p.gpa.dupe(u8, single), null); + try std.testing.expectEqual(@intFromEnum(pardes.syntax.Syn.comment), try Color.valueColor(file)); + try std.testing.expectEqualStrings(comment, source.file.?.content); +} -- cgit v1.3 From c1990b3e6e196ad41379aa432bf3ccca8a65d9f0 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Sun, 20 Sep 2026 00:36:50 -0300 Subject: Flatten the 9P control tree and move it out of fs.zig The served tree loses the self/ level: /index /ctl /new /log /screen /listeners /pane//... /os, with /src only in -Dembed-sources=true builds (default off, on for esp32p4). ctl speaks the editor's own language with two lowercase verbs, look TEXT and exec TEXT, plus acme's addr verbs; the new/ factory directory becomes one clone file; cons is gone (exec Msg); name and sel are files; stats report real lengths, modes and mtimes; /log streams pane new/del/rename/save events. The tree code lives in src/ninep/ (tree, pane, ctl, addr, pty, events, screen, sources); fs.zig keeps host access, mounts, resolution and find/grep. Same engine and transports. README (fs-help.txt) and docs rewritten; tests updated and extended. Co-Authored-By: Claude Fable 5.1 --- build.zig | 6 +- docs/config.md | 3 +- docs/fs.md | 126 +- docs/v9fs.md | 12 +- src/9p.zig | 2 +- src/9p_io.zig | 39 +- src/CHANGELOG.md | 10 + src/effect_sources.zig | 1 + src/fs-help.txt | 103 +- src/fs.zig | 3594 +------------------------------------------- src/main.zig | 4 +- src/memory.zig | 5 +- src/ninep/addr.zig | 276 ++++ src/ninep/ctl.zig | 503 +++++++ src/ninep/events.zig | 558 +++++++ src/ninep/pane.zig | 840 +++++++++++ src/ninep/pty.zig | 388 +++++ src/ninep/screen.zig | 351 +++++ src/ninep/sources.zig | 152 ++ src/ninep/testing.zig | 135 ++ src/ninep/tree.zig | 850 +++++++++++ src/panes.zig | 7 +- src/pardes.zig | 34 +- src/tutor.txt | 25 +- test/agent_session.py | 14 +- test/appearance_gallery.py | 26 +- test/collapse_layout.py | 8 +- test/column_tags.py | 32 +- test/font_size.py | 2 +- test/fs.py | 367 +++-- test/fs_bench.zig | 43 +- test/fs_namespace.zig | 12 +- test/fs_soak.py | 29 +- test/look_placement.py | 8 +- test/ninep.py | 39 +- test/output.zig | 12 +- test/panes.zig | 8 +- test/pdf_scroll_bench.zig | 18 +- test/snapshot.zig | 2 +- test/tag_cleanup.py | 10 +- test/ui_review.py | 50 +- test/v9fs.py | 33 +- test/v9fs_terminal.py | 6 +- test/window_opacity.py | 12 +- 44 files changed, 4779 insertions(+), 3976 deletions(-) create mode 100644 src/ninep/addr.zig create mode 100644 src/ninep/ctl.zig create mode 100644 src/ninep/events.zig create mode 100644 src/ninep/pane.zig create mode 100644 src/ninep/pty.zig create mode 100644 src/ninep/screen.zig create mode 100644 src/ninep/sources.zig create mode 100644 src/ninep/testing.zig create mode 100644 src/ninep/tree.zig (limited to 'src/main.zig') diff --git a/build.zig b/build.zig index aeae7443..6734d9b0 100644 --- a/build.zig +++ b/build.zig @@ -104,6 +104,7 @@ pub fn build(b: *std.Build) void { ninep_options.addOption(bool, "quic", enable_quic); const enable_mupdf = b.option(bool, "mupdf", "native PDF rendering with MuPDF (AGPL/commercial; native default on, web/esp32p4 off; -Dmupdf=false disables)") orelse !freestanding_core; const enable_jpx = b.option(bool, "jpx", "JPEG 2000 in PDFs, for scanned documents (default on; -Djpx=false drops openjpeg)") orelse true; + const embed_sources = b.option(bool, "embed-sources", "serve the editor's own sources under /src of its 9P tree (default off; on for -Dplatform=esp32p4, whose only source is the device)") orelse is_esp32p4; const is_web_target = target.result.cpu.arch == .wasm32 and target.result.os.tag == .freestanding; const is_esp32p4_target = target.result.cpu.arch == .riscv32 and target.result.os.tag == .freestanding; const optimize = if (is_web) @@ -309,6 +310,7 @@ pub fn build(b: *std.Build) void { .esp32p4_rows = esp32p4_rows, .theme_animation = theme_animation, .prebuilt_shaders = prebuilt_shaders, + .embed_sources = embed_sources, .zig_lib_dir = b.graph.zig_lib_directory.path orelse "", .commit = gitCommit(b), }; @@ -600,8 +602,6 @@ pub fn build(b: *std.Build) void { if (shell == .macos) mod.addAnonymousImport("effect-source-crt.ci.metal", .{ .root_source_file = b.path("shaders/crt.ci.metal"), }); - mod.addAnonymousImport("root-build.zig", .{ .root_source_file = b.path("build.zig") }); - mod.addAnonymousImport("root-build.zig.zon", .{ .root_source_file = b.path("build.zig.zon") }); } const gui_shell_mod: ?*std.Build.Module = gui_mod orelse @@ -1435,6 +1435,7 @@ const ShellConfig = struct { /// the default is off for the board and on everywhere else. theme_animation: ?bool, prebuilt_shaders: bool, + embed_sources: bool, zig_lib_dir: []const u8, commit: ?[]const u8, }; @@ -1456,6 +1457,7 @@ fn shellOptions(b: *std.Build, cfg: ShellConfig, platform: Platform) *std.Build. // prevents Config/EffectCode from describing tty/macOS/web as "prebuilt". o.addOption(bool, "gui_shader_sources_prebuilt", platform == .gui and cfg.prebuilt_shaders); o.addOption([]const u8, "zls_version", if (cfg.zls_backend) zls_version else "none"); + o.addOption(bool, "embed_sources", cfg.embed_sources); o.addOption([]const u8, "version", zon.version); // ...and the commit it was built from, when there is one. See `gitCommit` // for why this is optional and why it is read at configure time. diff --git a/docs/config.md b/docs/config.md index 972f9403..a55aef1c 100644 --- a/docs/config.md +++ b/docs/config.md @@ -496,7 +496,8 @@ palette; Ripple and Glitch primarily perturb sample coordinates. `EffectCode PanelAscii` or `EffectCode Crt` lists the current backend's build-embedded source paths under `/virtual`. Look opens each full file; -no checkout is needed. TTY exposes grid transitions, native GUI builds also +no checkout is needed, but the build must carry them (`-Dembed-sources=true`, +the default only for esp32p4); otherwise the command reports them unavailable. TTY exposes grid transitions, native GUI builds also expose scene shaders, and web has neither. Shared implementations share paths. SDL reports whether GLSL was compiled during this build or came from the `-Dprebuilt-shaders` snapshot paired with the committed SPIR-V. diff --git a/docs/fs.md b/docs/fs.md index 942a26a3..c16f810b 100644 --- a/docs/fs.md +++ b/docs/fs.md @@ -16,9 +16,13 @@ Explicit paths bypass that search: | Editor path | Meaning | 9P server path | |---|---|---| | `/n/os/proc/self` | OS filesystem | `/os/proc/self` | -| `/n/self/pane/2/body` | pane 2's text | `/self/pane/2/body` | -| `/virtual/src/pardes.zig` | source embedded in this build | `/self/src/pardes.zig` | -| `/n/peer/self/pane/2/body` | another session's text | peer's `/self/pane/2/body` | +| `/n/self/pane/2/body` | pane 2's text | `/pane/2/body` | +| `/virtual/pane/2/body` | the same, in the editor's own spelling | `/pane/2/body` | +| `/virtual/src/pardes.zig` | source embedded in this build | `/src/pardes.zig` | +| `/n/peer/pane/2/body` | another session's text | peer's `/pane/2/body` | + +The mount name `self` is reserved and maps to the server root, so `/n/self/X` +and `/virtual/X` both name the served `/X`. `--mount=peer=work` mounts the named session `work`; the dial can also be an absolute socket path, `unix!/path`, `tcp!IP!port`, or `quic!IP!port`. @@ -31,7 +35,7 @@ pending Save. Mounts are saved in dumps. Save uses the file's original mount. socket. Build with `-Dquic=true` and system OpenSSL 3.6+ to enable QUIC; `--9p-quic='quic!127.0.0.1!5641'` adds its listener. Both accept numeric IPv4/IPv6 addresses, not DNS names. Listener port zero chooses a free port; -`/self/listeners` reports all active dial addresses. +`/listeners` reports all active dial addresses. All connections have session access, including `os`. TCP is unencrypted. QUIC uses an ephemeral TLS identity without peer verification or login. @@ -40,56 +44,108 @@ The four application connection slots are shared across transports; OpenSSL's internal buffers are separate, dynamically allocated memory. [Plan9port's client](https://9fans.github.io/plan9port/man/man1/9p.html) can -drive Unix or TCP without a kernel mount: +drive Unix or TCP without a kernel mount, and `9ns` mounts the tree in a +private namespace: ```sh -9p -n -a "unix!$PARDES_9P" read self/index -9p -n -a 'tcp!127.0.0.1!5640' read self/index +9p -n -a "unix!$PARDES_9P" read index +9p -n -a 'tcp!127.0.0.1!5640' ls pane/1 +9ns --unix "$PARDES_9P" -- sh -c 'cat "$NINE_MOUNT/index"' ``` For [Linux v9fs](https://www.kernel.org/doc/html/latest/filesystems/9p.html), use `version=9p2000,cache=none,access=any` and `trans=unix`, or `trans=tcp` with `port=5640`. Set `uname`, `dfltuid`, and `dfltgid` for the local user. -Leave `aname` empty: the mount root contains `os` and `self`. The opt-in +Leave `aname` empty. The opt-in [Linux v9fs experiment](v9fs.md) tests a kernel mount in a separate subprocess namespace (`zig build v9fs-test`, requiring explicit mount authorization). Neither 9P2000.u nor 9P2000.L is implemented. Existing Plan9port/v9fs clients need a userspace bridge for QUIC. -The server root contains `os` and `self`. Under `self`, `index` lists panes, -`README` explains the interface. `new/` lists its creation endpoints and another -`README`; listing, walking and statting entries do not create panes. Opening -`new/ctl` creates a pane and returns its serial, and `pane/` contains -`body`, `tag`, `ctl`, `addr`, `data`, `event`, and selection files. Terminal -panes additionally have `pty/{ctl,status,data}`. - -`EffectCode ` lists the current backend's embedded implementation -files under `/virtual`; Look opens their full source. - -`self/screen` returns JSON with `cols`, `rows`, `cursor`, a `styles` table, -and row-major `cells` of `[grapheme, style_index]`. Each open freezes one -frame until close, including across multiple reads. The independent client -can inspect it directly with `Client(socket_path).screen()`. - -A terminal `body` freezes its history on the first read of each open handle; -later reads use the same bytes while output continues. Close and reopen for -newer history, or read `pty/data` for the live stream. Screen and terminal-body -snapshots share 32 handle slots, released on close or disconnect. - -Writing `body` appends; opening it with truncation replaces its contents. -`addr` selects a range and `data` replaces that range. `ctl` accepts `name`, -`look `, `get`, `put`, `del`, and `delete`. Look resolves from that pane -without editing its body or tag. Holding `event` open redirects the pane's Look +## The served tree + +``` +/README this guide, also src/fs-help.txt +/index one line per pane: serial, kind (text|term|pdf|image), dirty flag, name +/ctl write: one command per line; read: the serials the last command made or touched +/new reading it creates one empty pane and answers "\n" (the /net/tcp/clone idiom) +/log one line per editor event: new|del|rename|save ; reads park +/screen rendered screen JSON; frozen per open handle +/listeners the session's dial addresses +/pane// name body tag ctl addr data xdata sel errors event, plus pty/{ctl,status,data} +/os/ the host filesystem +/src/ the editor's embedded sources, only when built with -Dembed-sources=true +``` + +Nothing in the tree is created by list, stat, walk or read, except that +reading `/new` makes a pane; that is its whole purpose, so a recursive read +of the tree makes one pane per open of it. + +`/ctl` and `/pane//ctl` take the editor's own command language, two verbs: + +- `look TEXT` is a right click on `TEXT`: a path opens a file, `file:12` jumps + to a line, a directory opens a shell there, a URL opens in the browser. From + `/ctl` the look happens at the active pane; from a pane's `ctl` at that pane. +- `exec TEXT` is a middle click: a command word from `src/builtins.zig` + (`Save`, `Del`, `New`, `Newcol`, `Mount NAME DIAL`, `Unmount NAME`, `Dump`, + `Restore`, `Msg TEXT`, `Find`, `Grep`, `Tty`, ...), or anything else, which + runs in the pane's terminal. + +Both verbs are lowercase; the words after `exec` are the editor's capitalized +commands. A pane's `ctl` also keeps acme's addr verbs (`addr=dot`, `dot=addr`, +`limit=addr`, `clean`, `dirty`, `cleartag`, `get`, `mark`, `nomark`, +`noscroll`, `scroll`, `show`). Every line of a write is checked before any +line runs; a malformed line fails the write with EINVAL. A command that fails +inside the editor is reported on the message row, not as a write error. + +After a write to either `ctl`, reading `/ctl` answers the serials of the panes +the command created, or, when it created none, the pane a look focused or the +pane an exec acted on (even one it closed), one per line. Before any command it answers `pid`, `version` and `panes` lines. + +`/pane//name` reads the pane's file name (a terminal's directory) and +writing it renames the buffer; a relative name resolves against the pane's +directory. `sel` reads the editor selection and writing it replaces the +selection. `body` appends on write and replaces on truncating open. `addr` +selects a range and `data` or `xdata` read or replace it. `errors` appends to +the directory's `+Errors` pane. Holding `event` open redirects the pane's Look and Exec clicks to that client; writing a record back performs the action. +Stats report real lengths for `index`, `ctl`, `name`, `body`, `tag` and `sel`, +modes 0644/0666 (0444 for read-only files, 0222 for write-only), the pane's +last edit time or the process start as mtime, and stable qids. Directory +entries carry no sizes; stat the entry. + +`/log` records `new`, `del`, `rename` and `save` while at least one client +holds it open; a read parks until a record arrives. `/screen` returns JSON with +`cols`, `rows`, `cursor`, a `styles` table, and row-major `cells` of +`[grapheme, style_index]`. Each open freezes one frame until close. A +terminal `body` freezes its history on the first read of each open handle; +`pty/data` streams live output. Screen and terminal-body snapshots share 32 +handle slots, released on close or disconnect. + +`-Dembed-sources=true` embeds the editor's sources and serves them under +`/src` (and `/shaders` on GUI builds). `EffectCode ` lists the current +backend's implementation files under `/virtual`, which Look opens; without the +option the command reports the sources as unavailable. The esp32p4 build +enables the option by default, so the device can serve its own source. + This is a control filesystem, not a complete POSIX export. Native filenames may contain up to 255 bytes. Existing regular OS files support read, write, and truncation to zero; protocol create, remove, rename, and other metadata -changes are refused. Ownership, permissions, and timestamps are synthetic. +changes are refused. Ownership and permissions under `/os` are synthetic. Zero-length truncation accepts the accompanying `mtime` hint sent by Linux v9fs; the hint is not stored. Standalone timestamp changes remain refused. +The tree lives in `src/ninep/`: `tree.zig` (nodes, lookup, readdir, dispatch, +the backend contract), `pane.zig` (pane files), `ctl.zig`, `addr.zig`, +`pty.zig`, `events.zig` (event and log streams), `screen.zig` and +`sources.zig`. The protocol engine is `src/9p.zig`, the transports +`src/9p_io.zig`; `src/fs.zig` keeps host access, mounts, resolution, find and +grep. + `zig build fs-test` drives real sessions using the independent Python client -in `test/ninep.py`. `zig build 9p-test` checks the freestanding wire protocol; -`zig build fs-bench` measures filesystem transactions in the core. +in `test/ninep.py`; `zig build fs-discovery-test` checks that browsing creates +nothing and that `new`, `ctl`, `name`, `sel` and `log` behave. `zig build +9p-test` checks the freestanding wire protocol; `zig build fs-bench` measures +filesystem transactions in the core. `zig build fs-test quic-test -Dquic=true` also exercises QUIC mounts and I/O. diff --git a/docs/v9fs.md b/docs/v9fs.md index 51b35a46..6cb4e998 100644 --- a/docs/v9fs.md +++ b/docs/v9fs.md @@ -8,11 +8,11 @@ your configured shell as your normal user, with your account's supplementary groups. The shell receives `PARDES_MOUNT`, the absolute mountpoint: ```sh -ls "$PARDES_MOUNT/self/pane" -cat "$PARDES_MOUNT/self/index" -cat "$PARDES_MOUNT/self/README" -ls -l "$PARDES_MOUNT/self/new" -cat "$PARDES_MOUNT/self/pane/$PARDES_PANE/body" +ls "$PARDES_MOUNT/pane" +cat "$PARDES_MOUNT/index" +cat "$PARDES_MOUNT/README" +cat "$PARDES_MOUNT/pane/$PARDES_PANE/body" +echo 'exec Msg hello' > "$PARDES_MOUNT/ctl" ``` The mount belongs to that pane's subprocess tree. Other panes and the editor @@ -96,7 +96,7 @@ unprivileged and uses `sudo -n`, retaining the calling terminal's authorization. Missing authorization or kernel support fails the test instead of skipping it. It checks mount isolation, privilege dropping, inherited access, directory refresh, body reads and truncation, independent wire updates, addressed edits, -shell redirection to ctl, Exec dispatch, rendered screen JSON, and OS-file reads. +shell redirection to name, Exec dispatch, rendered screen JSON, and OS-file reads. Linux follows `O_TRUNC` with a `Twstat` carrying zero length and an `mtime` hint. Pardes accepts this truncation without storing caller-selected timestamps; diff --git a/src/9p.zig b/src/9p.zig index 2948b9ed..3cffbffc 100644 --- a/src/9p.zig +++ b/src/9p.zig @@ -894,7 +894,7 @@ pub fn Server(comptime fs: type, comptime fid_capacity: usize) type { .qid = qidOf(if (a.node != 0) a.node else f.node, a.dir), .mode = (if (a.dir) dmdir else 0) | @as(u32, a.mode), .atime = 0, - .mtime = 0, + .mtime = if (@hasField(@TypeOf(a), "mtime")) a.mtime else 0, .length = a.size, .name = f.name[0..f.name_len], .uid = who, diff --git a/src/9p_io.zig b/src/9p_io.zig index 943561eb..d0db1c86 100644 --- a/src/9p_io.zig +++ b/src/9p_io.zig @@ -138,7 +138,7 @@ fn localIp(address: std.Io.net.IpAddress) bool { return false; } -const Srv = ninep.Server(pardes.filesystem, ninep.max_fids); +const Srv = ninep.Server(pardes.ctlfs, ninep.max_fids); const Conn = struct { fd: c_int = -1, @@ -149,7 +149,7 @@ const Conn = struct { in: [msize]u8 = undefined, out: [2 * msize]u8 = undefined, - fn step(c: *Conn, core: *pardes.Pardes, req: pardes.filesystem.Req) void { + fn step(c: *Conn, core: *pardes.Pardes, req: pardes.ctlfs.Req) void { core.update(.{ .fs_req = req }); var answered = false; while (core.nextEffect()) |effect| { @@ -160,7 +160,7 @@ const Conn = struct { } else core.perform(effect); } if (!answered) { - const reply = pardes.filesystem.Reply.fail(req.tag, pardes.filesystem.E.IO); + const reply = pardes.ctlfs.Reply.fail(req.tag, pardes.ctlfs.E.IO); c.srv.reply(&reply, ""); } } @@ -226,7 +226,7 @@ pub const Listener = struct { c.srv = .init(.{ .in = &c.in, .out = &c.out, - .root = pardes.filesystem.namespace_root, + .root = pardes.ctlfs.root, }); } } @@ -246,7 +246,7 @@ pub const Listener = struct { c.quic = connection; c.draining = false; c.accepted_ms = nowMs(); - c.srv = .init(.{ .in = &c.in, .out = &c.out, .root = pardes.filesystem.namespace_root }); + c.srv = .init(.{ .in = &c.in, .out = &c.out, .root = pardes.ctlfs.root }); }; } } @@ -748,17 +748,17 @@ test "Unix TCP and QUIC share one listener through reads writes reconnects and r defer testing.allocator.free(before); try testing.expectEqualStrings(w.expected, before); try testing.expectError(error.FileTooLarge, Client.readLimit(testing.allocator, w.dial, w.body_path, w.body_path, w.expected.len - 1)); - const listing = try Client.readLimit(testing.allocator, w.dial, "/self/pane", "/self/pane", 128); + const listing = try Client.readLimit(testing.allocator, w.dial, "/pane", "/pane", 128); defer testing.allocator.free(listing); - const exact_listing = try Client.readLimit(testing.allocator, w.dial, "/self/pane", "/self/pane", listing.len); + const exact_listing = try Client.readLimit(testing.allocator, w.dial, "/pane", "/pane", listing.len); defer testing.allocator.free(exact_listing); try testing.expectEqualStrings(listing, exact_listing); - try testing.expectError(error.FileTooLarge, Client.readLimit(testing.allocator, w.dial, "/self/pane", "/self/pane", listing.len - 1)); + try testing.expectError(error.FileTooLarge, Client.readLimit(testing.allocator, w.dial, "/pane", "/pane", listing.len - 1)); try Client.write(testing.allocator, w.dial, w.body_path, w.replacement); const after = try Client.read(testing.allocator, w.dial, w.body_path, w.body_path); defer testing.allocator.free(after); try testing.expectEqualStrings(w.replacement, after); - const screen = try Client.read(testing.allocator, w.dial, "/self/screen", "/self/screen"); + const screen = try Client.read(testing.allocator, w.dial, "/screen", "/screen"); defer testing.allocator.free(screen); const parsed = try std.json.parseFromSlice(struct { cols: u16, rows: u16 }, testing.allocator, screen, .{ .ignore_unknown_fields = true }); defer parsed.deinit(); @@ -790,7 +790,7 @@ test "Unix TCP and QUIC share one listener through reads writes reconnects and r var dial_buf: [64]u8 = undefined; const network_dial = try std.fmt.bufPrint(&dial_buf, "{s}!{s}!{d}", .{ protocol, host, port }); var body_buf: [64]u8 = undefined; - const body = try std.fmt.bufPrint(&body_buf, "/self/pane/{d}/body", .{pane.serial}); + const body = try std.fmt.bufPrint(&body_buf, "/pane/{d}/body", .{pane.serial}); for ([_][]const u8{ network_dial, l.path(), network_dial }, 0..) |dial, attempt| { var worker: Worker = .{ .dial = dial, .body_path = body, .expected = if (attempt == 0) "initial\n" else replacement, .replacement = replacement }; const thread = try std.Thread.spawn(.{}, Worker.run, .{&worker}); @@ -1245,15 +1245,14 @@ pub const Client = struct { test "a path becomes walk elements, normalised the way a shell would" { var out: [max_depth][]const u8 = undefined; - try testing.expectEqual(@as(usize, 4), try elements("/self/pane/1/body", &out)); - try testing.expectEqualStrings("self", out[0]); - try testing.expectEqualStrings("pane", out[1]); - try testing.expectEqualStrings("1", out[2]); - try testing.expectEqualStrings("body", out[3]); + try testing.expectEqual(@as(usize, 3), try elements("/pane/1/body", &out)); + try testing.expectEqualStrings("pane", out[0]); + try testing.expectEqualStrings("1", out[1]); + try testing.expectEqualStrings("body", out[2]); - try testing.expectEqual(@as(usize, 4), try elements("self/pane/1/body", &out)); - try testing.expectEqual(@as(usize, 4), try elements("//self//pane//1//body//", &out)); - try testing.expectEqual(@as(usize, 2), try elements("/self/index", &out)); + try testing.expectEqual(@as(usize, 3), try elements("pane/1/body", &out)); + try testing.expectEqual(@as(usize, 3), try elements("//pane//1//body//", &out)); + try testing.expectEqual(@as(usize, 1), try elements("/index", &out)); try testing.expectEqual(@as(usize, 0), try elements("/", &out)); @@ -1284,12 +1283,12 @@ pub const Client = struct { test "a dial with nothing listening is one error and not a wait" { if (comptime !supported) return error.SkipZigTest; var names: [max_depth][]const u8 = undefined; - const n = try elements("/self/pane/1/body", &names); + const n = try elements("/pane/1/body", &names); var remote: RemoteError = .{}; const before = nowMs(); try testing.expectError( Error.Dial, - fetchBytes(testing.allocator, .{ .unix = "/tmp/pardes-9p-no-such-socket.sock" }, names[0..n], &remote, null, "/self/pane/1/body", limits.max_file_bytes), + fetchBytes(testing.allocator, .{ .unix = "/tmp/pardes-9p-no-such-socket.sock" }, names[0..n], &remote, null, "/pane/1/body", limits.max_file_bytes), ); try testing.expect(nowMs() - before < budget_ms); } diff --git a/src/CHANGELOG.md b/src/CHANGELOG.md index 015f726b..18bcceb9 100644 --- a/src/CHANGELOG.md +++ b/src/CHANGELOG.md @@ -2,6 +2,16 @@ ## 0.0.3 +- Flatten the 9P control tree: `self/` is gone, so `/index`, `/pane//`, + `/screen` and `/os` sit at the root. `/new` is one clone file (reading it + makes a pane and answers its serial), `/ctl` takes `look TEXT` and + `exec TEXT` in the editor's own command language and answers the serials a + command touched, `/log` streams pane events, and each pane gains `name` and + `sel` (replacing `rdsel`/`wrsel`); `cons`, `new/` and the `name`, `put`, + `del` and `delete` ctl verbs are gone in favour of `name` and `exec`. Stats + carry real lengths, modes and mtimes. Sources are served under `/src` only + with `-Dembed-sources=true`. The tree code moved from `src/fs.zig` to + `src/ninep/`. - Add pinned tree-sitter declaration context, with optional compact tagline styling and separators between discontinuous source lines. - Configure search and LSP result context with `LocationsConfig`. Results use diff --git a/src/effect_sources.zig b/src/effect_sources.zig index 3ca15c3f..08680860 100644 --- a/src/effect_sources.zig +++ b/src/effect_sources.zig @@ -79,6 +79,7 @@ pub fn forSetting(setting: config.Runtime.Setting) ?[]const []const u8 { } test "EffectCode paths resolve uniquely to this backend's archived inputs" { + if (!@import("memory.zig").limits.embedded_sources) return error.SkipZigTest; for (config.Runtime.settings) |setting| { const available = switch (setting.action) { .transition => backend == .tty or backend == .gui or backend == .macos, diff --git a/src/fs-help.txt b/src/fs-help.txt index eeb000cc..a0a84b28 100644 --- a/src/fs-help.txt +++ b/src/fs-help.txt @@ -1,65 +1,42 @@ Pardes control filesystem ========================= -The mount root contains self/ (this editor) and os/ (host files). -This guide is available as self/README and self/new/README. -Examples below run inside a Tty9p shell, where PARDES_MOUNT is set. - -Explore -------- - ls "$PARDES_MOUNT/self" - cat "$PARDES_MOUNT/self/index" - ls -l "$PARDES_MOUNT/self/new" - ls "$PARDES_MOUNT/self/pane" - -index lists panes: serial, tag length, body length, reserved zero, -modified flag, then tag text. Use the serial in self/pane//. -screen is rendered screen JSON; listeners lists the session addresses. -cons accepts text to display in the editor. - -Create a pane -------------- -new/ lists the same files as a scratch pane, plus this README. -Listing, walking and statting these paths do not create anything. -OPENING any file except README creates one scratch pane below the active pane. -Each open creates a separate pane, even if you open the same path again. - - cat "$PARDES_MOUNT/self/new/ctl" - -This creates a pane and prints its control information, beginning with its -serial. Use self/pane// for all subsequent operations on that pane. -To create a pane and write its initial text in one operation: - - printf 'Hello from the shell\n' > "$PARDES_MOUNT/self/new/body" - -Reading all files recursively would open factories and create panes. -Use ls or stat to inspect them; read README for this guide. - -Work with an existing pane --------------------------- -Replace with a number from index or new/ctl: - - cat "$PARDES_MOUNT/self/pane//body" - printf 'Replacement text\n' > "$PARDES_MOUNT/self/pane//body" - printf 'More text\n' >> "$PARDES_MOUNT/self/pane//body" - printf 'name notes.txt\n' > "$PARDES_MOUNT/self/pane//ctl" - -body buffer text; for terminals, reads history and writes child input - tag editable pane tag - ctl control information on read; newline-separated commands on write - addr address range; write #0,#5 to select the first five bytes - data read from addr onward, or replace the range selected by addr - xdata read only the range selected by addr; writes replace that range - rdsel read the editor selection - wrsel replace the editor selection - errors write diagnostics - event pane interaction events; opening intercepts Look/Exec events - -Common ctl commands: name PATH, put (save), get (reload), dot=addr, -addr=dot, look PATH, del (close, refusing dirty text), delete (force close). -Reload and force close can discard unsaved changes. - -Terminal panes also expose pty/ctl, pty/status and pty/data. -Writing pty/data sends terminal input; use carriage return to submit a command. -Reading pty/data streams new output; read body for a history snapshot. - -Embedded source files under self/src/ document the complete interface. +README this guide +index one line per pane: serial, kind (text|term|pdf|image), dirty flag, name +ctl write commands; read the serials the last command made or touched +new reading it creates one empty pane and answers its serial +log one line per editor event (new/del/rename/save ); reads wait +screen rendered screen as JSON, frozen from open to close +listeners the session's dial addresses +pane// name body tag ctl addr data xdata sel errors event, and pty/ for terminals +os/ the host filesystem +src/ the editor's own sources, only in a -Dembed-sources=true build + +Commands, on /ctl (applied at the active pane) or on pane//ctl (at that pane): + look TEXT a right click: open a file, a file:12 location, a directory, a URL + exec TEXT a middle click: an editor command word (Save Del New Newcol Mount Unmount + Dump Restore Msg Find Grep Tty ...), or a shell command for the pane's terminal +Below, $m is the mount point (PARDES_MOUNT in a Tty9p shell; 9ns and 9p work too): + + cat $m/index which panes exist + n=$(cat $m/new) make a pane, remember its serial + echo 'look /etc/hosts:3' > $m/ctl; cat $m/ctl open a file, see the pane it went to + printf 'text\n' > $m/pane/$n/body append to a pane (>| truncates first) + cat $m/pane/$n/name; echo notes.txt > $m/pane/$n/name read, then rename + echo 'exec Save' > $m/pane/$n/ctl save it (exec Del closes it) + echo 'exec Msg hello' > $m/ctl show text in the editor + echo '#0,#5' > $m/pane/$n/addr; echo NEW > $m/pane/$n/data replace bytes 0..5 + echo 'dot=addr' > $m/pane/$n/ctl; cat $m/pane/$n/sel select the range, read it + cat $m/log block until a pane is made, renamed, saved or closed + cat $m/pane/$n/event hold it open to own that pane's clicks + echo 'exec' > $m/pane/$n/pty/ctl restart a shell; also winsize C R, sig INT + +Pitfalls, one each: + Every open of new makes another pane, so `cat $m/new` twice makes two. + ls, stat and find create nothing; reading log, event or pty/data blocks until something happens. + exec Del closes a pane even when it is dirty; index shows the dirty flag first. + look and exec are lowercase verbs; the words after exec are the editor's capitalized commands. + ctl also takes acme's addr verbs (addr=dot dot=addr limit=addr clean dirty get show ...), one per line. + Writing body appends; open it with truncation to replace; writes are whole UTF-8 sequences. + A terminal's body is a history snapshot frozen per open; pty/data is the live stream. + screen is frozen per open handle as well; reopen it for a fresh frame. + A command that fails is reported in the editor, not as a write error; a malformed line fails the write. diff --git a/src/fs.zig b/src/fs.zig index 4fe32347..7f416440 100644 --- a/src/fs.zig +++ b/src/fs.zig @@ -9,6 +9,22 @@ const panes = @import("panes.zig"); const mvzr = @import("mvzr"); const modal = @import("modal.zig"); const look = @import("look.zig"); +pub const tree = @import("ninep/tree.zig"); +const sources_fs = @import("ninep/sources.zig"); +const th = @import("ninep/testing.zig"); + +const Pardes = pardes.Pardes; +const MAX_PANES = pardes.MAX_PANES; +const Req = tree.Req; +const Reply = tree.Reply; +const E = tree.E; + +/// The served README; tree.zig answers it. +pub const help = @embedFile("fs-help.txt"); + +/// Host filesystem nodes: the root, and one hashed node per path a client walked to. +pub const os_root: u64 = (1 << 63) + 2; +pub const os_node: u64 = 1 << 62; pub const name_capacity: usize = 255; @@ -18,8 +34,6 @@ pub const sources: []const Source = if (limits.embedded_sources) else &.{}; const source_files = [_]Source{ - .{ .path = "build.zig", .contents = @embedFile("root-build.zig") }, - .{ .path = "build.zig.zon", .contents = @embedFile("root-build.zig.zon") }, .{ .path = "src/pardes.zig", .contents = @embedFile("pardes.zig") }, .{ .path = "src/panes.zig", .contents = @embedFile("panes.zig") }, .{ .path = "src/layout.zig", .contents = @embedFile("layout.zig") }, @@ -86,101 +100,6 @@ pub const Mount = struct { name: []const u8, dial: []const u8 }; pub const max_mounts = 8; pub const Resolved = struct { path: []const u8, dir: bool = false }; pub const OsPath = struct { node: u64, path: []const u8 }; -pub const archive_node: u64 = 1 << 61; - -pub fn archiveNode(path: []const u8) ?u64 { - if (path.len == 0) return archive_node; - if (path.len >= 4096) return null; - for (sources, 0..) |source, i| { - if (std.mem.eql(u8, source.path, path) or - (source.path.len > path.len and source.path[path.len] == '/' and std.mem.startsWith(u8, source.path, path))) - return archive_node | (@as(u64, i) << 12) | path.len; - } - return null; -} - -fn archiveInfo(node: u64) ?struct { path: []const u8, contents: []const u8, dir: bool } { - if (node == archive_node) return .{ .path = "", .contents = "", .dir = true }; - const index = (node & ~archive_node) >> 12; - if (index >= sources.len) return null; - const source = sources[@intCast(index)]; - const len: usize = @intCast(node & 4095); - if (len > source.path.len) return null; - return .{ .path = source.path[0..len], .contents = source.contents, .dir = len < source.path.len }; -} - -pub fn stageArchive(p: *pardes.Pardes, out: *std.ArrayList(u8), path: []const u8, skip: *u64) void { - var seen: [sources.len][]const u8 = undefined; - var count: usize = 0; - for (sources, 0..) |source, i| { - if (path.len != 0 and - (source.path.len <= path.len or source.path[path.len] != '/' or !std.mem.startsWith(u8, source.path, path))) continue; - const start = if (path.len == 0) 0 else path.len + 1; - const rest = source.path[start..]; - const len = std.mem.indexOfScalar(u8, rest, '/') orelse rest.len; - const name = rest[0..len]; - var duplicate = false; - for (seen[0..count]) |previous| if (std.mem.eql(u8, name, previous)) { - duplicate = true; - break; - }; - if (duplicate) continue; - seen[count] = name; - count += 1; - if (skip.* > 0) { - skip.* -= 1; - continue; - } - const node = archive_node | (@as(u64, i) << 12) | (start + len); - stageDirent(out, p.gpa, node, len < rest.len, name); - } -} - -pub fn archiveHandle(p: *pardes.Pardes, req: Req) Reply { - const info = archiveInfo(req.node) orelse return Reply.fail(req.tag, E.NOENT); - const attr: Reply.Attr = .{ - .node = req.node, - .name = std.fs.path.basename(info.path), - .dir = info.dir, - .size = if (info.dir) 0 else info.contents.len, - .mode = if (info.dir) 0o500 else 0o400, - }; - switch (req.op) { - .getattr => return .{ .tag = req.tag, .attr = attr }, - .open => return .{ .tag = req.tag, .handle = 1 }, - .release => return .{ .tag = req.tag }, - .lookup => { - if (!info.dir) return Reply.fail(req.tag, E.NOTDIR); - if (std.mem.eql(u8, req.data, "..")) { - const parent = std.fs.path.dirname(info.path) orelse ""; - if (parent.len == 0) return handle(p, .{ .tag = req.tag, .op = .getattr, .node = @intFromEnum(SelfFile.root) }); - const node = archiveNode(parent) orelse return Reply.fail(req.tag, E.NOENT); - return archiveHandle(p, .{ .tag = req.tag, .op = .getattr, .node = node }); - } - if (req.data.len == 0 or std.mem.indexOfAny(u8, req.data, "/\x00") != null) return Reply.fail(req.tag, E.NOENT); - var buf: [4096]u8 = undefined; - const path = if (info.path.len == 0) req.data else std.fmt.bufPrint(&buf, "{s}/{s}", .{ info.path, req.data }) catch return Reply.fail(req.tag, E.NOENT); - const node = archiveNode(path) orelse return Reply.fail(req.tag, E.NOENT); - return archiveHandle(p, .{ .tag = req.tag, .op = .getattr, .node = node }); - }, - .readdir => { - if (!info.dir) return Reply.fail(req.tag, E.NOTDIR); - const out = p.fs.stage(p.gpa); - var skip = req.off; - stageArchive(p, out, info.path, &skip); - return .{ .tag = req.tag, .payload = .{ .staged = @intCast(out.items.len) } }; - }, - .read => { - if (info.dir) return Reply.fail(req.tag, E.PERM); - const off: usize = @intCast(@min(req.off, info.contents.len)); - const bytes = info.contents[off..][0..@min(req.size, info.contents.len - off)]; - const out = p.fs.stage(p.gpa); - out.appendSlice(p.gpa, bytes) catch return Reply.fail(req.tag, E.NOMEM); - return .{ .tag = req.tag, .payload = .{ .staged = @intCast(bytes.len) } }; - }, - else => return Reply.fail(req.tag, E.PERM), - } -} fn osPath(p: *pardes.Pardes, node: u64) ?[]const u8 { if (node == os_root) return "/"; @@ -208,7 +127,7 @@ pub fn osHandle(p: *pardes.Pardes, req: Req) Reply { if (req.op == .release) return .{ .tag = req.tag }; const io = std.Io.Threaded.global_single_threaded.io(); const stat = std.Io.Dir.cwd().statFile(io, path, .{}) catch return Reply.fail(req.tag, E.NOENT); - const attr: Reply.Attr = .{ .name = if (req.node == os_root) "os" else std.fs.path.basename(path), .node = req.node, .dir = stat.kind == .directory, .size = stat.size, .mode = if (stat.kind == .directory) 0o500 else 0o600 }; + const attr: Reply.Attr = .{ .name = if (req.node == os_root) "os" else std.fs.path.basename(path), .node = req.node, .dir = stat.kind == .directory, .size = stat.size, .mode = if (stat.kind == .directory) 0o755 else 0o644, .mtime = std.math.cast(u32, stat.mtime.toSeconds()) orelse 0 }; switch (req.op) { .getattr => return .{ .tag = req.tag, .attr = attr }, .open => { @@ -218,7 +137,7 @@ pub fn osHandle(p: *pardes.Pardes, req: Req) Reply { .lookup => { if (stat.kind != .directory) return Reply.fail(req.tag, E.NOTDIR); if (req.node == os_root and std.mem.eql(u8, req.data, "..")) - return handle(p, .{ .tag = req.tag, .op = .getattr, .node = namespace_root }); + return tree.handle(p, .{ .tag = req.tag, .op = .getattr, .node = tree.root }); if (req.data.len == 0 or std.mem.indexOfAny(u8, req.data, "/\x00") != null) return Reply.fail(req.tag, E.NOENT); var buf: [4096]u8 = undefined; const joined = std.fmt.bufPrint(&buf, "{s}/{s}", .{ std.mem.trimEnd(u8, path, "/"), req.data }) catch return Reply.fail(req.tag, E.NOENT); @@ -244,7 +163,7 @@ pub fn osHandle(p: *pardes.Pardes, req: Req) Reply { continue; } const node = if (std.mem.eql(u8, normalized.path, "/")) os_root else os_node | (std.hash.Wyhash.hash(0, normalized.path) & (os_node - 1)); - stageDirent(out, p.gpa, node, child.kind == .directory, entry.name); + tree.stageDirent(out, p.gpa, node, child.kind == .directory, entry.name); if (out.items.len >= @max(req.size, 512)) break; } return .{ .tag = req.tag, .payload = .{ .staged = @intCast(out.items.len) } }; @@ -362,10 +281,16 @@ test "virtual writes enforce permissions even when contents are empty" { const p = try pardes.Pardes.init(std.testing.allocator, .{ .tty_only = true }); defer p.deinit(); for ([_][]const u8{ "", "bytes" }) |bytes| { - for ([_][]const u8{ "/virtual/index", "/virtual/screen", "/virtual/src/fs.zig", "/n/self/src/fs.zig" }) |path| + for ([_][]const u8{ "/virtual/index", "/virtual/screen", "/virtual/README", "/n/self/log" }) |path| try std.testing.expectError(error.ReadOnlyFilesystem, write(p, path, bytes)); - try std.testing.expectError(error.IsDirectory, write(p, "/virtual/src", bytes)); + try std.testing.expectError(error.IsDirectory, write(p, "/virtual/pane", bytes)); try std.testing.expectError(error.FileNotFound, write(p, "/virtual/missing", bytes)); + try std.testing.expectError(error.FileNotFound, write(p, "/virtual/cons", bytes)); + if (limits.embedded_sources) { + for ([_][]const u8{ "/virtual/src/fs.zig", "/n/self/src/fs.zig" }) |path| + try std.testing.expectError(error.ReadOnlyFilesystem, write(p, path, bytes)); + try std.testing.expectError(error.IsDirectory, write(p, "/virtual/src", bytes)); + } else try std.testing.expectError(error.FileNotFound, write(p, "/virtual/src/fs.zig", bytes)); } for (p.fs.snapshots) |snapshot| try std.testing.expect(snapshot.node == 0); } @@ -385,8 +310,8 @@ test "direct self reads and writes use the same dot paths as Look" { try std.testing.expectEqualStrings(pane.file.?.content, bytes); var resolved: [4096]u8 = undefined; const canonical = resolve(p, path, "/", &resolved).?; - try std.testing.expectEqual(resolveSelf(p, canonical.path[9..]), resolveSelf(p, path[root.len..])); - try std.testing.expectEqual(@as(?u64, @intFromEnum(SelfFile.root)), resolveSelf(p, "./pane/../../")); + try std.testing.expectEqual(tree.resolveSelf(p, canonical.path[9..]), tree.resolveSelf(p, path[root.len..])); + try std.testing.expectEqual(@as(?u64, tree.root), tree.resolveSelf(p, "./pane/../../")); const index_path = try std.fmt.bufPrint(&path_buf, "{s}/./pane/../index", .{root}); try std.testing.expectError(error.ReadOnlyFilesystem, write(p, index_path, "")); const index = try read(p, index_path); @@ -397,7 +322,7 @@ test "direct self reads and writes use the same dot paths as Look" { @memcpy(overlong[0..9], "/virtual/"); var resolved: [4096]u8 = undefined; try std.testing.expect(resolve(p, &overlong, "/", &resolved) == null); - try std.testing.expect(resolveSelf(p, overlong[9..]) == null); + try std.testing.expect(tree.resolveSelf(p, overlong[9..]) == null); try std.testing.expectError(error.FileNotFound, write(p, &overlong, "")); } @@ -462,8 +387,8 @@ test "bounded reads apply the same limits to self bodies and embedded sources" { contents[contents.len - 1] = '\n'; for ([_][]const u8{ &contents, "" }) |expected| { const pane = try p.setTestFile(expected); - for ([_][]const u8{ "/virtual", "/n/self", "/n/own/self" }) |prefix| { - if (!platform_has_fs and std.mem.eql(u8, prefix, "/n/own/self")) continue; + for ([_][]const u8{ "/virtual", "/n/self", "/n/own" }) |prefix| { + if (!platform_has_fs and std.mem.eql(u8, prefix, "/n/own")) continue; var path_buf: [128]u8 = undefined; const path = try std.fmt.bufPrint(&path_buf, "{s}/pane/{d}/body", .{ prefix, pane.serial }); const bytes = try readLimit(p, path, expected.len); @@ -478,7 +403,7 @@ test "bounded reads apply the same limits to self bodies and embedded sources" { } if (limits.embedded_sources) { const source = findEmbeddedSource("src/look.zig", false).?; - for ([_][]const u8{ "/virtual/src/look.zig", "/n/self/src/look.zig", "/n/own/self/src/look.zig" }) |path| { + for ([_][]const u8{ "/virtual/src/look.zig", "/n/self/src/look.zig", "/n/own/src/look.zig" }) |path| { if (!platform_has_fs and std.mem.startsWith(u8, path, "/n/own/")) continue; const bytes = try readLimit(p, path, source.contents.len); defer gpa.free(bytes); @@ -498,7 +423,7 @@ test "bounded reads count rendered directory paths and unknown self lengths" { defer p.deinit(); p.fs.socket_path = "/tmp/pardes-limited-in-process.sock"; try p.fs.mount(gpa, "own", p.fs.socket_path); - for ([_][]const u8{ "/n", "/virtual", "/n/self", "/n/own", "/n/own/self", "/virtual/listeners" }) |path| { + for ([_][]const u8{ "/n", "/virtual", "/n/self", "/n/own", "/n/own/pane", "/virtual/listeners", "/virtual/README" }) |path| { if (!platform_has_fs and std.mem.startsWith(u8, path, "/n/own")) continue; const expected = try read(p, path); defer gpa.free(expected); @@ -515,10 +440,10 @@ test "bounded reads count rendered directory paths and unknown self lengths" { test "bounded reads release terminal snapshots after success and size refusal" { if (!pardes.terminal_panes) return error.SkipZigTest; const gpa = std.testing.allocator; - const p = try withTerm(gpa); + const p = try th.withTerm(gpa); defer p.deinit(); var path_buf: [128]u8 = undefined; - const path = try std.fmt.bufPrint(&path_buf, "/virtual/pane/{d}/body", .{serialOf(p)}); + const path = try std.fmt.bufPrint(&path_buf, "/virtual/pane/{d}/body", .{th.serialOf(p)}); const empty = try readLimit(p, path, 0); defer gpa.free(empty); try std.testing.expectEqual(@as(usize, 0), empty.len); @@ -626,9 +551,9 @@ test "virtual body writes can read their input from the same pane" { const p = try pardes.Pardes.init(std.testing.allocator, .{ .tty_only = true }); defer p.deinit(); const pane = try p.setTestFile("same pane contents\n"); - const event_node = Node.of(pane.serial, .event); - _ = handle(p, .{ .tag = 0, .op = .open, .node = event_node }); - defer _ = handle(p, .{ .tag = 0, .op = .release, .node = event_node }); + const event_node = tree.Node.of(pane.serial, .event); + _ = tree.handle(p, .{ .tag = 0, .op = .open, .node = event_node }); + defer _ = tree.handle(p, .{ .tag = 0, .op = .release, .node = event_node }); var path_buffer: [64]u8 = undefined; const path = try std.fmt.bufPrint(&path_buffer, "/virtual/pane/{d}/body", .{pane.serial}); try write(p, path, pane.file.?.content); @@ -654,11 +579,10 @@ test "same-core mount directories preserve their mount prefix across reads" { try p.fs.mount(gpa, "own", socket_path); const roots = try read(p, "/n/own"); defer gpa.free(roots); - try std.testing.expectEqualStrings("/n/own/os/\n/n/own/self/\n", roots); - const self = try read(p, "/n/own/self"); - defer gpa.free(self); - try std.testing.expect(std.mem.indexOf(u8, self, "/n/own/self/index\n") != null); - try std.testing.expectError(error.NotADirectory, read(p, "/n/own/self/index/..")); + try std.testing.expect(std.mem.startsWith(u8, roots, "/n/own/README\n/n/own/index\n")); + try std.testing.expect(std.mem.indexOf(u8, roots, "/n/own/pane/\n/n/own/os/\n") != null); + try std.testing.expectError(error.NotADirectory, read(p, "/n/own/index/..")); + try std.testing.expectError(error.FileNotFound, read(p, "/n/own/self/index")); var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); @@ -767,11 +691,11 @@ pub fn resolveOs(path: []const u8, out: *[4096]u8) ?Resolved { fn resolveVirtual(p: ?*pardes.Pardes, path: []const u8, out: *[4096]u8) ?Resolved { var normalized_buf: [4096]u8 = undefined; const normalized = normalizeVirtualPath(path, &normalized_buf) orelse return null; - if (p) |core| if (resolveSelf(core, normalized) != null) + if (p) |core| if (tree.resolveSelf(core, normalized) != null) return .{ .path = std.fmt.bufPrint(out, "/virtual/{s}", .{normalized}) catch return null }; if (findEmbeddedSource(normalized, false)) |source| return .{ .path = std.fmt.bufPrint(out, "/virtual/{s}", .{source.path}) catch return null }; - if (archiveNode(normalized) != null) + if (sources_fs.node(normalized) != null) return .{ .path = std.fmt.bufPrint(out, "/virtual/{s}", .{normalized}) catch return null }; return null; } @@ -793,7 +717,7 @@ pub fn readLimit(p: *pardes.Pardes, path: []const u8, max_bytes: usize) ![]u8 { } return out.toOwnedSlice(); } - if (std.mem.eql(u8, path, "/virtual")) return readNode(p, @intFromEnum(SelfFile.root), path, limit); + if (std.mem.eql(u8, path, "/virtual")) return readNode(p, tree.root, path, limit); if (std.mem.startsWith(u8, path, "/n/")) { const explicit = path[3..]; const cut = std.mem.indexOfScalar(u8, explicit, '/') orelse explicit.len; @@ -812,7 +736,7 @@ pub fn readLimit(p: *pardes.Pardes, path: []const u8, max_bytes: usize) ![]u8 { return readNode(p, node, path, limit); } if (std.mem.eql(u8, name, "self")) { - const node = resolveSelf(p, remote_path) orelse return error.FileNotFound; + const node = tree.resolveSelf(p, remote_path) orelse return error.FileNotFound; return readNode(p, node, path, limit); } for (p.fs.mounts.items) |mount| { @@ -823,13 +747,13 @@ pub fn readLimit(p: *pardes.Pardes, path: []const u8, max_bytes: usize) ![]u8 { for (p.fs.os_paths.items[saved_paths..]) |temporary| p.gpa.free(temporary.path); p.fs.os_paths.shrinkRetainingCapacity(saved_paths); } - var node = namespace_root; + var node = tree.root; var directory = true; var parts = std.mem.tokenizeScalar(u8, remote_path, '/'); while (parts.next()) |part| { if (!directory) return error.NotADirectory; if (std.mem.eql(u8, part, ".")) continue; - const reply = handle(p, .{ .tag = 0, .op = .lookup, .node = node, .data = part }); + const reply = tree.handle(p, .{ .tag = 0, .op = .lookup, .node = node, .data = part }); if (reply.status != .ok) return error.FileNotFound; node = reply.attr.node; directory = reply.attr.dir; @@ -842,14 +766,14 @@ pub fn readLimit(p: *pardes.Pardes, path: []const u8, max_bytes: usize) ![]u8 { } if (std.mem.startsWith(u8, path, "/virtual/")) { const name = path[9..]; - if (resolveSelf(p, name)) |node| return readNode(p, node, path, limit); + if (tree.resolveSelf(p, name)) |node| return readNode(p, node, path, limit); } return readFileLimit(p.gpa, path, limit); } fn readNode(p: *pardes.Pardes, initial_node: u64, path: []const u8, limit: usize) ![]u8 { var node = initial_node; - const attr = handle(p, .{ .tag = 0, .op = .getattr, .node = node }); + const attr = tree.handle(p, .{ .tag = 0, .op = .getattr, .node = node }); if (attr.status != .ok) return error.FileNotFound; if (attr.attr.dir) { var out: std.Io.Writer.Allocating = .init(p.gpa); @@ -858,7 +782,7 @@ fn readNode(p: *pardes.Pardes, initial_node: u64, path: []const u8, limit: usize const max_bytes = @min(limit, limits.max_stream_bytes); const prefix = std.mem.trimEnd(u8, path, "/"); while (true) { - const reply = handle(p, .{ .tag = 0, .op = .readdir, .node = node, .off = index, .size = 8192 }); + const reply = tree.handle(p, .{ .tag = 0, .op = .readdir, .node = node, .off = index, .size = 8192 }); if (reply.status != .ok) return error.ReadFailed; const entries = p.fsPayload(reply); if (entries.len == 0) return out.toOwnedSlice(); @@ -878,15 +802,15 @@ fn readNode(p: *pardes.Pardes, initial_node: u64, path: []const u8, limit: usize } } if (attr.attr.size > limit) return error.FileTooLarge; - const opened = handle(p, .{ .tag = 0, .op = .open, .node = node }); + const opened = tree.handle(p, .{ .tag = 0, .op = .open, .node = node }); if (opened.status != .ok) return error.OpenFailed; if (opened.attr.node != 0) node = opened.attr.node; - defer _ = handle(p, .{ .tag = 0, .op = .release, .node = node, .handle = opened.handle }); + defer _ = tree.handle(p, .{ .tag = 0, .op = .release, .node = node, .handle = opened.handle }); var out: std.Io.Writer.Allocating = .init(p.gpa); errdefer out.deinit(); while (true) { const want: u32 = @intCast(@min(8192, limit + 1 - out.written().len)); - const reply = handle(p, .{ .tag = 0, .op = .read, .node = node, .handle = opened.handle, .off = out.written().len, .size = want }); + const reply = tree.handle(p, .{ .tag = 0, .op = .read, .node = node, .handle = opened.handle, .off = out.written().len, .size = want }); if (reply.status == .again) return error.NotAFile; if (reply.status != .ok) return error.ReadFailed; const bytes = p.fsPayload(reply); @@ -923,27 +847,27 @@ pub fn write(p: *pardes.Pardes, path: []const u8, bytes: []const u8) !void { } } if (self_path) |name| { - var node = resolveSelf(p, name) orelse return error.FileNotFound; - const attributes = handle(p, .{ .tag = 0, .op = .getattr, .node = node }); + var node = tree.resolveSelf(p, name) orelse return error.FileNotFound; + const attributes = tree.handle(p, .{ .tag = 0, .op = .getattr, .node = node }); if (attributes.status != .ok) return error.FileNotFound; if (attributes.attr.dir) return error.IsDirectory; if (attributes.attr.mode & 0o200 == 0) return error.ReadOnlyFilesystem; - const opened = handle(p, .{ .tag = 0, .op = .open, .node = node }); + const opened = tree.handle(p, .{ .tag = 0, .op = .open, .node = node }); if (opened.status != .ok) return error.OpenFailed; if (opened.attr.node != 0) node = opened.attr.node; - defer _ = handle(p, .{ .tag = 0, .op = .release, .node = node, .handle = opened.handle }); + defer _ = tree.handle(p, .{ .tag = 0, .op = .release, .node = node, .handle = opened.handle }); var preserved: ?[]u8 = null; defer if (preserved) |copy| p.gpa.free(copy); - const target = Node.target(node); + const target = tree.Node.target(node); if (target != null and target.? == .pane and target.?.pane.file == .body) { preserved = try p.gpa.dupe(u8, bytes); - const trunc = handle(p, .{ .tag = 0, .op = .setattr, .node = node, .truncate = true }); + const trunc = tree.handle(p, .{ .tag = 0, .op = .setattr, .node = node, .truncate = true }); if (trunc.status != .ok) return error.WriteFailed; } const contents = preserved orelse bytes; var off: usize = 0; while (off < contents.len) { - const reply = handle(p, .{ .tag = 0, .op = .write, .node = node, .off = off, .data = contents[off..] }); + const reply = tree.handle(p, .{ .tag = 0, .op = .write, .node = node, .off = off, .data = contents[off..] }); if (reply.status != .ok or reply.written == 0) return error.WriteFailed; off += reply.written; } @@ -964,7 +888,7 @@ fn resolveEmbedded(word: []const u8, cwd: []const u8, scratch: *[4096]u8) ?Sourc return findEmbeddedSource(normalized_word, false); } -fn normalizeVirtualPath(path: []const u8, out: *[4096]u8) ?[]const u8 { +pub fn normalizeVirtualPath(path: []const u8, out: *[4096]u8) ?[]const u8 { if (std.mem.indexOfScalar(u8, path, 0) != null) return null; var len: usize = 0; var parts = std.mem.tokenizeAny(u8, path, "/\\"); @@ -1322,361 +1246,6 @@ fn readFileLimit(gpa: std.mem.Allocator, path: []const u8, limit: usize) ![]u8 { return buf; } -const Pardes = pardes.Pardes; -const Pane = pardes.Pane; -const MAX_PANES = pardes.MAX_PANES; - -pub const namespace_root: u64 = 1 << 63; -pub const namespace_panes: u64 = namespace_root + 1; -pub const os_root: u64 = namespace_root + 2; -pub const os_node: u64 = 1 << 62; -const factory_base: u64 = namespace_root + 256; -const fs_help = @embedFile("fs-help.txt"); - -pub fn resolveSelf(p: *Pardes, path: []const u8) ?u64 { - var path_buf: [4096]u8 = undefined; - const normalized = normalizeVirtualPath(path, &path_buf) orelse return null; - var parts = std.mem.tokenizeScalar(u8, normalized, '/'); - const first = parts.next() orelse return @intFromEnum(SelfFile.root); - if (!std.mem.eql(u8, first, "pane")) { - const top = topFileNamed(first) orelse return archiveNode(normalized); - if (parts.next()) |name| { - if (top != .new or parts.next() != null) return null; - if (std.mem.eql(u8, name, "README")) return @intFromEnum(SelfFile.README); - const file = paneFileNamed(name) orelse return null; - if (file.inPty()) return null; - return factory_base + @intFromEnum(file); - } - return @intFromEnum(top); - } - const serial = serialNamed(parts.next() orelse return namespace_panes) orelse return null; - const id = p.paneBySerial(serial) orelse return null; - const file = paneFileNamed(parts.next() orelse return Node.of(serial, .dir)) orelse return null; - if (file.inPty() and !p.panes[id].?.isTerminal()) return null; - if (parts.next()) |name| { - if (file != .pty) return null; - const child = ptyFileNamed(name) orelse return null; - if (parts.next() != null) return null; - return Node.of(serial, child); - } - return Node.of(serial, file); -} - -fn namespace(p: *Pardes, req: Req) Reply { - switch (req.op) { - .getattr => return .{ .tag = req.tag, .attr = .{ .node = req.node, .dir = true, .mode = 0o500 } }, - .open => return .{ .tag = req.tag, .handle = 1 }, - .release => return .{ .tag = req.tag }, - .lookup => { - if (std.mem.eql(u8, req.data, "..")) return handle(p, .{ - .tag = req.tag, - .op = .getattr, - .node = if (req.node == namespace_root) namespace_root else @intFromEnum(SelfFile.root), - }); - if (req.node == namespace_root) { - if (std.mem.eql(u8, req.data, "self")) return handle(p, .{ .tag = req.tag, .op = .getattr, .node = @intFromEnum(SelfFile.root) }); - if (std.mem.eql(u8, req.data, "os")) return handle(p, .{ .tag = req.tag, .op = .getattr, .node = os_root }); - } else { - const serial = serialNamed(req.data) orelse return Reply.fail(req.tag, E.NOENT); - if (serial == 0) return Reply.fail(req.tag, E.NOENT); - return handle(p, .{ .tag = req.tag, .op = .getattr, .node = Node.of(serial, .dir) }); - } - return Reply.fail(req.tag, E.NOENT); - }, - .readdir => { - const out = p.fs.stage(p.gpa); - var skip = req.off; - if (req.node == namespace_root) { - if (skip == 0) stageDirent(out, p.gpa, os_root, true, "os") else skip -= 1; - if (skip == 0) stageDirent(out, p.gpa, @intFromEnum(SelfFile.root), true, "self"); - } else { - var last: u32 = 0; - while (nextSerialAfter(p, last)) |serial| { - last = serial; - if (skip > 0) { - skip -= 1; - continue; - } - var buf: [16]u8 = undefined; - const name = std.fmt.bufPrint(&buf, "{d}", .{serial}) catch unreachable; - stageDirent(out, p.gpa, Node.of(serial, .dir), true, name); - } - } - return .{ .tag = req.tag, .payload = .{ .staged = @intCast(out.items.len) } }; - }, - else => return Reply.fail(req.tag, E.PERM), - } -} - -pub const Op = enum(u8) { - lookup, - getattr, - setattr, - open, - read, - write, - release, - readdir, -}; - -pub const Status = enum(u8) { - ok, - again, - err, -}; - -pub const Req = struct { - tag: u64, - op: Op, - node: u64, - handle: u32 = 0, - off: u64 = 0, - size: u32 = 0, - data: []const u8 = &.{}, - truncate: bool = false, - - pub fn changesPane(req: Req) bool { - return switch (req.op) { - .write, .setattr => true, - .lookup => false, - .open => req.node >= factory_base and req.node < factory_base + 16, - .getattr, .read, .release, .readdir => false, - }; - } -}; - -pub const Reply = struct { - tag: u64, - status: Status = .ok, - errno: u16 = 0, - attr: Attr = .{}, - handle: u32 = 0, - payload: Payload = .none, - written: u32 = 0, - - pub const Attr = struct { - name: []const u8 = "", - node: u64 = 0, - dir: bool = false, - size: u64 = 0, - mode: u16 = 0o600, - }; - - pub const Payload = union(enum) { - none, - staged: u32, - region: struct { pane: u8, serial: u32, off: u32, len: u32 }, - }; - - pub fn fail(tag: u64, e: u16) Reply { - return .{ .tag = tag, .status = .err, .errno = e }; - } -}; - -pub const E = struct { - pub const PERM: u16 = 1; - pub const NOENT: u16 = 2; - pub const IO: u16 = 5; - pub const NOMEM: u16 = 12; - pub const NOTDIR: u16 = 20; - pub const INVAL: u16 = 22; - pub const NFILE: u16 = 23; - pub const NOSPC: u16 = 28; - pub const NOSYS: u16 = 38; -}; - -pub const PaneFile = enum(u4) { - dir = 0, - addr, - body, - ctl, - data, - errors, - event, - tag, - xdata, - rdsel, - wrsel, - pty, - pty_ctl, - pty_status, - pty_data, - - pub fn name(f: PaneFile) []const u8 { - return switch (f) { - .dir => ".", - .pty_ctl => "ctl", - .pty_status => "status", - .pty_data => "data", - else => @tagName(f), - }; - } - - pub fn mode(f: PaneFile) u16 { - return switch (f) { - .dir, .pty => 0o500, - .errors, .wrsel, .pty_ctl => 0o200, - .rdsel, .pty_status => 0o400, - else => 0o600, - }; - } - - pub fn isDir(f: PaneFile) bool { - return f == .dir or f == .pty; - } - - pub fn inPty(f: PaneFile) bool { - return switch (f) { - .pty, .pty_ctl, .pty_status, .pty_data => true, - else => false, - }; - } -}; - -pub const SelfFile = enum(u4) { - root = 1, - index = 2, - cons = 3, - new = 4, - screen = 5, - listeners = 6, - README = 7, - - pub fn name(f: SelfFile) []const u8 { - return if (f == .root) "." else @tagName(f); - } - - pub fn mode(f: SelfFile) u16 { - return switch (f) { - .root, .new => 0o500, - .index, .screen, .listeners, .README => 0o400, - .cons => 0o200, - }; - } - - pub fn dir(f: SelfFile) bool { - return f == .root or f == .new; - } -}; - -pub const Node = packed struct(u64) { - file: u4 = 0, - serial: u60 = 0, - - pub fn of(serial: u32, file: PaneFile) u64 { - std.debug.assert(serial != 0); - return @bitCast(Node{ .file = @intFromEnum(file), .serial = serial }); - } - - pub fn target(node: u64) ?Target { - const n: Node = @bitCast(node); - if (n.serial == 0) { - return .{ .top = std.enums.fromInt(SelfFile, n.file) orelse return null }; - } - return .{ .pane = .{ - .serial = std.math.cast(u32, n.serial) orelse return null, - .file = std.enums.fromInt(PaneFile, n.file) orelse return null, - } }; - } -}; - -pub const Target = union(enum) { - top: SelfFile, - pane: struct { serial: u32, file: PaneFile }, -}; - -pub const out_reserve = 4 * 1024; - -pub const queue_cap = 64 * 1024; - -pub const Queue = struct { - buf: std.ArrayList(u8) = .empty, - head: usize = 0, - - pub fn deinit(q: *Queue, gpa: std.mem.Allocator) void { - q.buf.deinit(gpa); - q.head = 0; - } - - pub fn push(q: *Queue, gpa: std.mem.Allocator, record: []const u8) void { - if (record.len > std.math.maxInt(u32)) return; - while (q.buf.items.len - q.head + record.len + 4 > queue_cap) { - if (q.peek() == null) return; - q.pop(); - } - q.compact(); - var head: [4]u8 = undefined; - std.mem.writeInt(u32, &head, @intCast(record.len), .little); - q.buf.appendSlice(gpa, &head) catch return; - q.buf.appendSlice(gpa, record) catch { - q.buf.shrinkRetainingCapacity(q.buf.items.len - 4); - return; - }; - } - - pub fn peek(q: *const Queue) ?[]const u8 { - const rest = q.buf.items[@min(q.head, q.buf.items.len)..]; - if (rest.len < 4) return null; - const len = std.mem.readInt(u32, rest[0..4], .little); - if (rest.len < 4 + len) return null; - return rest[4 .. 4 + len]; - } - - pub fn pop(q: *Queue) void { - const record = q.peek() orelse return; - q.head += 4 + record.len; - if (q.head == q.buf.items.len) { - q.buf.clearRetainingCapacity(); - q.head = 0; - } - } - - pub fn popFront(q: *Queue, n: usize) void { - const record = q.peek() orelse return; - if (n >= record.len) return q.pop(); - q.head += n; - std.mem.writeInt(u32, q.buf.items[q.head..][0..4], @intCast(record.len - n), .little); - } - - fn compact(q: *Queue) void { - if (q.head == 0 or q.head * 2 < q.buf.items.len) return; - const rest = q.buf.items.len - q.head; - std.mem.copyForwards(u8, q.buf.items[0..rest], q.buf.items[q.head..]); - q.buf.shrinkRetainingCapacity(rest); - q.head = 0; - } - - pub fn empty(q: *const Queue) bool { - return q.peek() == null; - } - - pub fn clearAndFree(q: *Queue, gpa: std.mem.Allocator) void { - q.buf.clearAndFree(gpa); - q.head = 0; - } -}; - -pub const PaneState = struct { - addr: Range = .{}, - limit: ?Range = null, - readers: u16 = 0, - events: Queue = .{}, - nomark: bool = false, - noscroll: bool = false, - tag_snap: std.ArrayList(u8) = .empty, - pty_readers: u16 = 0, - pty_out: Queue = .{}, - - pub const Range = struct { q0: u32 = 0, q1: u32 = 0 }; - - fn deinit(pf: *PaneState, gpa: std.mem.Allocator) void { - pf.events.deinit(gpa); - pf.pty_out.deinit(gpa); - pf.tag_snap.deinit(gpa); - pf.* = .{}; - } -}; - pub const Namespace = struct { socket_path: []const u8 = "", tcp_address: ?std.Io.net.IpAddress = null, @@ -1684,11 +1253,20 @@ pub const Namespace = struct { mounts: std.ArrayList(Mount) = .empty, node_name: [16]u8 = undefined, os_paths: std.ArrayList(OsPath) = .empty, - snapshots: [32]struct { node: u64 = 0, bytes: ?[]const u8 = null } = @splat(.{}), + snapshots: [tree.screen.snapshot_slots]tree.screen.Snapshot = @splat(.{}), out: std.ArrayList(u8) = .empty, - panes: [MAX_PANES]PaneState = @splat(.{}), + panes: [MAX_PANES]tree.pane.State = @splat(.{}), listeners: u16 = 0, origin: u8 = 'K', + /// The editor-wide event stream, recorded only while /log is held open. + log: tree.events.Queue = .{}, + log_readers: u16 = 0, + /// What the last ctl command created or touched, answered by reading /ctl. + results: [MAX_PANES]u32 = undefined, + results_len: u8 = 0, + results_valid: bool = false, + /// Process start, the mtime of everything that has no edit time of its own. + started: u32 = 0, pub fn deinit(st: *Namespace, gpa: std.mem.Allocator) void { for (st.mounts.items) |entry| { @@ -1700,6 +1278,7 @@ pub const Namespace = struct { st.os_paths.deinit(gpa); for (st.snapshots) |snapshot| if (snapshot.bytes) |bytes| gpa.free(bytes); for (&st.panes) |*pf| pf.deinit(gpa); + st.log.deinit(gpa); st.out.deinit(gpa); } @@ -1718,7 +1297,7 @@ pub const Namespace = struct { pub fn stage(st: *Namespace, gpa: std.mem.Allocator) *std.ArrayList(u8) { st.out.clearRetainingCapacity(); - st.out.ensureTotalCapacity(gpa, out_reserve) catch {}; + st.out.ensureTotalCapacity(gpa, tree.out_reserve) catch {}; return &st.out; } @@ -1764,3023 +1343,6 @@ pub fn unmount(p: *Pardes, name: []const u8) !void { return error.NotMounted; } -pub const max_record_text = 256; - -pub const Action = enum(u8) { - body_delete = 'D', - tag_delete = 'd', - body_insert = 'I', - tag_insert = 'i', - body_look = 'L', - tag_look = 'l', - body_exec = 'X', - tag_exec = 'x', - - pub fn char(a: Action) u8 { - return @intFromEnum(a); - } - - pub fn fromChar(c: u8) ?Action { - return std.enums.fromInt(Action, c); - } - - pub fn onTag(a: Action) bool { - return @intFromEnum(a) >= 'a'; - } -}; - -pub const flag_builtin: u32 = 1; -pub const flag_expansion: u32 = 2; -pub const flag_filename: u32 = 4; -pub const flag_chorded: u32 = 8; - -pub fn formatRecord( - buf: []u8, - origin: u8, - action: Action, - q0: u32, - q1: u32, - flag: u32, - text: []const u8, -) []const u8 { - const sent = if (text.len >= max_record_text) text[0..0] else text; - return std.fmt.bufPrint(buf, "{c}{c}{d} {d} {d} {d} {s}\n", .{ - origin, - action.char(), - q0, - q1, - flag, - sent.len, - sent, - }) catch buf[0..0]; -} - -pub const Span = struct { at: u32, removed: u32, inserted: u32 }; - -pub fn diffSpan(old: []const u8, new: []const u8) Span { - const both = @min(old.len, new.len); - const stride = 64; - var head: usize = 0; - while (head + stride <= both and - std.mem.eql(u8, old[head..][0..stride], new[head..][0..stride])) head += stride; - while (head < both and old[head] == new[head]) head += 1; - var tail: usize = 0; - const rest = both - head; - while (tail + stride <= rest and std.mem.eql( - u8, - old[old.len - tail - stride ..][0..stride], - new[new.len - tail - stride ..][0..stride], - )) tail += stride; - while (tail < rest and old[old.len - 1 - tail] == new[new.len - 1 - tail]) tail += 1; - return .{ - .at = @intCast(head), - .removed = @intCast(old.len - tail - head), - .inserted = @intCast(new.len - tail - head), - }; -} - -pub fn noteReplace(p: *Pardes, id: usize, on_tag: bool, old: []const u8, new: []const u8) void { - if (!p.fs.scripted(id)) return; - const span = diffSpan(old, new); - if (span.removed == 0 and span.inserted == 0) return; - if (span.removed > 0) _ = noteAction( - p, - id, - if (on_tag) .tag_delete else .body_delete, - span.at, - span.at + span.removed, - 0, - "", - ); - if (span.inserted > 0) _ = noteAction( - p, - id, - if (on_tag) .tag_insert else .body_insert, - span.at, - span.at + span.inserted, - 0, - new[span.at..][0..span.inserted], - ); -} - -pub fn noteAction( - p: *Pardes, - id: usize, - action: Action, - q0: u32, - q1: u32, - flag: u32, - text: []const u8, -) bool { - if (!p.fs.scripted(id)) return false; - var buf: [max_record_text + 64]u8 = undefined; - const record = formatRecord(&buf, p.fs.origin, action, q0, q1, flag, text); - p.fs.panes[id].events.push(p.gpa, record); - return true; -} - -pub fn notePtyOutput(p: *Pardes, id: usize, bytes: []const u8) void { - if (id >= MAX_PANES or bytes.len == 0) return; - const pf = &p.fs.panes[id]; - if (pf.pty_readers == 0) return; - var off: usize = 0; - while (off < bytes.len) { - const n = @min(bytes.len - off, queue_cap / 2); - pf.pty_out.push(p.gpa, bytes[off..][0..n]); - off += n; - } -} - -pub fn handle(p: *Pardes, req: Req) Reply { - if (req.node >= factory_base and req.node < factory_base + 16) { - const file = std.enums.fromInt(PaneFile, req.node - factory_base) orelse return Reply.fail(req.tag, E.NOENT); - if (file == .dir or file.inPty()) return Reply.fail(req.tag, E.NOENT); - // Truncating a factory is harmless: its next open creates an empty pane. - if (req.op == .getattr or (req.op == .setattr and req.truncate)) - return .{ .tag = req.tag, .attr = .{ .node = req.node, .name = file.name(), .mode = file.mode() } }; - if (req.op != .open) return Reply.fail(req.tag, E.PERM); - const serial = newPane(p) orelse return Reply.fail(req.tag, E.NFILE); - const node = Node.of(serial, file); - var reply = handle(p, .{ .tag = req.tag, .op = .open, .node = node }); - reply.attr.node = node; - return reply; - } - if (req.node == namespace_root or req.node == namespace_panes) return namespace(p, req); - if (req.node == os_root or req.node & os_node != 0) return osHandle(p, req); - if (req.node & archive_node != 0) return archiveHandle(p, req); - const target = Node.target(req.node) orelse return Reply.fail(req.tag, E.NOENT); - if (req.op == .write or req.op == .setattr) p.fs.origin = switch (target) { - .pane => |t| @as(u8, if (t.file == .body or t.file == .tag) 'E' else 'F'), - .top => 'F', - }; - return switch (req.op) { - .lookup => lookup(p, req, target), - .getattr => switch (attrOf(p, target)) { - .ok => |a| .{ .tag = req.tag, .attr = a }, - .missing => Reply.fail(req.tag, E.NOENT), - }, - .setattr => setattr(p, req, target), - .open => open(p, req, target), - .release => release(p, req), - .readdir => readdir(p, req, target), - .read => handleRead(p, req, target), - .write => handleWrite(p, req, target), - }; -} - -const AttrResult = union(enum) { ok: Reply.Attr, missing }; - -fn attrOf(p: *Pardes, target: Target) AttrResult { - switch (target) { - .top => |f| return .{ .ok = .{ - .name = if (f == .root) "self" else f.name(), - .node = @intFromEnum(f), - .dir = f.dir(), - .mode = f.mode(), - .size = topSize(p, f), - } }, - .pane => |t| { - const id = p.paneBySerial(t.serial) orelse return .missing; - if (t.file.inPty() and !p.panes[id].?.isTerminal()) return .missing; - return .{ .ok = .{ - .name = if (t.file == .dir) (std.fmt.bufPrint(&p.fs.node_name, "{d}", .{t.serial}) catch unreachable) else t.file.name(), - .node = Node.of(t.serial, t.file), - .dir = t.file.isDir(), - .mode = t.file.mode(), - .size = paneFileSize(p, id, t.file), - } }; - }, - } -} - -fn topSize(p: *Pardes, f: SelfFile) u64 { - return switch (f) { - .root, .new, .cons, .screen, .listeners => 0, - .index => indexLen(p), - .README => fs_help.len, - }; -} - -fn paneFileSize(p: *Pardes, id: usize, f: PaneFile) u64 { - const pane = p.panes[id] orelse return 0; - return switch (f) { - .body, .data, .xdata => bodyLen(p, pane), - .tag => tagLen(p, pane), - .dir, .addr, .ctl, .errors, .event, .rdsel, .wrsel => 0, - .pty, .pty_ctl, .pty_status, .pty_data => 0, - }; -} - -fn bodyOf(pane: *const Pane) []const u8 { - if (pane.file) |*f| return f.content; - return ""; -} - -fn fileOf(pane: *Pane) ?*panes.File.State { - return if (pane.file) |*f| f else null; -} - -fn tagOf(p: *Pardes, pane: *Pane) []const u8 { - return p.tagText(p.scratch.allocator(), pane) catch ""; -} - -fn dirOf(pane: *Pane) []const u8 { - if (pane.file) |*f| return std.fs.path.dirname(f.path) orelse "/"; - const cwd = pane.cwdSlice(); - return if (cwd.len > 0) cwd else "/"; -} - -fn dirtyOf(pane: *const Pane) bool { - const f = if (pane.file) |*x| x else return false; - if (!panes.Output.fileTraits(f.output).saves) return false; - return f.revision != f.saved_revision; -} - -fn clip(n: usize) u32 { - return std.math.cast(u32, n) orelse std.math.maxInt(u32); -} - -fn cellOf(row: i32, col: i32) modal.Cursor { - return .{ .row = @intCast(@max(0, row)), .col = @intCast(@max(0, col)) }; -} - -fn firstLine(s: []const u8) []const u8 { - return s[0 .. std.mem.indexOfScalar(u8, s, '\n') orelse s.len]; -} - -fn dotOf(pane: *Pane) PaneState.Range { - const text = bodyOf(pane); - const head = modal.offsetAt(text, cellOf(pane.cur_row, pane.cur_col)); - if (!pane.vsel.active) return .{ .q0 = clip(head), .q1 = clip(head) }; - const anchor = modal.offsetAt(text, cellOf(pane.vsel.row, pane.vsel.col)); - var hi = @max(head, anchor); - if (hi < text.len) hi = modal.nextGrapheme(text, hi); - return .{ .q0 = clip(@min(head, anchor)), .q1 = clip(hi) }; -} - -fn setDot(pane: *Pane, r: PaneState.Range) void { - const text = bodyOf(pane); - const q0 = @min(@as(usize, r.q0), text.len); - const q1 = @max(q0, @min(@as(usize, r.q1), text.len)); - const a = modal.positionAt(text, q0); - pane.vsel = .{ .active = q1 > q0, .row = @intCast(a.row), .col = @intCast(a.col), .explicit = true }; - const h = modal.positionAt(text, if (q1 > q0) modal.prevGrapheme(text, q1) else q0); - pane.cur_row = @intCast(h.row); - pane.cur_col = @intCast(h.col); - pane.cur_pinned = true; - pane.sticky_col = -1; - pane.msel.active = false; - pane.ensureCursorVisible(); -} - -fn showOffset(pane: *Pane, off: usize) void { - const text = bodyOf(pane); - const c = modal.positionAt(text, @min(off, text.len)); - pane.cur_row = @intCast(c.row); - pane.cur_col = @intCast(c.col); - pane.cur_pinned = true; - pane.sticky_col = -1; - pane.ensureCursorVisible(); -} - -fn clampAddr(pf: *PaneState, len: usize) void { - const n = clip(len); - pf.addr.q0 = @min(pf.addr.q0, n); - pf.addr.q1 = @min(pf.addr.q1, n); - if (pf.limit) |*l| { - l.q0 = @min(l.q0, n); - l.q1 = @min(l.q1, n); - } -} - -fn shiftBy(r: PaneState.Range, at: u32, removed: u32, inserted: u32) PaneState.Range { - return .{ .q0 = shiftOne(r.q0, at, removed, inserted), .q1 = shiftOne(r.q1, at, removed, inserted) }; -} - -fn shiftOne(v: u32, at: u32, removed: u32, inserted: u32) u32 { - if (v <= at) return v; - if (v <= at +| removed) return at +| inserted; - return v - removed +| inserted; -} - -fn wholeUtf8(data: []const u8) usize { - var i = data.len; - var back: usize = 0; - while (i > 0 and back < 4) : (back += 1) { - i -= 1; - const c = data[i]; - if (c < 0x80) return data.len; - if (c & 0xC0 == 0xC0) { - const need = std.unicode.utf8ByteSequenceLength(c) catch return data.len; - if (i + need <= data.len or i == 0) return data.len; - return i; - } - } - return data.len; -} - -fn paneFileNamed(name: []const u8) ?PaneFile { - const f = std.meta.stringToEnum(PaneFile, name) orelse return null; - if (f == .dir) return null; - return if (f.inPty() and f != .pty) null else f; -} - -fn ptyFileNamed(name: []const u8) ?PaneFile { - if (std.mem.eql(u8, name, "ctl")) return .pty_ctl; - if (std.mem.eql(u8, name, "status")) return .pty_status; - if (std.mem.eql(u8, name, "data")) return .pty_data; - return null; -} - -fn topFileNamed(name: []const u8) ?SelfFile { - const f = std.meta.stringToEnum(SelfFile, name) orelse return null; - return if (f == .root) null else f; -} - -fn serialNamed(name: []const u8) ?u32 { - if (name.len == 0 or name.len > 10) return null; - for (name) |c| if (c < '0' or c > '9') return null; - return std.fmt.parseInt(u32, name, 10) catch null; -} - -fn nextSerialAfter(p: *Pardes, after: u32) ?u32 { - var best: ?u32 = null; - for (p.panes) |slot| { - const pane = slot orelse continue; - if (pane.serial <= after) continue; - if (best == null or pane.serial < best.?) best = pane.serial; - } - return best; -} - -fn newPane(p: *Pardes) ?u32 { - const slot = p.freeSlot() orelse return null; - p.newScratchBelow(p.active); - const pane = p.panes[slot] orelse return null; - return pane.serial; -} - -fn lookup(p: *Pardes, req: Req, target: Target) Reply { - const name = req.data; - if (std.mem.eql(u8, name, "..")) { - const parent: u64 = switch (target) { - .top => |top| if (top == .root) namespace_root else @intFromEnum(SelfFile.root), - .pane => |t| if (t.file == .pty) Node.of(t.serial, .dir) else namespace_panes, - }; - return handle(p, .{ .tag = req.tag, .op = .getattr, .node = parent }); - } - if (name.len == 0 or std.mem.indexOfScalar(u8, name, '/') != null) return Reply.fail(req.tag, E.NOENT); - const node: u64 = switch (target) { - .top => |f| switch (f) { - .root => root: { - if (std.mem.eql(u8, name, "pane")) return .{ .tag = req.tag, .attr = .{ .node = namespace_panes, .dir = true, .mode = 0o500 } }; - if (topFileNamed(name)) |t| break :root @intFromEnum(t); - if (archiveNode(name)) |node| return archiveHandle(p, .{ .tag = req.tag, .op = .getattr, .node = node }); - return Reply.fail(req.tag, E.NOENT); - }, - .new => new: { - if (std.mem.eql(u8, name, "README")) break :new @intFromEnum(SelfFile.README); - const want = paneFileNamed(name) orelse return Reply.fail(req.tag, E.NOENT); - if (want.inPty()) return Reply.fail(req.tag, E.NOENT); - return handle(p, .{ .tag = req.tag, .op = .getattr, .node = factory_base + @intFromEnum(want) }); - }, - else => return Reply.fail(req.tag, E.NOTDIR), - }, - .pane => |t| pane: { - _ = p.paneBySerial(t.serial) orelse return Reply.fail(req.tag, E.NOENT); - const f = switch (t.file) { - .dir => paneFileNamed(name), - .pty => ptyFileNamed(name), - else => return Reply.fail(req.tag, E.NOTDIR), - } orelse return Reply.fail(req.tag, E.NOENT); - break :pane Node.of(t.serial, f); - }, - }; - return switch (attrOf(p, Node.target(node) orelse return Reply.fail(req.tag, E.NOENT))) { - .ok => |a| .{ .tag = req.tag, .attr = a }, - .missing => Reply.fail(req.tag, E.NOENT), - }; -} - -pub fn stageDirent(out: *std.ArrayList(u8), gpa: std.mem.Allocator, node: u64, dir: bool, name: []const u8) void { - if (name.len == 0 or name.len > 255) return; - var head: [10]u8 = undefined; - std.mem.writeInt(u64, head[0..8], node, .little); - head[8] = @intFromBool(dir); - head[9] = @intCast(name.len); - out.appendSlice(gpa, &head) catch return; - out.appendSlice(gpa, name) catch return; -} - -fn stagePaneFiles(p: *Pardes, out: *std.ArrayList(u8), serial: u32, terminal: bool, skip: *u64) void { - inline for (comptime std.enums.values(PaneFile)) |f| { - if (comptime f == .dir or (f.inPty() and f != .pty)) continue; - const present = f != .pty or terminal; - if (present) { - if (skip.* > 0) skip.* -= 1 else stageDirent(out, p.gpa, Node.of(serial, f), f.isDir(), f.name()); - } - } -} - -fn stagePtyFiles(p: *Pardes, out: *std.ArrayList(u8), serial: u32, skip: *u64) void { - inline for (comptime std.enums.values(PaneFile)) |f| { - if (comptime !f.inPty() or f == .pty) continue; - if (skip.* > 0) skip.* -= 1 else stageDirent(out, p.gpa, Node.of(serial, f), false, f.name()); - } -} - -fn readdir(p: *Pardes, req: Req, target: Target) Reply { - const out = p.fs.stage(p.gpa); - var skip = req.off; - switch (target) { - .top => |f| switch (f) { - .root => { - inline for (.{ SelfFile.index, SelfFile.cons, SelfFile.new }) |t| { - if (skip > 0) skip -= 1 else stageDirent(out, p.gpa, @intFromEnum(t), t.dir(), t.name()); - } - if (skip > 0) skip -= 1 else stageDirent(out, p.gpa, namespace_panes, true, "pane"); - if (skip > 0) skip -= 1 else stageDirent(out, p.gpa, @intFromEnum(SelfFile.screen), false, "screen"); - if (skip > 0) skip -= 1 else stageDirent(out, p.gpa, @intFromEnum(SelfFile.listeners), false, "listeners"); - if (skip > 0) skip -= 1 else stageDirent(out, p.gpa, @intFromEnum(SelfFile.README), false, "README"); - stageArchive(p, out, "", &skip); - }, - .new => { - if (skip > 0) skip -= 1 else stageDirent(out, p.gpa, @intFromEnum(SelfFile.README), false, "README"); - inline for (comptime std.enums.values(PaneFile)) |file| { - if (comptime file == .dir or file.inPty()) continue; - if (skip > 0) skip -= 1 else stageDirent(out, p.gpa, factory_base + @intFromEnum(file), false, file.name()); - } - }, - else => return Reply.fail(req.tag, E.NOTDIR), - }, - .pane => |t| { - const id = p.paneBySerial(t.serial) orelse return Reply.fail(req.tag, E.NOENT); - const terminal = p.panes[id].?.isTerminal(); - switch (t.file) { - .dir => stagePaneFiles(p, out, t.serial, terminal, &skip), - .pty => { - if (!terminal) return Reply.fail(req.tag, E.NOENT); - stagePtyFiles(p, out, t.serial, &skip); - }, - else => return Reply.fail(req.tag, E.NOTDIR), - } - }, - } - return .{ .tag = req.tag, .payload = .{ .staged = @intCast(out.items.len) } }; -} - -fn open(p: *Pardes, req: Req, target: Target) Reply { - const snapshot = switch (target) { - .top => |f| f == .screen, - .pane => |t| t.file == .body and if (p.paneBySerial(t.serial)) |id| p.panes[id].?.isTerminal() else false, - }; - if (snapshot) { - for (&p.fs.snapshots, 0..) |*slot, i| { - if (slot.node != 0) continue; - const bytes = if (target == .top) screenSnapshot(p) catch return Reply.fail(req.tag, E.NOMEM) else null; - slot.* = .{ .node = req.node, .bytes = bytes }; - return .{ .tag = req.tag, .handle = @intCast(i + 1) }; - } - return Reply.fail(req.tag, E.NFILE); - } - switch (target) { - .top => {}, - .pane => |t| { - const id = p.paneBySerial(t.serial) orelse return Reply.fail(req.tag, E.NOENT); - const pf = &p.fs.panes[id]; - if (t.file.inPty() and !p.panes[id].?.isTerminal()) return Reply.fail(req.tag, E.NOENT); - switch (t.file) { - .ctl => pf.limit = null, - .addr => { - pf.addr = .{}; - pf.limit = null; - }, - .event => { - pf.readers +|= 1; - p.fs.listeners +|= 1; - }, - .pty_data => pf.pty_readers +|= 1, - else => {}, - } - }, - } - return .{ .tag = req.tag, .handle = 1 }; -} - -fn release(p: *Pardes, req: Req) Reply { - if (req.handle > 0 and req.handle <= p.fs.snapshots.len) { - const snapshot = &p.fs.snapshots[req.handle - 1]; - if (snapshot.node == req.node) { - if (snapshot.bytes) |bytes| p.gpa.free(bytes); - snapshot.* = .{}; - return .{ .tag = req.tag }; - } - } - const target = Node.target(req.node) orelse return .{ .tag = req.tag }; - switch (target) { - .top => {}, - .pane => |t| { - if (t.file != .event and t.file != .pty_data) return .{ .tag = req.tag }; - const id = p.paneBySerial(t.serial) orelse return .{ .tag = req.tag }; - const pf = &p.fs.panes[id]; - if (t.file == .pty_data) { - if (pf.pty_readers == 0) return .{ .tag = req.tag }; - pf.pty_readers -= 1; - if (pf.pty_readers == 0) pf.pty_out.clearAndFree(p.gpa); - return .{ .tag = req.tag }; - } - if (pf.readers == 0) return .{ .tag = req.tag }; - pf.readers -= 1; - p.fs.listeners -|= 1; - if (pf.readers == 0) pf.tag_snap.clearAndFree(p.gpa); - }, - } - return .{ .tag = req.tag }; -} - -fn setattr(p: *Pardes, req: Req, target: Target) Reply { - if (req.truncate) switch (target) { - .pane => |t| switch (t.file) { - .body, .data, .xdata => { - const id = p.paneBySerial(t.serial) orelse return Reply.fail(req.tag, E.NOENT); - const pane = p.panes[id].?; - if (fileOf(pane) != null) { - _ = spliceBody(p, id, pane, 0, bodyOf(pane).len, "") orelse - return Reply.fail(req.tag, E.NOMEM); - p.fs.panes[id].addr = .{}; - setDot(pane, .{}); - } - }, - else => {}, - }, - else => {}, - }; - return switch (attrOf(p, target)) { - .ok => |a| .{ .tag = req.tag, .attr = a }, - .missing => Reply.fail(req.tag, E.NOENT), - }; -} - -fn staged(p: *Pardes, req: Req) Reply { - const out = &p.fs.out; - const off = @min(req.off, out.items.len); - const n = @min(out.items.len - off, req.size); - if (off > 0) std.mem.copyForwards(u8, out.items[0..n], out.items[off..][0..n]); - out.shrinkRetainingCapacity(n); - return .{ .tag = req.tag, .payload = .{ .staged = @intCast(n) } }; -} - -fn handleRead(p: *Pardes, req: Req, target: Target) Reply { - switch (target) { - .top => |f| return switch (f) { - .index => readIndex(p, req), - .README => help: { - const off = @min(req.off, fs_help.len); - const bytes = fs_help[off..][0..@min(req.size, fs_help.len - off)]; - p.fs.stage(p.gpa).appendSlice(p.gpa, bytes) catch break :help Reply.fail(req.tag, E.NOMEM); - break :help .{ .tag = req.tag, .payload = .{ .staged = @intCast(bytes.len) } }; - }, - .listeners => listeners: { - var buf: [512]u8 = undefined; - var text = std.Io.Writer.fixed(&buf); - if (p.fs.socket_path.len != 0) - text.print("unix!{s}\n", .{p.fs.socket_path}) catch break :listeners Reply.fail(req.tag, E.IO); - for ([_]?std.Io.net.IpAddress{ p.fs.tcp_address, p.fs.quic_address }, [_][]const u8{ "tcp", "quic" }) |maybe, transport| { - const address = maybe orelse continue; - switch (address) { - .ip4 => |ip| text.print("{s}!{d}.{d}.{d}.{d}!{d}\n", .{ transport, ip.bytes[0], ip.bytes[1], ip.bytes[2], ip.bytes[3], ip.port }) catch - break :listeners Reply.fail(req.tag, E.IO), - .ip6 => |ip| text.print("{s}!{f}!{d}\n", .{ transport, std.Io.net.Ip6Address.Unresolved{ .bytes = ip.bytes, .interface_name = null }, ip.port }) catch - break :listeners Reply.fail(req.tag, E.IO), - } - } - const bytes = text.buffered(); - const off = @min(req.off, bytes.len); - const len = @min(bytes.len - off, req.size); - p.fs.stage(p.gpa).appendSlice(p.gpa, bytes[off..][0..len]) catch break :listeners Reply.fail(req.tag, E.NOMEM); - break :listeners .{ .tag = req.tag, .payload = .{ .staged = @intCast(len) } }; - }, - .screen => readSnapshot(p, req, null), - .cons, .root, .new => Reply.fail(req.tag, E.PERM), - }, - .pane => |t| { - const id = p.paneBySerial(t.serial) orelse return Reply.fail(req.tag, E.NOENT); - const pane = p.panes[id].?; - const pf = &p.fs.panes[id]; - if (t.file.inPty() and !pane.isTerminal()) return Reply.fail(req.tag, E.NOENT); - return switch (t.file) { - .addr => readAddr(p, req, pf, pane), - .body => readBody(p, req, id, pane), - .ctl => readCtl(p, req, pane), - .data => readData(req, id, pane, pf, false), - .xdata => readData(req, id, pane, pf, true), - .tag => readTag(p, req, pane), - .event => readQueue(p, req, &pf.events), - .rdsel => readRdsel(req, id, pane), - .pty_status => readPtyStatus(p, req, id, pane), - .pty_data => readPtyData(p, req, pf), - .dir, .errors, .wrsel, .pty, .pty_ctl => Reply.fail(req.tag, E.PERM), - }; - }, - } -} - -fn screenSnapshot(p: *Pardes) ![]u8 { - var arena: std.heap.ArenaAllocator = .init(p.gpa); - defer arena.deinit(); - const surface = try p.render(arena.allocator()); - var styles: std.ArrayList(pardes.CellStyle) = .empty; - var indices: std.ArrayList(usize) = .empty; - for (surface.cells) |cell| { - const style: pardes.CellStyle = if (cell.default) .{} else cell.style; - const index = for (styles.items, 0..) |previous, i| { - if (std.meta.eql(style, previous)) break i; - } else new: { - try styles.append(arena.allocator(), style); - break :new styles.items.len - 1; - }; - try indices.append(arena.allocator(), index); - } - var out: std.Io.Writer.Allocating = .init(p.gpa); - errdefer out.deinit(); - const writer = &out.writer; - try writer.print("{{\"cols\":{d},\"rows\":{d},\"cursor\":", .{ surface.cols, surface.rows }); - try std.json.Stringify.value(surface.cursor, .{}, writer); - try writer.writeAll(",\"styles\":"); - try std.json.Stringify.value(styles.items, .{ .emit_strings_as_arrays = true }, writer); - try writer.writeAll(",\"cells\":["); - for (surface.cells, indices.items, 0..) |cell, index, i| { - if (i != 0) try writer.writeByte(','); - try std.json.Stringify.value(.{ if (cell.default) " " else cell.grapheme(), index }, .{}, writer); - } - try writer.writeAll("]}\n"); - return out.toOwnedSlice(); -} - -const ctl_fields = 5 * 12; - -fn stageCtlNumbers(p: *Pardes, out: *std.ArrayList(u8), pane: *Pane) void { - out.print(p.gpa, "{d:>11} {d:>11} {d:>11} {d:>11} {d:>11} ", .{ - pane.serial, - tagOf(p, pane).len, - bodyOf(pane).len, - @as(u32, 0), - @intFromBool(dirtyOf(pane)), - }) catch {}; -} - -fn readIndex(p: *Pardes, req: Req) Reply { - const out = p.fs.stage(p.gpa); - var last: u32 = 0; - while (nextSerialAfter(p, last)) |s| { - last = s; - const pane = p.panes[p.paneBySerial(s).?].?; - stageCtlNumbers(p, out, pane); - out.appendSlice(p.gpa, firstLine(tagOf(p, pane))) catch {}; - out.append(p.gpa, '\n') catch {}; - } - return staged(p, req); -} - -fn readAddr(p: *Pardes, req: Req, pf: *PaneState, pane: *Pane) Reply { - clampAddr(pf, bodyOf(pane).len); - const out = p.fs.stage(p.gpa); - out.print(p.gpa, "{d:>11} {d:>11} ", .{ pf.addr.q0, pf.addr.q1 }) catch {}; - return staged(p, req); -} - -fn readBody(p: *Pardes, req: Req, id: usize, pane: *Pane) Reply { - if (pane.file != null) { - const text = bodyOf(pane); - const off = @min(req.off, text.len); - const n = @min(text.len - off, req.size); - return .{ .tag = req.tag, .payload = .{ .region = .{ - .pane = @intCast(id), - .serial = pane.serial, - .off = clip(off), - .len = clip(n), - } } }; - } - if (req.handle != 0 and pane.isTerminal()) return readSnapshot(p, req, pane); - const text = panes.Terminal.screenTextAlloc(pane, p.gpa) catch - return Reply.fail(req.tag, E.NOMEM); - defer p.gpa.free(text); - const out = p.fs.stage(p.gpa); - out.appendSlice(p.gpa, text) catch return Reply.fail(req.tag, E.NOMEM); - return staged(p, req); -} - -fn readSnapshot(p: *Pardes, req: Req, pane: ?*Pane) Reply { - if (req.handle == 0 or req.handle > p.fs.snapshots.len) return Reply.fail(req.tag, E.INVAL); - const snapshot = &p.fs.snapshots[req.handle - 1]; - if (snapshot.node == 0 or snapshot.node != req.node) return Reply.fail(req.tag, E.INVAL); - if (snapshot.bytes == null) { - const terminal = pane orelse return Reply.fail(req.tag, E.INVAL); - snapshot.bytes = panes.Terminal.screenTextAlloc(terminal, p.gpa) catch return Reply.fail(req.tag, E.NOMEM); - } - const bytes = snapshot.bytes.?; - const off = @min(req.off, bytes.len); - const len = @min(bytes.len - off, req.size); - const out = p.fs.stage(p.gpa); - out.appendSlice(p.gpa, bytes[off..][0..len]) catch return Reply.fail(req.tag, E.NOMEM); - return .{ .tag = req.tag, .payload = .{ .staged = @intCast(len) } }; -} - -fn fontName(p: *Pardes) []const u8 { - const name = p.settings.font.effective_name.get(); - return if (name.len == 0) "default" else name; -} - -fn stageQuoted(out: *std.ArrayList(u8), gpa: std.mem.Allocator, s: []const u8) void { - const plain = s.len > 0 and for (s) |c| { - if (c <= ' ' or c == '\'') break false; - } else true; - if (plain) { - out.appendSlice(gpa, s) catch {}; - return; - } - out.append(gpa, '\'') catch {}; - for (s) |c| { - if (c == '\'') out.append(gpa, '\'') catch {}; - out.append(gpa, c) catch {}; - } - out.append(gpa, '\'') catch {}; -} - -fn readCtl(p: *Pardes, req: Req, pane: *Pane) Reply { - const out = p.fs.stage(p.gpa); - stageCtlNumbers(p, out, pane); - out.print(p.gpa, "{d:>11} ", .{pane.cols}) catch {}; - stageQuoted(out, p.gpa, fontName(p)); - out.print(p.gpa, " {d:>11} ", .{config.tab_width}) catch {}; - return staged(p, req); -} - -fn readTag(p: *Pardes, req: Req, pane: *Pane) Reply { - const out = p.fs.stage(p.gpa); - out.appendSlice(p.gpa, tagOf(p, pane)) catch {}; - return staged(p, req); -} - -fn readData(req: Req, id: usize, pane: *Pane, pf: *PaneState, stop_at_end: bool) Reply { - const text = bodyOf(pane); - clampAddr(pf, text.len); - const q0: usize = pf.addr.q0; - const hi: usize = if (stop_at_end) @max(q0, @as(usize, pf.addr.q1)) else text.len; - var end = @min(hi, q0 +| req.size); - end = @max(q0, modal.graphemeStart(text, end)); - pf.addr.q0 = clip(end); - if (!stop_at_end) pf.addr.q1 = clip(end); - if (pane.file == null) return .{ .tag = req.tag }; - return .{ .tag = req.tag, .payload = .{ .region = .{ - .pane = @intCast(id), - .serial = pane.serial, - .off = clip(q0), - .len = clip(end - q0), - } } }; -} - -fn readRdsel(req: Req, id: usize, pane: *Pane) Reply { - if (pane.file == null) return .{ .tag = req.tag }; - const text = bodyOf(pane); - const d = dotOf(pane); - const lo = @min(@as(usize, d.q0), text.len); - const hi = @max(lo, @min(@as(usize, d.q1), text.len)); - const off = @min(req.off, hi - lo); - const n = @min(hi - lo - off, req.size); - return .{ .tag = req.tag, .payload = .{ .region = .{ - .pane = @intCast(id), - .serial = pane.serial, - .off = clip(lo + off), - .len = clip(n), - } } }; -} - -fn readQueue(p: *Pardes, req: Req, q: *Queue) Reply { - const record = q.peek() orelse return .{ .tag = req.tag, .status = .again }; - if (req.size < record.len) return Reply.fail(req.tag, E.INVAL); - const out = p.fs.stage(p.gpa); - out.appendSlice(p.gpa, record) catch return Reply.fail(req.tag, E.NOMEM); - q.pop(); - return .{ .tag = req.tag, .payload = .{ .staged = @intCast(out.items.len) } }; -} - -fn readPtyStatus(p: *Pardes, req: Req, id: usize, pane: *Pane) Reply { - const out = p.fs.stage(p.gpa); - out.print(p.gpa, "{d:>11} {d:>11} {d:>11} ", .{ - pane.cols, - pane.rows, - @intFromBool(p.hostTtyTaken(id)), - }) catch {}; - return staged(p, req); -} - -fn readPtyData(p: *Pardes, req: Req, pf: *PaneState) Reply { - if (pf.pty_out.empty()) return .{ .tag = req.tag, .status = .again }; - const out = p.fs.stage(p.gpa); - while (out.items.len < req.size) { - const chunk = pf.pty_out.peek() orelse break; - const n = @min(chunk.len, req.size - out.items.len); - out.appendSlice(p.gpa, chunk[0..n]) catch break; - pf.pty_out.popFront(n); - } - return .{ .tag = req.tag, .payload = .{ .staged = @intCast(out.items.len) } }; -} - -fn handleWrite(p: *Pardes, req: Req, target: Target) Reply { - switch (target) { - .top => |f| return switch (f) { - .cons => if (appendErrors(p, p.active, req.data)) |took| - .{ .tag = req.tag, .written = @intCast(took) } - else - Reply.fail(req.tag, E.IO), - else => Reply.fail(req.tag, E.PERM), - }, - .pane => |t| { - const id = p.paneBySerial(t.serial) orelse return Reply.fail(req.tag, E.NOENT); - const pane = p.panes[id].?; - if (t.file.inPty() and !pane.isTerminal()) return Reply.fail(req.tag, E.NOENT); - return switch (t.file) { - .addr => writeAddr(p, req, id, pane), - .body => writeBody(p, req, id, pane), - .ctl => writeCtl(p, req, t.serial), - .data, .xdata => writeData(p, req, id, pane), - .tag => writeTag(p, req, pane), - .event => writeEvent(p, req, id), - .wrsel => writeWrsel(p, req, id, pane), - .errors => if (appendErrors(p, id, req.data)) |took| - .{ .tag = req.tag, .written = @intCast(took) } - else - Reply.fail(req.tag, E.IO), - .pty_ctl => writePtyCtl(p, req, id), - .pty_data => writePtyData(p, req, id), - .dir, .rdsel, .pty, .pty_status => Reply.fail(req.tag, E.PERM), - }; - }, - } -} - -fn spliceBody(p: *Pardes, id: usize, pane: *Pane, q0: usize, q1: usize, bytes: []const u8) ?usize { - const f = fileOf(pane) orelse return null; - const take = if (bytes.len == 0) 0 else wholeUtf8(bytes); - const lo = @min(q0, f.content.len); - const hi = @max(lo, @min(q1, f.content.len)); - const new = p.gpa.alloc(u8, f.content.len - (hi - lo) + take) catch return null; - @memcpy(new[0..lo], f.content[0..lo]); - @memcpy(new[lo..][0..take], bytes[0..take]); - @memcpy(new[lo + take ..], f.content[hi..]); - if (!p.fs.panes[id].nomark) panes.File.pushUndo(p, pane); - panes.File.setContent(p, f, new); - return take; -} - -fn writeBody(p: *Pardes, req: Req, id: usize, pane: *Pane) Reply { - if (req.data.len == 0) return .{ .tag = req.tag, .written = 0 }; - if (pane.file == null) { - const take = wholeUtf8(req.data); - p.emitWrite(id, req.data[0..take]); - return .{ .tag = req.tag, .written = @intCast(take) }; - } - const at = bodyOf(pane).len; - const take = spliceBody(p, id, pane, at, at, req.data) orelse - return Reply.fail(req.tag, E.NOMEM); - if (!p.fs.panes[id].noscroll) showOffset(pane, at + take); - return .{ .tag = req.tag, .written = @intCast(take) }; -} - -fn writeTag(p: *Pardes, req: Req, pane: *Pane) Reply { - if (req.data.len == 0) return .{ .tag = req.tag, .written = 0 }; - p.seedTail(pane); - const room = pane.tag_tail.len - pane.tag_tail_len; - if (room == 0) return Reply.fail(req.tag, E.NOSPC); - const take = wholeUtf8(req.data[0..@min(req.data.len, room)]); - @memcpy(pane.tag_tail[pane.tag_tail_len..][0..take], req.data[0..take]); - pane.tag_tail_len += take; - pane.tag_init = true; - return .{ .tag = req.tag, .written = @intCast(take) }; -} - -fn writeData(p: *Pardes, req: Req, id: usize, pane: *Pane) Reply { - if (fileOf(pane) == null) return Reply.fail(req.tag, E.INVAL); - const pf = &p.fs.panes[id]; - clampAddr(pf, bodyOf(pane).len); - const q0: usize = pf.addr.q0; - const q1: usize = @max(q0, @as(usize, pf.addr.q1)); - const before = dotOf(pane); - const take = spliceBody(p, id, pane, q0, q1, req.data) orelse - return Reply.fail(req.tag, E.NOMEM); - setDot(pane, shiftBy(before, clip(q0), clip(q1 - q0), clip(take))); - pf.addr = .{ .q0 = clip(q0 + take), .q1 = clip(q0 + take) }; - if (!pf.noscroll) showOffset(pane, q0 + take); - return .{ .tag = req.tag, .written = @intCast(take) }; -} - -fn writeWrsel(p: *Pardes, req: Req, id: usize, pane: *Pane) Reply { - if (fileOf(pane) == null) return Reply.fail(req.tag, E.INVAL); - const d = dotOf(pane); - const q0: usize = d.q0; - const q1: usize = @max(q0, @as(usize, d.q1)); - const take = spliceBody(p, id, pane, q0, q1, req.data) orelse - return Reply.fail(req.tag, E.NOMEM); - setDot(pane, .{ .q0 = clip(q0 + take), .q1 = clip(q0 + take) }); - return .{ .tag = req.tag, .written = @intCast(take) }; -} - -fn writeAddr(p: *Pardes, req: Req, id: usize, pane: *Pane) Reply { - const pf = &p.fs.panes[id]; - const text = bodyOf(pane); - clampAddr(pf, text.len); - const expr = std.mem.trimEnd(u8, req.data, "\n"); - var a: Addr = .{ .text = text, .lim = pf.limit, .expr = expr }; - const r = a.address(pf.addr) orelse return Reply.fail(req.tag, E.INVAL); - if (a.i < expr.len) return Reply.fail(req.tag, E.INVAL); - pf.addr = r; - return .{ .tag = req.tag, .written = @intCast(req.data.len) }; -} - -fn safePattern(pat: []const u8) bool { - var i: usize = 0; - while (i < pat.len) : (i += 1) { - if (pat[i] != '\\') continue; - if (i + 1 >= pat.len) return false; - i += 1; - } - return true; -} - -const Addr = struct { - text: []const u8, - lim: ?PaneState.Range, - expr: []const u8, - i: usize = 0, - depth: u8 = 0, - - const max_depth = 32; - const Size = enum { char, line }; - - fn address(a: *Addr, ar_in: PaneState.Range) ?PaneState.Range { - const start = a.i; - var ar = ar_in; - var r = ar_in; - var dir: u8 = 0; - var size: Size = .line; - var c: u8 = 0; - while (a.i < a.expr.len) { - const prevc = c; - c = a.expr[a.i]; - a.i += 1; - switch (c) { - ',', ';' => { - if (c == ';') ar = r; - if (prevc == 0) r.q0 = 0; // lhs defaults to 0 - if (a.i >= a.expr.len) { - r.q1 = clip(a.text.len); // rhs defaults to $ - } else { - if (a.depth >= max_depth) return null; - a.depth += 1; - const nr = a.address(ar) orelse return null; - a.depth -= 1; - r.q1 = nr.q1; - } - return r; - }, - '+', '-' => { - if (prevc == '+' or prevc == '-') { - const nc = if (a.i < a.expr.len) a.expr[a.i] else 0; - if (nc != '#' and nc != '/' and nc != '?') - r = a.number(r, 1, prevc, .line) orelse return null; - } - dir = c; - }, - '.', '$' => { - if (a.i != start + 1) { - a.i -= 1; - return r; - } - r = if (c == '.') ar else .{ .q0 = clip(a.text.len), .q1 = clip(a.text.len) }; - dir = if (a.i < a.expr.len) '+' else 0; - }, - '#', '0'...'9' => { - var digit = c; - if (c == '#') { - if (a.i >= a.expr.len or a.expr[a.i] < '0' or a.expr[a.i] > '9') { - a.i -= 1; - return r; - } - digit = a.expr[a.i]; - a.i += 1; - size = .char; - } - var n: u64 = digit - '0'; - while (a.i < a.expr.len) : (a.i += 1) { - const d = a.expr[a.i]; - if (d < '0' or d > '9') break; - n = @min(n * 10 + (d - '0'), std.math.maxInt(u32)); - } - r = a.number(r, @intCast(n), dir, size) orelse return null; - dir = 0; - size = .line; - }, - '/', '?' => { - const back = c == '?'; - r = a.regexp(r, a.pattern(c), back) orelse return null; - dir = 0; - size = .line; - }, - else => { - a.i -= 1; - return r; - }, - } - } - if (dir != 0) r = a.number(r, 1, dir, .line) orelse return null; - return r; - } - - fn pattern(a: *Addr, delim: u8) []const u8 { - const s = a.i; - while (a.i < a.expr.len) { - const c = a.expr[a.i]; - if (c == '\n') break; - a.i += 1; - if (c == '\\') { - if (a.i < a.expr.len) a.i += 1; - continue; - } - if (c == delim) return a.expr[s .. a.i - 1]; - } - return a.expr[s..a.i]; - } - - fn number(a: *Addr, r_in: PaneState.Range, n: u32, dir: u8, size: Size) ?PaneState.Range { - var r = r_in; - if (size == .char) { - var off: i64 = n; - if (dir == '+') { - off = @as(i64, r.q1) + n; - } else if (dir == '-') { - if (r.q0 == 0 and n > 0) r.q0 = clip(a.text.len); - off = @as(i64, r.q0) - n; - } - if (off < 0 or off > @as(i64, @intCast(a.text.len))) return null; - const g = clip(modal.graphemeStart(a.text, @intCast(off))); - return .{ .q0 = g, .q1 = g }; - } - var line: i64 = n; - var q0: usize = r.q0; - var q1: usize = r.q1; - switch (dir) { - '-' => { - if (q0 < a.text.len) while (q0 > 0 and a.text[q0 - 1] != '\n') { - q0 -= 1; - }; - q1 = q0; - while (line > 0 and q0 > 0) { - if (a.text[q0 - 1] == '\n') { - line -= 1; - q1 = q0; - } - q0 -= 1; - } - if (line > 1) return null; - while (q0 > 0 and a.text[q0 - 1] != '\n') q0 -= 1; - return .{ .q0 = clip(q0), .q1 = clip(q1) }; - }, - '+' => { - if (q1 > 0) while (q1 < a.text.len and a.text[q1 - 1] != '\n') { - q1 += 1; - }; - q0 = q1; - }, - else => { - q0 = 0; - q1 = 0; - }, - } - while (line > 0 and q1 < a.text.len) { - const ch = a.text[q1]; - q1 += 1; - if (ch == '\n' or q1 == a.text.len) { - line -= 1; - if (line > 0) q0 = q1; - } - } - if (line > 0) return null; - return .{ .q0 = clip(q0), .q1 = clip(q1) }; - } - - fn regexp(a: *Addr, r: PaneState.Range, pat: []const u8, back: bool) ?PaneState.Range { - if (pat.len == 0 or !safePattern(pat)) return null; - const re = mvzr.compile(pat) orelse return null; - if (back) { - const hi = @min(@as(usize, r.q0), a.text.len); - var best: ?mvzr.Match = null; - var at: usize = 0; - while (at < hi) { - const m = re.matchPos(at, a.text[0..hi]) orelse break; - best = m; - at = if (m.end > m.start) m.end else m.end + 1; - } - const m = best orelse return null; - return .{ .q0 = clip(m.start), .q1 = clip(m.end) }; - } - const hi = if (a.lim) |l| @min(@as(usize, l.q1), a.text.len) else a.text.len; - const from = @min(@as(usize, r.q1), hi); - const m = re.match(a.text[from..hi]) orelse return null; - return .{ .q0 = clip(from + m.start), .q1 = clip(from + m.end) }; - } -}; - -const Verb = enum { - @"addr=dot", - clean, - cleartag, - del, - delete, - dirty, - @"dot=addr", - get, - @"limit=addr", - mark, - nomark, - noscroll, - put, - scroll, - show, -}; - -const refused_verbs = [_][]const u8{ "dump", "dumpdir", "font", "lock", "menu", "nomenu", "unlock" }; - -fn verbIs(line: []const u8, word: []const u8) bool { - if (!std.mem.startsWith(u8, line, word)) return false; - return line.len == word.len or line[word.len] == ' '; -} - -fn writeCtl(p: *Pardes, req: Req, serial: u32) Reply { - for ([2]bool{ false, true }) |apply| { - var dirty = if (p.paneBySerial(serial)) |id| dirtyOf(p.panes[id].?) else false; - var it = std.mem.splitScalar(u8, req.data, '\n'); - while (it.next()) |raw| { - const line = std.mem.trim(u8, raw, " \t\r"); - if (line.len == 0) continue; - const live = p.paneBySerial(serial) orelse if (apply) break else return Reply.fail(req.tag, E.NOENT); - const errno = ctlVerb(p, live, line, apply, &dirty); - if (errno != 0) return Reply.fail(req.tag, errno); - } - } - return .{ .tag = req.tag, .written = @intCast(req.data.len) }; -} - -/// Change a buffer's absolute name without writing or renaming a disk file. -/// Tag editing preserves user commands; the 9P name operation resets its tail. -pub fn nameBuffer(p: *Pardes, id: usize, full: []const u8, preserve_tag: bool) !void { - const pane = p.panes[id] orelse return error.NoPane; - const f = fileOf(pane) orelse return error.NotFile; - if (!std.fs.path.isAbsolute(full) or full.len == 0 or full.len >= 4096) - return error.InvalidName; - for (full) |c| if (c < ' ') return error.InvalidName; - if (std.mem.eql(u8, f.path, full)) return; - const copy = try p.gpa.dupe(u8, full); - p.gpa.free(f.path); - f.path = copy; - if (panes.Output.fileTraits(f.output).saves) { - f.output = null; - pane.clearCwd(); - if (!preserve_tag) { - pane.tag_init = false; - pane.tag_tail_len = 0; - } - f.saved_revision = f.revision -% 1; - f.watch_after_save = localPath(full) != null; - } - if (f.highlights.len > 0) p.tree_sitter_gpa.free(f.highlights); - f.highlights = &.{}; - f.highlight_start = 0; - f.syntax_dirty = true; - f.context_revision = null; - pane.context_rows = 0; - pane.wrap_n = 0; - p.invalidateLookHover(id); - p.emit(.{ .watch = .{ .pane = @intCast(id), .on = false } }); -} - -fn ctlVerb(p: *Pardes, id: usize, line: []const u8, apply: bool, dirty: *bool) u16 { - const pane = p.panes[id] orelse return E.INVAL; - const pf = &p.fs.panes[id]; - - if (verbIs(line, "look")) { - if (line.len <= 5) return E.INVAL; - const word = std.mem.trim(u8, line[5..], " \t"); - if (word.len == 0) return E.INVAL; - for (word) |c| if (c < ' ') return E.INVAL; - if (apply) p.lookAt(id, word); - return 0; - } - if (verbIs(line, "name")) { - if (line.len <= 5) return E.INVAL; - const name = std.mem.trim(u8, line[5..], " \t"); - if (name.len == 0) return E.INVAL; - for (name) |c| if (c <= ' ') return E.INVAL; - const f = fileOf(pane) orelse return 0; - const full = std.fs.path.resolvePosix(p.gpa, &.{ Pardes.paneDir(pane), name }) catch return E.NOMEM; - defer p.gpa.free(full); - if (!std.fs.path.isAbsolute(full) or full.len >= 4096) return E.INVAL; - if (std.mem.eql(u8, f.path, full)) return 0; - if (panes.Output.fileTraits(f.output).saves) dirty.* = true; - if (!apply) return 0; - nameBuffer(p, id, full, false) catch return E.NOMEM; - return 0; - } - for (refused_verbs) |w| if (verbIs(line, w)) return E.INVAL; - - const v = std.meta.stringToEnum(Verb, line) orelse return E.INVAL; - if (v == .del and dirty.*) return E.INVAL; - switch (v) { - .dirty => dirty.* = true, - .clean, .get, .put => dirty.* = false, - else => {}, - } - if (!apply) return 0; - - switch (v) { - .@"addr=dot" => pf.addr = dotOf(pane), - .@"dot=addr" => { - clampAddr(pf, bodyOf(pane).len); - setDot(pane, pf.addr); - }, - .@"limit=addr" => { - clampAddr(pf, bodyOf(pane).len); - pf.limit = pf.addr; - }, - .clean => if (fileOf(pane)) |f| { - f.saved_revision = f.revision; - }, - .dirty => if (fileOf(pane)) |f| { - f.saved_revision = f.revision -% 1; - }, - .cleartag => { - pane.tag_tail_len = 0; - pane.tag_init = true; - }, - .del, .delete => p.removePane(id) catch return E.NOMEM, - .put => { - const serial = pane.serial; - if (fileOf(pane)) |f| { - if (f.output == null) { - p.perform(.{ .save_file = .{ .pane = @intCast(id) } }); - const current = p.paneBySerial(serial) orelse return E.NOENT; - if (dirtyOf(p.panes[current].?)) return E.IO; - } else _ = p.executeBuiltinLine(id, "Save"); - } else _ = p.executeBuiltinLine(id, "Save"); - }, - .get => if (fileOf(pane)) |f| { - if (panes.Output.fileTraits(f.output).saves) { - if (read(p, f.path)) |bytes| { - panes.File.pushUndo(p, pane); - panes.File.setContent(p, f, bytes); - f.saved_revision = f.revision; - } else |err| return switch (err) { - error.FileNotFound => E.NOENT, - else => E.IO, - }; - } - }, - .mark => { - pf.nomark = false; - panes.File.pushUndo(p, pane); - }, - .nomark => pf.nomark = true, - .noscroll => pf.noscroll = true, - .scroll => pf.noscroll = false, - .show => showOffset(pane, dotOf(pane).q0), - } - return 0; -} - -const PtyVerb = enum { winsize, sig, exec }; - -fn ptyDimension(word: []const u8) ?u16 { - if (word.len == 0 or word.len > 5) return null; - for (word) |c| if (c < '0' or c > '9') return null; - const n = std.fmt.parseInt(u16, word, 10) catch return null; - return if (n == 0) null else n; -} - -fn ptySignalNamed(word: []const u8) ?pardes.PtySignal { - if (std.mem.eql(u8, word, "INT")) return .int; - if (std.mem.eql(u8, word, "TERM")) return .term; - if (std.mem.eql(u8, word, "HUP")) return .hup; - if (std.mem.eql(u8, word, "QUIT")) return .quit; - if (std.mem.eql(u8, word, "KILL")) return .kill; - return null; -} - -fn writePtyCtl(p: *Pardes, req: Req, id: usize) Reply { - for ([2]bool{ false, true }) |apply| { - var it = std.mem.splitScalar(u8, req.data, '\n'); - while (it.next()) |raw| { - const line = std.mem.trim(u8, raw, " \t\r"); - if (line.len == 0) continue; - if (!ptyVerb(p, id, line, apply)) return Reply.fail(req.tag, E.INVAL); - } - } - return .{ .tag = req.tag, .written = @intCast(req.data.len) }; -} - -fn ptyVerb(p: *Pardes, id: usize, line: []const u8, apply: bool) bool { - const pane = p.panes[id] orelse return false; - var words = std.mem.tokenizeAny(u8, line, " \t"); - const v = std.meta.stringToEnum(PtyVerb, words.next() orelse return false) orelse return false; - switch (v) { - .winsize => { - const cols = ptyDimension(words.next() orelse return false) orelse return false; - const rows = ptyDimension(words.next() orelse return false) orelse return false; - if (words.next() != null) return false; - if (!apply) return true; - p.emit(.{ .resize_pty = .{ .pane = @intCast(id), .cols = cols, .rows = rows } }); - }, - .sig => { - const which = ptySignalNamed(words.next() orelse return false) orelse return false; - if (words.next() != null) return false; - if (!apply) return true; - p.emit(.{ .signal_pty = .{ .pane = @intCast(id), .sig = which } }); - }, - .exec => { - if (words.next() != null) return false; - if (pane.cwdSlice().len > pardes.effect_path_cap) return false; - if (!apply) return true; - p.emit(.{ .spawn = .{ .pane = @intCast(id), .cwd = .from(pane.cwdSlice()) } }); - }, - } - return true; -} - -fn writePtyData(p: *Pardes, req: Req, id: usize) Reply { - if (req.data.len == 0) return .{ .tag = req.tag, .written = 0 }; - const take = wholeUtf8(req.data); - p.emitWrite(id, req.data[0..take]); - return .{ .tag = req.tag, .written = @intCast(take) }; -} - -const EventRecord = struct { action: Action, q0: u32, q1: u32 }; - -const EventReader = struct { - data: []const u8, - i: usize = 0, - - fn next(er: *EventReader) ?EventRecord { - if (er.i >= er.data.len) return null; - var i = er.i; - if (i + 2 > er.data.len) return null; - i += 1; - const action = Action.fromChar(er.data[i]) orelse return null; - i += 1; - const q0 = scanNumber(er.data, &i) orelse return null; - const q1 = scanNumber(er.data, &i) orelse return null; - while (i < er.data.len and er.data[i] == ' ') i += 1; - if (i >= er.data.len or er.data[i] != '\n') return null; - er.i = i + 1; - return .{ .action = action, .q0 = q0, .q1 = q1 }; - } -}; - -fn scanNumber(data: []const u8, i: *usize) ?u32 { - while (i.* < data.len and data[i.*] == ' ') i.* += 1; - const s = i.*; - var n: u64 = 0; - while (i.* < data.len and data[i.*] >= '0' and data[i.*] <= '9') : (i.* += 1) - n = @min(n * 10 + (data[i.*] - '0'), std.math.maxInt(u32)); - if (i.* == s) return null; - return @intCast(n); -} - -fn writeEvent(p: *Pardes, req: Req, id: usize) Reply { - const pane0 = p.panes[id] orelse return Reply.fail(req.tag, E.NOENT); - const serial = pane0.serial; - { - const body = bodyOf(pane0); - const tag = tagOf(p, pane0); - var check: EventReader = .{ .data = req.data }; - while (check.next()) |r| { - switch (r.action) { - .body_look, .tag_look, .body_exec, .tag_exec => {}, - else => return Reply.fail(req.tag, E.INVAL), - } - const n = if (r.action.onTag()) tag.len else body.len; - if (r.q0 > r.q1 or r.q1 > n) return Reply.fail(req.tag, E.INVAL); - } - if (check.i != req.data.len) return Reply.fail(req.tag, E.INVAL); - } - var run: EventReader = .{ .data = req.data }; - while (run.next()) |r| { - const now = p.paneBySerial(serial) orelse break; - const pane = p.panes[now].?; - const whole = if (r.action.onTag()) tagOf(p, pane) else bodyOf(pane); - const lo = @min(@as(usize, r.q0), whole.len); - const hi = @max(lo, @min(@as(usize, r.q1), whole.len)); - const text = p.scratch.allocator().dupe(u8, whole[lo..hi]) catch continue; - switch (r.action) { - .body_exec, .tag_exec => _ = p.execute(now, text), - .body_look, .tag_look => p.lookAt(now, text), - else => unreachable, - } - } - return .{ .tag = req.tag, .written = @intCast(req.data.len) }; -} - -fn appendErrors(p: *Pardes, id: usize, text: []const u8) ?usize { - if (text.len == 0) return 0; - const pane = p.panes[id] orelse return null; - const dir = dirOf(pane); - for (p.panes, 0..) |slot, i| { - const q = slot orelse continue; - const qf = fileOf(q) orelse continue; - const o = qf.output orelse continue; - if (std.meta.activeTag(o.from) != .errors) continue; - if (!std.mem.eql(u8, std.fs.path.dirname(qf.path) orelse "", dir)) continue; - return spliceBody(p, i, q, qf.content.len, qf.content.len, text); - } - const free = p.freeSlot() orelse return null; - const content = p.gpa.dupe(u8, text) catch return null; - const np = panes.Output.open(p, free, dir, .errors, "", content) catch { - p.gpa.free(content); - return null; - }; - p.placeDoc(id, free, np); - return text.len; -} - -fn indexLen(p: *Pardes) u64 { - var n: u64 = 0; - for (p.panes) |slot| { - const pane = slot orelse continue; - n += ctl_fields + firstLine(tagOf(p, pane)).len + 1; - } - return n; -} - -fn bodyLen(p: *Pardes, pane: *Pane) u64 { - _ = p; - return bodyOf(pane).len; -} - -fn tagLen(p: *Pardes, pane: *Pane) u64 { - return tagOf(p, pane).len; -} - -test "filesystem inspection preserves pending and displayed Look hover" { - const delay = config.look_preview_delay_frames orelse return; - const gpa = std.testing.allocator; - const p = try withFile(gpa, "alpha beta gamma\n"); - defer p.deinit(); - var frame: std.heap.ArenaAllocator = .init(gpa); - defer frame.deinit(); - _ = try p.render(frame.allocator()); - const rect = p.rects[0]; - p.update(.{ .mouse = .{ - .button = .none, - .kind = .motion, - .col = rect.x + config.GUTTER + config.PREFIX_W + 7, - .row = if (p.settings.tag_bottom) rect.y else rect.y + pardes.BOX_H, - } }); - try testing.expect(p.look_hover_wait != null); - const body = Node.of(serialOf(p), .body); - const screen = @intFromEnum(SelfFile.screen); - for (0..2) |phase| { - if (phase == 1) { - for (0..delay) |_| p.update(.tick); - try testing.expect(p.look_hover_preview != null); - } - const waiting = p.look_hover_wait; - const preview = p.look_hover_preview; - const requests = [_]Req{ - .{ .tag = 1, .op = .lookup, .node = @intFromEnum(SelfFile.root), .data = "screen" }, - .{ .tag = 1, .op = .lookup, .node = @intFromEnum(SelfFile.new), .data = ".." }, - .{ .tag = 1, .op = .lookup, .node = @intFromEnum(SelfFile.new), .data = "body" }, - .{ .tag = 2, .op = .getattr, .node = body }, - .{ .tag = 3, .op = .open, .node = body }, - .{ .tag = 4, .op = .read, .node = body, .size = 5 }, - .{ .tag = 5, .op = .release, .node = body, .handle = 1 }, - .{ .tag = 6, .op = .readdir, .node = @intFromEnum(SelfFile.root), .size = 4096 }, - .{ .tag = 7, .op = .open, .node = screen }, - .{ .tag = 8, .op = .read, .node = screen, .handle = 1, .size = 32 }, - .{ .tag = 9, .op = .release, .node = screen, .handle = 1 }, - }; - for (requests) |req| { - const answer = call(p, req); - try testing.expectEqual(Status.ok, answer.reply.status); - try testing.expect(std.meta.eql(waiting, p.look_hover_wait)); - try testing.expect(std.meta.eql(preview, p.look_hover_preview)); - try testing.expect(p.raw_hover_intent); - } - } - try testing.expectEqual(Status.ok, wr(p, body, "changed").reply.status); - try testing.expect(p.look_hover_wait == null); - try testing.expect(p.look_hover_preview == null); - try testing.expect(!p.raw_hover_intent); -} - -test "filesystem pane creation and truncation cancel Look hover" { - const requests = [_]Req{ - .{ .tag = 2, .op = .open, .node = factory_base + @intFromEnum(PaneFile.body) }, - .{ .tag = 3, .op = .setattr, .node = 0, .truncate = true }, - }; - for (requests) |request| { - const p = try withFile(testing.allocator, "word\n"); - defer p.deinit(); - p.look_hover_wait = .{ .col = 1, .row = 1, .pane = 0, .serial = serialOf(p) }; - p.raw_hover_intent = true; - var req = request; - if (req.op == .setattr) req.node = Node.of(serialOf(p), .body); - try testing.expectEqual(Status.ok, call(p, req).reply.status); - try testing.expect(p.look_hover_wait == null); - try testing.expect(p.look_hover_preview == null); - try testing.expect(!p.raw_hover_intent); - } -} - -test "terminal body handles keep one history snapshot across fragmented reads" { - const gpa = std.testing.allocator; - const p = try withTerm(gpa); - defer p.deinit(); - const node = Node.of(serialOf(p), .body); - p.update(.{ .output = .{ .pane = 0, .bytes = "old caf\xc3\xa9\r\nold tail" } }); - while (p.nextEffect()) |_| {} - const original = try panes.Terminal.screenTextAlloc(p.panes[0].?, gpa); - defer gpa.free(original); - const opened = call(p, .{ .tag = 1, .op = .open, .node = node }); - try testing.expectEqual(Status.ok, opened.reply.status); - const first = call(p, .{ .tag = 2, .op = .read, .node = node, .handle = opened.reply.handle, .size = 3 }); - try testing.expectEqualStrings(original[0..3], first.bytes); - p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[3J\x1b[2J\x1b[Hnew output" } }); - while (p.nextEffect()) |_| {} - var offset: usize = 3; - while (offset < original.len) { - const part = call(p, .{ .tag = 3, .op = .read, .node = node, .handle = opened.reply.handle, .off = offset, .size = 3 }); - try testing.expectEqualStrings(original[offset..][0..@min(3, original.len - offset)], part.bytes); - offset += part.bytes.len; - } - try testing.expectEqualStrings("", call(p, .{ .tag = 4, .op = .read, .node = node, .handle = opened.reply.handle, .off = original.len, .size = 3 }).bytes); - _ = call(p, .{ .tag = 5, .op = .release, .node = node, .handle = opened.reply.handle }); - const newer = call(p, .{ .tag = 6, .op = .open, .node = node }); - try testing.expectEqualStrings("new output", call(p, .{ .tag = 7, .op = .read, .node = node, .handle = newer.reply.handle, .size = 32 }).bytes); - _ = call(p, .{ .tag = 8, .op = .release, .node = node, .handle = newer.reply.handle }); -} - -test "an empty terminal body snapshot stays empty while output continues" { - const p = try withTerm(std.testing.allocator); - defer p.deinit(); - const node = Node.of(serialOf(p), .body); - const opened = call(p, .{ .tag = 1, .op = .open, .node = node }); - try testing.expectEqualStrings("", call(p, .{ .tag = 2, .op = .read, .node = node, .handle = opened.reply.handle, .size = 32 }).bytes); - try testing.expect(p.fs.snapshots[opened.reply.handle - 1].bytes != null); - p.update(.{ .output = .{ .pane = 0, .bytes = "new output" } }); - while (p.nextEffect()) |_| {} - try testing.expectEqualStrings("", call(p, .{ .tag = 3, .op = .read, .node = node, .handle = opened.reply.handle, .size = 32 }).bytes); - _ = call(p, .{ .tag = 4, .op = .release, .node = node, .handle = opened.reply.handle }); - const newer = call(p, .{ .tag = 5, .op = .open, .node = node }); - try testing.expectEqualStrings("new output", call(p, .{ .tag = 6, .op = .read, .node = node, .handle = newer.reply.handle, .size = 32 }).bytes); - _ = call(p, .{ .tag = 7, .op = .release, .node = node, .handle = newer.reply.handle }); -} - -test "terminal body snapshots are lazy bounded and released after the pane closes" { - const gpa = std.testing.allocator; - const p = try withTerm(gpa); - defer p.deinit(); - const node = Node.of(serialOf(p), .body); - var handles: [32]u32 = undefined; - for (&handles) |*opened_handle| { - const opened = call(p, .{ .tag = 1, .op = .open, .node = node }); - try testing.expectEqual(Status.ok, opened.reply.status); - opened_handle.* = opened.reply.handle; - } - for (p.fs.snapshots) |snapshot| { - try testing.expectEqual(node, snapshot.node); - try testing.expect(snapshot.bytes == null); - } - try testing.expectEqual(E.NFILE, call(p, .{ .tag = 2, .op = .open, .node = node }).errno()); - const scratch = call(p, .{ .tag = 2, .op = .open, .node = factory_base + @intFromEnum(PaneFile.body) }); - try testing.expectEqual(Status.ok, scratch.reply.status); - const scratch_id = p.paneBySerial(Node.target(scratch.reply.attr.node).?.pane.serial).?; - try testing.expect(p.panes[scratch_id].?.file != null); - _ = call(p, .{ .tag = 2, .op = .release, .node = scratch.reply.attr.node, .handle = scratch.reply.handle }); - p.update(.{ .output = .{ .pane = 0, .bytes = "latest output" } }); - while (p.nextEffect()) |_| {} - var failing = std.testing.FailingAllocator.init(gpa, .{ .fail_index = 0 }); - p.gpa = failing.allocator(); - const failed = call(p, .{ .tag = 3, .op = .read, .node = node, .handle = handles[0], .size = 32 }); - p.gpa = gpa; - try testing.expectEqual(E.NOMEM, failed.errno()); - try testing.expect(p.fs.snapshots[handles[0] - 1].bytes == null); - const first = call(p, .{ .tag = 4, .op = .read, .node = node, .handle = handles[0], .size = 32 }); - try testing.expectEqualStrings("latest output", first.bytes); - const saved = p.fs.snapshots[handles[0] - 1].bytes.?; - failing = std.testing.FailingAllocator.init(gpa, .{ .fail_index = 0 }); - p.gpa = failing.allocator(); - const second = call(p, .{ .tag = 5, .op = .read, .node = node, .handle = handles[0], .off = 7, .size = 32 }); - p.gpa = gpa; - try testing.expectEqualStrings("output", second.bytes); - try testing.expect(!failing.has_induced_failure); - try testing.expectEqual(saved.ptr, p.fs.snapshots[handles[0] - 1].bytes.?.ptr); - const screen = @intFromEnum(SelfFile.screen); - try testing.expectEqual(E.INVAL, call(p, .{ .tag = 6, .op = .read, .node = screen, .handle = handles[0], .size = 32 }).errno()); - _ = call(p, .{ .tag = 7, .op = .release, .node = screen, .handle = handles[0] }); - try testing.expectEqual(node, p.fs.snapshots[handles[0] - 1].node); - try p.removePane(0); - for (handles) |opened_handle| _ = call(p, .{ .tag = 8, .op = .release, .node = node, .handle = opened_handle }); - for (p.fs.snapshots) |snapshot| { - try testing.expectEqual(@as(u64, 0), snapshot.node); - try testing.expect(snapshot.bytes == null); - } -} - -test "screen snapshots preserve rendered cells and styles until their handle is released" { - const gpa = std.testing.allocator; - const p = try withFile(gpa, "const value = 1;\n"); - defer p.deinit(); - const node = @intFromEnum(SelfFile.screen); - const opened = call(p, .{ .tag = 1, .op = .open, .node = node }); - try testing.expectEqual(Status.ok, opened.reply.status); - const snapshot = p.fs.snapshots[opened.reply.handle - 1].bytes.?; - const original = try gpa.dupe(u8, snapshot); - defer gpa.free(original); - const parsed = try std.json.parseFromSlice(std.json.Value, gpa, original, .{}); - defer parsed.deinit(); - const data = parsed.value.object; - try testing.expectEqual(@as(i64, p.screen_w), data.get("cols").?.integer); - try testing.expectEqual(@as(i64, p.screen_h), data.get("rows").?.integer); - try testing.expectEqual(@as(usize, p.screen_w) * p.screen_h, data.get("cells").?.array.items.len); - try testing.expect(data.get("styles").?.array.items.len > 0); - _ = wr(p, Node.of(serialOf(p), .body), "changed\n"); - const newer = call(p, .{ .tag = 2, .op = .open, .node = node }); - try testing.expectEqual(Status.ok, newer.reply.status); - try testing.expect(!std.mem.eql(u8, original, p.fs.snapshots[newer.reply.handle - 1].bytes.?)); - var off: usize = 0; - while (off < original.len) { - const result = call(p, .{ .tag = 3, .op = .read, .node = node, .handle = opened.reply.handle, .off = off, .size = 13 }); - try testing.expectEqual(Status.ok, result.reply.status); - try testing.expectEqualSlices(u8, original[off..][0..@min(13, original.len - off)], result.bytes); - off += result.bytes.len; - } - _ = call(p, .{ .tag = 4, .op = .release, .node = node, .handle = opened.reply.handle }); - _ = call(p, .{ .tag = 5, .op = .release, .node = node, .handle = newer.reply.handle }); - for (p.fs.snapshots) |slot| try testing.expect(slot.node == 0); -} - -test "screen inspection preserves acknowledged presentation and the next real frame" { - const gpa = testing.allocator; - for (std.enums.values(pardes.layout.Transition)) |transition| { - errdefer std.debug.print("screen inspection during {s}\n", .{@tagName(transition)}); - const control = try withFile(gpa, "const value = 1;\n"); - defer control.deinit(); - const inspected = try withFile(gpa, "const value = 1;\n"); - defer inspected.deinit(); - var arena: std.heap.ArenaAllocator = .init(gpa); - defer arena.deinit(); - for ([_]*Pardes{ control, inspected }) |p| { - p.settings.panel_transition = .off; - p.update(.tick); - p.acknowledgePanelPresentation((try p.render(arena.allocator())).panelTracks()); - p.settings.panel_transition = transition; - } - for (0..4) |phase| { - for ([_]*Pardes{ control, inspected }) |p| switch (phase) { - 0 => {}, - 1 => p.update(.{ .command = "New" }), - 2 => { - p.update(.tick); - try testing.expectEqual(Status.ok, wr(p, Node.of(p.panes[p.active].?.serial, .body), "changed cells\n").reply.status); - }, - 3 => { - for (0..transition.frames() + 1) |_| p.update(.tick); - p.acknowledgePanelPresentation((try p.render(arena.allocator())).panelTracks()); - p.update(.{ .command = "Del" }); - }, - else => unreachable, - }; - const screen = @intFromEnum(SelfFile.screen); - for (0..2) |_| { - const opened = call(inspected, .{ .tag = 1, .op = .open, .node = screen }); - try testing.expectEqual(Status.ok, opened.reply.status); - const captured = call(inspected, .{ .tag = 2, .op = .read, .node = screen, .handle = opened.reply.handle, .size = 32 }); - try testing.expectEqual(Status.ok, captured.reply.status); - try testing.expect(captured.bytes.len > 0); - try testing.expectEqual(Status.ok, call(inspected, .{ - .tag = 3, - .op = .release, - .node = screen, - .handle = opened.reply.handle, - }).reply.status); - } - const a = &control.presentation; - const b = &inspected.presentation; - try testing.expectEqualDeep(a.shown, b.shown); - try testing.expectEqualDeep(a.shown_tracks, b.shown_tracks); - try testing.expectEqualDeep(a.shown_closing[0..a.shown_closing_len], b.shown_closing[0..b.shown_closing_len]); - try testing.expectEqual(a.pending, b.pending); - try testing.expectEqual(a.acknowledged, b.acknowledged); - try testing.expectEqual(a.previous_valid, b.previous_valid); - try testing.expectEqual(a.previous_cols, b.previous_cols); - try testing.expectEqual(a.previous_rows, b.previous_rows); - try testing.expectEqualDeep(a.previous_layout, b.previous_layout); - try testing.expectEqual(a.previous_cells.len, b.previous_cells.len); - for (a.previous_cells, b.previous_cells) |*expected, *actual| - try testing.expect(expected.visuallyEqual(actual)); - - const expected = try control.render(arena.allocator()); - const actual = try inspected.render(arena.allocator()); - try testing.expectEqual(expected.cols, actual.cols); - try testing.expectEqual(expected.rows, actual.rows); - try testing.expectEqualDeep(expected.cursor, actual.cursor); - try testing.expectEqualDeep(expected.panelTracks(), actual.panelTracks()); - try testing.expectEqualDeep(expected.cell_diffs, actual.cell_diffs); - try testing.expectEqual(expected.previous_cells.len, actual.previous_cells.len); - try testing.expectEqual(expected.cells.len, actual.cells.len); - try testing.expectEqual(@as(usize, 0), expected.nimages); - try testing.expectEqual(@as(usize, 0), actual.nimages); - for (expected.cells, actual.cells) |*left, *right| try testing.expect(left.visuallyEqual(right)); - for (expected.previous_cells, actual.previous_cells) |*left, *right| try testing.expect(left.visuallyEqual(right)); - if (phase == 1 and transition != .off) try testing.expect(expected.panelTracks().len > 0); - if (phase == 1 and transition.needsPreviousGrid()) try testing.expect(expected.hasPanelDiff()); - if (phase == 3 and transition == .vertical) try testing.expect(a.closing_len > 0); - control.acknowledgePanelPresentation(expected.panelTracks()); - inspected.acknowledgePanelPresentation(actual.panelTracks()); - try testing.expectEqualDeep(a.shown, b.shown); - try testing.expectEqualDeep(a.previous_layout, b.previous_layout); - _ = arena.reset(.retain_capacity); - } - } -} - -const testing = std.testing; - -const Answer = struct { - reply: Reply = .{ .tag = 0, .status = .err, .errno = E.IO }, - bytes: []const u8 = "", - saved: bool = false, - watch: ?bool = null, - pty_buf: [256]u8 = undefined, - pty_len: usize = 0, - winsize: ?struct { cols: u16, rows: u16 } = null, - signal: ?pardes.PtySignal = null, - spawned: bool = false, - - fn pty(a: *const Answer) []const u8 { - return a.pty_buf[0..a.pty_len]; - } - - fn errno(a: Answer) u16 { - return if (a.reply.status == .err) a.reply.errno else 0; - } -}; - -fn call(p: *Pardes, req: Req) Answer { - p.update(.{ .fs_req = req }); - var ans: Answer = .{}; - while (p.nextEffect()) |e| switch (e) { - .fs_reply => |r| { - ans.reply = r; - ans.bytes = p.fsPayload(r); - }, - .save_file, .save_text => ans.saved = true, - .watch => |w| ans.watch = w.on, - .write => |w| { - const b = w.bytes.slice(); - const n = @min(b.len, ans.pty_buf.len - ans.pty_len); - @memcpy(ans.pty_buf[ans.pty_len..][0..n], b[0..n]); - ans.pty_len += n; - }, - .resize_pty => |r| ans.winsize = .{ .cols = r.cols, .rows = r.rows }, - .signal_pty => |s| ans.signal = s.sig, - .spawn => ans.spawned = true, - else => {}, - }; - return ans; -} - -fn rd(p: *Pardes, node: u64, off: u64, size: u32) Answer { - return call(p, .{ .tag = 1, .op = .read, .node = node, .off = off, .size = size }); -} - -fn wr(p: *Pardes, node: u64, data: []const u8) Answer { - return call(p, .{ .tag = 2, .op = .write, .node = node, .data = data }); -} - -fn rdir(p: *Pardes, node: u64, skip: u64) Answer { - return call(p, .{ .tag = 4, .op = .readdir, .node = node, .off = skip, .size = 4096 }); -} - -fn look_up(p: *Pardes, dir: u64, name: []const u8) Answer { - return call(p, .{ .tag = 3, .op = .lookup, .node = dir, .data = name }); -} - -fn withFile(gpa: std.mem.Allocator, text: []const u8) !*Pardes { - const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24 }); - errdefer p.deinit(); - while (p.nextEffect()) |_| {} - _ = try p.setTestFile(text); - while (p.nextEffect()) |_| {} - return p; -} - -fn withTerm(gpa: std.mem.Allocator) !*Pardes { - const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24 }); - errdefer p.deinit(); - while (p.nextEffect()) |_| {} - std.debug.assert(p.panes[0].?.isTerminal()); - return p; -} - -fn serialOf(p: *Pardes) u32 { - return p.panes[0].?.serial; -} - -const Dirent = struct { node: u64, dir: bool, name: []const u8 }; - -fn dirents(bytes: []const u8, out: []Dirent) []Dirent { - var n: usize = 0; - var i: usize = 0; - while (i + 10 <= bytes.len and n < out.len) { - const node = std.mem.readInt(u64, bytes[i..][0..8], .little); - const kind = bytes[i + 8]; - const len = bytes[i + 9]; - i += 10; - if (i + len > bytes.len) break; - out[n] = .{ .node = node, .dir = kind == 1, .name = bytes[i .. i + len] }; - i += len; - n += 1; - } - return out[0..n]; -} - -fn nameAt(list: []const Dirent, want: []const u8) ?Dirent { - for (list) |d| if (std.mem.eql(u8, d.name, want)) return d; - return null; -} - -test "listener addresses are readable canonical dials with bounded partial reads" { - const gpa = testing.allocator; - const p = try Pardes.init(gpa, .{ .tty_only = true }); - defer p.deinit(); - p.fs.socket_path = "/tmp/a socket.sock"; - p.fs.tcp_address = .{ .ip4 = .loopback(5640) }; - p.fs.quic_address = .{ .ip6 = .loopback(5641) }; - const expected = "unix!/tmp/a socket.sock\ntcp!127.0.0.1!5640\nquic!::1!5641\n"; - for ([_][]const u8{ "/virtual/listeners", "/n/self/listeners" }) |path| { - const bytes = try read(p, path); - defer gpa.free(bytes); - try testing.expectEqualStrings(expected, bytes); - try testing.expectError(error.ReadOnlyFilesystem, write(p, path, "")); - } - const node = @intFromEnum(SelfFile.listeners); - var off: usize = 0; - while (off < expected.len) { - const part = rd(p, node, off, 3); - try testing.expectEqual(Status.ok, part.reply.status); - try testing.expectEqualStrings(expected[off..][0..@min(3, expected.len - off)], part.bytes); - off += part.bytes.len; - } - try testing.expectEqual(@as(usize, 0), rd(p, node, off, 3).bytes.len); -} - -test "readdir lists the root, a pane directory, and new/ without creating anything" { - const gpa = testing.allocator; - const p = try withFile(gpa, "hello\n"); - defer p.deinit(); - const serial = serialOf(p); - var buf: [32]Dirent = undefined; - - const root = rdir(p, @intFromEnum(SelfFile.root), 0); - try testing.expectEqual(Status.ok, root.reply.status); - const top = dirents(root.bytes, &buf); - try testing.expect(top.len >= 5); - try testing.expectEqualStrings("index", top[0].name); - try testing.expectEqualStrings("cons", top[1].name); - try testing.expectEqualStrings("new", top[2].name); - try testing.expect(top[2].dir and !top[0].dir); - try testing.expectEqualStrings("pane", top[3].name); - try testing.expect(top[3].dir); - try testing.expectEqual(namespace_panes, top[3].node); - var idbuf: [16]u8 = undefined; - try testing.expect(nameAt(top, try std.fmt.bufPrint(&idbuf, "{d}", .{serial})) == null); - try testing.expect(nameAt(top, "src") != null); - - const rest = rdir(p, @intFromEnum(SelfFile.root), 3); - try testing.expectEqual(top.len - 3, dirents(rest.bytes, &buf).len); - const eof = rdir(p, @intFromEnum(SelfFile.root), 99); - try testing.expectEqual(Status.ok, eof.reply.status); - try testing.expectEqual(@as(usize, 0), eof.bytes.len); - - const dir = rdir(p, Node.of(serial, .dir), 0); - const files = dirents(dir.bytes, &buf); - try testing.expectEqual(@as(usize, 10), files.len); - try testing.expect(nameAt(files, "addr") != null); - try testing.expect(nameAt(files, "xdata") != null); - try testing.expect(nameAt(files, ".") == null); - try testing.expectEqual(Node.of(serial, .body), nameAt(files, "body").?.node); - - const before = p.next_serial; - const new = rdir(p, @intFromEnum(SelfFile.new), 0); - try testing.expectEqual(Status.ok, new.reply.status); - const factories = dirents(new.bytes, &buf); - try testing.expectEqual(@as(usize, 11), factories.len); - try testing.expect(nameAt(factories, "README") != null); - for (factories) |entry| { - const inspected = look_up(p, @intFromEnum(SelfFile.new), entry.name); - try testing.expectEqual(Status.ok, inspected.reply.status); - try testing.expectEqual(entry.node, inspected.reply.attr.node); - try testing.expectEqual(Status.ok, call(p, .{ .tag = 1, .op = .getattr, .node = entry.node }).reply.status); - } - try testing.expectEqual(before, p.next_serial); - - try testing.expectEqual(E.NOTDIR, rdir(p, Node.of(serial, .body), 0).errno()); -} - -test "lookup resolves top files, pane serials and pane files" { - const gpa = testing.allocator; - const p = try withFile(gpa, "hello\n"); - defer p.deinit(); - const serial = serialOf(p); - const root = @intFromEnum(SelfFile.root); - - try testing.expectEqual(@as(u64, @intFromEnum(SelfFile.index)), look_up(p, root, "index").reply.attr.node); - try testing.expect(look_up(p, root, "new").reply.attr.dir); - try testing.expectEqual(E.NOENT, look_up(p, root, "nosuchthing").errno()); - - var idbuf: [16]u8 = undefined; - const serial_name = try std.fmt.bufPrint(&idbuf, "{d}", .{serial}); - try testing.expectEqual(E.NOENT, look_up(p, root, serial_name).errno()); - const dir = look_up(p, namespace_panes, serial_name); - try testing.expectEqual(Node.of(serial, .dir), dir.reply.attr.node); - try testing.expect(dir.reply.attr.dir); - try testing.expectEqual(E.NOENT, look_up(p, namespace_panes, "99999").errno()); - - const body = look_up(p, Node.of(serial, .dir), "body"); - try testing.expectEqual(Node.of(serial, .body), body.reply.attr.node); - const stat = call(p, .{ .tag = 4, .op = .getattr, .node = Node.of(serial, .body) }); - try testing.expectEqual(body.reply.attr.size, stat.reply.attr.size); - try testing.expectEqual(@as(u64, "hello\n".len), stat.reply.attr.size); - try testing.expectEqual(E.NOENT, look_up(p, Node.of(serial, .dir), "editout").errno()); - try testing.expectEqual(E.NOTDIR, look_up(p, Node.of(serial, .body), "x").errno()); -} - -test "new/ lookup is inert and each open creates a distinct pane" { - const gpa = testing.allocator; - const p = try withFile(gpa, "first\n"); - defer p.deinit(); - const before = serialOf(p); - - try testing.expectEqual(E.NOENT, look_up(p, @intFromEnum(SelfFile.new), "bogus").errno()); - try testing.expectEqual(before, p.next_serial); - - const a = look_up(p, @intFromEnum(SelfFile.new), "body"); - try testing.expectEqual(Status.ok, a.reply.status); - try testing.expectEqual(before, p.next_serial); - const opened = call(p, .{ .tag = 1, .op = .open, .node = a.reply.attr.node }); - try testing.expectEqual(Status.ok, opened.reply.status); - const made: Node = @bitCast(opened.reply.attr.node); - try testing.expect(made.serial != before); - try testing.expectEqual(@intFromEnum(PaneFile.body), made.file); - - _ = wr(p, opened.reply.attr.node, "hi"); - const second = call(p, .{ .tag = 2, .op = .open, .node = a.reply.attr.node }); - try testing.expectEqual(Status.ok, second.reply.status); - try testing.expect(second.reply.attr.node != opened.reply.attr.node); - const id = p.paneBySerial(@intCast(made.serial)).?; - try testing.expectEqualStrings("hi", p.panes[id].?.file.?.content); -} - -test "index prints winctlprint's five fields then the tag" { - const gpa = testing.allocator; - const p = try withFile(gpa, "hello\nthere\n"); - defer p.deinit(); - const pane = p.panes[0].?; - - const a = rd(p, @intFromEnum(SelfFile.index), 0, 4096); - try testing.expectEqual(Status.ok, a.reply.status); - var got: [512]u8 = undefined; - @memcpy(got[0..a.bytes.len], a.bytes); - const line = got[0..a.bytes.len]; - - const tag = try gpa.dupe(u8, tagOf(p, pane)); - defer gpa.free(tag); - var want: std.ArrayList(u8) = .empty; - defer want.deinit(gpa); - try want.print(gpa, "{d:>11} {d:>11} {d:>11} {d:>11} {d:>11} {s}\n", .{ - pane.serial, tag.len, @as(usize, "hello\nthere\n".len), 0, 0, firstLine(tag), - }); - try testing.expectEqualStrings(want.items, line); - try testing.expectEqual(@as(usize, 60), std.mem.indexOf(u8, line, firstLine(tag)).?); - - const mid = rd(p, @intFromEnum(SelfFile.index), 60, 5); - try testing.expectEqualStrings(firstLine(tag)[0..5], mid.bytes); - - pane.file.?.saved_revision = pane.file.?.revision -% 1; - const dirty = rd(p, @intFromEnum(SelfFile.index), 48, 12); - try testing.expectEqualStrings(" 1 ", dirty.bytes); -} - -test "ctl read is index's five fields plus width in cells, font and tab width" { - const gpa = testing.allocator; - const p = try withFile(gpa, "x\n"); - defer p.deinit(); - const pane = p.panes[0].?; - - const a = rd(p, Node.of(pane.serial, .ctl), 0, 4096); - try testing.expectEqual(Status.ok, a.reply.status); - var want: std.ArrayList(u8) = .empty; - defer want.deinit(gpa); - try want.print(gpa, "{d:>11} {d:>11} {d:>11} {d:>11} {d:>11} {d:>11} {s} {d:>11} ", .{ - pane.serial, tagOf(p, pane).len, @as(usize, 2), 0, 0, pane.cols, "default", config.tab_width, - }); - try testing.expectEqualStrings(want.items, a.bytes); - - var quoted: std.ArrayList(u8) = .empty; - defer quoted.deinit(gpa); - stageQuoted("ed, gpa, "DejaVu Sans Mono"); - try testing.expectEqualStrings("'DejaVu Sans Mono'", quoted.items); - quoted.clearRetainingCapacity(); - stageQuoted("ed, gpa, "it's"); - try testing.expectEqualStrings("'it''s'", quoted.items); -} - -test "body reads at any offset and writes append" { - const gpa = testing.allocator; - const p = try withFile(gpa, "one\ntwo\n"); - defer p.deinit(); - const serial = serialOf(p); - const body = Node.of(serial, .body); - - try testing.expectEqualStrings("one\ntwo\n", rd(p, body, 0, 100).bytes); - try testing.expectEqualStrings("two\n", rd(p, body, 4, 100).bytes); - try testing.expectEqualStrings("wo", rd(p, body, 5, 2).bytes); - try testing.expectEqualStrings("", rd(p, body, 999, 2).bytes); - try testing.expect(rd(p, body, 0, 100).bytes.ptr == p.panes[0].?.file.?.content.ptr); - - const w = call(p, .{ .tag = 5, .op = .write, .node = body, .off = 0, .data = "three\n" }); - try testing.expectEqual(@as(u32, 6), w.reply.written); - try testing.expectEqualStrings("one\ntwo\nthree\n", p.panes[0].?.file.?.content); - - const short = wr(p, body, "a\xC3"); - try testing.expectEqual(@as(u32, 1), short.reply.written); - try testing.expectEqualStrings("one\ntwo\nthree\na", p.panes[0].?.file.?.content); -} - -test "a body write to a terminal pane types at its shell" { - const gpa = testing.allocator; - const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 40, .rows = 10 }); - defer p.deinit(); - while (p.nextEffect()) |_| {} - const pane = p.panes[0].?; - try testing.expect(pane.isTerminal()); - - const a = wr(p, Node.of(pane.serial, .body), "ls -l\r"); - try testing.expectEqual(@as(u32, 6), a.reply.written); - try testing.expectEqualStrings("ls -l\r", a.pty()); - - const r = rd(p, Node.of(pane.serial, .body), 0, 64); - try testing.expectEqual(Status.ok, r.reply.status); -} - -test "tag reads the whole tag and writes append to the editable tail" { - const gpa = testing.allocator; - const p = try withFile(gpa, "x\n"); - defer p.deinit(); - const pane = p.panes[0].?; - const node = Node.of(pane.serial, .tag); - - const whole = rd(p, node, 0, 4096); - try testing.expect(std.mem.startsWith(u8, whole.bytes, "/test.txt")); - try testing.expect(std.mem.indexOf(u8, whole.bytes, "Del") != null); - - const before = rd(p, node, 0, 4096).bytes.len; - const w = wr(p, node, " Mine"); - try testing.expectEqual(@as(u32, 5), w.reply.written); - try testing.expect(std.mem.endsWith(u8, pane.tag_tail[0..pane.tag_tail_len], " Mine")); - const after = rd(p, node, 0, 4096); - try testing.expectEqual(before + 5, after.bytes.len); - try testing.expect(std.mem.endsWith(u8, after.bytes, " Mine")); - - pane.tag_tail_len = pane.tag_tail.len; - try testing.expectEqual(E.NOSPC, wr(p, node, "x").errno()); -} - -test "the address language, form by form" { - const gpa = testing.allocator; - const p = try withFile(gpa, "one\ntwo\nthree\n"); - defer p.deinit(); - const serial = serialOf(p); - const addr = Node.of(serial, .addr); - - const Case = struct { expr: []const u8, q0: u32, q1: u32 }; - for ([_]Case{ - .{ .expr = "#0", .q0 = 0, .q1 = 0 }, - .{ .expr = "#5", .q0 = 5, .q1 = 5 }, - .{ .expr = "0", .q0 = 0, .q1 = 0 }, - .{ .expr = "1", .q0 = 0, .q1 = 4 }, - .{ .expr = "2", .q0 = 4, .q1 = 8 }, - .{ .expr = "$", .q0 = 14, .q1 = 14 }, - .{ .expr = ",", .q0 = 0, .q1 = 14 }, - .{ .expr = "1,2", .q0 = 0, .q1 = 8 }, - .{ .expr = "#1,#4", .q0 = 1, .q1 = 4 }, - .{ .expr = "2+1", .q0 = 8, .q1 = 14 }, - .{ .expr = "$-1", .q0 = 8, .q1 = 14 }, - .{ .expr = "/two/", .q0 = 4, .q1 = 7 }, - .{ .expr = "/t.o/", .q0 = 4, .q1 = 7 }, - .{ .expr = "1\n", .q0 = 0, .q1 = 4 }, - }) |c| { - _ = wr(p, addr, "#0"); - const w = wr(p, addr, c.expr); - try testing.expectEqual(Status.ok, w.reply.status); - const got = rd(p, addr, 0, 64); - var want: [32]u8 = undefined; - try testing.expectEqualStrings( - try std.fmt.bufPrint(&want, "{d:>11} {d:>11} ", .{ c.q0, c.q1 }), - got.bytes, - ); - } - - _ = wr(p, addr, "1"); - _ = wr(p, addr, "."); - try testing.expectEqual(@as(u32, 0), p.fs.panes[0].addr.q0); - try testing.expectEqual(@as(u32, 4), p.fs.panes[0].addr.q1); - - _ = wr(p, addr, "$"); - _ = wr(p, addr, "?o?"); - try testing.expectEqual(@as(u32, 6), p.fs.panes[0].addr.q0); // the `o` in "two" - try testing.expectEqual(@as(u32, 7), p.fs.panes[0].addr.q1); - - _ = wr(p, addr, "1"); - _ = wr(p, Node.of(serial, .ctl), "limit=addr\n"); - _ = wr(p, addr, "#0"); - try testing.expectEqual(E.INVAL, wr(p, addr, "/three/").errno()); - _ = wr(p, Node.of(serial, .ctl), "clean\n"); - _ = call(p, .{ .tag = 6, .op = .open, .node = Node.of(serial, .ctl) }); - try testing.expect(p.fs.panes[0].limit == null); - _ = wr(p, addr, "#0"); - try testing.expectEqual(Status.ok, wr(p, addr, "/three/").reply.status); - - for ([_][]const u8{ "zzz", "#", "//", "/nomatch/", "1 2", "99", "/a\\" }) |bad| { - _ = wr(p, addr, "#0"); - try testing.expectEqual(E.INVAL, wr(p, addr, bad).errno()); - } - - const nested = "," ** 4096; - _ = wr(p, addr, "#0"); - try testing.expectEqual(E.INVAL, wr(p, addr, nested).errno()); -} - -test "data and xdata read from addr, move it, and write through it" { - const gpa = testing.allocator; - const p = try withFile(gpa, "one\ntwo\n"); - defer p.deinit(); - const serial = serialOf(p); - const addr = Node.of(serial, .addr); - const data = Node.of(serial, .data); - const xdata = Node.of(serial, .xdata); - - _ = wr(p, addr, "#0"); - try testing.expectEqualStrings("one", rd(p, data, 0, 3).bytes); - try testing.expectEqual(@as(u32, 3), p.fs.panes[0].addr.q0); - try testing.expectEqual(@as(u32, 3), p.fs.panes[0].addr.q1); - - _ = wr(p, addr, "1"); - try testing.expectEqualStrings("one\n", rd(p, xdata, 0, 100).bytes); - _ = wr(p, addr, "1"); - try testing.expectEqualStrings("one\ntwo\n", rd(p, data, 0, 100).bytes); - - _ = wr(p, addr, "1"); - const w = wr(p, data, "ONE\n"); - try testing.expectEqual(@as(u32, 4), w.reply.written); - try testing.expectEqualStrings("ONE\ntwo\n", p.panes[0].?.file.?.content); - try testing.expectEqual(@as(u32, 4), p.fs.panes[0].addr.q0); -} - -test "data never splits a grapheme, in either direction" { - const gpa = testing.allocator; - const p = try withFile(gpa, "\u{00e9}x\n"); - defer p.deinit(); - const serial = serialOf(p); - _ = wr(p, Node.of(serial, .addr), "#0"); - try testing.expectEqualStrings("", rd(p, Node.of(serial, .data), 0, 1).bytes); - _ = wr(p, Node.of(serial, .addr), "#0"); - try testing.expectEqualStrings("\u{00e9}", rd(p, Node.of(serial, .data), 0, 2).bytes); - - _ = wr(p, Node.of(serial, .addr), "#0"); - try testing.expectEqual(@as(u32, 1), wr(p, Node.of(serial, .data), "a\xC3").reply.written); -} - -test "rdsel reads the selection and wrsel replaces it" { - const gpa = testing.allocator; - const p = try withFile(gpa, "one\ntwo\n"); - defer p.deinit(); - const serial = serialOf(p); - const ctl = Node.of(serial, .ctl); - - _ = wr(p, Node.of(serial, .addr), "#0,#3"); - try testing.expectEqual(Status.ok, wr(p, ctl, "dot=addr\n").reply.status); - try testing.expectEqualStrings("one", rd(p, Node.of(serial, .rdsel), 0, 100).bytes); - - _ = wr(p, ctl, "addr=dot\n"); - try testing.expectEqual(@as(u32, 0), p.fs.panes[0].addr.q0); - try testing.expectEqual(@as(u32, 3), p.fs.panes[0].addr.q1); - - try testing.expectEqual(Status.ok, wr(p, Node.of(serial, .wrsel), "ONE").reply.status); - try testing.expectEqualStrings("ONE\ntwo\n", p.panes[0].?.file.?.content); - _ = wr(p, Node.of(serial, .wrsel), "!"); - try testing.expectEqualStrings("ONE!\ntwo\n", p.panes[0].?.file.?.content); -} - -test "every ctl verb, and every refusal" { - const gpa = testing.allocator; - const p = try withFile(gpa, "one\ntwo\n"); - defer p.deinit(); - const serial = serialOf(p); - const ctl = Node.of(serial, .ctl); - const pane = p.panes[0].?; - const pf = &p.fs.panes[0]; - - try testing.expectEqual(Status.ok, wr(p, ctl, "nomark\nnoscroll\ndirty\n").reply.status); - try testing.expect(pf.nomark and pf.noscroll and dirtyOf(pane)); - try testing.expectEqual(Status.ok, wr(p, ctl, "mark\nscroll\nclean\n").reply.status); - try testing.expect(!pf.nomark and !pf.noscroll and !dirtyOf(pane)); - - _ = wr(p, ctl, "cleartag\n"); - try testing.expectEqual(@as(usize, 0), pane.tag_tail_len); - - _ = wr(p, Node.of(serial, .addr), "2"); - _ = wr(p, ctl, "limit=addr\n"); - try testing.expectEqual(@as(u32, 4), pf.limit.?.q0); - _ = wr(p, ctl, "dot=addr\nshow\n"); - try testing.expectEqual(@as(i32, 1), pane.cur_row); - - try testing.expectEqual(Status.ok, wr(p, ctl, "name /tmp/renamed.txt\n").reply.status); - try testing.expectEqualStrings("/tmp/renamed.txt", pane.file.?.path); - try testing.expectEqual(E.INVAL, wr(p, ctl, "name two words\n").errno()); - try testing.expectEqual(E.INVAL, wr(p, ctl, "name\n").errno()); - try testing.expectEqualStrings("/tmp/renamed.txt", pane.file.?.path); - - try testing.expectEqual(Status.ok, wr(p, ctl, "put\n").reply.status); - try testing.expectEqualStrings(pane.file.?.content, p.fallback.get("/tmp/renamed.txt").?); - - for ([_][]const u8{ - "menu", "nomenu", "dump echo hi", "dumpdir /tmp", "font Go Mono", "lock", "unlock", "bogus", "DEL", - }) |bad| try testing.expectEqual(E.INVAL, wr(p, ctl, bad).errno()); - - try testing.expect(!dirtyOf(pane)); - try testing.expectEqual(E.INVAL, wr(p, ctl, "dirty\nbogus\n").errno()); - try testing.expect(!dirtyOf(pane)); -} - -test "ctl look opens spaced paths and locations without editing the source pane" { - if (!platform_has_fs) return error.SkipZigTest; - const gpa = testing.allocator; - var tmp = testing.tmpDir(.{}); - defer tmp.cleanup(); - try tmp.dir.writeFile(testing.io, .{ .sub_path = "two words.zig", .data = "first\nsecond\nthird\n" }); - var path_buf: [4096]u8 = undefined; - const path = path_buf[0..try tmp.dir.realPathFile(testing.io, "two words.zig", &path_buf)]; - const p = try withFile(gpa, "source stays intact\n"); - defer p.deinit(); - const source = p.panes[0].?; - const ctl = Node.of(source.serial, .ctl); - const revision = source.file.?.revision; - const undo_len = source.file.?.history.undo_len; - source.cur_col = 3; - var command: [4200]u8 = undefined; - try testing.expectEqual(Status.ok, wr(p, ctl, try std.fmt.bufPrint(&command, "look {s}:2:3\n", .{path})).reply.status); - const opened = p.panes[p.active].?; - try testing.expect(opened != source); - try testing.expectEqualStrings(path, opened.file.?.path); - try testing.expectEqualStrings("first\nsecond\nthird\n", opened.file.?.content); - try testing.expectEqual(@as(i32, 1), opened.cur_row); - try testing.expectEqual(@as(i32, 2), opened.cur_col); - try testing.expectEqualStrings("source stays intact\n", source.file.?.content); - try testing.expectEqual(revision, source.file.?.revision); - try testing.expectEqual(undo_len, source.file.?.history.undo_len); - try testing.expectEqual(@as(i32, 3), source.cur_col); - - try testing.expectEqual(Status.ok, wr(p, ctl, try std.fmt.bufPrint(&command, "look {s}:3:2\n", .{path})).reply.status); - try testing.expect(p.panes[p.active].? == opened); - try testing.expectEqual(@as(i32, 2), opened.cur_row); - try testing.expectEqual(@as(i32, 1), opened.cur_col); -} - -test "ctl look validates the whole batch before opening virtual files" { - const gpa = testing.allocator; - const p = try withFile(gpa, "source\n"); - defer p.deinit(); - const source = p.panes[0].?; - const ctl = Node.of(source.serial, .ctl); - const serial = p.next_serial; - for ([_][]const u8{ - "look", "look \t", "look /virtual/index\x00ignored", "look /virtual/index\nbogus\n", - }) |invalid| { - try testing.expectEqual(E.INVAL, wr(p, ctl, invalid).errno()); - try testing.expectEqual(serial, p.next_serial); - try testing.expectEqual(@as(usize, 0), p.active); - try testing.expectEqualStrings("source\n", source.file.?.content); - } - try testing.expectEqual(Status.ok, wr(p, ctl, "look /n/self/index\n").reply.status); - const opened = p.panes[p.active].?; - try testing.expectEqualStrings("/virtual/index", opened.file.?.path); - try testing.expect(std.mem.indexOf(u8, opened.file.?.content, "/test.txt") != null); - try testing.expectEqualStrings("source\n", source.file.?.content); -} - -test "ctl name promotes a scratch without changing its body or undo history" { - const gpa = testing.allocator; - const p = try withFile(gpa, "opener\n"); - defer p.deinit(); - _ = call(p, .{ .tag = 1, .op = .open, .node = factory_base + @intFromEnum(PaneFile.ctl) }); - const pane = p.panes[p.active].?; - const ctl = Node.of(pane.serial, .ctl); - const body = Node.of(pane.serial, .body); - _ = wr(p, body, "scratch "); - _ = wr(p, body, "work\n"); - const undo_len = pane.file.?.history.undo_len; - var tmp = testing.tmpDir(.{}); - defer tmp.cleanup(); - try tmp.dir.writeFile(testing.io, .{ .sub_path = "renamed.zig", .data = "existing target\n" }); - var directory_buf: [4096]u8 = undefined; - const directory = directory_buf[0..try tmp.dir.realPath(testing.io, &directory_buf)]; - var path_buffer: [4096]u8 = undefined; - const path = try std.fmt.bufPrint(&path_buffer, "{s}/renamed.zig", .{directory}); - var command: [4104]u8 = undefined; - const renamed = wr(p, ctl, try std.fmt.bufPrint(&command, "name {s}\n", .{path})); - try testing.expectEqual(Status.ok, renamed.reply.status); - try testing.expectEqual(false, renamed.watch.?); - try testing.expectEqualStrings("scratch work\n", pane.file.?.content); - try testing.expectEqual(undo_len, pane.file.?.history.undo_len); - try testing.expect(pane.file.?.output == null and dirtyOf(pane)); - try testing.expect(pane.file.?.watch_after_save); - const target = try readFile(gpa, path); - defer gpa.free(target); - try testing.expectEqualStrings("existing target\n", target); - const saved = wr(p, ctl, "put\n"); - try testing.expectEqual(Status.ok, saved.reply.status); - try testing.expectEqual(true, saved.watch.?); - try testing.expect(!dirtyOf(pane) and !pane.file.?.watch_after_save); - try testing.expectEqualStrings("scratch work\n", p.fallback.get(path).?); -} - -test "ctl name refreshes cached syntax for unchanged contents" { - if (!pardes.syntax.enabled) return error.SkipZigTest; - pardes.syntax.start(testing.allocator); - defer pardes.syntax.stop(); - const p = try withFile(testing.allocator, "fn check() void {}\n"); - defer p.deinit(); - const pane = p.panes[0].?; - panes.File.refreshHighlights(p); - try testing.expectEqual(@as(usize, 0), pane.file.?.highlights.len); - try testing.expectEqual(Status.ok, wr(p, Node.of(pane.serial, .ctl), "name renamed.zig\n").reply.status); - panes.File.refreshHighlights(p); - try testing.expect(pane.file.?.highlights.len >= 2); - try testing.expectEqual(@intFromEnum(pardes.syntax.Syn.keyword), pane.file.?.highlights[0]); - try testing.expectEqual(@intFromEnum(pardes.syntax.Syn.keyword), pane.file.?.highlights[1]); - try testing.expectEqualStrings("fn check() void {}\n", pane.file.?.content); -} - -test "ctl relative names use the file directory and can name a new target" { - const gpa = testing.allocator; - const p = try withFile(gpa, "retained body\n"); - defer p.deinit(); - var tmp = testing.tmpDir(.{}); - defer tmp.cleanup(); - try tmp.dir.writeFile(testing.io, .{ .sub_path = "note.txt", .data = "from pane directory\n" }); - var directory_buf: [4096]u8 = undefined; - const directory = directory_buf[0..try tmp.dir.realPath(testing.io, &directory_buf)]; - const pane = p.panes[0].?; - const ctl = Node.of(pane.serial, .ctl); - var command: [4140]u8 = undefined; - try testing.expectEqual(Status.ok, wr(p, ctl, try std.fmt.bufPrint(&command, "name {s}/old.txt\n", .{directory})).reply.status); - try testing.expectEqual(Status.ok, wr(p, ctl, "name child/../note.txt\nget\n").reply.status); - try testing.expectEqualStrings("from pane directory\n", pane.file.?.content); - try testing.expectEqualStrings(directory, Pardes.paneDir(pane)); - try testing.expectEqual(Status.ok, wr(p, ctl, "name ./created.txt\nput\n").reply.status); - try testing.expect(!dirtyOf(pane)); - var expected_buf: [4096]u8 = undefined; - const expected = try std.fmt.bufPrint(&expected_buf, "{s}/created.txt", .{directory}); - try testing.expectEqualStrings(expected, pane.file.?.path); - try testing.expectEqualStrings(pane.file.?.content, p.fallback.get(expected).?); -} - -test "ctl relative names follow inherited scratch and virtual directories" { - const p = try withFile(testing.allocator, "source body\n"); - defer p.deinit(); - const source = p.panes[0].?; - try testing.expectEqual(Status.ok, wr(p, Node.of(source.serial, .ctl), "name /project/src/source.zig\n").reply.status); - _ = call(p, .{ .tag = 1, .op = .open, .node = factory_base + @intFromEnum(PaneFile.ctl) }); - const scratch = p.panes[p.active].?; - const ctl = Node.of(scratch.serial, .ctl); - try testing.expectEqualStrings("/project/src", Pardes.paneDir(scratch)); - try testing.expectEqual(Status.ok, wr(p, ctl, "name ../out/./notes.txt\n").reply.status); - try testing.expectEqualStrings("/project/out/notes.txt", scratch.file.?.path); - try testing.expectEqualStrings("/project/out", Pardes.paneDir(scratch)); - var command: [256]u8 = undefined; - try testing.expectEqual(Status.ok, wr(p, ctl, try std.fmt.bufPrint(&command, "name /virtual/pane/{d}/./body\nget\n", .{source.serial})).reply.status); - try testing.expectEqualStrings(source.file.?.content, scratch.file.?.content); - const unchanged = wr(p, ctl, "name ./body\n"); - try testing.expectEqual(Status.ok, unchanged.reply.status); - try testing.expect(unchanged.watch == null); - try testing.expect(!dirtyOf(scratch)); - try testing.expect(!scratch.file.?.watch_after_save); -} - -test "ctl get reloads the pane from disk and del honours a dirty body" { - const gpa = testing.allocator; - var tmp = testing.tmpDir(.{}); - defer tmp.cleanup(); - try tmp.dir.writeFile(testing.io, .{ .sub_path = "note.txt", .data = "from disk\n" }); - var directory_buf: [4096]u8 = undefined; - const directory = directory_buf[0..try tmp.dir.realPath(testing.io, &directory_buf)]; - var path_buf: [4096]u8 = undefined; - const path = try std.fmt.bufPrint(&path_buf, "{s}/note.txt", .{directory}); - - const p = try withFile(gpa, "in memory\n"); - defer p.deinit(); - const serial = serialOf(p); - const ctl = Node.of(serial, .ctl); - const pane = p.panes[0].?; - - var name: [std.fs.max_path_bytes + 8]u8 = undefined; - _ = wr(p, ctl, try std.fmt.bufPrint(&name, "name {s}\n", .{path})); - try testing.expectEqual(Status.ok, wr(p, ctl, "get\n").reply.status); - try testing.expectEqualStrings("from disk\n", pane.file.?.content); - try testing.expect(!dirtyOf(pane)); - try testing.expect(pane.file.?.history.undo_len > 0); - - _ = wr(p, ctl, "dirty\n"); - try testing.expectEqual(E.INVAL, wr(p, ctl, "del\n").errno()); - try testing.expect(p.paneBySerial(serial) != null); - _ = call(p, .{ .tag = 1, .op = .open, .node = factory_base + @intFromEnum(PaneFile.body) }); - try testing.expectEqual(Status.ok, wr(p, ctl, "delete\n").reply.status); - try testing.expect(p.paneBySerial(serial) == null); -} - -test "ctl get reports missing files without losing dirty contents or applying del" { - const p = try withFile(testing.allocator, "unsaved contents\n"); - defer p.deinit(); - var tmp = testing.tmpDir(.{}); - defer tmp.cleanup(); - var directory_buf: [4096]u8 = undefined; - const directory = directory_buf[0..try tmp.dir.realPath(testing.io, &directory_buf)]; - var name: [4140]u8 = undefined; - const ctl = Node.of(serialOf(p), .ctl); - try testing.expectEqual(Status.ok, wr(p, ctl, try std.fmt.bufPrint(&name, "name {s}/missing.txt\ndirty\n", .{directory})).reply.status); - try testing.expectEqual(E.NOENT, wr(p, ctl, "get\ndel\n").errno()); - const pane = p.panes[0].?; - try testing.expectEqualStrings("unsaved contents\n", pane.file.?.content); - try testing.expect(dirtyOf(pane)); -} - -test "ctl put waits for one host write and stops before del when saving fails" { - const Refusing = struct { - p: *Pardes, - calls: usize = 0, - - fn writeFile(ctx: ?*anyopaque, id: u8, _: []const u8, _: []const u8) void { - const self: *@This() = @ptrCast(@alignCast(ctx.?)); - self.calls += 1; - self.p.saveFailed(id, "save", error.PermissionDenied); - } - }; - const p = try withFile(testing.allocator, "retained contents\n"); - defer p.deinit(); - var refusing: Refusing = .{ .p = p }; - p.host = .{ .ctx = &refusing, .vtable = &.{ .write_file = Refusing.writeFile } }; - const serial = serialOf(p); - const ctl = Node.of(serial, .ctl); - for ([_][]const u8{ "clean\n", "dirty\n" }, 0..) |initial, i| { - _ = wr(p, ctl, initial); - const result = wr(p, ctl, "put\ndel\n"); - try testing.expectEqual(E.IO, result.errno()); - try testing.expect(!result.saved); - try testing.expectEqual(i + 1, refusing.calls); - const pane = p.panes[p.paneBySerial(serial).?].?; - try testing.expect(dirtyOf(pane)); - try testing.expectEqualStrings("retained contents\n", pane.file.?.content); - } -} - -test "self directories walk to their namespace parents" { - const p = try withFile(testing.allocator, "contents\n"); - defer p.deinit(); - const root = @intFromEnum(SelfFile.root); - for ([_]struct { node: u64, parent: u64 }{ - .{ .node = root, .parent = namespace_root }, - .{ .node = @intFromEnum(SelfFile.new), .parent = root }, - .{ .node = namespace_panes, .parent = root }, - .{ .node = Node.of(serialOf(p), .dir), .parent = namespace_panes }, - }) |case| { - const result = look_up(p, case.node, ".."); - try testing.expectEqual(Status.ok, result.reply.status); - try testing.expectEqual(case.parent, result.reply.attr.node); - } -} - -test "errors and cons append to one +Errors buffer per directory" { - const gpa = testing.allocator; - const p = try withFile(gpa, "x\n"); - defer p.deinit(); - const serial = serialOf(p); - - const live = for (p.panes) |slot| { - if (slot) |q| if (q.file) |f| if (f.output) |o| if (std.meta.activeTag(o.from) == .errors) break q; - } else null; - try testing.expect(live == null); - - try testing.expectEqual(Status.ok, wr(p, Node.of(serial, .errors), "boom\n").reply.status); - _ = wr(p, @intFromEnum(SelfFile.cons), "again\n"); - - var found: usize = 0; - for (p.panes) |slot| { - const q = slot orelse continue; - const f = q.file orelse continue; - const o = f.output orelse continue; - if (std.meta.activeTag(o.from) != .errors) continue; - found += 1; - try testing.expectEqualStrings("boom\nagain\n", f.content); - try testing.expectEqualStrings("/+Errors", f.path); - } - try testing.expectEqual(@as(usize, 1), found); -} - -test "setattr truncation empties the body and answers fresh attributes" { - const gpa = testing.allocator; - const p = try withFile(gpa, "one\ntwo\n"); - defer p.deinit(); - const serial = serialOf(p); - - const a = call(p, .{ .tag = 7, .op = .setattr, .node = Node.of(serial, .body), .truncate = true }); - try testing.expectEqual(Status.ok, a.reply.status); - try testing.expectEqual(@as(u64, 0), a.reply.attr.size); - try testing.expectEqualStrings("", p.panes[0].?.file.?.content); - - _ = wr(p, Node.of(serial, .body), "new text\n"); - try testing.expectEqualStrings("new text\n", p.panes[0].?.file.?.content); - - const noop = call(p, .{ .tag = 8, .op = .setattr, .node = Node.of(serial, .body) }); - try testing.expectEqual(@as(u64, 9), noop.reply.attr.size); -} - -test "event records are acme's bytes, one per read, and .again when empty" { - const gpa = testing.allocator; - const p = try withFile(gpa, "Msg fs-ran\n"); - defer p.deinit(); - const serial = serialOf(p); - const event = Node.of(serial, .event); - - _ = noteAction(p, 0, .body_exec, 1, 4, flag_builtin, "sg "); - try testing.expect(p.fs.panes[0].events.empty()); - - const h = call(p, .{ .tag = 10, .op = .open, .node = event }); - try testing.expect(h.reply.handle != 0); - try testing.expectEqual(@as(u16, 1), p.fs.listeners); - - try testing.expectEqual(Status.again, rd(p, event, 0, 4096).reply.status); - - p.fs.origin = 'M'; - _ = noteAction(p, 0, .body_exec, 1, 4, flag_builtin, "ell"); - _ = noteAction(p, 0, .body_delete, 0, 3, 0, ""); - try testing.expectEqualStrings("MX1 4 1 3 ell\n", rd(p, event, 0, 4096).bytes); - try testing.expectEqualStrings("MD0 3 0 0 \n", rd(p, event, 0, 4096).bytes); - try testing.expectEqual(Status.again, rd(p, event, 0, 4096).reply.status); - - _ = noteAction(p, 0, .body_look, 0, 3, flag_filename, "one"); - try testing.expectEqual(E.INVAL, rd(p, event, 0, 4).errno()); - try testing.expectEqualStrings("ML0 3 4 3 one\n", rd(p, event, 0, 4096).bytes); - - const big = "z" ** max_record_text; - _ = noteAction(p, 0, .body_exec, 0, max_record_text, 0, big); - try testing.expectEqualStrings("MX0 256 0 0 \n", rd(p, event, 0, 4096).bytes); - - _ = call(p, .{ .tag = 11, .op = .release, .node = event, .handle = h.reply.handle }); - try testing.expectEqual(@as(u16, 0), p.fs.listeners); -} - -fn drainEvents(p: *Pardes, node: u64, store: []u8, out: [][]const u8) [][]const u8 { - var used: usize = 0; - var n: usize = 0; - while (n < out.len) { - const a = rd(p, node, 0, 4096); - if (a.reply.status != .ok) break; - @memcpy(store[used..][0..a.bytes.len], a.bytes); - out[n] = store[used..][0..a.bytes.len]; - used += a.bytes.len; - n += 1; - } - return out[0..n]; -} - -test "a write through the filesystem is reported once, attributed to the file it came through" { - const gpa = testing.allocator; - const p = try withFile(gpa, "one\ntwo\n"); - defer p.deinit(); - const serial = serialOf(p); - const event = Node.of(serial, .event); - _ = call(p, .{ .tag = 40, .op = .open, .node = event }); - var store: [4096]u8 = undefined; - var slots: [16][]const u8 = undefined; - _ = drainEvents(p, event, &store, &slots); - - _ = wr(p, Node.of(serial, .body), "three\n"); - const body_recs = drainEvents(p, event, &store, &slots); - try testing.expect(body_recs.len >= 1); - try testing.expectEqualStrings("EI8 14 0 6 three\n\n", body_recs[0]); - for (body_recs[1..]) |r| { - try testing.expectEqual(@as(u8, 'E'), r[0]); - try testing.expect(Action.fromChar(r[1]).?.onTag()); - } - - _ = wr(p, Node.of(serial, .addr), "1"); - _ = wr(p, Node.of(serial, .data), "ONE\n"); - const data_recs = drainEvents(p, event, &store, &slots); - try testing.expectEqual(@as(usize, 2), data_recs.len); - try testing.expectEqualStrings("FD0 3 0 0 \n", data_recs[0]); - try testing.expectEqualStrings("FI0 3 0 3 ONE\n", data_recs[1]); - try testing.expectEqual(Status.again, rd(p, event, 0, 4096).reply.status); -} - -test "two event readers each count once, and the second closing leaves the first" { - const gpa = testing.allocator; - const p = try withFile(gpa, "x\n"); - defer p.deinit(); - const event = Node.of(serialOf(p), .event); - - _ = call(p, .{ .tag = 12, .op = .open, .node = event }); - _ = call(p, .{ .tag = 13, .op = .open, .node = event }); - try testing.expectEqual(@as(u16, 2), p.fs.panes[0].readers); - try testing.expectEqual(@as(u16, 2), p.fs.listeners); - - _ = call(p, .{ .tag = 14, .op = .release, .node = event }); - try testing.expectEqual(@as(u16, 1), p.fs.panes[0].readers); - try testing.expect(p.fs.scripted(0)); - - _ = call(p, .{ .tag = 15, .op = .release, .node = Node.of(serialOf(p), .body) }); - try testing.expectEqual(@as(u16, 1), p.fs.listeners); - - _ = call(p, .{ .tag = 16, .op = .release, .node = event }); - try testing.expectEqual(@as(u16, 0), p.fs.listeners); - try testing.expect(!p.fs.scripted(0)); - _ = call(p, .{ .tag = 17, .op = .release, .node = event }); - try testing.expectEqual(@as(u16, 0), p.fs.listeners); -} - -test "a pane deleted while its event file is open leaves no suppression behind" { - const gpa = testing.allocator; - const p = try withFile(gpa, "x\n"); - defer p.deinit(); - const serial = serialOf(p); - const event = Node.of(serial, .event); - _ = call(p, .{ .tag = 1, .op = .open, .node = factory_base + @intFromEnum(PaneFile.body) }); - - const a = call(p, .{ .tag = 18, .op = .open, .node = event }); - const b = call(p, .{ .tag = 19, .op = .open, .node = event }); - try testing.expectEqual(@as(u16, 2), p.fs.listeners); - - _ = wr(p, Node.of(serial, .ctl), "delete\n"); - try testing.expect(p.paneBySerial(serial) == null); - try testing.expectEqual(@as(u16, 0), p.fs.listeners); - - _ = call(p, .{ .tag = 20, .op = .release, .node = event, .handle = a.reply.handle }); - _ = call(p, .{ .tag = 21, .op = .release, .node = event, .handle = b.reply.handle }); - try testing.expectEqual(@as(u16, 0), p.fs.listeners); - - try testing.expectEqual(E.NOENT, rd(p, event, 0, 64).errno()); - try testing.expectEqual(E.NOENT, rd(p, Node.of(serial, .body), 0, 64).errno()); - try testing.expectEqual(E.NOENT, wr(p, Node.of(serial, .ctl), "clean\n").errno()); - try testing.expectEqual(E.NOENT, call(p, .{ .tag = 22, .op = .open, .node = event }).errno()); -} - -test "writing an event record back performs the action it names" { - const gpa = testing.allocator; - const p = try withFile(gpa, "Msg fs-ran\n"); - defer p.deinit(); - const serial = serialOf(p); - const event = Node.of(serial, .event); - const pane = p.panes[0].?; - - const w = wr(p, event, "FX0 10\n"); - try testing.expectEqual(Status.ok, w.reply.status); - try testing.expectEqualStrings("fs-ran", pane.msg[0..pane.msg_len]); - - pane.msg_len = 0; - try testing.expectEqual(Status.ok, wr(p, event, "FX0 10\nFX0 10\n").reply.status); - try testing.expectEqualStrings("fs-ran", pane.msg[0..pane.msg_len]); - - pane.msg_len = 0; - for ([_][]const u8{ - "FX0 10\nFQ0 1\n", // unknown type character - "FX0 999\n", // out of range - "FX0 10", // no newline - "FX5 1\n", // q0 > q1 - "FD0 3\n", // a report, not a request - "F\n", - }) |bad| { - try testing.expectEqual(E.INVAL, wr(p, event, bad).errno()); - try testing.expectEqual(@as(usize, 0), pane.msg_len); - } - - _ = call(p, .{ .tag = 23, .op = .open, .node = event }); - p.fs.origin = 'K'; - _ = wr(p, event, "KX0 10\n"); - try testing.expectEqual(@as(u8, 'F'), p.fs.origin); -} - -test "a pane that is not a terminal has no pty/ at all" { - const gpa = testing.allocator; - const p = try withFile(gpa, "hello\n"); - defer p.deinit(); - const serial = serialOf(p); - const dir = Node.of(serial, .dir); - - try testing.expectEqual(E.NOENT, look_up(p, dir, "pty").errno()); - try testing.expectEqual(E.NOENT, call(p, .{ - .tag = 1, - .op = .getattr, - .node = Node.of(serial, .pty), - }).errno()); - try testing.expectEqual(E.NOENT, rd(p, Node.of(serial, .pty_status), 0, 256).errno()); - try testing.expectEqual(E.NOENT, wr(p, Node.of(serial, .pty_ctl), "winsize 80 24\n").errno()); - try testing.expectEqual(E.NOENT, rdir(p, Node.of(serial, .pty), 0).errno()); - try testing.expectEqual(E.NOENT, call(p, .{ - .tag = 2, - .op = .open, - .node = Node.of(serial, .pty_data), - }).errno()); - try testing.expectEqual(@as(u16, 0), p.fs.panes[0].pty_readers); - - var buf: [32]Dirent = undefined; - const files = dirents(rdir(p, dir, 0).bytes, &buf); - try testing.expectEqual(@as(usize, 10), files.len); - try testing.expect(nameAt(files, "pty") == null); - - try testing.expectEqual(E.NOENT, look_up(p, dir, "pty_ctl").errno()); - try testing.expectEqual(E.NOENT, look_up(p, dir, "status").errno()); - - const before = p.next_serial; - try testing.expectEqual(E.NOENT, look_up(p, @intFromEnum(SelfFile.new), "pty").errno()); - try testing.expectEqual(before, p.next_serial); -} - -test "a terminal pane's pty/ holds exactly ctl, status and data" { - const gpa = testing.allocator; - const p = try withTerm(gpa); - defer p.deinit(); - const serial = serialOf(p); - const dir = Node.of(serial, .dir); - - const pty = look_up(p, dir, "pty"); - try testing.expectEqual(Node.of(serial, .pty), pty.reply.attr.node); - try testing.expect(pty.reply.attr.dir); - try testing.expectEqual(@as(u16, 0o500), pty.reply.attr.mode); - - var buf: [32]Dirent = undefined; - const files = dirents(rdir(p, dir, 0).bytes, &buf); - try testing.expectEqual(@as(usize, 11), files.len); - try testing.expect(nameAt(files, "pty").?.dir); - - const inside = dirents(rdir(p, Node.of(serial, .pty), 0).bytes, &buf); - try testing.expectEqual(@as(usize, 3), inside.len); - try testing.expectEqualStrings("ctl", inside[0].name); - try testing.expectEqualStrings("status", inside[1].name); - try testing.expectEqualStrings("data", inside[2].name); - for (inside) |d| try testing.expect(!d.dir); - try testing.expectEqual(Node.of(serial, .pty_data), inside[2].node); - - const ctl = look_up(p, Node.of(serial, .pty), "ctl"); - try testing.expectEqual(Node.of(serial, .pty_ctl), ctl.reply.attr.node); - try testing.expectEqual(@as(u16, 0o200), ctl.reply.attr.mode); - try testing.expectEqual(@as(u16, 0o400), look_up(p, Node.of(serial, .pty), "status").reply.attr.mode); - try testing.expectEqual(E.NOENT, look_up(p, Node.of(serial, .pty), "body").errno()); - try testing.expectEqual(E.NOENT, look_up(p, Node.of(serial, .pty), "pty").errno()); - - try testing.expectEqual(E.NOTDIR, look_up(p, Node.of(serial, .pty_ctl), "x").errno()); - try testing.expectEqual(E.NOTDIR, rdir(p, Node.of(serial, .pty_ctl), 0).errno()); - try testing.expectEqual(E.PERM, rd(p, Node.of(serial, .pty), 0, 16).errno()); - try testing.expectEqual(E.PERM, rd(p, Node.of(serial, .pty_ctl), 0, 16).errno()); - try testing.expectEqual(E.PERM, wr(p, Node.of(serial, .pty_status), "x").errno()); -} - -test "every pty/ctl verb, and every refusal" { - const gpa = testing.allocator; - const p = try withTerm(gpa); - defer p.deinit(); - const ctl = Node.of(serialOf(p), .pty_ctl); - - const pane = p.panes[0].?; - const cols = pane.cols; - const rows = pane.rows; - const ws = wr(p, ctl, "winsize 132 44\n"); - try testing.expectEqual(@as(u32, "winsize 132 44\n".len), ws.reply.written); - try testing.expectEqual(@as(u16, 132), ws.winsize.?.cols); - try testing.expectEqual(@as(u16, 44), ws.winsize.?.rows); - try testing.expectEqual(cols, pane.cols); - try testing.expectEqual(rows, pane.rows); - - for ([_]struct { line: []const u8, want: pardes.PtySignal }{ - .{ .line = "sig INT", .want = .int }, - .{ .line = "sig TERM", .want = .term }, - .{ .line = "sig HUP", .want = .hup }, - .{ .line = "sig QUIT", .want = .quit }, - .{ .line = "sig KILL", .want = .kill }, - }) |c| { - const a = wr(p, ctl, c.line); - try testing.expectEqual(Status.ok, a.reply.status); - try testing.expectEqual(c.want, a.signal.?); - } - - const ex = wr(p, ctl, "exec\n"); - try testing.expectEqual(Status.ok, ex.reply.status); - try testing.expect(ex.spawned); - - const both = wr(p, ctl, "winsize 100 30\nsig TERM"); - try testing.expectEqual(@as(u16, 100), both.winsize.?.cols); - try testing.expectEqual(pardes.PtySignal.term, both.signal.?); - - for ([_][]const u8{ - "winsize", // no arguments - "winsize 80", // one argument - "winsize 80 24 extra", // three - "winsize 0 24", // zero is "unknown", never a width - "winsize 80 0", - "winsize -1 24", // not a decimal - "winsize 999999 24", // wider than a u16 - "sig", // no name - "sig INT TERM", // two - "sig SIGINT", - "sig int", // lower case - "sig 9", // a number is one platform's number - "sig USR1", // a real signal, deliberately not offered - "exec /bin/sh", // the effect carries no argv; refused, never ignored - "raw", - "cooked", - "winsize 80 24\nbogus", // a good verb beside a bad one - "bogus\nwinsize 80 24", - "name x", // a `ctl` verb; the two files share no vocabulary - "del", - }) |bad| { - const a = wr(p, ctl, bad); - try testing.expectEqual(E.INVAL, a.errno()); - try testing.expect(a.winsize == null); - try testing.expect(a.signal == null); - try testing.expect(!a.spawned); - } - - const spaced = wr(p, ctl, "\n winsize 90 20 \n\n"); - try testing.expectEqual(Status.ok, spaced.reply.status); - try testing.expectEqual(@as(u16, 90), spaced.winsize.?.cols); - try testing.expectEqual(Status.ok, wr(p, ctl, "").reply.status); -} - -const FakeTty = struct { - taken: bool, - - const vtable: pardes.Host.VTable = .{ .tty_taken = answer }; - - fn answer(ctx: ?*anyopaque, pane: u8) bool { - _ = pane; - const f: *FakeTty = @ptrCast(@alignCast(ctx.?)); - return f.taken; - } -}; - -test "owned cwd pty exec rejects long paths before applying its batch" { - const p = try withTerm(testing.allocator); - defer p.deinit(); - const pane = p.panes[0].?; - const ctl = Node.of(pane.serial, .pty_ctl); - var path: [1025]u8 = @splat('d'); - path[0] = '/'; - p.setCwd(0, &path); - for ([_][]const u8{ "exec\n", "winsize 100 30\nexec\n", "sig TERM\nexec\n" }) |command| { - const result = wr(p, ctl, command); - try testing.expectEqual(E.INVAL, result.errno()); - try testing.expect(!result.spawned); - try testing.expect(result.signal == null and result.winsize == null); - } - try testing.expectEqualStrings(&path, pane.cwdSlice()); - p.setCwd(0, path[0..pardes.effect_path_cap]); - const accepted = wr(p, ctl, "exec\n"); - try testing.expectEqual(Status.ok, accepted.reply.status); - try testing.expect(accepted.spawned); -} - -test "owned cwd name promotion releases the former directory" { - const p = try withTerm(testing.allocator); - defer p.deinit(); - p.newScratchBelow(0); - const id = p.active; - const pane = p.panes[id].?; - try pane.setOwnedCwd("/old/directory"); - const result = wr(p, Node.of(pane.serial, .ctl), "name saved.txt\n"); - try testing.expectEqual(Status.ok, result.reply.status); - try testing.expect(pane.cwd == .none); - try testing.expect(pane.file.?.output == null); - try testing.expectEqualStrings("/old/directory/saved.txt", pane.file.?.path); - try testing.expectEqualStrings("/old/directory", Pardes.paneDir(pane)); -} - -test "pty/status reports the grid and who holds the tty" { - const gpa = testing.allocator; - const p = try withTerm(gpa); - defer p.deinit(); - const pane = p.panes[0].?; - const status = Node.of(pane.serial, .pty_status); - - const a = rd(p, status, 0, 256); - try testing.expectEqual(Status.ok, a.reply.status); - var want: [64]u8 = undefined; - const whole = try std.fmt.bufPrint(&want, "{d:>11} {d:>11} {d:>11} ", .{ pane.cols, pane.rows, 0 }); - try testing.expectEqualStrings(whole, a.bytes); - try testing.expectEqual(@as(usize, 3 * 12), a.bytes.len); - try testing.expectEqualStrings(whole[12..], rd(p, status, 12, 256).bytes); - - var probe: FakeTty = .{ .taken = true }; - p.host = .{ .ctx = &probe, .vtable = &FakeTty.vtable }; - const held = rd(p, status, 0, 256); - try testing.expectEqualStrings( - try std.fmt.bufPrint(&want, "{d:>11} {d:>11} {d:>11} ", .{ pane.cols, pane.rows, 1 }), - held.bytes, - ); -} - -test "pty/data writes at the shell and reads the raw stream" { - const gpa = testing.allocator; - const p = try withTerm(gpa); - defer p.deinit(); - const serial = serialOf(p); - const data = Node.of(serial, .pty_data); - - const w = call(p, .{ .tag = 2, .op = .write, .node = data, .off = 999, .data = "ls -l\r" }); - try testing.expectEqual(@as(u32, 6), w.reply.written); - try testing.expectEqualStrings("ls -l\r", w.pty()); - try testing.expectEqual(@as(u32, 1), wr(p, data, "a\xC3").reply.written); - try testing.expectEqual(@as(u32, 0), wr(p, data, "").reply.written); - - try testing.expectEqual(Status.again, rd(p, data, 0, 64).reply.status); - - p.update(.{ .output = .{ .pane = 0, .bytes = "unwatched" } }); - while (p.nextEffect()) |_| {} - try testing.expectEqual(@as(usize, 0), p.fs.panes[0].pty_out.buf.items.len); - try testing.expectEqual(Status.again, rd(p, data, 0, 64).reply.status); - - _ = call(p, .{ .tag = 5, .op = .open, .node = data }); - try testing.expectEqual(@as(u16, 1), p.fs.panes[0].pty_readers); - try testing.expectEqual(@as(u16, 0), p.fs.listeners); - try testing.expect(!p.fs.scripted(0)); - - p.update(.{ .output = .{ .pane = 0, .bytes = "hello" } }); - while (p.nextEffect()) |_| {} - try testing.expectEqualStrings("hello", rd(p, data, 0, 64).bytes); - try testing.expectEqual(Status.again, rd(p, data, 0, 64).reply.status); - - p.update(.{ .output = .{ .pane = 0, .bytes = "abcdef" } }); - while (p.nextEffect()) |_| {} - try testing.expectEqualStrings("ab", rd(p, data, 0, 2).bytes); - try testing.expectEqualStrings("cd", rd(p, data, 0, 2).bytes); - p.update(.{ .output = .{ .pane = 0, .bytes = "ghi" } }); - while (p.nextEffect()) |_| {} - try testing.expectEqualStrings("efghi", rd(p, data, 0, 64).bytes); - - p.update(.{ .output = .{ .pane = 0, .bytes = "orphan" } }); - while (p.nextEffect()) |_| {} - _ = call(p, .{ .tag = 6, .op = .release, .node = data }); - try testing.expectEqual(@as(u16, 0), p.fs.panes[0].pty_readers); - try testing.expectEqual(@as(usize, 0), p.fs.panes[0].pty_out.buf.capacity); - try testing.expectEqual(Status.again, rd(p, data, 0, 64).reply.status); - - _ = call(p, .{ .tag = 7, .op = .open, .node = data }); - _ = call(p, .{ .tag = 8, .op = .open, .node = data }); - _ = call(p, .{ .tag = 9, .op = .release, .node = data }); - try testing.expectEqual(@as(u16, 1), p.fs.panes[0].pty_readers); - p.update(.{ .output = .{ .pane = 0, .bytes = "still" } }); - while (p.nextEffect()) |_| {} - try testing.expectEqualStrings("still", rd(p, data, 0, 64).bytes); -} - -test "the pty queue drops the oldest at its cap" { - const gpa = testing.allocator; - const p = try withTerm(gpa); - defer p.deinit(); - const data = Node.of(serialOf(p), .pty_data); - _ = call(p, .{ .tag = 5, .op = .open, .node = data }); - - const oldest: [4096]u8 = @splat('A'); - const rest: [4096]u8 = @splat('B'); - notePtyOutput(p, 0, &oldest); - for (0..queue_cap / rest.len + 4) |_| notePtyOutput(p, 0, &rest); - const q = &p.fs.panes[0].pty_out; - try testing.expect(q.buf.items.len - q.head <= queue_cap); - - var seen: usize = 0; - while (true) { - const a = rd(p, data, 0, 1 << 16); - if (a.reply.status == .again) break; - try testing.expect(std.mem.indexOfScalar(u8, a.bytes, 'A') == null); - if (a.bytes.len == 0) break; - seen += a.bytes.len; - } - try testing.expect(seen > 0 and seen <= queue_cap); +test { + _ = tree; } diff --git a/src/main.zig b/src/main.zig index 40ec8667..4b1910bd 100644 --- a/src/main.zig +++ b/src/main.zig @@ -281,10 +281,10 @@ fn nativeMain(init: std.process.Init) !void { const serial = std.fmt.parseInt(u32, pane_text, 10) catch break :forwarding; if (serial == 0) break :forwarding; var ctl_buf: [64]u8 = undefined; - const ctl = try std.fmt.bufPrint(&ctl_buf, "/self/pane/{d}/ctl", .{serial}); + const ctl = try std.fmt.bufPrint(&ctl_buf, "/pane/{d}/ctl", .{serial}); const word = positional orelse { var tag_buf: [64]u8 = undefined; - const tag = try std.fmt.bufPrint(&tag_buf, "/self/pane/{d}/tag", .{serial}); + const tag = try std.fmt.bufPrint(&tag_buf, "/pane/{d}/tag", .{serial}); const contents = ninep_io.Client.read(arena, dial, tag, tag) catch break :forwarding; arena.free(contents); try std.Io.File.stderr().writeStreamingAll(init.io, nested_text); diff --git a/src/memory.zig b/src/memory.zig index 60ec1bb6..f30e4392 100644 --- a/src/memory.zig +++ b/src/memory.zig @@ -19,7 +19,8 @@ pub const limits = struct { pub const message_log = if (board) 16 else 128; pub const max_tag_tail: usize = if (board) 512 else 4096; pub const host_path_cap: usize = if (board) 0 else 4095; - pub const embedded_sources = !board; + /// -Dembed-sources: the editor serves its own sources under /src. + pub const embedded_sources = config.embed_sources; pub const hexdump_row_bytes: u32 = if (board) 8 else 16; pub const arena = struct { @@ -138,7 +139,7 @@ test "memory limits preserve desktop capacities" { try std.testing.expectEqual(128, limits.message_log); try std.testing.expectEqual(@as(usize, 4096), limits.max_tag_tail); try std.testing.expectEqual(@as(usize, 4095), limits.host_path_cap); - try std.testing.expect(limits.embedded_sources); + try std.testing.expectEqual(config.embed_sources, limits.embedded_sources); try std.testing.expectEqual(@as(u32, 16), limits.hexdump_row_bytes); try std.testing.expectEqual(32 * MiB, limits.arena.pardes); try std.testing.expectEqual(16 * MiB, limits.arena.frame); diff --git a/src/ninep/addr.zig b/src/ninep/addr.zig new file mode 100644 index 00000000..f7642b9e --- /dev/null +++ b/src/ninep/addr.zig @@ -0,0 +1,276 @@ +//! The address language of a pane's `addr` file: acme's, with mvzr regexps. +const std = @import("std"); +const mvzr = @import("mvzr"); +const modal = @import("../modal.zig"); +const pane_files = @import("pane.zig"); + +pub const Range = pane_files.State.Range; + +fn clip(n: usize) u32 { + return std.math.cast(u32, n) orelse std.math.maxInt(u32); +} + +fn safePattern(pat: []const u8) bool { + var i: usize = 0; + while (i < pat.len) : (i += 1) { + if (pat[i] != '\\') continue; + if (i + 1 >= pat.len) return false; + i += 1; + } + return true; +} + +pub const Addr = struct { + text: []const u8, + lim: ?Range, + expr: []const u8, + i: usize = 0, + depth: u8 = 0, + + const max_depth = 32; + const Size = enum { char, line }; + + pub fn address(a: *Addr, ar_in: Range) ?Range { + const start = a.i; + var ar = ar_in; + var r = ar_in; + var dir: u8 = 0; + var size: Size = .line; + var c: u8 = 0; + while (a.i < a.expr.len) { + const prevc = c; + c = a.expr[a.i]; + a.i += 1; + switch (c) { + ',', ';' => { + if (c == ';') ar = r; + if (prevc == 0) r.q0 = 0; // lhs defaults to 0 + if (a.i >= a.expr.len) { + r.q1 = clip(a.text.len); // rhs defaults to $ + } else { + if (a.depth >= max_depth) return null; + a.depth += 1; + const nr = a.address(ar) orelse return null; + a.depth -= 1; + r.q1 = nr.q1; + } + return r; + }, + '+', '-' => { + if (prevc == '+' or prevc == '-') { + const nc = if (a.i < a.expr.len) a.expr[a.i] else 0; + if (nc != '#' and nc != '/' and nc != '?') + r = a.number(r, 1, prevc, .line) orelse return null; + } + dir = c; + }, + '.', '$' => { + if (a.i != start + 1) { + a.i -= 1; + return r; + } + r = if (c == '.') ar else .{ .q0 = clip(a.text.len), .q1 = clip(a.text.len) }; + dir = if (a.i < a.expr.len) '+' else 0; + }, + '#', '0'...'9' => { + var digit = c; + if (c == '#') { + if (a.i >= a.expr.len or a.expr[a.i] < '0' or a.expr[a.i] > '9') { + a.i -= 1; + return r; + } + digit = a.expr[a.i]; + a.i += 1; + size = .char; + } + var n: u64 = digit - '0'; + while (a.i < a.expr.len) : (a.i += 1) { + const d = a.expr[a.i]; + if (d < '0' or d > '9') break; + n = @min(n * 10 + (d - '0'), std.math.maxInt(u32)); + } + r = a.number(r, @intCast(n), dir, size) orelse return null; + dir = 0; + size = .line; + }, + '/', '?' => { + const back = c == '?'; + r = a.regexp(r, a.pattern(c), back) orelse return null; + dir = 0; + size = .line; + }, + else => { + a.i -= 1; + return r; + }, + } + } + if (dir != 0) r = a.number(r, 1, dir, .line) orelse return null; + return r; + } + + fn pattern(a: *Addr, delim: u8) []const u8 { + const s = a.i; + while (a.i < a.expr.len) { + const c = a.expr[a.i]; + if (c == '\n') break; + a.i += 1; + if (c == '\\') { + if (a.i < a.expr.len) a.i += 1; + continue; + } + if (c == delim) return a.expr[s .. a.i - 1]; + } + return a.expr[s..a.i]; + } + + fn number(a: *Addr, r_in: Range, n: u32, dir: u8, size: Size) ?Range { + var r = r_in; + if (size == .char) { + var off: i64 = n; + if (dir == '+') { + off = @as(i64, r.q1) + n; + } else if (dir == '-') { + if (r.q0 == 0 and n > 0) r.q0 = clip(a.text.len); + off = @as(i64, r.q0) - n; + } + if (off < 0 or off > @as(i64, @intCast(a.text.len))) return null; + const g = clip(modal.graphemeStart(a.text, @intCast(off))); + return .{ .q0 = g, .q1 = g }; + } + var line: i64 = n; + var q0: usize = r.q0; + var q1: usize = r.q1; + switch (dir) { + '-' => { + if (q0 < a.text.len) while (q0 > 0 and a.text[q0 - 1] != '\n') { + q0 -= 1; + }; + q1 = q0; + while (line > 0 and q0 > 0) { + if (a.text[q0 - 1] == '\n') { + line -= 1; + q1 = q0; + } + q0 -= 1; + } + if (line > 1) return null; + while (q0 > 0 and a.text[q0 - 1] != '\n') q0 -= 1; + return .{ .q0 = clip(q0), .q1 = clip(q1) }; + }, + '+' => { + if (q1 > 0) while (q1 < a.text.len and a.text[q1 - 1] != '\n') { + q1 += 1; + }; + q0 = q1; + }, + else => { + q0 = 0; + q1 = 0; + }, + } + while (line > 0 and q1 < a.text.len) { + const ch = a.text[q1]; + q1 += 1; + if (ch == '\n' or q1 == a.text.len) { + line -= 1; + if (line > 0) q0 = q1; + } + } + if (line > 0) return null; + return .{ .q0 = clip(q0), .q1 = clip(q1) }; + } + + fn regexp(a: *Addr, r: Range, pat: []const u8, back: bool) ?Range { + if (pat.len == 0 or !safePattern(pat)) return null; + const re = mvzr.compile(pat) orelse return null; + if (back) { + const hi = @min(@as(usize, r.q0), a.text.len); + var best: ?mvzr.Match = null; + var at: usize = 0; + while (at < hi) { + const m = re.matchPos(at, a.text[0..hi]) orelse break; + best = m; + at = if (m.end > m.start) m.end else m.end + 1; + } + const m = best orelse return null; + return .{ .q0 = clip(m.start), .q1 = clip(m.end) }; + } + const hi = if (a.lim) |l| @min(@as(usize, l.q1), a.text.len) else a.text.len; + const from = @min(@as(usize, r.q1), hi); + const m = re.match(a.text[from..hi]) orelse return null; + return .{ .q0 = clip(from + m.start), .q1 = clip(from + m.end) }; + } +}; + +const testing = std.testing; +const th = @import("testing.zig"); +const tree = @import("tree.zig"); +const Node = tree.Node; +const E = tree.E; +const Status = tree.Status; + +test "the address language, form by form" { + const gpa = testing.allocator; + const p = try th.withFile(gpa, "one\ntwo\nthree\n"); + defer p.deinit(); + const serial = th.serialOf(p); + const addr = Node.of(serial, .addr); + + const Case = struct { expr: []const u8, q0: u32, q1: u32 }; + for ([_]Case{ + .{ .expr = "#0", .q0 = 0, .q1 = 0 }, + .{ .expr = "#5", .q0 = 5, .q1 = 5 }, + .{ .expr = "0", .q0 = 0, .q1 = 0 }, + .{ .expr = "1", .q0 = 0, .q1 = 4 }, + .{ .expr = "2", .q0 = 4, .q1 = 8 }, + .{ .expr = "$", .q0 = 14, .q1 = 14 }, + .{ .expr = ",", .q0 = 0, .q1 = 14 }, + .{ .expr = "1,2", .q0 = 0, .q1 = 8 }, + .{ .expr = "#1,#4", .q0 = 1, .q1 = 4 }, + .{ .expr = "2+1", .q0 = 8, .q1 = 14 }, + .{ .expr = "$-1", .q0 = 8, .q1 = 14 }, + .{ .expr = "/two/", .q0 = 4, .q1 = 7 }, + .{ .expr = "/t.o/", .q0 = 4, .q1 = 7 }, + .{ .expr = "1\n", .q0 = 0, .q1 = 4 }, + }) |c| { + _ = th.wr(p, addr, "#0"); + const w = th.wr(p, addr, c.expr); + try testing.expectEqual(Status.ok, w.reply.status); + const got = th.rd(p, addr, 0, 64); + var want: [32]u8 = undefined; + try testing.expectEqualStrings( + try std.fmt.bufPrint(&want, "{d:>11} {d:>11} ", .{ c.q0, c.q1 }), + got.bytes, + ); + } + + _ = th.wr(p, addr, "1"); + _ = th.wr(p, addr, "."); + try testing.expectEqual(@as(u32, 0), p.fs.panes[0].addr.q0); + try testing.expectEqual(@as(u32, 4), p.fs.panes[0].addr.q1); + + _ = th.wr(p, addr, "$"); + _ = th.wr(p, addr, "?o?"); + try testing.expectEqual(@as(u32, 6), p.fs.panes[0].addr.q0); // the `o` in "two" + try testing.expectEqual(@as(u32, 7), p.fs.panes[0].addr.q1); + + _ = th.wr(p, addr, "1"); + _ = th.wr(p, Node.of(serial, .ctl), "limit=addr\n"); + _ = th.wr(p, addr, "#0"); + try testing.expectEqual(E.INVAL, th.wr(p, addr, "/three/").errno()); + _ = th.wr(p, Node.of(serial, .ctl), "clean\n"); + _ = th.call(p, .{ .tag = 6, .op = .open, .node = Node.of(serial, .ctl) }); + try testing.expect(p.fs.panes[0].limit == null); + _ = th.wr(p, addr, "#0"); + try testing.expectEqual(Status.ok, th.wr(p, addr, "/three/").reply.status); + + for ([_][]const u8{ "zzz", "#", "//", "/nomatch/", "1 2", "99", "/a\\" }) |bad| { + _ = th.wr(p, addr, "#0"); + try testing.expectEqual(E.INVAL, th.wr(p, addr, bad).errno()); + } + + const nested = "," ** 4096; + _ = th.wr(p, addr, "#0"); + try testing.expectEqual(E.INVAL, th.wr(p, addr, nested).errno()); +} diff --git a/src/ninep/ctl.zig b/src/ninep/ctl.zig new file mode 100644 index 00000000..d61ebf75 --- /dev/null +++ b/src/ninep/ctl.zig @@ -0,0 +1,503 @@ +//! The two ctl files. `look TEXT` is a right click and `exec TEXT` a middle +//! click in the editor's own command language; a pane's ctl adds the addr +//! verbs. Reading /ctl answers the serials the last command made or touched. +const std = @import("std"); +const pardes = @import("../pardes.zig"); +const panes = @import("../panes.zig"); +const config = @import("../config.zig"); +const fs = @import("../fs.zig"); +const tree = @import("tree.zig"); +const pane_files = @import("pane.zig"); + +const Pardes = pardes.Pardes; +const Pane = pardes.Pane; +const MAX_PANES = pardes.MAX_PANES; +const Req = tree.Req; +const Reply = tree.Reply; +const E = tree.E; + +const Verb = enum { + @"addr=dot", + clean, + cleartag, + dirty, + @"dot=addr", + get, + @"limit=addr", + mark, + nomark, + noscroll, + scroll, + show, +}; + +fn verbIs(line: []const u8, word: []const u8) bool { + if (!std.mem.startsWith(u8, line, word)) return false; + return line.len == word.len or line[word.len] == ' ' or line[word.len] == '\t'; +} + +/// The text after `look` or `exec`, or null when the line is not that verb. +/// Control characters other than tab are refused. +fn textAfter(line: []const u8, verb: []const u8) ?[]const u8 { + if (!verbIs(line, verb)) return null; + const text = std.mem.trim(u8, line[verb.len..], " \t"); + if (text.len == 0) return ""; + for (text) |c| if (c < ' ' and c != '\t') return ""; + return text; +} + +// ---- which panes a command made or touched ---- + +const Serials = struct { + list: [MAX_PANES]u32 = undefined, + len: usize = 0, + + fn snapshot(p: *Pardes) Serials { + var s: Serials = .{}; + for (p.panes) |slot| if (slot) |pane| { + s.list[s.len] = pane.serial; + s.len += 1; + }; + return s; + } + + fn has(s: *const Serials, serial: u32) bool { + for (s.list[0..s.len]) |known| if (known == serial) return true; + return false; + } +}; + +fn noteResult(p: *Pardes, serial: u32) void { + for (p.fs.results[0..p.fs.results_len]) |known| if (known == serial) return; + if (p.fs.results_len == p.fs.results.len) return; + p.fs.results[p.fs.results_len] = serial; + p.fs.results_len += 1; +} + +fn activeSerial(p: *Pardes) ?u32 { + const pane = p.panes[p.active] orelse return null; + return pane.serial; +} + +/// Runs one look or exec from the pane `id`, then records the panes it +/// created; failing that, a look records the pane it focused and an exec +/// the pane it acted on (even one it closed). +fn run(p: *Pardes, id: usize, exec: bool, text: []const u8) void { + const context = p.panes[id].?.serial; + const before = Serials.snapshot(p); + if (exec) _ = p.execute(id, text) else p.lookAt(id, text); + const after = Serials.snapshot(p); + var created = false; + for (after.list[0..after.len]) |serial| if (!before.has(serial)) { + noteResult(p, serial); + created = true; + }; + if (created) return; + noteResult(p, if (exec) context else activeSerial(p) orelse return); +} + +fn beginResults(p: *Pardes) void { + p.fs.results_len = 0; + p.fs.results_valid = true; +} + +// ---- /ctl ---- + +pub fn writeRoot(p: *Pardes, req: Req) Reply { + for ([2]bool{ false, true }) |apply| { + if (apply) beginResults(p); + var it = std.mem.splitScalar(u8, req.data, '\n'); + while (it.next()) |raw| { + const line = std.mem.trim(u8, raw, " \t\r"); + if (line.len == 0) continue; + const exec = verbIs(line, "exec"); + const text = textAfter(line, if (exec) "exec" else "look") orelse return Reply.fail(req.tag, E.INVAL); + if (text.len == 0) return Reply.fail(req.tag, E.INVAL); + if (!apply) continue; + if (p.panes[p.active] == null) return Reply.fail(req.tag, E.NOENT); + run(p, p.active, exec, text); + } + } + return .{ .tag = req.tag, .written = @intCast(req.data.len) }; +} + +pub fn rootText(p: *Pardes, buf: []u8) []const u8 { + var w = std.Io.Writer.fixed(buf); + if (p.fs.results_valid) { + for (p.fs.results[0..p.fs.results_len]) |serial| w.print("{d}\n", .{serial}) catch break; + return w.buffered(); + } + var count: usize = 0; + for (p.panes) |slot| count += @intFromBool(slot != null); + const pid: u32 = if (comptime pardes.hosted) @intCast(std.c.getpid()) else 0; + w.print("pid {d}\nversion {s}\npanes {d}\n", .{ pid, pardes.version, count }) catch {}; + return w.buffered(); +} + +pub const root_text_cap = @max(MAX_PANES * 11, 64 + pardes.version.len); + +pub fn readRoot(p: *Pardes, req: Req) Reply { + var buf: [root_text_cap]u8 = undefined; + const text = rootText(p, &buf); + const out = p.fs.stage(p.gpa); + out.appendSlice(p.gpa, text) catch return Reply.fail(req.tag, E.NOMEM); + return tree.stagedReply(p, req); +} + +// ---- /pane//ctl ---- + +fn fontName(p: *Pardes) []const u8 { + const name = p.settings.font.effective_name.get(); + return if (name.len == 0) "default" else name; +} + +fn writeQuoted(w: *std.Io.Writer, s: []const u8) !void { + const plain = s.len > 0 and for (s) |c| { + if (c <= ' ' or c == '\'') break false; + } else true; + if (plain) return w.writeAll(s); + try w.writeByte('\''); + for (s) |c| { + if (c == '\'') try w.writeByte('\''); + try w.writeByte(c); + } + try w.writeByte('\''); +} + +pub const pane_text_cap = 7 * 12 + 2 * 256 + 4; + +/// acme's winctlprint: serial, tag length, body length, a reserved zero, the +/// dirty flag, then the width in cells, the font and the tab width. +pub fn paneText(p: *Pardes, pane: *Pane, buf: []u8) []const u8 { + var w = std.Io.Writer.fixed(buf); + w.print("{d:>11} {d:>11} {d:>11} {d:>11} {d:>11} {d:>11} ", .{ + pane.serial, + pane_files.tagOf(p, pane).len, + pane_files.bodyOf(pane).len, + @as(u32, 0), + @intFromBool(pane_files.dirtyOf(pane)), + pane.cols, + }) catch return w.buffered(); + writeQuoted(&w, fontName(p)) catch return w.buffered(); + w.print(" {d:>11} ", .{config.tab_width}) catch {}; + return w.buffered(); +} + +pub fn readPane(p: *Pardes, req: Req, pane: *Pane) Reply { + var buf: [pane_text_cap]u8 = undefined; + const out = p.fs.stage(p.gpa); + out.appendSlice(p.gpa, paneText(p, pane, &buf)) catch return Reply.fail(req.tag, E.NOMEM); + return tree.stagedReply(p, req); +} + +pub fn writePane(p: *Pardes, req: Req, serial: u32) Reply { + for ([2]bool{ false, true }) |apply| { + if (apply) beginResults(p); + var it = std.mem.splitScalar(u8, req.data, '\n'); + while (it.next()) |raw| { + const line = std.mem.trim(u8, raw, " \t\r"); + if (line.len == 0) continue; + const live = p.paneBySerial(serial) orelse if (apply) break else return Reply.fail(req.tag, E.NOENT); + const errno = paneVerb(p, live, line, apply); + if (errno != 0) return Reply.fail(req.tag, errno); + } + } + return .{ .tag = req.tag, .written = @intCast(req.data.len) }; +} + +fn paneVerb(p: *Pardes, id: usize, line: []const u8, apply: bool) u16 { + const pane = p.panes[id] orelse return E.INVAL; + const pf = &p.fs.panes[id]; + + for ([_]bool{ false, true }) |exec| if (textAfter(line, if (exec) "exec" else "look")) |text| { + if (text.len == 0) return E.INVAL; + if (apply) run(p, id, exec, text); + return 0; + }; + const v = std.meta.stringToEnum(Verb, line) orelse return E.INVAL; + if (!apply) return 0; + + switch (v) { + .@"addr=dot" => pf.addr = pane_files.dotOf(pane), + .@"dot=addr" => { + pane_files.clampAddr(pf, pane_files.bodyOf(pane).len); + pane_files.setDot(pane, pf.addr); + }, + .@"limit=addr" => { + pane_files.clampAddr(pf, pane_files.bodyOf(pane).len); + pf.limit = pf.addr; + }, + .clean => if (pane_files.fileOf(pane)) |f| { + f.saved_revision = f.revision; + }, + .dirty => if (pane_files.fileOf(pane)) |f| { + f.saved_revision = f.revision -% 1; + }, + .cleartag => { + pane.tag_tail_len = 0; + pane.tag_init = true; + }, + .get => if (pane_files.fileOf(pane)) |f| { + if (panes.Output.fileTraits(f.output).saves) { + if (fs.read(p, f.path)) |bytes| { + panes.File.pushUndo(p, pane); + panes.File.setContent(p, f, bytes); + f.saved_revision = f.revision; + } else |err| return switch (err) { + error.FileNotFound => E.NOENT, + else => E.IO, + }; + } + }, + .mark => { + pf.nomark = false; + panes.File.pushUndo(p, pane); + }, + .nomark => pf.nomark = true, + .noscroll => pf.noscroll = true, + .scroll => pf.noscroll = false, + .show => pane_files.showOffset(pane, pane_files.dotOf(pane).q0), + } + return 0; +} + +// ---- tests ---- + +const testing = std.testing; +const th = @import("testing.zig"); +const call = th.call; +const rd = th.rd; +const wr = th.wr; +const withFile = th.withFile; +const serialOf = th.serialOf; +const Node = tree.Node; +const Status = tree.Status; +const root_ctl = @intFromEnum(tree.TopFile.ctl); + +test "pane ctl read is index's five fields plus width in cells, font and tab width" { + const gpa = testing.allocator; + const p = try withFile(gpa, "x\n"); + defer p.deinit(); + const pane = p.panes[0].?; + + const a = rd(p, Node.of(pane.serial, .ctl), 0, 4096); + try testing.expectEqual(Status.ok, a.reply.status); + var want: std.ArrayList(u8) = .empty; + defer want.deinit(gpa); + try want.print(gpa, "{d:>11} {d:>11} {d:>11} {d:>11} {d:>11} {d:>11} {s} {d:>11} ", .{ + pane.serial, pane_files.tagOf(p, pane).len, @as(usize, 2), 0, 0, pane.cols, "default", config.tab_width, + }); + try testing.expectEqualStrings(want.items, a.bytes); + try testing.expectEqual(@as(u64, a.bytes.len), call(p, .{ .tag = 1, .op = .getattr, .node = Node.of(pane.serial, .ctl) }).reply.attr.size); + + var quoted: [64]u8 = undefined; + var w = std.Io.Writer.fixed("ed); + try writeQuoted(&w, "DejaVu Sans Mono"); + try testing.expectEqualStrings("'DejaVu Sans Mono'", w.buffered()); + w = std.Io.Writer.fixed("ed); + try writeQuoted(&w, "it's"); + try testing.expectEqualStrings("'it''s'", w.buffered()); +} + +test "every pane ctl verb, and every refusal" { + const gpa = testing.allocator; + const p = try withFile(gpa, "one\ntwo\n"); + defer p.deinit(); + const serial = serialOf(p); + const ctl_node = Node.of(serial, .ctl); + const pane = p.panes[0].?; + const pf = &p.fs.panes[0]; + + try testing.expectEqual(Status.ok, wr(p, ctl_node, "nomark\nnoscroll\ndirty\n").reply.status); + try testing.expect(pf.nomark and pf.noscroll and pane_files.dirtyOf(pane)); + try testing.expectEqual(Status.ok, wr(p, ctl_node, "mark\nscroll\nclean\n").reply.status); + try testing.expect(!pf.nomark and !pf.noscroll and !pane_files.dirtyOf(pane)); + + _ = wr(p, ctl_node, "cleartag\n"); + try testing.expectEqual(@as(usize, 0), pane.tag_tail_len); + + _ = wr(p, Node.of(serial, .addr), "2"); + _ = wr(p, ctl_node, "limit=addr\n"); + try testing.expectEqual(@as(u32, 4), pf.limit.?.q0); + _ = wr(p, ctl_node, "dot=addr\nshow\n"); + try testing.expectEqual(@as(i32, 1), pane.cur_row); + + for ([_][]const u8{ + "menu", "nomenu", "dump echo hi", "dumpdir /tmp", "font Go Mono", "lock", "unlock", "bogus", "DEL", + "name x.txt", "put", "del", "delete", "Look x", "Exec Save", + }) |bad| try testing.expectEqual(E.INVAL, wr(p, ctl_node, bad).errno()); + + try testing.expect(!pane_files.dirtyOf(pane)); + try testing.expectEqual(E.INVAL, wr(p, ctl_node, "dirty\nbogus\n").errno()); + try testing.expect(!pane_files.dirtyOf(pane)); +} + +test "exec runs a builtin at the pane and records the pane it acted on" { + const gpa = testing.allocator; + const p = try withFile(gpa, "Msg fs-ran\n"); + defer p.deinit(); + const serial = serialOf(p); + const pane = p.panes[0].?; + try testing.expectEqual(Status.ok, wr(p, Node.of(serial, .ctl), "exec Msg from ctl\n").reply.status); + try testing.expectEqualStrings("from ctl", pane.msg[0..pane.msg_len]); + var expected: [16]u8 = undefined; + try testing.expectEqualStrings(try std.fmt.bufPrint(&expected, "{d}\n", .{serial}), rd(p, root_ctl, 0, 4096).bytes); + + try testing.expectEqual(Status.ok, wr(p, Node.of(serial, .ctl), "exec New\n").reply.status); + const made = p.panes[p.active].?; + try testing.expect(made.serial != serial); + try testing.expectEqualStrings(try std.fmt.bufPrint(&expected, "{d}\n", .{made.serial}), rd(p, root_ctl, 0, 4096).bytes); + + try testing.expectEqual(Status.ok, wr(p, Node.of(made.serial, .ctl), "exec Del\n").reply.status); + try testing.expect(p.paneBySerial(made.serial) == null); + try testing.expectEqualStrings(try std.fmt.bufPrint(&expected, "{d}\n", .{made.serial}), rd(p, root_ctl, 0, 4096).bytes); +} + +test "the root ctl reads editor status until a command runs and validates whole batches" { + const gpa = testing.allocator; + const p = try withFile(gpa, "Msg root\n"); + defer p.deinit(); + const status = rd(p, root_ctl, 0, 4096); + try testing.expectEqual(Status.ok, status.reply.status); + var lines = std.mem.tokenizeScalar(u8, status.bytes, '\n'); + try testing.expect(std.mem.startsWith(u8, lines.next().?, "pid ")); + var expected: [64]u8 = undefined; + try testing.expectEqualStrings(try std.fmt.bufPrint(&expected, "version {s}", .{pardes.version}), lines.next().?); + try testing.expectEqualStrings("panes 1", lines.next().?); + try testing.expect(lines.next() == null); + const stat = call(p, .{ .tag = 1, .op = .getattr, .node = root_ctl }); + try testing.expectEqual(@as(u64, status.bytes.len), stat.reply.attr.size); + try testing.expectEqual(@as(u16, 0o666), stat.reply.attr.mode); + + const serial = p.next_serial; + for ([_][]const u8{ "look", "exec", "look \t", "Look /virtual/index", "exec Msg a\x00b", "exec Msg x\nbogus\n", "name x", "put" }) |invalid| { + try testing.expectEqual(E.INVAL, wr(p, root_ctl, invalid).errno()); + try testing.expectEqual(serial, p.next_serial); + } + try testing.expectEqualStrings(status.bytes, rd(p, root_ctl, 0, 4096).bytes); + + const pane = p.panes[0].?; + try testing.expectEqual(Status.ok, wr(p, root_ctl, "exec Msg hello there\n").reply.status); + try testing.expectEqualStrings("hello there", pane.msg[0..pane.msg_len]); + try testing.expectEqualStrings(try std.fmt.bufPrint(&expected, "{d}\n", .{pane.serial}), rd(p, root_ctl, 0, 4096).bytes); + + try testing.expectEqual(Status.ok, wr(p, root_ctl, "look /virtual/index\nexec New\n").reply.status); + var made: [MAX_PANES]u32 = undefined; + var n: usize = 0; + for (p.panes) |slot| if (slot) |q| if (q.serial != pane.serial) { + made[n] = q.serial; + n += 1; + }; + try testing.expectEqual(@as(usize, 2), n); + const listed = rd(p, root_ctl, 0, 4096); + try testing.expectEqualStrings(try std.fmt.bufPrint(&expected, "{d}\n{d}\n", .{ @min(made[0], made[1]), @max(made[0], made[1]) }), listed.bytes); + const opened = p.panes[p.paneBySerial(@min(made[0], made[1])).?].?; + try testing.expectEqualStrings("/virtual/index", opened.file.?.path); +} + +test "look opens spaced paths and locations without editing the source pane" { + if (!fs.platform_has_fs) return error.SkipZigTest; + const gpa = testing.allocator; + var tmp = testing.tmpDir(.{}); + defer tmp.cleanup(); + try tmp.dir.writeFile(testing.io, .{ .sub_path = "two words.zig", .data = "first\nsecond\nthird\n" }); + var path_buf: [4096]u8 = undefined; + const path = path_buf[0..try tmp.dir.realPathFile(testing.io, "two words.zig", &path_buf)]; + const p = try withFile(gpa, "source stays intact\n"); + defer p.deinit(); + const source = p.panes[0].?; + const ctl_node = Node.of(source.serial, .ctl); + const revision = source.file.?.revision; + const undo_len = source.file.?.history.undo_len; + source.cur_col = 3; + var command: [4200]u8 = undefined; + try testing.expectEqual(Status.ok, wr(p, ctl_node, try std.fmt.bufPrint(&command, "look {s}:2:3\n", .{path})).reply.status); + const opened = p.panes[p.active].?; + try testing.expect(opened != source); + try testing.expectEqualStrings(path, opened.file.?.path); + try testing.expectEqualStrings("first\nsecond\nthird\n", opened.file.?.content); + try testing.expectEqual(@as(i32, 1), opened.cur_row); + try testing.expectEqual(@as(i32, 2), opened.cur_col); + try testing.expectEqualStrings("source stays intact\n", source.file.?.content); + try testing.expectEqual(revision, source.file.?.revision); + try testing.expectEqual(undo_len, source.file.?.history.undo_len); + try testing.expectEqual(@as(i32, 3), source.cur_col); + var expected: [16]u8 = undefined; + try testing.expectEqualStrings(try std.fmt.bufPrint(&expected, "{d}\n", .{opened.serial}), rd(p, root_ctl, 0, 4096).bytes); + + p.active = 0; + try testing.expectEqual(Status.ok, wr(p, root_ctl, try std.fmt.bufPrint(&command, "look {s}:3:2\n", .{path})).reply.status); + try testing.expect(p.panes[p.active].? == opened); + try testing.expectEqual(@as(i32, 2), opened.cur_row); + try testing.expectEqual(@as(i32, 1), opened.cur_col); + try testing.expectEqualStrings(try std.fmt.bufPrint(&expected, "{d}\n", .{opened.serial}), rd(p, root_ctl, 0, 4096).bytes); +} + +test "look validates the whole batch before opening virtual files" { + const gpa = testing.allocator; + const p = try withFile(gpa, "source\n"); + defer p.deinit(); + const source = p.panes[0].?; + const ctl_node = Node.of(source.serial, .ctl); + const serial = p.next_serial; + for ([_][]const u8{ + "look", "look \t", "look /virtual/index\x00ignored", "look /virtual/index\nbogus\n", + }) |invalid| { + try testing.expectEqual(E.INVAL, wr(p, ctl_node, invalid).errno()); + try testing.expectEqual(serial, p.next_serial); + try testing.expectEqual(@as(usize, 0), p.active); + try testing.expectEqualStrings("source\n", source.file.?.content); + } + try testing.expectEqual(Status.ok, wr(p, ctl_node, "look /n/self/index\n").reply.status); + const opened = p.panes[p.active].?; + try testing.expectEqualStrings("/virtual/index", opened.file.?.path); + try testing.expect(std.mem.indexOf(u8, opened.file.?.content, "/test.txt") != null); + try testing.expectEqualStrings("source\n", source.file.?.content); +} + +test "get reloads the pane from disk and reports a missing file without losing dirty contents" { + const gpa = testing.allocator; + var tmp = testing.tmpDir(.{}); + defer tmp.cleanup(); + try tmp.dir.writeFile(testing.io, .{ .sub_path = "note.txt", .data = "from disk\n" }); + var directory_buf: [4096]u8 = undefined; + const directory = directory_buf[0..try tmp.dir.realPath(testing.io, &directory_buf)]; + var path_buf: [4096]u8 = undefined; + const path = try std.fmt.bufPrint(&path_buf, "{s}/note.txt", .{directory}); + + const p = try withFile(gpa, "in memory\n"); + defer p.deinit(); + const serial = serialOf(p); + const ctl_node = Node.of(serial, .ctl); + const pane = p.panes[0].?; + + var name: [std.fs.max_path_bytes + 8]u8 = undefined; + _ = wr(p, Node.of(serial, .name), try std.fmt.bufPrint(&name, "{s}\n", .{path})); + try testing.expectEqual(Status.ok, wr(p, ctl_node, "get\n").reply.status); + try testing.expectEqualStrings("from disk\n", pane.file.?.content); + try testing.expect(!pane_files.dirtyOf(pane)); + try testing.expect(pane.file.?.history.undo_len > 0); + + _ = wr(p, Node.of(serial, .name), try std.fmt.bufPrint(&name, "{s}/missing.txt\n", .{directory})); + _ = wr(p, Node.of(serial, .body), "unsaved\n"); + try testing.expectEqual(E.NOENT, wr(p, ctl_node, "get\nexec Del\n").errno()); + try testing.expect(p.paneBySerial(serial) != null); + try testing.expectEqualStrings("from disk\nunsaved\n", pane.file.?.content); + try testing.expect(pane_files.dirtyOf(pane)); +} + +test "exec Save writes the named file through the host" { + const gpa = testing.allocator; + const p = try withFile(gpa, "one\ntwo\n"); + defer p.deinit(); + const serial = serialOf(p); + const pane = p.panes[0].?; + try testing.expectEqual(Status.ok, wr(p, Node.of(serial, .name), "/tmp/renamed.txt\n").reply.status); + try testing.expect(pane_files.dirtyOf(pane)); + const saved = wr(p, Node.of(serial, .ctl), "exec Save\n"); + try testing.expectEqual(Status.ok, saved.reply.status); + try testing.expect(saved.saved); + p.perform(.{ .save_file = .{ .pane = 0 } }); + try testing.expect(!pane_files.dirtyOf(pane)); + try testing.expectEqualStrings(pane.file.?.content, p.fallback.get("/tmp/renamed.txt").?); +} diff --git a/src/ninep/events.zig b/src/ninep/events.zig new file mode 100644 index 00000000..fb49e41b --- /dev/null +++ b/src/ninep/events.zig @@ -0,0 +1,558 @@ +//! Event streams: per-pane `event` records, the editor-wide `log`, and the +//! bounded queues that park a read until something happens. +const std = @import("std"); +const pardes = @import("../pardes.zig"); +const tree = @import("tree.zig"); +const pane_files = @import("pane.zig"); + +const Pardes = pardes.Pardes; +const Pane = pardes.Pane; +const MAX_PANES = pardes.MAX_PANES; +const Req = tree.Req; +const Reply = tree.Reply; +const E = tree.E; + +pub const queue_cap = 64 * 1024; + +/// Wall-clock seconds, or zero where the platform has no clock. +pub fn now() u32 { + if (comptime !pardes.hosted) return 0; + var ts: std.c.timespec = undefined; + if (std.c.clock_gettime(.REALTIME, &ts) != 0) return 0; + return std.math.cast(u32, ts.sec) orelse 0; +} + +pub const Queue = struct { + buf: std.ArrayList(u8) = .empty, + head: usize = 0, + + pub fn deinit(q: *Queue, gpa: std.mem.Allocator) void { + q.buf.deinit(gpa); + q.head = 0; + } + + pub fn push(q: *Queue, gpa: std.mem.Allocator, record: []const u8) void { + if (record.len > std.math.maxInt(u32)) return; + while (q.buf.items.len - q.head + record.len + 4 > queue_cap) { + if (q.peek() == null) return; + q.pop(); + } + q.compact(); + var head: [4]u8 = undefined; + std.mem.writeInt(u32, &head, @intCast(record.len), .little); + q.buf.appendSlice(gpa, &head) catch return; + q.buf.appendSlice(gpa, record) catch { + q.buf.shrinkRetainingCapacity(q.buf.items.len - 4); + return; + }; + } + + pub fn peek(q: *const Queue) ?[]const u8 { + const rest = q.buf.items[@min(q.head, q.buf.items.len)..]; + if (rest.len < 4) return null; + const len = std.mem.readInt(u32, rest[0..4], .little); + if (rest.len < 4 + len) return null; + return rest[4 .. 4 + len]; + } + + pub fn pop(q: *Queue) void { + const record = q.peek() orelse return; + q.head += 4 + record.len; + if (q.head == q.buf.items.len) { + q.buf.clearRetainingCapacity(); + q.head = 0; + } + } + + pub fn popFront(q: *Queue, n: usize) void { + const record = q.peek() orelse return; + if (n >= record.len) return q.pop(); + q.head += n; + std.mem.writeInt(u32, q.buf.items[q.head..][0..4], @intCast(record.len - n), .little); + } + + fn compact(q: *Queue) void { + if (q.head == 0 or q.head * 2 < q.buf.items.len) return; + const rest = q.buf.items.len - q.head; + std.mem.copyForwards(u8, q.buf.items[0..rest], q.buf.items[q.head..]); + q.buf.shrinkRetainingCapacity(rest); + q.head = 0; + } + + pub fn empty(q: *const Queue) bool { + return q.peek() == null; + } + + pub fn clearAndFree(q: *Queue, gpa: std.mem.Allocator) void { + q.buf.clearAndFree(gpa); + q.head = 0; + } +}; + +/// One record per read; `.again` parks the read until a record arrives. +pub fn readQueue(p: *Pardes, req: Req, q: *Queue) Reply { + const record = q.peek() orelse return .{ .tag = req.tag, .status = .again }; + if (req.size < record.len) return Reply.fail(req.tag, E.INVAL); + const out = p.fs.stage(p.gpa); + out.appendSlice(p.gpa, record) catch return Reply.fail(req.tag, E.NOMEM); + q.pop(); + return .{ .tag = req.tag, .payload = .{ .staged = @intCast(out.items.len) } }; +} + +// ---- the editor-wide log ---- + +pub const LogKind = enum { new, del, rename, save }; + +/// A pane installed now is announced by `announce` once the update that made +/// it has finished, when its name is known. +pub fn noteInstall(p: *Pardes, id: usize) void { + if (id < MAX_PANES) p.fs.panes[id].unannounced = true; +} + +/// A pane leaving; one never announced leaves silently. +pub fn noteRetire(p: *Pardes, id: usize, pane: *Pane) void { + if (id >= MAX_PANES) return; + if (p.fs.panes[id].unannounced) { + p.fs.panes[id].unannounced = false; + return; + } + noteLog(p, .del, pane); +} + +/// Called at the end of every update: reports the panes installed by it. +pub fn announce(p: *Pardes) void { + for (p.panes, 0..) |slot, id| { + const pf = &p.fs.panes[id]; + if (!pf.unannounced) continue; + pf.unannounced = false; + if (slot) |pane| noteLog(p, .new, pane); + } +} + +/// Records ` ` while a reader holds /log open. +pub fn noteLog(p: *Pardes, kind: LogKind, pane: *Pane) void { + if (p.fs.log_readers == 0) return; + var buf: [4096 + 64]u8 = undefined; + const name = pane_files.nameOf(pane); + const record = std.fmt.bufPrint(&buf, "{s} {d} {s}\n", .{ @tagName(kind), pane.serial, name[0..@min(name.len, 4096)] }) catch return; + p.fs.log.push(p.gpa, record); +} + +// ---- per-pane event records ---- + +pub const max_record_text = 256; + +pub const Action = enum(u8) { + body_delete = 'D', + tag_delete = 'd', + body_insert = 'I', + tag_insert = 'i', + body_look = 'L', + tag_look = 'l', + body_exec = 'X', + tag_exec = 'x', + + pub fn char(a: Action) u8 { + return @intFromEnum(a); + } + + pub fn fromChar(c: u8) ?Action { + return std.enums.fromInt(Action, c); + } + + pub fn onTag(a: Action) bool { + return @intFromEnum(a) >= 'a'; + } +}; + +pub const flag_builtin: u32 = 1; +pub const flag_expansion: u32 = 2; +pub const flag_filename: u32 = 4; +pub const flag_chorded: u32 = 8; + +pub fn formatRecord( + buf: []u8, + origin: u8, + action: Action, + q0: u32, + q1: u32, + flag: u32, + text: []const u8, +) []const u8 { + const sent = if (text.len >= max_record_text) text[0..0] else text; + return std.fmt.bufPrint(buf, "{c}{c}{d} {d} {d} {d} {s}\n", .{ + origin, + action.char(), + q0, + q1, + flag, + sent.len, + sent, + }) catch buf[0..0]; +} + +pub const Span = struct { at: u32, removed: u32, inserted: u32 }; + +pub fn diffSpan(old: []const u8, new: []const u8) Span { + const both = @min(old.len, new.len); + const stride = 64; + var head: usize = 0; + while (head + stride <= both and + std.mem.eql(u8, old[head..][0..stride], new[head..][0..stride])) head += stride; + while (head < both and old[head] == new[head]) head += 1; + var tail: usize = 0; + const rest = both - head; + while (tail + stride <= rest and std.mem.eql( + u8, + old[old.len - tail - stride ..][0..stride], + new[new.len - tail - stride ..][0..stride], + )) tail += stride; + while (tail < rest and old[old.len - 1 - tail] == new[new.len - 1 - tail]) tail += 1; + return .{ + .at = @intCast(head), + .removed = @intCast(old.len - tail - head), + .inserted = @intCast(new.len - tail - head), + }; +} + +pub fn noteReplace(p: *Pardes, id: usize, on_tag: bool, old: []const u8, new: []const u8) void { + if (!p.fs.scripted(id)) return; + const span = diffSpan(old, new); + if (span.removed == 0 and span.inserted == 0) return; + if (span.removed > 0) _ = noteAction( + p, + id, + if (on_tag) .tag_delete else .body_delete, + span.at, + span.at + span.removed, + 0, + "", + ); + if (span.inserted > 0) _ = noteAction( + p, + id, + if (on_tag) .tag_insert else .body_insert, + span.at, + span.at + span.inserted, + 0, + new[span.at..][0..span.inserted], + ); +} + +pub fn noteAction( + p: *Pardes, + id: usize, + action: Action, + q0: u32, + q1: u32, + flag: u32, + text: []const u8, +) bool { + if (!p.fs.scripted(id)) return false; + var buf: [max_record_text + 64]u8 = undefined; + const record = formatRecord(&buf, p.fs.origin, action, q0, q1, flag, text); + p.fs.panes[id].events.push(p.gpa, record); + return true; +} + +pub fn notePtyOutput(p: *Pardes, id: usize, bytes: []const u8) void { + if (id >= MAX_PANES or bytes.len == 0) return; + const pf = &p.fs.panes[id]; + if (pf.pty_readers == 0) return; + var off: usize = 0; + while (off < bytes.len) { + const n = @min(bytes.len - off, queue_cap / 2); + pf.pty_out.push(p.gpa, bytes[off..][0..n]); + off += n; + } +} + +const EventRecord = struct { action: Action, q0: u32, q1: u32 }; + +const EventReader = struct { + data: []const u8, + i: usize = 0, + + fn next(er: *EventReader) ?EventRecord { + if (er.i >= er.data.len) return null; + var i = er.i; + if (i + 2 > er.data.len) return null; + i += 1; + const action = Action.fromChar(er.data[i]) orelse return null; + i += 1; + const q0 = scanNumber(er.data, &i) orelse return null; + const q1 = scanNumber(er.data, &i) orelse return null; + while (i < er.data.len and er.data[i] == ' ') i += 1; + if (i >= er.data.len or er.data[i] != '\n') return null; + er.i = i + 1; + return .{ .action = action, .q0 = q0, .q1 = q1 }; + } +}; + +fn scanNumber(data: []const u8, i: *usize) ?u32 { + while (i.* < data.len and data[i.*] == ' ') i.* += 1; + const s = i.*; + var n: u64 = 0; + while (i.* < data.len and data[i.*] >= '0' and data[i.*] <= '9') : (i.* += 1) + n = @min(n * 10 + (data[i.*] - '0'), std.math.maxInt(u32)); + if (i.* == s) return null; + return @intCast(n); +} + +/// Writing a Look or Exec record back performs the action it names. +pub fn writeEvent(p: *Pardes, req: Req, id: usize) Reply { + const pane0 = p.panes[id] orelse return Reply.fail(req.tag, E.NOENT); + const serial = pane0.serial; + { + const body = pane_files.bodyOf(pane0); + const tag = pane_files.tagOf(p, pane0); + var check: EventReader = .{ .data = req.data }; + while (check.next()) |r| { + switch (r.action) { + .body_look, .tag_look, .body_exec, .tag_exec => {}, + else => return Reply.fail(req.tag, E.INVAL), + } + const n = if (r.action.onTag()) tag.len else body.len; + if (r.q0 > r.q1 or r.q1 > n) return Reply.fail(req.tag, E.INVAL); + } + if (check.i != req.data.len) return Reply.fail(req.tag, E.INVAL); + } + var run: EventReader = .{ .data = req.data }; + while (run.next()) |r| { + const live = p.paneBySerial(serial) orelse break; + const pane = p.panes[live].?; + const whole = if (r.action.onTag()) pane_files.tagOf(p, pane) else pane_files.bodyOf(pane); + const lo = @min(@as(usize, r.q0), whole.len); + const hi = @max(lo, @min(@as(usize, r.q1), whole.len)); + const text = p.scratch.allocator().dupe(u8, whole[lo..hi]) catch continue; + switch (r.action) { + .body_exec, .tag_exec => _ = p.execute(live, text), + .body_look, .tag_look => p.lookAt(live, text), + else => unreachable, + } + } + return .{ .tag = req.tag, .written = @intCast(req.data.len) }; +} + +// ---- tests ---- + +const testing = std.testing; +const th = @import("testing.zig"); +const call = th.call; +const rd = th.rd; +const wr = th.wr; +const withFile = th.withFile; +const serialOf = th.serialOf; +const Node = tree.Node; +const Status = tree.Status; + +test "event records are acme's bytes, one per read, and .again when empty" { + const gpa = testing.allocator; + const p = try withFile(gpa, "Msg fs-ran\n"); + defer p.deinit(); + const serial = serialOf(p); + const event = Node.of(serial, .event); + + _ = noteAction(p, 0, .body_exec, 1, 4, flag_builtin, "sg "); + try testing.expect(p.fs.panes[0].events.empty()); + + const h = call(p, .{ .tag = 10, .op = .open, .node = event }); + try testing.expect(h.reply.handle != 0); + try testing.expectEqual(@as(u16, 1), p.fs.listeners); + + try testing.expectEqual(Status.again, rd(p, event, 0, 4096).reply.status); + + p.fs.origin = 'M'; + _ = noteAction(p, 0, .body_exec, 1, 4, flag_builtin, "ell"); + _ = noteAction(p, 0, .body_delete, 0, 3, 0, ""); + try testing.expectEqualStrings("MX1 4 1 3 ell\n", rd(p, event, 0, 4096).bytes); + try testing.expectEqualStrings("MD0 3 0 0 \n", rd(p, event, 0, 4096).bytes); + try testing.expectEqual(Status.again, rd(p, event, 0, 4096).reply.status); + + _ = noteAction(p, 0, .body_look, 0, 3, flag_filename, "one"); + try testing.expectEqual(E.INVAL, rd(p, event, 0, 4).errno()); + try testing.expectEqualStrings("ML0 3 4 3 one\n", rd(p, event, 0, 4096).bytes); + + const big = "z" ** max_record_text; + _ = noteAction(p, 0, .body_exec, 0, max_record_text, 0, big); + try testing.expectEqualStrings("MX0 256 0 0 \n", rd(p, event, 0, 4096).bytes); + + _ = call(p, .{ .tag = 11, .op = .release, .node = event, .handle = h.reply.handle }); + try testing.expectEqual(@as(u16, 0), p.fs.listeners); +} + +fn drainEvents(p: *Pardes, node: u64, store: []u8, out: [][]const u8) [][]const u8 { + var used: usize = 0; + var n: usize = 0; + while (n < out.len) { + const a = rd(p, node, 0, 4096); + if (a.reply.status != .ok) break; + @memcpy(store[used..][0..a.bytes.len], a.bytes); + out[n] = store[used..][0..a.bytes.len]; + used += a.bytes.len; + n += 1; + } + return out[0..n]; +} + +test "a write through the filesystem is reported once, attributed to the file it came through" { + const gpa = testing.allocator; + const p = try withFile(gpa, "one\ntwo\n"); + defer p.deinit(); + const serial = serialOf(p); + const event = Node.of(serial, .event); + _ = call(p, .{ .tag = 40, .op = .open, .node = event }); + var store: [4096]u8 = undefined; + var slots: [16][]const u8 = undefined; + _ = drainEvents(p, event, &store, &slots); + + _ = wr(p, Node.of(serial, .body), "three\n"); + const body_recs = drainEvents(p, event, &store, &slots); + try testing.expect(body_recs.len >= 1); + try testing.expectEqualStrings("EI8 14 0 6 three\n\n", body_recs[0]); + for (body_recs[1..]) |r| { + try testing.expectEqual(@as(u8, 'E'), r[0]); + try testing.expect(Action.fromChar(r[1]).?.onTag()); + } + + _ = wr(p, Node.of(serial, .addr), "1"); + _ = wr(p, Node.of(serial, .data), "ONE\n"); + const data_recs = drainEvents(p, event, &store, &slots); + try testing.expectEqual(@as(usize, 2), data_recs.len); + try testing.expectEqualStrings("FD0 3 0 0 \n", data_recs[0]); + try testing.expectEqualStrings("FI0 3 0 3 ONE\n", data_recs[1]); + try testing.expectEqual(Status.again, rd(p, event, 0, 4096).reply.status); +} + +test "two event readers each count once, and the second closing leaves the first" { + const gpa = testing.allocator; + const p = try withFile(gpa, "x\n"); + defer p.deinit(); + const event = Node.of(serialOf(p), .event); + + _ = call(p, .{ .tag = 12, .op = .open, .node = event }); + _ = call(p, .{ .tag = 13, .op = .open, .node = event }); + try testing.expectEqual(@as(u16, 2), p.fs.panes[0].readers); + try testing.expectEqual(@as(u16, 2), p.fs.listeners); + + _ = call(p, .{ .tag = 14, .op = .release, .node = event }); + try testing.expectEqual(@as(u16, 1), p.fs.panes[0].readers); + try testing.expect(p.fs.scripted(0)); + + _ = call(p, .{ .tag = 15, .op = .release, .node = Node.of(serialOf(p), .body) }); + try testing.expectEqual(@as(u16, 1), p.fs.listeners); + + _ = call(p, .{ .tag = 16, .op = .release, .node = event }); + try testing.expectEqual(@as(u16, 0), p.fs.listeners); + try testing.expect(!p.fs.scripted(0)); + _ = call(p, .{ .tag = 17, .op = .release, .node = event }); + try testing.expectEqual(@as(u16, 0), p.fs.listeners); +} + +test "a pane deleted while its event file is open leaves no suppression behind" { + const gpa = testing.allocator; + const p = try withFile(gpa, "x\n"); + defer p.deinit(); + const serial = serialOf(p); + const event = Node.of(serial, .event); + _ = try th.newPane(p); + + const a = call(p, .{ .tag = 18, .op = .open, .node = event }); + const b = call(p, .{ .tag = 19, .op = .open, .node = event }); + try testing.expectEqual(@as(u16, 2), p.fs.listeners); + + _ = wr(p, Node.of(serial, .ctl), "exec Del\n"); + try testing.expect(p.paneBySerial(serial) == null); + try testing.expectEqual(@as(u16, 0), p.fs.listeners); + + _ = call(p, .{ .tag = 20, .op = .release, .node = event, .handle = a.reply.handle }); + _ = call(p, .{ .tag = 21, .op = .release, .node = event, .handle = b.reply.handle }); + try testing.expectEqual(@as(u16, 0), p.fs.listeners); + + try testing.expectEqual(E.NOENT, rd(p, event, 0, 64).errno()); + try testing.expectEqual(E.NOENT, rd(p, Node.of(serial, .body), 0, 64).errno()); + try testing.expectEqual(E.NOENT, wr(p, Node.of(serial, .ctl), "clean\n").errno()); + try testing.expectEqual(E.NOENT, call(p, .{ .tag = 22, .op = .open, .node = event }).errno()); +} + +test "writing an event record back performs the action it names" { + const gpa = testing.allocator; + const p = try withFile(gpa, "Msg fs-ran\n"); + defer p.deinit(); + const serial = serialOf(p); + const event = Node.of(serial, .event); + const pane = p.panes[0].?; + + const w = wr(p, event, "FX0 10\n"); + try testing.expectEqual(Status.ok, w.reply.status); + try testing.expectEqualStrings("fs-ran", pane.msg[0..pane.msg_len]); + + pane.msg_len = 0; + try testing.expectEqual(Status.ok, wr(p, event, "FX0 10\nFX0 10\n").reply.status); + try testing.expectEqualStrings("fs-ran", pane.msg[0..pane.msg_len]); + + pane.msg_len = 0; + for ([_][]const u8{ + "FX0 10\nFQ0 1\n", // unknown type character + "FX0 999\n", // out of range + "FX0 10", // no newline + "FX5 1\n", // q0 > q1 + "FD0 3\n", // a report, not a request + "F\n", + }) |bad| { + try testing.expectEqual(E.INVAL, wr(p, event, bad).errno()); + try testing.expectEqual(@as(usize, 0), pane.msg_len); + } + + _ = call(p, .{ .tag = 23, .op = .open, .node = event }); + p.fs.origin = 'K'; + _ = wr(p, event, "KX0 10\n"); + try testing.expectEqual(@as(u8, 'F'), p.fs.origin); +} + +test "the log parks until a pane is created, renamed, saved or deleted" { + const gpa = testing.allocator; + const p = try withFile(gpa, "logged\n"); + defer p.deinit(); + const log = @intFromEnum(tree.TopFile.log); + _ = try th.newPane(p); + try testing.expect(p.fs.log.empty()); + + const opened = call(p, .{ .tag = 1, .op = .open, .node = log }); + try testing.expectEqual(Status.ok, opened.reply.status); + try testing.expectEqual(@as(u16, 1), p.fs.log_readers); + try testing.expectEqual(Status.again, rd(p, log, 0, 4096).reply.status); + + const serial = try th.newPane(p); + const id = p.paneBySerial(serial).?; + var expected: [4200]u8 = undefined; + try testing.expectEqualStrings( + try std.fmt.bufPrint(&expected, "new {d} {s}\n", .{ serial, pane_files.nameOf(p.panes[id].?) }), + rd(p, log, 0, 4096).bytes, + ); + try testing.expectEqual(Status.ok, wr(p, Node.of(serial, .name), "/tmp/logged.txt\n").reply.status); + try testing.expectEqualStrings( + try std.fmt.bufPrint(&expected, "rename {d} /tmp/logged.txt\n", .{serial}), + rd(p, log, 0, 4096).bytes, + ); + const saving = wr(p, Node.of(serial, .ctl), "exec Save\n"); + try testing.expectEqual(Status.ok, saving.reply.status); + try testing.expect(saving.saved); + p.perform(.{ .save_file = .{ .pane = @intCast(id) } }); + try testing.expectEqualStrings( + try std.fmt.bufPrint(&expected, "save {d} /tmp/logged.txt\n", .{serial}), + rd(p, log, 0, 4096).bytes, + ); + try testing.expectEqual(Status.ok, wr(p, Node.of(serial, .ctl), "exec Del\n").reply.status); + try testing.expectEqualStrings( + try std.fmt.bufPrint(&expected, "del {d} /tmp/logged.txt\n", .{serial}), + rd(p, log, 0, 4096).bytes, + ); + try testing.expectEqual(Status.again, rd(p, log, 0, 4096).reply.status); + + _ = call(p, .{ .tag = 2, .op = .release, .node = log, .handle = opened.reply.handle }); + try testing.expectEqual(@as(u16, 0), p.fs.log_readers); + _ = try th.newPane(p); + try testing.expect(p.fs.log.empty()); + try testing.expectEqual(@as(usize, 0), p.fs.log.buf.capacity); +} diff --git a/src/ninep/pane.zig b/src/ninep/pane.zig new file mode 100644 index 00000000..b37ae645 --- /dev/null +++ b/src/ninep/pane.zig @@ -0,0 +1,840 @@ +//! The files under /pane//: name, body, tag, ctl, addr, data, xdata, +//! sel, errors and event. Terminal panes add pty/ (pty.zig). +const std = @import("std"); +const pardes = @import("../pardes.zig"); +const panes = @import("../panes.zig"); +const modal = @import("../modal.zig"); +const config = @import("../config.zig"); +const fs = @import("../fs.zig"); +const tree = @import("tree.zig"); +const events = @import("events.zig"); +const addressing = @import("addr.zig"); +const ctl = @import("ctl.zig"); +const pty = @import("pty.zig"); +const screen = @import("screen.zig"); + +const Pardes = pardes.Pardes; +const Pane = pardes.Pane; +const Req = tree.Req; +const Reply = tree.Reply; +const E = tree.E; +const PaneFile = tree.PaneFile; +const Node = tree.Node; + +/// Filesystem state a pane carries beside its editor state. +pub const State = struct { + addr: Range = .{}, + limit: ?Range = null, + readers: u16 = 0, + events: events.Queue = .{}, + nomark: bool = false, + noscroll: bool = false, + tag_snap: std.ArrayList(u8) = .empty, + pty_readers: u16 = 0, + pty_out: events.Queue = .{}, + /// Installed during this update; /log hears about it once the update ends + /// and the pane has its file, name and place. + unannounced: bool = false, + + pub const Range = struct { q0: u32 = 0, q1: u32 = 0 }; + + pub fn deinit(pf: *State, gpa: std.mem.Allocator) void { + pf.events.deinit(gpa); + pf.pty_out.deinit(gpa); + pf.tag_snap.deinit(gpa); + pf.* = .{}; + } +}; + +// ---- what a pane is ---- + +pub fn bodyOf(pane: *const Pane) []const u8 { + if (pane.file) |*f| return f.content; + return ""; +} + +pub fn fileOf(pane: *Pane) ?*panes.File.State { + return if (pane.file) |*f| f else null; +} + +pub fn tagOf(p: *Pardes, pane: *Pane) []const u8 { + return p.tagText(p.scratch.allocator(), pane) catch ""; +} + +pub fn dirOf(pane: *Pane) []const u8 { + if (pane.file) |*f| return std.fs.path.dirname(f.path) orelse "/"; + const cwd = pane.cwdSlice(); + return if (cwd.len > 0) cwd else "/"; +} + +pub fn dirtyOf(pane: *const Pane) bool { + const f = if (pane.file) |*x| x else return false; + if (!panes.Output.fileTraits(f.output).saves) return false; + return f.revision != f.saved_revision; +} + +/// The pane's name: its file, its document, or a terminal's directory. +pub fn nameOf(pane: *const Pane) []const u8 { + if (pane.file) |*f| return f.path; + if (pane.pdfPath()) |path| return path; + if (pane.image) |state| return state.path; + const cwd = pane.cwdSlice(); + return if (cwd.len > 0) cwd else "/"; +} + +pub fn kindOf(pane: *const Pane) []const u8 { + if (pane.file != null) return "text"; + if (pane.pdfPath() != null) return "pdf"; + if (pane.image != null) return "image"; + return "term"; +} + +pub fn mtimeOf(p: *Pardes, pane: *const Pane) u32 { + if (pane.file) |*f| if (f.mtime != 0) return f.mtime; + return p.fs.started; +} + +pub fn clip(n: usize) u32 { + return std.math.cast(u32, n) orelse std.math.maxInt(u32); +} + +fn cellOf(row: i32, col: i32) modal.Cursor { + return .{ .row = @intCast(@max(0, row)), .col = @intCast(@max(0, col)) }; +} + +pub fn dotOf(pane: *Pane) State.Range { + const text = bodyOf(pane); + const head = modal.offsetAt(text, cellOf(pane.cur_row, pane.cur_col)); + if (!pane.vsel.active) return .{ .q0 = clip(head), .q1 = clip(head) }; + const anchor = modal.offsetAt(text, cellOf(pane.vsel.row, pane.vsel.col)); + var hi = @max(head, anchor); + if (hi < text.len) hi = modal.nextGrapheme(text, hi); + return .{ .q0 = clip(@min(head, anchor)), .q1 = clip(hi) }; +} + +pub fn setDot(pane: *Pane, r: State.Range) void { + const text = bodyOf(pane); + const q0 = @min(@as(usize, r.q0), text.len); + const q1 = @max(q0, @min(@as(usize, r.q1), text.len)); + const a = modal.positionAt(text, q0); + pane.vsel = .{ .active = q1 > q0, .row = @intCast(a.row), .col = @intCast(a.col), .explicit = true }; + const h = modal.positionAt(text, if (q1 > q0) modal.prevGrapheme(text, q1) else q0); + pane.cur_row = @intCast(h.row); + pane.cur_col = @intCast(h.col); + pane.cur_pinned = true; + pane.sticky_col = -1; + pane.msel.active = false; + pane.ensureCursorVisible(); +} + +pub fn showOffset(pane: *Pane, off: usize) void { + const text = bodyOf(pane); + const c = modal.positionAt(text, @min(off, text.len)); + pane.cur_row = @intCast(c.row); + pane.cur_col = @intCast(c.col); + pane.cur_pinned = true; + pane.sticky_col = -1; + pane.ensureCursorVisible(); +} + +pub fn clampAddr(pf: *State, len: usize) void { + const n = clip(len); + pf.addr.q0 = @min(pf.addr.q0, n); + pf.addr.q1 = @min(pf.addr.q1, n); + if (pf.limit) |*l| { + l.q0 = @min(l.q0, n); + l.q1 = @min(l.q1, n); + } +} + +fn shiftBy(r: State.Range, at: u32, removed: u32, inserted: u32) State.Range { + return .{ .q0 = shiftOne(r.q0, at, removed, inserted), .q1 = shiftOne(r.q1, at, removed, inserted) }; +} + +fn shiftOne(v: u32, at: u32, removed: u32, inserted: u32) u32 { + if (v <= at) return v; + if (v <= at +| removed) return at +| inserted; + return v - removed +| inserted; +} + +pub fn wholeUtf8(data: []const u8) usize { + var i = data.len; + var back: usize = 0; + while (i > 0 and back < 4) : (back += 1) { + i -= 1; + const c = data[i]; + if (c < 0x80) return data.len; + if (c & 0xC0 == 0xC0) { + const need = std.unicode.utf8ByteSequenceLength(c) catch return data.len; + if (i + need <= data.len or i == 0) return data.len; + return i; + } + } + return data.len; +} + +pub fn spliceBody(p: *Pardes, id: usize, pane: *Pane, q0: usize, q1: usize, bytes: []const u8) ?usize { + const f = fileOf(pane) orelse return null; + const take = if (bytes.len == 0) 0 else wholeUtf8(bytes); + const lo = @min(q0, f.content.len); + const hi = @max(lo, @min(q1, f.content.len)); + const new = p.gpa.alloc(u8, f.content.len - (hi - lo) + take) catch return null; + @memcpy(new[0..lo], f.content[0..lo]); + @memcpy(new[lo..][0..take], bytes[0..take]); + @memcpy(new[lo + take ..], f.content[hi..]); + if (!p.fs.panes[id].nomark) panes.File.pushUndo(p, pane); + panes.File.setContent(p, f, new); + return take; +} + +// ---- sizes reported by stat ---- + +pub fn fileSize(p: *Pardes, id: usize, f: PaneFile) u64 { + const pane = p.panes[id] orelse return 0; + return switch (f) { + .body, .data, .xdata => bodyOf(pane).len, + .tag => tagOf(p, pane).len, + .name => nameOf(pane).len + 1, + .ctl => ctl: { + var buf: [ctl.pane_text_cap]u8 = undefined; + break :ctl ctl.paneText(p, pane, &buf).len; + }, + .sel => sel: { + const d = dotOf(pane); + break :sel @max(d.q0, d.q1) - d.q0; + }, + .dir, .addr, .errors, .event, .pty, .pty_ctl, .pty_status, .pty_data => 0, + }; +} + +// ---- the index ---- + +pub fn stageIndexLine(p: *Pardes, out: *std.ArrayList(u8), pane: *Pane) void { + out.print(p.gpa, "{d} {s} {d} {s}\n", .{ pane.serial, kindOf(pane), @intFromBool(dirtyOf(pane)), nameOf(pane) }) catch {}; +} + +pub fn indexLen(p: *Pardes) u64 { + var n: u64 = 0; + var last: u32 = 0; + while (tree.nextSerialAfter(p, last)) |serial| { + last = serial; + const pane = p.panes[p.paneBySerial(serial).?].?; + var digits: [16]u8 = undefined; + n += (std.fmt.bufPrint(&digits, "{d}", .{serial}) catch unreachable).len; + n += 1 + kindOf(pane).len + 3 + nameOf(pane).len + 1; + } + return n; +} + +// ---- reads ---- + +pub fn read(p: *Pardes, req: Req, id: usize, pane: *Pane, file: PaneFile) Reply { + const pf = &p.fs.panes[id]; + return switch (file) { + .name => name: { + const out = p.fs.stage(p.gpa); + out.appendSlice(p.gpa, nameOf(pane)) catch {}; + out.append(p.gpa, '\n') catch {}; + break :name tree.stagedReply(p, req); + }, + .body => readBody(p, req, id, pane), + .tag => tag: { + const out = p.fs.stage(p.gpa); + out.appendSlice(p.gpa, tagOf(p, pane)) catch {}; + break :tag tree.stagedReply(p, req); + }, + .ctl => ctl.readPane(p, req, pane), + .addr => addr: { + clampAddr(pf, bodyOf(pane).len); + const out = p.fs.stage(p.gpa); + out.print(p.gpa, "{d:>11} {d:>11} ", .{ pf.addr.q0, pf.addr.q1 }) catch {}; + break :addr tree.stagedReply(p, req); + }, + .data => readData(req, id, pane, pf, false), + .xdata => readData(req, id, pane, pf, true), + .sel => readSel(req, id, pane), + .event => events.readQueue(p, req, &pf.events), + .pty_status => pty.readStatus(p, req, id, pane), + .pty_data => pty.readData(p, req, pf), + .dir, .errors, .pty, .pty_ctl => Reply.fail(req.tag, E.PERM), + }; +} + +fn readBody(p: *Pardes, req: Req, id: usize, pane: *Pane) Reply { + if (pane.file != null) { + const text = bodyOf(pane); + const off = @min(req.off, text.len); + const n = @min(text.len - off, req.size); + return .{ .tag = req.tag, .payload = .{ .region = .{ + .pane = @intCast(id), + .serial = pane.serial, + .off = clip(off), + .len = clip(n), + } } }; + } + if (req.handle != 0 and pane.isTerminal()) return screen.readSnapshot(p, req, pane); + const text = panes.Terminal.screenTextAlloc(pane, p.gpa) catch + return Reply.fail(req.tag, E.NOMEM); + defer p.gpa.free(text); + const out = p.fs.stage(p.gpa); + out.appendSlice(p.gpa, text) catch return Reply.fail(req.tag, E.NOMEM); + return tree.stagedReply(p, req); +} + +fn readData(req: Req, id: usize, pane: *Pane, pf: *State, stop_at_end: bool) Reply { + const text = bodyOf(pane); + clampAddr(pf, text.len); + const q0: usize = pf.addr.q0; + const hi: usize = if (stop_at_end) @max(q0, @as(usize, pf.addr.q1)) else text.len; + var end = @min(hi, q0 +| req.size); + end = @max(q0, modal.graphemeStart(text, end)); + pf.addr.q0 = clip(end); + if (!stop_at_end) pf.addr.q1 = clip(end); + if (pane.file == null) return .{ .tag = req.tag }; + return .{ .tag = req.tag, .payload = .{ .region = .{ + .pane = @intCast(id), + .serial = pane.serial, + .off = clip(q0), + .len = clip(end - q0), + } } }; +} + +fn readSel(req: Req, id: usize, pane: *Pane) Reply { + if (pane.file == null) return .{ .tag = req.tag }; + const text = bodyOf(pane); + const d = dotOf(pane); + const lo = @min(@as(usize, d.q0), text.len); + const hi = @max(lo, @min(@as(usize, d.q1), text.len)); + const off = @min(req.off, hi - lo); + const n = @min(hi - lo - off, req.size); + return .{ .tag = req.tag, .payload = .{ .region = .{ + .pane = @intCast(id), + .serial = pane.serial, + .off = clip(lo + off), + .len = clip(n), + } } }; +} + +// ---- writes ---- + +pub fn write(p: *Pardes, req: Req, id: usize, pane: *Pane, file: PaneFile) Reply { + return switch (file) { + .name => writeName(p, req, id, pane), + .body => writeBody(p, req, id, pane), + .tag => writeTag(p, req, pane), + .ctl => ctl.writePane(p, req, pane.serial), + .addr => writeAddr(p, req, id, pane), + .data, .xdata => writeData(p, req, id, pane), + .sel => writeSel(p, req, id, pane), + .event => events.writeEvent(p, req, id), + .errors => if (appendErrors(p, id, req.data)) |took| + .{ .tag = req.tag, .written = @intCast(took) } + else + Reply.fail(req.tag, E.IO), + .pty_ctl => pty.writeCtl(p, req, id), + .pty_data => pty.writeData(p, req, id), + .dir, .pty, .pty_status => Reply.fail(req.tag, E.PERM), + }; +} + +fn writeBody(p: *Pardes, req: Req, id: usize, pane: *Pane) Reply { + if (req.data.len == 0) return .{ .tag = req.tag, .written = 0 }; + if (pane.file == null) { + const take = wholeUtf8(req.data); + p.emitWrite(id, req.data[0..take]); + return .{ .tag = req.tag, .written = @intCast(take) }; + } + const at = bodyOf(pane).len; + const take = spliceBody(p, id, pane, at, at, req.data) orelse + return Reply.fail(req.tag, E.NOMEM); + if (!p.fs.panes[id].noscroll) showOffset(pane, at + take); + return .{ .tag = req.tag, .written = @intCast(take) }; +} + +fn writeTag(p: *Pardes, req: Req, pane: *Pane) Reply { + if (req.data.len == 0) return .{ .tag = req.tag, .written = 0 }; + p.seedTail(pane); + const room = pane.tag_tail.len - pane.tag_tail_len; + if (room == 0) return Reply.fail(req.tag, E.NOSPC); + const take = wholeUtf8(req.data[0..@min(req.data.len, room)]); + @memcpy(pane.tag_tail[pane.tag_tail_len..][0..take], req.data[0..take]); + pane.tag_tail_len += take; + pane.tag_init = true; + return .{ .tag = req.tag, .written = @intCast(take) }; +} + +fn writeData(p: *Pardes, req: Req, id: usize, pane: *Pane) Reply { + if (fileOf(pane) == null) return Reply.fail(req.tag, E.INVAL); + const pf = &p.fs.panes[id]; + clampAddr(pf, bodyOf(pane).len); + const q0: usize = pf.addr.q0; + const q1: usize = @max(q0, @as(usize, pf.addr.q1)); + const before = dotOf(pane); + const take = spliceBody(p, id, pane, q0, q1, req.data) orelse + return Reply.fail(req.tag, E.NOMEM); + setDot(pane, shiftBy(before, clip(q0), clip(q1 - q0), clip(take))); + pf.addr = .{ .q0 = clip(q0 + take), .q1 = clip(q0 + take) }; + if (!pf.noscroll) showOffset(pane, q0 + take); + return .{ .tag = req.tag, .written = @intCast(take) }; +} + +fn writeSel(p: *Pardes, req: Req, id: usize, pane: *Pane) Reply { + if (fileOf(pane) == null) return Reply.fail(req.tag, E.INVAL); + const d = dotOf(pane); + const q0: usize = d.q0; + const q1: usize = @max(q0, @as(usize, d.q1)); + const take = spliceBody(p, id, pane, q0, q1, req.data) orelse + return Reply.fail(req.tag, E.NOMEM); + setDot(pane, .{ .q0 = clip(q0 + take), .q1 = clip(q0 + take) }); + return .{ .tag = req.tag, .written = @intCast(take) }; +} + +fn writeAddr(p: *Pardes, req: Req, id: usize, pane: *Pane) Reply { + const pf = &p.fs.panes[id]; + const text = bodyOf(pane); + clampAddr(pf, text.len); + const expr = std.mem.trimEnd(u8, req.data, "\n"); + var a: addressing.Addr = .{ .text = text, .lim = pf.limit, .expr = expr }; + const r = a.address(pf.addr) orelse return Reply.fail(req.tag, E.INVAL); + if (a.i < expr.len) return Reply.fail(req.tag, E.INVAL); + pf.addr = r; + return .{ .tag = req.tag, .written = @intCast(req.data.len) }; +} + +/// Writing `name` renames the buffer: a relative name resolves against the +/// pane's directory, as the tag's name field does. +fn writeName(p: *Pardes, req: Req, id: usize, pane: *Pane) Reply { + const name = std.mem.trim(u8, req.data, " \t\r\n"); + if (name.len == 0) return Reply.fail(req.tag, E.INVAL); + for (name) |c| if (c < ' ') return Reply.fail(req.tag, E.INVAL); + if (fileOf(pane) == null) return Reply.fail(req.tag, E.PERM); + const full = std.fs.path.resolvePosix(p.scratch.allocator(), &.{ pardes.Pardes.paneDir(pane), name }) catch + return Reply.fail(req.tag, E.NOMEM); + if (!std.fs.path.isAbsolute(full) or full.len >= 4096) return Reply.fail(req.tag, E.INVAL); + nameBuffer(p, id, full, false) catch |err| return Reply.fail(req.tag, switch (err) { + error.OutOfMemory => E.NOMEM, + else => E.INVAL, + }); + return .{ .tag = req.tag, .written = @intCast(req.data.len) }; +} + +/// Change a buffer's absolute name without writing or renaming a disk file. +/// Tag editing preserves user commands; the filesystem's rename resets its tail. +pub fn nameBuffer(p: *Pardes, id: usize, full: []const u8, preserve_tag: bool) !void { + const pane = p.panes[id] orelse return error.NoPane; + const f = fileOf(pane) orelse return error.NotFile; + if (!std.fs.path.isAbsolute(full) or full.len == 0 or full.len >= 4096) + return error.InvalidName; + for (full) |c| if (c < ' ') return error.InvalidName; + if (std.mem.eql(u8, f.path, full)) return; + const copy = try p.gpa.dupe(u8, full); + p.gpa.free(f.path); + f.path = copy; + if (panes.Output.fileTraits(f.output).saves) { + f.output = null; + pane.clearCwd(); + if (!preserve_tag) { + pane.tag_init = false; + pane.tag_tail_len = 0; + } + f.saved_revision = f.revision -% 1; + f.watch_after_save = fs.localPath(full) != null; + } + if (f.highlights.len > 0) p.tree_sitter_gpa.free(f.highlights); + f.highlights = &.{}; + f.highlight_start = 0; + f.syntax_dirty = true; + f.context_revision = null; + pane.context_rows = 0; + pane.wrap_n = 0; + p.invalidateLookHover(id); + p.emit(.{ .watch = .{ .pane = @intCast(id), .on = false } }); + events.noteLog(p, .rename, pane); +} + +/// Diagnostics go to the +Errors buffer of the pane's directory. +pub fn appendErrors(p: *Pardes, id: usize, text: []const u8) ?usize { + if (text.len == 0) return 0; + const pane = p.panes[id] orelse return null; + const dir = dirOf(pane); + for (p.panes, 0..) |slot, i| { + const q = slot orelse continue; + const qf = fileOf(q) orelse continue; + const o = qf.output orelse continue; + if (std.meta.activeTag(o.from) != .errors) continue; + if (!std.mem.eql(u8, std.fs.path.dirname(qf.path) orelse "", dir)) continue; + return spliceBody(p, i, q, qf.content.len, qf.content.len, text); + } + const free = p.freeSlot() orelse return null; + const content = p.gpa.dupe(u8, text) catch return null; + const np = panes.Output.open(p, free, dir, .errors, "", content) catch { + p.gpa.free(content); + return null; + }; + p.placeDoc(id, free, np); + return text.len; +} + +/// Truncation empties a body; every other setattr just answers fresh attributes. +pub fn truncate(p: *Pardes, id: usize, pane: *Pane, file: PaneFile) tree.Status { + switch (file) { + .body, .data, .xdata => if (fileOf(pane) != null) { + _ = spliceBody(p, id, pane, 0, bodyOf(pane).len, "") orelse return .err; + p.fs.panes[id].addr = .{}; + setDot(pane, .{}); + }, + else => {}, + } + return .ok; +} + +// ---- tests ---- + +const testing = std.testing; +const th = @import("testing.zig"); +const call = th.call; +const rd = th.rd; +const wr = th.wr; +const withFile = th.withFile; +const serialOf = th.serialOf; +const Status = tree.Status; + +test "index lists serial kind dirty flag and name and stat reports its length" { + const gpa = testing.allocator; + const p = try withFile(gpa, "hello\nthere\n"); + defer p.deinit(); + const pane = p.panes[0].?; + const index = @intFromEnum(tree.TopFile.index); + + const a = rd(p, index, 0, 4096); + try testing.expectEqual(Status.ok, a.reply.status); + var want: [64]u8 = undefined; + try testing.expectEqualStrings(try std.fmt.bufPrint(&want, "{d} text 0 /test.txt\n", .{pane.serial}), a.bytes); + const stat = call(p, .{ .tag = 1, .op = .getattr, .node = index }); + try testing.expectEqual(@as(u64, a.bytes.len), stat.reply.attr.size); + try testing.expectEqual(@as(u16, 0o444), stat.reply.attr.mode); + + pane.file.?.saved_revision = pane.file.?.revision -% 1; + try testing.expectEqualStrings(try std.fmt.bufPrint(&want, "{d} text 1 /test.txt\n", .{pane.serial}), rd(p, index, 0, 4096).bytes); + const mid = rd(p, index, 2, 4); + try testing.expectEqualStrings("text", mid.bytes); + + const serial = try th.newPane(p); + const both = rd(p, index, 0, 4096); + try testing.expectEqual(@as(u64, both.bytes.len), indexLen(p)); + var expected: [4200]u8 = undefined; + const made = p.panes[p.paneBySerial(serial).?].?; + try testing.expect(std.mem.endsWith(u8, both.bytes, try std.fmt.bufPrint(&expected, "\n{d} text 0 {s}\n", .{ serial, nameOf(made) }))); +} + +test "a terminal is listed as term with its directory as name" { + const p = try th.withTerm(testing.allocator); + defer p.deinit(); + const pane = p.panes[0].?; + p.setCwd(0, "/work/dir"); + var want: [64]u8 = undefined; + try testing.expectEqualStrings( + try std.fmt.bufPrint(&want, "{d} term 0 /work/dir\n", .{pane.serial}), + rd(p, @intFromEnum(tree.TopFile.index), 0, 4096).bytes, + ); + try testing.expectEqualStrings("/work/dir\n", rd(p, Node.of(pane.serial, .name), 0, 4096).bytes); + try testing.expectEqual(E.PERM, wr(p, Node.of(pane.serial, .name), "/elsewhere\n").errno()); +} + +test "body reads at any offset and writes append" { + const gpa = testing.allocator; + const p = try withFile(gpa, "one\ntwo\n"); + defer p.deinit(); + const serial = serialOf(p); + const body = Node.of(serial, .body); + + try testing.expectEqualStrings("one\ntwo\n", rd(p, body, 0, 100).bytes); + try testing.expectEqualStrings("two\n", rd(p, body, 4, 100).bytes); + try testing.expectEqualStrings("wo", rd(p, body, 5, 2).bytes); + try testing.expectEqualStrings("", rd(p, body, 999, 2).bytes); + try testing.expect(rd(p, body, 0, 100).bytes.ptr == p.panes[0].?.file.?.content.ptr); + + const w = call(p, .{ .tag = 5, .op = .write, .node = body, .off = 0, .data = "three\n" }); + try testing.expectEqual(@as(u32, 6), w.reply.written); + try testing.expectEqualStrings("one\ntwo\nthree\n", p.panes[0].?.file.?.content); + + const short = wr(p, body, "a\xC3"); + try testing.expectEqual(@as(u32, 1), short.reply.written); + try testing.expectEqualStrings("one\ntwo\nthree\na", p.panes[0].?.file.?.content); + + const stat = call(p, .{ .tag = 6, .op = .getattr, .node = body }); + try testing.expectEqual(@as(u64, "one\ntwo\nthree\na".len), stat.reply.attr.size); + try testing.expectEqual(@as(u16, 0o666), stat.reply.attr.mode); + try testing.expect(stat.reply.attr.mtime >= p.fs.started); +} + +test "a body write to a terminal pane types at its shell" { + const gpa = testing.allocator; + const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 40, .rows = 10 }); + defer p.deinit(); + while (p.nextEffect()) |_| {} + const pane = p.panes[0].?; + try testing.expect(pane.isTerminal()); + + const a = wr(p, Node.of(pane.serial, .body), "ls -l\r"); + try testing.expectEqual(@as(u32, 6), a.reply.written); + try testing.expectEqualStrings("ls -l\r", a.pty()); + + const r = rd(p, Node.of(pane.serial, .body), 0, 64); + try testing.expectEqual(Status.ok, r.reply.status); +} + +test "tag reads the whole tag and writes append to the editable tail" { + const gpa = testing.allocator; + const p = try withFile(gpa, "x\n"); + defer p.deinit(); + const pane = p.panes[0].?; + const node = Node.of(pane.serial, .tag); + + const whole = rd(p, node, 0, 4096); + try testing.expect(std.mem.startsWith(u8, whole.bytes, "/test.txt")); + try testing.expect(std.mem.indexOf(u8, whole.bytes, "Del") != null); + try testing.expectEqual(@as(u64, whole.bytes.len), call(p, .{ .tag = 1, .op = .getattr, .node = node }).reply.attr.size); + + const before = rd(p, node, 0, 4096).bytes.len; + const w = wr(p, node, " Mine"); + try testing.expectEqual(@as(u32, 5), w.reply.written); + try testing.expect(std.mem.endsWith(u8, pane.tag_tail[0..pane.tag_tail_len], " Mine")); + const after = rd(p, node, 0, 4096); + try testing.expectEqual(before + 5, after.bytes.len); + try testing.expect(std.mem.endsWith(u8, after.bytes, " Mine")); + + pane.tag_tail_len = pane.tag_tail.len; + try testing.expectEqual(E.NOSPC, wr(p, node, "x").errno()); +} + +test "data and xdata read from addr, move it, and write through it" { + const gpa = testing.allocator; + const p = try withFile(gpa, "one\ntwo\n"); + defer p.deinit(); + const serial = serialOf(p); + const addr = Node.of(serial, .addr); + const data = Node.of(serial, .data); + const xdata = Node.of(serial, .xdata); + + _ = wr(p, addr, "#0"); + try testing.expectEqualStrings("one", rd(p, data, 0, 3).bytes); + try testing.expectEqual(@as(u32, 3), p.fs.panes[0].addr.q0); + try testing.expectEqual(@as(u32, 3), p.fs.panes[0].addr.q1); + + _ = wr(p, addr, "1"); + try testing.expectEqualStrings("one\n", rd(p, xdata, 0, 100).bytes); + _ = wr(p, addr, "1"); + try testing.expectEqualStrings("one\ntwo\n", rd(p, data, 0, 100).bytes); + + _ = wr(p, addr, "1"); + const w = wr(p, data, "ONE\n"); + try testing.expectEqual(@as(u32, 4), w.reply.written); + try testing.expectEqualStrings("ONE\ntwo\n", p.panes[0].?.file.?.content); + try testing.expectEqual(@as(u32, 4), p.fs.panes[0].addr.q0); +} + +test "data never splits a grapheme, in either direction" { + const gpa = testing.allocator; + const p = try withFile(gpa, "\u{00e9}x\n"); + defer p.deinit(); + const serial = serialOf(p); + _ = wr(p, Node.of(serial, .addr), "#0"); + try testing.expectEqualStrings("", rd(p, Node.of(serial, .data), 0, 1).bytes); + _ = wr(p, Node.of(serial, .addr), "#0"); + try testing.expectEqualStrings("\u{00e9}", rd(p, Node.of(serial, .data), 0, 2).bytes); + + _ = wr(p, Node.of(serial, .addr), "#0"); + try testing.expectEqual(@as(u32, 1), wr(p, Node.of(serial, .data), "a\xC3").reply.written); +} + +test "sel reads the selection and writing sel replaces it" { + const gpa = testing.allocator; + const p = try withFile(gpa, "one\ntwo\n"); + defer p.deinit(); + const serial = serialOf(p); + const ctl_node = Node.of(serial, .ctl); + const sel = Node.of(serial, .sel); + + _ = wr(p, Node.of(serial, .addr), "#0,#3"); + try testing.expectEqual(Status.ok, wr(p, ctl_node, "dot=addr\n").reply.status); + try testing.expectEqualStrings("one", rd(p, sel, 0, 100).bytes); + try testing.expectEqual(@as(u64, 3), call(p, .{ .tag = 1, .op = .getattr, .node = sel }).reply.attr.size); + + _ = wr(p, ctl_node, "addr=dot\n"); + try testing.expectEqual(@as(u32, 0), p.fs.panes[0].addr.q0); + try testing.expectEqual(@as(u32, 3), p.fs.panes[0].addr.q1); + + try testing.expectEqual(Status.ok, wr(p, sel, "ONE").reply.status); + try testing.expectEqualStrings("ONE\ntwo\n", p.panes[0].?.file.?.content); + _ = wr(p, sel, "!"); + try testing.expectEqualStrings("ONE!\ntwo\n", p.panes[0].?.file.?.content); + try testing.expectEqual(@as(u64, 0), call(p, .{ .tag = 2, .op = .getattr, .node = sel }).reply.attr.size); +} + +test "name reads the file name and writing it promotes a scratch without touching its body" { + const gpa = testing.allocator; + const p = try withFile(gpa, "opener\n"); + defer p.deinit(); + const serial = try th.newPane(p); + const pane = p.panes[p.paneBySerial(serial).?].?; + const name = Node.of(serial, .name); + const body = Node.of(serial, .body); + var scratch_name: [4200]u8 = undefined; + const scratch_line = try std.fmt.bufPrint(&scratch_name, "{s}\n", .{nameOf(pane)}); + try testing.expectEqualStrings(scratch_line, rd(p, name, 0, 4096).bytes); + try testing.expectEqual(@as(u64, scratch_line.len), call(p, .{ .tag = 1, .op = .getattr, .node = name }).reply.attr.size); + _ = wr(p, body, "scratch "); + _ = wr(p, body, "work\n"); + const undo_len = pane.file.?.history.undo_len; + var tmp = testing.tmpDir(.{}); + defer tmp.cleanup(); + try tmp.dir.writeFile(testing.io, .{ .sub_path = "renamed.zig", .data = "existing target\n" }); + var directory_buf: [4096]u8 = undefined; + const directory = directory_buf[0..try tmp.dir.realPath(testing.io, &directory_buf)]; + var path_buffer: [4096]u8 = undefined; + const path = try std.fmt.bufPrint(&path_buffer, "{s}/renamed.zig", .{directory}); + var line: [4104]u8 = undefined; + const renamed = wr(p, name, try std.fmt.bufPrint(&line, "{s}\n", .{path})); + try testing.expectEqual(Status.ok, renamed.reply.status); + try testing.expectEqual(false, renamed.watch.?); + try testing.expectEqualStrings("scratch work\n", pane.file.?.content); + try testing.expectEqual(undo_len, pane.file.?.history.undo_len); + try testing.expect(pane.file.?.output == null and dirtyOf(pane)); + try testing.expect(pane.file.?.watch_after_save); + try testing.expectEqualStrings(path, std.mem.trimEnd(u8, rd(p, name, 0, 4096).bytes, "\n")); + const target = try fs.readFile(gpa, path); + defer gpa.free(target); + try testing.expectEqualStrings("existing target\n", target); + for ([_][]const u8{ "", "\n", "bad\x01name\n" }) |bad| + try testing.expectEqual(E.INVAL, wr(p, name, bad).errno()); + try testing.expectEqualStrings(path, pane.file.?.path); + try testing.expectEqual(Status.ok, wr(p, name, "two words.zig\n").reply.status); + const spaced = try std.fmt.bufPrint(&path_buffer, "{s}/two words.zig", .{directory}); + try testing.expectEqualStrings(spaced, pane.file.?.path); +} + +test "name refreshes cached syntax for unchanged contents" { + if (!pardes.syntax.enabled) return error.SkipZigTest; + pardes.syntax.start(testing.allocator); + defer pardes.syntax.stop(); + const p = try withFile(testing.allocator, "fn check() void {}\n"); + defer p.deinit(); + const pane = p.panes[0].?; + panes.File.refreshHighlights(p); + try testing.expectEqual(@as(usize, 0), pane.file.?.highlights.len); + try testing.expectEqual(Status.ok, wr(p, Node.of(pane.serial, .name), "renamed.zig\n").reply.status); + panes.File.refreshHighlights(p); + try testing.expect(pane.file.?.highlights.len >= 2); + try testing.expectEqual(@intFromEnum(pardes.syntax.Syn.keyword), pane.file.?.highlights[0]); + try testing.expectEqual(@intFromEnum(pardes.syntax.Syn.keyword), pane.file.?.highlights[1]); + try testing.expectEqualStrings("fn check() void {}\n", pane.file.?.content); +} + +test "relative names use the file directory and can name a new target" { + const gpa = testing.allocator; + const p = try withFile(gpa, "retained body\n"); + defer p.deinit(); + var tmp = testing.tmpDir(.{}); + defer tmp.cleanup(); + try tmp.dir.writeFile(testing.io, .{ .sub_path = "note.txt", .data = "from pane directory\n" }); + var directory_buf: [4096]u8 = undefined; + const directory = directory_buf[0..try tmp.dir.realPath(testing.io, &directory_buf)]; + const pane = p.panes[0].?; + const name = Node.of(pane.serial, .name); + const ctl_node = Node.of(pane.serial, .ctl); + var line: [4140]u8 = undefined; + try testing.expectEqual(Status.ok, wr(p, name, try std.fmt.bufPrint(&line, "{s}/old.txt\n", .{directory})).reply.status); + try testing.expectEqual(Status.ok, wr(p, name, "child/../note.txt\n").reply.status); + try testing.expectEqual(Status.ok, wr(p, ctl_node, "get\n").reply.status); + try testing.expectEqualStrings("from pane directory\n", pane.file.?.content); + try testing.expectEqualStrings(directory, Pardes.paneDir(pane)); + try testing.expectEqual(Status.ok, wr(p, name, "./created.txt\n").reply.status); + var expected_buf: [4096]u8 = undefined; + const expected = try std.fmt.bufPrint(&expected_buf, "{s}/created.txt", .{directory}); + try testing.expectEqualStrings(expected, pane.file.?.path); + try testing.expect(dirtyOf(pane)); +} + +test "relative names follow inherited scratch and virtual directories" { + const p = try withFile(testing.allocator, "source body\n"); + defer p.deinit(); + const source = p.panes[0].?; + try testing.expectEqual(Status.ok, wr(p, Node.of(source.serial, .name), "/project/src/source.zig\n").reply.status); + const serial = try th.newPane(p); + const scratch = p.panes[p.paneBySerial(serial).?].?; + const name = Node.of(serial, .name); + try testing.expectEqualStrings("/project/src", Pardes.paneDir(scratch)); + try testing.expectEqual(Status.ok, wr(p, name, "../out/./notes.txt\n").reply.status); + try testing.expectEqualStrings("/project/out/notes.txt", scratch.file.?.path); + try testing.expectEqualStrings("/project/out", Pardes.paneDir(scratch)); + var line: [256]u8 = undefined; + try testing.expectEqual(Status.ok, wr(p, name, try std.fmt.bufPrint(&line, "/virtual/pane/{d}/./body\n", .{source.serial})).reply.status); + try testing.expectEqual(Status.ok, wr(p, Node.of(serial, .ctl), "get\n").reply.status); + try testing.expectEqualStrings(source.file.?.content, scratch.file.?.content); + const unchanged = wr(p, name, "./body\n"); + try testing.expectEqual(Status.ok, unchanged.reply.status); + try testing.expect(unchanged.watch == null); + try testing.expect(!dirtyOf(scratch)); + try testing.expect(!scratch.file.?.watch_after_save); +} + +test "owned cwd name promotion releases the former directory" { + const p = try th.withTerm(testing.allocator); + defer p.deinit(); + p.newScratchBelow(0); + const id = p.active; + const pane = p.panes[id].?; + try pane.setOwnedCwd("/old/directory"); + const result = wr(p, Node.of(pane.serial, .name), "saved.txt\n"); + try testing.expectEqual(Status.ok, result.reply.status); + try testing.expect(pane.cwd == .none); + try testing.expect(pane.file.?.output == null); + try testing.expectEqualStrings("/old/directory/saved.txt", pane.file.?.path); + try testing.expectEqualStrings("/old/directory", Pardes.paneDir(pane)); +} + +test "errors append to one +Errors buffer per directory" { + const gpa = testing.allocator; + const p = try withFile(gpa, "x\n"); + defer p.deinit(); + const serial = serialOf(p); + + const live = for (p.panes) |slot| { + if (slot) |q| if (q.file) |f| if (f.output) |o| if (std.meta.activeTag(o.from) == .errors) break q; + } else null; + try testing.expect(live == null); + + try testing.expectEqual(Status.ok, wr(p, Node.of(serial, .errors), "boom\n").reply.status); + try testing.expectEqual(Status.ok, wr(p, Node.of(serial, .errors), "again\n").reply.status); + + var found: usize = 0; + for (p.panes) |slot| { + const q = slot orelse continue; + const f = q.file orelse continue; + const o = f.output orelse continue; + if (std.meta.activeTag(o.from) != .errors) continue; + found += 1; + try testing.expectEqualStrings("boom\nagain\n", f.content); + try testing.expectEqualStrings("/+Errors", f.path); + } + try testing.expectEqual(@as(usize, 1), found); +} + +test "setattr truncation empties the body and answers fresh attributes" { + const gpa = testing.allocator; + const p = try withFile(gpa, "one\ntwo\n"); + defer p.deinit(); + const serial = serialOf(p); + + const a = call(p, .{ .tag = 7, .op = .setattr, .node = Node.of(serial, .body), .truncate = true }); + try testing.expectEqual(Status.ok, a.reply.status); + try testing.expectEqual(@as(u64, 0), a.reply.attr.size); + try testing.expectEqualStrings("", p.panes[0].?.file.?.content); + + _ = wr(p, Node.of(serial, .body), "new text\n"); + try testing.expectEqualStrings("new text\n", p.panes[0].?.file.?.content); + + const noop = call(p, .{ .tag = 8, .op = .setattr, .node = Node.of(serial, .body) }); + try testing.expectEqual(@as(u64, 9), noop.reply.attr.size); +} diff --git a/src/ninep/pty.zig b/src/ninep/pty.zig new file mode 100644 index 00000000..e6696b85 --- /dev/null +++ b/src/ninep/pty.zig @@ -0,0 +1,388 @@ +//! A terminal pane's pty/: ctl (winsize, sig, exec), status and the raw data stream. +const std = @import("std"); +const pardes = @import("../pardes.zig"); +const tree = @import("tree.zig"); +const pane_files = @import("pane.zig"); + +const Pardes = pardes.Pardes; +const Pane = pardes.Pane; +const Req = tree.Req; +const Reply = tree.Reply; +const E = tree.E; +const PaneFile = tree.PaneFile; + +pub fn fileNamed(name: []const u8) ?PaneFile { + if (std.mem.eql(u8, name, "ctl")) return .pty_ctl; + if (std.mem.eql(u8, name, "status")) return .pty_status; + if (std.mem.eql(u8, name, "data")) return .pty_data; + return null; +} + +const Verb = enum { winsize, sig, exec }; + +fn dimension(word: []const u8) ?u16 { + if (word.len == 0 or word.len > 5) return null; + for (word) |c| if (c < '0' or c > '9') return null; + const n = std.fmt.parseInt(u16, word, 10) catch return null; + return if (n == 0) null else n; +} + +fn signalNamed(word: []const u8) ?pardes.PtySignal { + if (std.mem.eql(u8, word, "INT")) return .int; + if (std.mem.eql(u8, word, "TERM")) return .term; + if (std.mem.eql(u8, word, "HUP")) return .hup; + if (std.mem.eql(u8, word, "QUIT")) return .quit; + if (std.mem.eql(u8, word, "KILL")) return .kill; + return null; +} + +pub fn writeCtl(p: *Pardes, req: Req, id: usize) Reply { + for ([2]bool{ false, true }) |apply| { + var it = std.mem.splitScalar(u8, req.data, '\n'); + while (it.next()) |raw| { + const line = std.mem.trim(u8, raw, " \t\r"); + if (line.len == 0) continue; + if (!verb(p, id, line, apply)) return Reply.fail(req.tag, E.INVAL); + } + } + return .{ .tag = req.tag, .written = @intCast(req.data.len) }; +} + +fn verb(p: *Pardes, id: usize, line: []const u8, apply: bool) bool { + const pane = p.panes[id] orelse return false; + var words = std.mem.tokenizeAny(u8, line, " \t"); + const v = std.meta.stringToEnum(Verb, words.next() orelse return false) orelse return false; + switch (v) { + .winsize => { + const cols = dimension(words.next() orelse return false) orelse return false; + const rows = dimension(words.next() orelse return false) orelse return false; + if (words.next() != null) return false; + if (!apply) return true; + p.emit(.{ .resize_pty = .{ .pane = @intCast(id), .cols = cols, .rows = rows } }); + }, + .sig => { + const which = signalNamed(words.next() orelse return false) orelse return false; + if (words.next() != null) return false; + if (!apply) return true; + p.emit(.{ .signal_pty = .{ .pane = @intCast(id), .sig = which } }); + }, + .exec => { + if (words.next() != null) return false; + if (pane.cwdSlice().len > pardes.effect_path_cap) return false; + if (!apply) return true; + p.emit(.{ .spawn = .{ .pane = @intCast(id), .cwd = .from(pane.cwdSlice()) } }); + }, + } + return true; +} + +pub fn readStatus(p: *Pardes, req: Req, id: usize, pane: *Pane) Reply { + const out = p.fs.stage(p.gpa); + out.print(p.gpa, "{d:>11} {d:>11} {d:>11} ", .{ + pane.cols, + pane.rows, + @intFromBool(p.hostTtyTaken(id)), + }) catch {}; + return tree.stagedReply(p, req); +} + +pub fn readData(p: *Pardes, req: Req, pf: *pane_files.State) Reply { + if (pf.pty_out.empty()) return .{ .tag = req.tag, .status = .again }; + const out = p.fs.stage(p.gpa); + while (out.items.len < req.size) { + const chunk = pf.pty_out.peek() orelse break; + const n = @min(chunk.len, req.size - out.items.len); + out.appendSlice(p.gpa, chunk[0..n]) catch break; + pf.pty_out.popFront(n); + } + return .{ .tag = req.tag, .payload = .{ .staged = @intCast(out.items.len) } }; +} + +pub fn writeData(p: *Pardes, req: Req, id: usize) Reply { + if (req.data.len == 0) return .{ .tag = req.tag, .written = 0 }; + const take = pane_files.wholeUtf8(req.data); + p.emitWrite(id, req.data[0..take]); + return .{ .tag = req.tag, .written = @intCast(take) }; +} + +// ---- tests ---- + +const testing = std.testing; +const th = @import("testing.zig"); +const events = @import("events.zig"); +const call = th.call; +const rd = th.rd; +const wr = th.wr; +const rdir = th.rdir; +const look_up = th.look_up; +const withFile = th.withFile; +const withTerm = th.withTerm; +const serialOf = th.serialOf; +const Node = tree.Node; +const Status = tree.Status; + +test "a pane that is not a terminal has no pty/ at all" { + const gpa = testing.allocator; + const p = try withFile(gpa, "hello\n"); + defer p.deinit(); + const serial = serialOf(p); + const dir = Node.of(serial, .dir); + + try testing.expectEqual(E.NOENT, look_up(p, dir, "pty").errno()); + try testing.expectEqual(E.NOENT, call(p, .{ + .tag = 1, + .op = .getattr, + .node = Node.of(serial, .pty), + }).errno()); + try testing.expectEqual(E.NOENT, rd(p, Node.of(serial, .pty_status), 0, 256).errno()); + try testing.expectEqual(E.NOENT, wr(p, Node.of(serial, .pty_ctl), "winsize 80 24\n").errno()); + try testing.expectEqual(E.NOENT, rdir(p, Node.of(serial, .pty), 0).errno()); + try testing.expectEqual(E.NOENT, call(p, .{ + .tag = 2, + .op = .open, + .node = Node.of(serial, .pty_data), + }).errno()); + try testing.expectEqual(@as(u16, 0), p.fs.panes[0].pty_readers); + + var buf: [32]th.Dirent = undefined; + const files = th.dirents(rdir(p, dir, 0).bytes, &buf); + try testing.expectEqual(@as(usize, 10), files.len); + try testing.expect(th.nameAt(files, "pty") == null); + + try testing.expectEqual(E.NOENT, look_up(p, dir, "pty_ctl").errno()); + try testing.expectEqual(E.NOENT, look_up(p, dir, "status").errno()); +} + +test "a terminal pane's pty/ holds exactly ctl, status and data" { + const gpa = testing.allocator; + const p = try withTerm(gpa); + defer p.deinit(); + const serial = serialOf(p); + const dir = Node.of(serial, .dir); + + const pty = look_up(p, dir, "pty"); + try testing.expectEqual(Node.of(serial, .pty), pty.reply.attr.node); + try testing.expect(pty.reply.attr.dir); + try testing.expectEqual(@as(u16, 0o755), pty.reply.attr.mode); + + var buf: [32]th.Dirent = undefined; + const files = th.dirents(rdir(p, dir, 0).bytes, &buf); + try testing.expectEqual(@as(usize, 11), files.len); + try testing.expect(th.nameAt(files, "pty").?.dir); + + const inside = th.dirents(rdir(p, Node.of(serial, .pty), 0).bytes, &buf); + try testing.expectEqual(@as(usize, 3), inside.len); + try testing.expectEqualStrings("ctl", inside[0].name); + try testing.expectEqualStrings("status", inside[1].name); + try testing.expectEqualStrings("data", inside[2].name); + for (inside) |d| try testing.expect(!d.dir); + try testing.expectEqual(Node.of(serial, .pty_data), inside[2].node); + + const ctl = look_up(p, Node.of(serial, .pty), "ctl"); + try testing.expectEqual(Node.of(serial, .pty_ctl), ctl.reply.attr.node); + try testing.expectEqual(@as(u16, 0o222), ctl.reply.attr.mode); + try testing.expectEqual(@as(u16, 0o444), look_up(p, Node.of(serial, .pty), "status").reply.attr.mode); + try testing.expectEqual(E.NOENT, look_up(p, Node.of(serial, .pty), "body").errno()); + try testing.expectEqual(E.NOENT, look_up(p, Node.of(serial, .pty), "pty").errno()); + + try testing.expectEqual(E.NOTDIR, look_up(p, Node.of(serial, .pty_ctl), "x").errno()); + try testing.expectEqual(E.NOTDIR, rdir(p, Node.of(serial, .pty_ctl), 0).errno()); + try testing.expectEqual(E.PERM, rd(p, Node.of(serial, .pty), 0, 16).errno()); + try testing.expectEqual(E.PERM, rd(p, Node.of(serial, .pty_ctl), 0, 16).errno()); + try testing.expectEqual(E.PERM, wr(p, Node.of(serial, .pty_status), "x").errno()); +} + +test "every pty/ctl verb, and every refusal" { + const gpa = testing.allocator; + const p = try withTerm(gpa); + defer p.deinit(); + const ctl = Node.of(serialOf(p), .pty_ctl); + + const pane = p.panes[0].?; + const cols = pane.cols; + const rows = pane.rows; + const ws = wr(p, ctl, "winsize 132 44\n"); + try testing.expectEqual(@as(u32, "winsize 132 44\n".len), ws.reply.written); + try testing.expectEqual(@as(u16, 132), ws.winsize.?.cols); + try testing.expectEqual(@as(u16, 44), ws.winsize.?.rows); + try testing.expectEqual(cols, pane.cols); + try testing.expectEqual(rows, pane.rows); + + for ([_]struct { line: []const u8, want: pardes.PtySignal }{ + .{ .line = "sig INT", .want = .int }, + .{ .line = "sig TERM", .want = .term }, + .{ .line = "sig HUP", .want = .hup }, + .{ .line = "sig QUIT", .want = .quit }, + .{ .line = "sig KILL", .want = .kill }, + }) |c| { + const a = wr(p, ctl, c.line); + try testing.expectEqual(Status.ok, a.reply.status); + try testing.expectEqual(c.want, a.signal.?); + } + + const ex = wr(p, ctl, "exec\n"); + try testing.expectEqual(Status.ok, ex.reply.status); + try testing.expect(ex.spawned); + + const both = wr(p, ctl, "winsize 100 30\nsig TERM"); + try testing.expectEqual(@as(u16, 100), both.winsize.?.cols); + try testing.expectEqual(pardes.PtySignal.term, both.signal.?); + + for ([_][]const u8{ + "winsize", // no arguments + "winsize 80", // one argument + "winsize 80 24 extra", // three + "winsize 0 24", // zero is "unknown", never a width + "winsize 80 0", + "winsize -1 24", // not a decimal + "winsize 999999 24", // wider than a u16 + "sig", // no name + "sig INT TERM", // two + "sig SIGINT", + "sig int", // lower case + "sig 9", // a number is one platform's number + "sig USR1", // a real signal, deliberately not offered + "exec /bin/sh", // the effect carries no argv; refused, never ignored + "raw", + "cooked", + "winsize 80 24\nbogus", // a good verb beside a bad one + "bogus\nwinsize 80 24", + "look x", // a `ctl` verb; the two files share no vocabulary + "exec Del", + }) |bad| { + const a = wr(p, ctl, bad); + try testing.expectEqual(E.INVAL, a.errno()); + try testing.expect(a.winsize == null); + try testing.expect(a.signal == null); + try testing.expect(!a.spawned); + } + + const spaced = wr(p, ctl, "\n winsize 90 20 \n\n"); + try testing.expectEqual(Status.ok, spaced.reply.status); + try testing.expectEqual(@as(u16, 90), spaced.winsize.?.cols); + try testing.expectEqual(Status.ok, wr(p, ctl, "").reply.status); +} + +test "owned cwd pty exec rejects long paths before applying its batch" { + const p = try withTerm(testing.allocator); + defer p.deinit(); + const pane = p.panes[0].?; + const ctl = Node.of(pane.serial, .pty_ctl); + var path: [1025]u8 = @splat('d'); + path[0] = '/'; + p.setCwd(0, &path); + for ([_][]const u8{ "exec\n", "winsize 100 30\nexec\n", "sig TERM\nexec\n" }) |command| { + const result = wr(p, ctl, command); + try testing.expectEqual(E.INVAL, result.errno()); + try testing.expect(!result.spawned); + try testing.expect(result.signal == null and result.winsize == null); + } + try testing.expectEqualStrings(&path, pane.cwdSlice()); + p.setCwd(0, path[0..pardes.effect_path_cap]); + const accepted = wr(p, ctl, "exec\n"); + try testing.expectEqual(Status.ok, accepted.reply.status); + try testing.expect(accepted.spawned); +} + +test "pty/status reports the grid and who holds the tty" { + const gpa = testing.allocator; + const p = try withTerm(gpa); + defer p.deinit(); + const pane = p.panes[0].?; + const status = Node.of(pane.serial, .pty_status); + + const a = rd(p, status, 0, 256); + try testing.expectEqual(Status.ok, a.reply.status); + var want: [64]u8 = undefined; + const whole = try std.fmt.bufPrint(&want, "{d:>11} {d:>11} {d:>11} ", .{ pane.cols, pane.rows, 0 }); + try testing.expectEqualStrings(whole, a.bytes); + try testing.expectEqual(@as(usize, 3 * 12), a.bytes.len); + try testing.expectEqualStrings(whole[12..], rd(p, status, 12, 256).bytes); + + var probe: th.FakeTty = .{ .taken = true }; + p.host = .{ .ctx = &probe, .vtable = &th.FakeTty.vtable }; + const held = rd(p, status, 0, 256); + try testing.expectEqualStrings( + try std.fmt.bufPrint(&want, "{d:>11} {d:>11} {d:>11} ", .{ pane.cols, pane.rows, 1 }), + held.bytes, + ); +} + +test "pty/data writes at the shell and reads the raw stream" { + const gpa = testing.allocator; + const p = try withTerm(gpa); + defer p.deinit(); + const serial = serialOf(p); + const data = Node.of(serial, .pty_data); + + const w = call(p, .{ .tag = 2, .op = .write, .node = data, .off = 999, .data = "ls -l\r" }); + try testing.expectEqual(@as(u32, 6), w.reply.written); + try testing.expectEqualStrings("ls -l\r", w.pty()); + try testing.expectEqual(@as(u32, 1), wr(p, data, "a\xC3").reply.written); + try testing.expectEqual(@as(u32, 0), wr(p, data, "").reply.written); + + try testing.expectEqual(Status.again, rd(p, data, 0, 64).reply.status); + + p.update(.{ .output = .{ .pane = 0, .bytes = "unwatched" } }); + while (p.nextEffect()) |_| {} + try testing.expectEqual(@as(usize, 0), p.fs.panes[0].pty_out.buf.items.len); + try testing.expectEqual(Status.again, rd(p, data, 0, 64).reply.status); + + _ = call(p, .{ .tag = 5, .op = .open, .node = data }); + try testing.expectEqual(@as(u16, 1), p.fs.panes[0].pty_readers); + try testing.expectEqual(@as(u16, 0), p.fs.listeners); + try testing.expect(!p.fs.scripted(0)); + + p.update(.{ .output = .{ .pane = 0, .bytes = "hello" } }); + while (p.nextEffect()) |_| {} + try testing.expectEqualStrings("hello", rd(p, data, 0, 64).bytes); + try testing.expectEqual(Status.again, rd(p, data, 0, 64).reply.status); + + p.update(.{ .output = .{ .pane = 0, .bytes = "abcdef" } }); + while (p.nextEffect()) |_| {} + try testing.expectEqualStrings("ab", rd(p, data, 0, 2).bytes); + try testing.expectEqualStrings("cd", rd(p, data, 0, 2).bytes); + p.update(.{ .output = .{ .pane = 0, .bytes = "ghi" } }); + while (p.nextEffect()) |_| {} + try testing.expectEqualStrings("efghi", rd(p, data, 0, 64).bytes); + + p.update(.{ .output = .{ .pane = 0, .bytes = "orphan" } }); + while (p.nextEffect()) |_| {} + _ = call(p, .{ .tag = 6, .op = .release, .node = data }); + try testing.expectEqual(@as(u16, 0), p.fs.panes[0].pty_readers); + try testing.expectEqual(@as(usize, 0), p.fs.panes[0].pty_out.buf.capacity); + try testing.expectEqual(Status.again, rd(p, data, 0, 64).reply.status); + + _ = call(p, .{ .tag = 7, .op = .open, .node = data }); + _ = call(p, .{ .tag = 8, .op = .open, .node = data }); + _ = call(p, .{ .tag = 9, .op = .release, .node = data }); + try testing.expectEqual(@as(u16, 1), p.fs.panes[0].pty_readers); + p.update(.{ .output = .{ .pane = 0, .bytes = "still" } }); + while (p.nextEffect()) |_| {} + try testing.expectEqualStrings("still", rd(p, data, 0, 64).bytes); +} + +test "the pty queue drops the oldest at its cap" { + const gpa = testing.allocator; + const p = try withTerm(gpa); + defer p.deinit(); + const data = Node.of(serialOf(p), .pty_data); + _ = call(p, .{ .tag = 5, .op = .open, .node = data }); + + const oldest: [4096]u8 = @splat('A'); + const rest: [4096]u8 = @splat('B'); + events.notePtyOutput(p, 0, &oldest); + for (0..events.queue_cap / rest.len + 4) |_| events.notePtyOutput(p, 0, &rest); + const q = &p.fs.panes[0].pty_out; + try testing.expect(q.buf.items.len - q.head <= events.queue_cap); + + var seen: usize = 0; + while (true) { + const a = rd(p, data, 0, 1 << 16); + if (a.reply.status == .again) break; + try testing.expect(std.mem.indexOfScalar(u8, a.bytes, 'A') == null); + if (a.bytes.len == 0) break; + seen += a.bytes.len; + } + try testing.expect(seen > 0 and seen <= events.queue_cap); +} diff --git a/src/ninep/screen.zig b/src/ninep/screen.zig new file mode 100644 index 00000000..5b68b34c --- /dev/null +++ b/src/ninep/screen.zig @@ -0,0 +1,351 @@ +//! /screen, /listeners and the snapshot handles that freeze a screen or a +//! terminal history between open and close. +const std = @import("std"); +const pardes = @import("../pardes.zig"); +const panes = @import("../panes.zig"); +const tree = @import("tree.zig"); + +const Pardes = pardes.Pardes; +const Pane = pardes.Pane; +const Req = tree.Req; +const Reply = tree.Reply; +const E = tree.E; + +pub const Snapshot = struct { node: u64 = 0, bytes: ?[]const u8 = null }; +pub const snapshot_slots = 32; + +pub fn render(p: *Pardes) ![]u8 { + var arena: std.heap.ArenaAllocator = .init(p.gpa); + defer arena.deinit(); + const surface = try p.render(arena.allocator()); + var styles: std.ArrayList(pardes.CellStyle) = .empty; + var indices: std.ArrayList(usize) = .empty; + for (surface.cells) |cell| { + const style: pardes.CellStyle = if (cell.default) .{} else cell.style; + const index = for (styles.items, 0..) |previous, i| { + if (std.meta.eql(style, previous)) break i; + } else new: { + try styles.append(arena.allocator(), style); + break :new styles.items.len - 1; + }; + try indices.append(arena.allocator(), index); + } + var out: std.Io.Writer.Allocating = .init(p.gpa); + errdefer out.deinit(); + const writer = &out.writer; + try writer.print("{{\"cols\":{d},\"rows\":{d},\"cursor\":", .{ surface.cols, surface.rows }); + try std.json.Stringify.value(surface.cursor, .{}, writer); + try writer.writeAll(",\"styles\":"); + try std.json.Stringify.value(styles.items, .{ .emit_strings_as_arrays = true }, writer); + try writer.writeAll(",\"cells\":["); + for (surface.cells, indices.items, 0..) |cell, index, i| { + if (i != 0) try writer.writeByte(','); + try std.json.Stringify.value(.{ if (cell.default) " " else cell.grapheme(), index }, .{}, writer); + } + try writer.writeAll("]}\n"); + return out.toOwnedSlice(); +} + +/// A screen freezes at open; a terminal body freezes at its first read. +pub fn openSnapshot(p: *Pardes, req: Req, of_screen: bool) Reply { + for (&p.fs.snapshots, 0..) |*slot, i| { + if (slot.node != 0) continue; + const bytes = if (of_screen) render(p) catch return Reply.fail(req.tag, E.NOMEM) else null; + slot.* = .{ .node = req.node, .bytes = bytes }; + return .{ .tag = req.tag, .handle = @intCast(i + 1) }; + } + return Reply.fail(req.tag, E.NFILE); +} + +pub fn readSnapshot(p: *Pardes, req: Req, pane: ?*Pane) Reply { + if (req.handle == 0 or req.handle > p.fs.snapshots.len) return Reply.fail(req.tag, E.INVAL); + const snapshot = &p.fs.snapshots[req.handle - 1]; + if (snapshot.node == 0 or snapshot.node != req.node) return Reply.fail(req.tag, E.INVAL); + if (snapshot.bytes == null) { + const terminal = pane orelse return Reply.fail(req.tag, E.INVAL); + snapshot.bytes = panes.Terminal.screenTextAlloc(terminal, p.gpa) catch return Reply.fail(req.tag, E.NOMEM); + } + const bytes = snapshot.bytes.?; + const off = @min(req.off, bytes.len); + const len = @min(bytes.len - off, req.size); + const out = p.fs.stage(p.gpa); + out.appendSlice(p.gpa, bytes[off..][0..len]) catch return Reply.fail(req.tag, E.NOMEM); + return .{ .tag = req.tag, .payload = .{ .staged = @intCast(len) } }; +} + +/// True when the handle named a snapshot, which is now released. +pub fn releaseSnapshot(p: *Pardes, req: Req) bool { + if (req.handle == 0 or req.handle > p.fs.snapshots.len) return false; + const snapshot = &p.fs.snapshots[req.handle - 1]; + if (snapshot.node != req.node) return false; + if (snapshot.bytes) |bytes| p.gpa.free(bytes); + snapshot.* = .{}; + return true; +} + +pub fn readListeners(p: *Pardes, req: Req) Reply { + var buf: [512]u8 = undefined; + var text = std.Io.Writer.fixed(&buf); + if (p.fs.socket_path.len != 0) + text.print("unix!{s}\n", .{p.fs.socket_path}) catch return Reply.fail(req.tag, E.IO); + for ([_]?std.Io.net.IpAddress{ p.fs.tcp_address, p.fs.quic_address }, [_][]const u8{ "tcp", "quic" }) |maybe, transport| { + const address = maybe orelse continue; + switch (address) { + .ip4 => |ip| text.print("{s}!{d}.{d}.{d}.{d}!{d}\n", .{ transport, ip.bytes[0], ip.bytes[1], ip.bytes[2], ip.bytes[3], ip.port }) catch + return Reply.fail(req.tag, E.IO), + .ip6 => |ip| text.print("{s}!{f}!{d}\n", .{ transport, std.Io.net.Ip6Address.Unresolved{ .bytes = ip.bytes, .interface_name = null }, ip.port }) catch + return Reply.fail(req.tag, E.IO), + } + } + const out = p.fs.stage(p.gpa); + out.appendSlice(p.gpa, text.buffered()) catch return Reply.fail(req.tag, E.NOMEM); + return tree.stagedReply(p, req); +} + +// ---- tests ---- + +const testing = std.testing; +const th = @import("testing.zig"); +const fs = @import("../fs.zig"); +const call = th.call; +const rd = th.rd; +const wr = th.wr; +const withFile = th.withFile; +const withTerm = th.withTerm; +const serialOf = th.serialOf; +const Node = tree.Node; +const Status = tree.Status; +const screen_node = @intFromEnum(tree.TopFile.screen); + +test "listener addresses are readable canonical dials with bounded partial reads" { + const gpa = testing.allocator; + const p = try Pardes.init(gpa, .{ .tty_only = true }); + defer p.deinit(); + p.fs.socket_path = "/tmp/a socket.sock"; + p.fs.tcp_address = .{ .ip4 = .loopback(5640) }; + p.fs.quic_address = .{ .ip6 = .loopback(5641) }; + const expected = "unix!/tmp/a socket.sock\ntcp!127.0.0.1!5640\nquic!::1!5641\n"; + for ([_][]const u8{ "/virtual/listeners", "/n/self/listeners" }) |path| { + const bytes = try fs.read(p, path); + defer gpa.free(bytes); + try testing.expectEqualStrings(expected, bytes); + try testing.expectError(error.ReadOnlyFilesystem, fs.write(p, path, "")); + } + const node = @intFromEnum(tree.TopFile.listeners); + var off: usize = 0; + while (off < expected.len) { + const part = rd(p, node, off, 3); + try testing.expectEqual(Status.ok, part.reply.status); + try testing.expectEqualStrings(expected[off..][0..@min(3, expected.len - off)], part.bytes); + off += part.bytes.len; + } + try testing.expectEqual(@as(usize, 0), rd(p, node, off, 3).bytes.len); +} + +test "terminal body handles keep one history snapshot across fragmented reads" { + const gpa = testing.allocator; + const p = try withTerm(gpa); + defer p.deinit(); + const node = Node.of(serialOf(p), .body); + p.update(.{ .output = .{ .pane = 0, .bytes = "old caf\xc3\xa9\r\nold tail" } }); + while (p.nextEffect()) |_| {} + const original = try panes.Terminal.screenTextAlloc(p.panes[0].?, gpa); + defer gpa.free(original); + const opened = call(p, .{ .tag = 1, .op = .open, .node = node }); + try testing.expectEqual(Status.ok, opened.reply.status); + const first = call(p, .{ .tag = 2, .op = .read, .node = node, .handle = opened.reply.handle, .size = 3 }); + try testing.expectEqualStrings(original[0..3], first.bytes); + p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[3J\x1b[2J\x1b[Hnew output" } }); + while (p.nextEffect()) |_| {} + var offset: usize = 3; + while (offset < original.len) { + const part = call(p, .{ .tag = 3, .op = .read, .node = node, .handle = opened.reply.handle, .off = offset, .size = 3 }); + try testing.expectEqualStrings(original[offset..][0..@min(3, original.len - offset)], part.bytes); + offset += part.bytes.len; + } + try testing.expectEqualStrings("", call(p, .{ .tag = 4, .op = .read, .node = node, .handle = opened.reply.handle, .off = original.len, .size = 3 }).bytes); + _ = call(p, .{ .tag = 5, .op = .release, .node = node, .handle = opened.reply.handle }); + const newer = call(p, .{ .tag = 6, .op = .open, .node = node }); + try testing.expectEqualStrings("new output", call(p, .{ .tag = 7, .op = .read, .node = node, .handle = newer.reply.handle, .size = 32 }).bytes); + _ = call(p, .{ .tag = 8, .op = .release, .node = node, .handle = newer.reply.handle }); +} + +test "an empty terminal body snapshot stays empty while output continues" { + const p = try withTerm(std.testing.allocator); + defer p.deinit(); + const node = Node.of(serialOf(p), .body); + const opened = call(p, .{ .tag = 1, .op = .open, .node = node }); + try testing.expectEqualStrings("", call(p, .{ .tag = 2, .op = .read, .node = node, .handle = opened.reply.handle, .size = 32 }).bytes); + try testing.expect(p.fs.snapshots[opened.reply.handle - 1].bytes != null); + p.update(.{ .output = .{ .pane = 0, .bytes = "new output" } }); + while (p.nextEffect()) |_| {} + try testing.expectEqualStrings("", call(p, .{ .tag = 3, .op = .read, .node = node, .handle = opened.reply.handle, .size = 32 }).bytes); + _ = call(p, .{ .tag = 4, .op = .release, .node = node, .handle = opened.reply.handle }); + const newer = call(p, .{ .tag = 5, .op = .open, .node = node }); + try testing.expectEqualStrings("new output", call(p, .{ .tag = 6, .op = .read, .node = node, .handle = newer.reply.handle, .size = 32 }).bytes); + _ = call(p, .{ .tag = 7, .op = .release, .node = node, .handle = newer.reply.handle }); +} + +test "terminal body snapshots are lazy bounded and released after the pane closes" { + const gpa = testing.allocator; + const p = try withTerm(gpa); + defer p.deinit(); + const node = Node.of(serialOf(p), .body); + var handles: [snapshot_slots]u32 = undefined; + for (&handles) |*opened_handle| { + const opened = call(p, .{ .tag = 1, .op = .open, .node = node }); + try testing.expectEqual(Status.ok, opened.reply.status); + opened_handle.* = opened.reply.handle; + } + for (p.fs.snapshots) |snapshot| { + try testing.expectEqual(node, snapshot.node); + try testing.expect(snapshot.bytes == null); + } + try testing.expectEqual(E.NFILE, call(p, .{ .tag = 2, .op = .open, .node = node }).errno()); + const scratch = try th.newPane(p); + const scratch_id = p.paneBySerial(scratch).?; + try testing.expect(p.panes[scratch_id].?.file != null); + p.update(.{ .output = .{ .pane = 0, .bytes = "latest output" } }); + while (p.nextEffect()) |_| {} + var failing = std.testing.FailingAllocator.init(gpa, .{ .fail_index = 0 }); + p.gpa = failing.allocator(); + const failed = call(p, .{ .tag = 3, .op = .read, .node = node, .handle = handles[0], .size = 32 }); + p.gpa = gpa; + try testing.expectEqual(E.NOMEM, failed.errno()); + try testing.expect(p.fs.snapshots[handles[0] - 1].bytes == null); + const first = call(p, .{ .tag = 4, .op = .read, .node = node, .handle = handles[0], .size = 32 }); + try testing.expectEqualStrings("latest output", first.bytes); + const saved = p.fs.snapshots[handles[0] - 1].bytes.?; + failing = std.testing.FailingAllocator.init(gpa, .{ .fail_index = 0 }); + p.gpa = failing.allocator(); + const second = call(p, .{ .tag = 5, .op = .read, .node = node, .handle = handles[0], .off = 7, .size = 32 }); + p.gpa = gpa; + try testing.expectEqualStrings("output", second.bytes); + try testing.expect(!failing.has_induced_failure); + try testing.expectEqual(saved.ptr, p.fs.snapshots[handles[0] - 1].bytes.?.ptr); + try testing.expectEqual(E.INVAL, call(p, .{ .tag = 6, .op = .read, .node = screen_node, .handle = handles[0], .size = 32 }).errno()); + _ = call(p, .{ .tag = 7, .op = .release, .node = screen_node, .handle = handles[0] }); + try testing.expectEqual(node, p.fs.snapshots[handles[0] - 1].node); + try p.removePane(0); + for (handles) |opened_handle| _ = call(p, .{ .tag = 8, .op = .release, .node = node, .handle = opened_handle }); + for (p.fs.snapshots) |snapshot| { + try testing.expectEqual(@as(u64, 0), snapshot.node); + try testing.expect(snapshot.bytes == null); + } +} + +test "screen snapshots preserve rendered cells and styles until their handle is released" { + const gpa = testing.allocator; + const p = try withFile(gpa, "const value = 1;\n"); + defer p.deinit(); + const opened = call(p, .{ .tag = 1, .op = .open, .node = screen_node }); + try testing.expectEqual(Status.ok, opened.reply.status); + const snapshot = p.fs.snapshots[opened.reply.handle - 1].bytes.?; + const original = try gpa.dupe(u8, snapshot); + defer gpa.free(original); + const parsed = try std.json.parseFromSlice(std.json.Value, gpa, original, .{}); + defer parsed.deinit(); + const data = parsed.value.object; + try testing.expectEqual(@as(i64, p.screen_w), data.get("cols").?.integer); + try testing.expectEqual(@as(i64, p.screen_h), data.get("rows").?.integer); + try testing.expectEqual(@as(usize, p.screen_w) * p.screen_h, data.get("cells").?.array.items.len); + try testing.expect(data.get("styles").?.array.items.len > 0); + _ = wr(p, Node.of(serialOf(p), .body), "changed\n"); + const newer = call(p, .{ .tag = 2, .op = .open, .node = screen_node }); + try testing.expectEqual(Status.ok, newer.reply.status); + try testing.expect(!std.mem.eql(u8, original, p.fs.snapshots[newer.reply.handle - 1].bytes.?)); + var off: usize = 0; + while (off < original.len) { + const result = call(p, .{ .tag = 3, .op = .read, .node = screen_node, .handle = opened.reply.handle, .off = off, .size = 13 }); + try testing.expectEqual(Status.ok, result.reply.status); + try testing.expectEqualSlices(u8, original[off..][0..@min(13, original.len - off)], result.bytes); + off += result.bytes.len; + } + _ = call(p, .{ .tag = 4, .op = .release, .node = screen_node, .handle = opened.reply.handle }); + _ = call(p, .{ .tag = 5, .op = .release, .node = screen_node, .handle = newer.reply.handle }); + for (p.fs.snapshots) |slot| try testing.expect(slot.node == 0); +} + +test "screen inspection preserves acknowledged presentation and the next real frame" { + const gpa = testing.allocator; + for (std.enums.values(pardes.layout.Transition)) |transition| { + errdefer std.debug.print("screen inspection during {s}\n", .{@tagName(transition)}); + const control = try withFile(gpa, "const value = 1;\n"); + defer control.deinit(); + const inspected = try withFile(gpa, "const value = 1;\n"); + defer inspected.deinit(); + var arena: std.heap.ArenaAllocator = .init(gpa); + defer arena.deinit(); + for ([_]*Pardes{ control, inspected }) |p| { + p.settings.panel_transition = .off; + p.update(.tick); + p.acknowledgePanelPresentation((try p.render(arena.allocator())).panelTracks()); + p.settings.panel_transition = transition; + } + for (0..4) |phase| { + for ([_]*Pardes{ control, inspected }) |p| switch (phase) { + 0 => {}, + 1 => p.update(.{ .command = "New" }), + 2 => { + p.update(.tick); + try testing.expectEqual(Status.ok, wr(p, Node.of(p.panes[p.active].?.serial, .body), "changed cells\n").reply.status); + }, + 3 => { + for (0..transition.frames() + 1) |_| p.update(.tick); + p.acknowledgePanelPresentation((try p.render(arena.allocator())).panelTracks()); + p.update(.{ .command = "Del" }); + }, + else => unreachable, + }; + for (0..2) |_| { + const opened = call(inspected, .{ .tag = 1, .op = .open, .node = screen_node }); + try testing.expectEqual(Status.ok, opened.reply.status); + const captured = call(inspected, .{ .tag = 2, .op = .read, .node = screen_node, .handle = opened.reply.handle, .size = 32 }); + try testing.expectEqual(Status.ok, captured.reply.status); + try testing.expect(captured.bytes.len > 0); + try testing.expectEqual(Status.ok, call(inspected, .{ + .tag = 3, + .op = .release, + .node = screen_node, + .handle = opened.reply.handle, + }).reply.status); + } + const a = &control.presentation; + const b = &inspected.presentation; + try testing.expectEqualDeep(a.shown, b.shown); + try testing.expectEqualDeep(a.shown_tracks, b.shown_tracks); + try testing.expectEqualDeep(a.shown_closing[0..a.shown_closing_len], b.shown_closing[0..b.shown_closing_len]); + try testing.expectEqual(a.pending, b.pending); + try testing.expectEqual(a.acknowledged, b.acknowledged); + try testing.expectEqual(a.previous_valid, b.previous_valid); + try testing.expectEqual(a.previous_cols, b.previous_cols); + try testing.expectEqual(a.previous_rows, b.previous_rows); + try testing.expectEqualDeep(a.previous_layout, b.previous_layout); + try testing.expectEqual(a.previous_cells.len, b.previous_cells.len); + for (a.previous_cells, b.previous_cells) |*expected, *actual| + try testing.expect(expected.visuallyEqual(actual)); + + const expected = try control.render(arena.allocator()); + const actual = try inspected.render(arena.allocator()); + try testing.expectEqual(expected.cols, actual.cols); + try testing.expectEqual(expected.rows, actual.rows); + try testing.expectEqualDeep(expected.cursor, actual.cursor); + try testing.expectEqualDeep(expected.panelTracks(), actual.panelTracks()); + try testing.expectEqualDeep(expected.cell_diffs, actual.cell_diffs); + try testing.expectEqual(expected.previous_cells.len, actual.previous_cells.len); + try testing.expectEqual(expected.cells.len, actual.cells.len); + try testing.expectEqual(@as(usize, 0), expected.nimages); + try testing.expectEqual(@as(usize, 0), actual.nimages); + for (expected.cells, actual.cells) |*left, *right| try testing.expect(left.visuallyEqual(right)); + for (expected.previous_cells, actual.previous_cells) |*left, *right| try testing.expect(left.visuallyEqual(right)); + if (phase == 1 and transition != .off) try testing.expect(expected.panelTracks().len > 0); + if (phase == 1 and transition.needsPreviousGrid()) try testing.expect(expected.hasPanelDiff()); + if (phase == 3 and transition == .vertical) try testing.expect(a.closing_len > 0); + control.acknowledgePanelPresentation(expected.panelTracks()); + inspected.acknowledgePanelPresentation(actual.panelTracks()); + try testing.expectEqualDeep(a.shown, b.shown); + try testing.expectEqualDeep(a.previous_layout, b.previous_layout); + _ = arena.reset(.retain_capacity); + } + } +} diff --git a/src/ninep/sources.zig b/src/ninep/sources.zig new file mode 100644 index 00000000..b0408594 --- /dev/null +++ b/src/ninep/sources.zig @@ -0,0 +1,152 @@ +//! The editor's embedded sources, served read-only from the root when the +//! build carries them (-Dembed-sources=true). +const std = @import("std"); +const pardes = @import("../pardes.zig"); +const fs = @import("../fs.zig"); +const tree = @import("tree.zig"); + +const Pardes = pardes.Pardes; +const Req = tree.Req; +const Reply = tree.Reply; +const E = tree.E; +const sources = fs.sources; + +pub const archive_node: u64 = 1 << 61; + +/// The node of an archive path, or null when nothing embedded lives there. +/// The empty path is the archive root, which is never listed by itself. +pub fn node(path: []const u8) ?u64 { + if (path.len == 0) return archive_node; + if (path.len >= 4096) return null; + for (sources, 0..) |source, i| { + if (std.mem.eql(u8, source.path, path) or + (source.path.len > path.len and source.path[path.len] == '/' and std.mem.startsWith(u8, source.path, path))) + return archive_node | (@as(u64, i) << 12) | path.len; + } + return null; +} + +fn info(n: u64) ?struct { path: []const u8, contents: []const u8, dir: bool } { + if (n == archive_node) return .{ .path = "", .contents = "", .dir = true }; + const index = (n & ~archive_node) >> 12; + if (index >= sources.len) return null; + const source = sources[@intCast(index)]; + const len: usize = @intCast(n & 4095); + if (len > source.path.len) return null; + return .{ .path = source.path[0..len], .contents = source.contents, .dir = len < source.path.len }; +} + +/// Stages the children of one archive directory; "" lists the top-level +/// directories the served root shows. +pub fn stage(p: *Pardes, out: *std.ArrayList(u8), path: []const u8, skip: *u64) void { + var seen: [sources.len][]const u8 = undefined; + var count: usize = 0; + for (sources, 0..) |source, i| { + if (path.len != 0 and + (source.path.len <= path.len or source.path[path.len] != '/' or !std.mem.startsWith(u8, source.path, path))) continue; + const start = if (path.len == 0) 0 else path.len + 1; + const rest = source.path[start..]; + const len = std.mem.indexOfScalar(u8, rest, '/') orelse rest.len; + const name = rest[0..len]; + var duplicate = false; + for (seen[0..count]) |previous| if (std.mem.eql(u8, name, previous)) { + duplicate = true; + break; + }; + if (duplicate) continue; + seen[count] = name; + count += 1; + if (skip.* > 0) { + skip.* -= 1; + continue; + } + const child = archive_node | (@as(u64, i) << 12) | (start + len); + tree.stageDirent(out, p.gpa, child, len < rest.len, name); + } +} + +pub fn handle(p: *Pardes, req: Req) Reply { + const found = info(req.node) orelse return Reply.fail(req.tag, E.NOENT); + const attr: Reply.Attr = .{ + .node = req.node, + .name = std.fs.path.basename(found.path), + .dir = found.dir, + .size = if (found.dir) 0 else found.contents.len, + .mode = if (found.dir) 0o555 else 0o444, + .mtime = p.fs.started, + }; + switch (req.op) { + .getattr => return .{ .tag = req.tag, .attr = attr }, + .open => return .{ .tag = req.tag, .handle = 1 }, + .release => return .{ .tag = req.tag }, + .lookup => { + if (!found.dir) return Reply.fail(req.tag, E.NOTDIR); + if (std.mem.eql(u8, req.data, "..")) { + const parent = std.fs.path.dirname(found.path) orelse ""; + if (parent.len == 0) return tree.handle(p, .{ .tag = req.tag, .op = .getattr, .node = tree.root }); + const parent_node = node(parent) orelse return Reply.fail(req.tag, E.NOENT); + return handle(p, .{ .tag = req.tag, .op = .getattr, .node = parent_node }); + } + if (req.data.len == 0 or std.mem.indexOfAny(u8, req.data, "/\x00") != null) return Reply.fail(req.tag, E.NOENT); + var buf: [4096]u8 = undefined; + const path = if (found.path.len == 0) req.data else std.fmt.bufPrint(&buf, "{s}/{s}", .{ found.path, req.data }) catch return Reply.fail(req.tag, E.NOENT); + const child = node(path) orelse return Reply.fail(req.tag, E.NOENT); + return handle(p, .{ .tag = req.tag, .op = .getattr, .node = child }); + }, + .readdir => { + if (!found.dir) return Reply.fail(req.tag, E.NOTDIR); + const out = p.fs.stage(p.gpa); + var skip = req.off; + stage(p, out, found.path, &skip); + return .{ .tag = req.tag, .payload = .{ .staged = @intCast(out.items.len) } }; + }, + .read => { + if (found.dir) return Reply.fail(req.tag, E.PERM); + const off: usize = @intCast(@min(req.off, found.contents.len)); + const bytes = found.contents[off..][0..@min(req.size, found.contents.len - off)]; + const out = p.fs.stage(p.gpa); + out.appendSlice(p.gpa, bytes) catch return Reply.fail(req.tag, E.NOMEM); + return .{ .tag = req.tag, .payload = .{ .staged = @intCast(bytes.len) } }; + }, + else => return Reply.fail(req.tag, E.PERM), + } +} + +const testing = std.testing; +const th = @import("testing.zig"); +const limits = @import("../memory.zig").limits; + +test "embedded sources appear under the root only when the build carries them" { + const p = try th.withFile(testing.allocator, "x\n"); + defer p.deinit(); + var buf: [64]th.Dirent = undefined; + const top = th.dirents(th.rdir(p, tree.root, 0).bytes, &buf); + const listed = th.nameAt(top, "src"); + try testing.expectEqual(limits.embedded_sources, listed != null); + const looked = th.look_up(p, tree.root, "src"); + try testing.expectEqual(limits.embedded_sources, looked.reply.status == .ok); + try testing.expect(tree.resolveSelf(p, "shaders/../src/../") == tree.root); + if (!limits.embedded_sources) { + try testing.expect(tree.resolveSelf(p, "src/pardes.zig") == null); + try testing.expect(tree.resolveSelf(p, "src") == null); + try testing.expect(th.nameAt(top, "build.zig") == null); + return; + } + try testing.expect(looked.reply.attr.dir); + try testing.expectEqual(@as(u16, 0o555), looked.reply.attr.mode); + try testing.expectEqual(listed.?.node, looked.reply.attr.node); + try testing.expect(th.nameAt(top, "build.zig") == null); + try testing.expect(th.nameAt(top, "build.zig.zon") == null); + const file = th.look_up(p, looked.reply.attr.node, "pardes.zig"); + try testing.expectEqual(tree.Status.ok, file.reply.status); + try testing.expectEqual(@as(u16, 0o444), file.reply.attr.mode); + try testing.expectEqual(@as(u64, fs.sourceBytes("src/pardes.zig").?.len), file.reply.attr.size); + try testing.expectEqual(file.reply.attr.node, tree.resolveSelf(p, "src/pardes.zig").?); + const opened = th.call(p, .{ .tag = 1, .op = .open, .node = file.reply.attr.node }); + const head = th.call(p, .{ .tag = 2, .op = .read, .node = file.reply.attr.node, .handle = opened.reply.handle, .size = 16 }); + try testing.expectEqualStrings(fs.sourceBytes("src/pardes.zig").?[0..16], head.bytes); + const parent = th.look_up(p, looked.reply.attr.node, ".."); + try testing.expectEqual(tree.root, parent.reply.attr.node); + try testing.expectEqual(E.NOENT, th.look_up(p, tree.root, "build.zig").errno()); + try testing.expectEqual(E.NOENT, th.look_up(p, looked.reply.attr.node, "missing.zig").errno()); +} diff --git a/src/ninep/testing.zig b/src/ninep/testing.zig new file mode 100644 index 00000000..ba26cb38 --- /dev/null +++ b/src/ninep/testing.zig @@ -0,0 +1,135 @@ +//! Test helpers shared by the control-tree modules: drive one request +//! through the core and collect the reply and the effects it raised. +const std = @import("std"); +const pardes = @import("../pardes.zig"); +const tree = @import("tree.zig"); + +const Pardes = pardes.Pardes; +pub const Req = tree.Req; +pub const Reply = tree.Reply; +pub const E = tree.E; + +pub const Answer = struct { + reply: Reply = .{ .tag = 0, .status = .err, .errno = E.IO }, + bytes: []const u8 = "", + saved: bool = false, + watch: ?bool = null, + pty_buf: [256]u8 = undefined, + pty_len: usize = 0, + winsize: ?struct { cols: u16, rows: u16 } = null, + signal: ?pardes.PtySignal = null, + spawned: bool = false, + + pub fn pty(a: *const Answer) []const u8 { + return a.pty_buf[0..a.pty_len]; + } + + pub fn errno(a: Answer) u16 { + return if (a.reply.status == .err) a.reply.errno else 0; + } +}; + +pub fn call(p: *Pardes, req: Req) Answer { + p.update(.{ .fs_req = req }); + var ans: Answer = .{}; + while (p.nextEffect()) |e| switch (e) { + .fs_reply => |r| { + ans.reply = r; + ans.bytes = p.fsPayload(r); + }, + .save_file, .save_text => ans.saved = true, + .watch => |w| ans.watch = w.on, + .write => |w| { + const b = w.bytes.slice(); + const n = @min(b.len, ans.pty_buf.len - ans.pty_len); + @memcpy(ans.pty_buf[ans.pty_len..][0..n], b[0..n]); + ans.pty_len += n; + }, + .resize_pty => |r| ans.winsize = .{ .cols = r.cols, .rows = r.rows }, + .signal_pty => |s| ans.signal = s.sig, + .spawn => ans.spawned = true, + else => {}, + }; + return ans; +} + +pub fn rd(p: *Pardes, node: u64, off: u64, size: u32) Answer { + return call(p, .{ .tag = 1, .op = .read, .node = node, .off = off, .size = size }); +} + +pub fn wr(p: *Pardes, node: u64, data: []const u8) Answer { + return call(p, .{ .tag = 2, .op = .write, .node = node, .data = data }); +} + +pub fn rdir(p: *Pardes, node: u64, skip: u64) Answer { + return call(p, .{ .tag = 4, .op = .readdir, .node = node, .off = skip, .size = 4096 }); +} + +pub fn look_up(p: *Pardes, dir: u64, name: []const u8) Answer { + return call(p, .{ .tag = 3, .op = .lookup, .node = dir, .data = name }); +} + +/// Opens /new once, as a client would, and returns the pane it made. +pub fn newPane(p: *Pardes) !u32 { + const new = @intFromEnum(tree.TopFile.new); + const opened = call(p, .{ .tag = 9, .op = .open, .node = new }); + if (opened.reply.status != .ok or opened.reply.handle == 0) return error.NoPane; + _ = call(p, .{ .tag = 9, .op = .release, .node = new, .handle = opened.reply.handle }); + return opened.reply.handle; +} + +pub fn withFile(gpa: std.mem.Allocator, text: []const u8) !*Pardes { + const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24 }); + errdefer p.deinit(); + while (p.nextEffect()) |_| {} + _ = try p.setTestFile(text); + while (p.nextEffect()) |_| {} + return p; +} + +pub fn withTerm(gpa: std.mem.Allocator) !*Pardes { + const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24 }); + errdefer p.deinit(); + while (p.nextEffect()) |_| {} + std.debug.assert(p.panes[0].?.isTerminal()); + return p; +} + +pub fn serialOf(p: *Pardes) u32 { + return p.panes[0].?.serial; +} + +pub const Dirent = struct { node: u64, dir: bool, name: []const u8 }; + +pub fn dirents(bytes: []const u8, out: []Dirent) []Dirent { + var n: usize = 0; + var i: usize = 0; + while (i + 10 <= bytes.len and n < out.len) { + const node = std.mem.readInt(u64, bytes[i..][0..8], .little); + const kind = bytes[i + 8]; + const len = bytes[i + 9]; + i += 10; + if (i + len > bytes.len) break; + out[n] = .{ .node = node, .dir = kind == 1, .name = bytes[i .. i + len] }; + i += len; + n += 1; + } + return out[0..n]; +} + +pub fn nameAt(list: []const Dirent, want: []const u8) ?Dirent { + for (list) |d| if (std.mem.eql(u8, d.name, want)) return d; + return null; +} + +pub const FakeTty = struct { + taken: bool, + + pub const vtable: pardes.Host.VTable = .{ .tty_taken = answer }; + + fn answer(ctx: ?*anyopaque, pane: u8) bool { + _ = pane; + const f: *FakeTty = @ptrCast(@alignCast(ctx.?)); + return f.taken; + } +}; diff --git a/src/ninep/tree.zig b/src/ninep/tree.zig new file mode 100644 index 00000000..f716bf5f --- /dev/null +++ b/src/ninep/tree.zig @@ -0,0 +1,850 @@ +//! The control tree served over 9P: its nodes, lookup, readdir and the +//! dispatch that answers the engine in src/9p.zig. The backend contract +//! (Req, Reply, Op, Status, E) lives here; fs.zig keeps host access and mounts. +//! +//! /README /index /ctl /new /log /screen /listeners +//! /pane//{name,body,tag,ctl,addr,data,xdata,sel,errors,event,pty/} +//! /os/... the host filesystem /src/... embedded sources (opt-in) +const std = @import("std"); +const pardes = @import("../pardes.zig"); +const fs = @import("../fs.zig"); +pub const events = @import("events.zig"); +pub const pane = @import("pane.zig"); +pub const addr = @import("addr.zig"); +pub const ctl = @import("ctl.zig"); +pub const pty = @import("pty.zig"); +pub const sources = @import("sources.zig"); +pub const screen = @import("screen.zig"); + +const Pardes = pardes.Pardes; +const Pane = pardes.Pane; +const MAX_PANES = pardes.MAX_PANES; + +pub const name_capacity: usize = 255; + +// ---- the backend contract ---- + +pub const Op = enum(u8) { + lookup, + getattr, + setattr, + open, + read, + write, + release, + readdir, +}; + +pub const Status = enum(u8) { + ok, + again, + err, +}; + +pub const Req = struct { + tag: u64, + op: Op, + node: u64, + handle: u32 = 0, + off: u64 = 0, + size: u32 = 0, + data: []const u8 = &.{}, + truncate: bool = false, + + pub fn changesPane(req: Req) bool { + return switch (req.op) { + .write, .setattr => true, + .open => req.node == @intFromEnum(TopFile.new), + .lookup, .getattr, .read, .release, .readdir => false, + }; + } +}; + +pub const Reply = struct { + tag: u64, + status: Status = .ok, + errno: u16 = 0, + attr: Attr = .{}, + handle: u32 = 0, + payload: Payload = .none, + written: u32 = 0, + + pub const Attr = struct { + name: []const u8 = "", + node: u64 = 0, + dir: bool = false, + size: u64 = 0, + mode: u16 = 0o644, + mtime: u32 = 0, + }; + + pub const Payload = union(enum) { + none, + staged: u32, + region: struct { pane: u8, serial: u32, off: u32, len: u32 }, + }; + + pub fn fail(tag: u64, e: u16) Reply { + return .{ .tag = tag, .status = .err, .errno = e }; + } +}; + +pub const E = struct { + pub const PERM: u16 = 1; + pub const NOENT: u16 = 2; + pub const IO: u16 = 5; + pub const NOMEM: u16 = 12; + pub const NOTDIR: u16 = 20; + pub const INVAL: u16 = 22; + pub const NFILE: u16 = 23; + pub const NOSPC: u16 = 28; + pub const NOSYS: u16 = 38; +}; + +pub const out_reserve = 4 * 1024; + +// ---- nodes ---- + +pub const TopFile = enum(u4) { + root = 1, + README, + index, + ctl, + new, + log, + screen, + listeners, + pane, + + pub fn fileName(f: TopFile) []const u8 { + return if (f == .root) "/" else @tagName(f); + } + + pub fn mode(f: TopFile) u16 { + return switch (f) { + .root, .pane => 0o755, + .ctl => 0o666, + .README, .index, .new, .log, .screen, .listeners => 0o444, + }; + } + + pub fn dir(f: TopFile) bool { + return f == .root or f == .pane; + } +}; + +pub const root: u64 = @intFromEnum(TopFile.root); + +pub const PaneFile = enum(u4) { + dir = 0, + name, + body, + tag, + ctl, + addr, + data, + xdata, + sel, + errors, + event, + pty, + pty_ctl, + pty_status, + pty_data, + + pub fn fileName(f: PaneFile) []const u8 { + return switch (f) { + .dir => ".", + .pty_ctl => "ctl", + .pty_status => "status", + .pty_data => "data", + else => @tagName(f), + }; + } + + pub fn mode(f: PaneFile) u16 { + return switch (f) { + .dir, .pty => 0o755, + .errors, .pty_ctl => 0o222, + .pty_status => 0o444, + else => 0o666, + }; + } + + pub fn isDir(f: PaneFile) bool { + return f == .dir or f == .pty; + } + + pub fn inPty(f: PaneFile) bool { + return switch (f) { + .pty, .pty_ctl, .pty_status, .pty_data => true, + else => false, + }; + } +}; + +pub const Node = packed struct(u64) { + file: u4 = 0, + serial: u60 = 0, + + pub fn of(serial: u32, file: PaneFile) u64 { + std.debug.assert(serial != 0); + return @bitCast(Node{ .file = @intFromEnum(file), .serial = serial }); + } + + pub fn target(node: u64) ?Target { + const n: Node = @bitCast(node); + if (n.serial == 0) { + return .{ .top = std.enums.fromInt(TopFile, n.file) orelse return null }; + } + return .{ .pane = .{ + .serial = std.math.cast(u32, n.serial) orelse return null, + .file = std.enums.fromInt(PaneFile, n.file) orelse return null, + } }; + } +}; + +pub const Target = union(enum) { + top: TopFile, + pane: struct { serial: u32, file: PaneFile }, +}; + +fn paneFileNamed(name: []const u8) ?PaneFile { + const f = std.meta.stringToEnum(PaneFile, name) orelse return null; + if (f == .dir) return null; + return if (f.inPty() and f != .pty) null else f; +} + +fn topFileNamed(name: []const u8) ?TopFile { + const f = std.meta.stringToEnum(TopFile, name) orelse return null; + return if (f == .root) null else f; +} + +fn serialNamed(name: []const u8) ?u32 { + if (name.len == 0 or name.len > 10) return null; + for (name) |c| if (c < '0' or c > '9') return null; + const serial = std.fmt.parseInt(u32, name, 10) catch return null; + return if (serial == 0) null else serial; +} + +pub fn nextSerialAfter(p: *Pardes, after: u32) ?u32 { + var best: ?u32 = null; + for (p.panes) |slot| { + const pn = slot orelse continue; + if (pn.serial <= after) continue; + if (best == null or pn.serial < best.?) best = pn.serial; + } + return best; +} + +/// An editor path below the root (`pane/3/body`, `index`, `src/...`) to its node. +pub fn resolveSelf(p: *Pardes, path: []const u8) ?u64 { + var path_buf: [4096]u8 = undefined; + const normalized = fs.normalizeVirtualPath(path, &path_buf) orelse return null; + var parts = std.mem.tokenizeScalar(u8, normalized, '/'); + const first = parts.next() orelse return root; + if (!std.mem.eql(u8, first, "pane")) { + const top = topFileNamed(first) orelse return sources.node(normalized); + if (top == .pane or parts.next() != null) return null; + return @intFromEnum(top); + } + const serial = serialNamed(parts.next() orelse return @intFromEnum(TopFile.pane)) orelse return null; + const id = p.paneBySerial(serial) orelse return null; + const file = paneFileNamed(parts.next() orelse return Node.of(serial, .dir)) orelse return null; + if (file.inPty() and !p.panes[id].?.isTerminal()) return null; + if (parts.next()) |name| { + if (file != .pty) return null; + const child = pty.fileNamed(name) orelse return null; + if (parts.next() != null) return null; + return Node.of(serial, child); + } + return Node.of(serial, file); +} + +// ---- staging ---- + +pub fn stageDirent(out: *std.ArrayList(u8), gpa: std.mem.Allocator, node: u64, dir: bool, name: []const u8) void { + if (name.len == 0 or name.len > 255) return; + var head: [10]u8 = undefined; + std.mem.writeInt(u64, head[0..8], node, .little); + head[8] = @intFromBool(dir); + head[9] = @intCast(name.len); + out.appendSlice(gpa, &head) catch return; + out.appendSlice(gpa, name) catch return; +} + +/// Answers a read from whatever the handler staged, windowed by offset and size. +pub fn stagedReply(p: *Pardes, req: Req) Reply { + const out = &p.fs.out; + const off = @min(req.off, out.items.len); + const n = @min(out.items.len - off, req.size); + if (off > 0) std.mem.copyForwards(u8, out.items[0..n], out.items[off..][0..n]); + out.shrinkRetainingCapacity(n); + return .{ .tag = req.tag, .payload = .{ .staged = @intCast(n) } }; +} + +// ---- dispatch ---- + +pub fn handle(p: *Pardes, req: Req) Reply { + if (req.node == fs.os_root or req.node & fs.os_node != 0) return fs.osHandle(p, req); + if (req.node & sources.archive_node != 0) return sources.handle(p, req); + const target = Node.target(req.node) orelse return Reply.fail(req.tag, E.NOENT); + if (req.op == .write or req.op == .setattr) p.fs.origin = switch (target) { + .pane => |t| @as(u8, if (t.file == .body or t.file == .tag) 'E' else 'F'), + .top => 'F', + }; + return switch (req.op) { + .lookup => lookup(p, req, target), + .getattr => attrReply(p, req.tag, target), + .setattr => setattr(p, req, target), + .open => open(p, req, target), + .release => release(p, req), + .readdir => readdir(p, req, target), + .read => read(p, req, target), + .write => write(p, req, target), + }; +} + +fn attrOf(p: *Pardes, target: Target) ?Reply.Attr { + switch (target) { + .top => |f| return .{ + .name = f.fileName(), + .node = @intFromEnum(f), + .dir = f.dir(), + .mode = f.mode(), + .size = topSize(p, f), + .mtime = p.fs.started, + }, + .pane => |t| { + const id = p.paneBySerial(t.serial) orelse return null; + const pn = p.panes[id].?; + if (t.file.inPty() and !pn.isTerminal()) return null; + return .{ + .name = if (t.file == .dir) (std.fmt.bufPrint(&p.fs.node_name, "{d}", .{t.serial}) catch unreachable) else t.file.fileName(), + .node = Node.of(t.serial, t.file), + .dir = t.file.isDir(), + .mode = t.file.mode(), + .size = pane.fileSize(p, id, t.file), + .mtime = pane.mtimeOf(p, pn), + }; + }, + } +} + +fn attrReply(p: *Pardes, tag: u64, target: Target) Reply { + const a = attrOf(p, target) orelse return Reply.fail(tag, E.NOENT); + return .{ .tag = tag, .attr = a }; +} + +fn topSize(p: *Pardes, f: TopFile) u64 { + return switch (f) { + .root, .pane, .new, .log, .screen, .listeners => 0, + .index => pane.indexLen(p), + .README => fs.help.len, + .ctl => ctl: { + var buf: [ctl.root_text_cap]u8 = undefined; + break :ctl ctl.rootText(p, &buf).len; + }, + }; +} + +fn lookup(p: *Pardes, req: Req, target: Target) Reply { + const name = req.data; + if (std.mem.eql(u8, name, "..")) { + const parent: u64 = switch (target) { + .top => |top| if (top.dir()) root else return Reply.fail(req.tag, E.NOTDIR), + .pane => |t| switch (t.file) { + .dir => @intFromEnum(TopFile.pane), + .pty => Node.of(t.serial, .dir), + else => return Reply.fail(req.tag, E.NOTDIR), + }, + }; + return handle(p, .{ .tag = req.tag, .op = .getattr, .node = parent }); + } + if (name.len == 0 or std.mem.indexOfAny(u8, name, "/\x00") != null) return Reply.fail(req.tag, E.NOENT); + const node: u64 = switch (target) { + .top => |f| switch (f) { + .root => root: { + if (std.mem.eql(u8, name, "os")) return fs.osHandle(p, .{ .tag = req.tag, .op = .getattr, .node = fs.os_root }); + if (topFileNamed(name)) |t| break :root @intFromEnum(t); + if (sources.node(name)) |n| return sources.handle(p, .{ .tag = req.tag, .op = .getattr, .node = n }); + return Reply.fail(req.tag, E.NOENT); + }, + .pane => pane: { + const serial = serialNamed(name) orelse return Reply.fail(req.tag, E.NOENT); + break :pane Node.of(serial, .dir); + }, + else => return Reply.fail(req.tag, E.NOTDIR), + }, + .pane => |t| pane: { + _ = p.paneBySerial(t.serial) orelse return Reply.fail(req.tag, E.NOENT); + const f = switch (t.file) { + .dir => paneFileNamed(name), + .pty => pty.fileNamed(name), + else => return Reply.fail(req.tag, E.NOTDIR), + } orelse return Reply.fail(req.tag, E.NOENT); + break :pane Node.of(t.serial, f); + }, + }; + return attrReply(p, req.tag, Node.target(node) orelse return Reply.fail(req.tag, E.NOENT)); +} + +fn stagePaneFiles(p: *Pardes, out: *std.ArrayList(u8), serial: u32, terminal: bool, skip: *u64) void { + inline for (comptime std.enums.values(PaneFile)) |f| { + if (comptime f == .dir or (f.inPty() and f != .pty)) continue; + const present = f != .pty or terminal; + if (present) { + if (skip.* > 0) skip.* -= 1 else stageDirent(out, p.gpa, Node.of(serial, f), f.isDir(), f.fileName()); + } + } +} + +fn stagePtyFiles(p: *Pardes, out: *std.ArrayList(u8), serial: u32, skip: *u64) void { + inline for (comptime std.enums.values(PaneFile)) |f| { + if (comptime !f.inPty() or f == .pty) continue; + if (skip.* > 0) skip.* -= 1 else stageDirent(out, p.gpa, Node.of(serial, f), false, f.fileName()); + } +} + +fn readdir(p: *Pardes, req: Req, target: Target) Reply { + const out = p.fs.stage(p.gpa); + var skip = req.off; + switch (target) { + .top => |f| switch (f) { + .root => { + inline for (.{ TopFile.README, TopFile.index, TopFile.ctl, TopFile.new, TopFile.log, TopFile.screen, TopFile.listeners, TopFile.pane }) |t| { + if (skip > 0) skip -= 1 else stageDirent(out, p.gpa, @intFromEnum(t), t.dir(), t.fileName()); + } + if (skip > 0) skip -= 1 else stageDirent(out, p.gpa, fs.os_root, true, "os"); + sources.stage(p, out, "", &skip); + }, + .pane => { + var last: u32 = 0; + while (nextSerialAfter(p, last)) |serial| { + last = serial; + if (skip > 0) { + skip -= 1; + continue; + } + var buf: [16]u8 = undefined; + const name = std.fmt.bufPrint(&buf, "{d}", .{serial}) catch unreachable; + stageDirent(out, p.gpa, Node.of(serial, .dir), true, name); + } + }, + else => return Reply.fail(req.tag, E.NOTDIR), + }, + .pane => |t| { + const id = p.paneBySerial(t.serial) orelse return Reply.fail(req.tag, E.NOENT); + const terminal = p.panes[id].?.isTerminal(); + switch (t.file) { + .dir => stagePaneFiles(p, out, t.serial, terminal, &skip), + .pty => { + if (!terminal) return Reply.fail(req.tag, E.NOENT); + stagePtyFiles(p, out, t.serial, &skip); + }, + else => return Reply.fail(req.tag, E.NOTDIR), + } + }, + } + return .{ .tag = req.tag, .payload = .{ .staged = @intCast(out.items.len) } }; +} + +fn newPane(p: *Pardes) ?u32 { + const slot = p.freeSlot() orelse return null; + p.newScratchBelow(p.active); + const pn = p.panes[slot] orelse return null; + return pn.serial; +} + +fn open(p: *Pardes, req: Req, target: Target) Reply { + switch (target) { + .top => |f| switch (f) { + // The clone idiom: each open makes one empty pane; reads answer its serial. + .new => { + const serial = newPane(p) orelse return Reply.fail(req.tag, E.NFILE); + return .{ .tag = req.tag, .handle = serial }; + }, + .screen => return screen.openSnapshot(p, req, true), + .log => p.fs.log_readers +|= 1, + else => {}, + }, + .pane => |t| { + const id = p.paneBySerial(t.serial) orelse return Reply.fail(req.tag, E.NOENT); + const pn = p.panes[id].?; + const pf = &p.fs.panes[id]; + if (t.file.inPty() and !pn.isTerminal()) return Reply.fail(req.tag, E.NOENT); + switch (t.file) { + .body => if (pn.isTerminal()) return screen.openSnapshot(p, req, false), + .ctl => pf.limit = null, + .addr => { + pf.addr = .{}; + pf.limit = null; + }, + .event => { + pf.readers +|= 1; + p.fs.listeners +|= 1; + }, + .pty_data => pf.pty_readers +|= 1, + else => {}, + } + }, + } + return .{ .tag = req.tag, .handle = 1 }; +} + +fn release(p: *Pardes, req: Req) Reply { + if (screen.releaseSnapshot(p, req)) return .{ .tag = req.tag }; + const target = Node.target(req.node) orelse return .{ .tag = req.tag }; + switch (target) { + .top => |f| if (f == .log and p.fs.log_readers > 0) { + p.fs.log_readers -= 1; + if (p.fs.log_readers == 0) p.fs.log.clearAndFree(p.gpa); + }, + .pane => |t| { + if (t.file != .event and t.file != .pty_data) return .{ .tag = req.tag }; + const id = p.paneBySerial(t.serial) orelse return .{ .tag = req.tag }; + const pf = &p.fs.panes[id]; + if (t.file == .pty_data) { + if (pf.pty_readers == 0) return .{ .tag = req.tag }; + pf.pty_readers -= 1; + if (pf.pty_readers == 0) pf.pty_out.clearAndFree(p.gpa); + return .{ .tag = req.tag }; + } + if (pf.readers == 0) return .{ .tag = req.tag }; + pf.readers -= 1; + p.fs.listeners -|= 1; + if (pf.readers == 0) pf.tag_snap.clearAndFree(p.gpa); + }, + } + return .{ .tag = req.tag }; +} + +fn setattr(p: *Pardes, req: Req, target: Target) Reply { + if (req.truncate) switch (target) { + .pane => |t| { + const id = p.paneBySerial(t.serial) orelse return Reply.fail(req.tag, E.NOENT); + if (pane.truncate(p, id, p.panes[id].?, t.file) != .ok) return Reply.fail(req.tag, E.NOMEM); + }, + .top => {}, + }; + return attrReply(p, req.tag, target); +} + +fn read(p: *Pardes, req: Req, target: Target) Reply { + switch (target) { + .top => |f| return switch (f) { + .README => help: { + const off = @min(req.off, fs.help.len); + const bytes = fs.help[off..][0..@min(req.size, fs.help.len - off)]; + p.fs.stage(p.gpa).appendSlice(p.gpa, bytes) catch break :help Reply.fail(req.tag, E.NOMEM); + break :help .{ .tag = req.tag, .payload = .{ .staged = @intCast(bytes.len) } }; + }, + .index => index: { + const out = p.fs.stage(p.gpa); + var last: u32 = 0; + while (nextSerialAfter(p, last)) |serial| { + last = serial; + pane.stageIndexLine(p, out, p.panes[p.paneBySerial(serial).?].?); + } + break :index stagedReply(p, req); + }, + .ctl => ctl.readRoot(p, req), + .new => new: { + if (req.handle == 0) break :new Reply.fail(req.tag, E.INVAL); + p.fs.stage(p.gpa).print(p.gpa, "{d}\n", .{req.handle}) catch break :new Reply.fail(req.tag, E.NOMEM); + break :new stagedReply(p, req); + }, + .log => events.readQueue(p, req, &p.fs.log), + .screen => screen.readSnapshot(p, req, null), + .listeners => screen.readListeners(p, req), + .root, .pane => Reply.fail(req.tag, E.PERM), + }, + .pane => |t| { + const id = p.paneBySerial(t.serial) orelse return Reply.fail(req.tag, E.NOENT); + const pn = p.panes[id].?; + if (t.file.inPty() and !pn.isTerminal()) return Reply.fail(req.tag, E.NOENT); + return pane.read(p, req, id, pn, t.file); + }, + } +} + +fn write(p: *Pardes, req: Req, target: Target) Reply { + switch (target) { + .top => |f| return switch (f) { + .ctl => ctl.writeRoot(p, req), + else => Reply.fail(req.tag, E.PERM), + }, + .pane => |t| { + const id = p.paneBySerial(t.serial) orelse return Reply.fail(req.tag, E.NOENT); + const pn = p.panes[id].?; + if (t.file.inPty() and !pn.isTerminal()) return Reply.fail(req.tag, E.NOENT); + return pane.write(p, req, id, pn, t.file); + }, + } +} + +// ---- tests ---- + +test { + _ = events; + _ = pane; + _ = addr; + _ = ctl; + _ = pty; + _ = sources; + _ = screen; +} + +const testing = std.testing; +const th = @import("testing.zig"); +const config = @import("../config.zig"); +const call = th.call; +const rd = th.rd; +const wr = th.wr; +const rdir = th.rdir; +const look_up = th.look_up; +const withFile = th.withFile; +const serialOf = th.serialOf; + +test "filesystem inspection preserves pending and displayed Look hover" { + const delay = config.look_preview_delay_frames orelse return; + const gpa = testing.allocator; + const p = try withFile(gpa, "alpha beta gamma\n"); + defer p.deinit(); + var frame: std.heap.ArenaAllocator = .init(gpa); + defer frame.deinit(); + _ = try p.render(frame.allocator()); + const rect = p.rects[0]; + p.update(.{ .mouse = .{ + .button = .none, + .kind = .motion, + .col = rect.x + config.GUTTER + config.PREFIX_W + 7, + .row = if (p.settings.tag_bottom) rect.y else rect.y + pardes.BOX_H, + } }); + try testing.expect(p.look_hover_wait != null); + const body = Node.of(serialOf(p), .body); + const screen_node = @intFromEnum(TopFile.screen); + for (0..2) |phase| { + if (phase == 1) { + for (0..delay) |_| p.update(.tick); + try testing.expect(p.look_hover_preview != null); + } + const waiting = p.look_hover_wait; + const preview = p.look_hover_preview; + const requests = [_]Req{ + .{ .tag = 1, .op = .lookup, .node = root, .data = "screen" }, + .{ .tag = 1, .op = .lookup, .node = root, .data = "new" }, + .{ .tag = 1, .op = .getattr, .node = @intFromEnum(TopFile.new) }, + .{ .tag = 2, .op = .getattr, .node = body }, + .{ .tag = 3, .op = .open, .node = body }, + .{ .tag = 4, .op = .read, .node = body, .size = 5 }, + .{ .tag = 5, .op = .release, .node = body, .handle = 1 }, + .{ .tag = 6, .op = .readdir, .node = root, .size = 4096 }, + .{ .tag = 7, .op = .open, .node = screen_node }, + .{ .tag = 8, .op = .read, .node = screen_node, .handle = 1, .size = 32 }, + .{ .tag = 9, .op = .release, .node = screen_node, .handle = 1 }, + }; + for (requests) |req| { + const answer = call(p, req); + try testing.expectEqual(Status.ok, answer.reply.status); + try testing.expect(std.meta.eql(waiting, p.look_hover_wait)); + try testing.expect(std.meta.eql(preview, p.look_hover_preview)); + try testing.expect(p.raw_hover_intent); + } + } + try testing.expectEqual(Status.ok, wr(p, body, "changed").reply.status); + try testing.expect(p.look_hover_wait == null); + try testing.expect(p.look_hover_preview == null); + try testing.expect(!p.raw_hover_intent); +} + +test "filesystem pane creation and truncation cancel Look hover" { + const requests = [_]Req{ + .{ .tag = 2, .op = .open, .node = @intFromEnum(TopFile.new) }, + .{ .tag = 3, .op = .setattr, .node = 0, .truncate = true }, + }; + for (requests) |request| { + const p = try withFile(testing.allocator, "word\n"); + defer p.deinit(); + p.look_hover_wait = .{ .col = 1, .row = 1, .pane = 0, .serial = serialOf(p) }; + p.raw_hover_intent = true; + var req = request; + if (req.op == .setattr) req.node = Node.of(serialOf(p), .body); + try testing.expectEqual(Status.ok, call(p, req).reply.status); + try testing.expect(p.look_hover_wait == null); + try testing.expect(p.look_hover_preview == null); + try testing.expect(!p.raw_hover_intent); + } +} + +test "readdir lists the root and a pane directory without creating anything" { + const gpa = testing.allocator; + const p = try withFile(gpa, "hello\n"); + defer p.deinit(); + const serial = serialOf(p); + var buf: [32]th.Dirent = undefined; + + const before = p.next_serial; + const top_reply = rdir(p, root, 0); + try testing.expectEqual(Status.ok, top_reply.reply.status); + var top_bytes: [4096]u8 = undefined; + @memcpy(top_bytes[0..top_reply.bytes.len], top_reply.bytes); + const top = th.dirents(top_bytes[0..top_reply.bytes.len], &buf); + try testing.expect(top.len >= 9); + for ([_][]const u8{ "README", "index", "ctl", "new", "log", "screen", "listeners", "pane", "os" }, 0..) |name, i| { + try testing.expectEqualStrings(name, top[i].name); + try testing.expectEqual(i >= 7, top[i].dir); + } + try testing.expectEqual(@intFromEnum(TopFile.pane), top[7].node); + try testing.expectEqual(fs.os_root, top[8].node); + var idbuf: [16]u8 = undefined; + try testing.expect(th.nameAt(top, try std.fmt.bufPrint(&idbuf, "{d}", .{serial})) == null); + try testing.expect(th.nameAt(top, "self") == null); + try testing.expect(th.nameAt(top, "cons") == null); + + var rest_buf: [32]th.Dirent = undefined; + const rest = rdir(p, root, 3); + try testing.expectEqual(top.len - 3, th.dirents(rest.bytes, &rest_buf).len); + const eof = rdir(p, root, 99); + try testing.expectEqual(Status.ok, eof.reply.status); + try testing.expectEqual(@as(usize, 0), eof.bytes.len); + + // Walk, stat and open-for-read every top entry a browser would, then every pane file. + for (top) |entry| { + if (std.mem.eql(u8, entry.name, "os")) continue; + const inspected = look_up(p, root, entry.name); + try testing.expectEqual(Status.ok, inspected.reply.status); + try testing.expectEqual(entry.node, inspected.reply.attr.node); + try testing.expectEqual(Status.ok, call(p, .{ .tag = 1, .op = .getattr, .node = entry.node }).reply.status); + try testing.expectEqual(before, p.next_serial); + } + const panes_dir = rdir(p, @intFromEnum(TopFile.pane), 0); + const listed = th.dirents(panes_dir.bytes, &buf); + try testing.expectEqual(@as(usize, 1), listed.len); + try testing.expectEqual(Node.of(serial, .dir), listed[0].node); + + const dir = rdir(p, Node.of(serial, .dir), 0); + const files = th.dirents(dir.bytes, &buf); + try testing.expectEqual(@as(usize, 10), files.len); + for ([_][]const u8{ "name", "body", "tag", "ctl", "addr", "data", "xdata", "sel", "errors", "event" }, 0..) |name, i| + try testing.expectEqualStrings(name, files[i].name); + try testing.expect(th.nameAt(files, ".") == null); + try testing.expect(th.nameAt(files, "rdsel") == null); + try testing.expectEqual(Node.of(serial, .body), th.nameAt(files, "body").?.node); + for (files) |entry| { + const stat = call(p, .{ .tag = 1, .op = .getattr, .node = entry.node }); + try testing.expectEqual(Status.ok, stat.reply.status); + try testing.expectEqual(p.fs.started, stat.reply.attr.mtime); + } + try testing.expectEqual(before, p.next_serial); + + try testing.expectEqual(E.NOTDIR, rdir(p, Node.of(serial, .body), 0).errno()); + try testing.expectEqual(E.NOTDIR, rdir(p, @intFromEnum(TopFile.index), 0).errno()); +} + +test "lookup resolves top files, pane serials and pane files" { + const gpa = testing.allocator; + const p = try withFile(gpa, "hello\n"); + defer p.deinit(); + const serial = serialOf(p); + + try testing.expectEqual(@as(u64, @intFromEnum(TopFile.index)), look_up(p, root, "index").reply.attr.node); + try testing.expect(!look_up(p, root, "new").reply.attr.dir); + try testing.expectEqual(@as(u16, 0o444), look_up(p, root, "new").reply.attr.mode); + try testing.expect(look_up(p, root, "pane").reply.attr.dir); + try testing.expect(look_up(p, root, "os").reply.attr.dir); + try testing.expectEqual(E.NOENT, look_up(p, root, "nosuchthing").errno()); + try testing.expectEqual(E.NOENT, look_up(p, root, "self").errno()); + try testing.expectEqual(E.NOENT, look_up(p, root, "cons").errno()); + try testing.expectEqual(E.NOTDIR, look_up(p, @intFromEnum(TopFile.index), "x").errno()); + + var idbuf: [16]u8 = undefined; + const serial_name = try std.fmt.bufPrint(&idbuf, "{d}", .{serial}); + try testing.expectEqual(E.NOENT, look_up(p, root, serial_name).errno()); + const dir = look_up(p, @intFromEnum(TopFile.pane), serial_name); + try testing.expectEqual(Node.of(serial, .dir), dir.reply.attr.node); + try testing.expect(dir.reply.attr.dir); + try testing.expectEqualStrings(serial_name, dir.reply.attr.name); + try testing.expectEqual(E.NOENT, look_up(p, @intFromEnum(TopFile.pane), "99999").errno()); + try testing.expectEqual(E.NOENT, look_up(p, @intFromEnum(TopFile.pane), "0").errno()); + + const body = look_up(p, Node.of(serial, .dir), "body"); + try testing.expectEqual(Node.of(serial, .body), body.reply.attr.node); + const stat = call(p, .{ .tag = 4, .op = .getattr, .node = Node.of(serial, .body) }); + try testing.expectEqual(body.reply.attr.size, stat.reply.attr.size); + try testing.expectEqual(@as(u64, "hello\n".len), stat.reply.attr.size); + try testing.expectEqual(E.NOENT, look_up(p, Node.of(serial, .dir), "editout").errno()); + try testing.expectEqual(E.NOENT, look_up(p, Node.of(serial, .dir), "rdsel").errno()); + try testing.expectEqual(E.NOTDIR, look_up(p, Node.of(serial, .body), "x").errno()); +} + +test "each open of new creates exactly one pane whose serial the read answers" { + const gpa = testing.allocator; + const p = try withFile(gpa, "first\n"); + defer p.deinit(); + const before = p.next_serial; + const new = @intFromEnum(TopFile.new); + + try testing.expectEqual(Status.ok, look_up(p, root, "new").reply.status); + try testing.expectEqual(Status.ok, call(p, .{ .tag = 1, .op = .getattr, .node = new }).reply.status); + try testing.expectEqual(before, p.next_serial); + + const opened = call(p, .{ .tag = 1, .op = .open, .node = new }); + try testing.expectEqual(Status.ok, opened.reply.status); + try testing.expectEqual(before + 1, p.next_serial); + try testing.expectEqual(before + 1, opened.reply.handle); + try testing.expectEqual(@as(u64, 0), opened.reply.attr.node); + var expected: [16]u8 = undefined; + const line = try std.fmt.bufPrint(&expected, "{d}\n", .{opened.reply.handle}); + try testing.expectEqualStrings(line, call(p, .{ .tag = 2, .op = .read, .node = new, .handle = opened.reply.handle, .size = 64 }).bytes); + try testing.expectEqualStrings(line[1..], call(p, .{ .tag = 2, .op = .read, .node = new, .handle = opened.reply.handle, .off = 1, .size = 64 }).bytes); + try testing.expectEqualStrings("", call(p, .{ .tag = 2, .op = .read, .node = new, .handle = opened.reply.handle, .off = line.len, .size = 64 }).bytes); + try testing.expectEqual(before + 1, p.next_serial); + _ = call(p, .{ .tag = 3, .op = .release, .node = new, .handle = opened.reply.handle }); + + const id = p.paneBySerial(opened.reply.handle).?; + try testing.expectEqualStrings("", p.panes[id].?.file.?.content); + _ = wr(p, Node.of(opened.reply.handle, .body), "hi"); + const second = call(p, .{ .tag = 4, .op = .open, .node = new }); + try testing.expectEqual(Status.ok, second.reply.status); + try testing.expect(second.reply.handle != opened.reply.handle); + try testing.expectEqualStrings("hi", p.panes[id].?.file.?.content); + try testing.expectEqual(E.INVAL, call(p, .{ .tag = 5, .op = .read, .node = new, .size = 64 }).errno()); +} + +test "directories walk to their parents" { + const p = try withFile(testing.allocator, "contents\n"); + defer p.deinit(); + for ([_]struct { node: u64, parent: u64 }{ + .{ .node = root, .parent = root }, + .{ .node = @intFromEnum(TopFile.pane), .parent = root }, + .{ .node = Node.of(serialOf(p), .dir), .parent = @intFromEnum(TopFile.pane) }, + .{ .node = fs.os_root, .parent = root }, + }) |case| { + const result = look_up(p, case.node, ".."); + try testing.expectEqual(Status.ok, result.reply.status); + try testing.expectEqual(case.parent, result.reply.attr.node); + } + try testing.expectEqual(E.NOTDIR, look_up(p, @intFromEnum(TopFile.index), "..").errno()); + try testing.expectEqual(E.NOTDIR, look_up(p, Node.of(serialOf(p), .body), "..").errno()); +} + +test "editor paths resolve to the same nodes the wire serves" { + const p = try withFile(testing.allocator, "contents\n"); + defer p.deinit(); + const serial = serialOf(p); + var path: [64]u8 = undefined; + try testing.expectEqual(root, resolveSelf(p, "").?); + try testing.expectEqual(root, resolveSelf(p, "/./pane/../").?); + try testing.expectEqual(@intFromEnum(TopFile.index), resolveSelf(p, "index").?); + try testing.expectEqual(@intFromEnum(TopFile.new), resolveSelf(p, "new").?); + try testing.expectEqual(@intFromEnum(TopFile.pane), resolveSelf(p, "pane").?); + try testing.expectEqual(Node.of(serial, .dir), resolveSelf(p, try std.fmt.bufPrint(&path, "pane/{d}", .{serial})).?); + try testing.expectEqual(Node.of(serial, .sel), resolveSelf(p, try std.fmt.bufPrint(&path, "pane/{d}/sel", .{serial})).?); + try testing.expect(resolveSelf(p, try std.fmt.bufPrint(&path, "pane/{d}/pty/ctl", .{serial})) == null); + try testing.expect(resolveSelf(p, try std.fmt.bufPrint(&path, "pane/{d}/rdsel", .{serial})) == null); + try testing.expect(resolveSelf(p, "self/index") == null); + try testing.expect(resolveSelf(p, "new/ctl") == null); + try testing.expect(resolveSelf(p, "cons") == null); + try testing.expect(resolveSelf(p, "pane/0") == null); +} diff --git a/src/panes.zig b/src/panes.zig index 49e5d624..edd7038f 100644 --- a/src/panes.zig +++ b/src/panes.zig @@ -1014,6 +1014,8 @@ pub const File = struct { /// Equal means the screen matches disk. saved_revision: u32 = 0, watch_after_save: bool = false, + /// Seconds of the last content change, for the filesystem's stat; zero until edited. + mtime: u32 = 0, /// Non-null for a generated output buffer rather than an on-disk file. output: ?Output.State = null, mini: ?Mini.State = null, @@ -1702,7 +1704,7 @@ pub const File = struct { const pane = slot orelse continue; if (pane.file) |*state| if (state == f) break i; } else return; - pardes.filesystem.noteReplace(p, id, false, f.content, new); + pardes.ctlfs.events.noteReplace(p, id, false, f.content, new); } pub fn setContent(p: *Pardes, f: *State, new: []u8) void { @@ -1722,6 +1724,7 @@ pub const File = struct { p.gpa.free(f.content); f.content = new; f.revision +%= 1; + f.mtime = pardes.ctlfs.events.now(); if (f.line_starts.len > 0) p.gpa.free(f.line_starts); f.line_starts = &.{}; if (f.highlights.len > 0) p.tree_sitter_gpa.free(f.highlights); @@ -2876,6 +2879,8 @@ pub const Output = struct { else => return error.NotAnEffect, } if (!setting.enabled(builtins.capabilities)) return error.EffectUnavailable; + // Without -Dembed-sources the paths would name nothing this build can open. + if (!limits.embedded_sources) return error.EffectUnavailable; const paths = effect_sources.forSetting(setting) orelse return error.EffectUnavailable; diff --git a/src/pardes.zig b/src/pardes.zig index 5c0ac263..88442542 100644 --- a/src/pardes.zig +++ b/src/pardes.zig @@ -6,6 +6,7 @@ const mvzr = @import("mvzr"); pub const modal = @import("modal.zig"); pub const look = @import("look.zig"); pub const filesystem = @import("fs.zig"); +pub const ctlfs = @import("ninep/tree.zig"); pub const syntax = @import("syntax.zig"); pub const locations_config = @import("locations_config.zig"); const tracy = @import("tracy.zig"); @@ -4711,7 +4712,7 @@ pub const Event = union(enum) { /// this must not clamp onto and preview the final grid cell. pointer_leave, tick, - fs_req: filesystem.Req, + fs_req: ctlfs.Req, }; pub const attach_name_max = 256; @@ -4749,7 +4750,7 @@ pub const Effect = union(enum) { /// Write the build-time theme ring below the per-user config directory. /// The pane receives the completion/error message from the native host. dump_themes: struct { pane: u8 }, - fs_reply: filesystem.Reply, + fs_reply: ctlfs.Reply, attach: struct { pane: u8, name: Buf(attach_name_max) }, detach: struct { pane: u8 }, quit, @@ -6109,6 +6110,7 @@ pub const Pardes = struct { .fallback = .{ .gpa = gpa }, }; errdefer p.deinit(); + p.fs.started = ctlfs.events.now(); for (opts.mounts) |mount| try p.fs.mount(gpa, mount.name, mount.dial); p.opts.mounts = &.{}; p.opts.ninep_identity = .{}; @@ -6335,6 +6337,7 @@ pub const Pardes = struct { const watched = (if (pane.file) |f| f.output == null else false) or pane.hasPdf(); for (p.panes, 0..) |slot, id| if (slot == pane) { if (watched) p.emit(.{ .watch = .{ .pane = @intCast(id), .on = false } }); + ctlfs.events.noteRetire(p, id, pane); p.fs.forget(p.gpa, id); // ...and so do bytes still queued for the pty it no longer has. p.dropPendingWrite(id); @@ -6380,6 +6383,7 @@ pub const Pardes = struct { pane.serial = p.next_serial; p.rects[id] = .{}; p.panes[id] = pane; + ctlfs.events.noteInstall(p, id); } pub fn newShell(p: *Pardes, id: usize, cwd: []const u8) !*Pane { @@ -6924,7 +6928,7 @@ pub const Pardes = struct { return pane.pdfPath(); } - pub fn fsPayload(p: *const Pardes, r: filesystem.Reply) []const u8 { + pub fn fsPayload(p: *const Pardes, r: ctlfs.Reply) []const u8 { return switch (r.payload) { .none => &.{}, .staged => |n| p.fs.out.items[0..@min(n, p.fs.out.items.len)], @@ -6961,6 +6965,7 @@ pub const Pardes = struct { p.hostWriteFile(sf.pane, f.path, f.content); const saved_pane = p.panes[sf.pane] orelse return; if (saved_pane.serial != serial) return; + ctlfs.events.noteLog(p, .save, saved_pane); const saved = if (saved_pane.file) |*file| file else return; if (saved.saved_revision != saved.revision or !saved.watch_after_save) return; saved.watch_after_save = false; @@ -7116,7 +7121,7 @@ pub const Pardes = struct { }, .output => |o| { const pane = p.panes[o.pane] orelse return; - filesystem.notePtyOutput(p, o.pane, o.bytes); + ctlfs.events.notePtyOutput(p, o.pane, o.bytes); panes.Terminal.feedOutput(p, pane, o.bytes); }, .eof => |e| p.removePane(e.pane) catch |err| { @@ -7146,7 +7151,7 @@ pub const Pardes = struct { }, .paste => |bytes| p.applyPaste(bytes), .command => |line| _ = p.executeBuiltinLine(p.active, line), - .fs_req => |r| p.emit(.{ .fs_reply = filesystem.handle(p, r) }), + .fs_req => |r| p.emit(.{ .fs_reply = ctlfs.handle(p, r) }), .pinch => |scale| p.ov_pinch_scale = scale, .touch_scroll => |delta| p.ov_touch_scroll_delta = delta, .pointer_leave => { @@ -7163,6 +7168,7 @@ pub const Pardes = struct { _ = p.scratch.reset(.retain_capacity); p.sync(); p.fsReport(); + ctlfs.events.announce(p); } fn fsReport(p: *Pardes) void { @@ -7174,7 +7180,7 @@ pub const Pardes = struct { const snap = &p.fs.panes[id].tag_snap; if (std.mem.eql(u8, snap.items, tag)) continue; if (snap.capacity != 0 or snap.items.len != 0) - filesystem.noteReplace(p, id, true, snap.items, tag); + ctlfs.events.noteReplace(p, id, true, snap.items, tag); snap.clearRetainingCapacity(); snap.appendSlice(p.gpa, tag) catch {}; } @@ -7451,7 +7457,7 @@ pub const Pardes = struct { p.reportError(id, "name", err); return false; }; - filesystem.nameBuffer(p, id, full, true) catch |err| { + ctlfs.pane.nameBuffer(p, id, full, true) catch |err| { p.reportError(id, "name", err); return false; }; @@ -11673,21 +11679,21 @@ pub const Pardes = struct { ) bool { if (!p.fs.scripted(id)) return false; const is_look = cmd == config.look_cmd; - const action: filesystem.Action = if (is_look) + const action: ctlfs.events.Action = if (is_look) (if (on_tag) .tag_look else .body_look) else (if (on_tag) .tag_exec else .body_exec); const named = std.meta.stringToEnum(Builtin, commandText(text)) != null; const range = p.gestureRange(id, text, on_tag, operand); - var flag: u32 = if (named) filesystem.flag_builtin else 0; - if (range.q0 == range.q1 and text.len > 0) flag |= filesystem.flag_expansion; + var flag: u32 = if (named) ctlfs.events.flag_builtin else 0; + if (range.q0 == range.q1 and text.len > 0) flag |= ctlfs.events.flag_expansion; if (is_look) { - if (!named and std.mem.indexOfAny(u8, text, "/.:") != null) flag |= filesystem.flag_filename; - } else if (chorded) flag |= filesystem.flag_chorded; - return filesystem.noteAction(p, id, action, range.q0, range.q1, flag, text); + if (!named and std.mem.indexOfAny(u8, text, "/.:") != null) flag |= ctlfs.events.flag_filename; + } else if (chorded) flag |= ctlfs.events.flag_chorded; + return ctlfs.events.noteAction(p, id, action, range.q0, range.q1, flag, text); } - fn gestureRange(p: *Pardes, id: usize, text: []const u8, on_tag: bool, operand: PointerOperand) filesystem.PaneState.Range { + fn gestureRange(p: *Pardes, id: usize, text: []const u8, on_tag: bool, operand: PointerOperand) ctlfs.pane.State.Range { const pane = p.panes[id] orelse return .{}; if (on_tag) { const tag = p.tagText(p.scratch.allocator(), pane) catch return .{}; diff --git a/src/tutor.txt b/src/tutor.txt index ae22ede9..394a48a3 100644 --- a/src/tutor.txt +++ b/src/tutor.txt @@ -387,29 +387,30 @@ typed pardes the 9P socket opens by default - A directory per pane holding `body`, `tag`, `ctl`, `addr`, `data`, - `event`, `pty/` and the rest, plus `index`, `cons` and `new/` at the - top under /self. Every pane shell receives `$PARDES_9P` (the socket) - and `$PARDES_PANE` (its serial). Use a 9P client to read and write: + A directory per pane holding `name`, `body`, `tag`, `ctl`, `addr`, + `data`, `sel`, `event`, `pty/` and the rest, plus `index`, `ctl`, + `new` and `log` at the root. Every pane shell receives `$PARDES_9P` + (the socket) and `$PARDES_PANE` (its serial). Use a 9P client: - /self/pane//body - /self/index - /self/new/ctl + /pane//body + /index + /new reading it makes a pane, answers its serial + /ctl `look FILE:12` and `exec Save`, as the mouse does A terminal pane also has `pty/`: - /self/pane/3/pty/ctl winsize, sig - /self/pane/3/pty/data terminal input/output + /pane/3/pty/ctl winsize, sig + /pane/3/pty/data terminal input/output Over 9P the same tree answers plan9port, from anywhere: 9p -a $XDG_RUNTIME_DIR/pardes-9p-work.sock ls / - 9p -a $XDG_RUNTIME_DIR/pardes-9p-work.sock read /self/index + 9p -a $XDG_RUNTIME_DIR/pardes-9p-work.sock read index ...and pardes is a 9P CLIENT too, so one session can read another's: pardes --mount=peer=work - /n/peer/self/pane/1/body Look opens the other session's body + /n/peer/pane/1/body Look opens the other session's body TWO THINGS WORTH KNOWING. While a program holds a pane's `event` file open, MIDDLE AND RIGHT CLICKS IN THAT PANE BELONG TO IT: pardes reports @@ -467,7 +468,7 @@ typed SPC is the leader (SPC ? lists every path) SCRIPTING 9P is served by default on $PARDES_9P - /self/pane//{body,tag,ctl,addr,data,event,pty/} + /pane//{name,body,tag,ctl,addr,data,sel,event,pty/} a script holding `event` owns that pane's middle and right clicks; writing a record back runs it diff --git a/test/agent_session.py b/test/agent_session.py index b920b006..aa87c845 100644 --- a/test/agent_session.py +++ b/test/agent_session.py @@ -52,21 +52,21 @@ def run(args, command, status): client, _ = context.__enter__() try: try: - while not client.read('/self/pane/1/body').strip(): + while not client.read('/pane/1/body').strip(): time.sleep(.01) started = time.monotonic() - client.write('/self/pane/1/pty/data', shlex.join(['/bin/sh', str(script)]).encode() + b'\r') + client.write('/pane/1/pty/data', shlex.join(['/bin/sh', str(script)]).encode() + b'\r') status['phase'] = 'readiness' wait_ready(client, args.ready) if args.prepare_key is not None: status['phase'] = 'preparation' - client.write('/self/pane/1/pty/data', args.prepare_key) + client.write('/pane/1/pty/data', args.prepare_key) wait_ready(client, args.ready) ready_ms = (time.monotonic() - started) * 1000 status.update(phase='history', required_body_rows=args.min_rows) while True: started = time.monotonic() - body = client.read('/self/pane/1/body') + body = client.read('/pane/1/body') body_read_ms = (time.monotonic() - started) * 1000 rows = body.count(b'\n') + int(bool(body) and not body.endswith(b'\n')) status.update(body_bytes=len(body), body_rows=rows) @@ -81,13 +81,13 @@ def run(args, command, status): raise AssertionError('probe is already visible') status['phase'] = 'probe-visible' started = time.monotonic() - client.write('/self/pane/1/pty/data', probe.encode()) + client.write('/pane/1/pty/data', probe.encode()) while probe not in screen_text(client).replace('\n', ''): time.sleep(.01) write_ms = (time.monotonic() - started) * 1000 status['phase'] = 'probe-cleared' started = time.monotonic() - client.write('/self/pane/1/pty/data', b'\x15') + client.write('/pane/1/pty/data', b'\x15') while True: observed = screen_text(client) status['observed_visible_text_sha256'] = hashlib.sha256(observed.encode()).hexdigest() @@ -109,7 +109,7 @@ def run(args, command, status): client.socket.settimeout(.25) for _ in range(2): try: - client.write('/self/pane/1/pty/data', b'\x03') + client.write('/pane/1/pty/data', b'\x03') except (OSError, EOFError): pass time.sleep(.05) diff --git a/test/appearance_gallery.py b/test/appearance_gallery.py index 7779efa9..0fa12136 100644 --- a/test/appearance_gallery.py +++ b/test/appearance_gallery.py @@ -80,21 +80,21 @@ def run(args): before = set(panes(client)) command(client, source, 'Newcol') right = require(wait_for(lambda: next((s for s in panes(client) if s not in before), None)), 'right column missing') - client.write(f'/self/pane/{right}/ctl', f'name {root / "Review"}\n'.encode()) - client.write(f'/self/pane/{right}/body', PREFERENCE_NOTES if args.theme_selector else NOTES, truncate=True) - client.write(f'/self/pane/{right}/ctl', b'clean\n') + client.write(f'/pane/{right}/name', f'{root / "Review"}\n'.encode()) + client.write(f'/pane/{right}/body', PREFERENCE_NOTES if args.theme_selector else NOTES, truncate=True) + client.write(f'/pane/{right}/ctl', b'clean\n') before = set(panes(client)) command(client, right, 'Tty') terminal = require(wait_for(lambda: next((s for s in panes(client) if s not in before), None)), 'terminal missing') - client.write(f'/self/pane/{terminal}/pty/data', b"PS1='$ '; printf '\\033[2J\\033[H\\033[1;36mPardes workspace\\033[0m\\n\\n'; printf 'Agave source: read-only\\nTerminal: ready\\n\\n'; printf '\\033[32mSmall touches. Same workflow.\\033[0m\\n'\r") - require(wait_for(lambda: b'Small touches. Same workflow.' in client.read(f'/self/pane/{terminal}/body')), 'terminal output missing') + client.write(f'/pane/{terminal}/pty/data', b"PS1='$ '; printf '\\033[2J\\033[H\\033[1;36mPardes workspace\\033[0m\\n\\n'; printf 'Agave source: read-only\\nTerminal: ready\\n\\n'; printf '\\033[32mSmall touches. Same workflow.\\033[0m\\n'\r") + require(wait_for(lambda: b'Small touches. Same workflow.' in client.read(f'/pane/{terminal}/body')), 'terminal output missing') def config_report(): before = set(panes(client)) command(client, right, 'Config') pane = require(wait_for(lambda: next((s for s in panes(client) if s not in before), None)), 'Config output missing') - text = client.read(f'/self/pane/{pane}/body').decode() - client.write(f'/self/pane/{pane}/ctl', b'del\n') + text = client.read(f'/pane/{pane}/body').decode() + client.write(f'/pane/{pane}/ctl', b'exec Del\n') return text settings = config_report() @@ -135,7 +135,7 @@ def run(args): command(client, right, 'Theme ' + theme) if args.theme_selector: # Keep both quiet active gutter ink and vivid comments in view. - client.write(f'/self/pane/{source}/ctl', f'look {source_path}:117\n'.encode()) + client.write(f'/pane/{source}/ctl', f'look {source_path}:117\n'.encode()) take_frame('classic-' + theme) if args.theme_selector: frame = client.screen() @@ -162,7 +162,7 @@ def run(args): command(client, right, 'ThemeSel') selector = require(wait_for(lambda: next((s for s in panes(client) if s not in before), None)), 'ThemeSel missing') - body = client.read(f'/self/pane/{selector}/body').decode() + body = client.read(f'/pane/{selector}/body').decode() native, legacy = body.split('# Legacy and imported themes', 1) for theme in ('forge_black', 'forge_soft', 'orchard_black'): require('Theme ' + theme + '\n' in native, 'native contrast variant below legacy heading') @@ -171,14 +171,14 @@ def run(args): 'ThemeSel did not open at native first entry') take_frame('theme-selector') report['native_themes_first'] = True - client.write(f'/self/pane/{selector}/ctl', b'del\n') + client.write(f'/pane/{selector}/ctl', b'exec Del\n') command(client, terminal, 'Collapse') for pet in (() if args.skip_pets else ('cat', 'frog', 'off')): command(client, right, 'Pet ' + pet) settings = config_report() require('Pet: ' + pet + '\n' in settings, 'pet setting not applied') # Returning focus to the source closes all transient report state. - client.write(f'/self/pane/{source}/ctl', f'look {source_path}:1\n'.encode()) + client.write(f'/pane/{source}/ctl', f'look {source_path}:1\n'.encode()) take_frame('pet-' + pet) if pet != 'off': frame = client.screen() @@ -194,9 +194,9 @@ def run(args): require(band_digest('pet-' + pet) != band_digest('pet-' + pet + '-later'), 'pet did not animate in workspace tag') report['pets'].append(pet) - require(client.read(f'/self/pane/{source}/body') == original == source_path.read_bytes(), 'Agave source changed') + require(client.read(f'/pane/{source}/body') == original == source_path.read_bytes(), 'Agave source changed') report['source_unchanged'] = True - client.write(f'/self/pane/{terminal}/pty/data', b'exit\r') + client.write(f'/pane/{terminal}/pty/data', b'exit\r') (root / 'report.json').write_text(json.dumps(report, indent=2)) print(json.dumps(report, indent=2)) diff --git a/test/collapse_layout.py b/test/collapse_layout.py index e549bd37..244ee57a 100644 --- a/test/collapse_layout.py +++ b/test/collapse_layout.py @@ -29,7 +29,7 @@ def geometry(client, names): def toggle(client, serial): """Execute the default tag's Collapse word without changing any body or tag.""" - pane = f'/self/pane/{serial}' + pane = f'/pane/{serial}' tag = client.read(pane + '/tag') at = tag.rfind(b' Collapse') require(at >= 0, 'default pane tag lacks Collapse') @@ -57,8 +57,8 @@ def run(args): for index, label in enumerate(names): if index: serials.append(new_pane(client, b'')) - pane = f'/self/pane/{serials[index]}' - client.write(pane + '/ctl', ('name ' + label + '\n').encode()) + pane = f'/pane/{serials[index]}' + client.write(pane + '/name', (label + '\n').encode()) client.write(pane + '/body', contents, truncate=True) original = require(wait_for(lambda: geometry(client, names)), 'four pane tags not visible') require(all(height > 1 for _, height in original), f'fixture has no body room: {original}') @@ -82,7 +82,7 @@ def run(args): require(wait_for(lambda: geometry(client, names) == original), f'expansion did not restore original geometry: {geometry(client, names)}') for serial in serials: - require(client.read(f'/self/pane/{serial}/body') == contents, 'Collapse changed pane contents') + require(client.read(f'/pane/{serial}/body') == contents, 'Collapse changed pane contents') require((root / (name + '.txt')).read_bytes() == b'initial\n', 'fixture source file changed') print(f'{"TTY" if args.tty else "SDL"}: 7 local collapse/expand pairs, exact unrelated pane geometry, and content preservation passed') diff --git a/test/column_tags.py b/test/column_tags.py index 6173d38a..80b623bd 100644 --- a/test/column_tags.py +++ b/test/column_tags.py @@ -70,7 +70,7 @@ def await_text(client, row, text): def tag(client, serial): - return client.read(f'/self/pane/{serial}/tag').decode().rstrip('\n') + return client.read(f'/pane/{serial}/tag').decode().rstrip('\n') def new_serial(client, previous): @@ -79,10 +79,10 @@ def new_serial(client, previous): def exec_tag_without_cleanup(client, serial, text): """Restore can replace the whole core, so never touch the old pane after it.""" - client.write(f'/self/pane/{serial}/tag', (' ' + text).encode()) - whole = client.read(f'/self/pane/{serial}/tag') + client.write(f'/pane/{serial}/tag', (' ' + text).encode()) + whole = client.read(f'/pane/{serial}/tag') start = whole.rfind(text.encode()) - client.write(f'/self/pane/{serial}/event', f'Mx{start} {start + len(text.encode())}\n'.encode()) + client.write(f'/pane/{serial}/event', f'Mx{start} {start + len(text.encode())}\n'.encode()) def reconnect(address): @@ -140,10 +140,10 @@ def run(args): keys.click(*require(locate(client, 'Newcol', row=0), 'Newcol missing'), button=1) right = require(wait_for(lambda: new_serial(client, before)), 'Newcol did not create its pane') right_name = root / 'right.rs' - client.write(f'/self/pane/{right}/ctl', f'name {right_name}\n'.encode()) + client.write(f'/pane/{right}/name', f'{right_name}\n'.encode()) right_body = b'// Column-local scratch\nfn main() {\n let ready = true;\n}\n' - client.write(f'/self/pane/{right}/body', right_body) - client.write(f'/self/pane/{right}/ctl', b'clean\n') + client.write(f'/pane/{right}/body', right_body) + client.write(f'/pane/{right}/ctl', b'clean\n') require(wait_for(lambda: locate(client, 'New Tty', row=1, minimum_col=75)), 'right column tag missing') require(locate(client, 'New Tty', row=1, minimum_col=75) == (75, 1), 'right column tag retains an inset') @@ -171,9 +171,9 @@ def run(args): before = panes(client) keys.click(col_start, 1, button=1) extra = require(wait_for(lambda: new_serial(client, before)), 'right-column New did not create a pane') - client.write(f'/self/pane/{extra}/body', b'RIGHT-COLUMN-NEW\n') + client.write(f'/pane/{extra}/body', b'RIGHT-COLUMN-NEW\n') require(wait_for(lambda: locate(client, 'RIGHT-COLUMN-NEW', minimum_col=75)), 'right-column command targeted another column') - client.write(f'/self/pane/{extra}/ctl', b'delete\n') + client.write(f'/pane/{extra}/ctl', b'exec Del\n') checks.append('middle-click New targets the inactive right column') # An owned short-path file makes its complete tag visible. Pane-tag @@ -197,7 +197,7 @@ def run(args): keys.escape() require(wait_for(lambda: tag(client, right).startswith(str(right_name) + ' ')), 'Escape did not cancel filename draft') require(not (root / 'Xright.rs').exists(), 'editing a filename wrote a file') - require(client.read(f'/self/pane/{right}/body') == right_body, 'tag editing changed file body') + require(client.read(f'/pane/{right}/body') == right_body, 'tag editing changed file body') checks.append('filename draft cancels without disk writes or body changes') # Keep a real embedded shell in the right column for useful captures. @@ -205,9 +205,9 @@ def run(args): before = panes(client) keys.click(*require(locate(client, 'Tty', row=1, minimum_col=75), 'Tty missing'), button=1) terminal = require(wait_for(lambda: new_serial(client, before)), 'column Tty did not create a pane') - require('pty' in client.list(f'/self/pane/{terminal}'), 'Tty created a non-terminal pane') - client.write(f'/self/pane/{terminal}/pty/data', b"printf 'Column-local terminal ready\\n'; pwd\r") - require(wait_for(lambda: b'\nColumn-local terminal ready\n' in client.read(f'/self/pane/{terminal}/body').replace(b'\r', b'')), 'terminal command output missing') + require('pty' in client.list(f'/pane/{terminal}'), 'Tty created a non-terminal pane') + client.write(f'/pane/{terminal}/pty/data', b"printf 'Column-local terminal ready\\n'; pwd\r") + require(wait_for(lambda: b'\nColumn-local terminal ready\n' in client.read(f'/pane/{terminal}/body').replace(b'\r', b'')), 'terminal command output missing') checks.append('right-column embedded terminal executes harmless commands') # Persistence is checked through real Dump/Restore dispatch and the @@ -285,11 +285,11 @@ def run(args): capture(client, root, 'columns-tag-reveal', not args.tty) keys.escape() checks.append('long-path pane tag reveals its command tail when the caret moves to End') - require(client.read(f'/self/pane/{source_serial}/body') == original == source.read_bytes(), 'Agave source changed') + require(client.read(f'/pane/{source_serial}/body') == original == source.read_bytes(), 'Agave source changed') checks.append('Agave source bytes unchanged') for serial in panes(client): - if 'pty' in client.list(f'/self/pane/{serial}'): - client.write(f'/self/pane/{serial}/pty/data', b'exit\r') + if 'pty' in client.list(f'/pane/{serial}'): + client.write(f'/pane/{serial}/pty/data', b'exit\r') report = {'checks': checks, 'cols': 150, 'rows': 48, 'host': 'tty' if args.tty else 'sdl', 'input': 'keyboard and SGR mouse through the host PTY parser', 'source': str(source), 'artifacts': str(root)} diff --git a/test/font_size.py b/test/font_size.py index e40b7b3a..3a0a9a28 100644 --- a/test/font_size.py +++ b/test/font_size.py @@ -29,7 +29,7 @@ def run(args): def ready(): for serial, tag in panes(client).items(): if '/+Config ' in tag: - body = client.read(f'/self/pane/{serial}/body').decode() + body = client.read(f'/pane/{serial}/body').decode() if f'Font effective size: {size:.2f} pixels' in body: return body return None diff --git a/test/fs.py b/test/fs.py index 2ffd5098..819a78d6 100644 --- a/test/fs.py +++ b/test/fs.py @@ -72,7 +72,7 @@ def session(binary, root, name, *options, socket_name=None, file=None, tty=False time.sleep(.005) with Client(address) as client: if network is not None: - for dial in client.read('/self/listeners').decode().splitlines(): + for dial in client.read('/listeners').decode().splitlines(): parts = dial.split('!') if parts[0] in ['tcp', 'quic']: assert len(parts) == 3 and 0 < int(parts[2]) < 65536, dial @@ -101,60 +101,136 @@ def session(binary, root, name, *options, socket_name=None, file=None, tty=False def new_pane(client, contents): - serial = int(client.read('/self/new/ctl').split()[0]) - client.write(f'/self/pane/{serial}/body', contents) + serial = int(client.read('/new').split()[0]) + if contents: + client.write(f'/pane/{serial}/body', contents) return serial def look(client, path, source=None): + """A right click on `path` from a pane (a fresh scratch by default).""" serial = source if source is not None else new_pane(client, b'') - client.write(f'/self/pane/{serial}/body', path.encode(), truncate=True) - client.write(f'/self/pane/{serial}/event', f'ML0 {len(path.encode())}\n'.encode()) - rows = client.read('/self/index').splitlines() - opened = int(rows[-1].split()[0]) - assert opened != serial, f'Look did not open {path}' - return opened + client.write(f'/pane/{serial}/ctl', f'look {path}\n'.encode()) + results = [int(row) for row in client.read('/ctl').split()] + assert len(results) == 1 and results[0] != serial, (path, results) + return results[0] def execute(client, serial, command): - text = command.encode() - client.write(f'/self/pane/{serial}/body', text, truncate=True) - client.write(f'/self/pane/{serial}/event', f'MX0 {len(text)}\n'.encode()) + """A middle click on `command` from a pane.""" + client.write(f'/pane/{serial}/ctl', f'exec {command}\n'.encode()) -def discovery(binary): +def walk_tree(client, path='/', skip=('/new', '/log', '/os', '/screen')): + """Stat every entry below `path`, as `find` does, without opening anything.""" + seen = [] + for name in client.list(path): + child = (path.rstrip('/') + '/' + name) + info = client.stat(child) + seen.append((child, info)) + if info['dir'] and child not in skip: + seen.extend(walk_tree(client, child, skip)) + return seen + + +def discovery(binary, embedded=False): with tempfile.TemporaryDirectory(prefix='pardes-discovery-') as directory: - with session(binary, Path(directory), 'discovery') as (client, _): - before = client.read('/self/index') - entries = client.list('/self/new') - assert {'README', 'ctl', 'body', 'addr', 'data', 'event'} <= set(entries) - guide = client.read('/self/README') - assert guide == client.read('/self/new/README') - assert b'Each open creates a separate pane' in guide - # Walk and stat each entry, as a filesystem browser does, without open. - from ninep import string - for name in entries: - client.fid += 1 - fid = client.fid - client.rpc(110, struct.pack(' 0, (path, info) + assert client.read('/index') == before, 'browsing created a pane' + assert client.stat('/index')['length'] == len(before) > 0 + index = client.stat('/index') + assert index['mode'] == 0o444 and client.stat('/ctl')['mode'] == 0o666 + assert client.stat('/pane/1/body')['mode'] == 0o666 and client.stat('/pane')['mode'] == 0o755 + fixture = int(before.split()[0]) + assert before.split()[1:3] == [b'text', b'0'] and before.endswith(b'/discovery.txt\n'), before + # Before any command, /ctl reports the editor. + status = dict(line.split(maxsplit=1) for line in client.read('/ctl').decode().splitlines()) + assert int(status['pid']) > 0 and status['version'] and int(status['panes']) == 1, status + # /new: one pane per open, its serial is the file's content. + log = client.open('/log') + first = int(client.read('/new').split()[0]) + second = int(client.read('/new').split()[0]) + assert first != second and first != fixture, (first, second) + assert client.read_fid(log) == f'new {first} {root}/+New\n'.encode() + assert client.read_fid(log) == f'new {second} {root}/+New\n'.encode() + assert set(client.list('/pane')) == {str(fixture), str(first), str(second)} + client.write(f'/pane/{first}/body', b'first pane', truncate=True) + assert client.read(f'/pane/{first}/body') == b'first pane' + assert client.read(f'/pane/{second}/body') == b'' + assert client.stat(f'/pane/{first}/body')['length'] == len(b'first pane') + rows = {int(row.split()[0]): row.split() for row in client.read('/index').splitlines()} + assert rows[first][1:3] == [b'text', b'1'] and rows[second][1:3] == [b'text', b'0'], rows + # name: read the file name, write to rename; sel: the selection. + assert client.read(f'/pane/{first}/name') == f'{root}/+New\n'.encode() + client.write(f'/pane/{first}/name', b'notes.txt\n') + assert client.read(f'/pane/{first}/name') == f'{root}/notes.txt\n'.encode() + assert client.read_fid(log) == f'rename {first} {root}/notes.txt\n'.encode() + assert client.stat(f'/pane/{first}/name')['length'] == len(f'{root}/notes.txt\n') + client.write(f'/pane/{first}/addr', b'#0,#5') + client.write(f'/pane/{first}/ctl', b'dot=addr\n') + assert client.read(f'/pane/{first}/sel') == b'first' + assert client.stat(f'/pane/{first}/sel')['length'] == 5 + client.write(f'/pane/{first}/sel', b'FIRST') + assert client.read(f'/pane/{first}/body') == b'FIRST pane' + assert client.read(f'/pane/{first}/sel') == b'' + # exec Msg shows text; exec Save writes the named file; exec Del closes. + client.write(f'/pane/{first}/ctl', b'exec Msg hello from 9P\n') + assert 'hello from 9P' in ''.join(cell[0] for cell in client.screen()['cells']) + client.write(f'/pane/{first}/ctl', b'exec Save\n') + assert (root / 'notes.txt').read_bytes() == b'FIRST pane' + assert client.read_fid(log) == f'save {first} {root}/notes.txt\n'.encode() + assert client.read('/ctl') == f'{first}\n'.encode() + client.write('/ctl', b'exec Del\n') + assert client.read_fid(log) == f'del {second} {root}/+New\n'.encode() + assert str(second) not in client.list('/pane') + # look through /ctl opens a file; the serial reads back. + (root / 'opened.txt').write_bytes(b'one\ntwo\nthree\n') + client.write('/ctl', f'look {root}/opened.txt:2\n'.encode()) + opened = int(client.read('/ctl')) + assert opened not in (fixture, first, second), opened + assert client.read(f'/pane/{opened}/body') == b'one\ntwo\nthree\n' + assert client.read(f'/pane/{opened}/name') == f'{root}/opened.txt\n'.encode() + assert client.read_fid(log) == f'new {opened} {root}/opened.txt\n'.encode() + client.write(f'/pane/{first}/ctl', f'look {root}/opened.txt:3\n'.encode()) + assert client.read('/ctl') == f'{opened}\n'.encode(), 'a repeated look targets the open pane' + assert set(client.list('/pane')) == {str(fixture), str(first), str(opened)} + # Writing an event record back still performs the action it names. + client.write(f'/pane/{first}/body', b'Msg via event', truncate=True) + client.write(f'/pane/{first}/event', b'FX0 13\n') + assert 'via event' in ''.join(cell[0] for cell in client.screen()['cells']) + for bad in [b'Look x\n', b'Exec Msg x\n', b'put\n', b'name x\n', b'del\n']: try: - client.rpc(124, struct.pack(' [--quic | --discovery]') diff --git a/test/fs_bench.zig b/test/fs_bench.zig index 7fe49734..f9735ee2 100644 --- a/test/fs_bench.zig +++ b/test/fs_bench.zig @@ -1,6 +1,7 @@ const std = @import("std"); const pardes = @import("pardes"); const filesystem = pardes.filesystem; +const ctlfs = pardes.ctlfs; pub const std_options: std.Options = .{ .log_level = .err }; @@ -73,8 +74,8 @@ const Session = struct { s.core.deinit(); } - fn node(s: *const Session, file: filesystem.PaneFile) u64 { - return filesystem.Node.of(s.file_serial, file); + fn node(s: *const Session, file: ctlfs.PaneFile) u64 { + return ctlfs.Node.of(s.file_serial, file); } }; @@ -90,9 +91,9 @@ fn checkNumbers(bytes: []const u8, expected: []const usize) ![]const u8 { return std.mem.trimStart(u8, rest, " "); } -fn checkReply(s: *Session, req: filesystem.Req, reply: filesystem.Reply) !void { +fn checkReply(s: *Session, req: ctlfs.Req, reply: ctlfs.Reply) !void { const event_read = req.op == .read and req.node == s.node(.event); - const expected_status: filesystem.Status = if (event_read) .again else .ok; + const expected_status: ctlfs.Status = if (event_read) .again else .ok; if (reply.tag != req.tag or reply.errno != 0 or reply.status != expected_status) return error.IncorrectReply; const body = s.core.panes[s.file_id].?.file.?.content; @@ -112,16 +113,18 @@ fn checkReply(s: *Session, req: filesystem.Req, reply: filesystem.Reply) !void { if (reply.payload != .staged or reply.payload.staged != bytes.len or bytes.len > req.size) return error.IncorrectReply; const pane = s.core.panes[s.file_id].?; + if (req.node == @intFromEnum(ctlfs.TopFile.index)) { + var expected_buf: [4200]u8 = undefined; + const expected = try std.fmt.bufPrint(&expected_buf, "{d} text {d} {s}\n", .{ s.file_serial, @intFromBool(pane.file.?.revision != pane.file.?.saved_revision), pane.file.?.path }); + if (!std.mem.eql(u8, expected, bytes)) return error.IncorrectReply; + return; + } const rest = try checkNumbers(bytes, &.{ s.file_serial, s.tag.len, body.len, 0, @intFromBool(pane.file.?.revision != pane.file.?.saved_revision) }); if (req.node == s.node(.ctl)) { const tail = try checkNumbers(rest, &.{pane.cols}); if (!std.mem.startsWith(u8, tail, "default ")) return error.IncorrectReply; if ((try checkNumbers(tail[8..], &.{pardes.config.tab_width})).len != 0) return error.IncorrectReply; - } else if (req.node == @intFromEnum(filesystem.SelfFile.index)) { - const tag = s.tag[0 .. std.mem.indexOfScalar(u8, s.tag, '\n') orelse s.tag.len]; - if (rest.len != tag.len + 1 or rest[rest.len - 1] != '\n' or !std.mem.eql(u8, rest[0..tag.len], tag)) - return error.IncorrectReply; } else return error.UnmeasuredOperation; } }, @@ -129,8 +132,8 @@ fn checkReply(s: *Session, req: filesystem.Req, reply: filesystem.Reply) !void { const bytes = s.core.fs.out.items; if (reply.payload != .staged or reply.payload.staged != bytes.len or bytes.len > req.size) return error.IncorrectReply; - const names = [_][]const u8{ "index", "cons", "new", "pane", "screen", "listeners" }; - const nodes = [_]u64{ @intFromEnum(filesystem.SelfFile.index), @intFromEnum(filesystem.SelfFile.cons), @intFromEnum(filesystem.SelfFile.new), filesystem.namespace_panes, @intFromEnum(filesystem.SelfFile.screen), @intFromEnum(filesystem.SelfFile.listeners) }; + const names = [_][]const u8{ "README", "index", "ctl", "new", "log", "screen", "listeners", "pane", "os" }; + const nodes = [_]u64{ @intFromEnum(ctlfs.TopFile.README), @intFromEnum(ctlfs.TopFile.index), @intFromEnum(ctlfs.TopFile.ctl), @intFromEnum(ctlfs.TopFile.new), @intFromEnum(ctlfs.TopFile.log), @intFromEnum(ctlfs.TopFile.screen), @intFromEnum(ctlfs.TopFile.listeners), @intFromEnum(ctlfs.TopFile.pane), filesystem.os_root }; var off: usize = 0; var entry: usize = 0; while (off < bytes.len) : (entry += 1) { @@ -140,7 +143,7 @@ fn checkReply(s: *Session, req: filesystem.Req, reply: filesystem.Reply) !void { const size: usize = bytes[off + 9]; off += 10; if (dir > 1 or size == 0 or size > bytes.len - off) return error.IncorrectReply; - if (entry < names.len and (node != nodes[entry] or dir != @intFromBool(entry == 2 or entry == 3) or + if (entry < names.len and (node != nodes[entry] or dir != @intFromBool(entry >= 7) or !std.mem.eql(u8, names[entry], bytes[off..][0..size]))) return error.IncorrectReply; off += size; } @@ -151,21 +154,21 @@ fn checkReply(s: *Session, req: filesystem.Req, reply: filesystem.Reply) !void { } } -fn bench(s: *Session, name: []const u8, reps: usize, req: filesystem.Req, note: []const u8) !void { +fn bench(s: *Session, name: []const u8, reps: usize, req: ctlfs.Req, note: []const u8) !void { std.debug.assert(reps > 0); const initial_bytes = s.core.panes[s.file_id].?.file.?.content.len; const initial_hash = if (req.op == .write) std.hash.Wyhash.hash(0, s.core.panes[s.file_id].?.file.?.content) else 0; for (0..64) |_| { - try checkReply(s, req, filesystem.handle(s.core, req)); + try checkReply(s, req, ctlfs.handle(s.core, req)); _ = s.core.scratch.reset(.retain_capacity); } s.counting.allocations = 0; - const expected_status: filesystem.Status = if (req.op == .read and req.node == s.node(.event)) .again else .ok; + const expected_status: ctlfs.Status = if (req.op == .read and req.node == s.node(.event)) .again else .ok; var valid = true; - var reply: filesystem.Reply = undefined; + var reply: ctlfs.Reply = undefined; const start = nowNs(); for (0..reps) |_| { - reply = filesystem.handle(s.core, req); + reply = ctlfs.handle(s.core, req); valid = valid and reply.tag == req.tag and reply.status == expected_status and reply.errno == 0; std.mem.doNotOptimizeAway(reply); _ = s.core.scratch.reset(.retain_capacity); @@ -223,7 +226,7 @@ pub fn main(init: std.process.Init) !void { try bench(&s, "lookup ctl", reps, .{ .tag = 2, .op = .lookup, - .node = filesystem.Node.of(s.file_serial, .dir), + .node = ctlfs.Node.of(s.file_serial, .dir), .data = "ctl", }, "name -> node"); try bench(&s, "read body 4K", reps, .{ @@ -249,13 +252,13 @@ pub fn main(init: std.process.Init) !void { try bench(&s, "read index", reps, .{ .tag = 6, .op = .read, - .node = @intFromEnum(filesystem.SelfFile.index), + .node = @intFromEnum(ctlfs.TopFile.index), .size = 4096, }, "one line per pane"); - try bench(&s, "readdir self", reps, .{ + try bench(&s, "readdir root", reps, .{ .tag = 7, .op = .readdir, - .node = @intFromEnum(filesystem.SelfFile.root), + .node = ctlfs.root, .size = 4096, }, "staged dirents"); try bench(&s, "read event (empty)", reps, .{ diff --git a/test/fs_namespace.zig b/test/fs_namespace.zig index c856148d..8b6f245e 100644 --- a/test/fs_namespace.zig +++ b/test/fs_namespace.zig @@ -13,13 +13,13 @@ test "runtime Mount and Unmount copy command arguments and change Look resolutio try std.testing.expectEqualStrings("peer", p.fs.mounts.items[0].name); try std.testing.expectEqualStrings("/tmp/a socket.sock", p.fs.mounts.items[0].dial); var path: [4096]u8 = undefined; - try std.testing.expectEqualStrings("/n/peer/self/index", filesystem.resolve(p, "/n/peer/self/index", "/", &path).?.path); + try std.testing.expectEqualStrings("/n/peer/index", filesystem.resolve(p, "/n/peer/index", "/", &path).?.path); try std.testing.expect(p.executeBuiltinLine(0, "Mount peer /tmp/other.sock")); try std.testing.expectEqual(@as(usize, 1), p.fs.mounts.items.len); try std.testing.expectEqualStrings("/tmp/a socket.sock", p.fs.mounts.items[0].dial); try std.testing.expect(p.executeBuiltinLine(0, "Unmount peer")); try std.testing.expectEqual(@as(usize, 0), p.fs.mounts.items.len); - try std.testing.expect(filesystem.resolve(p, "/n/peer/self/index", "/", &path) == null); + try std.testing.expect(filesystem.resolve(p, "/n/peer/index", "/", &path) == null); for ([_][]const u8{ "Mount", "Mount name", "Mount os /tmp/peer.sock", "Mount peer tcp!127.0.0.1!0", "Unmount", "Unmount name extra" }) |invalid| { try std.testing.expect(p.executeBuiltinLine(0, invalid)); try std.testing.expectEqual(@as(usize, 0), p.fs.mounts.items.len); @@ -185,6 +185,7 @@ test "filesystem resolves OS first then virtual with explicit mounts and parent const fallback = filesystem.resolve(p, "index", directory, &resolved_buffer) orelse return error.MissingVirtualFallback; try std.testing.expectEqualStrings("/virtual/index", fallback.path); + if (!pardes.memory.limits.embedded_sources) return; for ([_][]const u8{ "src/pardes.zig", "/virtual/src/pardes.zig", "/virtual/src/../src/pardes.zig" }) |word| { const found = filesystem.resolve(p, word, directory, &resolved_buffer) orelse return error.MissingEmbeddedSource; const bytes = try filesystem.read(p, found.path); @@ -235,6 +236,7 @@ test "explicit OS file opens and restores keep their names and request watches" } test "virtual file opens do not request OS watches" { + if (!pardes.memory.limits.embedded_sources) return error.SkipZigTest; const p = try pardes.Pardes.init(std.testing.allocator, .{ .tty_only = true }); defer p.deinit(); while (p.nextEffect()) |_| {} @@ -243,16 +245,16 @@ test "virtual file opens do not request OS watches" { while (p.nextEffect()) |effect| if (effect == .watch) return error.VirtualFileWatch; } -test "Look at the self factory reserves its own pane and failed opens release it" { +test "Look at the clone file reserves its own pane and failed opens release it" { const p = try pardes.Pardes.init(std.testing.allocator, .{ .tty_only = true }); defer p.deinit(); - p.lookAt(0, "/virtual/new/ctl"); + p.lookAt(0, "/virtual/new"); var control_count: usize = 0; var scratch_count: usize = 0; for (p.panes) |slot| { const pane = slot orelse continue; const file = pane.file orelse continue; - if (std.mem.eql(u8, file.path, "/virtual/new/ctl")) control_count += 1; + if (std.mem.eql(u8, file.path, "/virtual/new")) control_count += 1; if (file.output) |output| if (output.from == .cmd and output.from.cmd == .New) { scratch_count += 1; }; diff --git a/test/fs_soak.py b/test/fs_soak.py index 1201fda2..5569a7c7 100644 --- a/test/fs_soak.py +++ b/test/fs_soak.py @@ -56,7 +56,7 @@ def read_fid(client, fid, limit, count): def check_body(client, pane, count=4096): - fid = client.open(f'/self/pane/{pane["serial"]}/body') + fid = client.open(f'/pane/{pane["serial"]}/body') try: actual = read_fid(client, fid, BODY_LIMIT, count) finally: @@ -127,7 +127,7 @@ def run(args): address = unix_address if args.transport == 'tcp': listeners = [line.split('!') for line in - control.read('/self/listeners').decode().splitlines() + control.read('/listeners').decode().splitlines() if line.startswith('tcp!')] assert len(listeners) == 1, listeners transport, host, port = listeners[0] @@ -140,11 +140,12 @@ def run(args): for slot in range(4): body = payload(rng) serial = 1 if slot == 0 else new_pane(client, body) - base = f'/self/pane/{serial}' + base = f'/pane/{serial}' if slot == 0: client.write(base + '/body', body, truncate=True) path = root / f'pane-{slot}-0.zig' - client.write(base + '/ctl', f'name {path}\nput\n'.encode()) + client.write(base + '/name', f'{path}\n'.encode()) + client.write(base + '/ctl', b'exec Save\n') panes.append({'serial': serial, 'body': body, 'path': path, 'variant': 0}) emit(kind='start', seed=args.seed, session_pid=pid, transport=args.transport, host='tty' if args.tty else 'detached', @@ -161,7 +162,7 @@ def run(args): for operation in operations: slot = rng.randrange(len(panes)) pane = panes[slot] - base = f'/self/pane/{pane["serial"]}' + base = f'/pane/{pane["serial"]}' if operation == 'append': addition = payload(rng, min(256, BODY_LIMIT - len(pane['body']))) client.write(base + '/body', addition) @@ -185,7 +186,8 @@ def run(args): elif operation == 'save': pane['variant'] ^= 1 pane['path'] = root / f'pane-{slot}-{pane["variant"]}.zig' - client.write(base + '/ctl', f'name {pane["path"]}\nput\n'.encode()) + client.write(base + '/name', f'{pane["path"]}\n'.encode()) + client.write(base + '/ctl', b'exec Save\n') check_bytes(pane['path'].read_bytes(), pane['body'], 'saved file') check_bytes(client.read('/os' + str(pane['path'])), pane['body'], 'OS mount') elif operation == 'reload': @@ -194,19 +196,20 @@ def run(args): client.write(base + '/ctl', b'get\n') elif operation == 'cycle': old_serial = pane['serial'] - client.write(base + '/ctl', b'delete\n') + client.write(base + '/ctl', b'exec Del\n') pane['body'] = payload(rng) pane['serial'] = new_pane(client, pane['body']) assert pane['serial'] != old_serial - base = f'/self/pane/{pane["serial"]}' - client.write(base + '/ctl', f'name {pane["path"]}\nput\n'.encode()) + base = f'/pane/{pane["serial"]}' + client.write(base + '/name', f'{pane["path"]}\n'.encode()) + client.write(base + '/ctl', b'exec Save\n') elif operation == 'reconnect': client.socket.close() client = Client(address) check_session(client, control, pid) check_body(control, pane) elif operation == 'screen': - frozen = client.open('/self/screen') + frozen = client.open('/screen') try: before = read_fid(client, frozen, SCREEN_LIMIT, 4096) check_screen(before) @@ -217,7 +220,7 @@ def run(args): check_bytes(after, before, 'frozen screen') finally: client.close(frozen) - fresh = client.open('/self/screen') + fresh = client.open('/screen') try: check_screen(read_fid(client, fresh, SCREEN_LIMIT, 4096)) finally: @@ -225,8 +228,8 @@ def run(args): operation_count += 1 check_body(client, pane) expected = {str(pane['serial']) for pane in panes} - assert set(client.list('/self/pane')) == expected - assert set(control.list('/self/pane')) == expected + assert set(client.list('/pane')) == expected + assert set(control.list('/pane')) == expected for pane in panes: check_body(client, pane) check_body(control, pane) diff --git a/test/look_placement.py b/test/look_placement.py index e9918c5d..1341e776 100644 --- a/test/look_placement.py +++ b/test/look_placement.py @@ -70,7 +70,7 @@ def run_case(args, root, source_index): require(len(serials) == 3, 'classic fixture did not boot three terminals') markers = {} for index, serial in enumerate(serials): - pane = f'/self/pane/{serial}' + pane = f'/pane/{serial}' require('pty' in client.list(pane), 'fixture contains an existing document') marker = f'LP_{index}' markers[serial] = marker @@ -89,7 +89,7 @@ def run_case(args, root, source_index): require(before[serials[0]][:2] == (0, 2) and before[serials[1]][0] == 0 and before[serials[1]][1] > 2 and before[serials[2]][:2] == (75, 2), f'unexpected initial classic layout: {before}') - client.write(f'/self/pane/{source}/ctl', f'look {target}\n'.encode()) + client.write(f'/pane/{source}/ctl', f'look {target}\n'.encode()) opened = require(wait_for(lambda: next((serial for serial in panes(client) if serial not in serials), None)), 'Look did not open the first document') @@ -111,9 +111,9 @@ def run_case(args, root, source_index): require(rectangle_text(before_frame, before[serial]) == rectangle_text(after_frame, after[serial]), f'Look changed unrelated terminal {serial} rendered text') - require(client.read(f'/self/pane/{opened}/body') == contents, + require(client.read(f'/pane/{opened}/body') == contents, 'opened document contents differ') - client.write(f'/self/pane/{source}/ctl', f'look {target}:2\n'.encode()) + client.write(f'/pane/{source}/ctl', f'look {target}:2\n'.encode()) require(list(panes(client)) == serials + [opened], 'repeated Look created a duplicate pane') require(wait_for(lambda: geometry(client, markers)[1] == after), 'repeated Look changed layout') diff --git a/test/ninep.py b/test/ninep.py index b128cc8a..6c625951 100644 --- a/test/ninep.py +++ b/test/ninep.py @@ -116,7 +116,44 @@ class Client: self.close(fid) def screen(self): - return json.loads(self.read('/self/screen')) + return json.loads(self.read('/screen')) + + def walk(self, path): + names = [part for part in os.fspath(path).split('/') if part] + self.fid += 1 + fid = self.fid + oldfid = 1 + try: + for start in range(0, max(1, len(names)), 16): + part = names[start:start + 16] + reply = self.rpc(110, struct.pack('16} transport={x:0>16}\n" ++ " got frames={d} images={d} visual={x:0>16} transport={x:0>16}\n", .{ - name, round, want.frames, want.images, - want.visual, want.transport, got.frames, got.images, - got.visual, got.transport, + name, round, want.frames, want.images, + want.visual, want.transport, got.frames, got.images, + got.visual, got.transport, }, ); return error.UnstableIdentity; @@ -569,8 +569,8 @@ fn reportText(config: Config, travel: Travel, results: []const Result) void { std.debug.print( "{s}: {d} pages, {d}px strip at {d}x{d} cells of {d}x{d}px\n", .{ - config.path, travel.pages, travel.strip_px, bench_cols, - bench_rows, bench_cell_pixels.w, bench_cell_pixels.h, + config.path, travel.pages, travel.strip_px, bench_cols, + bench_rows, bench_cell_pixels.w, bench_cell_pixels.h, }, ); std.debug.print( @@ -578,9 +578,9 @@ fn reportText(config: Config, travel: Travel, results: []const Result) void { .{ config.warmup, config.reps }, ); std.debug.print("{s:<16} {s:>6} {s:>7} {s:>10} {s:>10} {s:>10} {s:>10} {s:>10} {s:>11} {s:>7} {s:>5} {s:<16} {s}\n", .{ - "scenario", "frames", "notches", "min", - "median", "p90", "p99", "max", - "total_us", "rasters", "kept", "visual", + "scenario", "frames", "notches", "min", + "median", "p90", "p99", "max", + "total_us", "rasters", "kept", "visual", "transport", }); std.debug.print("{s}\n", .{"-" ** 160}); @@ -618,7 +618,7 @@ fn reportJson(io: std.Io, config: Config, travel: Travel, results: []const Resul "{{\"benchmark\":\"pardes-pdf-scroll\",\"build\":\"{s}\",\"path\":\"{s}\"," ++ "\"pages\":{d},\"strip_px\":{d},\"warmup\":{d},\"reps\":{d},\"results\":[", .{ - bench_config.core_optimize, config.path, travel.pages, + bench_config.core_optimize, config.path, travel.pages, travel.strip_px, config.warmup, config.reps, }, ) catch return; diff --git a/test/snapshot.zig b/test/snapshot.zig index a7a1ba48..7fa84a86 100644 --- a/test/snapshot.zig +++ b/test/snapshot.zig @@ -1151,7 +1151,7 @@ const Screen9p = struct { fn snap9p(arena: std.mem.Allocator, h: *eh.Harness, label: []const u8, prev: *Prev) ![]u8 { var dial_buf: [24]u8 = undefined; const dial = try std.fmt.bufPrint(&dial_buf, "{d}", .{h.pid}); - const bytes = try Client.read(gpa, dial, "/self/screen", "/self/screen"); + const bytes = try Client.read(gpa, dial, "/screen", "/screen"); defer gpa.free(bytes); const parsed = try std.json.parseFromSlice(Screen9p, gpa, bytes, .{}); defer parsed.deinit(); diff --git a/test/tag_cleanup.py b/test/tag_cleanup.py index 52ee8e9d..7b7d8bbf 100644 --- a/test/tag_cleanup.py +++ b/test/tag_cleanup.py @@ -28,7 +28,7 @@ def run(args): launch=launch, inherited=inherited, terminal=terminal) as (client, _): keys = HostInput(terminal['input_fd']) pdf = next(serial for serial, tag in panes(client).items() if str(source) in tag) - pdf_tag = client.read(f'/self/pane/{pdf}/tag').decode().strip() + pdf_tag = client.read(f'/pane/{pdf}/tag').decode().strip() require(pdf_tag.startswith(str(source) + ' [1/'), 'PDF name/page prefix missing') require(pdf_tag.endswith('] Tty Del PdfSections PdfTint Collapse'), 'PDF commands missing') require(all(word not in pdf_tag for word in ['PdfFit', 'filtered', 'full', 'disabled']), 'PDF tag contains fit or tint-state clutter') @@ -36,7 +36,7 @@ def run(args): before = set(panes(client)) execute(client, control, 'Tty') tty = require(wait_for(lambda: next((s for s in panes(client) if s not in before), None)), 'terminal missing') - client.write(f'/self/pane/{control}/ctl', b'delete\n') # owned command-only scratch + client.write(f'/pane/{control}/ctl', b'exec Del\n') # owned command-only scratch def tag_position(): frame = client.screen() @@ -64,11 +64,11 @@ def run(args): keys.send(b'\t') require(wait_for(lambda: (p := tag_position()) and p[2] == ' '), 'Mode from edited tag ignored parked raw mode') keys.send(b'\x02') - client.write(f'/self/pane/{tty}/pty/data', b"printf 'Mode toggle ready\\n'\r") - require(wait_for(lambda: b'Mode toggle ready' in client.read(f'/self/pane/{tty}/body')), 'terminal input failed') + client.write(f'/pane/{tty}/pty/data', b"printf 'Mode toggle ready\\n'\r") + require(wait_for(lambda: b'Mode toggle ready' in client.read(f'/pane/{tty}/body')), 'terminal input failed') capture(client, root, 'pdf-and-tty-tags', not args.tty) require(source.read_bytes() == original, 'PDF file changed') - client.write(f'/self/pane/{tty}/pty/data', b'exit\r') + client.write(f'/pane/{tty}/pty/data', b'exit\r') print('PDF tag, Mode click, Ctrl-B, edited-tag execution and source preservation passed') diff --git a/test/ui_review.py b/test/ui_review.py index df492eac..2b6faa29 100644 --- a/test/ui_review.py +++ b/test/ui_review.py @@ -21,7 +21,7 @@ from fs import session def panes(client): return {int(row.split(maxsplit=5)[0]): row.split(maxsplit=5)[5] - for row in client.read('/self/index').decode().splitlines()} + for row in client.read('/index').decode().splitlines()} def wait_for(fn, seconds=12): deadline = time.monotonic() + seconds @@ -34,7 +34,7 @@ def wait_for(fn, seconds=12): def command(client, serial, text): """Execute a temporary tag command without changing source contents.""" - tag = f'/self/pane/{serial}/tag' + tag = f'/pane/{serial}/tag' before = client.read(tag).rstrip(b'\n') tail_start = before.index(b'Save Tty Del') while tail_start and before[tail_start - 1:tail_start] == b' ': @@ -42,13 +42,13 @@ def command(client, serial, text): client.write(tag, b' ' + text.encode()) current = client.read(tag) start = current.rfind(text.encode()) - client.write(f'/self/pane/{serial}/event', f'Mx{start} {start + len(text.encode())}\n'.encode()) - client.write(f'/self/pane/{serial}/ctl', b'cleartag\n') + client.write(f'/pane/{serial}/event', f'Mx{start} {start + len(text.encode())}\n'.encode()) + client.write(f'/pane/{serial}/ctl', b'cleartag\n') client.write(tag, before[tail_start:]) def new_output(client, before): return next((serial for serial in panes(client) if serial not in before and - client.read(f'/self/pane/{serial}/body').strip()), None) + client.read(f'/pane/{serial}/body').strip()), None) def require(value, description): if not value: @@ -63,7 +63,7 @@ def capture(client, root, label, gui): text = '\n'.join(''.join(cell[0] for cell in screen['cells'][at:at+cols]) for at in range(0, len(screen['cells']), cols)) (root / (label + '.txt')).write_text(text) - (root / (label + '-index.txt')).write_text(client.read('/self/index').decode()) + (root / (label + '-index.txt')).write_text(client.read('/index').decode()) if gui: require(wait_for(lambda: (root / 'latest.ppm').exists(), 8), 'GPU capture missing') def convert_frame(): @@ -106,28 +106,28 @@ def run(args): before = panes(client) command(client, source, 'Find crds_value') find_pane = require(wait_for(lambda: new_output(client, before)), 'Find did not return results') - require(b'crds_value.rs' in client.read(f'/self/pane/{find_pane}/body'), 'Find result missing source') + require(b'crds_value.rs' in client.read(f'/pane/{find_pane}/body'), 'Find result missing source') report['find'] = True capture(client, root, '02-find', not args.tty) if find_pane: - (root / 'find-results.txt').write_bytes(client.read(f'/self/pane/{find_pane}/body')) - client.write(f'/self/pane/{find_pane}/ctl', b'del\n') + (root / 'find-results.txt').write_bytes(client.read(f'/pane/{find_pane}/body')) + client.write(f'/pane/{find_pane}/ctl', b'exec Del\n') before = panes(client) command(client, source, 'Grep CrdsValueLabel') grep_pane = require(wait_for(lambda: new_output(client, before)), 'Grep did not return results') - require(b'CrdsValueLabel' in client.read(f'/self/pane/{grep_pane}/body'), 'Grep result missing match') + require(b'CrdsValueLabel' in client.read(f'/pane/{grep_pane}/body'), 'Grep result missing match') report['grep'] = True if grep_pane: - (root / 'grep-results.txt').write_bytes(client.read(f'/self/pane/{grep_pane}/body')) + (root / 'grep-results.txt').write_bytes(client.read(f'/pane/{grep_pane}/body')) capture(client, root, '03-grep', not args.tty) command(client, source, 'Tty') terminal = require(wait_for(lambda: next((serial for serial in panes(client) - if 'pty' in client.list(f'/self/pane/{serial}')), None)), + if 'pty' in client.list(f'/pane/{serial}')), None)), 'Tty did not create a terminal') if terminal: - client.write(f'/self/pane/{terminal}/pty/data', b"printf '\\033[1;36mAgave workspace\\033[0m\\n'; pwd; printf '\\033[32mRead-only UI review ready\\033[0m\\n'\r") + client.write(f'/pane/{terminal}/pty/data', b"printf '\\033[1;36mAgave workspace\\033[0m\\n'; pwd; printf '\\033[32mRead-only UI review ready\\033[0m\\n'\r") require(wait_for(lambda: b'\nRead-only UI review ready\n' in - client.read(f'/self/pane/{terminal}/body').replace(b'\r', b'')), + client.read(f'/pane/{terminal}/body').replace(b'\r', b'')), 'Terminal command output was not observed') report['terminal'] = True capture(client, root, '04-terminal', not args.tty) @@ -137,46 +137,46 @@ def run(args): symbols = wait_for(lambda: new_output(client, before), args.lsp_wait) report['symbols'] = 'returned results' if symbols else 'no output before deadline' if symbols: - (root / 'symbols-results.txt').write_bytes(client.read(f'/self/pane/{symbols}/body')) + (root / 'symbols-results.txt').write_bytes(client.read(f'/pane/{symbols}/body')) capture(client, root, '05-symbols', not args.tty) if symbols: - client.write(f'/self/pane/{symbols}/ctl', b'del\n') + client.write(f'/pane/{symbols}/ctl', b'exec Del\n') offset = original.index(b'CrdsValue {') - client.write(f'/self/pane/{source}/addr', f'#{offset},#{offset}'.encode()) - client.write(f'/self/pane/{source}/ctl', b'dot=addr\nshow\n') + client.write(f'/pane/{source}/addr', f'#{offset},#{offset}'.encode()) + client.write(f'/pane/{source}/ctl', b'dot=addr\nshow\n') before = panes(client) command(client, source, 'Hover') hover = wait_for(lambda: new_output(client, before), args.lsp_wait) report['hover'] = 'returned results' if hover else 'no output before deadline' if hover: - (root / 'hover-results.txt').write_bytes(client.read(f'/self/pane/{hover}/body')) + (root / 'hover-results.txt').write_bytes(client.read(f'/pane/{hover}/body')) capture(client, root, '06-hover', not args.tty) # Look focuses the source without changing it; gd then travels through # the host's real input parser, unlike tag builtin dispatch above. line = original[:original.index(b'impl Sanitize for CrdsValue')].count(b'\n') + 1 - client.write(f'/self/pane/{source}/ctl', f'look {source_path}:{line}:19\n'.encode()) + client.write(f'/pane/{source}/ctl', f'look {source_path}:{line}:19\n'.encode()) os.write(terminal_handle['input_fd'], b'gd') time.sleep(1) capture(client, root, '07-definition', not args.tty) command(client, source, 'Lspinfo') lsp = wait_for(lambda: next((serial for serial, tag in panes(client).items() if '+Lsp' in tag), None)) if lsp: - info = client.read(f'/self/pane/{lsp}/body') + info = client.read(f'/pane/{lsp}/body') (root / 'lsp-info.txt').write_bytes(info) report['lsp'] = info.decode() capture(client, root, '08-lsp-info', not args.tty) if lsp: - client.write(f'/self/pane/{lsp}/ctl', b'del\n') + client.write(f'/pane/{lsp}/ctl', b'exec Del\n') for theme in args.themes: command(client, source, 'Theme ' + theme) capture(client, root, 'theme-' + theme, not args.tty) for serial, tag in panes(client).items(): if any(word in tag for word in ['+Hover', '+Search']): - (root / f'pane-{serial}.txt').write_bytes(client.read(f'/self/pane/{serial}/body')) - assert client.read(f'/self/pane/{source}/body') == original == source_path.read_bytes() + (root / f'pane-{serial}.txt').write_bytes(client.read(f'/pane/{serial}/body')) + assert client.read(f'/pane/{source}/body') == original == source_path.read_bytes() report['source_unchanged'] = True if terminal: - client.write(f'/self/pane/{terminal}/pty/data', b'exit\r') + client.write(f'/pane/{terminal}/pty/data', b'exit\r') (root / 'report.json').write_text(json.dumps(report, indent=2)) print('artifacts', root, flush=True) diff --git a/test/v9fs.py b/test/v9fs.py index 7dc88195..16916d0b 100644 --- a/test/v9fs.py +++ b/test/v9fs.py @@ -42,25 +42,26 @@ def worker(mountpoint, socket, uid, gid, original_namespace): assert len(mounted) == 1 and ' - 9p ' in mounted[0], mounted assert not any(field.startswith(('shared:', 'master:')) for field in mounted[0].split()[6:]) - assert set(os.listdir(mountpoint)) == {'os', 'self'} - tree = mountpoint / 'self' - assert {'index', 'pane', 'new', 'screen'} <= set(os.listdir(tree)) + tree = mountpoint + assert {'os', 'index', 'pane', 'new', 'ctl', 'log', 'screen', 'README'} <= set(os.listdir(tree)) + assert 'self' not in os.listdir(tree) # A direct connection provides independent evidence for VFS reads/writes. with Client(socket) as client: - assert (tree / 'index').read_bytes() == client.read('/self/index') + assert (tree / 'index').read_bytes() == client.read('/index') assert (tree / 'pane/1/body').read_bytes() == b'initial\n' - before = client.read('/self/index') - subprocess.run(['ls', '-l', str(tree / 'new')], check=True, capture_output=True, timeout=5) - assert {'README', 'ctl', 'body'} <= set(os.listdir(tree / 'new')) - assert (tree / 'new/README').read_bytes() == (tree / 'README').read_bytes() - assert client.read('/self/index') == before, 'browsing created panes' - serial = int((tree / 'new/ctl').read_bytes().split()[0]) - another = int((tree / 'new/ctl').read_bytes().split()[0]) + before = client.read('/index') + subprocess.run(['ls', '-l', str(tree), str(tree / 'pane' / '1')], check=True, capture_output=True, timeout=5) + subprocess.run(['find', str(tree / 'pane'), str(tree / 'new'), '-ls'], check=True, capture_output=True, timeout=5) + assert (tree / 'README').read_bytes() == client.read('/README') + assert (tree / 'new').stat().st_size == 0 + assert client.read('/index') == before, 'browsing created panes' + serial = int((tree / 'new').read_bytes().split()[0]) + another = int((tree / 'new').read_bytes().split()[0]) assert serial != another, 'cached factory reused a pane' - client.write(f'/self/pane/{another}/ctl', b'delete\n') + client.write(f'/pane/{another}/ctl', b'exec Del\n') pane = tree / 'pane' / str(serial) - wire = f'/self/pane/{serial}' + wire = f'/pane/{serial}' assert str(serial) in os.listdir(tree / 'pane') assert serial in [int(row.split()[0]) for row in (tree / 'index').read_bytes().splitlines()] @@ -76,7 +77,7 @@ def worker(mountpoint, socket, uid, gid, original_namespace): assert client.read(wire + '/body') == b'v9fs update\nappended\n' # Exercise an actual shell redirection, including its O_TRUNC open. - subprocess.run(['/bin/sh', '-c', 'printf "name kernel-probe\\n" > "$1/ctl"', + subprocess.run(['/bin/sh', '-c', 'printf "kernel-probe\\n" > "$1/name"', 'v9fs-probe', str(pane)], check=True, timeout=5) tag = client.read(wire + '/tag') assert tag.split(maxsplit=1)[0] == str(socket.parent / 'kernel-probe').encode(), tag @@ -100,7 +101,7 @@ def worker(mountpoint, socket, uid, gid, original_namespace): # Reading OS files through the exported tree does not recurse through # the mount: the core still lives in the supervisor's namespace. assert (mountpoint / 'os' / str(socket.parent).lstrip('/') / 'kernel.txt').read_bytes() == b'initial\n' - write_existing(pane / 'ctl', b'delete\n') + write_existing(pane / 'ctl', b'exec Del\n') assert serial not in [int(row.split()[0]) for row in (tree / 'index').read_bytes().splitlines()] print('v9fs: namespace isolation, privilege drop, inherited mount, directory refresh, ' @@ -154,7 +155,7 @@ def run(binary, helper): print(run_helper(command), end='') assert os.readlink('/proc/self/ns/mnt') == namespace assert list(target.iterdir()) == [], 'mount escaped its private namespace' - assert client.read('/self/pane/1/body') == b'initial\n', 'core stopped serving after probe exit' + assert client.read('/pane/1/body') == b'initial\n', 'core stopped serving after probe exit' print('v9fs: supervisor namespace unchanged and session cleanup passed') diff --git a/test/v9fs_terminal.py b/test/v9fs_terminal.py index cc273a40..b49246d1 100644 --- a/test/v9fs_terminal.py +++ b/test/v9fs_terminal.py @@ -74,7 +74,7 @@ sys.exit(1) execute(client, control, 'Tty9p') until(report_path.exists, 'Tty9p did not reach the sudo stand-in') report = json.loads(report_path.read_text()) - pane = f"/self/pane/{report['pane']}" + pane = f"/pane/{report['pane']}" until(lambda: b'V9FS_AUTH_READY' in client.read(pane + '/body'), 'prompt not visible') assert report['socket'] == str(address) assert report['argv'][:2] == ['-E', '--'], report @@ -85,7 +85,7 @@ sys.exit(1) assert report['path'] == path assert report['shell'] == str(Path(shell).resolve()), report # The detached core remains responsive during authentication. - assert client.read('/self/pane/1/body') == b'initial\n' + assert client.read('/pane/1/body') == b'initial\n' target = Path(report['mount']) assert target.is_dir() and list(target.iterdir()) == [] if interrupted: @@ -100,7 +100,7 @@ sys.exit(1) client.write(pane + '/pty/data', b'printf "OUTER_READY:%s\\n" "$PARDES_PANE"\r') expected = ('OUTER_READY:' + report['pane']).encode() until(lambda: expected in client.read(pane + '/body'), 'original shell did not remain usable') - assert client.read('/self/pane/1/body') == b'initial\n' + assert client.read('/pane/1/body') == b'initial\n' print('Tty9p: shell-first startup, quoted paths, hidden password input, failure recovery and cleanup passed') diff --git a/test/window_opacity.py b/test/window_opacity.py index 8abe8677..b9529373 100644 --- a/test/window_opacity.py +++ b/test/window_opacity.py @@ -49,9 +49,9 @@ def run(args): command(client, source, 'Tty') terminal = require(wait_for(lambda: next((serial for serial in panes(client) if serial not in before), None)), 'terminal missing') - client.write(f'/self/pane/{terminal}/pty/data', + client.write(f'/pane/{terminal}/pty/data', b"PS1='$ '; printf '\\033[2J\\033[H\\033[36mTerminal opacity sample\\033[0m\\n'\r") - require(wait_for(lambda: b'Terminal opacity sample' in client.read(f'/self/pane/{terminal}/body')), + require(wait_for(lambda: b'Terminal opacity sample' in client.read(f'/pane/{terminal}/body')), 'terminal output missing') def output(builtin): @@ -59,8 +59,8 @@ def run(args): command(client, source, builtin) pane = require(wait_for(lambda: next((serial for serial in panes(client) if serial not in before), None)), builtin + ' output missing') - text = client.read(f'/self/pane/{pane}/body').decode() - client.write(f'/self/pane/{pane}/ctl', b'del\n') + text = client.read(f'/pane/{pane}/body').decode() + client.write(f'/pane/{pane}/ctl', b'exec Del\n') return text help_text = output('Help') @@ -208,9 +208,9 @@ def run(args): require(all(int(value) == 0xffffffff for value in multipliers), 'whole-window alpha modifier would fade foreground text') require('WindowOpacity: 100%\n' in output('Config'), '100% opacity not restored') - require(source_path.read_bytes() == original == client.read(f'/self/pane/{source}/body'), + require(source_path.read_bytes() == original == client.read(f'/pane/{source}/body'), 'source contents changed') - client.write(f'/self/pane/{terminal}/pty/data', b'exit\r') + client.write(f'/pane/{terminal}/pty/data', b'exit\r') report.update(source_unchanged=True, core_rgb_and_text_unchanged=True, invalid_value_ignored=True, help_updated=True, restored_opaque=True) (root / 'report.json').write_text(json.dumps(report, indent=2) + '\n') -- cgit v1.3 From 9070942b29bd10dddcdecdb0e88ba0fb40608467 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Mon, 21 Sep 2026 20:07:43 -0300 Subject: Plan 9 idiom for the control filesystem, and the regressions a624a56 left The 9P tree stops being a command language wearing a filesystem. /new created a pane as a side effect of a *read*; it is now Tcreate in /pane, with Tremove to close, which cloud9's engine has always supported and the editor never declared: tree.zig now says `features = .{ .create = true, .remove = true }`. Eleven pane ctl verbs become files that can be read as well as written -- dot, limit, dirty, mark, scroll, look, exec -- leaving ctl with `get`, the one verb no file would say better. Root /ctl splits into a read-only /status and the /look and /exec files whose write IS the click. stat carries real sizes where it used to answer 0, and qid versions track a pane's revision, so a client can poll for change without re-reading the body. Commit a624a56 moved raw-tty keys to an early-return branch that knew only Ctrl-B and bare Escape, and in the same edit deleted the paste branch below it. That cost Shift-Escape (the unconditional way out of tty mode) and both paste chords: Ctrl-V and Ctrl-Shift-V reached the child as keystrokes, so an agent CLI running in a pane took Ctrl-V for its image-paste binding and answered "No image found in clipboard". Both are restored, with tests. Nested detection was not subtly broken but deleted: 60367d8 removed nested.zig's process-ancestry walk and left "am I inside pardes" derived from PARDES_FORWARD_LOOK, which read "0" both for --nested and for "the listener did not come up". PARDES_PID now answers that question on its own, checked with kill(pid, 0); PARDES_9P and PARDES_PANE answer how to reach it; the flag is gone. The posted-9P registry also self-heals now -- a session that aborts cannot unlink its own socket, so posting sweeps entries whose target refuses a connection, symlinks only and on a definite ECONNREFUSED only. Elsewhere: tty scrolling is sticky-bottom, following new output only from the last row, with typing and entering raw mode snapping back to live; the boot layouts are a Boot enum instead of a chain of ifs, and the bare tty startup (Boot.tty, which main.zig names) opens an empty text pane under the shell while tests keep Boot.tty_shell; builtins announce themselves on the message row under a Verbose setting that is on by default; Config prints each setting the way you would type it back, so WindowOpacity 70 rather than "WindowOpacity: 70%"; LocationsConfig opens its window only when called bare; every tagline puts the word that closes the thing last, and a column now outlives its panes -- closing the last one leaves an empty pane, and only Delcol, newly on the column tagline, takes the column away. Co-Authored-By: Claude Opus 5 (1M context) --- .agents/skills/pardes-9p/SKILL.md | 271 +++++++++++++++++++------------- docs/cloud9.md | 11 ++ docs/config.md | 18 ++- docs/design.typ | 31 ++-- docs/fs.md | 120 +++++++++----- docs/v9fs.md | 2 +- features.txt | 48 ++++++ src/9p_io.zig | 290 +++++++++++++++++++++++++++++++--- src/builtins.zig | 15 +- src/config.zig | 187 +++++++++++----------- src/fs-help.txt | 42 ++--- src/fs.zig | 11 +- src/host_io.zig | 3 + src/main.zig | 71 +++++++-- src/ninep/addr.zig | 16 +- src/ninep/ctl.zig | 319 ++++++++++++++++---------------------- src/ninep/events.zig | 15 +- src/ninep/pane.zig | 241 ++++++++++++++++++++++++---- src/ninep/pty.zig | 9 +- src/ninep/screen.zig | 25 ++- src/ninep/testing.zig | 29 +++- src/ninep/tree.zig | 207 ++++++++++++++++--------- src/panes.zig | 14 +- src/pardes.zig | 294 +++++++++++++++++++++++++++++------ src/tty/tty.zig | 31 ++++ src/tutor.txt | 21 +-- test/appearance_gallery.py | 14 +- test/column_tags.py | 4 +- test/e2e_harness.zig | 2 +- test/font_size.py | 6 +- test/fs.py | 134 +++++++++------- test/fs_bench.zig | 4 +- test/fs_namespace.zig | 15 +- test/fs_soak.py | 8 +- test/look_placement.py | 6 +- test/ninep.py | 19 +++ test/output.zig | 32 ++-- test/panes.zig | 76 ++++++++- test/pdf.zig | 2 +- test/tag_cleanup.py | 2 +- test/ui_review.py | 12 +- test/v9fs.py | 35 +++-- test/window_opacity.py | 2 +- 43 files changed, 1898 insertions(+), 816 deletions(-) (limited to 'src/main.zig') diff --git a/.agents/skills/pardes-9p/SKILL.md b/.agents/skills/pardes-9p/SKILL.md index 09dee666..2cea4d4a 100644 --- a/.agents/skills/pardes-9p/SKILL.md +++ b/.agents/skills/pardes-9p/SKILL.md @@ -1,23 +1,127 @@ --- name: pardes-9p -description: Inspect and drive a running Pardes editor over 9P, or exercise its panes, builtins, terminal input and rendered output in an isolated session. Use for Pardes interaction, plugin development and end-to-end debugging through its control filesystem. +description: Inspect and drive a running Pardes editor through its control filesystem, or exercise its panes, builtins, terminal input and rendered output in an isolated session. Use for Pardes interaction, plugin development and end-to-end debugging. --- # Pardes over 9P -Use the existing [Python client](../../../test/ninep.py) for ad hoc interaction -and functional tests. Do not build another wire client. Project tooling stays -in Zig. Run the examples from the repository root; paths below are relative to -that root unless linked. +Pardes is driven by reading and writing files. Prefer ordinary file tools over +a mount; reach for the Python client only when nothing is mounted, or when the +work needs a fid held open. Do not build another wire client: project tooling +stays in Zig. Run the examples from the repository root; paths below are +relative to that root unless linked. -## Connect and identify panes +## Find the session through the mount -Every native session opens a Unix socket. Inside a pane, `PARDES_9P` names the -socket and `PARDES_PANE` is that pane's serial. Outside Pardes, find -`pardes-9p-*.sock` under `$XDG_RUNTIME_DIR`, or `~/.local/state/pardes` when -that variable is unset. Select the intended session explicitly; do not assume -the newest socket is the right one. Names come from `--9p=name`, the detached -session name, or the process ID. +This machine keeps a FUSE mount of every posted session under `/mnt/9p`: +`/mnt/9p/pardes//` is one session's served root. Inside a pane, +`$PARDES_9P` is that session's socket (`/run/user/1000/pardes-9p-.sock`), +so its pid is the directory to use, and `$PARDES_PANE` is the calling pane's +serial: + +```sh +m=/mnt/9p/pardes/$(basename "$PARDES_9P" .sock | sed 's/^pardes-9p-//') +cat "$m/index" +cat "$m/pane/$PARDES_PANE/body" +``` + +Entries for dead sessions stay listed and answer `Input/output error` on any +access, so name the session you mean rather than globbing or taking the newest. +`cat "$m/index"` is the cheapest liveness check, and `cat "$m/status"` reports +the `pid`, `version` and `panes` of a session new enough to serve it. + +`/mnt/9p/pardes` is the registry of posted sessions, mounted once for the +machine. It is not the per-pane kernel mount the `Tty9p` builtin makes, which +gives one pane's shell `$PARDES_MOUNT`; see [docs/v9fs.md](../../../docs/v9fs.md) +for that. Either mountpoint serves the same tree. + +A running session serves whatever binary started it. If a listing does not +match this document, that session predates the change; restart it. + +## The tree, and what to do with it + +``` +$m/README the served guide, worth reading first +$m/index one line per pane: serial, kind (text|term|pdf|image), dirty flag, name +$m/status pid, version, panes +$m/look write a line = a right click on it at the active pane +$m/exec write a line = a middle click: an editor command word, or a shell line +$m/log one record per read: new|del|rename|save ; reads park +$m/screen the rendered screen as JSON, frozen per open +$m/listeners this session's dial addresses +$m/pane/ mkdir opens a pane; rmdir closes it +$m/os/ the host filesystem +``` + +The first field of an index row is a stable pane serial, not a slot or row +number. A row is `serial kind dirty name`, so `row.split(maxsplit=3)` keeps a +name with spaces intact. Re-read the index after anything that might open, +reuse or close a pane. + +```sh +cat "$m/index" # which panes exist +mkdir "$m/pane/x"; n=$(awk 'END{print $1}' "$m/index") # open one, take its serial +printf 'text\n' > "$m/pane/$n/body" # append +cat "$m/pane/$n/tag" # what its tagline offers +echo notes.txt > "$m/pane/$n/name" # rename the buffer +echo Save > "$m/pane/$n/exec" # save it +echo "/etc/hosts:3" > "$m/look"; cat "$m/look" # open a file, see where it landed +rmdir "$m/pane/$n" # close it, dirty or not +``` + +The name `mkdir` asks for is ignored: a pane is named by the serial the editor +gives it, and because `/index` is ordered by serial its last row is the pane +just made. Nothing else in the tree can be created or removed, and no read +creates anything, so `ls`, `stat` and `find` over the whole tree are inert. + +`look` and `exec` are the editor's two clicks, one per line of a write, at the +active pane from the root and at that pane from `$m/pane//look` and +`$m/pane//exec`. Reading any of them answers the serials the last command +made, or the pane it focused or acted on. A command that fails is reported in +the editor, not as a write error, so inspect the resulting pane, index, message +or screen; only a malformed line fails the write itself. + +## Edit through addresses, dot and the flag files + +For a file or scratch pane, with `pane=$m/pane/`: + +| Operation | Shell | Python client | +|---|---|---| +| Read text | `cat $pane/body` | `client.read(pane + '/body')` | +| Append text | `echo text >> $pane/body` | `client.write(pane + '/body', b'text\n')` | +| Replace all text | `echo text > $pane/body` | `client.write(pane + '/body', b'text\n', truncate=True)` | +| Address a byte range | `echo '#0,#2' > $pane/addr` | `client.write(pane + '/addr', b'#0,#2')` | +| Replace that range | `echo 'pub fn' > $pane/data` | `client.write(pane + '/data', b'pub fn')` | +| Read the selection | `cat $pane/dot` (offsets), `cat $pane/sel` (text) | the same two reads | +| Select the addressed range | `cp $pane/addr $pane/dot` | `client.write(pane + '/dot', client.read(pane + '/addr'))` | +| Reload from disk | `echo get > $pane/ctl` | `client.write(pane + '/ctl', b'get\n')` | +| Close it | `rmdir $pane` | `client.remove(pane)` | + +`addr`, `dot` and `limit` each read the pair of offsets they also accept, which +is why copying one onto another is all that acme's `addr=dot`, `dot=addr` and +`limit=addr` ever were; a write may also be an address expression (`#0,#5`, +`/pattern/`, `2+1`). Moving `dot` scrolls the pane to it. `limit` bounds a +search and reads empty until set; truncate it to lift it. + +`dirty`, `mark` and `scroll` read `0` or `1` and take `0` or `1`: whether the +buffer differs from its file, whether a write pushes an undo point, and whether +a write scrolls. Truncating `tag` clears the part of the tag you may edit. + +Address state belongs to the pane, not to a client: opening `addr` resets it, +so two clients addressing the same pane will interfere. `$pane/ctl` reads +acme's window status line — serial, tag length, body length, a reserved zero, +the dirty flag, the width in cells, the font and the tab width — and takes the +one verb `get`. + +Terminal panes have no file: writing their `body` sends child input, and +truncation does not erase terminal history. + +## The Python client, for what a shell cannot express + +Use the existing [Python client](../../../test/ninep.py) when there is no +mount, or when the work needs a fid held open across several operations — +`log`, `event` and `pty/data` are consuming queues whose reads park, and shell +redirection cannot hold one open. ```sh PYTHONPATH=test python3 -B - "$PARDES_9P" <<'PY' @@ -25,103 +129,56 @@ import sys from ninep import Client with Client(sys.argv[1]) as client: - print(client.read('/self/index').decode(), end='') - print(client.read('/self/listeners').decode(), end='') + print(client.read('/index').decode(), end='') + print(client.read('/listeners').decode(), end='') PY ``` -`Client` takes a raw Unix socket path, or `(numeric_ip, port)` for TCP; it -does not parse Pardes dial strings or implement QUIC. It negotiates 9P2000, -uses a five-second socket timeout, and closes on leaving `with`. - -The first field of each index row is a stable pane serial, not a slot or row -number. The tag starts after five numeric fields; use `row.split(maxsplit=5)` -to preserve spaces. Inspect `/self/pane//tag`, `body`, or directory -entries before choosing a target. Re-read the index after actions that might -open, reuse or close panes. - -Wire paths start with `/self` or `/os`. `/n/self`, `/n/os`, `/n/peer` and -`/virtual` belong to editor Look paths, not the server root. For example, -Look `/virtual/src/pardes.zig` corresponds to reading `/self/src/pardes.zig`. - -## Edit, Look and execute - -For a file or scratch pane, with a connected `client` and a confirmed -`serial`, let `pane = f'/self/pane/{serial}'`. Terminal body writes instead -send child input; truncation does not erase terminal history. - -| Operation | Client call | -|---|---| -| Read text | `client.read(pane + '/body')` | -| Append text | `client.write(pane + '/body', b'text\n')` | -| Replace all text | `client.write(pane + '/body', b'text\n', truncate=True)` | -| Select a byte range | `client.write(pane + '/addr', b'#0,#2')` | -| Replace that range | `client.write(pane + '/data', b'pub fn')` | -| Show the addressed selection | `client.write(pane + '/ctl', b'dot=addr\n')` | -| Look from this pane | `client.write(pane + '/ctl', b'look /virtual/src/pardes.zig:10\n')` | -| Save | `client.write(pane + '/ctl', b'put\n')` | -| Reload | `client.write(pane + '/ctl', b'get\n')` | -| Close, refusing dirty text | `client.write(pane + '/ctl', b'del\n')` | - -`delete` force-closes, discarding unsaved text. `get` replaces edits with file -contents. Use those only when that loss is intended. Reading `/self/new/ctl` -creates a scratch pane and returns its serial as the first field; it is not -an observational read. - -`ctl` is not a builtin interpreter. Execute builtins through a body Exec event -on an owned scratch pane: - -```python -from fs import new_pane, execute - -control = new_pane(client, b'') -execute(client, control, 'Msg 9p-ready') -``` - -`execute` overwrites that pane's body with the command, then writes -`MX0 \n` to its `event` file. Keep the control pane separate -from user text. The same helper can run `Mini path`, `Mount peer dial`, and -`Unmount peer`; commands resolve relative to the control pane's directory. -A successful event write acknowledges dispatch, not completion: inspect the -resulting pane, message or screen for success. +`Client` takes a raw Unix socket path, or `(numeric_ip, port)` for TCP; it does +not parse Pardes dial strings or implement QUIC. It negotiates 9P2000, uses a +five-second socket timeout, and closes on leaving `with`. Its paths are the +served root: `/index`, `/pane/2/body`, `/os/...`. `/n/self`, `/n/os`, `/n/peer` +and `/virtual` are editor Look paths, not server paths — Look +`/virtual/src/pardes.zig` corresponds to reading `/src/pardes.zig`. -Opening `addr` resets its range. To inspect the current selection, open -`addr` first, write `addr=dot\n` to `ctl`, then use `read_fid` on that already -open handle. Do not replace that last step with `client.read`, which reopens -and resets it. Address state is shared by the pane, not private to a client. +For live terminal output or plugin events, use `open` / `read_fid` / `close`, +not the read-until-EOF helper. `pty/data` captures output while held open; it +is not a history replay. Both files are shared, consuming queues, not +per-client broadcasts, so a slow reader loses older data. Holding `event` open +intercepts that pane's Look and Exec clicks, so it is not a passive logger: for +Look/Exec records whose offsets identify the intended text, forward the short +record ` \n`, not the whole report with flags and text. +Expansion and chord reports need explicit handling, and terminal-body events +can carry text only in the report, which a short writeback cannot reproduce. +Read the event implementation before building an interceptor. Close handles in +`finally`, and disconnect after a socket timeout. The service shares four +connection slots and 32 screen/terminal-history snapshot handles. + +A file's qid version is the pane's revision for `body`, `data` and `xdata`, so +`stat` sees an edit land without reading the text; it stays zero elsewhere. +Stat sizes are real, and for `log`, `event` and `pty/data` report the length of +the record a read would answer — zero when nothing is waiting. ## Terminal input and screen observations Only terminal panes have `pty/`. Write keystroke bytes to `pty/data`, not `body`: `client.write(pane + '/pty/data', b'printf hello\r')` submits a shell -command. For an interactive application, send its actual input bytes; -`b'\x03'` is Ctrl-C, and Ctrl-U is `b'\x15'` where that application supports it. -These inputs go to the child terminal, not Pardes editor key bindings. +command. For an interactive application, send its actual input bytes; `b'\x03'` +is Ctrl-C, and Ctrl-U is `b'\x15'` where that application supports it. These go +to the child terminal, not to Pardes key bindings. `pty/ctl` takes `winsize C R`, +`sig INT` and `exec`, one per line. -`client.screen()` returns `cols`, `rows`, `cursor`, `styles`, and row-major +`client.screen()` returns `cols`, `rows`, `cursor`, `styles` and row-major `cells` of `[grapheme, style_index]`. Reconstruct rows using `cols`; resolve -each cell's style through `styles` when checking highlighting. Compare colors -and attributes, not just style-table indices or flattened text. +each cell's style through `styles` when checking highlighting, and compare +colors and attributes rather than style-table indices or flattened text. -Each screen open freezes one frame. A terminal `body` freezes history on its -first read. `client.read` and `client.screen` reopen each time; use repeated -calls for fresh observations. Do not poll a stale handle. Poll a specific -condition with a deadline and a short delay, rather than a fixed long sleep. -For large histories, measure whole-body reads separately from screen polling; -9P write-to-observation timing includes RPC, rendering and polling overhead. - -For live terminal output or plugin events, use `open` / `read_fid` / `close`, -not the read-until-EOF helper. `pty/data` captures output while held open; -it is not a history replay. Both files are shared, consuming queues, not -per-client broadcasts; slow readers can lose older data. Holding `event` open -intercepts Look/Exec clicks, so it is not a passive logger. For Look/Exec -records whose offsets identify the intended file/tag text, forward the short -record ` \n`, not the entire report with flags and text. -Expansion/chord reports need explicit handling; terminal-body events can have -empty ranges with text carried only in the report, so short writeback cannot -reproduce them. Read the event implementation before building an interceptor. -Close handles in `finally`; disconnect after a socket timeout. The service -shares four connection slots and 32 screen/terminal-history snapshot handles. +Each screen open freezes one frame, and a terminal `body` freezes its history +on its first read. `client.read` and `client.screen` reopen each time, so +repeat the call for a fresh observation rather than polling a stale handle. +Poll a specific condition with a deadline and a short delay, not a fixed long +sleep. For large histories, measure whole-body reads separately from screen +polling; write-to-observation timing includes RPC, rendering and polling. ## Exercise an isolated session @@ -140,22 +197,23 @@ binary = str(Path(sys.argv[1]).resolve()) with tempfile.TemporaryDirectory(prefix='pardes-9p-skill-') as directory: with session(binary, Path(directory), 'skill') as (client, address): serial = new_pane(client, b'fn main() void {}\n') - pane = f'/self/pane/{serial}' - client.write(pane + '/ctl', b'name probe.zig\n') + pane = f'/pane/{serial}' + client.write(pane + '/name', b'probe.zig\n') client.write(pane + '/addr', b'#0,#2') client.write(pane + '/data', b'pub fn') assert client.read(pane + '/body') == b'pub fn main() void {}\n' - control = new_pane(client, b'') - execute(client, control, 'Msg 9p-ready') + execute(client, serial, 'Msg 9p-ready') frame = client.screen() assert '9p-ready' in ''.join(cell[0] for cell in frame['cells']) print('9P edit, builtin and screen checks passed') PY ``` -For terminal tests, use `session(..., tty=True)` and read +`new_pane` is `mkdir` plus a read of the index; `execute` writes one line to a +pane's `exec`. Both are in `test/fs.py`. For terminal tests, use +`session(..., tty=True)` and read [test/agent_session.py](../../../test/agent_session.py) for bounded interactive -driving. Its readiness text and history threshold are application-specific; +driving; its readiness text and history threshold are application-specific, and session cleanup alone does not guarantee arbitrary grandchildren have exited. Use [test/snapshot.zig](../../../test/snapshot.zig) when editor key/mouse input or an independent terminal-rendering comparison matters; 9P screen inspection @@ -163,6 +221,7 @@ alone does not test physical input routing or the host renderer. Read [docs/fs.md](../../../docs/fs.md) for runtime mounts, TCP/QUIC listeners, Plan9port and Linux v9fs compatibility. Unix is always available; network -listeners are opt-in and grant full session/OS-file access. Use isolated -loopback listeners for tests. For less common control verbs or event details, -read their implementation and tests in [src/fs.zig](../../../src/fs.zig). +listeners are opt-in and grant full session and OS-file access, so use isolated +loopback listeners for tests. For event details or anything this page leaves +open, read the implementation and its tests in +[src/ninep/](../../../src/ninep/). diff --git a/docs/cloud9.md b/docs/cloud9.md index 79fda717..d030db1d 100644 --- a/docs/cloud9.md +++ b/docs/cloud9.md @@ -54,6 +54,17 @@ way a private `ZMX_DIR` does for zmx. Stopping unposts, and only while the entry is still ours, so a name another editor has since claimed is never unlinked. +An exit that cannot run any code of its own — an aborted test, a kill, a +crash — leaves its entry and its socket behind, so posting first sweeps the +group: every entry that is a symlink and whose socket answers a connect with +a definite ECONNREFUSED is unlinked, along with the socket it points at when +a `stat` agrees that is a socket of ours. Anything that is not a symlink is +somebody else's, and any other answer — connected, busy, refused permission, +a surprise — counts as live, because uncertainty belongs to the server that +owns the socket rather than to the sweeper. That is `cloud9.post.Probe`'s +classification, repeated in `src/9p_io.zig` only because `post.probe` is raw +Linux syscalls and pardes also builds for darwin. + **Consuming.** Nothing. `9ns --mntgen` mounts the whole registry at `/mnt/9p`, and an interactive fish already self-wraps in one, so a pardes started from a terminal sees every posted service as ordinary files — diff --git a/docs/config.md b/docs/config.md index a55aef1c..04b0fd82 100644 --- a/docs/config.md +++ b/docs/config.md @@ -111,6 +111,10 @@ Workspace, column and pane command text can be edited directly; see `ColumnTags` toggles the column command row in both GUI and TTY; it is on by default. Add `ColumnTags` to startup configuration to reclaim that row on a compact screen. Hiding it preserves your custom column commands. +`Verbose` toggles the message-row announcement every builtin makes of its own +name before it runs; it is on by default, and the builtins that own the message +row themselves (`Msg`) never announce. Turning it off leaves the row to the +messages a builtin chooses to write. `SyntaxBold` toggles bold syntax keywords; it is off by default. These settings are shared by GUI and TTY, and `Config` reports their current states. Like `Colors` and `Wrap`, these commands take no argument and invert @@ -334,10 +338,16 @@ The installed `pardes-v9fs` helper lives beside the editor; development builds can set `PARDES_V9FS_HELPER` to its absolute path. See [v9fs.md](v9fs.md). Ctrl-B switches between raw TTY and editor mode. Plain Escape at a detected -shell prompt hops back to the previous pane. Other keys, including Ctrl-O, Ctrl-W, -paste shortcuts, and modified Escape belong -to the child. Use `Mode` in the pane tag to return to editor -mode in place. Desktop paste events still feed the terminal. +shell prompt hops back to the previous pane. Other keys, including Ctrl-O, +Ctrl-W and modified Escape, belong to the child. Use `Mode` in the pane tag to +return to editor mode in place. Desktop paste events still feed the terminal. + +The paste chords are the exception the window keeps. Ctrl-V types the yank +register at the program, and Ctrl-Shift-V asks the desktop for its clipboard +and types that; both go through the program's bracketed paste when it has +asked for one. Neither reaches the child as a keystroke, so an application +that would otherwise answer Ctrl-V by reading the system clipboard itself +never gets the chance to read the wrong thing. `Font` and `FontSel` exist ONLY in the SDL GUI and native macOS builds — a terminal's font belongs to its emulator and a browser's to the page — so a diff --git a/docs/design.typ b/docs/design.typ index 4c8956ba..f8f0b05c 100644 --- a/docs/design.typ +++ b/docs/design.typ @@ -1492,15 +1492,20 @@ same thread as editing. == Nested Look -Pane shells inherit `PARDES_9P`, `PARDES_PANE` (the pane serial), and -`PARDES_FORWARD_LOOK`. A child launch resolves its OS-relative argument in -the child's working directory, then writes `look ` to the parent's -`self/pane//ctl`. Explicit `/virtual` and `/n` paths resolve in the -parent. The ordinary filesystem update performs layout and drains host effects. - -`--nested` starts a separate editor and disables forwarding from its direct -pane shells. Its 9P socket remains available for control and plugins. There is -no executable-name discovery or separate Look listener. +Pane shells inherit `PARDES_PID` (the editor's process id), `PARDES_9P` and +`PARDES_PANE` (the pane serial). The first answers whether the shell is inside +a pardes at all, the other two answer how to reach it, and they are separate +because a session whose listener never came up still owns its children. A child +launch that finds a live `PARDES_PID` and no way to reach it says so instead of +starting a second editor. Otherwise it resolves its OS-relative argument in the +child's working directory, then writes `look ` to the parent's +`pane//ctl`. Explicit `/virtual` and `/n` paths resolve in the parent. +The ordinary filesystem update performs layout and drains host effects. + +`--nested` starts a separate editor and withholds `PARDES_PID` from its direct +pane shells, which is the whole of the opt-out. Its 9P socket remains available +for control and plugins, so those shells still get `PARDES_9P` and +`PARDES_PANE`. There is no executable-name discovery or separate Look listener. Detached frontends use `pardes-detached-.sock` in the same runtime directory. The shared Unix socket conventions live in `src/9p_io.zig`. @@ -1928,9 +1933,11 @@ arrives bracketed, as one `paste` event. staged edits: Enter commits a new buffer save target, Escape cancels, and no disk rename or write happens until explicit Save. Terminal cwd and image/PDF status stay generated. Save leads the tail of every pane holding text of its own: -`Save Tty Del Collapse` for a file or an output buffer, -`Save Tty Del Togglettymode Filter Collapse` for a terminal, and `Tty Del Collapse` -for an image. PDFs use `Tty Del PdfSections PdfTint Collapse`, without tint status text. +`Save Tty Collapse Del` for a file or an output buffer, +`Tty Save Mode Filter Collapse Del` for a terminal, and `Tty Collapse Del` +for an image. PDFs use `Tty PdfSections PdfTint Collapse Del`, without tint status text. +The word that closes the thing is last on every tagline, so overshooting the +click before it cannot destroy anything. `Collapse` toggles a pane between its tagline alone and its expanded height; hidden body contents and running terminals are retained. An unsaved file has `*` after its name; an image tag diff --git a/docs/fs.md b/docs/fs.md index 55ffdc9c..0bcc0313 100644 --- a/docs/fs.md +++ b/docs/fs.md @@ -1,14 +1,19 @@ # Filesystem Every native session serves 9P2000 on a Unix socket. Pane shells receive -`PARDES_9P` (socket path) and `PARDES_PANE` (pane serial). The socket is +`PARDES_PID` (the editor's process id), `PARDES_9P` (socket path) and +`PARDES_PANE` (pane serial). The socket is `$XDG_RUNTIME_DIR/pardes-9p-.sock`, or lives under `~/.local/state/pardes` when XDG_RUNTIME_DIR is unset. Detached sessions use their session name; `--9p=` overrides it. A `pardes ` launched from a pane forwards Look to that pane over 9P. -`--nested` opens a separate editor and disables forwarding from its pane shells; -its 9P service stays available. +`PARDES_PID` alone says the shell is inside pardes; `PARDES_9P` and +`PARDES_PANE` say how to reach it, and a launch that has the first without the +other two refuses rather than opening a second editor. `--nested` opens a +separate editor and withholds `PARDES_PID` from its pane shells, so a pardes +started in one of them runs a session of its own; its 9P service stays +available. Look resolves the OS filesystem first, then the editor's virtual filesystem. Explicit paths bypass that search: @@ -68,53 +73,79 @@ Existing Plan9port/v9fs clients need a userspace bridge for QUIC. ``` /README this guide, also src/fs-help.txt /index one line per pane: serial, kind (text|term|pdf|image), dirty flag, name -/ctl write: one command per line; read: the serials the last command made or touched -/new reading it creates one empty pane and answers "\n" (the /net/tcp/clone idiom) +/status pid, version and pane count +/look write a line: a right click on it at the active pane; read: the serials it touched +/exec write a line: a middle click; read the same serials /log one line per editor event: new|del|rename|save ; reads park /screen rendered screen JSON; frozen per open handle /listeners the session's dial addresses -/pane// name body tag ctl addr data xdata sel errors event, plus pty/{ctl,status,data} +/pane/ create a directory here to open a pane; remove one to close it +/pane// name body tag ctl addr dot limit data xdata sel dirty mark scroll + errors event look exec, plus pty/{ctl,status,data} on terminals /os/ the host filesystem /src/ the editor's embedded sources, only when built with -Dembed-sources=true ``` -Nothing in the tree is created by list, stat, walk or read, except that -reading `/new` makes a pane; that is its whole purpose, so a recursive read -of the tree makes one pane per open of it. - -`/ctl` and `/pane//ctl` take the editor's own command language, two verbs: - -- `look TEXT` is a right click on `TEXT`: a path opens a file, `file:12` jumps - to a line, a directory opens a shell there, a URL opens in the browser. From - `/ctl` the look happens at the active pane; from a pane's `ctl` at that pane. -- `exec TEXT` is a middle click: a command word from `src/builtins.zig` - (`Save`, `Del`, `New`, `Newcol`, `Mount NAME DIAL`, `Unmount NAME`, `Dump`, - `Restore`, `Msg TEXT`, `Find`, `Grep`, `Tty`, ...), or anything else, which - runs in the pane's terminal. - -Both verbs are lowercase; the words after `exec` are the editor's capitalized -commands. A pane's `ctl` also keeps acme's addr verbs (`addr=dot`, `dot=addr`, -`limit=addr`, `clean`, `dirty`, `cleartag`, `get`, `mark`, `nomark`, -`noscroll`, `scroll`, `show`). Every line of a write is checked before any -line runs; a malformed line fails the write with EINVAL. A command that fails -inside the editor is reported on the message row, not as a write error. - -After a write to either `ctl`, reading `/ctl` answers the serials of the panes -the command created, or, when it created none, the pane a look focused or the -pane an exec acted on (even one it closed), one per line. Before any command it answers `pid`, `version` and `panes` lines. +Nothing in the tree is created by list, stat, walk or read. A pane is opened +by Tcreate in `/pane` (`mkdir`) and closed by Tremove on `/pane/` (`rmdir`), +which is the only create and the only remove the tree serves. The name a +create asks for is ignored, since a pane is named by the serial the editor +gives it: the Rcreate qid names the new directory, and because `/index` is +ordered by serial its last line is the pane just made. + +`/look` and `/exec` are the editor's two clicks, one per line of a write: + +- a line written to `look` is a right click on it: a path opens a file, + `file:12` jumps to a line, a directory opens a shell there, a URL opens in + the browser. +- a line written to `exec` is a middle click: a command word from + `src/builtins.zig` (`Save`, `Del`, `New`, `Newcol`, `Mount NAME DIAL`, + `Unmount NAME`, `Dump`, `Restore`, `Msg TEXT`, `Find`, `Grep`, `Tty`, ...), + or anything else, which runs in the pane's terminal. + +The root's pair clicks at the active pane and `/pane//look` and +`/pane//exec` at that pane. Blank lines are skipped, and every other line +is checked before any of them runs, so a control character fails the whole +write with EINVAL; a command that fails inside the editor is reported on the +message row, not as a write error. Reading any of these files answers the +serials of the panes the last command created, or, when it created none, the +pane a look focused or the pane an exec acted on (even one it closed), one +per line. `/pane//name` reads the pane's file name (a terminal's directory) and writing it renames the buffer; a relative name resolves against the pane's -directory. `sel` reads the editor selection and writing it replaces the -selection. `body` appends on write and replaces on truncating open. `addr` -selects a range and `data` or `xdata` read or replace it. `errors` appends to -the directory's `+Errors` pane. Holding `event` open redirects the pane's Look -and Exec clicks to that client; writing a record back performs the action. - -Stats report real lengths for `index`, `ctl`, `name`, `body`, `tag` and `sel`, -modes 0644/0666 (0444 for read-only files, 0222 for write-only), the pane's -last edit time or the process start as mtime, and stable qids. Directory -entries carry no sizes; stat the entry. +directory. `body` appends on write and replaces on truncating open. `sel` +reads the selected text and writing it replaces the selection. `errors` +appends to the directory's `+Errors` pane. Holding `event` open redirects the +pane's Look and Exec clicks to that client; writing a record back performs the +action. `ctl` reads acme's window status line — serial, tag length, body +length, a reserved zero, the dirty flag, the width in cells, the font and the +tab width — and takes one verb, `get`, which reloads the buffer from the name +it carries. + +The three range files `addr`, `dot` and `limit` each read the pair of offsets +they also accept, so copying one onto another is all that acme's `addr=dot`, +`dot=addr` and `limit=addr` ever were. A write is either that pair or an +address expression (`#0,#5`, `/pattern/`, `2+1`); `addr` selects what `data` +and `xdata` read or replace, `dot` is the editor's own selection and moving it +scrolls the pane into view, and `limit` bounds a search and reads empty until +it is set. Truncating a range file empties it; truncating `limit` lifts it. + +The three flag files `dirty`, `mark` and `scroll` read `0` or `1` and take +`0` or `1`: whether the buffer differs from its file, whether a write pushes +an undo point (writing `1` pushes one now), and whether a write scrolls the +pane. Truncating `tag` clears the part of the tag you may edit. + +Stats report real lengths for `index`, `status`, `look`, `exec`, `listeners`, +`name`, `body`, `tag`, `sel`, `ctl`, the range files and the flag files, and +for `log`, `event` and `pty/data` the length of the record a read would +answer, which is zero when nothing is waiting. Modes are 0644/0666 (0444 for +read-only files, 0222 for write-only); mtime is the pane's last edit or the +process start. The qid version of `body`, `data` and `xdata` is the pane's +revision, so a stat sees an edit land without reading the text; every other +file leaves it zero rather than promise a version it cannot keep. Directory +entries carry no sizes, and neither does `/screen`, which has no length until +an open renders its frame; stat the entry. `/log` records `new`, `del`, `rename` and `save` while at least one client holds it open; a read parks until a record arrives. `/screen` returns JSON with @@ -132,8 +163,10 @@ enables the option by default, so the device can serve its own source. This is a control filesystem, not a complete POSIX export. Native filenames may contain up to 255 bytes. Existing regular OS files support read, write, -and truncation to zero; protocol create, remove, rename, and other metadata -changes are refused. Ownership and permissions under `/os` are synthetic. +and truncation to zero; under `/os` protocol create, remove, rename and other +metadata changes are refused, as is every create and remove in the control +tree but the pane directories. Ownership and permissions under `/os` are +synthetic. Zero-length truncation accepts the accompanying `mtime` hint sent by Linux v9fs; the hint is not stored. Standalone timestamp changes remain refused. @@ -148,7 +181,8 @@ for Unix and TCP, a poll loop for QUIC, and the 9P client for mounts); `zig build fs-test` drives real sessions using the independent Python client in `test/ninep.py`; `zig build fs-discovery-test` checks that browsing creates -nothing and that `new`, `ctl`, `name`, `sel` and `log` behave. `zig build +nothing, that a pane create and remove work, and that `look`, `exec`, `name`, +`sel` and `log` behave. `zig build 9p-test` checks the two engine configurations' budgets (the engine's own tests are cloud9's `zig build test`); `zig build fs-bench` measures filesystem transactions in the core. diff --git a/docs/v9fs.md b/docs/v9fs.md index 6cb4e998..8cc97ff9 100644 --- a/docs/v9fs.md +++ b/docs/v9fs.md @@ -12,7 +12,7 @@ ls "$PARDES_MOUNT/pane" cat "$PARDES_MOUNT/index" cat "$PARDES_MOUNT/README" cat "$PARDES_MOUNT/pane/$PARDES_PANE/body" -echo 'exec Msg hello' > "$PARDES_MOUNT/ctl" +echo 'Msg hello' > "$PARDES_MOUNT/exec" ``` The mount belongs to that pane's subprocess tree. Other panes and the editor diff --git a/features.txt b/features.txt index 3bfc6967..bee079a7 100644 --- a/features.txt +++ b/features.txt @@ -20,3 +20,51 @@ on tty mode the mouse selection works but the pardes selection on that pane shou between tty panes without changing the pardes semantics or adding anything extra, just neat tricks like this. Still, you might need to come up with something to decrease the number of movements/interactions needed to do simple things like copy and pasting text from a terminal to another. + +The 9p protocol needs to be simplified and made plan9 idiomatic. Stop leaning on ctl verbs: a name should be the operation. The filesystem should carry more +in stat metadata (real sizes, mtimes, qid versions so a client can poll for change cheaply) and use the real 9P operations for what is currently a ctl verb or a +magic read. cloud9's engine already exposes fs.Features{create, remove, wstat} and the editor backend simply never declared them, so /new creating a pane on +*read* becomes a Tcreate in /pane, del becomes Tremove, cleartag becomes a truncating write to tag, and clean/dirty, scroll/noscroll, mark/nomark and +addr=dot/dot=addr/limit=addr become their own files. What is left of ctl should be only the verbs with no file analog. + +shift-esc stopped leaving raw tty mode on the sdl backend. Commit a624a56 moved raw tty keys to an early-return branch that only knew ctrl-B and bare Esc, so +shift-esc was forwarded to the child instead. It is the unconditional way out of tty mode and should stay that way. + +On tty mode scrolling should work and not always move the focus down to follow a new line. The terminal only moves down to follow new output when the last line +is already at the bottom, like most terminals and editors. Typing and entering raw mode snap back to live output, so nobody types blind. + +The different kinds of layout pardes can initialize (tty mode, file mode, the classic three-shell boot, and the others that already exist) should be an explicit +enum rather than a chain of ifs over tty_only/shells/file/missing. That part of the code needs to be more explicit. The bare tty startup should always start with +an empty text pane at the bottom, not focused. + +Nested pardes detection stopped working. Spawning a subprocess should export an env variable holding the pardes pid, so a child can see it and call a Look on the +parent through the 9p mount instead of starting a second session; whether 9p is mounted is another env variable the child can check. + +Builtins should call Msg with the builtin name when they are called, minus a few exceptions like Msg itself. This is gated on a verbose config that is on by +default and can be turned off. + +The sr.ht upstream has a macos update pushed to it. Pull it, merge it into the tip here as its own change, then look at what the macos backend gained and port +those features to the sdl backend wherever it makes sense. + +Config options should print symmetrically with the way they are set: instead of showing transparency with a colon and a percent sign it should read like +`Etcetera 70`, exactly what you would type to set it, and the same for every other setting. LocationsConfig should only open an output window with the current +config when it is called with no arguments. + +Closing the last pane in a column should not delete the column: it should leave a new empty pane there instead. A column closes only when it is closed explicitly, +so if there is no builtin for that, add a Delcol that sits on the column tagline by default. And in every tagline the builtin that kills or closes the thing should +come last, which does not look like the case for panes right now. + +Pasting regressed on the terminal: inside agent sessions text is being pasted as an image and simply does not work. Reproduce it first, then fix it. + +The 9p skill documentation should teach interacting with a running pardes through the /mnt/9p mount with ordinary file tools — cat, echo, ls — as the normal +ad-hoc path, and fall back to the python client only when nothing is mounted. + +Dead sessions are never removed from the posted-9P registry, which is a bug. A session that aborts or is killed leaves both its socket in $XDG_RUNTIME_DIR and its +symlink under the registry directory, so /mnt/9p/pardes lists entries that give Input/output error on access. postToRegistry only ever replaces its own name's +entry; nothing sweeps the rest. Posting should sweep the service directory and unlink every entry whose target refuses a connection, and the dangling socket with +it. cloud9 already classifies a refused connect as stale (post.zig Probe), and 9p_io.zig already has `alive`, which treats uncertainty as live -- that is the right +bias, so only a definite refusal reaps. + +After all of the above, do an optimization pass on startup time for the gui and tty platforms: measure first, then optimize. build.zig already has a `perf` step +(gesture latency and bounded terminal stress, with --json and a --base baseline to compare against), so a startup measurement belongs there rather than in a new +harness, and the baseline files are how a regression gets caught later. diff --git a/src/9p_io.zig b/src/9p_io.zig index 4f7c2e97..3d019e0d 100644 --- a/src/9p_io.zig +++ b/src/9p_io.zig @@ -596,7 +596,7 @@ pub const Listener = struct { } for (l.control) |fd| { setCloexec(fd); - setNonblock(fd); + _ = setNonblock(fd); } l.arm(); l.watcher = try std.Thread.spawn(.{}, watchQuic, .{l}); @@ -671,6 +671,7 @@ pub const Listener = struct { log.warn("registry post skipped: cannot create {s}", .{svc}); return; } + sweepRegistry(l.io, svc); var entry_buf: [sun_path_len:0]u8 = undefined; const entry = std.fmt.bufPrintSentinel(&entry_buf, "{s}/{s}", .{ svc, name }, 0) catch { log.warn("registry post skipped: name too long: {s}", .{name}); @@ -679,15 +680,15 @@ pub const Listener = struct { const target = l.path_buf[0..l.path_len]; // Replace only what is provably not live: our own entry, or a - // dead predecessor's symlink. `isListening` treats uncertainty - // as live, so it is only asked about an entry that *is* a - // symlink; anything else is left strictly alone and the - // symlink below simply fails. + // dead predecessor's symlink. `probe` treats uncertainty as + // live, so it is only asked about an entry that *is* a symlink; + // anything else is left strictly alone and the symlink below + // simply fails. var link_buf: [sun_path_len]u8 = undefined; const n = libc.readlink(entry, &link_buf, link_buf.len); if (n >= 0) { const had = link_buf[0..@intCast(n)]; - if (!std.mem.eql(u8, had, target) and alive(entry)) { + if (!std.mem.eql(u8, had, target) and probe(entry) == .live) { log.warn("registry entry pardes/{s} is live; not re-posted", .{name}); return; } @@ -842,12 +843,129 @@ pub fn listen(io: std.Io, gpa: std.mem.Allocator, named: []const u8, fallback: [ const alive = transport.isListening; -fn setNonblock(fd: c_int) void { +/// What is at a socket path, in cloud9's three answers (`post.Probe`). +/// Asked here with libc rather than through `cloud9.post.probe`, whose +/// raw Linux syscalls darwin cannot compile, but the classification is +/// that file's and must not become a second opinion: the one definite +/// refusal is `.stale`, nothing at the path at all is `.none`, and +/// everything else — connected, busy, refused permission, a surprise — +/// is `.live`. Uncertainty belongs to the server that owns the socket, +/// never to a sweeper deciding what to delete. +const Probe = enum { none, stale, live }; + +/// `SOCK.STREAM`, and the kernel's own non-blocking bit where there is +/// one. Darwin's `SOCK.NONBLOCK` is a Zig shim for `std.posix.socket` +/// to unpack, not an ABI value, so handing it to the raw libc call +/// would ask a kernel that has never heard of it; there it is an +/// `fcntl` instead. +const probe_socket_kind: c_uint = libc.SOCK.STREAM | (if (darwin) 0 else libc.SOCK.NONBLOCK); + +fn probe(path: [:0]const u8) Probe { + if (path.len + 1 > sun_path_len) return .live; // cannot ask; assume occupied + var addr: libc.sockaddr.un = .{ .path = @splat(0) }; + @memcpy(addr.path[0 .. path.len + 1], path[0 .. path.len + 1]); + const fd = libc.socket(libc.AF.UNIX, probe_socket_kind, 0); + if (fd < 0) return .live; + defer _ = libc.close(fd); + + // Non-blocking is the whole safety of this function, so it is read + // back rather than assumed: a BLOCKING connect to a live server + // whose backlog is full parks in the kernel with no timeout to end + // it — measured, it simply never returns — and a sweep that parks + // takes the editor's startup with it. An fd that cannot be proven + // non-blocking is never connected at all, which lands on `.live`, + // the answer that deletes nothing. + if (comptime darwin) _ = setNonblock(fd); + if (!isNonblocking(fd)) return .live; + + if (libc.connect(fd, @ptrCast(&addr), @sizeOf(@TypeOf(addr))) == 0) return .live; + // cloud9's `post.probe` mapping, answer for answer. The connection + // is never wanted: EAGAIN (a full Unix backlog) and EINPROGRESS say + // somebody is listening, which is all that was asked, and the fd + // closes without ever waiting for it to become writable. + return switch (libc.errno(-1)) { + .AGAIN, .INPROGRESS, .PERM, .ACCES => .live, + .CONNREFUSED => .stale, + .NOENT, .NOTDIR => .none, + else => .live, + }; +} + +/// Reaps the registry entries whose editor is gone, once per post. +/// +/// A clean exit unposts itself (`unpostFromRegistry`), so everything +/// left behind comes from an exit that could not: an aborted test, a +/// kill, a crash. No code in the dead process can ever run, so the cure +/// has to be somebody else's readdir, and the next editor to start is +/// the somebody. It is only ever a symlink that is followed or +/// unlinked, because that is the only thing `postToRegistry` makes and +/// anything else under a name belongs to whoever put it there; and only +/// a definite refusal counts as gone. The socket a stale entry points +/// at goes too, but not before a stat agrees it is a socket of ours: a +/// plain file answers a connect with the same refusal. +fn sweepRegistry(io: std.Io, svc: [:0]const u8) void { + if (comptime !supported) return; + + // The names are staged before anything is unlinked, so the sweep + // never asks a directory to keep reading while it is being edited. + var names: [4096]u8 = undefined; + var staged: usize = 0; + { + const dir = std.Io.Dir.openDirAbsolute(io, svc, .{ .iterate = true }) catch return; + defer dir.close(io); + var read_buf: [std.Io.Dir.Iterator.reader_buffer_len]u8 align(@alignOf(usize)) = undefined; + var reader: std.Io.Dir.Reader = .init(dir, &read_buf); + while (true) { + const listed = (reader.next(io) catch break) orelse break; + if (listed.name.len == 0 or listed.name.len > 255) continue; + if (staged + 1 + listed.name.len > names.len) break; + names[staged] = @intCast(listed.name.len); + @memcpy(names[staged + 1 ..][0..listed.name.len], listed.name); + staged += 1 + listed.name.len; + } + } + + var reaped: usize = 0; + var i: usize = 0; + while (i < staged) { + const name = names[i + 1 ..][0..names[i]]; + i += 1 + name.len; + var entry_buf: [sun_path_len:0]u8 = undefined; + const entry = std.fmt.bufPrintSentinel(&entry_buf, "{s}/{s}", .{ svc, name }, 0) catch continue; + const facts = statNoFollow(entry) orelse continue; + if (facts.mode & 0o170000 != 0o120000) continue; // not a symlink: not ours to judge + const state = probe(entry); + if (state == .live) continue; + var link_buf: [sun_path_len]u8 = undefined; + const n = libc.readlink(entry, &link_buf, link_buf.len); + if (libc.unlink(entry) != 0) continue; + reaped += 1; + // A relative target would resolve against this editor's working + // directory, which says nothing about what the entry named. + if (state != .stale or n <= 0 or link_buf[0] != '/') continue; + var target_buf: [sun_path_len:0]u8 = undefined; + const target = std.fmt.bufPrintSentinel(&target_buf, "{s}", .{link_buf[0..@intCast(n)]}, 0) catch continue; + const t = statNoFollow(target) orelse continue; + if (t.mode & 0o170000 == 0o140000 and t.uid == libc.getuid()) _ = libc.unlink(target); + } + if (reaped != 0) log.info("reaped {d} stale registry entries under {s}", .{ reaped, svc }); +} + +/// Whether it worked, because `probe` is not allowed to find out the +/// hard way: a caller that needs the guarantee has to be able to check. +fn setNonblock(fd: c_int) bool { const flags = libc.fcntl(fd, libc.F.GETFL, @as(c_int, 0)); - if (flags < 0) return; + if (flags < 0) return false; var o: libc.O = @bitCast(@as(u32, @bitCast(flags))); o.NONBLOCK = true; - _ = libc.fcntl(fd, libc.F.SETFL, @as(c_int, @bitCast(@as(u32, @bitCast(o))))); + return libc.fcntl(fd, libc.F.SETFL, @as(c_int, @bitCast(@as(u32, @bitCast(o))))) >= 0; +} + +fn isNonblocking(fd: c_int) bool { + const flags = libc.fcntl(fd, libc.F.GETFL, @as(c_int, 0)); + if (flags < 0) return false; + const o: libc.O = @bitCast(@as(u32, @bitCast(flags))); + return o.NONBLOCK; } const testing = std.testing; @@ -866,6 +984,108 @@ test "a name that is not one path component is no address at all" { try testing.expect(socketPath(&buf, "/run", "a\x00b") == null); } +test "the registry sweep takes the dead entries and leaves everything else" { + if (comptime !supported) return error.SkipZigTest; + // Under the real runtime directory, because a sun_path is 108 bytes + // and the test cache's temporary directories are longer than that. + var dir_buf: [sun_path_len:0]u8 = undefined; + const base = socketDir(&dir_buf) orelse return error.SkipZigTest; + if (!ensureSocketDir(base)) return error.SkipZigTest; + + var svc_buf: [sun_path_len:0]u8 = undefined; + const svc = std.fmt.bufPrintSentinel(&svc_buf, "{s}/sweep-{d}", .{ base, @as(u32, @intCast(libc.getpid())) }, 0) catch + return error.SkipZigTest; + if (libc.mkdir(svc, 0o700) != 0) return error.SkipZigTest; + + var paths: [5][sun_path_len:0]u8 = undefined; + const live_sock = try std.fmt.bufPrintSentinel(&paths[0], "{s}/live.sock", .{svc}, 0); + const dead_sock = try std.fmt.bufPrintSentinel(&paths[1], "{s}/dead.sock", .{svc}, 0); + const live = try std.fmt.bufPrintSentinel(&paths[2], "{s}/live", .{svc}, 0); + const dead = try std.fmt.bufPrintSentinel(&paths[3], "{s}/dead", .{svc}, 0); + const stranger = try std.fmt.bufPrintSentinel(&paths[4], "{s}/stranger", .{svc}, 0); + defer { + for ([_][:0]const u8{ live_sock, dead_sock, live, dead, stranger }) |p| _ = libc.unlink(p); + _ = libc.rmdir(svc); + } + + const listening = bindSocket(live_sock); + try testing.expect(listening >= 0); + defer _ = libc.close(listening); + try testing.expectEqual(@as(c_int, 0), libc.listen(listening, 1)); + + // Bound and then dropped: the file stays, and nobody answers it — + // exactly what an aborted test leaves behind. + const abandoned = bindSocket(dead_sock); + try testing.expect(abandoned >= 0); + _ = libc.close(abandoned); + + try testing.expectEqual(@as(c_int, 0), libc.symlink(live_sock, live)); + try testing.expectEqual(@as(c_int, 0), libc.symlink(dead_sock, dead)); + // Not a symlink, so not this program's to reason about, even though + // connecting to it is refused exactly like the dead socket. + try std.Io.Dir.cwd().writeFile(testing.io, .{ .sub_path = stranger, .data = "" }); + + // The guarantee itself, asserted rather than inferred from the fact + // that the test finished: if a probe socket ever stops being + // non-blocking the connect below parks instead of failing, and a + // parked test costs whoever is building far more than a red one. + const checking = libc.socket(libc.AF.UNIX, probe_socket_kind, 0); + try testing.expect(checking >= 0); + if (comptime darwin) try testing.expect(setNonblock(checking)); + try testing.expect(isNonblocking(checking)); + _ = libc.close(checking); + + // The listener's backlog is filled before anything is asked, because + // a full backlog is the one place a blocking connect parks forever + // (`unix_wait_for_peer`, no timeout) and a sweep that only answers + // while nobody is queued is the sweep that hangs a build. Nothing + // below accepts any of these, so the queue stays full throughout. + var queued: [8]c_int = @splat(-1); + defer for (queued) |fd| { + if (fd >= 0) _ = libc.close(fd); + }; + for (&queued) |*slot| { + const fd = libc.socket(libc.AF.UNIX, probe_socket_kind, 0); + if (fd < 0) break; + if (comptime darwin) _ = setNonblock(fd); + var addr: libc.sockaddr.un = .{ .path = @splat(0) }; + @memcpy(addr.path[0 .. live_sock.len + 1], live_sock[0 .. live_sock.len + 1]); + _ = libc.connect(fd, @ptrCast(&addr), @sizeOf(@TypeOf(addr))); + slot.* = fd; + } + + const started = transport.nowMs(); + try testing.expectEqual(Probe.live, probe(live)); + try testing.expectEqual(Probe.stale, probe(dead)); + + sweepRegistry(testing.io, svc); + + // Promptly, and not "eventually": a blocking probe never comes back + // at all, so any wall-clock bound at all is the assertion that + // matters. A second is several thousand times what three connects + // and a readdir cost. + try testing.expect(transport.nowMs() - started < 1000); + + try testing.expect(statNoFollow(dead) == null); + try testing.expect(statNoFollow(dead_sock) == null); + try testing.expect(statNoFollow(live) != null); + try testing.expect(statNoFollow(live_sock) != null); + try testing.expect(statNoFollow(stranger) != null); + try testing.expectEqual(Probe.live, probe(live)); +} + +fn bindSocket(path: [:0]const u8) c_int { + const fd = libc.socket(libc.AF.UNIX, libc.SOCK.STREAM, 0); + if (fd < 0) return fd; + var addr: libc.sockaddr.un = .{ .path = @splat(0) }; + @memcpy(addr.path[0 .. path.len + 1], path[0 .. path.len + 1]); + if (libc.bind(fd, @ptrCast(&addr), @sizeOf(@TypeOf(addr))) != 0) { + _ = libc.close(fd); + return -1; + } + return fd; +} + test "one connection's buffers are sized from the one msize constant" { try testing.expect(msize >= ninep.min_msize); try testing.expectEqual(@as(u32, msize), Runner.msize); @@ -1102,24 +1322,41 @@ pub fn start(io: std.Io, gpa: std.mem.Allocator, core: *pardes.Pardes) ?*Listene return listener; } -pub fn exportPaneEnv(listener: ?*const Listener, serial: u32, forward_look: bool) void { - _ = unsetenv("PARDES_FORWARD_LOOK"); +/// What a pane shell is told about the editor above it, set into this +/// process's environment just before `forkpty` so the child inherits it. +/// +/// Two independent facts, and they are separate variables because they answer +/// separate questions. `PARDES_PID` says "you are inside this editor, and it +/// will take a Look from you": a session whose 9P listener never came up still +/// owns its children, so the child says so rather than looking, from its own +/// side, exactly like no pardes at all. `PARDES_9P` and `PARDES_PANE` say how +/// to reach it, and a `--nested` session exports them too — its socket stays +/// open to scripts and to mounted shells — while withholding `PARDES_PID`, +/// which is the whole of what `--nested` means. +pub fn exportPaneEnv(listener: ?*const Listener, serial: u32, adopts: bool) void { + var announced = false; + if (adopts) announcing: { + var buf: [16]u8 = undefined; + const text = std.fmt.bufPrintSentinel(&buf, "{d}", .{@as(u32, @intCast(libc.getpid()))}, 0) catch + break :announcing; + announced = setenv("PARDES_PID", text, 1) == 0; + } + if (!announced) _ = unsetenv("PARDES_PID"); + if (listener) |l| exporting: { var sock: [sun_path_len]u8 = undefined; const path = std.fmt.bufPrintSentinel(&sock, "{s}", .{l.path()}, 0) catch break :exporting; var buf: [16]u8 = undefined; const id = std.fmt.bufPrintSentinel(&buf, "{d}", .{serial}, 0) catch break :exporting; if (setenv("PARDES_9P", path, 1) != 0) break :exporting; - if (setenv("PARDES_PANE", id, 1) != 0) break :exporting; - if (setenv("PARDES_FORWARD_LOOK", if (forward_look) "1" else "0", 1) == 0) return; + if (setenv("PARDES_PANE", id, 1) == 0) return; } _ = unsetenv("PARDES_9P"); _ = unsetenv("PARDES_PANE"); - _ = setenv("PARDES_FORWARD_LOOK", "0", 1); } -test "9P shell environment preserves identity when nested Look forwarding is disabled" { - const names = [_][*:0]const u8{ "XDG_RUNTIME_DIR", "HOME", "PARDES_9P", "PARDES_PANE", "PARDES_FORWARD_LOOK" }; +test "9P shell environment states being inside pardes apart from how to reach it" { + const names = [_][*:0]const u8{ "XDG_RUNTIME_DIR", "HOME", "PARDES_PID", "PARDES_9P", "PARDES_PANE" }; var saved: [names.len]?[:0]u8 = @splat(null); for (names, &saved) |name, *value| { if (libc.getenv(name)) |old| value.* = try testing.allocator.dupeZ(u8, std.mem.span(old)); @@ -1146,17 +1383,32 @@ test "9P shell environment preserves identity when nested Look forwarding is dis const path = "/tmp/pardes-example.sock"; @memcpy(listener.path_buf[0..path.len], path); listener.path_len = path.len; + var own: [16]u8 = undefined; + const own_pid = try std.fmt.bufPrint(&own, "{d}", .{@as(u32, @intCast(libc.getpid()))}); + + // A `--nested` session: reachable for scripts and mounts, but nobody's + // parent, so a pardes started in one of its shells runs a session of + // its own instead of handing its argument over. exportPaneEnv(listener, 7, false); try testing.expectEqualStrings(path, std.mem.span(libc.getenv("PARDES_9P").?)); try testing.expectEqualStrings("7", std.mem.span(libc.getenv("PARDES_PANE").?)); - try testing.expectEqualStrings("0", std.mem.span(libc.getenv("PARDES_FORWARD_LOOK").?)); + try testing.expect(libc.getenv("PARDES_PID") == null); + exportPaneEnv(listener, 8, true); try testing.expectEqualStrings("8", std.mem.span(libc.getenv("PARDES_PANE").?)); - try testing.expectEqualStrings("1", std.mem.span(libc.getenv("PARDES_FORWARD_LOOK").?)); + try testing.expectEqualStrings(own_pid, std.mem.span(libc.getenv("PARDES_PID").?)); + + // A session whose listener never came up is still the session this shell + // is inside: the pid stands on its own, and only the address is missing. + exportPaneEnv(null, 0, true); + try testing.expect(libc.getenv("PARDES_9P") == null); + try testing.expect(libc.getenv("PARDES_PANE") == null); + try testing.expectEqualStrings(own_pid, std.mem.span(libc.getenv("PARDES_PID").?)); + exportPaneEnv(null, 0, false); try testing.expect(libc.getenv("PARDES_9P") == null); try testing.expect(libc.getenv("PARDES_PANE") == null); - try testing.expectEqualStrings("0", std.mem.span(libc.getenv("PARDES_FORWARD_LOOK").?)); + try testing.expect(libc.getenv("PARDES_PID") == null); } pub const Client = struct { diff --git a/src/builtins.zig b/src/builtins.zig index 39d70e5d..aa2b2d6d 100644 --- a/src/builtins.zig +++ b/src/builtins.zig @@ -137,6 +137,14 @@ pub const registry = struct { unreachable; } + /// Does this builtin say its own name on the message row before it runs? + /// The ones that own that row themselves declare `quiet` and do not. + pub fn announces(b: Builtin()) bool { + inline for (manualBuiltinList(), 0..) |T, i| + if (@intFromEnum(b) == i) return !(@hasDecl(T, "quiet") and T.quiet); + return true; // a setting builtin changes something invisible; say so + } + pub fn dispatch(b: Builtin(), c: Ctx) void { inline for (manualBuiltinList(), 0..) |T, i| if (@intFromEnum(b) == i) return T.run(c); @@ -259,6 +267,7 @@ pub const Unmount = struct { pub const Msg = struct { pub const takes_arg = true; + pub const quiet = true; // it IS the message row pub fn run(c: Ctx) void { if (c.arg) |text| c.p.setMessage(c.id, text) @@ -542,11 +551,15 @@ pub const LocationsConfig = struct { pub const output: OutputTraits = .{ .name = "+LocationsConfig" }; pub fn run(c: Ctx) void { - const next = c.p.locations_config.parse(c.arg orelse "") catch |err| { + const argument = std.mem.trim(u8, c.arg orelse "", " \t\r\n"); + const next = c.p.locations_config.parse(argument) catch |err| { c.p.reportError(c.id, "LocationsConfig", err); return; }; c.p.locations_config = next; + // Bare, it is a question, and the window is the answer. With arguments + // it is a setting, and a setting that opens a window is noise. + if (argument.len != 0) return; report(c) catch |err| c.p.reportError(c.id, "LocationsConfig", err); } diff --git a/src/config.zig b/src/config.zig index 440549b3..3169b20c 100644 --- a/src/config.zig +++ b/src/config.zig @@ -71,6 +71,7 @@ pub const leader_path = paths: { .FocusTint = null, .ColumnTags = null, .SyntaxBold = null, + .Verbose = null, .TreeContextTagStyle = null, .Wrap = "tw", .Tagbottom = "tb", @@ -224,10 +225,10 @@ pub const tty_filter_min_contrast: f64 = 1.5; pub const topbar_str = "Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Kill"; -pub const pane_builtins_str = "Tty Del Collapse"; -pub const pdf_pane_builtins_str = "Tty Del PdfSections PdfTint Collapse"; -pub const file_pane_builtins_str = "Save Tty Del Collapse"; -pub const terminal_pane_builtins_str = "Tty Save Del Mode Filter Collapse"; +pub const pane_builtins_str = "Tty Collapse Del"; +pub const pdf_pane_builtins_str = "Tty PdfSections PdfTint Collapse Del"; +pub const file_pane_builtins_str = "Save Tty Collapse Del"; +pub const terminal_pane_builtins_str = "Tty Save Mode Filter Collapse Del"; // Each mode badge is one codepoint. pub const tag_normal = " "; @@ -540,6 +541,8 @@ pub const Runtime = struct { focus_tint: bool = true, column_tags: bool = true, syntax_bold: bool = false, + /// Builtins announce themselves on the message row. + verbose: bool = true, window_opacity: u8 = 100, window_blur: u8 = 0, window_opacity_pending: bool = true, @@ -637,7 +640,7 @@ pub const Runtime = struct { pub const Capability = std.meta.FieldEnum(Capabilities); - pub const Toggle = enum { colors, wrap, tree_context_tag_style, tag_bottom, debug, focus_tint, column_tags, syntax_bold }; + pub const Toggle = enum { colors, wrap, tree_context_tag_style, tag_bottom, debug, focus_tint, column_tags, syntax_bold, verbose }; pub const Scene = std.meta.FieldEnum(layout.SceneEffect); pub const Action = union(enum) { @@ -682,6 +685,7 @@ pub const Runtime = struct { .{ .word = "FocusTint", .action = .{ .toggle = .focus_tint } }, .{ .word = "ColumnTags", .action = .{ .toggle = .column_tags } }, .{ .word = "SyntaxBold", .action = .{ .toggle = .syntax_bold } }, + .{ .word = "Verbose", .action = .{ .toggle = .verbose } }, .{ .word = "Theme", .action = .theme }, .{ .word = "Shell", .action = .shell }, .{ .word = "Font", .action = .font, .availability = .font_picker }, @@ -761,15 +765,10 @@ pub const Runtime = struct { pub fn apply(state: *Runtime, setting: Setting, argument: ?[]const u8) bool { switch (setting.action) { + // Every toggle names a bool field of its own, so one line covers + // all of them and a new toggle needs no arm here. .toggle => |field| switch (field) { - .colors => state.colors = !state.colors, - .wrap => state.wrap = !state.wrap, - .tree_context_tag_style => state.tree_context_tag_style = !state.tree_context_tag_style, - .tag_bottom => state.tag_bottom = !state.tag_bottom, - .debug => state.debug = !state.debug, - .focus_tint => state.focus_tint = !state.focus_tint, - .column_tags => state.column_tags = !state.column_tags, - .syntax_bold => state.syntax_bold = !state.syntax_bold, + inline else => |f| @field(state, @tagName(f)) = !@field(state, @tagName(f)), }, .shell => { const value = std.mem.trim(u8, argument orelse return false, " \t\r\n"); @@ -835,46 +834,42 @@ pub const Runtime = struct { return findAction(.{ .transition = transition }).?.word; } + /// Each line reads as the command that would set it: the word, then the + /// value you would type after it. No colons, no units — `WindowOpacity 70` + /// is both what Config prints and what you write back. pub fn writeReport(out: *std.Io.Writer, context: ReportContext) !void { const state = context.state; var wrote_transition = false; for (settings) |setting| switch (setting.action) { .toggle => |field| { const value = switch (field) { - .colors => state.colors, - .wrap => state.wrap, - .tree_context_tag_style => state.tree_context_tag_style, - .tag_bottom => state.tag_bottom, - .debug => state.debug, - .focus_tint => state.focus_tint, - .column_tags => state.column_tags, - .syntax_bold => state.syntax_bold, + inline else => |f| @field(state, @tagName(f)), }; - try out.print("{s}: {s}\n", .{ setting.word, onOff(value) }); + try out.print("{s} {s}\n", .{ setting.word, onOff(value) }); }, - .theme => try out.print("{s}: {s}\n", .{ setting.word, context.theme_name }), + .theme => try out.print("{s} {s}\n", .{ setting.word, context.theme_name }), .window_opacity => { if (setting.enabled(context.capabilities)) - try out.print("{s}: {d}%{s}\n", .{ + try out.print("{s} {d}{s}\n", .{ setting.word, state.window_opacity, if (state.window_opacity_pending) " (pending)" else "", }) else - try out.print("{s}: unsupported\n", .{setting.word}); + try out.print("{s} unsupported\n", .{setting.word}); }, .window_blur => { if (setting.enabled(context.capabilities)) - try out.print("{s}: {d}%\n", .{ setting.word, state.window_blur }) + try out.print("{s} {d}\n", .{ setting.word, state.window_blur }) else - try out.print("{s}: unsupported\n", .{setting.word}); + try out.print("{s} unsupported\n", .{setting.word}); }, .shell => { const chosen = state.shell.requested.get(); try out.print( - "{s} requested (new panes): {s}{s}\n" ++ - "{s} effective (last spawn): {s}\n" ++ - "{s} pending: {s}\n", + "{s} requested (new panes) {s}{s}\n" ++ + "{s} effective (last spawn) {s}\n" ++ + "{s} pending {s}\n", .{ setting.word, if (chosen.len == 0) context.compiled_default_shell else chosen, @@ -887,18 +882,18 @@ pub const Runtime = struct { ); }, .font => if (!setting.enabled(context.capabilities)) - try out.print("{s}: unsupported\n", .{setting.word}) + try out.print("{s} unsupported\n", .{setting.word}) else { if (state.font.requested_size_hundredths == 0) - try out.print("{s} requested size: unchanged\n", .{setting.word}) + try out.print("{s} requested size unchanged\n", .{setting.word}) else - try out.print("{s} requested size: {d}.{d:0>2}\n", .{ setting.word, state.font.requested_size_hundredths / 100, state.font.requested_size_hundredths % 100 }); + try out.print("{s} requested size {d}.{d:0>2}\n", .{ setting.word, state.font.requested_size_hundredths / 100, state.font.requested_size_hundredths % 100 }); try out.print( - "{s} requested: {s}\n" ++ - "{s} requested path: {s}\n" ++ - "{s} effective: {s}\n" ++ - "{s} pending: {s}\n" ++ - "{s} effective size: {d}.{d:0>2} {s}\n", + "{s} requested {s}\n" ++ + "{s} requested path {s}\n" ++ + "{s} effective {s}\n" ++ + "{s} pending {s}\n" ++ + "{s} effective size {d}.{d:0>2} {s}\n", .{ setting.word, shown(state.font.requested_name.get()), @@ -916,28 +911,28 @@ pub const Runtime = struct { ); }, .tagline_size => if (!context.capabilities.tagline_font_size) - try out.print("{s}: unsupported\n", .{setting.word}) + try out.print("{s} unsupported\n", .{setting.word}) else if (!setting.enabled(context.capabilities)) - try out.print("{s}: {d}% (build-time only)\n", .{ setting.word, state.font.tagline_percent }) + try out.print("{s} {d} (build-time only)\n", .{ setting.word, state.font.tagline_percent }) else - try out.print("{s}: {d}%\n", .{ setting.word, state.font.tagline_percent }), + try out.print("{s} {d}\n", .{ setting.word, state.font.tagline_percent }), .transition => { if (wrote_transition) continue; wrote_transition = true; if (!setting.enabled(context.capabilities)) - try out.writeAll("Panel transition: unsupported\n") + try out.writeAll("Panel transition unsupported\n") else - try out.print("Panel transition: {s}\n", .{transitionSettingName(state.panel_transition)}); + try out.print("Panel transition {s}\n", .{transitionSettingName(state.panel_transition)}); }, .scene => |effect| { if (!setting.enabled(context.capabilities)) { - try out.print("{s}: unsupported\n", .{setting.word}); + try out.print("{s} unsupported\n", .{setting.word}); continue; } const enabled = switch (effect) { inline else => |field| @field(state.scene_effects, @tagName(field)), }; - try out.print("{s}: {s}\n", .{ setting.word, onOff(enabled) }); + try out.print("{s} {s}\n", .{ setting.word, onOff(enabled) }); }, }; @@ -1073,7 +1068,8 @@ pub const Runtime = struct { test "Config report observes every simple setting and all live context" { var state: Runtime = .{}; - var storage: [4096]u8 = undefined; + // Every setting, every context line: the report outgrows 4K. + var storage: [8192]u8 = undefined; const context: ReportContext = .{ .startup_config_path = "/tmp/pardes/init", .platform = "gui", @@ -1112,37 +1108,38 @@ pub const Runtime = struct { const report = storage[0..out.end]; const expected = switch (setting.action) { .toggle => |field| switch (field) { - .colors => "Colors: off\n", - .wrap => "Wrap: off\n", - .tree_context_tag_style => "TreeContextTagStyle: off\n", - .tag_bottom => "Tagbottom: on\n", - .debug => "Debug: on\n", - .focus_tint => "FocusTint: off\n", - .column_tags => "ColumnTags: off\n", - .syntax_bold => "SyntaxBold: on\n", + .colors => "Colors off\n", + .wrap => "Wrap off\n", + .tree_context_tag_style => "TreeContextTagStyle off\n", + .tag_bottom => "Tagbottom on\n", + .debug => "Debug on\n", + .focus_tint => "FocusTint off\n", + .column_tags => "ColumnTags off\n", + .syntax_bold => "SyntaxBold on\n", + .verbose => "Verbose off\n", }, - .shell => "Shell requested (new panes): fish\n", - .tagline_size => "TaglineSize: 73%\n", - .window_opacity => "WindowOpacity: 85% (pending)\n", - .window_blur => "WindowBlur: 40%\n", + .shell => "Shell requested (new panes) fish\n", + .tagline_size => "TaglineSize 73\n", + .window_opacity => "WindowOpacity 85 (pending)\n", + .window_blur => "WindowBlur 40\n", .transition => |transition| switch (transition) { .off => unreachable, - .slide => "Panel transition: PanelSlide\n", - .zoom => "Panel transition: PanelZoom\n", - .dissolve => "Panel transition: PanelDissolve\n", - .ascii => "Panel transition: PanelAscii\n", - .vertical => "Panel transition: PanelVertical\n", - .edges => "Panel transition: PanelEdges\n", - .fall => "Panel transition: PanelFall\n", - .wave => "Panel transition: PanelWave\n", - .curtain => "Panel transition: PanelCurtain\n", - .scramble => "Panel transition: PanelScramble\n", - .typewriter => "Panel transition: PanelType\n", + .slide => "Panel transition PanelSlide\n", + .zoom => "Panel transition PanelZoom\n", + .dissolve => "Panel transition PanelDissolve\n", + .ascii => "Panel transition PanelAscii\n", + .vertical => "Panel transition PanelVertical\n", + .edges => "Panel transition PanelEdges\n", + .fall => "Panel transition PanelFall\n", + .wave => "Panel transition PanelWave\n", + .curtain => "Panel transition PanelCurtain\n", + .scramble => "Panel transition PanelScramble\n", + .typewriter => "Panel transition PanelType\n", }, .scene => |effect| switch (effect) { - .crt => "Crt: on\n", - .ripple => "Ripple: on\n", - .glitch => "Glitch: on\n", + .crt => "Crt on\n", + .ripple => "Ripple on\n", + .glitch => "Glitch on\n", }, .theme, .font => unreachable, }; @@ -1163,15 +1160,15 @@ pub const Runtime = struct { try writeReport(&out, context); const report = storage[0..out.end]; for ([_][]const u8{ - "Theme: acme\n", - "WindowOpacity: 85%\n", - "Font requested size: 18.50\n", - "Font requested: Wanted Mono\n", - "Font requested path: /fonts/wanted.ttf\n", - "Font effective: Effective Mono\n", - "Font pending: on\n", - "Font effective size: 13.75 points\n", - "TaglineSize: 82%\n", + "Theme acme\n", + "WindowOpacity 85\n", + "Font requested size 18.50\n", + "Font requested Wanted Mono\n", + "Font requested path /fonts/wanted.ttf\n", + "Font effective Effective Mono\n", + "Font pending on\n", + "Font effective size 13.75 points\n", + "TaglineSize 82\n", "Startup config: /tmp/pardes/init\n", "Platform: gui\n", "Compiled default shell: /bin/sh\n", @@ -1197,23 +1194,23 @@ pub const Runtime = struct { out = .fixed(&storage); try writeReport(&out, defaults_context); const defaults_report = storage[0..out.end]; - try std.testing.expect(std.mem.indexOf(u8, defaults_report, "WindowOpacity: unsupported\n") != null); + try std.testing.expect(std.mem.indexOf(u8, defaults_report, "WindowOpacity unsupported\n") != null); try std.testing.expect(!find("WindowOpacity").?.enabled(defaults_context.capabilities)); - try std.testing.expect(std.mem.indexOf(u8, defaults_report, "WindowBlur: unsupported\n") != null); + try std.testing.expect(std.mem.indexOf(u8, defaults_report, "WindowBlur unsupported\n") != null); try std.testing.expect(!find("WindowBlur").?.enabled(defaults_context.capabilities)); try std.testing.expect(find("WindowOpacity").?.enabled(context.capabilities)); - try std.testing.expect(std.mem.indexOf(u8, defaults_report, "Shell requested (new panes): /bin/sh (default)\n") != null); - try std.testing.expect(std.mem.indexOf(u8, defaults_report, "Shell effective (last spawn): (none)\n") != null); - try std.testing.expect(std.mem.indexOf(u8, defaults_report, "Shell pending: on\n") != null); + try std.testing.expect(std.mem.indexOf(u8, defaults_report, "Shell requested (new panes) /bin/sh (default)\n") != null); + try std.testing.expect(std.mem.indexOf(u8, defaults_report, "Shell effective (last spawn) (none)\n") != null); + try std.testing.expect(std.mem.indexOf(u8, defaults_report, "Shell pending on\n") != null); try std.testing.expect(std.mem.indexOf(u8, defaults_report, "Startup config: no per-user config path\n") != null); try std.testing.expect(std.mem.indexOf(u8, defaults_report, "GUI shader source:") == null); - try std.testing.expect(std.mem.indexOf(u8, defaults_report, "Font: unsupported\n") != null); - try std.testing.expect(std.mem.indexOf(u8, defaults_report, "Font requested:") == null); - try std.testing.expect(std.mem.indexOf(u8, defaults_report, "Panel transition: off\n") != null); - try std.testing.expect(std.mem.indexOf(u8, defaults_report, "Crt: unsupported\n") != null); - try std.testing.expect(std.mem.indexOf(u8, defaults_report, "Ripple: unsupported\n") != null); - try std.testing.expect(std.mem.indexOf(u8, defaults_report, "Glitch: unsupported\n") != null); - try std.testing.expect(std.mem.indexOf(u8, defaults_report, "TaglineSize: unsupported\n") != null); + try std.testing.expect(std.mem.indexOf(u8, defaults_report, "Font unsupported\n") != null); + try std.testing.expect(std.mem.indexOf(u8, defaults_report, "Font requested") == null); + try std.testing.expect(std.mem.indexOf(u8, defaults_report, "Panel transition off\n") != null); + try std.testing.expect(std.mem.indexOf(u8, defaults_report, "Crt unsupported\n") != null); + try std.testing.expect(std.mem.indexOf(u8, defaults_report, "Ripple unsupported\n") != null); + try std.testing.expect(std.mem.indexOf(u8, defaults_report, "Glitch unsupported\n") != null); + try std.testing.expect(std.mem.indexOf(u8, defaults_report, "TaglineSize unsupported\n") != null); try std.testing.expect(std.mem.indexOf(u8, defaults_report, "Look hover delay: off\n") != null); try std.testing.expect(std.mem.indexOf(u8, defaults_report, "Native images: off\n") != null); @@ -1223,8 +1220,8 @@ pub const Runtime = struct { out = .fixed(&storage); try writeReport(&out, defaults_context); const web_report = storage[0..out.end]; - try std.testing.expect(std.mem.indexOf(u8, web_report, "Panel transition: unsupported\n") != null); - try std.testing.expect(std.mem.indexOf(u8, web_report, "TaglineSize: 100% (build-time only)\n") != null); + try std.testing.expect(std.mem.indexOf(u8, web_report, "Panel transition unsupported\n") != null); + try std.testing.expect(std.mem.indexOf(u8, web_report, "TaglineSize 100 (build-time only)\n") != null); } }; diff --git a/src/fs-help.txt b/src/fs-help.txt index a0a84b28..1e5d64c2 100644 --- a/src/fs-help.txt +++ b/src/fs-help.txt @@ -2,41 +2,43 @@ Pardes control filesystem ========================= README this guide index one line per pane: serial, kind (text|term|pdf|image), dirty flag, name -ctl write commands; read the serials the last command made or touched -new reading it creates one empty pane and answers its serial +status pid, version and pane count +look write a line: a right click on it at the active pane; read: the serials it touched +exec write a line: a middle click, an editor command word or a shell line; read the same log one line per editor event (new/del/rename/save ); reads wait screen rendered screen as JSON, frozen from open to close listeners the session's dial addresses -pane// name body tag ctl addr data xdata sel errors event, and pty/ for terminals +pane/ mkdir makes a pane, rmdir closes it +pane// name body tag ctl addr dot limit data xdata sel dirty mark scroll + errors event look exec, and pty/ for terminals os/ the host filesystem src/ the editor's own sources, only in a -Dembed-sources=true build -Commands, on /ctl (applied at the active pane) or on pane//ctl (at that pane): - look TEXT a right click: open a file, a file:12 location, a directory, a URL - exec TEXT a middle click: an editor command word (Save Del New Newcol Mount Unmount - Dump Restore Msg Find Grep Tty ...), or a shell command for the pane's terminal Below, $m is the mount point (PARDES_MOUNT in a Tty9p shell; 9ns and 9p work too): cat $m/index which panes exist - n=$(cat $m/new) make a pane, remember its serial - echo 'look /etc/hosts:3' > $m/ctl; cat $m/ctl open a file, see the pane it went to - printf 'text\n' > $m/pane/$n/body append to a pane (>| truncates first) + mkdir $m/pane/x; n=$(awk 'END{print $1}' $m/index) make a pane, take its serial + echo /etc/hosts:3 > $m/look; cat $m/look open a file, see the pane it went to + printf 'text\n' > $m/pane/$n/body append to a pane (>| truncates first) cat $m/pane/$n/name; echo notes.txt > $m/pane/$n/name read, then rename - echo 'exec Save' > $m/pane/$n/ctl save it (exec Del closes it) - echo 'exec Msg hello' > $m/ctl show text in the editor + echo Save > $m/pane/$n/exec save it; rmdir $m/pane/$n closes it + echo 'Msg hello' > $m/exec show text in the editor echo '#0,#5' > $m/pane/$n/addr; echo NEW > $m/pane/$n/data replace bytes 0..5 - echo 'dot=addr' > $m/pane/$n/ctl; cat $m/pane/$n/sel select the range, read it + cp $m/pane/$n/addr $m/pane/$n/dot; cat $m/pane/$n/sel select the range, read it + cat $m/pane/$n/dirty; echo 0 > $m/pane/$n/dirty is it modified? say it is not cat $m/log block until a pane is made, renamed, saved or closed cat $m/pane/$n/event hold it open to own that pane's clicks - echo 'exec' > $m/pane/$n/pty/ctl restart a shell; also winsize C R, sig INT + echo exec > $m/pane/$n/pty/ctl restart a shell; also winsize C R, sig INT Pitfalls, one each: - Every open of new makes another pane, so `cat $m/new` twice makes two. - ls, stat and find create nothing; reading log, event or pty/data blocks until something happens. - exec Del closes a pane even when it is dirty; index shows the dirty flag first. - look and exec are lowercase verbs; the words after exec are the editor's capitalized commands. - ctl also takes acme's addr verbs (addr=dot dot=addr limit=addr clean dirty get show ...), one per line. + Only mkdir in pane/ makes a pane; ls, stat, find and every read create nothing. + Panes are named by the serial the editor gives them, not by the name mkdir asked for. + rmdir closes a pane even when it is dirty; index and pane//dirty show the flag. + addr, dot and limit read the same pair of offsets they take, so cp between them works. + dirty, mark and scroll read "0" or "1" and take "0" or "1"; truncating limit lifts it. Writing body appends; open it with truncation to replace; writes are whole UTF-8 sequences. + Truncating tag clears the part you may edit; truncating dot or addr empties it. A terminal's body is a history snapshot frozen per open; pty/data is the live stream. screen is frozen per open handle as well; reopen it for a fresh frame. - A command that fails is reported in the editor, not as a write error; a malformed line fails the write. + A failing command is reported in the editor, not as a write error; a bad line fails the write. + pane//ctl reads acme's window status line and takes one verb, get, which reloads from disk. diff --git a/src/fs.zig b/src/fs.zig index 7f416440..7cb08980 100644 --- a/src/fs.zig +++ b/src/fs.zig @@ -260,12 +260,13 @@ test "unmount refuses pane paths inherited directories and queued save targets" } gpa.free(pane.file.?.path); pane.file.?.path = try gpa.dupe(u8, "/n/peer2/file"); - const shell = try p.newShell(1, "/n/peer/dir"); - p.setCwd(1, "/n/peer/dir"); + const slot = p.freeSlot().?; + const shell = try p.newShell(slot, "/n/peer/dir"); + p.setCwd(slot, "/n/peer/dir"); try std.testing.expectError(error.MountInUse, unmount(p, "peer")); pane.cwd = .{ .inherited = shell }; try std.testing.expectError(error.MountInUse, unmount(p, "peer")); - p.setCwd(1, "/"); + p.setCwd(slot, "/"); while (p.nextEffect()) |_| {} p.emit(.{ .save_text = .{ .pane = 0, .serial = pane.serial, .path = .from("/n/peer/pending") } }); try std.testing.expectError(error.MountInUse, unmount(p, "peer")); @@ -1261,10 +1262,10 @@ pub const Namespace = struct { /// The editor-wide event stream, recorded only while /log is held open. log: tree.events.Queue = .{}, log_readers: u16 = 0, - /// What the last ctl command created or touched, answered by reading /ctl. + /// What the last look or exec created or touched, answered by reading + /// either of those files. results: [MAX_PANES]u32 = undefined, results_len: u8 = 0, - results_valid: bool = false, /// Process start, the mtime of everything that has no edit time of its own. started: u32 = 0, diff --git a/src/host_io.zig b/src/host_io.zig index 212c23b4..fb09fcc7 100644 --- a/src/host_io.zig +++ b/src/host_io.zig @@ -874,6 +874,9 @@ pub fn forkShell( if (fs == null) return error.SessionSocketRequired; break :blk try @import("linux/v9fs.zig").helperPath(&helper_buf); } else null; + // The last argument is whether this session takes its children's Looks — + // every session does but a `--nested` one, and a fork with no core at all + // (the tests below) is nobody's parent. ninep_io.exportPaneEnv( fs, if (core) |c| (if (c.panes[pane]) |pn| pn.serial else 0) else 0, diff --git a/src/main.zig b/src/main.zig index 4b1910bd..1cbdf24c 100644 --- a/src/main.zig +++ b/src/main.zig @@ -112,6 +112,16 @@ const nested_text = \\ ; +/// $PARDES_PID named a live editor, so this shell IS inside one, but the Look +/// never got there. Saying so beats quietly opening the second editor that +/// $PARDES_PID exists to prevent. +const unreachable_text = + \\pardes: this shell is inside pardes, but that session did not take the + \\file. Check that it is still running, or pass --nested to start a second + \\editor in here anyway. + \\ +; + // The browser runtime calls a C main (exported below); everything else keeps // the std.process.Init entry. pub const main = if (is_emscripten) webMain else nativeMain; @@ -260,6 +270,10 @@ fn nativeMain(init: std.process.Init) !void { } } opts.tty_only = explicit_tty or session_only; + // The real bare-tty startup wants the editor half present from the first + // frame, so it names that layout; a core booted for a test names none and + // gets the raw shell by itself. + if (opts.tty_only) opts.boot = .tty; opts.mounts = mounts[0..mounts_len]; if (detach != null and attach != null) badArgs(init.io, "--detach and --attach are opposites: one runs the session, the other joins one", .{}); @@ -272,31 +286,60 @@ fn nativeMain(init: std.process.Init) !void { if (opts.mounts.len != 0 and attach != null) badArgs(init.io, "--mount configures a session's own core, and --attach has none of its own", .{}); if (!new_session and !opts.nested and detach == null and attach == null) forwarding: { - const enabled = std.c.getenv("PARDES_FORWARD_LOOK") orelse break :forwarding; - if (!std.mem.eql(u8, std.mem.span(enabled), "1")) break :forwarding; - const dial = std.mem.span(std.c.getenv("PARDES_9P") orelse break :forwarding); - ninep_io.Client.validateDial(dial) catch break :forwarding; - const pane_text = std.mem.span(std.c.getenv("PARDES_PANE") orelse break :forwarding); - for (pane_text) |byte| if (!std.ascii.isDigit(byte)) break :forwarding; - const serial = std.fmt.parseInt(u32, pane_text, 10) catch break :forwarding; - if (serial == 0) break :forwarding; - var ctl_buf: [64]u8 = undefined; - const ctl = try std.fmt.bufPrint(&ctl_buf, "/pane/{d}/ctl", .{serial}); + // Am I inside a pardes at all? That is $PARDES_PID and nothing else — + // one variable, exported by every session that means to take its + // children's Looks, so a session that could not open a socket is still + // recognisably the session this shell is inside. A pid naming no live + // process is a shell that outlived its editor (a daemon started from a + // pane, a stale environment carried into a new terminal), which is not + // nested at all. + const owner = std.mem.span(std.c.getenv("PARDES_PID") orelse break :forwarding); + const pid = std.fmt.parseInt(std.c.pid_t, owner, 10) catch break :forwarding; + if (pid <= 0 or std.c.kill(pid, @enumFromInt(0)) != 0) break :forwarding; + + // Can I reach it? That is the other two, and it is a separate answer. + const Parent = struct { dial: []const u8, serial: u32 }; + const found: ?Parent = reaching: { + const dial = std.mem.span(std.c.getenv("PARDES_9P") orelse break :reaching null); + ninep_io.Client.validateDial(dial) catch break :reaching null; + const pane_text = std.mem.span(std.c.getenv("PARDES_PANE") orelse break :reaching null); + for (pane_text) |byte| if (!std.ascii.isDigit(byte)) break :reaching null; + const serial = std.fmt.parseInt(u32, pane_text, 10) catch break :reaching null; + if (serial == 0) break :reaching null; + break :reaching .{ .dial = dial, .serial = serial }; + }; + const parent = found orelse { + try std.Io.File.stderr().writeStreamingAll(init.io, unreachable_text); + std.process.exit(1); + }; + // The pane's `look` file: one line, and the line is the clicked text + // itself, which is what a right click in that pane would have been. + var look_buf: [64]u8 = undefined; + const look = try std.fmt.bufPrint(&look_buf, "/pane/{d}/look", .{parent.serial}); const word = positional orelse { var tag_buf: [64]u8 = undefined; - const tag = try std.fmt.bufPrint(&tag_buf, "/pane/{d}/tag", .{serial}); - const contents = ninep_io.Client.read(arena, dial, tag, tag) catch break :forwarding; + const tag = try std.fmt.bufPrint(&tag_buf, "/pane/{d}/tag", .{parent.serial}); + const contents = ninep_io.Client.read(arena, parent.dial, tag, tag) catch { + try std.Io.File.stderr().writeStreamingAll(init.io, unreachable_text); + std.process.exit(1); + }; arena.free(contents); try std.Io.File.stderr().writeStreamingAll(init.io, nested_text); std.process.exit(1); }; + // A word this launch cannot turn into a path is an argument problem + // rather than a nesting one: fall through and let the session that + // starts report it, the way `pardes typo` outside pardes does. if (std.mem.indexOfAny(u8, word, "\r\n") != null) break :forwarding; const target = @import("look.zig").parsePathLine(word); var realbuf: [4096]u8 = undefined; const path = if (pardes.filesystem.isVirtual(target.path)) target.path else (pardes.filesystem.resolveOs(target.path, &realbuf) orelse break :forwarding).path; var command_buf: [8192]u8 = undefined; - const command = std.fmt.bufPrint(&command_buf, "look {s}{s}\n", .{ path, word[target.path.len..] }) catch break :forwarding; - ninep_io.Client.write(arena, dial, ctl, command) catch break :forwarding; + const command = std.fmt.bufPrint(&command_buf, "{s}{s}\n", .{ path, word[target.path.len..] }) catch break :forwarding; + ninep_io.Client.write(arena, parent.dial, look, command) catch { + try std.Io.File.stderr().writeStreamingAll(init.io, unreachable_text); + std.process.exit(1); + }; return; } if (positional) |a| { diff --git a/src/ninep/addr.zig b/src/ninep/addr.zig index f7642b9e..566e2364 100644 --- a/src/ninep/addr.zig +++ b/src/ninep/addr.zig @@ -255,17 +255,25 @@ test "the address language, form by form" { try testing.expectEqual(@as(u32, 6), p.fs.panes[0].addr.q0); // the `o` in "two" try testing.expectEqual(@as(u32, 7), p.fs.panes[0].addr.q1); + // limit is its own file: copying addr onto it bounds the search, and + // truncating it lifts the bound again. + const limit = Node.of(serial, .limit); _ = th.wr(p, addr, "1"); - _ = th.wr(p, Node.of(serial, .ctl), "limit=addr\n"); + try testing.expectEqualStrings("", th.rd(p, limit, 0, 64).bytes); + var copied: [64]u8 = undefined; + const pair = th.rd(p, addr, 0, 64).bytes; + @memcpy(copied[0..pair.len], pair); + _ = th.wr(p, limit, copied[0..pair.len]); + try testing.expectEqual(@as(u32, 4), p.fs.panes[0].limit.?.q1); + try testing.expectEqualStrings(" 0 4 ", th.rd(p, limit, 0, 64).bytes); _ = th.wr(p, addr, "#0"); try testing.expectEqual(E.INVAL, th.wr(p, addr, "/three/").errno()); - _ = th.wr(p, Node.of(serial, .ctl), "clean\n"); - _ = th.call(p, .{ .tag = 6, .op = .open, .node = Node.of(serial, .ctl) }); + _ = th.call(p, .{ .tag = 6, .op = .setattr, .node = limit, .truncate = true }); try testing.expect(p.fs.panes[0].limit == null); _ = th.wr(p, addr, "#0"); try testing.expectEqual(Status.ok, th.wr(p, addr, "/three/").reply.status); - for ([_][]const u8{ "zzz", "#", "//", "/nomatch/", "1 2", "99", "/a\\" }) |bad| { + for ([_][]const u8{ "zzz", "#", "//", "/nomatch/", "1 2 3", "99", "/a\\" }) |bad| { _ = th.wr(p, addr, "#0"); try testing.expectEqual(E.INVAL, th.wr(p, addr, bad).errno()); } diff --git a/src/ninep/ctl.zig b/src/ninep/ctl.zig index d61ebf75..c213ece5 100644 --- a/src/ninep/ctl.zig +++ b/src/ninep/ctl.zig @@ -1,6 +1,9 @@ -//! The two ctl files. `look TEXT` is a right click and `exec TEXT` a middle -//! click in the editor's own command language; a pane's ctl adds the addr -//! verbs. Reading /ctl answers the serials the last command made or touched. +//! The command files and the status they answer. Writing a line to `look` is +//! a right click on it and writing one to `exec` a middle click, at the +//! active pane from the root and at that pane from /pane//; reading either +//! answers the serials the last command made or touched. /status reports the +//! editor, and a pane's ctl its acme status line and the one verb, `get`, +//! that no file of its own would say any better. const std = @import("std"); const pardes = @import("../pardes.zig"); const panes = @import("../panes.zig"); @@ -16,36 +19,6 @@ const Req = tree.Req; const Reply = tree.Reply; const E = tree.E; -const Verb = enum { - @"addr=dot", - clean, - cleartag, - dirty, - @"dot=addr", - get, - @"limit=addr", - mark, - nomark, - noscroll, - scroll, - show, -}; - -fn verbIs(line: []const u8, word: []const u8) bool { - if (!std.mem.startsWith(u8, line, word)) return false; - return line.len == word.len or line[word.len] == ' ' or line[word.len] == '\t'; -} - -/// The text after `look` or `exec`, or null when the line is not that verb. -/// Control characters other than tab are refused. -fn textAfter(line: []const u8, verb: []const u8) ?[]const u8 { - if (!verbIs(line, verb)) return null; - const text = std.mem.trim(u8, line[verb.len..], " \t"); - if (text.len == 0) return ""; - for (text) |c| if (c < ' ' and c != '\t') return ""; - return text; -} - // ---- which panes a command made or touched ---- const Serials = struct { @@ -96,37 +69,49 @@ fn run(p: *Pardes, id: usize, exec: bool, text: []const u8) void { noteResult(p, if (exec) context else activeSerial(p) orelse return); } -fn beginResults(p: *Pardes) void { - p.fs.results_len = 0; - p.fs.results_valid = true; -} - -// ---- /ctl ---- +// ---- look and exec ---- -pub fn writeRoot(p: *Pardes, req: Req) Reply { +/// One command per line, checked whole before any line runs: a line is the +/// clicked text itself, so it may not be empty or carry control characters. +/// A null `serial` clicks at whichever pane is active as each line runs, +/// which is what the root's own look and exec mean; a serial stays put. +pub fn command(p: *Pardes, req: Req, serial: ?u32, exec: bool) Reply { for ([2]bool{ false, true }) |apply| { - if (apply) beginResults(p); + if (apply) p.fs.results_len = 0; var it = std.mem.splitScalar(u8, req.data, '\n'); while (it.next()) |raw| { - const line = std.mem.trim(u8, raw, " \t\r"); - if (line.len == 0) continue; - const exec = verbIs(line, "exec"); - const text = textAfter(line, if (exec) "exec" else "look") orelse return Reply.fail(req.tag, E.INVAL); - if (text.len == 0) return Reply.fail(req.tag, E.INVAL); + const text = std.mem.trim(u8, raw, " \t\r"); + if (text.len == 0) continue; + for (text) |c| if (c < ' ' and c != '\t') return Reply.fail(req.tag, E.INVAL); if (!apply) continue; - if (p.panes[p.active] == null) return Reply.fail(req.tag, E.NOENT); - run(p, p.active, exec, text); + const id = if (serial) |s| p.paneBySerial(s) orelse break else p.active; + if (p.panes[id] == null) return Reply.fail(req.tag, E.NOENT); + run(p, id, exec, text); } } return .{ .tag = req.tag, .written = @intCast(req.data.len) }; } -pub fn rootText(p: *Pardes, buf: []u8) []const u8 { - var w = std.Io.Writer.fixed(buf); - if (p.fs.results_valid) { - for (p.fs.results[0..p.fs.results_len]) |serial| w.print("{d}\n", .{serial}) catch break; - return w.buffered(); +pub fn resultsLen(p: *Pardes) u64 { + var n: u64 = 0; + for (p.fs.results[0..p.fs.results_len]) |serial| { + var digits: [16]u8 = undefined; + n += (std.fmt.bufPrint(&digits, "{d}\n", .{serial}) catch unreachable).len; } + return n; +} + +pub fn readResults(p: *Pardes, req: Req) Reply { + const out = p.fs.stage(p.gpa); + for (p.fs.results[0..p.fs.results_len]) |serial| + out.print(p.gpa, "{d}\n", .{serial}) catch return Reply.fail(req.tag, E.NOMEM); + return tree.stagedReply(p, req); +} + +// ---- /status ---- + +fn statusText(p: *Pardes, buf: []u8) []const u8 { + var w = std.Io.Writer.fixed(buf); var count: usize = 0; for (p.panes) |slot| count += @intFromBool(slot != null); const pid: u32 = if (comptime pardes.hosted) @intCast(std.c.getpid()) else 0; @@ -134,13 +119,17 @@ pub fn rootText(p: *Pardes, buf: []u8) []const u8 { return w.buffered(); } -pub const root_text_cap = @max(MAX_PANES * 11, 64 + pardes.version.len); +pub const status_text_cap = 64 + pardes.version.len; + +pub fn statusLen(p: *Pardes) u64 { + var buf: [status_text_cap]u8 = undefined; + return statusText(p, &buf).len; +} -pub fn readRoot(p: *Pardes, req: Req) Reply { - var buf: [root_text_cap]u8 = undefined; - const text = rootText(p, &buf); +pub fn readStatus(p: *Pardes, req: Req) Reply { + var buf: [status_text_cap]u8 = undefined; const out = p.fs.stage(p.gpa); - out.appendSlice(p.gpa, text) catch return Reply.fail(req.tag, E.NOMEM); + out.appendSlice(p.gpa, statusText(p, &buf)) catch return Reply.fail(req.tag, E.NOMEM); return tree.stagedReply(p, req); } @@ -190,74 +179,35 @@ pub fn readPane(p: *Pardes, req: Req, pane: *Pane) Reply { return tree.stagedReply(p, req); } -pub fn writePane(p: *Pardes, req: Req, serial: u32) Reply { - for ([2]bool{ false, true }) |apply| { - if (apply) beginResults(p); - var it = std.mem.splitScalar(u8, req.data, '\n'); - while (it.next()) |raw| { - const line = std.mem.trim(u8, raw, " \t\r"); - if (line.len == 0) continue; - const live = p.paneBySerial(serial) orelse if (apply) break else return Reply.fail(req.tag, E.NOENT); - const errno = paneVerb(p, live, line, apply); - if (errno != 0) return Reply.fail(req.tag, errno); - } +/// `get` is the one thing here that no file of the pane's own would say: it +/// reloads the buffer from the name it carries, wherever that name resolves. +/// Repeating it in one write would only reload the same bytes, so it runs once. +pub fn writePane(p: *Pardes, req: Req, pane: *Pane) Reply { + var asked = false; + var it = std.mem.splitScalar(u8, req.data, '\n'); + while (it.next()) |raw| { + const line = std.mem.trim(u8, raw, " \t\r"); + if (line.len == 0) continue; + if (!std.mem.eql(u8, line, "get")) return Reply.fail(req.tag, E.INVAL); + asked = true; + } + if (asked) { + const errno = get(p, pane); + if (errno != 0) return Reply.fail(req.tag, errno); } return .{ .tag = req.tag, .written = @intCast(req.data.len) }; } -fn paneVerb(p: *Pardes, id: usize, line: []const u8, apply: bool) u16 { - const pane = p.panes[id] orelse return E.INVAL; - const pf = &p.fs.panes[id]; - - for ([_]bool{ false, true }) |exec| if (textAfter(line, if (exec) "exec" else "look")) |text| { - if (text.len == 0) return E.INVAL; - if (apply) run(p, id, exec, text); - return 0; +fn get(p: *Pardes, pane: *Pane) u16 { + const f = pane_files.fileOf(pane) orelse return 0; + if (!panes.Output.fileTraits(f.output).saves) return 0; + const bytes = fs.read(p, f.path) catch |err| return switch (err) { + error.FileNotFound => E.NOENT, + else => E.IO, }; - const v = std.meta.stringToEnum(Verb, line) orelse return E.INVAL; - if (!apply) return 0; - - switch (v) { - .@"addr=dot" => pf.addr = pane_files.dotOf(pane), - .@"dot=addr" => { - pane_files.clampAddr(pf, pane_files.bodyOf(pane).len); - pane_files.setDot(pane, pf.addr); - }, - .@"limit=addr" => { - pane_files.clampAddr(pf, pane_files.bodyOf(pane).len); - pf.limit = pf.addr; - }, - .clean => if (pane_files.fileOf(pane)) |f| { - f.saved_revision = f.revision; - }, - .dirty => if (pane_files.fileOf(pane)) |f| { - f.saved_revision = f.revision -% 1; - }, - .cleartag => { - pane.tag_tail_len = 0; - pane.tag_init = true; - }, - .get => if (pane_files.fileOf(pane)) |f| { - if (panes.Output.fileTraits(f.output).saves) { - if (fs.read(p, f.path)) |bytes| { - panes.File.pushUndo(p, pane); - panes.File.setContent(p, f, bytes); - f.saved_revision = f.revision; - } else |err| return switch (err) { - error.FileNotFound => E.NOENT, - else => E.IO, - }; - } - }, - .mark => { - pf.nomark = false; - panes.File.pushUndo(p, pane); - }, - .nomark => pf.nomark = true, - .noscroll => pf.noscroll = true, - .scroll => pf.noscroll = false, - .show => pane_files.showOffset(pane, pane_files.dotOf(pane).q0), - } + panes.File.pushUndo(p, pane); + panes.File.setContent(p, f, bytes); + f.saved_revision = f.revision; return 0; } @@ -272,7 +222,9 @@ const withFile = th.withFile; const serialOf = th.serialOf; const Node = tree.Node; const Status = tree.Status; -const root_ctl = @intFromEnum(tree.TopFile.ctl); +const root_status = @intFromEnum(tree.TopFile.status); +const root_look = @intFromEnum(tree.TopFile.look); +const root_exec = @intFromEnum(tree.TopFile.exec); test "pane ctl read is index's five fields plus width in cells, font and tab width" { const gpa = testing.allocator; @@ -299,37 +251,18 @@ test "pane ctl read is index's five fields plus width in cells, font and tab wid try testing.expectEqualStrings("'it''s'", w.buffered()); } -test "every pane ctl verb, and every refusal" { +test "the pane ctl takes get, and nothing that a file of its own now answers" { const gpa = testing.allocator; const p = try withFile(gpa, "one\ntwo\n"); defer p.deinit(); - const serial = serialOf(p); - const ctl_node = Node.of(serial, .ctl); - const pane = p.panes[0].?; - const pf = &p.fs.panes[0]; - - try testing.expectEqual(Status.ok, wr(p, ctl_node, "nomark\nnoscroll\ndirty\n").reply.status); - try testing.expect(pf.nomark and pf.noscroll and pane_files.dirtyOf(pane)); - try testing.expectEqual(Status.ok, wr(p, ctl_node, "mark\nscroll\nclean\n").reply.status); - try testing.expect(!pf.nomark and !pf.noscroll and !pane_files.dirtyOf(pane)); - - _ = wr(p, ctl_node, "cleartag\n"); - try testing.expectEqual(@as(usize, 0), pane.tag_tail_len); - - _ = wr(p, Node.of(serial, .addr), "2"); - _ = wr(p, ctl_node, "limit=addr\n"); - try testing.expectEqual(@as(u32, 4), pf.limit.?.q0); - _ = wr(p, ctl_node, "dot=addr\nshow\n"); - try testing.expectEqual(@as(i32, 1), pane.cur_row); - + const ctl_node = Node.of(serialOf(p), .ctl); for ([_][]const u8{ - "menu", "nomenu", "dump echo hi", "dumpdir /tmp", "font Go Mono", "lock", "unlock", "bogus", "DEL", - "name x.txt", "put", "del", "delete", "Look x", "Exec Save", + "menu", "nomenu", "dump echo hi", "font Go Mono", "lock", "bogus", "DEL", + "name x.txt", "put", "del", "delete", "Look x", "Exec Save", "clean", + "dirty", "cleartag", "dot=addr", "addr=dot", "show", "mark", "nomark", + "scroll", "limit=addr", "get x", "look /tmp", "exec Del", }) |bad| try testing.expectEqual(E.INVAL, wr(p, ctl_node, bad).errno()); - - try testing.expect(!pane_files.dirtyOf(pane)); - try testing.expectEqual(E.INVAL, wr(p, ctl_node, "dirty\nbogus\n").errno()); - try testing.expect(!pane_files.dirtyOf(pane)); + try testing.expect(p.paneBySerial(serialOf(p)) != null); } test "exec runs a builtin at the pane and records the pane it acted on" { @@ -338,61 +271,69 @@ test "exec runs a builtin at the pane and records the pane it acted on" { defer p.deinit(); const serial = serialOf(p); const pane = p.panes[0].?; - try testing.expectEqual(Status.ok, wr(p, Node.of(serial, .ctl), "exec Msg from ctl\n").reply.status); - try testing.expectEqualStrings("from ctl", pane.msg[0..pane.msg_len]); + try testing.expectEqual(Status.ok, wr(p, Node.of(serial, .exec), "Msg from exec\n").reply.status); + try testing.expectEqualStrings("from exec", pane.msg[0..pane.msg_len]); var expected: [16]u8 = undefined; - try testing.expectEqualStrings(try std.fmt.bufPrint(&expected, "{d}\n", .{serial}), rd(p, root_ctl, 0, 4096).bytes); + const own = try std.fmt.bufPrint(&expected, "{d}\n", .{serial}); + try testing.expectEqualStrings(own, rd(p, root_exec, 0, 4096).bytes); + // Either command file reads back what the last one did. + try testing.expectEqualStrings(own, rd(p, Node.of(serial, .look), 0, 4096).bytes); + try testing.expectEqual(@as(u64, own.len), call(p, .{ .tag = 1, .op = .getattr, .node = root_exec }).reply.attr.size); - try testing.expectEqual(Status.ok, wr(p, Node.of(serial, .ctl), "exec New\n").reply.status); + try testing.expectEqual(Status.ok, wr(p, Node.of(serial, .exec), "New\n").reply.status); const made = p.panes[p.active].?; try testing.expect(made.serial != serial); - try testing.expectEqualStrings(try std.fmt.bufPrint(&expected, "{d}\n", .{made.serial}), rd(p, root_ctl, 0, 4096).bytes); + try testing.expectEqualStrings(try std.fmt.bufPrint(&expected, "{d}\n", .{made.serial}), rd(p, root_exec, 0, 4096).bytes); - try testing.expectEqual(Status.ok, wr(p, Node.of(made.serial, .ctl), "exec Del\n").reply.status); + try testing.expectEqual(Status.ok, wr(p, Node.of(made.serial, .exec), "Del\n").reply.status); try testing.expect(p.paneBySerial(made.serial) == null); - try testing.expectEqualStrings(try std.fmt.bufPrint(&expected, "{d}\n", .{made.serial}), rd(p, root_ctl, 0, 4096).bytes); + try testing.expectEqualStrings(try std.fmt.bufPrint(&expected, "{d}\n", .{made.serial}), rd(p, root_exec, 0, 4096).bytes); } -test "the root ctl reads editor status until a command runs and validates whole batches" { +test "status reads the editor, and look and exec validate whole batches" { const gpa = testing.allocator; const p = try withFile(gpa, "Msg root\n"); defer p.deinit(); - const status = rd(p, root_ctl, 0, 4096); + const status = rd(p, root_status, 0, 4096); try testing.expectEqual(Status.ok, status.reply.status); var lines = std.mem.tokenizeScalar(u8, status.bytes, '\n'); try testing.expect(std.mem.startsWith(u8, lines.next().?, "pid ")); var expected: [64]u8 = undefined; try testing.expectEqualStrings(try std.fmt.bufPrint(&expected, "version {s}", .{pardes.version}), lines.next().?); - try testing.expectEqualStrings("panes 1", lines.next().?); + var live: usize = 0; + for (p.panes) |slot| live += @intFromBool(slot != null); + try testing.expectEqualStrings(try std.fmt.bufPrint(&expected, "panes {d}", .{live}), lines.next().?); try testing.expect(lines.next() == null); - const stat = call(p, .{ .tag = 1, .op = .getattr, .node = root_ctl }); + const stat = call(p, .{ .tag = 1, .op = .getattr, .node = root_status }); try testing.expectEqual(@as(u64, status.bytes.len), stat.reply.attr.size); - try testing.expectEqual(@as(u16, 0o666), stat.reply.attr.mode); + try testing.expectEqual(@as(u16, 0o444), stat.reply.attr.mode); + try testing.expectEqual(E.PERM, wr(p, root_status, "anything\n").errno()); + try testing.expectEqualStrings("", rd(p, root_exec, 0, 4096).bytes); const serial = p.next_serial; - for ([_][]const u8{ "look", "exec", "look \t", "Look /virtual/index", "exec Msg a\x00b", "exec Msg x\nbogus\n", "name x", "put" }) |invalid| { - try testing.expectEqual(E.INVAL, wr(p, root_ctl, invalid).errno()); + for ([_][]const u8{ "Msg a\x00b", "Msg x\nMsg \x01y\n" }) |invalid| { + try testing.expectEqual(E.INVAL, wr(p, root_exec, invalid).errno()); try testing.expectEqual(serial, p.next_serial); } - try testing.expectEqualStrings(status.bytes, rd(p, root_ctl, 0, 4096).bytes); + // An empty write is a no-op, not a command. + try testing.expectEqual(Status.ok, wr(p, root_exec, "\n \n").reply.status); + try testing.expectEqualStrings("", rd(p, root_exec, 0, 4096).bytes); + try testing.expectEqualStrings(status.bytes, rd(p, root_status, 0, 4096).bytes); const pane = p.panes[0].?; - try testing.expectEqual(Status.ok, wr(p, root_ctl, "exec Msg hello there\n").reply.status); + try testing.expectEqual(Status.ok, wr(p, root_exec, "Msg hello there\n").reply.status); try testing.expectEqualStrings("hello there", pane.msg[0..pane.msg_len]); - try testing.expectEqualStrings(try std.fmt.bufPrint(&expected, "{d}\n", .{pane.serial}), rd(p, root_ctl, 0, 4096).bytes); - - try testing.expectEqual(Status.ok, wr(p, root_ctl, "look /virtual/index\nexec New\n").reply.status); - var made: [MAX_PANES]u32 = undefined; - var n: usize = 0; - for (p.panes) |slot| if (slot) |q| if (q.serial != pane.serial) { - made[n] = q.serial; - n += 1; - }; - try testing.expectEqual(@as(usize, 2), n); - const listed = rd(p, root_ctl, 0, 4096); - try testing.expectEqualStrings(try std.fmt.bufPrint(&expected, "{d}\n{d}\n", .{ @min(made[0], made[1]), @max(made[0], made[1]) }), listed.bytes); - const opened = p.panes[p.paneBySerial(@min(made[0], made[1])).?].?; + try testing.expectEqualStrings(try std.fmt.bufPrint(&expected, "{d}\n", .{pane.serial}), rd(p, root_exec, 0, 4096).bytes); + + try testing.expectEqual(Status.ok, wr(p, root_look, "/virtual/index\n").reply.status); + const opened = p.panes[p.active].?; try testing.expectEqualStrings("/virtual/index", opened.file.?.path); + try testing.expectEqualStrings(try std.fmt.bufPrint(&expected, "{d}\n", .{opened.serial}), rd(p, root_look, 0, 4096).bytes); + + try testing.expectEqual(Status.ok, wr(p, root_exec, "New\n").reply.status); + const made = p.panes[p.active].?; + try testing.expect(made.serial != opened.serial); + try testing.expectEqualStrings(try std.fmt.bufPrint(&expected, "{d}\n", .{made.serial}), rd(p, root_exec, 0, 4096).bytes); } test "look opens spaced paths and locations without editing the source pane" { @@ -406,12 +347,12 @@ test "look opens spaced paths and locations without editing the source pane" { const p = try withFile(gpa, "source stays intact\n"); defer p.deinit(); const source = p.panes[0].?; - const ctl_node = Node.of(source.serial, .ctl); + const look_node = Node.of(source.serial, .look); const revision = source.file.?.revision; const undo_len = source.file.?.history.undo_len; source.cur_col = 3; - var command: [4200]u8 = undefined; - try testing.expectEqual(Status.ok, wr(p, ctl_node, try std.fmt.bufPrint(&command, "look {s}:2:3\n", .{path})).reply.status); + var clicked: [4200]u8 = undefined; + try testing.expectEqual(Status.ok, wr(p, look_node, try std.fmt.bufPrint(&clicked, "{s}:2:3\n", .{path})).reply.status); const opened = p.panes[p.active].?; try testing.expect(opened != source); try testing.expectEqualStrings(path, opened.file.?.path); @@ -423,14 +364,14 @@ test "look opens spaced paths and locations without editing the source pane" { try testing.expectEqual(undo_len, source.file.?.history.undo_len); try testing.expectEqual(@as(i32, 3), source.cur_col); var expected: [16]u8 = undefined; - try testing.expectEqualStrings(try std.fmt.bufPrint(&expected, "{d}\n", .{opened.serial}), rd(p, root_ctl, 0, 4096).bytes); + try testing.expectEqualStrings(try std.fmt.bufPrint(&expected, "{d}\n", .{opened.serial}), rd(p, root_look, 0, 4096).bytes); p.active = 0; - try testing.expectEqual(Status.ok, wr(p, root_ctl, try std.fmt.bufPrint(&command, "look {s}:3:2\n", .{path})).reply.status); + try testing.expectEqual(Status.ok, wr(p, root_look, try std.fmt.bufPrint(&clicked, "{s}:3:2\n", .{path})).reply.status); try testing.expect(p.panes[p.active].? == opened); try testing.expectEqual(@as(i32, 2), opened.cur_row); try testing.expectEqual(@as(i32, 1), opened.cur_col); - try testing.expectEqualStrings(try std.fmt.bufPrint(&expected, "{d}\n", .{opened.serial}), rd(p, root_ctl, 0, 4096).bytes); + try testing.expectEqualStrings(try std.fmt.bufPrint(&expected, "{d}\n", .{opened.serial}), rd(p, root_look, 0, 4096).bytes); } test "look validates the whole batch before opening virtual files" { @@ -438,17 +379,17 @@ test "look validates the whole batch before opening virtual files" { const p = try withFile(gpa, "source\n"); defer p.deinit(); const source = p.panes[0].?; - const ctl_node = Node.of(source.serial, .ctl); + const look_node = Node.of(source.serial, .look); const serial = p.next_serial; for ([_][]const u8{ - "look", "look \t", "look /virtual/index\x00ignored", "look /virtual/index\nbogus\n", + "/virtual/index\x00ignored", "/virtual/index\n/virtual/\x01index\n", }) |invalid| { - try testing.expectEqual(E.INVAL, wr(p, ctl_node, invalid).errno()); + try testing.expectEqual(E.INVAL, wr(p, look_node, invalid).errno()); try testing.expectEqual(serial, p.next_serial); try testing.expectEqual(@as(usize, 0), p.active); try testing.expectEqualStrings("source\n", source.file.?.content); } - try testing.expectEqual(Status.ok, wr(p, ctl_node, "look /n/self/index\n").reply.status); + try testing.expectEqual(Status.ok, wr(p, look_node, "/n/self/index\n").reply.status); const opened = p.panes[p.active].?; try testing.expectEqualStrings("/virtual/index", opened.file.?.path); try testing.expect(std.mem.indexOf(u8, opened.file.?.content, "/test.txt") != null); @@ -480,7 +421,7 @@ test "get reloads the pane from disk and reports a missing file without losing d _ = wr(p, Node.of(serial, .name), try std.fmt.bufPrint(&name, "{s}/missing.txt\n", .{directory})); _ = wr(p, Node.of(serial, .body), "unsaved\n"); - try testing.expectEqual(E.NOENT, wr(p, ctl_node, "get\nexec Del\n").errno()); + try testing.expectEqual(E.NOENT, wr(p, ctl_node, "get\n").errno()); try testing.expect(p.paneBySerial(serial) != null); try testing.expectEqualStrings("from disk\nunsaved\n", pane.file.?.content); try testing.expect(pane_files.dirtyOf(pane)); @@ -494,7 +435,7 @@ test "exec Save writes the named file through the host" { const pane = p.panes[0].?; try testing.expectEqual(Status.ok, wr(p, Node.of(serial, .name), "/tmp/renamed.txt\n").reply.status); try testing.expect(pane_files.dirtyOf(pane)); - const saved = wr(p, Node.of(serial, .ctl), "exec Save\n"); + const saved = wr(p, Node.of(serial, .exec), "Save\n"); try testing.expectEqual(Status.ok, saved.reply.status); try testing.expect(saved.saved); p.perform(.{ .save_file = .{ .pane = 0 } }); diff --git a/src/ninep/events.zig b/src/ninep/events.zig index fb49e41b..bd53bcd9 100644 --- a/src/ninep/events.zig +++ b/src/ninep/events.zig @@ -89,6 +89,13 @@ pub const Queue = struct { } }; +/// What the next read would answer, which is the size a stat reports: a +/// client can see there is something waiting without parking on it. +pub fn pending(q: *const Queue) u64 { + const record = q.peek() orelse return 0; + return record.len; +} + /// One record per read; `.again` parks the read until a record arrives. pub fn readQueue(p: *Pardes, req: Req, q: *Queue) Reply { const record = q.peek() orelse return .{ .tag = req.tag, .status = .again }; @@ -461,7 +468,7 @@ test "a pane deleted while its event file is open leaves no suppression behind" const b = call(p, .{ .tag = 19, .op = .open, .node = event }); try testing.expectEqual(@as(u16, 2), p.fs.listeners); - _ = wr(p, Node.of(serial, .ctl), "exec Del\n"); + _ = wr(p, Node.of(serial, .exec), "Del\n"); try testing.expect(p.paneBySerial(serial) == null); try testing.expectEqual(@as(u16, 0), p.fs.listeners); @@ -471,7 +478,7 @@ test "a pane deleted while its event file is open leaves no suppression behind" try testing.expectEqual(E.NOENT, rd(p, event, 0, 64).errno()); try testing.expectEqual(E.NOENT, rd(p, Node.of(serial, .body), 0, 64).errno()); - try testing.expectEqual(E.NOENT, wr(p, Node.of(serial, .ctl), "clean\n").errno()); + try testing.expectEqual(E.NOENT, wr(p, Node.of(serial, .dirty), "0\n").errno()); try testing.expectEqual(E.NOENT, call(p, .{ .tag = 22, .op = .open, .node = event }).errno()); } @@ -535,7 +542,7 @@ test "the log parks until a pane is created, renamed, saved or deleted" { try std.fmt.bufPrint(&expected, "rename {d} /tmp/logged.txt\n", .{serial}), rd(p, log, 0, 4096).bytes, ); - const saving = wr(p, Node.of(serial, .ctl), "exec Save\n"); + const saving = wr(p, Node.of(serial, .exec), "Save\n"); try testing.expectEqual(Status.ok, saving.reply.status); try testing.expect(saving.saved); p.perform(.{ .save_file = .{ .pane = @intCast(id) } }); @@ -543,7 +550,7 @@ test "the log parks until a pane is created, renamed, saved or deleted" { try std.fmt.bufPrint(&expected, "save {d} /tmp/logged.txt\n", .{serial}), rd(p, log, 0, 4096).bytes, ); - try testing.expectEqual(Status.ok, wr(p, Node.of(serial, .ctl), "exec Del\n").reply.status); + try testing.expectEqual(Status.ok, wr(p, Node.of(serial, .exec), "Del\n").reply.status); try testing.expectEqualStrings( try std.fmt.bufPrint(&expected, "del {d} /tmp/logged.txt\n", .{serial}), rd(p, log, 0, 4096).bytes, diff --git a/src/ninep/pane.zig b/src/ninep/pane.zig index b37ae645..42c0c48e 100644 --- a/src/ninep/pane.zig +++ b/src/ninep/pane.zig @@ -1,5 +1,6 @@ -//! The files under /pane//: name, body, tag, ctl, addr, data, xdata, -//! sel, errors and event. Terminal panes add pty/ (pty.zig). +//! The files under /pane//: name, body, tag, ctl, the three range +//! files addr, dot and limit, data, xdata, sel, the three flag files dirty, +//! mark and scroll, errors, event, look and exec. Terminals add pty/ (pty.zig). const std = @import("std"); const pardes = @import("../pardes.zig"); const panes = @import("../panes.zig"); @@ -187,10 +188,15 @@ pub fn spliceBody(p: *Pardes, id: usize, pane: *Pane, q0: usize, q1: usize, byte return take; } -// ---- sizes reported by stat ---- +// ---- what stat reports ---- + +/// A range file's text: acme's addr format, two right-aligned offsets, so +/// that copying one range file onto another is the whole of `dot=addr`. +pub const range_len: u64 = 24; pub fn fileSize(p: *Pardes, id: usize, f: PaneFile) u64 { const pane = p.panes[id] orelse return 0; + const pf = &p.fs.panes[id]; return switch (f) { .body, .data, .xdata => bodyOf(pane).len, .tag => tagOf(p, pane).len, @@ -203,7 +209,24 @@ pub fn fileSize(p: *Pardes, id: usize, f: PaneFile) u64 { const d = dotOf(pane); break :sel @max(d.q0, d.q1) - d.q0; }, - .dir, .addr, .errors, .event, .pty, .pty_ctl, .pty_status, .pty_data => 0, + .addr, .dot => range_len, + .limit => if (pf.limit == null) 0 else range_len, + .dirty, .mark, .scroll => 2, + .look, .exec => ctl.resultsLen(p), + .event => events.pending(&pf.events), + .pty_status => pty.status_len, + .pty_data => events.pending(&pf.pty_out), + .dir, .errors, .pty, .pty_ctl => 0, + }; +} + +/// The qid version, which a client polls to watch a file for change. Only +/// the pane's text can promise one: its revision counts every edit, and +/// nothing else here changes in step with it. +pub fn versionOf(pane: *const Pane, f: PaneFile) u32 { + return switch (f) { + .body, .data, .xdata => if (pane.file) |*file| file.revision else 0, + else => 0, }; } @@ -246,13 +269,17 @@ pub fn read(p: *Pardes, req: Req, id: usize, pane: *Pane, file: PaneFile) Reply .ctl => ctl.readPane(p, req, pane), .addr => addr: { clampAddr(pf, bodyOf(pane).len); - const out = p.fs.stage(p.gpa); - out.print(p.gpa, "{d:>11} {d:>11} ", .{ pf.addr.q0, pf.addr.q1 }) catch {}; - break :addr tree.stagedReply(p, req); + break :addr readRange(p, req, pf.addr); }, + .dot => readRange(p, req, dotOf(pane)), + .limit => readRange(p, req, pf.limit), .data => readData(req, id, pane, pf, false), .xdata => readData(req, id, pane, pf, true), .sel => readSel(req, id, pane), + .dirty => readFlag(p, req, dirtyOf(pane)), + .mark => readFlag(p, req, !pf.nomark), + .scroll => readFlag(p, req, !pf.noscroll), + .look, .exec => ctl.readResults(p, req), .event => events.readQueue(p, req, &pf.events), .pty_status => pty.readStatus(p, req, id, pane), .pty_data => pty.readData(p, req, pf), @@ -260,6 +287,20 @@ pub fn read(p: *Pardes, req: Req, id: usize, pane: *Pane, file: PaneFile) Reply }; } +/// An unset limit reads empty, which is how a client tells it from one that +/// happens to bound nothing. +fn readRange(p: *Pardes, req: Req, r: ?State.Range) Reply { + const out = p.fs.stage(p.gpa); + if (r) |range| out.print(p.gpa, "{d:>11} {d:>11} ", .{ range.q0, range.q1 }) catch {}; + return tree.stagedReply(p, req); +} + +fn readFlag(p: *Pardes, req: Req, on: bool) Reply { + const out = p.fs.stage(p.gpa); + out.appendSlice(p.gpa, if (on) "1\n" else "0\n") catch {}; + return tree.stagedReply(p, req); +} + fn readBody(p: *Pardes, req: Req, id: usize, pane: *Pane) Reply { if (pane.file != null) { const text = bodyOf(pane); @@ -322,10 +363,12 @@ pub fn write(p: *Pardes, req: Req, id: usize, pane: *Pane, file: PaneFile) Reply .name => writeName(p, req, id, pane), .body => writeBody(p, req, id, pane), .tag => writeTag(p, req, pane), - .ctl => ctl.writePane(p, req, pane.serial), - .addr => writeAddr(p, req, id, pane), + .ctl => ctl.writePane(p, req, pane), + .addr, .dot, .limit => writeRange(p, req, id, pane, file), .data, .xdata => writeData(p, req, id, pane), .sel => writeSel(p, req, id, pane), + .dirty, .mark, .scroll => writeFlag(p, req, id, pane, file), + .look, .exec => ctl.command(p, req, pane.serial, file == .exec), .event => events.writeEvent(p, req, id), .errors => if (appendErrors(p, id, req.data)) |took| .{ .tag = req.tag, .written = @intCast(took) } @@ -389,15 +432,68 @@ fn writeSel(p: *Pardes, req: Req, id: usize, pane: *Pane) Reply { return .{ .tag = req.tag, .written = @intCast(take) }; } -fn writeAddr(p: *Pardes, req: Req, id: usize, pane: *Pane) Reply { +/// The pair of offsets a range file reads back, so that copying `addr` onto +/// `dot` or `limit` does what acme spelled `dot=addr` and `limit=addr`. +fn pairOf(text: []const u8) ?State.Range { + var it = std.mem.tokenizeAny(u8, text, " \t"); + const q0 = std.fmt.parseInt(u32, it.next() orelse return null, 10) catch return null; + const q1 = std.fmt.parseInt(u32, it.next() orelse return null, 10) catch return null; + if (it.next() != null) return null; + return .{ .q0 = q0, .q1 = @max(q0, q1) }; +} + +/// A range file takes an address expression, or that pair of offsets. +fn rangeOf(pf: *State, text: []const u8, data: []const u8) ?State.Range { + const expr = std.mem.trimEnd(u8, data, "\n"); + if (pairOf(expr)) |r| { + const n = clip(text.len); + return .{ .q0 = @min(r.q0, n), .q1 = @min(r.q1, n) }; + } + var a: addressing.Addr = .{ .text = text, .lim = pf.limit, .expr = expr }; + const r = a.address(pf.addr) orelse return null; + return if (a.i < expr.len) null else r; +} + +fn writeRange(p: *Pardes, req: Req, id: usize, pane: *Pane, file: PaneFile) Reply { const pf = &p.fs.panes[id]; const text = bodyOf(pane); clampAddr(pf, text.len); - const expr = std.mem.trimEnd(u8, req.data, "\n"); - var a: addressing.Addr = .{ .text = text, .lim = pf.limit, .expr = expr }; - const r = a.address(pf.addr) orelse return Reply.fail(req.tag, E.INVAL); - if (a.i < expr.len) return Reply.fail(req.tag, E.INVAL); - pf.addr = r; + const r = rangeOf(pf, text, req.data) orelse return Reply.fail(req.tag, E.INVAL); + switch (file) { + .addr => pf.addr = r, + .limit => pf.limit = r, + // Setting dot scrolls to it, which is the whole of acme's `show`. + .dot => { + if (fileOf(pane) == null) return Reply.fail(req.tag, E.INVAL); + setDot(pane, r); + }, + else => unreachable, + } + return .{ .tag = req.tag, .written = @intCast(req.data.len) }; +} + +fn flagOf(data: []const u8) ?bool { + const word = std.mem.trim(u8, data, " \t\r\n"); + if (std.mem.eql(u8, word, "1")) return true; + if (std.mem.eql(u8, word, "0")) return false; + return null; +} + +fn writeFlag(p: *Pardes, req: Req, id: usize, pane: *Pane, file: PaneFile) Reply { + const on = flagOf(req.data) orelse return Reply.fail(req.tag, E.INVAL); + const pf = &p.fs.panes[id]; + switch (file) { + .dirty => { + const f = fileOf(pane) orelse return Reply.fail(req.tag, E.INVAL); + f.saved_revision = if (on) f.revision -% 1 else f.revision; + }, + .mark => { + pf.nomark = !on; + if (on) panes.File.pushUndo(p, pane); + }, + .scroll => pf.noscroll = !on, + else => unreachable, + } return .{ .tag = req.tag, .written = @intCast(req.data.len) }; } @@ -475,14 +571,24 @@ pub fn appendErrors(p: *Pardes, id: usize, text: []const u8) ?usize { return text.len; } -/// Truncation empties a body; every other setattr just answers fresh attributes. +/// Truncation empties whatever the file holds: the body, the tag's editable +/// tail (acme's `cleartag`), a range. Every other setattr just answers fresh +/// attributes. pub fn truncate(p: *Pardes, id: usize, pane: *Pane, file: PaneFile) tree.Status { + const pf = &p.fs.panes[id]; switch (file) { .body, .data, .xdata => if (fileOf(pane) != null) { _ = spliceBody(p, id, pane, 0, bodyOf(pane).len, "") orelse return .err; - p.fs.panes[id].addr = .{}; + pf.addr = .{}; setDot(pane, .{}); }, + .tag => { + pane.tag_tail_len = 0; + pane.tag_init = true; + }, + .addr => pf.addr = .{}, + .limit => pf.limit = null, + .dot => if (fileOf(pane) != null) setDot(pane, .{}), else => {}, } return .ok; @@ -509,15 +615,19 @@ test "index lists serial kind dirty flag and name and stat reports its length" { const a = rd(p, index, 0, 4096); try testing.expectEqual(Status.ok, a.reply.status); var want: [64]u8 = undefined; - try testing.expectEqualStrings(try std.fmt.bufPrint(&want, "{d} text 0 /test.txt\n", .{pane.serial}), a.bytes); + const clean_row = try std.fmt.bufPrint(&want, "{d} text 0 /test.txt\n", .{pane.serial}); + try testing.expect(std.mem.indexOf(u8, a.bytes, clean_row) != null); + const at = std.mem.indexOf(u8, a.bytes, clean_row).?; const stat = call(p, .{ .tag = 1, .op = .getattr, .node = index }); try testing.expectEqual(@as(u64, a.bytes.len), stat.reply.attr.size); try testing.expectEqual(@as(u16, 0o444), stat.reply.attr.mode); pane.file.?.saved_revision = pane.file.?.revision -% 1; - try testing.expectEqualStrings(try std.fmt.bufPrint(&want, "{d} text 1 /test.txt\n", .{pane.serial}), rd(p, index, 0, 4096).bytes); - const mid = rd(p, index, 2, 4); - try testing.expectEqualStrings("text", mid.bytes); + var dirty_want: [64]u8 = undefined; + const dirty_row = try std.fmt.bufPrint(&dirty_want, "{d} text 1 /test.txt\n", .{pane.serial}); + try testing.expect(std.mem.indexOf(u8, rd(p, index, 0, 4096).bytes, dirty_row) != null); + const kind = at + std.mem.indexOfScalar(u8, clean_row, ' ').? + 1; + try testing.expectEqualStrings("text", rd(p, index, kind, 4).bytes); const serial = try th.newPane(p); const both = rd(p, index, 0, 4096); @@ -533,10 +643,11 @@ test "a terminal is listed as term with its directory as name" { const pane = p.panes[0].?; p.setCwd(0, "/work/dir"); var want: [64]u8 = undefined; - try testing.expectEqualStrings( - try std.fmt.bufPrint(&want, "{d} term 0 /work/dir\n", .{pane.serial}), + try testing.expect(std.mem.indexOf( + u8, rd(p, @intFromEnum(tree.TopFile.index), 0, 4096).bytes, - ); + try std.fmt.bufPrint(&want, "{d} term 0 /work/dir\n", .{pane.serial}), + ) != null); try testing.expectEqualStrings("/work/dir\n", rd(p, Node.of(pane.serial, .name), 0, 4096).bytes); try testing.expectEqual(E.PERM, wr(p, Node.of(pane.serial, .name), "/elsewhere\n").errno()); } @@ -566,6 +677,13 @@ test "body reads at any offset and writes append" { try testing.expectEqual(@as(u64, "one\ntwo\nthree\na".len), stat.reply.attr.size); try testing.expectEqual(@as(u16, 0o666), stat.reply.attr.mode); try testing.expect(stat.reply.attr.mtime >= p.fs.started); + + // The qid version is the pane's revision, so a stat sees an edit land. + try testing.expectEqual(p.panes[0].?.file.?.revision, stat.reply.attr.version); + _ = wr(p, body, "more\n"); + const later = call(p, .{ .tag = 7, .op = .getattr, .node = body }); + try testing.expect(later.reply.attr.version != stat.reply.attr.version); + try testing.expectEqual(@as(u32, 0), call(p, .{ .tag = 8, .op = .getattr, .node = Node.of(serial, .tag) }).reply.attr.version); } test "a body write to a terminal pane types at its shell" { @@ -653,18 +771,29 @@ test "sel reads the selection and writing sel replaces it" { const p = try withFile(gpa, "one\ntwo\n"); defer p.deinit(); const serial = serialOf(p); - const ctl_node = Node.of(serial, .ctl); + const addr_node = Node.of(serial, .addr); + const dot = Node.of(serial, .dot); const sel = Node.of(serial, .sel); - _ = wr(p, Node.of(serial, .addr), "#0,#3"); - try testing.expectEqual(Status.ok, wr(p, ctl_node, "dot=addr\n").reply.status); + // Copying addr onto dot is the whole of acme's `dot=addr`, and back again + // of `addr=dot`; each range file reads exactly what the other takes. + _ = wr(p, addr_node, "#0,#3"); + try testing.expectEqual(Status.ok, wr(p, dot, " 0 3 ").reply.status); + try testing.expectEqualStrings(" 0 3 ", rd(p, dot, 0, 100).bytes); + try testing.expectEqual(range_len, call(p, .{ .tag = 1, .op = .getattr, .node = dot }).reply.attr.size); try testing.expectEqualStrings("one", rd(p, sel, 0, 100).bytes); try testing.expectEqual(@as(u64, 3), call(p, .{ .tag = 1, .op = .getattr, .node = sel }).reply.attr.size); - _ = wr(p, ctl_node, "addr=dot\n"); + _ = wr(p, addr_node, "#0"); + _ = wr(p, addr_node, " 0 3 "); try testing.expectEqual(@as(u32, 0), p.fs.panes[0].addr.q0); try testing.expectEqual(@as(u32, 3), p.fs.panes[0].addr.q1); + // A truncation empties dot; an address expression addresses it. + _ = call(p, .{ .tag = 9, .op = .setattr, .node = dot, .truncate = true }); + try testing.expectEqualStrings("", rd(p, sel, 0, 100).bytes); + try testing.expectEqual(Status.ok, wr(p, dot, "#0,#3").reply.status); + try testing.expectEqual(Status.ok, wr(p, sel, "ONE").reply.status); try testing.expectEqualStrings("ONE\ntwo\n", p.panes[0].?.file.?.content); _ = wr(p, sel, "!"); @@ -672,6 +801,62 @@ test "sel reads the selection and writing sel replaces it" { try testing.expectEqual(@as(u64, 0), call(p, .{ .tag = 2, .op = .getattr, .node = sel }).reply.attr.size); } +test "the flag files read and write the state acme kept behind ctl verbs" { + const gpa = testing.allocator; + const p = try withFile(gpa, "one\ntwo\n"); + defer p.deinit(); + const serial = serialOf(p); + const pane = p.panes[0].?; + const pf = &p.fs.panes[0]; + const dirty = Node.of(serial, .dirty); + const mark = Node.of(serial, .mark); + const scroll = Node.of(serial, .scroll); + + for ([_]u64{ dirty, mark, scroll }) |node| { + try testing.expectEqual(@as(u64, 2), call(p, .{ .tag = 1, .op = .getattr, .node = node }).reply.attr.size); + for ([_][]const u8{ "", "yes", "2", "0 1", "true" }) |bad| + try testing.expectEqual(E.INVAL, wr(p, node, bad).errno()); + } + + try testing.expectEqualStrings("0\n", rd(p, dirty, 0, 8).bytes); + try testing.expectEqualStrings("1\n", rd(p, mark, 0, 8).bytes); + try testing.expectEqualStrings("1\n", rd(p, scroll, 0, 8).bytes); + + try testing.expectEqual(Status.ok, wr(p, dirty, "1\n").reply.status); + try testing.expect(dirtyOf(pane)); + try testing.expectEqualStrings("1\n", rd(p, dirty, 0, 8).bytes); + _ = wr(p, dirty, "0"); + try testing.expect(!dirtyOf(pane)); + + _ = wr(p, mark, "0"); + _ = wr(p, scroll, "0"); + try testing.expect(pf.nomark and pf.noscroll); + try testing.expectEqualStrings("0\n", rd(p, mark, 0, 8).bytes); + try testing.expectEqualStrings("0\n", rd(p, scroll, 0, 8).bytes); + _ = wr(p, mark, "1"); + _ = wr(p, scroll, "1"); + try testing.expect(!pf.nomark and !pf.noscroll); + + // A terminal has no file, so its dirty flag is readable but not writable. + const term = try th.withTerm(gpa); + defer term.deinit(); + try testing.expectEqualStrings("0\n", rd(term, Node.of(serialOf(term), .dirty), 0, 8).bytes); + try testing.expectEqual(E.INVAL, wr(term, Node.of(serialOf(term), .dirty), "1").errno()); +} + +test "truncating the tag clears its editable tail" { + const p = try withFile(testing.allocator, "x\n"); + defer p.deinit(); + const pane = p.panes[0].?; + const tag = Node.of(pane.serial, .tag); + _ = wr(p, tag, " Mine"); + try testing.expect(pane.tag_tail_len > 0); + const cleared = call(p, .{ .tag = 1, .op = .setattr, .node = tag, .truncate = true }); + try testing.expectEqual(Status.ok, cleared.reply.status); + try testing.expectEqual(@as(usize, 0), pane.tag_tail_len); + try testing.expect(std.mem.indexOf(u8, rd(p, tag, 0, 4096).bytes, " Mine") == null); +} + test "name reads the file name and writing it promotes a scratch without touching its body" { const gpa = testing.allocator; const p = try withFile(gpa, "opener\n"); diff --git a/src/ninep/pty.zig b/src/ninep/pty.zig index e6696b85..1b71a8d3 100644 --- a/src/ninep/pty.zig +++ b/src/ninep/pty.zig @@ -76,6 +76,9 @@ fn verb(p: *Pardes, id: usize, line: []const u8, apply: bool) bool { return true; } +/// Three right-aligned fields: cols, rows and whether the host holds the tty. +pub const status_len: u64 = 36; + pub fn readStatus(p: *Pardes, req: Req, id: usize, pane: *Pane) Reply { const out = p.fs.stage(p.gpa); out.print(p.gpa, "{d:>11} {d:>11} {d:>11} ", .{ @@ -146,7 +149,7 @@ test "a pane that is not a terminal has no pty/ at all" { var buf: [32]th.Dirent = undefined; const files = th.dirents(rdir(p, dir, 0).bytes, &buf); - try testing.expectEqual(@as(usize, 10), files.len); + try testing.expectEqual(@as(usize, 17), files.len); try testing.expect(th.nameAt(files, "pty") == null); try testing.expectEqual(E.NOENT, look_up(p, dir, "pty_ctl").errno()); @@ -167,7 +170,7 @@ test "a terminal pane's pty/ holds exactly ctl, status and data" { var buf: [32]th.Dirent = undefined; const files = th.dirents(rdir(p, dir, 0).bytes, &buf); - try testing.expectEqual(@as(usize, 11), files.len); + try testing.expectEqual(@as(usize, 18), files.len); try testing.expect(th.nameAt(files, "pty").?.dir); const inside = th.dirents(rdir(p, Node.of(serial, .pty), 0).bytes, &buf); @@ -247,7 +250,7 @@ test "every pty/ctl verb, and every refusal" { "cooked", "winsize 80 24\nbogus", // a good verb beside a bad one "bogus\nwinsize 80 24", - "look x", // a `ctl` verb; the two files share no vocabulary + "look x", // a pane command; pty/ctl shares none of that vocabulary "exec Del", }) |bad| { const a = wr(p, ctl, bad); diff --git a/src/ninep/screen.zig b/src/ninep/screen.zig index 5b68b34c..2684aa41 100644 --- a/src/ninep/screen.zig +++ b/src/ninep/screen.zig @@ -83,22 +83,33 @@ pub fn releaseSnapshot(p: *Pardes, req: Req) bool { return true; } -pub fn readListeners(p: *Pardes, req: Req) Reply { - var buf: [512]u8 = undefined; - var text = std.Io.Writer.fixed(&buf); +const listeners_cap = 512; + +fn listenersText(p: *Pardes, buf: []u8) []const u8 { + var text = std.Io.Writer.fixed(buf); if (p.fs.socket_path.len != 0) - text.print("unix!{s}\n", .{p.fs.socket_path}) catch return Reply.fail(req.tag, E.IO); + text.print("unix!{s}\n", .{p.fs.socket_path}) catch return text.buffered(); for ([_]?std.Io.net.IpAddress{ p.fs.tcp_address, p.fs.quic_address }, [_][]const u8{ "tcp", "quic" }) |maybe, transport| { const address = maybe orelse continue; switch (address) { .ip4 => |ip| text.print("{s}!{d}.{d}.{d}.{d}!{d}\n", .{ transport, ip.bytes[0], ip.bytes[1], ip.bytes[2], ip.bytes[3], ip.port }) catch - return Reply.fail(req.tag, E.IO), + return text.buffered(), .ip6 => |ip| text.print("{s}!{f}!{d}\n", .{ transport, std.Io.net.Ip6Address.Unresolved{ .bytes = ip.bytes, .interface_name = null }, ip.port }) catch - return Reply.fail(req.tag, E.IO), + return text.buffered(), } } + return text.buffered(); +} + +pub fn listenersLen(p: *Pardes) u64 { + var buf: [listeners_cap]u8 = undefined; + return listenersText(p, &buf).len; +} + +pub fn readListeners(p: *Pardes, req: Req) Reply { + var buf: [listeners_cap]u8 = undefined; const out = p.fs.stage(p.gpa); - out.appendSlice(p.gpa, text.buffered()) catch return Reply.fail(req.tag, E.NOMEM); + out.appendSlice(p.gpa, listenersText(p, &buf)) catch return Reply.fail(req.tag, E.NOMEM); return tree.stagedReply(p, req); } diff --git a/src/ninep/testing.zig b/src/ninep/testing.zig index ba26cb38..ad1d84e4 100644 --- a/src/ninep/testing.zig +++ b/src/ninep/testing.zig @@ -69,13 +69,30 @@ pub fn look_up(p: *Pardes, dir: u64, name: []const u8) Answer { return call(p, .{ .tag = 3, .op = .lookup, .node = dir, .data = name }); } -/// Opens /new once, as a client would, and returns the pane it made. +/// Creates a pane in /pane, as a client's mkdir does, and returns its serial. pub fn newPane(p: *Pardes) !u32 { - const new = @intFromEnum(tree.TopFile.new); - const opened = call(p, .{ .tag = 9, .op = .open, .node = new }); - if (opened.reply.status != .ok or opened.reply.handle == 0) return error.NoPane; - _ = call(p, .{ .tag = 9, .op = .release, .node = new, .handle = opened.reply.handle }); - return opened.reply.handle; + const made = mkdir(p, "scratch"); + if (made.reply.status != .ok) return error.NoPane; + const target = tree.Node.target(made.reply.attr.node) orelse return error.NoPane; + return switch (target) { + .pane => |t| t.serial, + .top => error.NoPane, + }; +} + +pub fn mkdir(p: *Pardes, name: []const u8) Answer { + return call(p, .{ + .tag = 9, + .op = .open, + .node = @intFromEnum(tree.TopFile.pane), + .data = name, + .create = true, + .perm = 0x8000_0000 | 0o755, + }); +} + +pub fn rmdir(p: *Pardes, node: u64) Answer { + return call(p, .{ .tag = 9, .op = .release, .node = node, .remove = true }); } pub fn withFile(gpa: std.mem.Allocator, text: []const u8) !*Pardes { diff --git a/src/ninep/tree.zig b/src/ninep/tree.zig index 56c3112d..46609649 100644 --- a/src/ninep/tree.zig +++ b/src/ninep/tree.zig @@ -4,8 +4,10 @@ //! extended here with the editor's reply payload; fs.zig keeps host access //! and mounts. //! -//! /README /index /ctl /new /log /screen /listeners -//! /pane//{name,body,tag,ctl,addr,data,xdata,sel,errors,event,pty/} +//! /README /index /status /look /exec /log /screen /listeners +//! /pane/ mkdir makes a pane, rmdir closes it +//! /pane//{name,body,tag,ctl,addr,dot,limit,data,xdata,sel, +//! dirty,mark,scroll,errors,event,look,exec,pty/} //! /os/... the host filesystem /src/... embedded sources (opt-in) const std = @import("std"); const cloud9 = @import("cloud9"); @@ -47,11 +49,16 @@ pub const Payload = union(enum) { pub const Reply = cloud9.fs.ReplyWith(Payload); +/// Tcreate opens a pane and Tremove closes one; nothing else in the tree is +/// created or destroyed by the protocol, and wstat stays a truncation. +pub const features: cloud9.fs.Features = .{ .create = true, .remove = true }; + pub fn changesPane(req: Req) bool { return switch (req.op) { .write, .setattr => true, - .open => req.node == @intFromEnum(TopFile.new), - .lookup, .getattr, .read, .release, .readdir => false, + .open => req.create, + .release => req.remove, + .lookup, .getattr, .read, .readdir => false, }; } @@ -63,8 +70,9 @@ pub const TopFile = enum(u4) { root = 1, README, index, - ctl, - new, + status, + look, + exec, log, screen, listeners, @@ -77,8 +85,8 @@ pub const TopFile = enum(u4) { pub fn mode(f: TopFile) u16 { return switch (f) { .root, .pane => 0o755, - .ctl => 0o666, - .README, .index, .new, .log, .screen, .listeners => 0o444, + .look, .exec => 0o666, + .README, .index, .status, .log, .screen, .listeners => 0o444, }; } @@ -89,18 +97,26 @@ pub const TopFile = enum(u4) { pub const root: u64 = @intFromEnum(TopFile.root); -pub const PaneFile = enum(u4) { +/// Declaration order is readdir order. +pub const PaneFile = enum(u5) { dir = 0, name, body, tag, ctl, addr, + dot, + limit, data, xdata, sel, + dirty, + mark, + scroll, errors, event, + look, + exec, pty, pty_ctl, pty_status, @@ -138,8 +154,8 @@ pub const PaneFile = enum(u4) { }; pub const Node = packed struct(u64) { - file: u4 = 0, - serial: u60 = 0, + file: u5 = 0, + serial: u59 = 0, pub fn of(serial: u32, file: PaneFile) u64 { std.debug.assert(serial != 0); @@ -240,8 +256,13 @@ pub fn stagedReply(p: *Pardes, req: Req) Reply { // ---- dispatch ---- pub fn handle(p: *Pardes, req: Req) Reply { - if (req.node == fs.os_root or req.node & fs.os_node != 0) return fs.osHandle(p, req); - if (req.node & sources.archive_node != 0) return sources.handle(p, req); + const host = req.node == fs.os_root or req.node & fs.os_node != 0; + const archive = req.node & sources.archive_node != 0; + // Only /pane is created in and removed from. The host tree and the + // embedded sources say so, rather than quietly doing nothing. + if ((host or archive) and (req.create or req.remove)) return Reply.fail(req.tag, E.PERM); + if (host) return fs.osHandle(p, req); + if (archive) return sources.handle(p, req); const target = Node.target(req.node) orelse return Reply.fail(req.tag, E.NOENT); if (req.op == .write or req.op == .setattr) p.fs.origin = switch (target) { .pane => |t| @as(u8, if (t.file == .body or t.file == .tag) 'E' else 'F'), @@ -280,6 +301,7 @@ fn attrOf(p: *Pardes, target: Target) ?Reply.Attr { .mode = t.file.mode(), .size = pane.fileSize(p, id, t.file), .mtime = pane.mtimeOf(p, pn), + .version = pane.versionOf(pn, t.file), }; }, } @@ -292,13 +314,14 @@ fn attrReply(p: *Pardes, tag: u64, target: Target) Reply { fn topSize(p: *Pardes, f: TopFile) u64 { return switch (f) { - .root, .pane, .new, .log, .screen, .listeners => 0, + // ponytail: /screen has no length until an open renders its frame. + .root, .pane, .screen => 0, .index => pane.indexLen(p), .README => fs.help.len, - .ctl => ctl: { - var buf: [ctl.root_text_cap]u8 = undefined; - break :ctl ctl.rootText(p, &buf).len; - }, + .status => ctl.statusLen(p), + .look, .exec => ctl.resultsLen(p), + .log => events.pending(&p.fs.log), + .listeners => screen.listenersLen(p), }; } @@ -366,7 +389,7 @@ fn readdir(p: *Pardes, req: Req, target: Target) Reply { switch (target) { .top => |f| switch (f) { .root => { - inline for (.{ TopFile.README, TopFile.index, TopFile.ctl, TopFile.new, TopFile.log, TopFile.screen, TopFile.listeners, TopFile.pane }) |t| { + inline for (.{ TopFile.README, TopFile.index, TopFile.status, TopFile.look, TopFile.exec, TopFile.log, TopFile.screen, TopFile.listeners, TopFile.pane }) |t| { if (skip > 0) skip -= 1 else stageDirent(out, p.gpa, @intFromEnum(t), t.dir(), t.fileName()); } if (skip > 0) skip -= 1 else stageDirent(out, p.gpa, fs.os_root, true, "os"); @@ -403,21 +426,27 @@ fn readdir(p: *Pardes, req: Req, target: Target) Reply { return .{ .tag = req.tag, .payload = .{ .staged = @intCast(out.items.len) } }; } -fn newPane(p: *Pardes) ?u32 { - const slot = p.freeSlot() orelse return null; +/// Tcreate in /pane opens a pane, the way mkdir opens a directory. The name +/// asked for is ignored: a pane is named by the serial the editor gives it, +/// which the reply carries back and /index lists last. +fn create(p: *Pardes, req: Req, target: Target) Reply { + switch (target) { + .top => |f| if (f != .pane) return Reply.fail(req.tag, E.PERM), + .pane => return Reply.fail(req.tag, E.PERM), + } + if (req.perm & cloud9.dmdir == 0) return Reply.fail(req.tag, E.PERM); + const slot = p.freeSlot() orelse return Reply.fail(req.tag, E.NFILE); p.newScratchBelow(p.active); - const pn = p.panes[slot] orelse return null; - return pn.serial; + const made = p.panes[slot] orelse return Reply.fail(req.tag, E.NFILE); + const attr = attrOf(p, .{ .pane = .{ .serial = made.serial, .file = .dir } }) orelse + return Reply.fail(req.tag, E.NFILE); + return .{ .tag = req.tag, .handle = 1, .attr = attr }; } fn open(p: *Pardes, req: Req, target: Target) Reply { + if (req.create) return create(p, req, target); switch (target) { .top => |f| switch (f) { - // The clone idiom: each open makes one empty pane; reads answer its serial. - .new => { - const serial = newPane(p) orelse return Reply.fail(req.tag, E.NFILE); - return .{ .tag = req.tag, .handle = serial }; - }, .screen => return screen.openSnapshot(p, req, true), .log => p.fs.log_readers +|= 1, else => {}, @@ -429,11 +458,7 @@ fn open(p: *Pardes, req: Req, target: Target) Reply { if (t.file.inPty() and !pn.isTerminal()) return Reply.fail(req.tag, E.NOENT); switch (t.file) { .body => if (pn.isTerminal()) return screen.openSnapshot(p, req, false), - .ctl => pf.limit = null, - .addr => { - pf.addr = .{}; - pf.limit = null; - }, + .addr => pf.addr = .{}, .event => { pf.readers +|= 1; p.fs.listeners +|= 1; @@ -446,7 +471,27 @@ fn open(p: *Pardes, req: Req, target: Target) Reply { return .{ .tag = req.tag, .handle = 1 }; } +/// Tremove closes a pane. Nothing else in the tree can be removed, and this +/// is also where an ORCLOSE open lands, so every node is checked here. +fn remove(p: *Pardes, req: Req) Reply { + const target = Node.target(req.node) orelse return Reply.fail(req.tag, E.NOENT); + const t = switch (target) { + .pane => |t| t, + .top => return Reply.fail(req.tag, E.PERM), + }; + if (t.file != .dir) return Reply.fail(req.tag, E.PERM); + const id = p.paneBySerial(t.serial) orelse return Reply.fail(req.tag, E.NOENT); + p.removePane(id) catch return Reply.fail(req.tag, E.IO); + return .{ .tag = req.tag }; +} + fn release(p: *Pardes, req: Req) Reply { + // The handle's bookkeeping runs whether or not the removal is allowed. + const done = releaseHandle(p, req); + return if (req.remove) remove(p, req) else done; +} + +fn releaseHandle(p: *Pardes, req: Req) Reply { if (screen.releaseSnapshot(p, req)) return .{ .tag = req.tag }; const target = Node.target(req.node) orelse return .{ .tag = req.tag }; switch (target) { @@ -502,12 +547,8 @@ fn read(p: *Pardes, req: Req, target: Target) Reply { } break :index stagedReply(p, req); }, - .ctl => ctl.readRoot(p, req), - .new => new: { - if (req.handle == 0) break :new Reply.fail(req.tag, E.INVAL); - p.fs.stage(p.gpa).print(p.gpa, "{d}\n", .{req.handle}) catch break :new Reply.fail(req.tag, E.NOMEM); - break :new stagedReply(p, req); - }, + .status => ctl.readStatus(p, req), + .look, .exec => ctl.readResults(p, req), .log => events.readQueue(p, req, &p.fs.log), .screen => screen.readSnapshot(p, req, null), .listeners => screen.readListeners(p, req), @@ -525,7 +566,7 @@ fn read(p: *Pardes, req: Req, target: Target) Reply { fn write(p: *Pardes, req: Req, target: Target) Reply { switch (target) { .top => |f| return switch (f) { - .ctl => ctl.writeRoot(p, req), + .look, .exec => ctl.command(p, req, null, f == .exec), else => Reply.fail(req.tag, E.PERM), }, .pane => |t| { @@ -587,8 +628,8 @@ test "filesystem inspection preserves pending and displayed Look hover" { const preview = p.look_hover_preview; const requests = [_]Req{ .{ .tag = 1, .op = .lookup, .node = root, .data = "screen" }, - .{ .tag = 1, .op = .lookup, .node = root, .data = "new" }, - .{ .tag = 1, .op = .getattr, .node = @intFromEnum(TopFile.new) }, + .{ .tag = 1, .op = .lookup, .node = root, .data = "status" }, + .{ .tag = 1, .op = .getattr, .node = @intFromEnum(TopFile.pane) }, .{ .tag = 2, .op = .getattr, .node = body }, .{ .tag = 3, .op = .open, .node = body }, .{ .tag = 4, .op = .read, .node = body, .size = 5 }, @@ -614,7 +655,7 @@ test "filesystem inspection preserves pending and displayed Look hover" { test "filesystem pane creation and truncation cancel Look hover" { const requests = [_]Req{ - .{ .tag = 2, .op = .open, .node = @intFromEnum(TopFile.new) }, + .{ .tag = 2, .op = .open, .node = @intFromEnum(TopFile.pane), .data = "x", .create = true, .perm = cloud9.dmdir | 0o755 }, .{ .tag = 3, .op = .setattr, .node = 0, .truncate = true }, }; for (requests) |request| { @@ -644,13 +685,13 @@ test "readdir lists the root and a pane directory without creating anything" { var top_bytes: [4096]u8 = undefined; @memcpy(top_bytes[0..top_reply.bytes.len], top_reply.bytes); const top = th.dirents(top_bytes[0..top_reply.bytes.len], &buf); - try testing.expect(top.len >= 9); - for ([_][]const u8{ "README", "index", "ctl", "new", "log", "screen", "listeners", "pane", "os" }, 0..) |name, i| { + try testing.expect(top.len >= 10); + for ([_][]const u8{ "README", "index", "status", "look", "exec", "log", "screen", "listeners", "pane", "os" }, 0..) |name, i| { try testing.expectEqualStrings(name, top[i].name); - try testing.expectEqual(i >= 7, top[i].dir); + try testing.expectEqual(i >= 8, top[i].dir); } - try testing.expectEqual(@intFromEnum(TopFile.pane), top[7].node); - try testing.expectEqual(fs.os_root, top[8].node); + try testing.expectEqual(@intFromEnum(TopFile.pane), top[8].node); + try testing.expectEqual(fs.os_root, top[9].node); var idbuf: [16]u8 = undefined; try testing.expect(th.nameAt(top, try std.fmt.bufPrint(&idbuf, "{d}", .{serial})) == null); try testing.expect(th.nameAt(top, "self") == null); @@ -674,13 +715,18 @@ test "readdir lists the root and a pane directory without creating anything" { } const panes_dir = rdir(p, @intFromEnum(TopFile.pane), 0); const listed = th.dirents(panes_dir.bytes, &buf); - try testing.expectEqual(@as(usize, 1), listed.len); - try testing.expectEqual(Node.of(serial, .dir), listed[0].node); + var idname: [16]u8 = undefined; + const own = th.nameAt(listed, try std.fmt.bufPrint(&idname, "{d}", .{serial})).?; + try testing.expectEqual(Node.of(serial, .dir), own.node); + try testing.expect(own.dir); const dir = rdir(p, Node.of(serial, .dir), 0); const files = th.dirents(dir.bytes, &buf); - try testing.expectEqual(@as(usize, 10), files.len); - for ([_][]const u8{ "name", "body", "tag", "ctl", "addr", "data", "xdata", "sel", "errors", "event" }, 0..) |name, i| + try testing.expectEqual(@as(usize, 17), files.len); + for ([_][]const u8{ + "name", "body", "tag", "ctl", "addr", "dot", "limit", "data", "xdata", + "sel", "dirty", "mark", "scroll", "errors", "event", "look", "exec", + }, 0..) |name, i| try testing.expectEqualStrings(name, files[i].name); try testing.expect(th.nameAt(files, ".") == null); try testing.expect(th.nameAt(files, "rdsel") == null); @@ -703,8 +749,10 @@ test "lookup resolves top files, pane serials and pane files" { const serial = serialOf(p); try testing.expectEqual(@as(u64, @intFromEnum(TopFile.index)), look_up(p, root, "index").reply.attr.node); - try testing.expect(!look_up(p, root, "new").reply.attr.dir); - try testing.expectEqual(@as(u16, 0o444), look_up(p, root, "new").reply.attr.mode); + try testing.expect(!look_up(p, root, "status").reply.attr.dir); + try testing.expectEqual(@as(u16, 0o444), look_up(p, root, "status").reply.attr.mode); + try testing.expectEqual(@as(u16, 0o666), look_up(p, root, "look").reply.attr.mode); + try testing.expectEqual(E.NOENT, look_up(p, root, "new").errno()); try testing.expect(look_up(p, root, "pane").reply.attr.dir); try testing.expect(look_up(p, root, "os").reply.attr.dir); try testing.expectEqual(E.NOENT, look_up(p, root, "nosuchthing").errno()); @@ -732,38 +780,46 @@ test "lookup resolves top files, pane serials and pane files" { try testing.expectEqual(E.NOTDIR, look_up(p, Node.of(serial, .body), "x").errno()); } -test "each open of new creates exactly one pane whose serial the read answers" { +test "creating in the pane directory opens a pane and removing one closes it" { const gpa = testing.allocator; const p = try withFile(gpa, "first\n"); defer p.deinit(); const before = p.next_serial; - const new = @intFromEnum(TopFile.new); + const panes_dir = @intFromEnum(TopFile.pane); - try testing.expectEqual(Status.ok, look_up(p, root, "new").reply.status); - try testing.expectEqual(Status.ok, call(p, .{ .tag = 1, .op = .getattr, .node = new }).reply.status); + // Browsing /pane creates nothing; only a create does. + try testing.expectEqual(Status.ok, rdir(p, panes_dir, 0).reply.status); try testing.expectEqual(before, p.next_serial); - const opened = call(p, .{ .tag = 1, .op = .open, .node = new }); - try testing.expectEqual(Status.ok, opened.reply.status); + const made = th.mkdir(p, "scratch"); + try testing.expectEqual(Status.ok, made.reply.status); try testing.expectEqual(before + 1, p.next_serial); - try testing.expectEqual(before + 1, opened.reply.handle); - try testing.expectEqual(@as(u64, 0), opened.reply.attr.node); + const serial = before + 1; + try testing.expectEqual(Node.of(serial, .dir), made.reply.attr.node); + try testing.expect(made.reply.attr.dir); var expected: [16]u8 = undefined; - const line = try std.fmt.bufPrint(&expected, "{d}\n", .{opened.reply.handle}); - try testing.expectEqualStrings(line, call(p, .{ .tag = 2, .op = .read, .node = new, .handle = opened.reply.handle, .size = 64 }).bytes); - try testing.expectEqualStrings(line[1..], call(p, .{ .tag = 2, .op = .read, .node = new, .handle = opened.reply.handle, .off = 1, .size = 64 }).bytes); - try testing.expectEqualStrings("", call(p, .{ .tag = 2, .op = .read, .node = new, .handle = opened.reply.handle, .off = line.len, .size = 64 }).bytes); - try testing.expectEqual(before + 1, p.next_serial); - _ = call(p, .{ .tag = 3, .op = .release, .node = new, .handle = opened.reply.handle }); + try testing.expectEqualStrings(try std.fmt.bufPrint(&expected, "{d}", .{serial}), made.reply.attr.name); - const id = p.paneBySerial(opened.reply.handle).?; + const id = p.paneBySerial(serial).?; try testing.expectEqualStrings("", p.panes[id].?.file.?.content); - _ = wr(p, Node.of(opened.reply.handle, .body), "hi"); - const second = call(p, .{ .tag = 4, .op = .open, .node = new }); + _ = wr(p, Node.of(serial, .body), "hi"); + const second = th.mkdir(p, "another"); try testing.expectEqual(Status.ok, second.reply.status); - try testing.expect(second.reply.handle != opened.reply.handle); + try testing.expect(second.reply.attr.node != made.reply.attr.node); try testing.expectEqualStrings("hi", p.panes[id].?.file.?.content); - try testing.expectEqual(E.INVAL, call(p, .{ .tag = 5, .op = .read, .node = new, .size = 64 }).errno()); + + // A plain file, and a create anywhere else, are refused. + try testing.expectEqual(E.PERM, call(p, .{ .tag = 1, .op = .open, .node = panes_dir, .data = "f", .create = true, .perm = 0o666 }).errno()); + try testing.expectEqual(E.PERM, call(p, .{ .tag = 1, .op = .open, .node = root, .data = "d", .create = true, .perm = cloud9.dmdir | 0o755 }).errno()); + try testing.expectEqual(E.PERM, call(p, .{ .tag = 1, .op = .open, .node = Node.of(serial, .dir), .data = "d", .create = true, .perm = cloud9.dmdir | 0o755 }).errno()); + + // Tremove closes the pane it names, and nothing else in the tree. + try testing.expectEqual(E.PERM, th.rmdir(p, Node.of(serial, .body)).errno()); + try testing.expectEqual(E.PERM, th.rmdir(p, @intFromEnum(TopFile.index)).errno()); + try testing.expect(p.paneBySerial(serial) != null); + try testing.expectEqual(Status.ok, th.rmdir(p, Node.of(serial, .dir)).reply.status); + try testing.expect(p.paneBySerial(serial) == null); + try testing.expectEqual(E.NOENT, th.rmdir(p, Node.of(serial, .dir)).errno()); } test "directories walk to their parents" { @@ -791,14 +847,15 @@ test "editor paths resolve to the same nodes the wire serves" { try testing.expectEqual(root, resolveSelf(p, "").?); try testing.expectEqual(root, resolveSelf(p, "/./pane/../").?); try testing.expectEqual(@intFromEnum(TopFile.index), resolveSelf(p, "index").?); - try testing.expectEqual(@intFromEnum(TopFile.new), resolveSelf(p, "new").?); + try testing.expectEqual(@intFromEnum(TopFile.status), resolveSelf(p, "status").?); + try testing.expect(resolveSelf(p, "new") == null); try testing.expectEqual(@intFromEnum(TopFile.pane), resolveSelf(p, "pane").?); try testing.expectEqual(Node.of(serial, .dir), resolveSelf(p, try std.fmt.bufPrint(&path, "pane/{d}", .{serial})).?); try testing.expectEqual(Node.of(serial, .sel), resolveSelf(p, try std.fmt.bufPrint(&path, "pane/{d}/sel", .{serial})).?); try testing.expect(resolveSelf(p, try std.fmt.bufPrint(&path, "pane/{d}/pty/ctl", .{serial})) == null); try testing.expect(resolveSelf(p, try std.fmt.bufPrint(&path, "pane/{d}/rdsel", .{serial})) == null); try testing.expect(resolveSelf(p, "self/index") == null); - try testing.expect(resolveSelf(p, "new/ctl") == null); + try testing.expect(resolveSelf(p, "status/ctl") == null); try testing.expect(resolveSelf(p, "cons") == null); try testing.expect(resolveSelf(p, "pane/0") == null); } diff --git a/src/panes.zig b/src/panes.zig index edd7038f..9a6802d0 100644 --- a/src/panes.zig +++ b/src/panes.zig @@ -6273,6 +6273,13 @@ pub const Terminal = struct { state.vt.screens.active.scroll(.{ .delta_row = delta }); } + /// Is the viewport already showing the last row of output? + pub fn atBottom(pane: *const Pane) bool { + if (comptime !enabled) return true; + const sb = scrollbar(pane); + return sb.offset + sb.len >= sb.total; + } + /// Snap the viewport back onto live output. pub fn followOutput(pane: *Pane) void { if (comptime !enabled) return; @@ -6559,10 +6566,14 @@ pub const Terminal = struct { const has_positions = pane.ovl != null or pane.cur_pinned or pane.vsel.active or pane.msel.active or pane.nsel > 0 or pane.append_at != null or pane.look_at != null or pane.ed_undo_len > 0 or pane.ed_redo_len > 0 or pointerRowCount(pane) > 0; + // Sticky bottom, as every other terminal does it: output drags the + // viewport down only when the viewport was already on the last row, so + // a reader scrolled back into the scrollback stays where they scrolled. + const at_bottom = atBottom(pane); if (has_positions) ingestWithPositions(pane, bytes) else ingest(pane, bytes); p.shell_rows.markStale(pane); const body_mode = if (pane.tag_edit) pane.tag_mode else pane.mode; - if (body_mode == .tty) followOutput(pane); + if (body_mode == .tty and at_bottom) followOutput(pane); } const RowPin = struct { pin: ?*ghostty_vt.Pin = null, offset: i32 = 0 }; @@ -6890,6 +6901,7 @@ pub const Terminal = struct { }; pane.mode = .tty; + followOutput(pane); // entering raw mode is a request for the live shell pane.msel.active = false; pane.vsel.active = false; pane.nsel = 0; diff --git a/src/pardes.zig b/src/pardes.zig index ed71102e..c66688f5 100644 --- a/src/pardes.zig +++ b/src/pardes.zig @@ -295,6 +295,12 @@ const pre_collapse_pdf_pane_tail = " Tty Del PdfSections PdfTint"; const pre_collapse_terminal_pane_tail = " Save Tty Del Togglettymode Filter"; const pre_tty_first_terminal_pane_tail = " Save Tty Del Togglettymode Filter Collapse"; const pre_mode_terminal_pane_tail = " Tty Save Del Togglettymode Filter Collapse"; +// ...and the defaults from before the closing word moved to the end of every +// tagline, where a click cannot land on it by overshooting the one before. +const pre_close_last_pane_tail = " Tty Collapse Del"; +const pre_close_last_file_pane_tail = " Save Tty Del Collapse"; +const pre_close_last_pdf_pane_tail = " Tty Del PdfSections PdfTint Collapse"; +const pre_close_last_terminal_pane_tail = " Tty Save Del Mode Filter Collapse"; const Builtin = builtins.registry.Builtin(); @@ -1078,7 +1084,7 @@ test "Collapse builtin keeps content and restores the pane from its default tag" const height = p.rects[0].h; const revision = pane.file.?.revision; for ([_][]const u8{ pane_tail, file_pane_tail, pdf_pane_tail, terminal_pane_tail }) |tail| - try std.testing.expect(std.mem.endsWith(u8, tail, " Collapse")); + try std.testing.expect(std.mem.endsWith(u8, tail, " Collapse Del")); try std.testing.expect(p.executeBuiltinLine(0, "Collapse")); p.sync(); @@ -1115,6 +1121,8 @@ test "LocationsConfig command reports partial updates and survives restore" { try std.testing.expectEqual(expected, p.locations_config); try std.testing.expect(p.executeBuiltinLine(0, "LocationsConfig context:2 unknown:on")); try std.testing.expectEqual(expected, p.locations_config); + // Setting it is silent; asking bare is what opens the window. + try std.testing.expect(p.executeBuiltinLine(0, "LocationsConfig")); var reports: usize = 0; for (p.panes) |slot| { const pane = slot orelse continue; @@ -1409,7 +1417,7 @@ test "legacy default tag tails upgrade while custom tails remain owned" { }); p.restoreTail(file, file_old); try std.testing.expect(!file.tag_init); - try std.testing.expectEqualStrings(" Save Tty Del Collapse", Pardes.curTail(file)); + try std.testing.expectEqualStrings(" Save Tty Collapse Del", Pardes.curTail(file)); const file_custom = try std.fmt.allocPrint(p.scratch.allocator(), "{s} Save Mine Del", .{ try p.tagPrefix(file), @@ -1430,7 +1438,7 @@ test "legacy default tag tails upgrade while custom tails remain owned" { try std.testing.expectEqualStrings(" New Del", Pardes.curTail(file)); const image_doc = try panes.Image.create(p, 1, "/tmp/legacy image.ppm", &.{}); - try std.testing.expectEqualStrings(" Tty Del Collapse", Pardes.curTail(image_doc)); + try std.testing.expectEqualStrings(" Tty Collapse Del", Pardes.curTail(image_doc)); p.restoreDumpTail(image_doc, .{ .kind = .image, .tag = "img /tmp/legacy image.ppm Keep Del", @@ -1576,7 +1584,7 @@ test "pane defaults keep creation of scratch panes in column tags" { var words = std.mem.tokenizeScalar(u8, tag, ' '); while (words.next()) |word| try std.testing.expect(!std.mem.eql(u8, word, "New")); } - try std.testing.expectEqualStrings("New Tty Find Grep Joincol", p.columnTag(0)); + try std.testing.expectEqualStrings("New Tty Find Grep Joincol Delcol", p.columnTag(0)); const terminal = p.panes[0].?; p.restoreTailAt(terminal, pre_column_terminal_pane_tail, "", .terminal); try std.testing.expect(!terminal.tag_init); @@ -2441,13 +2449,13 @@ test "Save reaches every tagline with text behind it and no other" { }); p.restoreTail(out, scratch_dumped); try std.testing.expect(!out.tag_init); - try std.testing.expectEqualStrings(" Save Tty Del Collapse", Pardes.curTail(out)); + try std.testing.expectEqualStrings(" Save Tty Collapse Del", Pardes.curTail(out)); // An image's bytes on disk already are what they are: nothing of the // pane's own is unwritten, so the word is absent and inert. const img_id = p.freeSlot().?; const img = try panes.Image.create(p, img_id, "/tmp/pardes-tag.ppm", &.{}); - try std.testing.expectEqualStrings(" Tty Del Collapse", Pardes.curTail(img)); + try std.testing.expectEqualStrings(" Tty Collapse Del", Pardes.curTail(img)); try std.testing.expect(p.executeBuiltinLine(img_id, "Save")); try std.testing.expect(img.prompt != .save); var buf: [256]u8 = undefined; @@ -5818,8 +5826,42 @@ test "repeated non-dyadic column splits preserve every unrelated boundary" { pub const Rect = layout.Rect; +/// The session layouts `init` can put on screen. One name each, so choosing +/// between them reads as a choice instead of a chain of ifs over four options. +pub const Boot = enum { + /// the document named on the command line, or the pane explaining why not + document, + /// a Look that found nothing: reported, not opened + missing, + /// the firmware's boot buffer, the only pane a board has + embedded, + /// the bare tty startup: one shell in raw tty mode, with an empty text + /// pane under it so the editor half is there before you want it + tty, + /// that raw shell by itself, which is all a core booted for a test wants + tty_shell, + /// acme's boot: two columns, the left one split in two + classic, + /// one greeted shell + shell, + + pub fn of(opts: Options) Boot { + if (opts.boot) |named| return named; + if (opts.file != null) return .document; + if (opts.missing != null) return .missing; + if (comptime platform == .esp32p4) return .embedded; + if (opts.tty_only) return .tty_shell; + // ponytail: 1 and 3 are the only shell counts anyone asked for + return if (opts.shells >= 3) .classic else .shell; + } +}; + pub const Options = struct { tty_only: bool = false, + /// The layout to boot, when a host means one outright rather than leaving + /// it to be read off the options below. `--tty` names `.tty`; a core + /// booted for a test names nothing and gets `.tty_shell`. + boot: ?Boot = null, /// initial shell panes: 1 (default) or 3 for the classic two-column boot. /// A `file` outranks this — see there. shells: u8 = 1, @@ -6035,6 +6077,11 @@ pub const Pardes = struct { pipe_wait: ?PendingPipe = null, fs: filesystem.Namespace = .{}, + boot: Boot = .shell, + /// Builtins announce themselves on the message row. Off while startup + /// configuration is applied: those lines are nobody clicking, and should + /// not leave the row holding the name of the last one. + announce: bool = true, // Reject overflow: evicting an older effect would reorder a byte stream. effects: [limits.effect_cap]Effect = undefined, @@ -6114,7 +6161,10 @@ pub const Pardes = struct { for (opts.mounts) |mount| try p.fs.mount(gpa, mount.name, mount.dial); p.opts.mounts = &.{}; p.opts.ninep_identity = .{}; - if (opts.file) |path| { + p.boot = Boot.of(opts); + switch (p.boot) { + .document => { + const path = opts.file.?; const opened = initial_doc: { if (comptime pdf_enabled) if (look.isPdfPath(path)) break :initial_doc panes.Pdf.openPane(p, 0, path, opts.file_line); @@ -6137,10 +6187,10 @@ pub const Pardes = struct { errdefer gpa.free(content); _ = try panes.Output.open(p, 0, std.fs.path.dirname(path) orelse "/", .errors, "", content); } - p.ncol = 1; - p.col_n[0] = 1; - p.col_panes[0][0] = 0; - } else if (opts.missing) |missing| { + p.oneColumn(); + }, + .missing => { + const missing = opts.missing.?; const content = try std.fmt.allocPrint( gpa, "file or directory not found\n\n\t{s}\n", @@ -6148,24 +6198,26 @@ pub const Pardes = struct { ); errdefer gpa.free(content); _ = try panes.Output.open(p, 0, missing.dir, .errors, "", content); - p.ncol = 1; - p.col_n[0] = 1; - p.col_panes[0][0] = 0; - } else if (comptime platform == .esp32p4) { + p.oneColumn(); + }, + .embedded => { const content = try p.gpa.dupe(u8, boot_buffer); errdefer p.gpa.free(content); _ = try panes.Output.open(p, 0, "", .{ .cmd = .New }, "", content); - p.ncol = 1; - p.col_n[0] = 1; - p.col_panes[0][0] = 0; - } else if (opts.tty_only) { + p.oneColumn(); + }, + .tty, .tty_shell => { _ = try p.newShell(0, ""); p.panes[0].?.mode = .tty; - p.ncol = 1; - p.col_n[0] = 1; - p.col_panes[0][0] = 0; - } else if (opts.shells >= 3) { - // classic layout: two columns, the left one split in two. + p.oneColumn(); + // A bare tty is still an editor: it opens with somewhere to put + // text under the shell. The shell keeps the keyboard. + if (p.boot == .tty) { + p.newScratchBelow(0); + p.active = 0; + } + }, + .classic => { _ = try p.newShell(0, ""); _ = try p.newShell(1, ""); _ = try p.newShell(2, ""); @@ -6176,13 +6228,12 @@ pub const Pardes = struct { p.col_panes[0][1] = 1; p.col_n[1] = 1; p.col_panes[1][0] = 2; - } else { - // ponytail: 1 and 3 are the only boot layouts; anything else acts as 1 + }, + .shell => { _ = try p.newShell(0, ""); p.panes[0].?.greet = true; - p.ncol = 1; - p.col_n[0] = 1; - p.col_panes[0][0] = 0; + p.oneColumn(); + }, } p.sync(); p.applyStartupConfig(); @@ -6195,6 +6246,13 @@ pub const Pardes = struct { return p; } + /// The layout every single-pane boot starts from. + fn oneColumn(p: *Pardes) void { + p.ncol = 1; + p.col_n[0] = 1; + p.col_panes[0][0] = 0; + } + pub fn deinit(p: *Pardes) void { p.cancelLookHover(); for (0..MAX_PANES) |id| p.dropPendingWrite(id); @@ -6268,7 +6326,7 @@ pub const Pardes = struct { } pub fn columnTag(p: *const Pardes, c: usize) []const u8 { - return p.col_tags[c].slice("New Tty Find Grep Joincol"); + return p.col_tags[c].slice("New Tty Find Grep Joincol Delcol"); } fn headerText(p: *Pardes) []const u8 { @@ -6413,6 +6471,17 @@ pub const Pardes = struct { return np; } + /// The empty pane that stands in for one that closed, keeping its column + /// alive and its directory. Unlike `newScratch` it inherits nothing: the + /// pane it replaces is on its way out. + fn newScratchIn(p: *Pardes, free: usize, dir: []const u8) !*Pane { + const content = try p.gpa.dupe(u8, ""); + errdefer p.gpa.free(content); + const np = try panes.Output.open(p, free, dir, .{ .cmd = .New }, "", content); + np.cur_pinned = true; + return np; + } + /// New: a scratch below the calling pane, in its column. pub fn newScratchBelow(p: *Pardes, from_id: usize) void { const free = p.freeSlot() orelse return; @@ -8237,8 +8306,23 @@ pub const Pardes = struct { p.ctrl_w_pending = false; if (key.ctrl and !key.alt and key.cp == p.opts.tty_toggle) return p.toggleTty(p.active); + // Shift-Escape is the unconditional way out, even mid-application; + // bare Escape only leaves at a shell prompt. + if (hit(key, config.tty_toggle_alt)) + return p.runBuiltin(.Last, p.active, "", null); if (key.cp == Key.escape and !key.ctrl and !key.alt and !key.shift and p.takesCommandLine(p.active)) return p.runBuiltin(.Last, p.active, "", null); + panes.Terminal.followOutput(pane); // typing snaps back to live output + // Paste stays the window's, the one exception to forwarding a raw + // tty's keys: Ctrl-V types the register at the program and + // Ctrl-Shift-V asks the desktop for its clipboard first. Forwarded, + // they reach an application that reads the clipboard on its own + // account instead — a coding agent goes there hunting for an image. + // A host that folds Shift into the letter says the same thing. + if (key.ctrl and !key.alt and (key.cp == 'v' or key.cp == 'V')) { + if (key.shift or key.cp == 'V') return p.clipRequest(p.active, .after); + return p.typeToTty(p.active, pane, p.yank orelse return); + } return panes.Terminal.forwardKey(p, p.active, key); } if (p.leader_on) return p.leaderKey(key); @@ -12499,6 +12583,8 @@ pub const Pardes = struct { } fn applyStartupConfig(p: *Pardes) void { + p.announce = false; + defer p.announce = true; var lines = std.mem.splitScalar(u8, p.opts.startup_config orelse return, '\n'); while (lines.next()) |line| _ = p.executeBuiltinLine(p.active, line); } @@ -12506,6 +12592,11 @@ pub const Pardes = struct { fn runBuiltin(p: *Pardes, b: Builtin, id: usize, txt: []const u8, arg: ?[]const u8) void { if (!p.multiOnce()) return; // a builtin is per-keystroke, never per-cursor const pane = p.panes[id] orelse return; + // A builtin says its own name before it runs, so a tagline click is + // legible even when what it did is invisible. Whatever the builtin + // then says for itself replaces the announcement. + if (p.announce and p.settings.verbose and builtins.registry.announces(b)) + p.setMessage(id, @tagName(b)); const c: builtins.Ctx = .{ .p = p, .pane = pane, .id = id, .txt = txt, .arg = arg }; builtins.registry.dispatch(b, c); } @@ -12887,11 +12978,13 @@ pub const Pardes = struct { const rest = saved_tag[pfx.len..]; const said = std.mem.trimStart(u8, rest, " "); const defaults: []const []const u8 = switch (class) { - .generic => &.{ pdf_pane_tail, pane_tail, pre_collapse_pdf_pane_tail, pre_collapse_pane_tail, pre_column_pdf_pane_tail, pre_column_pane_tail, prev_pane_tail, legacy_pane_tail }, - .file => &.{ context_pane_tail, file_pane_tail, pre_collapse_file_pane_tail, pre_column_file_pane_tail, prev_file_pane_tail, legacy_file_pane_tail }, + .generic => &.{ pdf_pane_tail, pane_tail, pre_close_last_pdf_pane_tail, pre_close_last_pane_tail, pre_collapse_pdf_pane_tail, pre_collapse_pane_tail, pre_column_pdf_pane_tail, pre_column_pane_tail, prev_pane_tail, legacy_pane_tail }, + .file => &.{ context_pane_tail, file_pane_tail, pre_close_last_file_pane_tail, pre_collapse_file_pane_tail, pre_column_file_pane_tail, prev_file_pane_tail, legacy_file_pane_tail }, .output => &.{ locations_pane_tail, file_pane_tail, + pre_close_last_file_pane_tail, + pre_close_last_pane_tail, prev_file_pane_tail, legacy_file_pane_tail, pane_tail, @@ -12902,7 +12995,7 @@ pub const Pardes = struct { pre_collapse_file_pane_tail, pre_collapse_pane_tail, }, - .terminal => &.{ terminal_pane_tail, pre_mode_terminal_pane_tail, pre_tty_first_terminal_pane_tail, pre_collapse_terminal_pane_tail, pre_column_terminal_pane_tail, pre_tty_terminal_pane_tail, prev_terminal_pane_tail, legacy_terminal_pane_tail, pane_tail, pre_collapse_pane_tail, pre_column_pane_tail, prev_pane_tail, legacy_pane_tail }, + .terminal => &.{ terminal_pane_tail, pre_close_last_terminal_pane_tail, pre_close_last_pane_tail, pre_mode_terminal_pane_tail, pre_tty_first_terminal_pane_tail, pre_collapse_terminal_pane_tail, pre_column_terminal_pane_tail, pre_tty_terminal_pane_tail, prev_terminal_pane_tail, legacy_terminal_pane_tail, pane_tail, pre_collapse_pane_tail, pre_column_pane_tail, prev_pane_tail, legacy_pane_tail }, }; for (defaults) |default| if (std.mem.eql(u8, said, std.mem.trimStart(u8, default, " "))) return; @@ -12912,11 +13005,34 @@ pub const Pardes = struct { pub fn removePane(p: *Pardes, id: usize) !void { const pane = p.panes[id] orelse return; + // A column outlives its panes. Closing the last one leaves an empty + // pane standing in its place and in its directory; only Delcol ever + // takes a column away. + const place = layout.findPane(p, id); + const last_in_column = if (place) |f| p.col_n[f.col] == 1 else false; + var dir_buf: [limits.host_path_cap]u8 = undefined; + var dir: []const u8 = ""; + if (last_in_column) { + const had = paneDir(pane); + const n = @min(had.len, dir_buf.len); + @memcpy(dir_buf[0..n], had[0..n]); + dir = dir_buf[0..n]; + } + // Before anything is torn down, so a failure here changes nothing. try p.deinitPane(pane); + // ...and after it, so the stand-in inherits none of the closing pane. + const heir: ?usize = heir: { + if (!last_in_column) break :heir null; + const f = place.?; + const free = p.freeSlot() orelse break :heir null; + _ = p.newScratchIn(free, dir) catch break :heir null; + layout.insert(p, f.col, f.idx + 1, free); + break :heir free; + }; layout.absorbVWeight(p, id); layout.removePane(p, id); p.panes[id] = null; - if (p.active == id) p.active = p.prevFocus(id) orelse { + if (p.active == id) p.active = heir orelse p.prevFocus(id) orelse { p.quit = true; p.emit(.quit); return; @@ -14408,6 +14524,75 @@ test "Esc back into a tty leaves its view at the prompt" { try std.testing.expectEqual(live, sp.terminal.?.vt.screens.active.pages.scrollbar().offset); } +test "the bare tty startup opens a text pane under the shell, unfocused" { + if (platform == .web) return; + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .boot = .tty }); + defer p.deinit(); + try std.testing.expectEqual(Boot.tty, p.boot); + + // One column, shell on top in raw mode, an empty text pane under it. + try std.testing.expectEqual(@as(usize, 1), p.ncol); + try std.testing.expectEqual(@as(usize, 2), p.col_n[0]); + const shell = p.panes[p.col_panes[0][0]].?; + const scratch = p.panes[p.col_panes[0][1]].?; + try std.testing.expect(shell.isTerminal()); + try std.testing.expectEqual(Pane.Mode.tty, shell.mode); + try std.testing.expect(!scratch.isTerminal()); + try std.testing.expectEqualStrings("", scratch.file.?.content); + + // ...and the shell keeps the keyboard. + try std.testing.expectEqual(p.col_panes[0][0], p.active); + + // Unnamed, it is the bare shell every test asks for. + const plain = try Pardes.init(std.testing.allocator, .{ .tty_only = true }); + defer plain.deinit(); + try std.testing.expectEqual(Boot.tty_shell, plain.boot); + try std.testing.expectEqual(@as(usize, 1), plain.col_n[0]); +} + +test "tty output follows only from the bottom" { + if (platform == .web) return; + const p = try Pardes.init(std.testing.allocator, .{ .cols = 80, .rows = 24, .file = "mise.toml" }); + defer p.deinit(); + p.update(.{ .resize = .{ .cols = 80, .rows = 24 } }); + p.update(.{ .key = .{ .cp = 'n', .alt = true } }); // a shell under the doc + const shell = p.active; + const sp = p.panes[shell].?; + p.update(.{ .key = .{ .cp = Key.escape, .shift = true } }); + try std.testing.expectEqual(Pane.Mode.tty, sp.mode); + + for (0..60) |i| { + var buf: [32]u8 = undefined; + p.update(.{ .output = .{ .pane = @intCast(shell), .bytes = std.fmt.bufPrint(&buf, "line {d}\r\n", .{i}) catch unreachable } }); + } + p.sync(); + const bottom = panes.Terminal.scrollbar(sp).offset; + try std.testing.expect(bottom > 0); + + // Scrolled back, the reader stays put however much the shell prints. + sp.scrollBy(-10); + p.sync(); + const parked = panes.Terminal.scrollbar(sp).offset; + try std.testing.expect(parked < bottom); + for (60..70) |i| { + var buf: [32]u8 = undefined; + p.update(.{ .output = .{ .pane = @intCast(shell), .bytes = std.fmt.bufPrint(&buf, "line {d}\r\n", .{i}) catch unreachable } }); + } + p.sync(); + try std.testing.expectEqual(parked, panes.Terminal.scrollbar(sp).offset); + + // Typing snaps back to live output, so nobody types blind. + p.update(.{ .key = .{ .cp = 'x', .text = "x" } }); + p.sync(); + try std.testing.expect(panes.Terminal.scrollbar(sp).offset > parked); + + // ...and from there output follows again. + const live = panes.Terminal.scrollbar(sp).offset; + p.update(.{ .output = .{ .pane = @intCast(shell), .bytes = "tail\r\n" } }); + p.sync(); + try std.testing.expect(panes.Terminal.scrollbar(sp).offset > live); +} + test "Esc back into a file leaves its view where it was" { if (platform == .web) return; const gpa = std.testing.allocator; @@ -14461,15 +14646,23 @@ test "raw tty Escape only leaves at a shell prompt" { const pane = p.panes[shell].?; var buf: [256]u8 = undefined; _ = drainWrites(p, &buf); - for ([_]Key{ - .{ .cp = Key.escape, .shift = true }, - }) |key| { - p.update(.{ .key = key }); - try std.testing.expectEqual(shell, p.active); - try std.testing.expectEqual(Pane.Mode.tty, pane.mode); - try std.testing.expect(drainWrites(p, &buf).len > 0); - } - p.update(.{ .key = .{ .cp = Key.escape } }); + + // Ordinary keys reach the child; Shift-Escape is the one unconditional way + // out and sends it nothing. + p.update(.{ .key = .{ .cp = 'x', .text = "x" } }); + try std.testing.expectEqual(shell, p.active); + try std.testing.expect(drainWrites(p, &buf).len > 0); + + p.update(.{ .key = .{ .cp = Key.escape, .shift = true } }); + try std.testing.expectEqual(@as(usize, 0), p.active); + try std.testing.expectEqualStrings("", drainWrites(p, &buf)); + try std.testing.expectEqual(Pane.Mode.tty, pane.mode); + + p.update(.{ .key = .{ .cp = Key.escape } }); // back into the shell + try std.testing.expectEqual(shell, p.active); + _ = drainWrites(p, &buf); + + p.update(.{ .key = .{ .cp = Key.escape } }); // bare Escape leaves at a prompt try std.testing.expectEqual(@as(usize, 0), p.active); try std.testing.expectEqualStrings("", drainWrites(p, &buf)); try std.testing.expectEqual(Pane.Mode.tty, pane.mode); @@ -14620,9 +14813,10 @@ test "raw tty forwards Ctrl letters and former global shortcuts to the child" { defer p.deinit(); var buf: [256]u8 = undefined; _ = drainWrites(p, &buf); - p.setYank("must not be pasted"); + p.setYank("register text"); for ('a'..'z' + 1) |letter| { if (letter == p.opts.tty_toggle) continue; // editor/TTY mode shortcut + if (letter == 'v') continue; // the window's paste, asserted just below p.update(.{ .key = .{ .cp = @intCast(letter), .ctrl = true } }); const expected = [_]u8{@intCast(letter - 'a' + 1)}; // The terminal encoder distinguishes Ctrl-I/M from Tab/Return. @@ -14636,15 +14830,21 @@ test "raw tty forwards Ctrl letters and former global shortcuts to the child" { try std.testing.expectEqual(Pane.Mode.tty, p.panes[0].?.mode); try std.testing.expect(!p.ctrl_w_pending and p.clip_pending == null); } - p.update(.{ .key = .{ .cp = 'v', .ctrl = true, .shift = true } }); - try std.testing.expectEqualStrings("\x1b[118;6u", drainWrites(p, &buf)); + // ...and the two paste chords are the exception: Ctrl-V types the register + // at the program, Ctrl-Shift-V asks the desktop first and types nothing yet. + p.update(.{ .key = .{ .cp = 'v', .ctrl = true } }); + try std.testing.expectEqualStrings("register text", drainWrites(p, &buf)); try std.testing.expect(p.clip_pending == null); + p.update(.{ .key = .{ .cp = 'v', .ctrl = true, .shift = true } }); + try std.testing.expectEqualStrings("", drainWrites(p, &buf)); + try std.testing.expect(p.clip_pending != null); + const unopened = p.freeSlot(); // whatever the boot layout already used for ([_]u8{ 'n', 'c' }) |letter| { p.update(.{ .key = .{ .cp = letter, .alt = true } }); const expected = [_]u8{ 0x1b, letter }; try std.testing.expectEqualStrings(&expected, drainWrites(p, &buf)); try std.testing.expectEqual(@as(usize, 0), p.active); - try std.testing.expect(p.panes[1] == null); + try std.testing.expectEqual(unopened, p.freeSlot()); } p.update(.{ .key = .{ .cp = Key.up } }); try std.testing.expectEqualStrings("\x1b[A", drainWrites(p, &buf)); diff --git a/src/tty/tty.zig b/src/tty/tty.zig index 23b7c09b..a1917ba9 100644 --- a/src/tty/tty.zig +++ b/src/tty/tty.zig @@ -71,6 +71,21 @@ fn inputReader(loop: *Loop, tty: anytype, cache: *vaxis.GraphemeCache) void { loop.postEvent(.quit) catch {}; } +/// How long a lone ESC waits for the rest of a sequence before it counts as +/// the Escape key. Long enough for the remainder of a real sequence to arrive +/// even over a slow link, short enough that nobody sees the delay. +const escape_hold_ms = 25; + +/// Is there more input right behind what we have already read? Only a real +/// terminal has an fd to ask; the test readers hand their parts over whole, so +/// for them the answer is always no. +fn morePending(tty: anytype) bool { + const Reader = @typeInfo(@TypeOf(tty)).pointer.child; + if (!@hasField(Reader, "fd") or @FieldType(Reader, "fd") != std.Io.File) return false; + var fds = [_]std.posix.pollfd{.{ .fd = tty.fd.handle, .events = std.posix.POLL.IN, .revents = 0 }}; + return (std.posix.poll(&fds, escape_hold_ms) catch return false) > 0; +} + fn readInput(loop: *Loop, tty: anytype, cache: *vaxis.GraphemeCache) !void { try loop.postEvent(.{ .winsize = try tty.getWinsize() }); var parser: vaxis.Parser = .{}; @@ -101,6 +116,22 @@ fn readInput(loop: *Loop, tty: anytype, cache: *vaxis.GraphemeCache) !void { } carried = end - consumed; std.mem.copyForwards(u8, buf[0..carried], buf[consumed..end]); + // A lone ESC opens most sequences and is also the Escape key, so the + // parser holds it for a remainder that a keypress never sends: the + // press would only land when the NEXT key arrived. Wait a beat, and + // when nothing follows it was the key. A terminal speaking the kitty + // protocol never reaches here — it spells Escape out in full. + if (carried == 1 and buf[0] == 0x1b and !morePending(tty)) { + carried = 0; + try vaxis.loop.handleEventGeneric( + loop, + loop.vaxis, + cache, + @TypeOf(Command.value), + @as(vaxis.Event, .{ .key_press = .{ .codepoint = vaxis.Key.escape } }), + loop.vaxis.opts.system_clipboard_allocator, + ); + } } } diff --git a/src/tutor.txt b/src/tutor.txt index 394a48a3..adf4ae3a 100644 --- a/src/tutor.txt +++ b/src/tutor.txt @@ -160,8 +160,10 @@ RAW INPUT Ctrl-b switches to editor mode. Other keys go to the child, - including Ctrl-o, Ctrl-w, Ctrl-V, Ctrl-Shift-V, Alt shortcuts, and - modified Escape. Plain Esc at a detected shell prompt hops + including Ctrl-o, Ctrl-w, Alt shortcuts, and + modified Escape. The two paste chords are the exception: Ctrl-V + types the yank register at the program and Ctrl-Shift-V types the + desktop clipboard. Plain Esc at a detected shell prompt hops to the previous pane. While a program owns the terminal, Esc goes to that program too. Use the Togglettymode tag to leave raw input in place. Desktop paste events still feed the child. @@ -387,15 +389,15 @@ typed pardes the 9P socket opens by default - A directory per pane holding `name`, `body`, `tag`, `ctl`, `addr`, - `data`, `sel`, `event`, `pty/` and the rest, plus `index`, `ctl`, - `new` and `log` at the root. Every pane shell receives `$PARDES_9P` - (the socket) and `$PARDES_PANE` (its serial). Use a 9P client: + A directory per pane holding `name`, `body`, `tag`, `addr`, `dot`, + `data`, `sel`, `dirty`, `event`, `pty/` and the rest, plus `index`, + `status`, `look`, `exec` and `log` at the root. Every pane shell + receives `$PARDES_9P` (the socket) and `$PARDES_PANE` (its serial): /pane//body /index - /new reading it makes a pane, answers its serial - /ctl `look FILE:12` and `exec Save`, as the mouse does + /pane mkdir here makes a pane, rmdir closes it + /look /exec `FILE:12` and `Save`, as the mouse does A terminal pane also has `pty/`: @@ -446,7 +448,8 @@ typed Esc goes to the program — except at a shell PROMPT, where it hops to the previous pane Ctrl-b switches to editor mode - All other keys belong to the child, including Ctrl-V + Ctrl-V types the register, Ctrl-Shift-V the clipboard + All other keys belong to the child DETACHED pardes --detach[=name] the core, no terminal pardes --attach[=name] a frontend for it diff --git a/test/appearance_gallery.py b/test/appearance_gallery.py index 0fa12136..48c0ea1b 100644 --- a/test/appearance_gallery.py +++ b/test/appearance_gallery.py @@ -82,7 +82,7 @@ def run(args): right = require(wait_for(lambda: next((s for s in panes(client) if s not in before), None)), 'right column missing') client.write(f'/pane/{right}/name', f'{root / "Review"}\n'.encode()) client.write(f'/pane/{right}/body', PREFERENCE_NOTES if args.theme_selector else NOTES, truncate=True) - client.write(f'/pane/{right}/ctl', b'clean\n') + client.write(f'/pane/{right}/dirty', b'0\n') before = set(panes(client)) command(client, right, 'Tty') terminal = require(wait_for(lambda: next((s for s in panes(client) if s not in before), None)), 'terminal missing') @@ -94,12 +94,12 @@ def run(args): command(client, right, 'Config') pane = require(wait_for(lambda: next((s for s in panes(client) if s not in before), None)), 'Config output missing') text = client.read(f'/pane/{pane}/body').decode() - client.write(f'/pane/{pane}/ctl', b'exec Del\n') + client.write(f'/pane/{pane}/exec', b'Del\n') return text settings = config_report() - require('Font effective size: 18.00 pixels' in settings, 'configured font size not applied: ' + settings) - require('TaglineSize: 80' in settings, 'configured tag size missing') + require('Font effective size 18.00 pixels' in settings, 'configured font size not applied: ' + settings) + require('TaglineSize 80' in settings, 'configured tag size missing') (root / 'effective-config.txt').write_text(settings) report['font_effective_pixels'] = 18 report['tagline_percent'] = 80 @@ -135,7 +135,7 @@ def run(args): command(client, right, 'Theme ' + theme) if args.theme_selector: # Keep both quiet active gutter ink and vivid comments in view. - client.write(f'/pane/{source}/ctl', f'look {source_path}:117\n'.encode()) + client.write(f'/pane/{source}/look', f'{source_path}:117\n'.encode()) take_frame('classic-' + theme) if args.theme_selector: frame = client.screen() @@ -171,14 +171,14 @@ def run(args): 'ThemeSel did not open at native first entry') take_frame('theme-selector') report['native_themes_first'] = True - client.write(f'/pane/{selector}/ctl', b'exec Del\n') + client.write(f'/pane/{selector}/exec', b'Del\n') command(client, terminal, 'Collapse') for pet in (() if args.skip_pets else ('cat', 'frog', 'off')): command(client, right, 'Pet ' + pet) settings = config_report() require('Pet: ' + pet + '\n' in settings, 'pet setting not applied') # Returning focus to the source closes all transient report state. - client.write(f'/pane/{source}/ctl', f'look {source_path}:1\n'.encode()) + client.write(f'/pane/{source}/look', f'{source_path}:1\n'.encode()) take_frame('pet-' + pet) if pet != 'off': frame = client.screen() diff --git a/test/column_tags.py b/test/column_tags.py index 80b623bd..fe3a8699 100644 --- a/test/column_tags.py +++ b/test/column_tags.py @@ -143,7 +143,7 @@ def run(args): client.write(f'/pane/{right}/name', f'{right_name}\n'.encode()) right_body = b'// Column-local scratch\nfn main() {\n let ready = true;\n}\n' client.write(f'/pane/{right}/body', right_body) - client.write(f'/pane/{right}/ctl', b'clean\n') + client.write(f'/pane/{right}/dirty', b'0\n') require(wait_for(lambda: locate(client, 'New Tty', row=1, minimum_col=75)), 'right column tag missing') require(locate(client, 'New Tty', row=1, minimum_col=75) == (75, 1), 'right column tag retains an inset') @@ -173,7 +173,7 @@ def run(args): extra = require(wait_for(lambda: new_serial(client, before)), 'right-column New did not create a pane') client.write(f'/pane/{extra}/body', b'RIGHT-COLUMN-NEW\n') require(wait_for(lambda: locate(client, 'RIGHT-COLUMN-NEW', minimum_col=75)), 'right-column command targeted another column') - client.write(f'/pane/{extra}/ctl', b'exec Del\n') + client.write(f'/pane/{extra}/exec', b'Del\n') checks.append('middle-click New targets the inactive right column') # An owned short-path file makes its complete tag visible. Pane-tag diff --git a/test/e2e_harness.zig b/test/e2e_harness.zig index f7f380df..5a181b78 100644 --- a/test/e2e_harness.zig +++ b/test/e2e_harness.zig @@ -92,7 +92,7 @@ pub const Harness = struct { const ws = posix.winsize{ .row = rows, .col = cols, .xpixel = 0, .ypixel = 0 }; const pid = forkpty(&master, null, null, &ws); if (pid == 0) { - for ([_][*:0]const u8{ "PARDES_9P", "PARDES_PANE", "PARDES_FORWARD_LOOK" }) |name| + for ([_][*:0]const u8{ "PARDES_PID", "PARDES_9P", "PARDES_PANE" }) |name| if (unsetenv(name) != 0) _exit(126); _ = execvp(exe, argv.ptr); _exit(127); diff --git a/test/font_size.py b/test/font_size.py index 3a0a9a28..b7104099 100644 --- a/test/font_size.py +++ b/test/font_size.py @@ -30,16 +30,16 @@ def run(args): for serial, tag in panes(client).items(): if '/+Config ' in tag: body = client.read(f'/pane/{serial}/body').decode() - if f'Font effective size: {size:.2f} pixels' in body: + if f'Font effective size {size:.2f} pixels' in body: return body return None return require(wait_for(ready), f'Font did not become {size} pixels') initial = report(18) - require('Font requested size: 18.00' in initial, 'startup size suffix ignored') + require('Font requested size 18.00' in initial, 'startup size suffix ignored') require(args.font in initial, 'requested font missing') execute(client, control, f'Font {args.font}:20.5') - require('Font requested size: 20.50' in report(20.5), 'fractional size ignored') + require('Font requested size 20.50' in report(20.5), 'fractional size ignored') execute(client, control, f'Font {args.font}') report(20.5) # no suffix preserves current size execute(client, control, f'Font {args.font}:900') diff --git a/test/fs.py b/test/fs.py index 819a78d6..c3ffa440 100644 --- a/test/fs.py +++ b/test/fs.py @@ -100,8 +100,15 @@ def session(binary, root, name, *options, socket_name=None, file=None, tty=False assert not reader.is_alive(), 'terminal reader did not stop' +def newest(client): + """The newest pane's serial: /index is ordered by serial.""" + return int(client.read('/index').splitlines()[-1].split()[0]) + + def new_pane(client, contents): - serial = int(client.read('/new').split()[0]) + """mkdir in /pane; the editor names the directory after the new serial.""" + client.mkdir('/pane', 'scratch') + serial = newest(client) if contents: client.write(f'/pane/{serial}/body', contents) return serial @@ -110,18 +117,18 @@ def new_pane(client, contents): def look(client, path, source=None): """A right click on `path` from a pane (a fresh scratch by default).""" serial = source if source is not None else new_pane(client, b'') - client.write(f'/pane/{serial}/ctl', f'look {path}\n'.encode()) - results = [int(row) for row in client.read('/ctl').split()] + client.write(f'/pane/{serial}/look', f'{path}\n'.encode()) + results = [int(row) for row in client.read('/look').split()] assert len(results) == 1 and results[0] != serial, (path, results) return results[0] def execute(client, serial, command): """A middle click on `command` from a pane.""" - client.write(f'/pane/{serial}/ctl', f'exec {command}\n'.encode()) + client.write(f'/pane/{serial}/exec', f'{command}\n'.encode()) -def walk_tree(client, path='/', skip=('/new', '/log', '/os', '/screen')): +def walk_tree(client, path='/', skip=('/log', '/os', '/screen')): """Stat every entry below `path`, as `find` does, without opening anything.""" seen = [] for name in client.list(path): @@ -138,18 +145,21 @@ def discovery(binary, embedded=False): root = Path(directory) with session(binary, root, 'discovery') as (client, _): top = client.list('/') - assert top[:9] == ['README', 'index', 'ctl', 'new', 'log', 'screen', 'listeners', 'pane', 'os'], top - assert 'self' not in top and 'cons' not in top, top + assert top[:10] == ['README', 'index', 'status', 'look', 'exec', 'log', 'screen', + 'listeners', 'pane', 'os'], top + assert 'self' not in top and 'cons' not in top and 'new' not in top, top assert ('src' in top) == embedded, (top, embedded) before = client.read('/index') guide = client.read('/README') - assert guide.count(b'\n') <= 45 and b'exec Msg' in guide and b'/new' in guide, guide + assert guide.count(b'\n') <= 45 and b'Msg hello' in guide and b'mkdir' in guide, guide assert client.stat('/README')['length'] == len(guide) # ls/stat/find over the whole tree, without opening, creates nothing. seen = walk_tree(client) names = {path for path, _ in seen} - assert {'/index', '/ctl', '/new', '/log', '/pane/1', '/pane/1/body', '/pane/1/name', - '/pane/1/sel', '/pane/1/ctl', '/pane/1/tag', '/pane/1/event'} <= names, sorted(names) + assert {'/index', '/status', '/look', '/exec', '/log', '/pane/1', '/pane/1/body', + '/pane/1/name', '/pane/1/sel', '/pane/1/ctl', '/pane/1/tag', '/pane/1/event', + '/pane/1/dot', '/pane/1/limit', '/pane/1/dirty', '/pane/1/mark', + '/pane/1/scroll', '/pane/1/look', '/pane/1/exec'} <= names, sorted(names) assert '/pane/1/pty' not in names, 'the fixture file pane grew a pty/' assert not any(name.startswith('/self') or name.endswith('/rdsel') or name.endswith('/wrsel') for name in names), sorted(names) @@ -159,18 +169,28 @@ def discovery(binary, embedded=False): assert client.read('/index') == before, 'browsing created a pane' assert client.stat('/index')['length'] == len(before) > 0 index = client.stat('/index') - assert index['mode'] == 0o444 and client.stat('/ctl')['mode'] == 0o666 + assert index['mode'] == 0o444 and client.stat('/status')['mode'] == 0o444 + assert client.stat('/exec')['mode'] == 0o666 assert client.stat('/pane/1/body')['mode'] == 0o666 and client.stat('/pane')['mode'] == 0o755 + # A range file reads the pair it takes; a flag file reads 0 or 1. + assert client.stat('/pane/1/addr')['length'] == 24 + assert client.stat('/pane/1/limit')['length'] == 0 + assert client.read('/pane/1/dirty') == b'0\n' + assert client.read('/pane/1/scroll') == b'1\n' fixture = int(before.split()[0]) assert before.split()[1:3] == [b'text', b'0'] and before.endswith(b'/discovery.txt\n'), before - # Before any command, /ctl reports the editor. - status = dict(line.split(maxsplit=1) for line in client.read('/ctl').decode().splitlines()) - assert int(status['pid']) > 0 and status['version'] and int(status['panes']) == 1, status - # /new: one pane per open, its serial is the file's content. + # /status reports the editor; /exec has nothing to report yet. + status = dict(line.split(maxsplit=1) for line in client.read('/status').decode().splitlines()) + assert int(status['pid']) > 0 and status['version'] and int(status['panes']) >= 1, status + assert client.read('/exec') == b'' + # mkdir makes a pane, named by the serial the editor gives it. log = client.open('/log') - first = int(client.read('/new').split()[0]) - second = int(client.read('/new').split()[0]) + client.mkdir('/pane', 'one') + first = newest(client) + client.mkdir('/pane', 'two') + second = newest(client) assert first != second and first != fixture, (first, second) + assert 'one' not in client.list('/pane') and 'two' not in client.list('/pane') assert client.read_fid(log) == f'new {first} {root}/+New\n'.encode() assert client.read_fid(log) == f'new {second} {root}/+New\n'.encode() assert set(client.list('/pane')) == {str(fixture), str(first), str(second)} @@ -186,51 +206,63 @@ def discovery(binary, embedded=False): assert client.read(f'/pane/{first}/name') == f'{root}/notes.txt\n'.encode() assert client.read_fid(log) == f'rename {first} {root}/notes.txt\n'.encode() assert client.stat(f'/pane/{first}/name')['length'] == len(f'{root}/notes.txt\n') + # Copying addr onto dot selects that range; sel reads and replaces it. client.write(f'/pane/{first}/addr', b'#0,#5') - client.write(f'/pane/{first}/ctl', b'dot=addr\n') + client.write(f'/pane/{first}/dot', client.read(f'/pane/{first}/addr')) + assert client.read(f'/pane/{first}/dot') == client.read(f'/pane/{first}/addr') assert client.read(f'/pane/{first}/sel') == b'first' assert client.stat(f'/pane/{first}/sel')['length'] == 5 client.write(f'/pane/{first}/sel', b'FIRST') assert client.read(f'/pane/{first}/body') == b'FIRST pane' assert client.read(f'/pane/{first}/sel') == b'' - # exec Msg shows text; exec Save writes the named file; exec Del closes. - client.write(f'/pane/{first}/ctl', b'exec Msg hello from 9P\n') + # exec Msg shows text; exec Save writes the named file; rmdir closes. + client.write(f'/pane/{first}/exec', b'Msg hello from 9P\n') assert 'hello from 9P' in ''.join(cell[0] for cell in client.screen()['cells']) - client.write(f'/pane/{first}/ctl', b'exec Save\n') + assert client.read(f'/pane/{first}/dirty') == b'1\n' + client.write(f'/pane/{first}/exec', b'Save\n') assert (root / 'notes.txt').read_bytes() == b'FIRST pane' assert client.read_fid(log) == f'save {first} {root}/notes.txt\n'.encode() - assert client.read('/ctl') == f'{first}\n'.encode() - client.write('/ctl', b'exec Del\n') + assert client.read('/exec') == f'{first}\n'.encode() + assert client.read(f'/pane/{first}/dirty') == b'0\n' + client.remove(f'/pane/{second}') assert client.read_fid(log) == f'del {second} {root}/+New\n'.encode() assert str(second) not in client.list('/pane') - # look through /ctl opens a file; the serial reads back. + # look opens a file; the serial reads back. (root / 'opened.txt').write_bytes(b'one\ntwo\nthree\n') - client.write('/ctl', f'look {root}/opened.txt:2\n'.encode()) - opened = int(client.read('/ctl')) + client.write('/look', f'{root}/opened.txt:2\n'.encode()) + opened = int(client.read('/look')) assert opened not in (fixture, first, second), opened assert client.read(f'/pane/{opened}/body') == b'one\ntwo\nthree\n' assert client.read(f'/pane/{opened}/name') == f'{root}/opened.txt\n'.encode() assert client.read_fid(log) == f'new {opened} {root}/opened.txt\n'.encode() - client.write(f'/pane/{first}/ctl', f'look {root}/opened.txt:3\n'.encode()) - assert client.read('/ctl') == f'{opened}\n'.encode(), 'a repeated look targets the open pane' - assert set(client.list('/pane')) == {str(fixture), str(first), str(opened)} + client.write(f'/pane/{first}/look', f'{root}/opened.txt:3\n'.encode()) + assert client.read('/look') == f'{opened}\n'.encode(), 'a repeated look targets the open pane' + assert {str(fixture), str(first), str(opened)} <= set(client.list('/pane')) # Writing an event record back still performs the action it names. client.write(f'/pane/{first}/body', b'Msg via event', truncate=True) client.write(f'/pane/{first}/event', b'FX0 13\n') assert 'via event' in ''.join(cell[0] for cell in client.screen()['cells']) - for bad in [b'Look x\n', b'Exec Msg x\n', b'put\n', b'name x\n', b'del\n']: + # A command line may not carry control characters, and nothing else + # in the tree may be created or removed. + refused = [lambda: client.write('/exec', b'Msg a\x00b'), + lambda: client.write('/status', b'anything\n'), + lambda: client.mkdir('/', 'x'), + lambda: client.create('/pane', 'plain-file'), + lambda: client.remove('/pane/1/body'), + lambda: client.remove('/index')] + for index, attempt in enumerate(refused): try: - client.write('/ctl', bad) + attempt() except OSError: pass else: - raise AssertionError(f'{bad!r} was accepted') + raise AssertionError(f'refusal {index} was accepted') client.close(log) if embedded: assert client.read('/src/pardes.zig').startswith(b'const std') assert client.stat('/src/pardes.zig')['mode'] == 0o444 assert b'pub const Pardes' in client.read(f'/pane/{look(client, "/virtual/src/pardes.zig")}/body') - print('9P discovery: listing/stat/find are inert; new, ctl, name, sel and log behave') + print('9P discovery: listing/stat/find are inert; create, remove, look, exec, name, sel and log behave') def test(binary, quic=False): @@ -266,7 +298,7 @@ def test(binary, quic=False): assert not (root / 'pardes-9p-renamed.sock').exists() assert named.read('/pane/1/body') == b'initial\n' with session(binary, root, 'first') as (client, address): - assert {'pane', 'index', 'new', 'ctl', 'log', 'os'} <= set(client.list('/')) + assert {'pane', 'index', 'status', 'look', 'exec', 'log', 'os'} <= set(client.list('/')) assert 'self' not in client.list('/') assert client.read('/pane/1/body') == b'initial\n' assert client.read('/os' + str(root / 'first.txt')) == b'initial\n' @@ -346,7 +378,7 @@ def test(binary, quic=False): opened = look(remote, '/n/peer/pane/' + str(serial) + '/body') assert remote.read(f'/pane/{opened}/body') == b'replaced\nevent\n' remote.write(f'/pane/{opened}/body', b'saved to peer\n', truncate=True) - remote.write(f'/pane/{opened}/ctl', b'exec Save\n') + remote.write(f'/pane/{opened}/exec', b'Save\n') assert client.read(body) == b'saved to peer\n' large = b'mounted file contents\n' * 60000 @@ -356,7 +388,7 @@ def test(binary, quic=False): assert remote.read(f'/pane/{opened}/body') == large edited = large[:-3] + b'edited\n' remote.write(f'/pane/{opened}/body', edited, truncate=True) - remote.write(f'/pane/{opened}/ctl', b'exec Save\n') + remote.write(f'/pane/{opened}/exec', b'Save\n') assert large_path.read_bytes() == edited assert client.read('/os' + str(large_path)) == edited @@ -368,12 +400,12 @@ def test(binary, quic=False): execute(remote, control, 'Mount peer ' + str(own_address)) execute(remote, control, 'Unmount peer') remote.write(f'/pane/{opened}/body', b'runtime mounted Save\n', truncate=True) - remote.write(f'/pane/{opened}/ctl', b'exec Save\n') + remote.write(f'/pane/{opened}/exec', b'Save\n') assert client.read('/pane/1/body') == b'runtime mounted Save\n' assert remote.read('/pane/1/body') == b'initial\n' roots = look(remote, '/n', source=control) assert b'/n/peer/\n' in remote.read(f'/pane/{roots}/body') - remote.write(f'/pane/{opened}/ctl', b'exec Del\n') + remote.write(f'/pane/{opened}/exec', b'Del\n') execute(remote, control, 'Unmount peer') remote.write(f'/pane/{roots}/ctl', b'get\n') assert remote.read(f'/pane/{roots}/body') == b'/n/os/\n/n/self/\n' @@ -385,7 +417,7 @@ def test(binary, quic=False): file='/n/peer/pane/1/body:1') as (remote, _): assert remote.read('/pane/1/body') == b'runtime mounted Save\n' - client.write(f'/pane/{serial}/ctl', b'exec Del\n') + client.write(f'/pane/{serial}/exec', b'Del\n') assert str(serial) not in client.list('/pane') for tty in [False, True]: @@ -424,7 +456,7 @@ def test(binary, quic=False): file_id, control_id = restored_ids contents = restored.read(f'/pane/{file_id}/body') assert contents == b'dumped state\n', (contents, saved.read_text(), restored.read('/index')) - assert restored.read(f'/pane/{control_id}/body') == b'', 'commands ran through ctl, not the body' + assert restored.read(f'/pane/{control_id}/body') == b'', 'commands ran through exec, not the body' assert restored.screen()['cols'] == 80 opened = look(restored, '/n/own/os' + str(root / (name + '.txt')), source=control_id) assert restored.read(f'/pane/{opened}/body') == b'initial\n' @@ -451,14 +483,12 @@ def test(binary, quic=False): assert client.read(f'/pane/{opened}/body') == expected assert client.read('/pane/1/body') == b'initial\n' if selected is not None: - addr = client.open(f'/pane/{opened}/addr') - client.write(f'/pane/{opened}/ctl', b'addr=dot\n') - actual = list(map(int, client.read_fid(addr).split())) - client.close(addr) + # The selection is dot; reading it takes no command at all. + actual = list(map(int, client.read(f'/pane/{opened}/dot').split())) assert actual == selected, (word, actual, selected) addr = client.open('/pane/1/addr', 2) - ctl = client.open('/pane/1/ctl', 1) - for fid, text in [(addr, b'#0,#3'), (ctl, b'limit=addr\n'), (addr, b'#0')]: + limit = client.open('/pane/1/limit', 2) + for fid, text in [(addr, b'#0,#3'), (limit, b'#0,#3'), (addr, b'#0')]: client.rpc(118, struct.pack(' req.size) return error.IncorrectReply; - const names = [_][]const u8{ "README", "index", "ctl", "new", "log", "screen", "listeners", "pane", "os" }; - const nodes = [_]u64{ @intFromEnum(ctlfs.TopFile.README), @intFromEnum(ctlfs.TopFile.index), @intFromEnum(ctlfs.TopFile.ctl), @intFromEnum(ctlfs.TopFile.new), @intFromEnum(ctlfs.TopFile.log), @intFromEnum(ctlfs.TopFile.screen), @intFromEnum(ctlfs.TopFile.listeners), @intFromEnum(ctlfs.TopFile.pane), filesystem.os_root }; + const names = [_][]const u8{ "README", "index", "status", "look", "exec", "log", "screen", "listeners", "pane", "os" }; + const nodes = [_]u64{ @intFromEnum(ctlfs.TopFile.README), @intFromEnum(ctlfs.TopFile.index), @intFromEnum(ctlfs.TopFile.status), @intFromEnum(ctlfs.TopFile.look), @intFromEnum(ctlfs.TopFile.exec), @intFromEnum(ctlfs.TopFile.log), @intFromEnum(ctlfs.TopFile.screen), @intFromEnum(ctlfs.TopFile.listeners), @intFromEnum(ctlfs.TopFile.pane), filesystem.os_root }; var off: usize = 0; var entry: usize = 0; while (off < bytes.len) : (entry += 1) { diff --git a/test/fs_namespace.zig b/test/fs_namespace.zig index 8b6f245e..3eba6639 100644 --- a/test/fs_namespace.zig +++ b/test/fs_namespace.zig @@ -245,22 +245,17 @@ test "virtual file opens do not request OS watches" { while (p.nextEffect()) |effect| if (effect == .watch) return error.VirtualFileWatch; } -test "Look at the clone file reserves its own pane and failed opens release it" { +test "Look at a virtual file opens one pane and failed opens release their slot" { const p = try pardes.Pardes.init(std.testing.allocator, .{ .tty_only = true }); defer p.deinit(); - p.lookAt(0, "/virtual/new"); - var control_count: usize = 0; - var scratch_count: usize = 0; + p.lookAt(0, "/virtual/index"); + var opened: usize = 0; for (p.panes) |slot| { const pane = slot orelse continue; const file = pane.file orelse continue; - if (std.mem.eql(u8, file.path, "/virtual/new")) control_count += 1; - if (file.output) |output| if (output.from == .cmd and output.from.cmd == .New) { - scratch_count += 1; - }; + if (std.mem.eql(u8, file.path, "/virtual/index")) opened += 1; } - try std.testing.expectEqual(@as(usize, 1), control_count); - try std.testing.expectEqual(@as(usize, 1), scratch_count); + try std.testing.expectEqual(@as(usize, 1), opened); const free = p.freeSlot().?; try std.testing.expectError(error.FileNotFound, pardes.panes.File.open(p, free, "/n/self/does-not-exist", 0)); try std.testing.expect(p.panes[free] == null); diff --git a/test/fs_soak.py b/test/fs_soak.py index 5569a7c7..a62f03e6 100644 --- a/test/fs_soak.py +++ b/test/fs_soak.py @@ -145,7 +145,7 @@ def run(args): client.write(base + '/body', body, truncate=True) path = root / f'pane-{slot}-0.zig' client.write(base + '/name', f'{path}\n'.encode()) - client.write(base + '/ctl', b'exec Save\n') + client.write(base + '/exec', b'Save\n') panes.append({'serial': serial, 'body': body, 'path': path, 'variant': 0}) emit(kind='start', seed=args.seed, session_pid=pid, transport=args.transport, host='tty' if args.tty else 'detached', @@ -187,7 +187,7 @@ def run(args): pane['variant'] ^= 1 pane['path'] = root / f'pane-{slot}-{pane["variant"]}.zig' client.write(base + '/name', f'{pane["path"]}\n'.encode()) - client.write(base + '/ctl', b'exec Save\n') + client.write(base + '/exec', b'Save\n') check_bytes(pane['path'].read_bytes(), pane['body'], 'saved file') check_bytes(client.read('/os' + str(pane['path'])), pane['body'], 'OS mount') elif operation == 'reload': @@ -196,13 +196,13 @@ def run(args): client.write(base + '/ctl', b'get\n') elif operation == 'cycle': old_serial = pane['serial'] - client.write(base + '/ctl', b'exec Del\n') + client.remove(base) pane['body'] = payload(rng) pane['serial'] = new_pane(client, pane['body']) assert pane['serial'] != old_serial base = f'/pane/{pane["serial"]}' client.write(base + '/name', f'{pane["path"]}\n'.encode()) - client.write(base + '/ctl', b'exec Save\n') + client.write(base + '/exec', b'Save\n') elif operation == 'reconnect': client.socket.close() client = Client(address) diff --git a/test/look_placement.py b/test/look_placement.py index 1341e776..8a31157f 100644 --- a/test/look_placement.py +++ b/test/look_placement.py @@ -74,7 +74,7 @@ def run_case(args, root, source_index): require('pty' in client.list(pane), 'fixture contains an existing document') marker = f'LP_{index}' markers[serial] = marker - client.write(pane + '/ctl', b'cleartag\n') + client.write(pane + '/tag', b'', truncate=True) client.write(pane + '/tag', f' {marker} Tty Del Collapse'.encode()) # Establish non-pristine shells and a stable prompt before measuring. client.write(pane + '/pty/data', f"printf 'ready-{index}\\n'\r".encode()) @@ -89,7 +89,7 @@ def run_case(args, root, source_index): require(before[serials[0]][:2] == (0, 2) and before[serials[1]][0] == 0 and before[serials[1]][1] > 2 and before[serials[2]][:2] == (75, 2), f'unexpected initial classic layout: {before}') - client.write(f'/pane/{source}/ctl', f'look {target}\n'.encode()) + client.write(f'/pane/{source}/look', f'{target}\n'.encode()) opened = require(wait_for(lambda: next((serial for serial in panes(client) if serial not in serials), None)), 'Look did not open the first document') @@ -113,7 +113,7 @@ def run_case(args, root, source_index): f'Look changed unrelated terminal {serial} rendered text') require(client.read(f'/pane/{opened}/body') == contents, 'opened document contents differ') - client.write(f'/pane/{source}/ctl', f'look {target}:2\n'.encode()) + client.write(f'/pane/{source}/look', f'{target}:2\n'.encode()) require(list(panes(client)) == serials + [opened], 'repeated Look created a duplicate pane') require(wait_for(lambda: geometry(client, markers)[1] == after), 'repeated Look changed layout') diff --git a/test/ninep.py b/test/ninep.py index 6c625951..ac4e146b 100644 --- a/test/ninep.py +++ b/test/ninep.py @@ -97,6 +97,25 @@ class Client: def close(self, fid): self.rpc(120, struct.pack(' |w| { + const bytes = w.bytes.slice(); + if (n + bytes.len > buf.len) break; + @memcpy(buf[n..][0..bytes.len], bytes); + n += bytes.len; + }, + else => {}, + }; + return buf[0..n]; + } + + // Raw tty mode forwards nearly every key to the child; the two paste + // chords are the exception, and forwarding them instead is what broke + // pasting into a terminal pane. An application that gets Ctrl-V rather + // than the text goes and reads the desktop clipboard on its own account, + // and a coding agent reading it is looking for an image, not for words. + test "raw tty paste chords type at the program instead of reaching it as keys" { + if (comptime !panes.Terminal.enabled) return error.SkipZigTest; + for ([_]bool{ false, true }) |bracketed| { + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 40, .rows = 12 }); + defer p.deinit(); + const pane = p.panes[0].?; + try std.testing.expectEqual(Pane.Mode.tty, pane.mode); + if (bracketed) p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[?2004h" } }); + try std.testing.expectEqual(bracketed, panes.Terminal.bracketedPaste(pane)); + p.yank = try p.gpa.dupe(u8, "one\ntwo"); // what a `y` anywhere left behind + var buf: [256]u8 = undefined; + _ = childInput(p, &buf); + + // Ctrl-V types the register straight at the program, asking the + // desktop for nothing. Under DECSET 2004 the program's own fences + // carry it, which is what stops readline RUNNING a multi-line paste. + p.update(.{ .key = .{ .cp = 'v', .ctrl = true } }); + try std.testing.expectEqualStrings( + if (bracketed) "\x1b[200~one\ntwo\x1b[201~" else "one\rtwo", + childInput(p, &buf), + ); + try std.testing.expect(p.clip_pending == null); + + // Ctrl-Shift-V is the other store: it ASKS, types nothing yet, and + // the answer lands at the program rather than in an edit buffer. A + // host that folds the Shift into the letter says the same thing. + for ([_]Key{ + .{ .cp = 'v', .ctrl = true, .shift = true }, + .{ .cp = 'V', .ctrl = true }, + }) |chord| { + p.update(.{ .key = chord }); + try std.testing.expect(p.clip_pending != null); + try std.testing.expectEqualStrings("", childInput(p, &buf)); + p.update(.{ .paste = "from-desktop" }); + try std.testing.expect(p.clip_pending == null); + try std.testing.expectEqualStrings( + if (bracketed) "\x1b[200~from-desktop\x1b[201~" else "from-desktop", + childInput(p, &buf), + ); + } + // ...and neither chord put the clipboard in the register on its way. + try std.testing.expectEqualStrings("one\ntwo", p.yank orelse ""); + } + } }; const ClickCursorTests = struct { @@ -1616,7 +1682,7 @@ test "generated output refuses every pipe prompt before seeding the tag" { const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true }); defer p.deinit(); const content = try p.gpa.dupe(u8, "generated\n"); - const pane = try panes.Output.open(p, 1, "/", .{ .cmd = .Help }, "", content); + const pane = try panes.Output.open(p, p.freeSlot().?, "/", .{ .cmd = .Help }, "", content); p.active = 1; for ([_]Key{ .{ .cp = '|' }, .{ .cp = '|', .alt = true }, .{ .cp = '!' }, .{ .cp = '!', .alt = true } }) |key| { p.update(.{ .key = key }); @@ -1825,14 +1891,14 @@ test "file history construction failures preserve existing panes" { defer if (incoming) |bytes| p.gpa.free(bytes); failing.fail_index = failing.alloc_index + failure; const result = switch (case) { - .open => panes.File.open(p, 1, path, 0), + .open => panes.File.open(p, p.freeSlot().?, path, 0), .restore => panes.File.restore(p, 1, .{ .kind = .file, .tag = "", .body = "", .file = .{ .path = "/restored.zig", .content = "restored\n" }, }), - .output => panes.Output.open(p, 1, "/", .{ .cmd = .Help }, "", incoming.?), + .output => panes.Output.open(p, p.freeSlot().?, "/", .{ .cmd = .Help }, "", incoming.?), .tutor => p.openTutorView(1), .replace => p.setTestFile("replacement\n"), }; @@ -1900,14 +1966,14 @@ test "file history owns bounded snapshot storage without per-edit bookkeeping al try std.testing.expectEqual(@as(usize, 0), history.redo_len); } -test "file history allocation precedes a filesystem read with side effects" { +test "file history allocation precedes reading the served tree" { var failing = std.testing.FailingAllocator.init(std.testing.allocator, .{}); const p = try Pardes.init(failing.allocator(), .{ .tty_only = true, .cols = 40, .rows = 12 }); defer p.deinit(); const original = p.panes[0].?; const serial = p.next_serial; failing.fail_index = failing.alloc_index + 2; - try std.testing.expectError(error.OutOfMemory, panes.File.open(p, 1, "/n/self/new", 0)); + try std.testing.expectError(error.OutOfMemory, panes.File.open(p, p.freeSlot().?, "/n/self/index", 0)); try std.testing.expect(failing.has_induced_failure); try std.testing.expectEqual(original, p.panes[0].?); try std.testing.expectEqual(serial, p.next_serial); diff --git a/test/pdf.zig b/test/pdf.zig index beeb0b40..930cc5c0 100644 --- a/test/pdf.zig +++ b/test/pdf.zig @@ -1253,7 +1253,7 @@ test "PdfTint cycles pane-local state without adding tag clutter" { try std.testing.expectEqual(PdfTintMode.filtered, pv.tint); const initial_tag = try pardes.test_api.tagText(p, p.scratch.allocator(), pane); try std.testing.expect(std.mem.startsWith(u8, initial_tag, pv.path)); - try std.testing.expect(std.mem.endsWith(u8, initial_tag, " PdfSections PdfTint Collapse")); + try std.testing.expect(std.mem.endsWith(u8, initial_tag, " PdfSections PdfTint Collapse Del")); try std.testing.expect(std.mem.indexOf(u8, initial_tag, "filtered") == null); try std.testing.expect(pardes.test_api.runBuiltin( diff --git a/test/tag_cleanup.py b/test/tag_cleanup.py index 7b7d8bbf..ae0a0e66 100644 --- a/test/tag_cleanup.py +++ b/test/tag_cleanup.py @@ -36,7 +36,7 @@ def run(args): before = set(panes(client)) execute(client, control, 'Tty') tty = require(wait_for(lambda: next((s for s in panes(client) if s not in before), None)), 'terminal missing') - client.write(f'/pane/{control}/ctl', b'exec Del\n') # owned command-only scratch + client.write(f'/pane/{control}/exec', b'Del\n') # owned command-only scratch def tag_position(): frame = client.screen() diff --git a/test/ui_review.py b/test/ui_review.py index 2b6faa29..a1cdcdeb 100644 --- a/test/ui_review.py +++ b/test/ui_review.py @@ -43,7 +43,7 @@ def command(client, serial, text): current = client.read(tag) start = current.rfind(text.encode()) client.write(f'/pane/{serial}/event', f'Mx{start} {start + len(text.encode())}\n'.encode()) - client.write(f'/pane/{serial}/ctl', b'cleartag\n') + client.write(f'/pane/{serial}/tag', b'', truncate=True) client.write(tag, before[tail_start:]) def new_output(client, before): @@ -111,7 +111,7 @@ def run(args): capture(client, root, '02-find', not args.tty) if find_pane: (root / 'find-results.txt').write_bytes(client.read(f'/pane/{find_pane}/body')) - client.write(f'/pane/{find_pane}/ctl', b'exec Del\n') + client.write(f'/pane/{find_pane}/exec', b'Del\n') before = panes(client) command(client, source, 'Grep CrdsValueLabel') grep_pane = require(wait_for(lambda: new_output(client, before)), 'Grep did not return results') @@ -140,10 +140,10 @@ def run(args): (root / 'symbols-results.txt').write_bytes(client.read(f'/pane/{symbols}/body')) capture(client, root, '05-symbols', not args.tty) if symbols: - client.write(f'/pane/{symbols}/ctl', b'exec Del\n') + client.write(f'/pane/{symbols}/exec', b'Del\n') offset = original.index(b'CrdsValue {') client.write(f'/pane/{source}/addr', f'#{offset},#{offset}'.encode()) - client.write(f'/pane/{source}/ctl', b'dot=addr\nshow\n') + client.write(f'/pane/{source}/dot', client.read(f'/pane/{source}/addr')) before = panes(client) command(client, source, 'Hover') hover = wait_for(lambda: new_output(client, before), args.lsp_wait) @@ -154,7 +154,7 @@ def run(args): # Look focuses the source without changing it; gd then travels through # the host's real input parser, unlike tag builtin dispatch above. line = original[:original.index(b'impl Sanitize for CrdsValue')].count(b'\n') + 1 - client.write(f'/pane/{source}/ctl', f'look {source_path}:{line}:19\n'.encode()) + client.write(f'/pane/{source}/look', f'{source_path}:{line}:19\n'.encode()) os.write(terminal_handle['input_fd'], b'gd') time.sleep(1) capture(client, root, '07-definition', not args.tty) @@ -166,7 +166,7 @@ def run(args): report['lsp'] = info.decode() capture(client, root, '08-lsp-info', not args.tty) if lsp: - client.write(f'/pane/{lsp}/ctl', b'exec Del\n') + client.write(f'/pane/{lsp}/exec', b'Del\n') for theme in args.themes: command(client, source, 'Theme ' + theme) capture(client, root, 'theme-' + theme, not args.tty) diff --git a/test/v9fs.py b/test/v9fs.py index 16916d0b..fa35388f 100644 --- a/test/v9fs.py +++ b/test/v9fs.py @@ -43,8 +43,8 @@ def worker(mountpoint, socket, uid, gid, original_namespace): assert not any(field.startswith(('shared:', 'master:')) for field in mounted[0].split()[6:]) tree = mountpoint - assert {'os', 'index', 'pane', 'new', 'ctl', 'log', 'screen', 'README'} <= set(os.listdir(tree)) - assert 'self' not in os.listdir(tree) + assert {'os', 'index', 'pane', 'status', 'look', 'exec', 'log', 'screen', 'README'} <= set(os.listdir(tree)) + assert 'self' not in os.listdir(tree) and 'new' not in os.listdir(tree) # A direct connection provides independent evidence for VFS reads/writes. with Client(socket) as client: assert (tree / 'index').read_bytes() == client.read('/index') @@ -52,14 +52,31 @@ def worker(mountpoint, socket, uid, gid, original_namespace): before = client.read('/index') subprocess.run(['ls', '-l', str(tree), str(tree / 'pane' / '1')], check=True, capture_output=True, timeout=5) - subprocess.run(['find', str(tree / 'pane'), str(tree / 'new'), '-ls'], check=True, capture_output=True, timeout=5) + subprocess.run(['find', str(tree / 'pane'), '-ls'], check=True, capture_output=True, timeout=5) assert (tree / 'README').read_bytes() == client.read('/README') - assert (tree / 'new').stat().st_size == 0 assert client.read('/index') == before, 'browsing created panes' - serial = int((tree / 'new').read_bytes().split()[0]) - another = int((tree / 'new').read_bytes().split()[0]) - assert serial != another, 'cached factory reused a pane' - client.write(f'/pane/{another}/ctl', b'exec Del\n') + # mkdir through the kernel mount opens a pane. The editor names it + # after its serial, not after the name asked for, so the kernel's own + # revalidation of that name may fail; the index is the answer. + def serials(): + return {int(row.split()[0]) for row in (tree / 'index').read_bytes().splitlines()} + + def mkpane(name): + known = serials() + try: + (tree / 'pane' / name).mkdir() + except FileNotFoundError: + pass + made = serials() - known + assert len(made) == 1, (name, made) + return made.pop() + + serial = mkpane('kernel-made') + another = mkpane('kernel-made-again') + assert serial != another, 'a second mkdir reused a pane' + assert not (tree / 'pane' / 'kernel-made').exists() + (tree / 'pane' / str(another)).rmdir() + assert another not in serials() pane = tree / 'pane' / str(serial) wire = f'/pane/{serial}' assert str(serial) in os.listdir(tree / 'pane') @@ -101,7 +118,7 @@ def worker(mountpoint, socket, uid, gid, original_namespace): # Reading OS files through the exported tree does not recurse through # the mount: the core still lives in the supervisor's namespace. assert (mountpoint / 'os' / str(socket.parent).lstrip('/') / 'kernel.txt').read_bytes() == b'initial\n' - write_existing(pane / 'ctl', b'exec Del\n') + (tree / 'pane' / str(serial)).rmdir() assert serial not in [int(row.split()[0]) for row in (tree / 'index').read_bytes().splitlines()] print('v9fs: namespace isolation, privilege drop, inherited mount, directory refresh, ' diff --git a/test/window_opacity.py b/test/window_opacity.py index b9529373..a576b1bd 100644 --- a/test/window_opacity.py +++ b/test/window_opacity.py @@ -60,7 +60,7 @@ def run(args): pane = require(wait_for(lambda: next((serial for serial in panes(client) if serial not in before), None)), builtin + ' output missing') text = client.read(f'/pane/{pane}/body').decode() - client.write(f'/pane/{pane}/ctl', b'exec Del\n') + client.write(f'/pane/{pane}/exec', b'Del\n') return text help_text = output('Help') -- cgit v1.3 From e714bbfa8b7cbf9970053cfbabbb9b1f02a2290e Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Mon, 21 Sep 2026 23:43:31 -0300 Subject: Draw a frame only when there is one worth drawing A 9P round trip on a local Unix socket cost 9.7 ms against the SDL shell and 0.758 ms against the terminal one. The server was not slow and the wake was not broken: instrumenting the path showed every request waking the loop early (wakes=210, woke_early=212, timed_out=38 over 250 ticks) and being answered on that same pass. The cost was that `pump` answers 9P at one point in a loop that then renders and presents unconditionally, so a client's next request landed while the main thread was blocked on the display, and each round trip therefore cost a whole frame. The frame rate was governing something that has nothing to do with drawing. `Pardes.needs_frame` starts true, is set by every event except a tick with nothing animating and a filesystem request that only reads, and is cleared once a frame is presented. `pump` returns before render and present when it is false and nothing is animating. An idle editor answering reads now draws nothing at all. 9P read_fid, one RPC: gui 9.7 ms -> 0.056 ms (173x) tty 0.758 ms -> 0.062 ms (12x) Verified the shells still paint rather than going quiet: the rendered screen carries the opened file, a write through 9P redraws within the frame, and `fs-discovery-test` passes over the real wire. Suite unchanged at 778/783 with the two pre-existing crashes. Also from the adversarial review of the previous commits: `pardes --tty FILE` silently discarded the file, and `--tty MISSING` silently discarded the error pane. main.zig named the boot layout before the positional was resolved, and naming one short-circuits `Boot.of`. The choice now happens after the argument is known, and only when there is no file and no missing word. macos.zig names the same layout, so the app no longer boots a different one from the terminal and SDL shells. `pre_close_last_pane_tail` was transcribed from the NEW default rather than the old one, so the upgrade path it was added for did not exist: a workspace dumped before the tagline reorder came back with the old default welded on as a custom tail. It is now the string it claims to be. A pane two rows tall lost its message and, worse, its prompt and the cursor with it. The notice cap keeps the LAST notices now, because the prompt is last and a prompt you cannot see is one you type into blind. Co-Authored-By: Claude Opus 5 (1M context) --- docs/config.md | 4 ++-- features.txt | 17 +++++++++++++++ src/macos.zig | 4 ++++ src/main.zig | 11 ++++++---- src/pardes.zig | 69 +++++++++++++++++++++++++++++++++++++++++++++++++++++++--- 5 files changed, 96 insertions(+), 9 deletions(-) (limited to 'src/main.zig') diff --git a/docs/config.md b/docs/config.md index e2b95e21..8eff79a8 100644 --- a/docs/config.md +++ b/docs/config.md @@ -37,7 +37,7 @@ hosted shell, `window_opacity` the SDL GUI only, and `tagline_font_size` everything but the TTY and the board. So the TTY reports Font, TaglineSize and the scene shaders as unsupported; the browser reports Font, panel transitions and the scene shaders as unsupported, -and its TaglineSize row reads `82% (build-time only)` — tagline font size is +and its TaglineSize row reads `82 (build-time only)` — tagline font size is its own capability precisely because GUI font SELECTION is native-only while the browser still applies the compiled percentage to its DOM glyphs. The startup path is printed whether or not a file exists — that is usually when @@ -203,7 +203,7 @@ does not make those areas more opaque. Regular text, syntax colors, tagline text, terminal glyphs, and the cursor keep their normal opacity. This does not blend foreground colors into their cell backgrounds. The TTY and other non-SDL hosts do not emulate this effect; their `Config` report says -`WindowOpacity: unsupported`. +`WindowOpacity unsupported`. On native Wayland, Pardes uses an alpha-capable transparent surface. It does not use whole-window opacity protocols such as `wp_alpha_modifier_v1`, because diff --git a/features.txt b/features.txt index e05f6f07..5583e7f3 100644 --- a/features.txt +++ b/features.txt @@ -139,3 +139,20 @@ tracing and the GPU/driver stack coming up, and the only lever on either is the The Last builtin should fall back to a heuristic when the jumplist has nothing to offer, so the bare tty layout -- a shell with an unfocused text pane under it -- alternates with Last even though that text pane was never focused and is not on the jumplist. + +Before finishing: remove the zig cache, then build ReleaseSafe with the full tree-sitter options, install to ~/.local/bin, and make sure the desktop entry and anything else that launches +pardes point at the updated binaries. + +Design smell, and it is a real one: Pardes.pump serialises input, event processing, 9P servicing, rendering and presenting into one loop, so the frame rate ends up +governing things that have nothing to do with drawing. The frame rate should only govern rendering. Evidence: a 9P RPC against an idle gui session costs 19.6 ms +and ZERO editor CPU -- it is not doing work, it is sleeping out the 16 ms SDL_WaitEventTimeout because the cross-thread wake does not wake it, and 9P is only +serviced afterwards in poll_frame. The same RPC against a tty session, same cloud9 runner, is 0.758 ms. So the server is fine and the gui host loop is the problem. + +Caching optimisations for the gui: worth doing, the renderer rebuilds more per frame than it needs to. + +FIXED, and it was the frame coupling after all: pump now draws a frame only when something that can change the screen happened. Pardes.needs_frame starts true, +is set by every event except a tick with nothing animating and a read-only fs_req, and is cleared once a frame is presented; pump returns before render/present +when it is false and nothing is animating. 9P round trip on a local socket: gui 9.7 ms -> 0.056 ms (173x), tty 0.758 ms -> 0.062 ms (12x). The wake path was never +the problem -- instrumentation proved every request woke the loop early (wakes=210, woke_early=212, timed_out=38 over 250 ticks) -- the reply simply could not be +produced until the loop had finished drawing a frame it did not need. Verified the gui still paints (screen shows the file, and a write through 9P redraws) and +the full suite is unchanged at 778/783 with the two known crashes. diff --git a/src/macos.zig b/src/macos.zig index d263cfc6..83b5eac9 100644 --- a/src/macos.zig +++ b/src/macos.zig @@ -709,6 +709,10 @@ fn initCore(runtime: ?*const Runtime, cols_arg: u16, rows_arg: u16) !void { var opts: pardes.Options = .{ .tty_only = true, + // The app is a real bare-tty startup, like the terminal and SDL + // shells, so it names the same layout rather than the bare shell a + // core booted for a test gets. + .boot = .tty, .frame_allocator = allocs.frame, .image_allocator = allocs.image, .pdf_allocator = allocs.pdf, diff --git a/src/main.zig b/src/main.zig index 1cbdf24c..9abc04bf 100644 --- a/src/main.zig +++ b/src/main.zig @@ -270,10 +270,6 @@ fn nativeMain(init: std.process.Init) !void { } } opts.tty_only = explicit_tty or session_only; - // The real bare-tty startup wants the editor half present from the first - // frame, so it names that layout; a core booted for a test names none and - // gets the raw shell by itself. - if (opts.tty_only) opts.boot = .tty; opts.mounts = mounts[0..mounts_len]; if (detach != null and attach != null) badArgs(init.io, "--detach and --attach are opposites: one runs the session, the other joins one", .{}); @@ -370,6 +366,13 @@ fn nativeMain(init: std.process.Init) !void { } } } + // The real bare-tty startup wants the editor half present from the first + // frame, so it names that layout; a core booted for a test names none and + // gets the raw shell by itself. This has to come AFTER the positional is + // resolved: naming a layout short-circuits `Boot.of`, so choosing it any + // earlier threw away a file argument, and the error pane for one that does + // not exist, without a word. + if (opts.tty_only and opts.file == null and opts.missing == null) opts.boot = .tty; const found = pardes.config.User.load(init.io, arena, init.environ_map); opts.startup_config = found.bytes; opts.startup_config_path = found.path; diff --git a/src/pardes.zig b/src/pardes.zig index 51442034..e9908d65 100644 --- a/src/pardes.zig +++ b/src/pardes.zig @@ -304,7 +304,7 @@ const pre_tty_first_terminal_pane_tail = " Save Tty Del Togglettymode Filter Col const pre_mode_terminal_pane_tail = " Tty Save Del Togglettymode Filter Collapse"; // ...and the defaults from before the closing word moved to the end of every // tagline, where a click cannot land on it by overshooting the one before. -const pre_close_last_pane_tail = " Tty Collapse Del"; +const pre_close_last_pane_tail = " Tty Del Collapse"; const pre_close_last_file_pane_tail = " Save Tty Del Collapse"; const pre_close_last_pdf_pane_tail = " Tty Del PdfSections PdfTint Collapse"; const pre_close_last_terminal_pane_tail = " Tty Save Del Mode Filter Collapse"; @@ -6099,6 +6099,9 @@ pub const Pardes = struct { fs: filesystem.Namespace = .{}, boot: Boot = .shell, + /// Is there a frame worth drawing? Cleared once one is presented, set by + /// anything that can change what is on screen. The first frame always is. + needs_frame: bool = true, /// Builtins announce themselves on the message row. Off while startup /// configuration is applied: those lines are nobody clicking, and should /// not leave the row holding the name of the last one. @@ -7137,13 +7140,28 @@ pub const Pardes = struct { // A quitting frame has already freed what it would draw. if (p.quit) return; if (v.poll_frame) |f| f(h.ctx); + // Nothing to draw: do not spend a frame, and above all do not block on + // the display for one. This is what keeps the frame rate governing + // rendering and nothing else. + if (!p.needs_frame and !p.animationActive()) return; _ = p.frame_arena.reset(.retain_capacity); const surface = try p.render(p.frame_arena.allocator()); if (v.present) |f| f(h.ctx, surface); if (v.post_present) |f| f(h.ctx); + p.needs_frame = false; } pub fn update(p: *Pardes, ev: Event) void { + // Only two events cannot change the screen: a tick with nothing + // animating, and a filesystem request that only reads. The second is + // what 9P traffic overwhelmingly is, and answering it used to drag a + // whole vsync-blocked frame behind it -- which is why a round trip on + // a local socket cost a frame instead of a few microseconds. + p.needs_frame = p.needs_frame or switch (ev) { + .tick => false, + .fs_req => |req| ctlfs.changesPane(req), + else => true, + }; p.shell_rows.sweep(p.gpa); switch (ev) { .tick => {}, @@ -13953,8 +13971,17 @@ pub const Pardes = struct { if (pane.promptAt()) |at| { if (pane.tagSlice()[@min(at, pane.tag_tail_len)..].len > 0) pane.notices.push(.prompt); } - // Never claim so many rows that the body has none left. - pane.notices.len = @min(pane.notices.len, r.h - BOX_H -| 1); + // A pane only has so many rows to give. When they do not all fit the + // LAST ones survive, because the prompt is last and it is the one + // carrying the cursor: a prompt you cannot see is a prompt you type + // into blind. A two-row pane spends its only body row on one notice, + // which is what the single shared row used to do anyway. + const room: u8 = @intCast(@min(@as(u16, Pane.Notices.max), r.h - BOX_H)); + if (pane.notices.len > room) { + const drop = pane.notices.len - room; + for (0..room) |i| pane.notices.kinds[i] = pane.notices.kinds[i + drop]; + pane.notices.len = room; + } } fn renderBodyLayer(p: *Pardes, arena: std.mem.Allocator, pane: *Pane, r: Rect, id: usize) !void { @@ -14603,6 +14630,42 @@ test "Esc back into a tty leaves its view at the prompt" { try std.testing.expectEqual(live, sp.terminal.?.vt.screens.active.pages.scrollbar().offset); } +test "closing the last pane in a column leaves an empty one in its place" { + if (platform == .web) return; + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 120, .rows = 24 }); + defer p.deinit(); + const shell = p.active; + p.newScratchColumn(shell); + const lone = p.active; + try std.testing.expect(lone != shell); + try std.testing.expectEqual(@as(usize, 2), p.ncol); + const at = layout.findPane(p, lone).?; + try std.testing.expectEqual(@as(usize, 1), p.col_n[at.col]); + const had = try std.testing.allocator.dupe(u8, p.panes[lone].?.cwdSlice()); + defer std.testing.allocator.free(had); + + try p.removePane(lone); + p.sync(); + + // The column outlives the pane: still two columns, and the one that was + // emptied holds a fresh empty pane in the same directory. + try std.testing.expectEqual(@as(usize, 2), p.ncol); + try std.testing.expectEqual(@as(usize, 1), p.col_n[at.col]); + const heir = p.col_panes[at.col][0]; + try std.testing.expect(heir != lone); + try std.testing.expect(p.panes[lone] == null); + const hp = p.panes[heir].?; + try std.testing.expectEqualStrings("", hp.file.?.content); + try std.testing.expectEqualStrings(had, hp.cwdSlice()); + try std.testing.expectEqual(heir, p.active); + try std.testing.expect(!p.quit); + + // ...and Delcol is what actually takes the column away. + try p.removeColumn(heir); + p.sync(); + try std.testing.expectEqual(@as(usize, 1), p.ncol); +} + test "the bare tty startup opens a text pane under the shell, unfocused" { if (platform == .web) return; const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .boot = .tty }); -- cgit v1.3 From 16717a555695ef666e9d2cd1bacc762a2ab15f4b Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Mon, 21 Sep 2026 23:53:58 -0300 Subject: Fixes from three adversarial reviews, and a destructive one among them The registry sweep could delete a live socket, anywhere on the filesystem. A reviewer reproduced it: a socket that is bound but has not reached listen(2) answers ECONNREFUSED exactly like a dead one -- that window is every server's startup -- and the sweep then followed the entry's symlink and unlinked whatever absolute path it named. It now follows a target only into the directory our own sockets live in and only to a `pardes-9p-*.sock` name, it re-probes immediately before deleting rather than trusting a probe that is by then several syscalls old, and a readlink that exactly filled its buffer is treated as the truncation it is. The test grew a case for an entry whose target is not ours: the entry goes, the file does not. Ctrl-V in raw tty mode was a black hole when the yank register was empty -- neither typed nor forwarded -- so vim's visual block, readline's quoted-insert and every other program's Ctrl-V simply vanished. With nothing to paste the chord belongs to the program again. The lone-ESC flush added earlier was dead code. vaxis already returns Escape for a one-byte 0x1b (`Parser.parseGround` asserts `input.len == 1`), so the carried byte it waited for can never exist; a reviewer showed a 3 ms gap and a 60 ms gap behaving identically. Removed rather than left to imply a guarantee it never provided. A shell whose editor is gone can start one again. Naming a live but unreachable session made `pardes ` exit 1, which let a stale environment variable lock someone out of their own editor; it falls through to an ordinary session, as it did before the variable existed. Also: the macOS ABI check for `pardes_topbar_pane_border_px` had been replaced by a duplicate of the line above it; `--startup` now fails on a leak the way every other measurement in that file does, and stops calling its maximum a p95 below twenty samples; the served README and the skill no longer tell you to write to `data` with `>`, which truncates the whole body before the write lands; `docs/v9fs.md` described the allocate-on-walk design that was rejected; and `test/fs.py` keys nesting off `PARDES_PID`, so its forwarding case stops passing only when the runner happens to be inside a live pardes. fs-test now reaches its one documented pre-existing failure instead of dying early. Suite 778/783 with the two known crashes. Co-Authored-By: Claude Opus 5 (1M context) --- .agents/skills/pardes-9p/SKILL.md | 6 ++-- docs/fs.md | 2 +- docs/ui-review.md | 2 +- docs/v9fs.md | 16 +++++------ features.txt | 11 ++++++++ src/9p_io.zig | 59 +++++++++++++++++++++++++++++++++------ src/fs-help.txt | 2 +- src/macos.zig | 1 + src/main.zig | 31 ++++++-------------- src/pardes.zig | 6 +++- src/tty/tty.zig | 31 -------------------- test/fs.py | 19 ++++++++++--- test/perf.zig | 9 +++++- 13 files changed, 112 insertions(+), 83 deletions(-) (limited to 'src/main.zig') diff --git a/.agents/skills/pardes-9p/SKILL.md b/.agents/skills/pardes-9p/SKILL.md index 91a8e864..aa856953 100644 --- a/.agents/skills/pardes-9p/SKILL.md +++ b/.agents/skills/pardes-9p/SKILL.md @@ -101,7 +101,7 @@ For a file or scratch pane, with `pane=$m/pane/`: | Append text | `echo text >> $pane/body` | `client.write(pane + '/body', b'text\n')` | | Replace all text | `echo text > $pane/body` | `client.write(pane + '/body', b'text\n', truncate=True)` | | Address a byte range | `echo '#0,#2' > $pane/addr` | `client.write(pane + '/addr', b'#0,#2')` | -| Replace that range | `echo 'pub fn' > $pane/data` | `client.write(pane + '/data', b'pub fn')` | +| Replace that range | `printf 'pub fn' >> $pane/data` | `client.write(pane + '/data', b'pub fn')` | | Read the selection | `cat $pane/dot` (offsets), `cat $pane/sel` (text) | the same two reads | | Select the addressed range | `cp $pane/addr $pane/dot` | `client.write(pane + '/dot', client.read(pane + '/addr'))` | | Reload from disk | `echo get > $pane/ctl` | `client.write(pane + '/ctl', b'get\n')` | @@ -220,8 +220,8 @@ with tempfile.TemporaryDirectory(prefix='pardes-9p-skill-') as directory: PY ``` -`new_pane` walks to `/pane/new` and reads the serial off the directory it -lands on; `execute` writes one line to a pane's `exec`. Both are in +`new_pane` opens `/pane/new` and reads the serial it answers; `execute` writes +one line to a pane's `exec`. Both are in `test/fs.py`. For terminal tests, use `session(..., tty=True)` and read [test/agent_session.py](../../../test/agent_session.py) for bounded interactive diff --git a/docs/fs.md b/docs/fs.md index 8607a26f..d1ed2b73 100644 --- a/docs/fs.md +++ b/docs/fs.md @@ -197,7 +197,7 @@ for Unix and TCP, a poll loop for QUIC, and the 9P client for mounts); `zig build fs-test` drives real sessions using the independent Python client in `test/ninep.py`; `zig build fs-discovery-test` checks that browsing -creates nothing, that the walk to `/pane/new` and a remove work, and that +creates nothing, that an open of `/pane/new` and a remove work, and that `look`, `exec`, `name`, `sel` and `log` behave. `zig build 9p-test` checks the two engine configurations' budgets (the engine's own tests are cloud9's `zig build test`); `zig build fs-bench` measures diff --git a/docs/ui-review.md b/docs/ui-review.md index 2438f2ef..58a42e61 100644 --- a/docs/ui-review.md +++ b/docs/ui-review.md @@ -198,7 +198,7 @@ Review artifacts from this pass: ## Regression checks Both native binaries built in ReleaseFast. The full TTY and SDL unit suites -passed with the inherited nesting variables `PARDES_FORWARD_LOOK`, `PARDES_9P` +passed with the inherited nesting variables `PARDES_PID`, `PARDES_9P` and `PARDES_PANE` removed from the test process. Those variables exposed an existing environment-ownership issue in native subprocess tests: libc's environment was changed while the Zig test I/O retained the old slice. This diff --git a/docs/v9fs.md b/docs/v9fs.md index 1b14c21f..cfbbd35b 100644 --- a/docs/v9fs.md +++ b/docs/v9fs.md @@ -13,16 +13,14 @@ cat "$PARDES_MOUNT/index" cat "$PARDES_MOUNT/README" cat "$PARDES_MOUNT/pane/$PARDES_PANE/body" echo 'Msg hello' > "$PARDES_MOUNT/exec" -awk '{print $1}' "$PARDES_MOUNT/pane/new/ctl" +n=$(cat "$PARDES_MOUNT/pane/new") ``` -Walking to `pane/new` opens a pane, and the walk lands on that pane's own -directory, so its `ctl` answers the serial to use afterwards. The kernel keeps -the name it walked rather than the one the server answers back, so -`pane/new` stays in the dentry cache as a name of its own; address the pane as -`pane/` once you have it, and expect a fresh path resolution of -`pane/new` to open another pane. It is not listed in `pane/`, so `ls -l` and -`find` over the mount create nothing. +**Opening** `pane/new` makes a pane, and reading that open file answers its +serial; address the pane as `pane/` from then on. Each open makes +another one, so read it once and keep the number. A *stat* makes nothing, +which is why `new` can be listed at all: `ls`, `ls -l` and `find` over the +whole mount create nothing, because none of them open it. The mount belongs to that pane's subprocess tree. Other panes and the editor core keep their original mount namespace. It works in native Linux TTY and SDL @@ -112,5 +110,5 @@ Pardes accepts this truncation without storing caller-selected timestamps; standalone timestamp, permission, and ownership changes remain unsupported. The initial kernel probe passed on this host on 2026-09-14. The broader -`fs-test` has an existing syntax-bold assertion failure at `test/fs.py:459`, +`fs-test` has an existing syntax-bold assertion failure (now `test/fs.py:615`), also reproduced on the cached editor binary preceding the truncation fix. diff --git a/features.txt b/features.txt index 5583e7f3..eeadba39 100644 --- a/features.txt +++ b/features.txt @@ -156,3 +156,14 @@ when it is false and nothing is animating. 9P round trip on a local socket: gui the problem -- instrumentation proved every request woke the loop early (wakes=210, woke_early=212, timed_out=38 over 250 ticks) -- the reply simply could not be produced until the loop had finished drawing a frame it did not need. Verified the gui still paints (screen shows the file, and a write through 9P redraws) and the full suite is unchanged at 778/783 with the two known crashes. + +Found by adversarial review and NOT fixed, because they are upstream or macOS-only rather than from this session's work: +- Surface.mark_hover is never assigned true anywhere in the tree, so the whole macOS hover ABI is inert: PARDES_CELL_HOVER is never emitted, encodeCellFlags always + contributes 0, and PardesView's liquid-glass affordance never draws. The tests pass only because they set the flag by hand. The comment in the look_hover_preview + paint block claims it carries those cells out to the hosts; it does not. +- -Dworkspace-tag is read only in src/macos.zig, and core.settings.workspace_tag is assigned only there, so the option builds cleanly for gui/tty/web and is + silently ignored. gui.zig hard-codes `true` at six taglineBandOffset call sites and still uses raw TOPBAR_H at five more. +- The detached wire encodes the pointer shape in the frame header variant (full_link/diff_link), so the newer `.target` shape collapses to `.arrow` for an attached + frontend. Fixing it means a new header variant, i.e. a protocol change. +- A shell that outlives its editor keeps PARDES_PID; if that pid is reused, `pardes ` now exits 1 instead of falling back to starting an editor. Exiting 1 + only when the socket itself refused would keep the old behaviour. diff --git a/src/9p_io.zig b/src/9p_io.zig index 3d019e0d..7f0134ed 100644 --- a/src/9p_io.zig +++ b/src/9p_io.zig @@ -671,7 +671,7 @@ pub const Listener = struct { log.warn("registry post skipped: cannot create {s}", .{svc}); return; } - sweepRegistry(l.io, svc); + sweepRegistry(l.io, svc, xdg); var entry_buf: [sun_path_len:0]u8 = undefined; const entry = std.fmt.bufPrintSentinel(&entry_buf, "{s}/{s}", .{ svc, name }, 0) catch { log.warn("registry post skipped: name too long: {s}", .{name}); @@ -903,7 +903,21 @@ fn probe(path: [:0]const u8) Probe { /// a definite refusal counts as gone. The socket a stale entry points /// at goes too, but not before a stat agrees it is a socket of ours: a /// plain file answers a connect with the same refusal. -fn sweepRegistry(io: std.Io, svc: [:0]const u8) void { +/// Is this the kind of path this editor is allowed to delete? A registry +/// entry is a symlink we wrote, but its target is just bytes on disk that +/// anyone could have pointed anywhere, so the sweep only ever follows one +/// into the directory our own sockets live in, and only to a name of the +/// shape we give them. Everything else gets its entry removed and its target +/// left strictly alone. +fn ourSocket(target: []const u8, sockets: []const u8) bool { + if (sockets.len == 0 or !std.mem.startsWith(u8, target, sockets)) return false; + if (target.len <= sockets.len or target[sockets.len] != '/') return false; + const base = target[sockets.len + 1 ..]; + if (std.mem.indexOfScalar(u8, base, '/') != null) return false; + return std.mem.startsWith(u8, base, "pardes-9p-") and std.mem.endsWith(u8, base, ".sock"); +} + +fn sweepRegistry(io: std.Io, svc: [:0]const u8, sockets: []const u8) void { if (comptime !supported) return; // The names are staged before anything is unlinked, so the sweep @@ -941,12 +955,22 @@ fn sweepRegistry(io: std.Io, svc: [:0]const u8) void { if (libc.unlink(entry) != 0) continue; reaped += 1; // A relative target would resolve against this editor's working - // directory, which says nothing about what the entry named. + // directory, which says nothing about what the entry named, and a + // readlink that exactly filled the buffer was truncated, so the path + // it produced is some other file's. if (state != .stale or n <= 0 or link_buf[0] != '/') continue; + if (@as(usize, @intCast(n)) >= link_buf.len) continue; var target_buf: [sun_path_len:0]u8 = undefined; const target = std.fmt.bufPrintSentinel(&target_buf, "{s}", .{link_buf[0..@intCast(n)]}, 0) catch continue; + if (!ourSocket(target, sockets)) continue; const t = statNoFollow(target) orelse continue; - if (t.mode & 0o170000 == 0o140000 and t.uid == libc.getuid()) _ = libc.unlink(target); + if (t.mode & 0o170000 != 0o140000 or t.uid != libc.getuid()) continue; + // Ask again, immediately before deleting. The first probe was of the + // ENTRY and is by now several syscalls old; a socket that is bound but + // has not reached listen(2) yet answers ECONNREFUSED exactly like a + // dead one, and that window is every server's startup. + if (probe(target) != .stale) continue; + _ = libc.unlink(target); } if (reaped != 0) log.info("reaped {d} stale registry entries under {s}", .{ reaped, svc }); } @@ -997,14 +1021,23 @@ test "the registry sweep takes the dead entries and leaves everything else" { return error.SkipZigTest; if (libc.mkdir(svc, 0o700) != 0) return error.SkipZigTest; - var paths: [5][sun_path_len:0]u8 = undefined; - const live_sock = try std.fmt.bufPrintSentinel(&paths[0], "{s}/live.sock", .{svc}, 0); - const dead_sock = try std.fmt.bufPrintSentinel(&paths[1], "{s}/dead.sock", .{svc}, 0); + // The sockets live where the real ones do -- beside the registry, not in + // it, and named the way a session names them -- because the sweep only + // follows an entry to a target of exactly that shape and place. + var paths: [6][sun_path_len:0]u8 = undefined; + const pid: u32 = @intCast(libc.getpid()); + const live_sock = try std.fmt.bufPrintSentinel(&paths[0], "{s}/pardes-9p-sweeplive-{d}.sock", .{ base, pid }, 0); + const dead_sock = try std.fmt.bufPrintSentinel(&paths[1], "{s}/pardes-9p-sweepdead-{d}.sock", .{ base, pid }, 0); const live = try std.fmt.bufPrintSentinel(&paths[2], "{s}/live", .{svc}, 0); const dead = try std.fmt.bufPrintSentinel(&paths[3], "{s}/dead", .{svc}, 0); const stranger = try std.fmt.bufPrintSentinel(&paths[4], "{s}/stranger", .{svc}, 0); + // A dead entry pointing at something that is NOT one of our sockets: the + // entry goes, the file it named must not. + const outsider_sock = try std.fmt.bufPrintSentinel(&paths[5], "{s}/sweep-outsider-{d}.sock", .{ base, pid }, 0); + var outsider_buf: [sun_path_len:0]u8 = undefined; + const outsider = try std.fmt.bufPrintSentinel(&outsider_buf, "{s}/outsider", .{svc}, 0); defer { - for ([_][:0]const u8{ live_sock, dead_sock, live, dead, stranger }) |p| _ = libc.unlink(p); + for ([_][:0]const u8{ live_sock, dead_sock, live, dead, stranger, outsider_sock, outsider }) |p| _ = libc.unlink(p); _ = libc.rmdir(svc); } @@ -1021,6 +1054,12 @@ test "the registry sweep takes the dead entries and leaves everything else" { try testing.expectEqual(@as(c_int, 0), libc.symlink(live_sock, live)); try testing.expectEqual(@as(c_int, 0), libc.symlink(dead_sock, dead)); + // Dead too, but its target is not one of our sockets by name, so the + // entry must go and the file it named must survive untouched. + const outside = bindSocket(outsider_sock); + try testing.expect(outside >= 0); + defer _ = libc.close(outside); + try testing.expectEqual(@as(c_int, 0), libc.symlink(outsider_sock, outsider)); // Not a symlink, so not this program's to reason about, even though // connecting to it is refused exactly like the dead socket. try std.Io.Dir.cwd().writeFile(testing.io, .{ .sub_path = stranger, .data = "" }); @@ -1058,7 +1097,7 @@ test "the registry sweep takes the dead entries and leaves everything else" { try testing.expectEqual(Probe.live, probe(live)); try testing.expectEqual(Probe.stale, probe(dead)); - sweepRegistry(testing.io, svc); + sweepRegistry(testing.io, svc, base); // Promptly, and not "eventually": a blocking probe never comes back // at all, so any wall-clock bound at all is the assertion that @@ -1071,6 +1110,8 @@ test "the registry sweep takes the dead entries and leaves everything else" { try testing.expect(statNoFollow(live) != null); try testing.expect(statNoFollow(live_sock) != null); try testing.expect(statNoFollow(stranger) != null); + try testing.expect(statNoFollow(outsider) == null); + try testing.expect(statNoFollow(outsider_sock) != null); try testing.expectEqual(Probe.live, probe(live)); } diff --git a/src/fs-help.txt b/src/fs-help.txt index 3113590a..7f55b3af 100644 --- a/src/fs-help.txt +++ b/src/fs-help.txt @@ -23,7 +23,7 @@ Below, $m is the mount point (PARDES_MOUNT in a Tty9p shell; 9ns and 9p work too cat $m/pane/$n/name; echo notes.txt > $m/pane/$n/name read, then rename echo Save > $m/pane/$n/exec save it; rmdir $m/pane/$n closes it echo 'Msg hello' > $m/exec show text in the editor - echo '#0,#5' > $m/pane/$n/addr; echo NEW > $m/pane/$n/data replace bytes 0..5 + echo '#0,#5' > $m/pane/$n/addr; printf NEW >> $m/pane/$n/data replace bytes 0..5 cp $m/pane/$n/addr $m/pane/$n/dot; cat $m/pane/$n/sel select the range, read it cat $m/pane/$n/dirty; echo 0 > $m/pane/$n/dirty is it modified? say it is not cat $m/log block until a pane is made, renamed, saved or closed diff --git a/src/macos.zig b/src/macos.zig index 83b5eac9..d3b33c55 100644 --- a/src/macos.zig +++ b/src/macos.zig @@ -2594,6 +2594,7 @@ test "pardes.h declares every export the way it is defined" { try expectSameAbi(@TypeOf(c.pardes_gui_tagline_font_percent), @TypeOf(pardes_gui_tagline_font_percent)); try expectSameAbi(@TypeOf(c.pardes_tagline_band_offset), @TypeOf(pardes_tagline_band_offset)); try expectSameAbi(@TypeOf(c.pardes_topbar_pane_border_rgb), @TypeOf(pardes_topbar_pane_border_rgb)); + try expectSameAbi(@TypeOf(c.pardes_topbar_pane_border_px), @TypeOf(pardes_topbar_pane_border_px)); try expectSameAbi(@TypeOf(c.pardes_tag_active_bg), @TypeOf(pardes_tag_active_bg)); try expectSameAbi(@TypeOf(c.pardes_tagline_origin_col), @TypeOf(pardes_tagline_origin_col)); try expectSameAbi(@TypeOf(c.pardes_grid_col_at), @TypeOf(pardes_grid_col_at)); diff --git a/src/main.zig b/src/main.zig index 9abc04bf..050cee60 100644 --- a/src/main.zig +++ b/src/main.zig @@ -112,16 +112,6 @@ const nested_text = \\ ; -/// $PARDES_PID named a live editor, so this shell IS inside one, but the Look -/// never got there. Saying so beats quietly opening the second editor that -/// $PARDES_PID exists to prevent. -const unreachable_text = - \\pardes: this shell is inside pardes, but that session did not take the - \\file. Check that it is still running, or pass --nested to start a second - \\editor in here anyway. - \\ -; - // The browser runtime calls a C main (exported below); everything else keeps // the std.process.Init entry. pub const main = if (is_emscripten) webMain else nativeMain; @@ -304,10 +294,13 @@ fn nativeMain(init: std.process.Init) !void { if (serial == 0) break :reaching null; break :reaching .{ .dial = dial, .serial = serial }; }; - const parent = found orelse { - try std.Io.File.stderr().writeStreamingAll(init.io, unreachable_text); - std.process.exit(1); - }; + // A pid we cannot reach is a session that is not answering: the shell + // says it is inside one, but there is nothing there to take the file. + // Starting an ordinary editor is what this did before the pid existed + // and is the more useful of the two answers -- refusing to start would + // leave a stale environment variable able to lock someone out of their + // own editor. + const parent = found orelse break :forwarding; // The pane's `look` file: one line, and the line is the clicked text // itself, which is what a right click in that pane would have been. var look_buf: [64]u8 = undefined; @@ -315,10 +308,7 @@ fn nativeMain(init: std.process.Init) !void { const word = positional orelse { var tag_buf: [64]u8 = undefined; const tag = try std.fmt.bufPrint(&tag_buf, "/pane/{d}/tag", .{parent.serial}); - const contents = ninep_io.Client.read(arena, parent.dial, tag, tag) catch { - try std.Io.File.stderr().writeStreamingAll(init.io, unreachable_text); - std.process.exit(1); - }; + const contents = ninep_io.Client.read(arena, parent.dial, tag, tag) catch break :forwarding; arena.free(contents); try std.Io.File.stderr().writeStreamingAll(init.io, nested_text); std.process.exit(1); @@ -332,10 +322,7 @@ fn nativeMain(init: std.process.Init) !void { const path = if (pardes.filesystem.isVirtual(target.path)) target.path else (pardes.filesystem.resolveOs(target.path, &realbuf) orelse break :forwarding).path; var command_buf: [8192]u8 = undefined; const command = std.fmt.bufPrint(&command_buf, "{s}{s}\n", .{ path, word[target.path.len..] }) catch break :forwarding; - ninep_io.Client.write(arena, parent.dial, look, command) catch { - try std.Io.File.stderr().writeStreamingAll(init.io, unreachable_text); - std.process.exit(1); - }; + ninep_io.Client.write(arena, parent.dial, look, command) catch break :forwarding; return; } if (positional) |a| { diff --git a/src/pardes.zig b/src/pardes.zig index e9908d65..5c6d2422 100644 --- a/src/pardes.zig +++ b/src/pardes.zig @@ -8368,7 +8368,11 @@ pub const Pardes = struct { // A host that folds Shift into the letter says the same thing. if (key.ctrl and !key.alt and (key.cp == 'v' or key.cp == 'V')) { if (key.shift or key.cp == 'V') return p.clipRequest(p.active, .after); - return p.typeToTty(p.active, pane, p.yank orelse return); + // With something in the register this is a paste. With nothing + // in it the chord is the program's -- vim's visual block, + // readline's quoted-insert -- and swallowing it would make + // Ctrl-V a black hole in every full-screen application. + if (p.yank) |text| return p.typeToTty(p.active, pane, text); } return panes.Terminal.forwardKey(p, p.active, key); } diff --git a/src/tty/tty.zig b/src/tty/tty.zig index a1917ba9..23b7c09b 100644 --- a/src/tty/tty.zig +++ b/src/tty/tty.zig @@ -71,21 +71,6 @@ fn inputReader(loop: *Loop, tty: anytype, cache: *vaxis.GraphemeCache) void { loop.postEvent(.quit) catch {}; } -/// How long a lone ESC waits for the rest of a sequence before it counts as -/// the Escape key. Long enough for the remainder of a real sequence to arrive -/// even over a slow link, short enough that nobody sees the delay. -const escape_hold_ms = 25; - -/// Is there more input right behind what we have already read? Only a real -/// terminal has an fd to ask; the test readers hand their parts over whole, so -/// for them the answer is always no. -fn morePending(tty: anytype) bool { - const Reader = @typeInfo(@TypeOf(tty)).pointer.child; - if (!@hasField(Reader, "fd") or @FieldType(Reader, "fd") != std.Io.File) return false; - var fds = [_]std.posix.pollfd{.{ .fd = tty.fd.handle, .events = std.posix.POLL.IN, .revents = 0 }}; - return (std.posix.poll(&fds, escape_hold_ms) catch return false) > 0; -} - fn readInput(loop: *Loop, tty: anytype, cache: *vaxis.GraphemeCache) !void { try loop.postEvent(.{ .winsize = try tty.getWinsize() }); var parser: vaxis.Parser = .{}; @@ -116,22 +101,6 @@ fn readInput(loop: *Loop, tty: anytype, cache: *vaxis.GraphemeCache) !void { } carried = end - consumed; std.mem.copyForwards(u8, buf[0..carried], buf[consumed..end]); - // A lone ESC opens most sequences and is also the Escape key, so the - // parser holds it for a remainder that a keypress never sends: the - // press would only land when the NEXT key arrived. Wait a beat, and - // when nothing follows it was the key. A terminal speaking the kitty - // protocol never reaches here — it spells Escape out in full. - if (carried == 1 and buf[0] == 0x1b and !morePending(tty)) { - carried = 0; - try vaxis.loop.handleEventGeneric( - loop, - loop.vaxis, - cache, - @TypeOf(Command.value), - @as(vaxis.Event, .{ .key_press = .{ .codepoint = vaxis.Key.escape } }), - loop.vaxis.opts.system_clipboard_allocator, - ); - } } } diff --git a/test/fs.py b/test/fs.py index b20dc8ee..c8dea2d9 100644 --- a/test/fs.py +++ b/test/fs.py @@ -470,7 +470,13 @@ def test(binary, quic=False): spaced = child_dir / 'space name.txt' spaced.write_bytes(b'first line\nsecond line\n') env = os.environ.copy() - env.update(PARDES_9P=str(address), PARDES_PANE='1', PARDES_FORWARD_LOOK='1') + # PARDES_PID is what says "you are inside a pardes"; the socket + # and the pane only say how to reach it. Without the pid the child + # starts its own session, so this test used to pass only when the + # runner itself happened to be running inside one. + status = dict(line.split(maxsplit=1) for line in client.read('/status').decode().splitlines()) + env.update(PARDES_9P=str(address), PARDES_PANE='1', PARDES_PID=status['pid']) + env.pop('PARDES_FORWARD_LOOK', None) for word, expected, selected, reuse in [('space name.txt:2:4', spaced.read_bytes(), [14, 14], False), ('/n/self/pane/1/body', b'initial\n', None, False), ('/virtual/pane/1/body:1:2-4', b'initial\n', [1, 4], True)]: @@ -518,7 +524,7 @@ def test(binary, quic=False): assert time.monotonic() < deadline, 'forwarding fixture Dump did not finish' time.sleep(.005) before = client.read('/index') - inherited = {key: env[key] for key in ['PARDES_9P', 'PARDES_PANE', 'PARDES_FORWARD_LOOK']} + inherited = {key: env[key] for key in ['PARDES_9P', 'PARDES_PANE', 'PARDES_PID']} cases = [ ('mount', ['--mount=peer=' + str(address), '/n/peer/pane/1/body'], None), ('name', ['--9p=forwarded-name'], 'forwarded-name'), @@ -543,7 +549,10 @@ def test(binary, quic=False): assert local.read('/index') == before assert local.read('/pane/1/body') == b'initial\n' else: - assert len(index) == (3 if name == 'shells' else 1), index + # A bare tty launch is a shell plus the empty text pane + # the boot puts under it; --shells=3 is the classic + # three-shell layout and has no scratch. + assert len(index) == (3 if name == 'shells' else 2), index if name in ['tcp', 'quic']: assert (name + '!127.0.0.1!').encode() in local.read('/listeners') assert client.read('/index') == before @@ -554,7 +563,9 @@ def test(binary, quic=False): ('stale-missing', dict(inherited, PARDES_9P=str(root / 'absent.sock')), 'missing-child-file.txt'), ('stale-noarg', dict(inherited, PARDES_9P=str(root / 'absent.sock')), None), ('stale-pane', dict(inherited, PARDES_PANE='4294967295'), str(spaced)), - ('disabled', dict(inherited, PARDES_FORWARD_LOOK='0'), str(spaced)), + # No pid means "not inside a pardes at all", which is what + # --nested withholds and what a plain shell has. + ('not-nested', {k: v for k, v in inherited.items() if k != 'PARDES_PID'}, str(spaced)), ]: with session(binary, root, name, tty=True, inherited=identity, launch=['--tty', *([word] if word else [])]) as (local, local_address): diff --git a/test/perf.zig b/test/perf.zig index 8f463204..5ac38ccf 100644 --- a/test/perf.zig +++ b/test/perf.zig @@ -200,6 +200,10 @@ fn measureStartup(io: std.Io, reps: usize, json: bool) !void { bytes += counter.bytes; peak = @max(peak, counter.peak); } + // Every other measurement in this file checks the session gave + // everything back; a boot that leaks is exactly what a startup + // benchmark should be the first to notice. + if (counter.live != 0) return error.LeakedStartupMemory; } std.mem.sort(u64, init_samples, {}, std.sort.asc(u64)); std.mem.sort(u64, frame_samples, {}, std.sort.asc(u64)); @@ -212,7 +216,10 @@ fn measureStartup(io: std.Io, reps: usize, json: bool) !void { .reps = reps, .cold_ns = cold_ns, .init_median_ns = init_samples[reps / 2], - .init_p95_ns = init_samples[@min(reps - 1, reps * 95 / 100)], + // A p95 needs at least twenty samples to be one; below that this + // is the maximum and says so rather than dressing it up. + .init_p95_ns = if (reps >= 20) init_samples[reps * 95 / 100] else init_samples[reps - 1], + .init_max_ns = init_samples[reps - 1], .frame_median_ns = frame_samples[reps / 2], .allocations = calls / reps, .allocated_bytes = bytes / reps, -- cgit v1.3 From 39c8dd6ad7e97a974c7a194ae212c1677e0c7029 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Thu, 24 Sep 2026 13:54:10 -0300 Subject: Allocate from libc's malloc in every release shell, and check macOS's Debug build too The tty, gui and detached shells allocate from std.start's gpa, which is a DebugAllocator in Debug and, because we link libc, libc's malloc otherwise. The macOS shell hardcoded std.heap.smp_allocator in every mode, so its Debug build checked nothing it allocated outside memory.zig's subsystems. Which allocator a release build should use was measured rather than assumed, in ReleaseFast, with an experimental gui that chose at startup between glibc's malloc and smp_allocator, with and without memory.zig's stack-fallback buffers, plus an A/A pair; ten interleaved rounds, compared round by round. The gui frame-cost harness (idle, scroll and typing in src/pardes.zig, terminal spew, wheel-scrolling docs/design.pdf, first paint) saw every candidate within the A/A pair's noise. Twelve rounds of the allocation-heavy paths themselves, highlighting all of src/pardes.zig (305k tree-sitter allocations) and pardes-pdf-bench's MuPDF renders, split them: smp_allocator was 2 to 6% slower on MuPDF's page-sized rasters (slower in 9 to 11 of 12 rounds), no better on tree-sitter, and the stack-fallback buffers changed nothing either way. So glibc's malloc it is, with the buffers kept. macos.zig now takes a DebugAllocator in Debug, deinitialized in pardes_deinit with leaks logged the way std.start treats the others', and libc's malloc otherwise. main.zig says why init.gpa is kept. Co-Authored-By: Claude Opus 5.5 (1M context) --- src/macos.zig | 14 +++++++++++++- src/main.zig | 5 +++++ 2 files changed, 18 insertions(+), 1 deletion(-) (limited to 'src/main.zig') diff --git a/src/macos.zig b/src/macos.zig index 3ff8bdfa..b19c5996 100644 --- a/src/macos.zig +++ b/src/macos.zig @@ -692,8 +692,15 @@ export fn pardes_init(runtime: ?*const Runtime, cols_arg: u16, rows_arg: u16) c_ return 0; } +/// The shell's gpa in a Debug build, as std.start's is for the others. +var debug_gpa: std.heap.DebugAllocator(.{}) = .init; + fn initCore(runtime: ?*const Runtime, cols_arg: u16, rows_arg: u16) !void { - const gpa = std.heap.smp_allocator; + // The allocator every other shell gets from std.start: a DebugAllocator + // in Debug, libc's malloc otherwise. libc's measured at least as fast as + // std.heap.smp_allocator everywhere and faster on MuPDF's page-sized + // rasters, so this shell no longer differs. + const gpa = if (builtin.mode == .Debug) debug_gpa.allocator() else std.heap.c_allocator; const allocs = pardes.memory.init(gpa); errdefer pardes.memory.deinit(); @@ -824,6 +831,11 @@ export fn pardes_deinit() void { st.threaded.deinit(); st.gpa.destroy(st.threaded); pardes.memory.deinit(); + // Leaks are logged and do not fail, as std.start treats the others'. + if (builtin.mode == .Debug) { + _ = debug_gpa.deinit(); + debug_gpa = .init; + } state = null; } diff --git a/src/main.zig b/src/main.zig index 050cee60..86c302fe 100644 --- a/src/main.zig +++ b/src/main.zig @@ -138,6 +138,11 @@ fn webMain() !void { try @import("gui/gui.zig").run(.{}, .{}, null); } +// init.gpa, what the tty, gui and detached shells allocate from, is +// std.start's: a DebugAllocator in Debug and, since we link libc, libc's +// malloc otherwise. Kept on purpose: glibc's malloc was measured at least as +// fast as std.heap.smp_allocator on every scenario and faster on MuPDF's +// page-sized rasters. macos.zig makes the same choice for itself. fn nativeMain(init: std.process.Init) !void { var stderr_probe: [64]u8 = undefined; _ = std.debug.lockStderr(&stderr_probe); -- cgit v1.3 From 2d0c506583d18d6f004fc117282deb2faea1d17e Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Tue, 29 Sep 2026 10:30:38 -0300 Subject: Recent lists the files opened lately, closed ones too, and a jump back to a closed file reopens it A file closed by accident, its path forgotten, could not be found again: the jumplist dropped closed panes. Every file opened (a look, a Save of a scratch, a Restore, a rename) goes first in a list of 200, kept once, its dot noted when it closes, kept across sessions in $XDG_STATE_HOME/pardes/ recent. `Recent` (SPC f r) shows it in a reused +Recent, each row `path:line:col open|closed` a look reopens; /recent reads `open|closed `. The jumplist keeps a closed file's entries, +Jumps marks them `(closed)`, and Back to one opens the file at its place. acme has no such thing; its dump and Load are the nearest. Co-Authored-By: Claude Opus 5.5 --- .agents/skills/pardes-9p/SKILL.md | 2 + README.md | 19 ++++++ docs/fs.md | 5 ++ docs/helix-keys.md | 2 +- src/Output.zig | 49 ++++++++++++++++ src/builtins.zig | 10 ++++ src/config.zig | 2 + src/fs-help.txt | 4 +- src/main.zig | 16 +++++ src/ninep/ctl.zig | 54 +++++++++++++++++ src/ninep/events.zig | 2 + src/ninep/pane.zig | 1 + src/ninep/tree.zig | 31 +++++++--- src/pardes.zig | 104 ++++++++++++++++++++++++++++++++- src/recent.zig | 119 ++++++++++++++++++++++++++++++++++++++ test/fs.py | 28 ++++++++- 16 files changed, 434 insertions(+), 14 deletions(-) create mode 100644 src/recent.zig (limited to 'src/main.zig') diff --git a/.agents/skills/pardes-9p/SKILL.md b/.agents/skills/pardes-9p/SKILL.md index 0575fab7..4678d55a 100644 --- a/.agents/skills/pardes-9p/SKILL.md +++ b/.agents/skills/pardes-9p/SKILL.md @@ -96,6 +96,8 @@ $m/ctl the settings, one a line as a write takes them; write a setting or column word Delcol, which closes that pane's column) go to $m/pane//ctl $m/commands every builtin: `Word`, `Word arg`, then `root`, `pane` or `both` (which ctl takes it), a setting's values comma-joined, then ` -- ` and one sentence of what it does +$m/recent files opened lately, closed ones too, most recent first: `open|closed `; + lost a file you closed? read this, or run Recent and look at its row to reopen it $m/layout one line per column (16 columns at most: Newcol past that fails, no space for a column): serial index x width current|notcurrent empty|full pane-serials...; active $m/tag the workspace tag (> replaces, >> appends, one line); $m/col//tag a column's (serials stay, as panes' do) $m/tagexec a word as a click in the workspace tag (pane//tagexec: in that pane's tag); every exec diff --git a/README.md b/README.md index 49ecfa4d..826f86c8 100644 --- a/README.md +++ b/README.md @@ -103,6 +103,25 @@ pane shells outlive every frontend; a frontend keeps only what needs the human's own display. From inside the editor, `Attach` and `Detach` do the same thing as words. See `docs/detached.md`. +## Recent files + +A file closed by accident is found again. `Recent` (`SPC f r`) lists the +files opened lately, most recent first, closed ones too, each marked `open` +or `closed` at the place its dot was when it closed: + +``` +/home/me/src/main.zig:120:5 closed +/home/me/notes.txt open +``` + +A look at a row opens that file there. The list keeps 200 files, each once, +and lasts across sessions in `$XDG_STATE_HOME/pardes/recent` (else +`~/.local/state/pardes/recent`). The jumplist keeps a closed file's entries +too: `Back` to one opens the file again at its place, and `+Jumps` marks it +`(closed)`. Over 9P, `/recent` reads `open ` or `closed ` a line. +acme has nothing like it (its dump and Load are the nearest); pardes goes +beyond acme here. + ## Tests ``` diff --git a/docs/fs.md b/docs/fs.md index a0b3dcf7..dedfe94f 100644 --- a/docs/fs.md +++ b/docs/fs.md @@ -125,6 +125,11 @@ Existing Plan9port/v9fs clients need a userspace bridge for QUIC. /commands every builtin: word, `arg` if it takes one, `root`, `pane` or `both` (the ctl that takes it: Edit is both, at the active pane from the root; a pane's word such as Undo or Msg is refused at the root), a setting's values, then ` -- ` and what it does +/recent the files opened lately, closed ones too, most recent first, a line each: + `open ` or `closed ` (read-only; `Recent` shows them in a pane, + a look at a row reopening the file at its last dot; kept across sessions + in $XDG_STATE_HOME/pardes/recent, 200 files; acme has none, its dump and + Load the nearest) /layout one line per column (16 at most; the board 6; Newcol past that fails, `no space for a column: 16 max`, ENOSPC), left to right: serial index x width current|notcurrent (the column with the keyboard now) empty|full pane-serials...; then active diff --git a/docs/helix-keys.md b/docs/helix-keys.md index 8874bf08..5d89ba92 100644 --- a/docs/helix-keys.md +++ b/docs/helix-keys.md @@ -143,7 +143,7 @@ language-backend queries, and the shell pipe. | `gd` `gD` `gy` `gi` `gr` | LSP definition / declaration / type-definition / implementation / references. ONE answer jumps straight there; several fill `+Search`, where n/N walk and Enter opens | in-process ZLS (`src/lsp/lsp_zls.zig`), `.zig` only — on a file the backend does not speak these do nothing at all, with no error row. Ctrl+left-click is the mouse spelling of `gd` | out of corpus | | `]d` `[d` / `]D` `[D` | step the diagnostics list / go to its last or first; if no list is up, asking the backend for one is part of the press | | out of corpus | | `=` | `format_selections` — writes a `- old` / `+ new` diff into `+Lsp` | deliberate divergence: the seam returns ROWS, not edits, so this SHOWS the formatting instead of applying it. Not in the corpus, so there is no waiver to name — the query leaves the core as an effect the headless harness has no shell to perform | out of corpus | -| `Ctrl-o` / `Ctrl-i` | jumplist back / forward (also Mouse4 / Mouse5 in SDL, macOS and web); successful navigation clears selections in both panes and places the cursor at the saved location; raw tty forwards both to the child — the `Back` / `Forward` builtins, also on `SPC j o` / `SPC j i`, with `SPC j l` rendering the stack as a buffer | helix binds both keys (`jump_backward` / `jump_forward`) but to a POSITION jumplist; pardes' stack is over panes and focus, so the keys agree and the semantics do not. `Ctrl-i` and Tab are the same byte under the legacy encoding; there Tab keeps meaning execute, and the pair only separates where the host speaks the kitty keyboard protocol | pardes-specific | +| `Ctrl-o` / `Ctrl-i` | jumplist back / forward (also Mouse4 / Mouse5 in SDL, macOS and web); successful navigation clears selections in both panes and places the cursor at the saved location; raw tty forwards both to the child — the `Back` / `Forward` builtins, also on `SPC j o` / `SPC j i`, with `SPC j l` rendering the stack as a buffer; a closed file's entry stays, marked `(closed)`, and a jump to it opens the file again at its place | helix binds both keys (`jump_backward` / `jump_forward`) but to a POSITION jumplist; pardes' stack is over panes and focus, so the keys agree and the semantics do not. `Ctrl-i` and Tab are the same byte under the legacy encoding; there Tab keeps meaning execute, and the pair only separates where the host speaks the kitty keyboard protocol | pardes-specific | | `\|` | pipe every selection through `/bin/sh -c`: its bytes in on stdin, its stdout replacing them, one undo across all cursors | helix's own key and meaning; the command is typed into the pane's tag after a bare `\|` marker rather than into a popup | out of corpus | | `A-\|` | the same, and the output is DISCARDED — the text is not touched at all | helix `shell_pipe_to`. For a command run for its effect. Marker `\|-` | out of corpus | | `!` | run with NO stdin, insert the output BEFORE each selection | helix `shell_insert_output`. Runs ONCE and every cursor gets that one answer, as helix does — ten cursors and `date` give ten identical stamps. Marker `!` | out of corpus | diff --git a/src/Output.zig b/src/Output.zig index 37d25168..dd6ab92a 100644 --- a/src/Output.zig +++ b/src/Output.zig @@ -505,6 +505,12 @@ pub fn openJumps(p: *Pardes, id: usize) !void { var out: std.Io.Writer.Allocating = .init(p.gpa); errdefer out.deinit(); for (p.jumps[0..p.njumps]) |j| { + // A closed file's entry: marked, and a look at it opens it again. + if (j.serial == 0) { + const e = p.recentByHash(j.path_hash) orelse continue; + try out.writer.print("{s}:{d}:{d} (closed)\n", .{ e.path, @max(1, j.line), @max(1, j.col) }); + continue; + } const jp = p.panes[j.pane] orelse continue; var idbuf: [16]u8 = undefined; const pdf_path: ?[]const u8 = if (comptime pardes.pdf_enabled) jp.pdfPath() else null; @@ -532,6 +538,49 @@ pub fn openJumps(p: *Pardes, id: usize) !void { try openStepped(p, id, .{ .cmd = .Jumplist }, content); } +/// The recent list as rows: `:: open|closed`, most recent +/// first; a look at a row opens the file there, as a +Jumps row does. +pub fn recentText(p: *Pardes, w: *std.Io.Writer, look_rows: bool) !void { + for (p.recent.entries.items) |e| { + var is_open = false; + for (p.panes) |slot| if (slot) |pane| if (pane.file) |f| if (f.output == null and std.mem.eql(u8, f.path, e.path)) { + is_open = true; + }; + const state: []const u8 = if (is_open) "open" else "closed"; + if (!look_rows) + try w.print("{s} {s}\n", .{ state, e.path }) + else if (e.line == 0) + try w.print("{s} {s}\n", .{ e.path, state }) + else + try w.print("{s}:{d}:{d} {s}\n", .{ e.path, e.line, e.col, state }); + } +} + +/// Recent: the one +Recent, filled again when it is there (as Find and +/// Grep's +Search is), else opened below the asking pane. +pub fn openRecent(p: *Pardes, id: usize) !void { + var out: std.Io.Writer.Allocating = .init(p.gpa); + errdefer out.deinit(); + try recentText(p, &out.writer, true); + const content = try out.toOwnedSlice(); + for (p.panes, 0..) |slot, i| { + const rp = slot orelse continue; + const rf = if (rp.file) |*f| f else continue; + const o = rf.output orelse continue; + if (!std.meta.eql(o.from, Origin{ .cmd = .Recent })) continue; + File.setContent(p, rf, content); + resetBody(p, rp); + p.fs.refilled = rp.serial; + if (p.panes[id]) |pane| { + pane.search_pane = i; + pane.search_row = null; + } + look.armLookWalk(p, i); + return; + } + try openStepped(p, id, .{ .cmd = .Recent }, content); +} + pub fn openThemes(p: *Pardes, id: usize) !void { var out: std.Io.Writer.Allocating = .init(p.gpa); errdefer out.deinit(); diff --git a/src/builtins.zig b/src/builtins.zig index 7fdf2176..2247fcbb 100644 --- a/src/builtins.zig +++ b/src/builtins.zig @@ -1447,6 +1447,7 @@ pub const Last = struct { while (i > 0) { i -= 1; const j = c.p.jumps[i]; + if (j.serial == 0) continue; // a closed file's: Back reopens it, Last goes to a pane // Restore the cursor without recentering the pane's retained view. if (j.pane != c.id) return look.focusPaneLine(c.p, j.pane, .{ .line = j.line, .col = j.col }, .keep); } @@ -1456,6 +1457,15 @@ pub const Last = struct { } }; +/// List the files opened lately, closed ones too, each a place to open again. +pub const Recent = struct { + pub const scope: Scope = .session; + pub const output: OutputTraits = .{ .name = config.recent_buffer, .steps = true, .locations = true }; + pub fn run(c: Ctx) void { + panes.Output.openRecent(c.p, c.id) catch |err| c.p.reportError(c.id, "recent", err); + } +}; + /// List the places jumped from, each a place to go. pub const Jumplist = struct { pub const scope: Scope = .session; diff --git a/src/config.zig b/src/config.zig index 229c70ea..c7ea5411 100644 --- a/src/config.zig +++ b/src/config.zig @@ -65,6 +65,7 @@ pub const leader_path = paths: { .New = "fn", .Tty = "nt", .Find = "ff", + .Recent = "fr", .Grep = "fg", .Config = "fc", .LocationsConfig = null, @@ -448,6 +449,7 @@ pub const help_buffer = "+Help"; pub const config_buffer = "+Config"; pub const effect_code_buffer = "+EffectCode"; pub const jumps_buffer = "+Jumps"; +pub const recent_buffer = "+Recent"; pub const themes_buffer = "+Themes"; pub const fonts_buffer = "+Fonts"; pub const pdf_sections_buffer = "+PdfSections"; diff --git a/src/fs-help.txt b/src/fs-help.txt index bd822b60..62d4ae48 100644 --- a/src/fs-help.txt +++ b/src/fs-help.txt @@ -11,11 +11,11 @@ listeners the session's dial addresses focus the serial of the pane with the keyboard (empty on a column tag); write a serial to give it the keyboard ctl settings a line; or Newcol, Dump, Restore [f], Exit (asks once), Kill [w], Placement acme|pardes, size C R (--detach) commands every builtin: word, arg if it takes one, root|pane|both (the ctl that takes it), -- what it does +recent files opened lately, closed ones too, most recent first: open|closed layout a line per column: serial index x width current|notcurrent empty|full pane-serials; active tag the workspace tag, tagexec a word as a click in it; col// a column's tag, ctl (Delcol Joincol New Tty), exec; rmdir: empty only pane/new open it to make a pane (/+New) in the active column, filling it if empty; the read answers its serial -pane// name body tag ctl addr dot limit data xdata sel dirty mark scroll errors (write-only: - appended to its directory's +Errors pane) event look exec tagexec, pty/ on terminals; rmdir closes +pane// name body tag ctl addr dot limit data xdata sel dirty mark scroll errors (write-only, to +Errors) event look exec tagexec, pty/ on terminals; rmdir closes os/, src/ the host filesystem; the editor's own sources $m below: $NINE_MOUNT/pardes/; $NINE_MOUNT under 9ns --unix; PARDES_MOUNT in a Tty9p shell. diff --git a/src/main.zig b/src/main.zig index 86c302fe..b784ec97 100644 --- a/src/main.zig +++ b/src/main.zig @@ -369,6 +369,7 @@ fn nativeMain(init: std.process.Init) !void { opts.startup_config = found.bytes; opts.startup_config_path = found.path; opts.config_dir = found.dir; + opts.recent_path = recentPath(init.io, arena, init.environ_map); if (found.dir) |d| @import("crash.zig").setDir(d); if (detach) |name| { const named = if (name.len != 0) @@ -427,3 +428,18 @@ test { if (comptime pardes.platform == .gui) _ = @import("gui/gui.zig"); if (comptime pardes.font_picker) _ = @import("fonts.zig"); } + +/// Where the list of files opened lately is kept: $XDG_STATE_HOME/pardes +/// /recent, else ~/.local/state/pardes/recent, the directory made if need +/// be; null with no home to keep it in (the list then lasts the session). +fn recentPath(io: std.Io, arena: std.mem.Allocator, env: *const std.process.Environ.Map) ?[]const u8 { + const dir = dir: { + if (env.get("XDG_STATE_HOME")) |base| if (base.len != 0 and std.fs.path.isAbsolute(base)) + break :dir std.fs.path.join(arena, &.{ base, "pardes" }) catch return null; + const home = env.get("HOME") orelse return null; + if (home.len == 0) return null; + break :dir std.fs.path.join(arena, &.{ home, ".local", "state", "pardes" }) catch return null; + }; + std.Io.Dir.cwd().createDirPath(io, dir) catch return null; + return std.fs.path.join(arena, &.{ dir, "recent" }) catch null; +} diff --git a/src/ninep/ctl.zig b/src/ninep/ctl.zig index 6631e5f9..22a0923b 100644 --- a/src/ninep/ctl.zig +++ b/src/ninep/ctl.zig @@ -2106,6 +2106,60 @@ test "a column takes panes until their documented minimums fill it, not until no } } +test "a closed file is found again: Recent and /recent list it closed, a look at its row reopens it at its dot, and a jump back does too" { + const p = try withFile(testing.allocator, "x\n"); + defer p.deinit(); + var tmp = testing.tmpDir(.{}); + defer tmp.cleanup(); + try tmp.dir.writeFile(testing.io, .{ .sub_path = "a.txt", .data = "one\ntwo\nthree\n" }); + try tmp.dir.writeFile(testing.io, .{ .sub_path = "b.txt", .data = "bee\n" }); + var dir_buf: [4096]u8 = undefined; + const dir = dir_buf[0..try tmp.dir.realPath(testing.io, &dir_buf)]; + var line: [4200]u8 = undefined; + const a_path = try std.fmt.bufPrint(&line, "{s}/a.txt", .{dir}); + var a_buf: [4200]u8 = undefined; + const a = a_buf[0..a_path.len]; + @memcpy(a, a_path); + // Opened, its dot on line 3, then closed. + try testing.expectEqual(Status.ok, wr(p, root_look, try std.fmt.bufPrint(&line, "{s}:3\n", .{a})).reply.status); + p.sync(); + const opened = p.active; + try testing.expectEqualStrings(a, p.panes[opened].?.file.?.path); + var want: [4300]u8 = undefined; + try testing.expect(std.mem.indexOf(u8, rd(p, @intFromEnum(tree.TopFile.recent), 0, 8192).bytes, try std.fmt.bufPrint(&want, "open {s}\n", .{a})) != null); + // Another file, so the jumplist has somewhere to come back from. + try testing.expectEqual(Status.ok, wr(p, root_look, try std.fmt.bufPrint(&line, "{s}/b.txt\n", .{dir})).reply.status); + p.sync(); + try testing.expectEqual(Status.ok, wr(p, Node.of(p.panes[opened].?.serial, .ctl), "Del\n").reply.status); + p.sync(); + try testing.expect(std.mem.indexOf(u8, rd(p, @intFromEnum(tree.TopFile.recent), 0, 8192).bytes, try std.fmt.bufPrint(&want, "closed {s}\n", .{a})) != null); + // Recent lists it, closed, at its dot; a look at the row opens it there. + try testing.expectEqual(Status.ok, wr(p, root_exec, "Recent\n").reply.status); + const rows = p.panes[p.paneBySerial(try std.fmt.parseInt(u32, std.mem.trimEnd(u8, rd(p, root_exec, 0, 64).bytes, "\n"), 10)).?].?; + const at = std.mem.indexOf(u8, rows.file.?.content, try std.fmt.bufPrint(&want, "{s}:3:", .{a})).?; + const row = rows.file.?.content[at .. std.mem.indexOfScalarPos(u8, rows.file.?.content, at, '\n').?]; + try testing.expect(std.mem.endsWith(u8, row, " closed")); + try testing.expectEqual(Status.ok, wr(p, Node.of(rows.serial, .look), try std.fmt.bufPrint(&line, "{s}\n", .{row[0 .. row.len - " closed".len]})).reply.status); + p.sync(); + const back = p.panes[p.active].?; + try testing.expectEqualStrings(a, back.file.?.path); + try testing.expectEqual(@as(i32, 2), back.body.cur_row); + // Closed again; the jumplist keeps its entry, closed, and a jump back + // to it opens it again. + _ = wr(p, Node.of(back.serial, .ctl), "Del\n"); + p.sync(); + var closed_entry = false; + for (p.jumps[0..p.njumps]) |j| closed_entry = closed_entry or j.serial == 0; + try testing.expect(closed_entry); + var tries: usize = 0; + while (tries < p.njumps) : (tries += 1) { + p.jumpBy(-1); + p.sync(); + if (p.panes[p.active].?.file) |f| if (std.mem.eql(u8, f.path, a)) break; + } + try testing.expectEqualStrings(a, p.panes[p.active].?.file.?.path); +} + test "size is monotonic: growing is never refused, and a size once taken is taken again" { const p = try Pardes.init(testing.allocator, .{ .tty_only = true, .cols = 160, .rows = 60 }); defer p.deinit(); diff --git a/src/ninep/events.zig b/src/ninep/events.zig index 868364a6..690efbe5 100644 --- a/src/ninep/events.zig +++ b/src/ninep/events.zig @@ -140,6 +140,8 @@ pub fn announce(p: *Pardes) void { if (!pane.fs.unannounced) continue; pane.fs.unannounced = false; noteLog(p, .new, pane); + // A file opened (a look, a Restore, a boot): first in Recent. + if (pane.file) |f| if (f.output == null) p.recent.opened(p.recentGpa(), f.path); } } diff --git a/src/ninep/pane.zig b/src/ninep/pane.zig index 1148041a..4370d401 100644 --- a/src/ninep/pane.zig +++ b/src/ninep/pane.zig @@ -683,6 +683,7 @@ pub fn nameBuffer(p: *Pardes, id: usize, full: []const u8, preserve_tag: bool) ! look.invalidateLookHover(p, id); p.emit(.{ .watch = .{ .pane = @intCast(id), .on = false } }); events.noteLog(p, .rename, pane); + if (f.output == null) p.recent.opened(p.recentGpa(), f.path); } /// Diagnostics go to the +Errors buffer of the pane's directory. diff --git a/src/ninep/tree.zig b/src/ninep/tree.zig index 9d2027bf..64089c01 100644 --- a/src/ninep/tree.zig +++ b/src/ninep/tree.zig @@ -219,6 +219,9 @@ pub const TopFile = enum(u5) { tag, col, tagexec, + /// The files opened lately, closed ones too, a line each: + /// `open|closed `, most recent first. + recent, pub fn fileName(f: TopFile) []const u8 { return if (f == .root) "/" else @tagName(f); @@ -228,7 +231,7 @@ pub const TopFile = enum(u5) { return switch (f) { .root, .pane, .col => 0o755, .look, .exec, .log, .focus, .ctl, .tag, .tagexec => 0o666, - .README, .index, .status, .screen, .listeners, .new, .commands, .layout => 0o444, + .README, .index, .status, .screen, .listeners, .new, .commands, .layout, .recent => 0o444, }; } @@ -239,6 +242,13 @@ pub const TopFile = enum(u5) { pub const root: u64 = @intFromEnum(TopFile.root); +fn recentLen(p: *Pardes) u64 { + var buf: [64]u8 = undefined; + var counting: std.Io.Writer.Discarding = .init(&buf); + pardes.panes.Output.recentText(p, &counting.writer, false) catch return 0; + return counting.fullCount(); +} + /// Declaration order is readdir order. pub const PaneFile = enum(u5) { dir = 0, @@ -556,6 +566,7 @@ fn topSize(p: *Pardes, f: TopFile) u64 { }, .ctl => ctl.rootLen(p), .commands => ctl.commandsLen(), + .recent => recentLen(p), .focus => focus: { if (p.header_focus) break :focus 0; const pn = p.panes[p.active] orelse break :focus 0; @@ -653,7 +664,7 @@ fn readdir(p: *Pardes, req: Req, target: Target) Reply { .root => { // The guide, then what describes the session, then the // files that act, then the directories. - inline for (.{ TopFile.README, TopFile.index, TopFile.status, TopFile.focus, TopFile.ctl, TopFile.commands, TopFile.look, TopFile.exec, TopFile.log, TopFile.screen, TopFile.listeners, TopFile.layout, TopFile.tag, TopFile.tagexec, TopFile.pane, TopFile.col }) |t| { + inline for (.{ TopFile.README, TopFile.index, TopFile.status, TopFile.focus, TopFile.ctl, TopFile.commands, TopFile.recent, TopFile.look, TopFile.exec, TopFile.log, TopFile.screen, TopFile.listeners, TopFile.layout, TopFile.tag, TopFile.tagexec, TopFile.pane, TopFile.col }) |t| { if (skip > 0) skip -= 1 else stageDirent(out, p.gpa, @intFromEnum(t), t.dir(), t.fileName()); } if (skip > 0) skip -= 1 else stageDirent(out, p.gpa, fs.os_root, true, "os"); @@ -933,6 +944,12 @@ fn readFile(p: *Pardes, req: Req, target: Target) Reply { .focus => ctl.readFocus(p, req), .ctl => ctl.readRoot(p, req), .commands => ctl.readCommands(p, req), + .recent => recent: { + var text: std.Io.Writer.Allocating = .init(p.scratch.allocator()); + pardes.panes.Output.recentText(p, &text.writer, false) catch break :recent Reply.fail(req.tag, E.NOMEM); + p.fs.stage(p.gpa).appendSlice(p.gpa, text.written()) catch break :recent Reply.fail(req.tag, E.NOMEM); + break :recent stagedReply(p, req); + }, .layout => layout: { var text: std.Io.Writer.Allocating = .init(p.scratch.allocator()); cols.writeLayout(p, &text.writer) catch break :layout Reply.fail(req.tag, E.NOMEM); @@ -1201,13 +1218,13 @@ test "readdir lists the root and a pane directory without creating anything" { @memcpy(top_bytes[0..top_reply.bytes.len], top_reply.bytes); const top = th.dirents(top_bytes[0..top_reply.bytes.len], &buf); try testing.expect(top.len >= 10); - for ([_][]const u8{ "README", "index", "status", "focus", "ctl", "commands", "look", "exec", "log", "screen", "listeners", "layout", "tag", "tagexec", "pane", "col", "os" }, 0..) |name, i| { + for ([_][]const u8{ "README", "index", "status", "focus", "ctl", "commands", "recent", "look", "exec", "log", "screen", "listeners", "layout", "tag", "tagexec", "pane", "col", "os" }, 0..) |name, i| { try testing.expectEqualStrings(name, top[i].name); - try testing.expectEqual(i >= 14, top[i].dir); + try testing.expectEqual(i >= 15, top[i].dir); } - try testing.expectEqual(@intFromEnum(TopFile.pane), top[14].node); - try testing.expectEqual(@intFromEnum(TopFile.col), top[15].node); - try testing.expectEqual(fs.os_root, top[16].node); + try testing.expectEqual(@intFromEnum(TopFile.pane), top[15].node); + try testing.expectEqual(@intFromEnum(TopFile.col), top[16].node); + try testing.expectEqual(fs.os_root, top[17].node); var idbuf: [16]u8 = undefined; try testing.expect(th.nameAt(top, try std.fmt.bufPrint(&idbuf, "{d}", .{serial})) == null); try testing.expect(th.nameAt(top, "self") == null); diff --git a/src/pardes.zig b/src/pardes.zig index f7aee16c..33aff840 100644 --- a/src/pardes.zig +++ b/src/pardes.zig @@ -14,6 +14,7 @@ const tracy = @import("tracy.zig"); pub const panes = @import("panes.zig"); pub const tagline = @import("tagline.zig"); pub const exec = @import("exec.zig"); +const recent_files = @import("recent.zig"); pub const mouse = @import("mouse.zig"); pub const normal = @import("normal.zig"); pub const edit = @import("edit.zig"); @@ -447,11 +448,17 @@ test "a compact tagline anchors at its own pane, and both shells step from the s try std.testing.expectEqual(@as(u16, 3), gridColAt(p, 3.5 * body_w, body_row, body_w, tag_w)); } +const recent_path_cap = limits.host_path_cap; + pub const Loc = struct { pane: u16, + /// 0 once its pane has closed: a file's entry stays, reopened by a + /// jump to it from `path_hash`'s recent entry. serial: u32, line: u32, col: u32, + /// The file it is in (Wyhash of the path), 0 for a pane with none. + path_hash: u64 = 0, }; test { @@ -474,6 +481,7 @@ test { _ = @import("draw.zig"); _ = @import("tag_layer.zig"); _ = @import("dump.zig"); // its tests ran nowhere before + _ = @import("recent.zig"); _ = @import("Presentation.zig"); _ = @import("animation.zig"); } @@ -4232,6 +4240,10 @@ pub const Options = struct { ninep_quic: ?[]const u8 = null, mounts: []const filesystem.Mount = &.{}, config_dir: ?[]const u8 = null, + /// Where the list of files opened lately is kept across sessions + /// (recent.zig), set by the host that has a state directory; none, it + /// lives as long as the session. + recent_path: ?[]const u8 = null, startup_config_path: ?[]const u8 = null, image_allocator: ?std.mem.Allocator = null, pdf_allocator: ?std.mem.Allocator = null, @@ -4298,6 +4310,12 @@ pub const Pardes = struct { presentation: Presentation = .{}, active: usize = 0, + /// The files opened lately, closed ones too (recent.zig): `Recent`, + /// /recent, and the jumplist's way back to a closed pane. + recent: recent_files.List = .{}, + /// The kept list was read (or there was none): only then is it written, + /// so a session never writes over one it did not read. + recent_loaded: bool = false, jumps: [MAX_JUMPS]Loc = undefined, njumps: usize = 0, jcur: usize = 0, @@ -4621,6 +4639,7 @@ pub const Pardes = struct { }, } p.sync(); + p.loadRecent(); exec.applyStartupConfig(p); colors.finishThemeInitialization(p); p.sync(); @@ -4641,7 +4660,58 @@ pub const Pardes = struct { p.col_panes[0][0] = 0; } + /// The recent list's own allocator: it is kept best effort (a file not + /// remembered for want of memory is no failure of what opened it), so + /// on a host it takes from the process heap, not the editor's, whose + /// every failure must be answered. + // ponytail: a host heap for a best-effort list; the board's gpa there. + pub fn recentGpa(p: *const Pardes) std.mem.Allocator { + return if (comptime hosted) std.heap.smp_allocator else p.gpa; + } + + /// The kept list of files opened lately, read once at start. + fn loadRecent(p: *Pardes) void { + const path = p.opts.recent_path orelse return; + if (comptime !hosted) return; + defer p.recent_loaded = true; + const bytes = filesystem.readFile(p.gpa, path) catch return; + defer p.gpa.free(bytes); + p.recent.read(p.recentGpa(), bytes); + } + + /// Written out when it changed, at the end of a step and at the end. + pub fn saveRecent(p: *Pardes) void { + if (!p.recent.dirty) return; + p.recent.dirty = false; + const path = p.opts.recent_path orelse return; + if (comptime !hosted) return; + if (!p.recent_loaded) return; + var out: std.Io.Writer.Allocating = .init(p.gpa); + defer out.deinit(); + p.recent.write(&out.writer) catch return; + turn.yield(); + defer turn.back(); + std.Io.Dir.cwd().writeFile(std.Io.Threaded.global_single_threaded.io(), .{ .sub_path = path, .data = out.written() }) catch {}; + } + + /// A file pane's path and dot, for the recent list (0 when none). + fn recentDot(pane: *const Pane) ?struct { path: []const u8, line: u32, col: u32 } { + const f = pane.file orelse return null; + if (f.output != null) return null; + return .{ .path = f.path, .line = @intCast(@max(0, pane.body.cur_row) + 1), .col = @intCast(@max(0, pane.body.cur_col) + 1) }; + } + + /// The recent entry a closed jump names, by its path's hash. + pub fn recentByHash(p: *const Pardes, hash: u64) ?recent_files.Entry { + for (p.recent.entries.items) |e| if (std.hash.Wyhash.hash(0, e.path) == hash) return e; + return null; + } + pub fn deinit(p: *Pardes) void { + // Every file open now is closed with its dot, and the list kept. + for (p.panes) |slot| if (slot) |pane| if (recentDot(pane)) |d| p.recent.closed(p.recentGpa(), d.path, d.line, d.col); + p.saveRecent(); + p.recent.deinit(p.recentGpa()); look.cancelLookHover(p); if (p.repl_ask) |ask| p.gpa.free(ask.text); for (0..MAX_PANES) |id| p.dropPendingWrite(id); @@ -4750,6 +4820,9 @@ pub const Pardes = struct { } fn retirePane(p: *Pardes, pane: *Pane) void { + // Closed, a file is remembered with its dot: Recent and a jump back + // to it reopen it there. + if (recentDot(pane)) |d| p.recent.closed(p.recentGpa(), d.path, d.line, d.col); const watched = (if (pane.file) |f| f.output == null else false) or pane.hasPdf(); for (p.panes, 0..) |slot, id| if (slot == pane) { if (watched) p.emit(.{ .watch = .{ .pane = @intCast(id), .on = false } }); @@ -5240,6 +5313,7 @@ pub const Pardes = struct { f.saved_revision = f.revision; f.disk_gone = false; ctlfs.events.noteLog(p, .save, pane); + p.recent.opened(p.recentGpa(), f.path); if (filesystem.localPath(f.path) != null) p.emit(.{ .watch = .{ .pane = id, .on = true } }); } @@ -6562,9 +6636,15 @@ pub const Pardes = struct { var cur: usize = 0; for (p.jumps[0..p.njumps], 0..) |j, i| { if (i == p.jcur) cur = w; // survives -> lands at w; dies -> the next one does - const pane = p.panes[j.pane] orelse continue; - if (pane.serial != j.serial) continue; - p.jumps[w] = j; + var kept = j; + const live = if (j.serial == 0) false else if (p.panes[j.pane]) |pane| pane.serial == j.serial else false; + // A file's pane closed: its entry stays, closed, while the recent + // list knows the file, and a jump to it opens it again. + if (!live) { + if (j.path_hash == 0 or p.recentByHash(j.path_hash) == null) continue; + kept.serial = 0; + } + p.jumps[w] = kept; w += 1; } p.njumps = w; @@ -6576,6 +6656,7 @@ pub const Pardes = struct { .serial = pane.serial, .line = if (pane.pdfPage()) |page| @intCast(page + 1) else if (pane.body.cur_pinned) @intCast(@max(0, pane.body.cur_row) + 1) else 0, .col = if (pane.pdfPage() != null) 0 else if (pane.body.cur_pinned) @intCast(@max(0, pane.body.cur_col) + 1) else 0, + .path_hash = if (recentDot(pane)) |d| std.hash.Wyhash.hash(0, d.path) else 0, }; if (p.njumps > 0 and p.samePlace(p.jumps[p.jcur], now)) { p.jumps[p.jcur] = now; // same visit; the entry IS where you are @@ -6604,6 +6685,21 @@ pub const Pardes = struct { if (p.njumps == 0 or next < 0 or next >= p.njumps) return; const j = p.jumps[@intCast(next)]; if (j.pane >= MAX_PANES) return; + // A closed file's entry: opened again at its dot, placed as a look + // places it, and the entry is that pane from here on. + if (j.serial == 0) { + const e = p.recentByHash(j.path_hash) orelse return; + var where: [recent_path_cap + 32]u8 = undefined; + const loc = std.fmt.bufPrint(&where, "{s}:{d}:{d}", .{ e.path, @max(1, j.line), @max(1, j.col) }) catch return; + const from = p.active; + look.lookAt(p, from, loc); + const opened = p.panes[p.active] orelse return; + if (p.active == from) return; + p.jumps[@intCast(next)].pane = @intCast(p.active); + p.jumps[@intCast(next)].serial = opened.serial; + p.jcur = @intCast(next); + return; + } const pane = p.panes[j.pane] orelse return; if (pane.serial != j.serial) return; if (p.panes[p.active]) |source| look.clearNavigationSelection(p, source); @@ -6640,6 +6736,8 @@ pub const Pardes = struct { if (refused) for (0..p.ncol) |c| if (!layout.columnAtMinimums(p, c)) { _ = layout.shareColumn(p, c); }; + // A file opened or closed this step: the kept list follows. + p.saveRecent(); tagline.flattenHeaders(p); if (p.header_column != null and p.columnBarHeight() == 0) { tagline.exitHeader(p); diff --git a/src/recent.zig b/src/recent.zig new file mode 100644 index 00000000..b6a1a66a --- /dev/null +++ b/src/recent.zig @@ -0,0 +1,119 @@ +//! The files opened lately, most recent first, those since closed too, as +//! `Recent` lists them and a jump to a closed pane reopens them: a path +//! and where the dot was when it closed. Kept across sessions in a small +//! file under $XDG_STATE_HOME/pardes (Options.recent_path) when the host +//! gives one. acme has nothing like it (its dump and Load are the nearest): +//! a file closed by accident, its path forgotten, is found here again. + +const std = @import("std"); + +/// At most this many files are remembered, the oldest dropped first. +pub const cap = 200; + +pub const Entry = struct { + path: []u8, + /// Where its dot was when it last closed (1-based; 0 none). + line: u32 = 0, + col: u32 = 0, +}; + +pub const List = struct { + entries: std.ArrayList(Entry) = .empty, + /// Changed since it was last written out. + dirty: bool = false, + + pub fn deinit(l: *List, gpa: std.mem.Allocator) void { + for (l.entries.items) |e| gpa.free(e.path); + l.entries.deinit(gpa); + } + + fn find(l: *const List, path: []const u8) ?usize { + for (l.entries.items, 0..) |e, i| if (std.mem.eql(u8, e.path, path)) return i; + return null; + } + + /// `path` opened: first in the list, once, keeping the dot it closed at. + pub fn opened(l: *List, gpa: std.mem.Allocator, path: []const u8) void { + if (path.len == 0) return; + var entry: Entry = if (l.find(path)) |i| l.entries.orderedRemove(i) else .{ + .path = gpa.dupe(u8, path) catch return, + }; + if (l.entries.items.len >= cap) { + const last = l.entries.pop().?; + gpa.free(last.path); + } + l.entries.insert(gpa, 0, entry) catch { + gpa.free(entry.path); + entry = undefined; + return; + }; + l.dirty = true; + } + + /// `path` closed with its dot at `line`:`col`: where a reopen lands. + /// Its place in the list is its opening's. + pub fn closed(l: *List, gpa: std.mem.Allocator, path: []const u8, line: u32, col: u32) void { + const i = l.find(path) orelse found: { + l.opened(gpa, path); + // Out of memory for it: nothing to note the dot on. + break :found l.find(path) orelse return; + }; + l.entries.items[i].line = line; + l.entries.items[i].col = col; + l.dirty = true; + } + + pub fn get(l: *const List, path: []const u8) ?Entry { + return l.entries.items[l.find(path) orelse return null]; + } + + /// One line a file, ` `, most recent first. + pub fn write(l: *const List, w: *std.Io.Writer) !void { + for (l.entries.items) |e| try w.print("{d} {d} {s}\n", .{ e.line, e.col, e.path }); + } + + /// The lines `write` wrote; a line that is not one is passed over. + pub fn read(l: *List, gpa: std.mem.Allocator, bytes: []const u8) void { + var lines = std.mem.splitScalar(u8, bytes, '\n'); + while (lines.next()) |line| { + if (l.entries.items.len >= cap) break; + var it = std.mem.splitScalar(u8, line, ' '); + const ln = std.fmt.parseInt(u32, it.next() orelse continue, 10) catch continue; + const col = std.fmt.parseInt(u32, it.next() orelse continue, 10) catch continue; + const path = it.rest(); + if (path.len == 0 or path[0] != '/' or l.find(path) != null) continue; + const owned = gpa.dupe(u8, path) catch return; + l.entries.append(gpa, .{ .path = owned, .line = ln, .col = col }) catch { + gpa.free(owned); + return; + }; + } + } +}; + +test "the list keeps a path once, most recent first, its dot from closing, capped" { + const gpa = std.testing.allocator; + var l: List = .{}; + defer l.deinit(gpa); + l.opened(gpa, "/a"); + l.opened(gpa, "/b"); + l.closed(gpa, "/a", 7, 3); + l.opened(gpa, "/a"); + try std.testing.expectEqualStrings("/a", l.entries.items[0].path); + try std.testing.expectEqual(@as(usize, 2), l.entries.items.len); + try std.testing.expectEqual(@as(u32, 7), l.get("/a").?.line); + var buf: [256]u8 = undefined; + var w = std.Io.Writer.fixed(&buf); + try l.write(&w); + try std.testing.expectEqualStrings("7 3 /a\n0 0 /b\n", w.buffered()); + var again: List = .{}; + defer again.deinit(gpa); + again.read(gpa, w.buffered()); + again.read(gpa, "junk\n"); + try std.testing.expectEqual(@as(usize, 2), again.entries.items.len); + for (0..cap + 5) |i| { + var name: [16]u8 = undefined; + l.opened(gpa, std.fmt.bufPrint(&name, "/f{d}", .{i}) catch unreachable); + } + try std.testing.expectEqual(@as(usize, cap), l.entries.items.len); +} diff --git a/test/fs.py b/test/fs.py index 20a9bbff..977b3e45 100644 --- a/test/fs.py +++ b/test/fs.py @@ -161,7 +161,7 @@ def discovery(binary, embedded=False): with session(binary, root, 'discovery') as (client, address): top = client.list('/') # A set: which files the root holds, not the order a listing gives. - assert set(top) - {'src', 'shaders'} == {'README', 'index', 'status', 'focus', 'ctl', 'commands', + assert set(top) - {'src', 'shaders'} == {'README', 'index', 'status', 'focus', 'ctl', 'commands', 'recent', 'look', 'exec', 'log', 'screen', 'listeners', 'layout', 'tag', 'tagexec', 'pane', 'col', 'os'}, top assert 'self' not in top and 'cons' not in top and 'new' not in top, top @@ -539,6 +539,31 @@ def new_terminals_named_once(binary): assert str(made[0]).encode() in b' '.join(r.split()[0] for r in client.read('/index').splitlines()) +def recent_survives_restart(binary): + """A file opened and closed is in /recent closed, and still is in the + next session: the list is kept under $XDG_STATE_HOME (here HOME's + .local/state) across restarts.""" + with tempfile.TemporaryDirectory(prefix='pardes-recent-') as directory: + root = Path(directory) + kept = root / 'kept.txt' + kept.write_bytes(b'one\ntwo\n') + with session(binary, root, 'recent1') as (client, _): + serial = look(client, f'{kept}:2') + assert f'open {kept}\n' in client.read('/recent').decode() + client.write(f'/pane/{serial}/ctl', b'Del\n') + assert f'closed {kept}\n' in client.read('/recent').decode(), client.read('/recent') + assert (root / '.local' / 'state' / 'pardes' / 'recent').exists() + with session(binary, root, 'recent2') as (client, _): + listed = client.read('/recent').decode() + assert f'closed {kept}\n' in listed, listed + # Recent shows it, and a look at its row opens it again. + client.write('/pane/1/exec', b'Recent\n') + rows = int(client.read('/pane/1/exec').split()[-1]) + row = next(r for r in client.read(f'/pane/{rows}/body').decode().splitlines() if r.startswith(f'{kept}:')) + client.write(f'/pane/{rows}/look', (row.split(' ')[0] + '\n').encode()) + assert f'open {kept}\n' in client.read('/recent').decode() + + def workflow_canary(binary): """One session driven as the dogfood agents drive it, asserting the log and the read-backs at every step: the canary for the main paths (the @@ -803,6 +828,7 @@ def test(binary, quic=False): unattended_messages_expire(binary) new_terminals_named_once(binary) workflow_canary(binary) + recent_survives_restart(binary) python_repl_runs_one_line(binary) signal_cleans_up(binary) for options, message in [ -- cgit v1.3 From 826ec1fac3c012e71ab34207328faaac5b5827b7 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Tue, 29 Sep 2026 09:43:05 -0300 Subject: Shader files compile again on save; an attached GUI runs the session's post chain shader_build.zig takes the Shadertoy compile out of the GUI's Post: the process that holds the core compiles each chain file behind the prefix on a thread, watches its directory (file_watch's new shader slots), and on a change reads and hashes each file, compiling only one whose bytes moved. A failed compile keeps the last good SPIR-V and is said once; the same bytes are never compiled or reported twice. A file is read with std, not fs.zig's readFile, whose turn hand-off a worker thread does not hold. A detached session compiles for its frontends and sends them the chain (wire post: each pass's scene and level or the file's SPIR-V, and ShaderAnimation) on attach and on every change, so an attached GUI runs the same passes, levels and animation as a local one while still reading no disk and running no program. The attached GUI describes its frames to the chain from the session's chrome and redraws an animating chain on its own. --- build.zig | 5 + docs/config.md | 7 +- docs/render-pipeline.md | 11 +- src/config.zig | 2 +- src/detached/client.zig | 33 +++- src/detached/server.zig | 36 ++++- src/detached/wire.zig | 71 ++++++++- src/file_watch.zig | 13 +- src/gui/Post.zig | 234 ++++------------------------ src/gui/gui.zig | 58 +++++-- src/main.zig | 1 + src/shader_build.zig | 402 ++++++++++++++++++++++++++++++++++++++++++++++++ src/tty/tty.zig | 2 + 13 files changed, 645 insertions(+), 230 deletions(-) create mode 100644 src/shader_build.zig (limited to 'src/main.zig') diff --git a/build.zig b/build.zig index 34acc007..48987edf 100644 --- a/build.zig +++ b/build.zig @@ -842,6 +842,11 @@ pub fn build(b: *std.Build) void { }); } + // A detached session compiles its attached GUIs' Shadertoy files + // (shader_build.zig), whichever shell it was built for. + if (gui_shell_mod != root_mod) + root_mod.addAnonymousImport("post-prefix.glsl", .{ .root_source_file = b.path("shaders/post/prefix.glsl") }); + if (is_web) { const dp = dump_path.?; root_mod.addAnonymousImport("embedded.dump.zon", .{ diff --git a/docs/config.md b/docs/config.md index 189c5382..59883b59 100644 --- a/docs/config.md +++ b/docs/config.md @@ -543,8 +543,11 @@ Crt 3 ``` The SDL GUI runs it as the bundled pass of its post chain, which also takes -Shadertoy files written for ghostty (`Shader ~/crt.glsl`, `Shader off`), and -`ShaderAnimation off|on|always` says when the chain animates on its own. With +Shadertoy files written for ghostty (`Shader ~/crt.glsl`, `Shader off`; +a file compiles again when it is saved, and a save that fails to compile +keeps the last good one and says why), and +`ShaderAnimation off|on|always` says when the chain animates on its own. A +GUI attached to a detached session runs the session's chain the same way. With the chain empty the pass is bypassed. CRT works in linear light with restrained scanlines, mask, bloom and vignette, and no curvature, so clicks land where they are drawn. diff --git a/docs/render-pipeline.md b/docs/render-pipeline.md index b8f735d9..88309d4a 100644 --- a/docs/render-pipeline.md +++ b/docs/render-pipeline.md @@ -501,8 +501,15 @@ Mirror ghostty 1.3.2 (`zig-pkg/ghostty-*/src/renderer/shadertoy.zig`, file, not ``. Level A redraws once a refresh of the window's display. A failed compile keeps the file's last good pipeline and says glslc's first line as a message; glslc missing is said once, and only files stay off (the bundled passes are compiled with the - build, through the same prefix). No file watching: `Shader ` twice - (out, then in) compiles it again. + build, through the same prefix). The files' directories are watched + (file_watch shader slots): a change there has each file read and hashed, + and one whose bytes moved compiles again; the same bytes (good or bad) + compile nothing and say nothing twice. The process that holds the core + compiles (shader_build.zig): a local GUI, or a detached session, which + sends its attached GUIs the chain with each file's SPIR-V (wire `post`, + on attach and on every change), so an attached GUI runs the same passes, + levels and ShaderAnimation as a local one and still reads no disk and runs + no program. - **Animation mode**: `ShaderAnimation off|on|always` (ghostty's `custom-shader-animation`): off = redraw only when content changes; on = continuous while the window is focused; always = continuous. Continuous means diff --git a/src/config.zig b/src/config.zig index 1b432415..86f3e7eb 100644 --- a/src/config.zig +++ b/src/config.zig @@ -1017,7 +1017,7 @@ pub const Runtime = struct { .{ .word = "Bloom", .action = .{ .scene = .bloom }, .availability = .scene_shaders, .doc = "The brightest ink glows a little: a level, 0 (off) through 3." }, .{ .word = "Vignette", .action = .{ .scene = .vignette }, .availability = .scene_shaders, .doc = "The window's corners fall into shade: a level, 0 (off) through 3." }, .{ .word = "Grain", .action = .{ .scene = .grain }, .availability = .scene_shaders, .doc = "The page takes a fine, still grain, like paper: a level, 0 (off) through 3." }, - .{ .word = "Shader", .action = .shader, .availability = .scene_shaders, .doc = "A Shadertoy file into the post chain, or out of it; off empties the chain." }, + .{ .word = "Shader", .action = .shader, .availability = .scene_shaders, .doc = "A Shadertoy file into the post chain, or out of it, compiled again when saved; off empties the chain." }, .{ .word = "ShaderAnimation", .action = .shader_animation, .availability = .scene_shaders, .doc = "When the post chain animates on its own: off, on (while focused) or always." }, .{ .word = "Placement", .action = .{ .choice = .placement }, .doc = "Where a new pane goes: acme, as makenewwindow does, or pardes, the older rules." }, .{ .word = "BootShell", .action = .{ .choice = .boot_shell }, .doc = "A document dropped where a lone untouched shell stands: keep the shell, or replace it." }, diff --git a/src/detached/client.zig b/src/detached/client.zig index 8c9a2560..69ab2fdd 100644 --- a/src/detached/client.zig +++ b/src/detached/client.zig @@ -109,6 +109,10 @@ pub const Client = struct { regions: std.ArrayListUnmanaged(pardes.Region) = .empty, /// The palette its chrome is drawn in, as its last frame gave it. chrome: pardes.Chrome = .{}, + /// The post chain its frames are drawn through, as the session last + /// sent it; its paths and SPIR-V owned here. `post_key` moves with it. + post: wire.Post = .{}, + post_key: u32 = 0, in: std.ArrayListUnmanaged(u8) = .empty, out: std.ArrayListUnmanaged(u8) = .empty, /// Bytes of `in` belonging to the message `next` returned last. Compacted at @@ -187,6 +191,7 @@ pub const Client = struct { } for (&c.tag_layers) |*layer| c.gpa.free(layer.cells); c.regions.deinit(c.gpa); + c.freePost(); c.in.deinit(c.gpa); c.out.deinit(c.gpa); } @@ -356,10 +361,30 @@ pub const Client = struct { // open a URI on this display or read this display's selection back // over the socket. `Ungreeted` is the same refusal a frame gets. .set_clipboard, .read_clipboard, .open_link => if (!c.attached()) return error.Ungreeted, + // Kept, like the chrome: the frames that follow are drawn + // through it. + .post => |chain| { + if (!c.attached()) return error.Ungreeted; + c.freePost(); + c.post = chain; + for (c.post.passes[0..c.post.len]) |*pass| { + pass.path = c.gpa.dupe(u8, pass.path) catch return error.Closed; + pass.spirv = c.gpa.dupe(u8, pass.spirv) catch return error.Closed; + } + c.post_key +%= 1; + }, } return msg; } + fn freePost(c: *Client) void { + for (c.post.passes[0..c.post.len]) |pass| { + c.gpa.free(pass.path); + c.gpa.free(pass.spirv); + } + c.post = .{}; + } + // ---- internals -------------------------------------------------------- fn reshape(c: *Client, cols: u16, rows: u16) (Error || wire.Error)!void { @@ -1131,7 +1156,7 @@ test "detached session: the seam's own routing rules, per surviving effect" { test "detached session: a frontend is never asked to fork, write, or watch" { // THE INVARIANT OF THE WHOLE DETACHED DESIGN, pinned as a property of the // protocol rather than of one code path: a frontend is input and screen, so - // the set of messages that can reach it is exactly the eight below. If a + // the set of messages that can reach it is exactly the nine below. If a // machine-local effect is ever put back on the wire, a frontend becomes the // process that owns a pane's shell again — and a pane whose shell belongs to // a frontend dies when that frontend leaves, which is the bug this replaced. @@ -1149,6 +1174,10 @@ test "detached session: a frontend is never asked to fork, write, or watch" { // The three that need THIS human's display and cannot be done by a // daemon nobody is looking at. "set_clipboard", "read_clipboard", "open_link", + // Display state, like a frame's chrome: the passes this display + // draws its frames through. A file's SPIR-V arrives compiled, so the + // frontend still reads no disk and runs no program. + "post", }; // One: the union a frontend decodes into has no other variant. Named @@ -1183,7 +1212,7 @@ test "detached session: a frontend is never asked to fork, write, or watch" { if (@intFromEnum(want) == tag) break true; } else false; if (!named) { - std.debug.print("tag 0x{x:0>2} is decodable by a frontend and is not one of the seven\n", .{tag}); + std.debug.print("tag 0x{x:0>2} is decodable by a frontend and is not one of the nine\n", .{tag}); return error.MachineLocalEffectOnTheWire; } } diff --git a/src/detached/server.zig b/src/detached/server.zig index 13cf4488..99a2afc2 100644 --- a/src/detached/server.zig +++ b/src/detached/server.zig @@ -11,6 +11,7 @@ const host_io = @import("../host_io.zig"); const selection_pipe = @import("../selection_pipe.zig"); const file_watch = @import("../file_watch.zig"); +const shader_build = @import("../shader_build.zig"); const ninep_io = @import("../9p_io.zig"); @@ -63,6 +64,8 @@ const Client = struct { mirror: std.ArrayListUnmanaged(pardes.Cell) = .empty, need_full: bool = true, accepted_ms: i64 = 0, + /// The post chain last sent (Session.sendPost); null: none yet. + post_sent: ?u64 = null, }; const Pty = struct { @@ -173,6 +176,8 @@ pub const Session = struct { /// the next poll returns at once, to draw it. ninep_wake: std.atomic.Value(bool) = .init(false), watches: file_watch.Table = @splat(null), + /// The post chain's files, compiled here for the GUIs attached. + shaders: shader_build = .{}, check_files: bool = false, in_loop: bool = false, greet_deadline_ms: u32 = greet_deadline_default_ms, @@ -254,6 +259,8 @@ pub const Session = struct { for (0..pardes.MAX_PANES) |pane| file_watch.watchPane(s.inotify_fd, &s.watches, @intCast(pane), null, 0, .{ .text = 0 }); _ = file_watch.applyThemeEffect(s.core, s.gpa, s.inotify_fd, &s.watches, 0, false, false); + // The new core's chain generations are its own. + s.shaders.generation = null; s.check_files = false; if (s.ninep) |listener| listener.reset(replacement); s.ninep_pending = false; @@ -267,6 +274,8 @@ pub const Session = struct { } pub fn deinit(s: *Session) void { + // First: its compile thread wakes the mailbox, closed below. + s.shaders.deinit(s.gpa, s.inotify_fd, &s.watches); if (s.mailbox.wake[0] >= 0) pardes.lsp.setStatusSink(null, null); if (s.mailbox.wake[0] >= 0) host_io.setExitWake(null, null); s.cancelWorkers(); @@ -766,6 +775,7 @@ pub const Session = struct { fn reloadWatched(s: *Session) void { if (!s.check_files) return; s.check_files = false; + s.shaders.recheck(); for (0..reload_retries) |_| { if (!file_watch.reloadChanged(s.core, s.io, s.gpa, &s.watches)) return; } @@ -823,6 +833,8 @@ pub const Session = struct { const completed = s.ninep_wake.swap(false, .acq_rel) or drained; for (&s.clients) |*c| if (c.fd >= 0) s.flush(c); const regridded = s.reconcile(); + // After the greeting reconcile sends: a chain before it is refused. + const compiled = s.sendPost(); // Nobody attached, nobody to dismiss a message: the loop expires // them itself, between the editor's steps (expireUnattended). s.core.unattended = s.primary() == null; @@ -891,7 +903,7 @@ pub const Session = struct { } var timeout: c_int = if (timeout_ms == 0) -1 else @intCast(@min(timeout_ms, std.math.maxInt(c_int))); if (s.nextWake(now)) |due| timeout = if (timeout < 0) due else @min(timeout, due); - if (completed or s.check_files or regridded or s.ninep_pending) timeout = 0; + if (completed or compiled or s.check_files or regridded or s.ninep_pending) timeout = 0; pardes.turn.rest(); const ready = libc.poll(&fds, @intCast(n), timeout); pardes.turn.wake(); @@ -1102,6 +1114,28 @@ pub const Session = struct { return regridded; } + /// Compiles the post chain's files (a finished compile wakes the loop + /// through the mailbox) and sends each attached frontend the chain it + /// has not seen: on attach, and when it or a file's SPIR-V changes. True + /// when a compile was taken in, so the loop draws what it said. + /// ponytail: a terminal frontend is sent it too and drops it; a hello + /// saying which frontend it is would spare those bytes. + fn sendPost(s: *Session) bool { + const files = for (s.core.settings.post.list()) |entry| { + if (entry.scene == null) break true; + } else false; + const compiled = s.shaders.sync(s.gpa, s.io, s.core, if (files) s.inotify() else s.inotify_fd, &s.watches, .{ .ctx = &s.mailbox, .call = wakeForExit }); + const key = @as(u64, s.shaders.revision) << 8 | @intFromEnum(s.core.settings.shader_animation); + var chain: wire.Post = .{ .animation = s.core.settings.shader_animation, .len = s.core.settings.post.len }; + _ = s.shaders.view(&s.core.settings.post, &chain.passes); + for (&s.clients) |*c| { + if (!c.attached or c.greet or c.post_sent == key) continue; + c.post_sent = key; + s.send(c, .{ .post = chain }); + } + return compiled; + } + fn send(s: *Session, c: *Client, msg: wire.ServerMsg) void { const want = wire.serverBound(msg); s.scratch.ensureTotalCapacity(s.gpa, want) catch return s.close(c, .oom); diff --git a/src/detached/wire.zig b/src/detached/wire.zig index 6903a1e8..ee8c72fb 100644 --- a/src/detached/wire.zig +++ b/src/detached/wire.zig @@ -3,6 +3,9 @@ const std = @import("std"); const pardes = @import("../pardes.zig"); const limits = @import("../memory.zig").limits; +const shader_build = @import("../shader_build.zig"); +const Scene = pardes.config.Runtime.Scene; +const ShaderAnimation = pardes.config.Runtime.ShaderAnimation; /// 7: tag layers gained the `.notice` kind, so a frame can carry a tag value /// an older frontend would reject mid-session. The greeting is where that has @@ -73,6 +76,9 @@ pub const ServerTag = enum(u8) { set_clipboard = 0x10, read_clipboard = 0x11, open_link = 0x12, + /// The post chain this frontend draws its frames through: sent on + /// attach and whenever it or a file's SPIR-V changes. + post = 0x13, }; /// Why the server hung up on a connect. Sent as a `refuse` and followed by a @@ -353,6 +359,22 @@ pub const ServerMsg = union(enum) { set_clipboard: []const u8, read_clipboard, open_link: []const u8, + post: Post, +}; + +/// The session's post chain, as a GUI attached to it draws it: its passes in +/// order, each a bundled scene at its level or a Shadertoy file's SPIR-V +/// (compiled by the session, shader_build.zig: a frontend reads no disk and +/// runs no program), and when it animates on its own. Slices borrow the +/// payload. +pub const Post = struct { + animation: ShaderAnimation = .on, + passes: [shader_build.max]shader_build.Pass = @splat(.{}), + len: u8 = 0, + + pub fn list(p: *const Post) []const shader_build.Pass { + return p.passes[0..p.len]; + } }; // --------------------------------------------------------------------------- @@ -1149,6 +1171,18 @@ pub fn encodeServer(out: []u8, msg: ServerMsg) Error![]const u8 { .set_clipboard => |t| try w.putSlice32(t), .read_clipboard => {}, .open_link => |u| try w.putSlice16(u), + .post => |p| { + try w.putByte(@intFromEnum(p.animation)); + try w.putByte(p.len); + for (p.list()) |pass| { + // 0 a file, else a bundled scene and one. + try w.putByte(if (pass.scene) |scene| @as(u8, @intFromEnum(scene)) + 1 else 0); + try w.putByte(pass.level); + try w.putU32(pass.revision); + try w.putSlice16(pass.path); + try w.putSlice32(pass.spirv); + } + }, } try finishMessage(&w, at); return w.written(); @@ -1170,6 +1204,11 @@ pub fn serverBound(msg: ServerMsg) usize { .frame => |f| frameBound(f.cols, f.rows), .set_clipboard => |t| t.len, .open_link => |u| u.len, + .post => |p| blk: { + var n: usize = 0; + for (p.list()) |pass| n += 12 + pass.path.len + pass.spirv.len; + break :blk n; + }, }; } @@ -1232,6 +1271,22 @@ pub fn decodeServer(tag: u8, payload: []const u8) Error!ServerMsg { .set_clipboard => .{ .set_clipboard = try r.getSlice32() }, .read_clipboard => .read_clipboard, .open_link => .{ .open_link = try r.getSlice16() }, + .post => blk: { + var p: Post = .{ .animation = try r.getTag(ShaderAnimation) }; + p.len = try r.getByte(); + if (p.len > shader_build.max) return error.Overlong; + for (p.passes[0..p.len]) |*pass| { + const kind = try r.getByte(); + pass.* = .{ + .scene = if (kind == 0) null else std.enums.fromInt(Scene, kind - 1) orelse return error.BadValue, + .level = try r.getByte(), + .revision = try r.getU32(), + .path = try r.getSlice16(), + .spirv = try r.getSlice32(), + }; + } + break :blk .{ .post = p }; + }, }; try r.end(); return msg; @@ -1349,6 +1404,18 @@ test "detached wire: every server message round-trips" { try testing.expectEqualStrings("yank", (try roundServer(&buf, .{ .set_clipboard = "yank" })).set_clipboard); try testing.expectEqual(ServerMsg.read_clipboard, try roundServer(&buf, .read_clipboard)); try testing.expectEqualStrings("https://x", (try roundServer(&buf, .{ .open_link = "https://x" })).open_link); + var chain: Post = .{ .animation = .always, .len = 2 }; + chain.passes[0] = .{ .scene = .bloom, .level = 3 }; + chain.passes[1] = .{ .path = "~/wave.glsl", .spirv = "\x03\x02\x23\x07spirv", .revision = 7 }; + const back = (try roundServer(&buf, .{ .post = chain })).post; + try testing.expectEqual(ShaderAnimation.always, back.animation); + try testing.expectEqual(@as(u8, 2), back.len); + try testing.expectEqual(Scene.bloom, back.passes[0].scene.?); + try testing.expectEqual(@as(u8, 3), back.passes[0].level); + try testing.expect(back.passes[1].scene == null); + try testing.expectEqualStrings("~/wave.glsl", back.passes[1].path); + try testing.expectEqualStrings("\x03\x02\x23\x07spirv", back.passes[1].spirv); + try testing.expectEqual(@as(u32, 7), back.passes[1].revision); } test "detached wire: only the display's own effects are on the wire" { @@ -1357,9 +1424,9 @@ test "detached wire: only the display's own effects are on the wire" { // is the direction that matters: it would hand a frontend work that must // outlive it. The count fails if one of the three is dropped, which would // silently leave a clipboard or a link unanswered on every frontend. - try testing.expectEqual(@as(usize, 8), std.enums.values(ServerTag).len); + try testing.expectEqual(@as(usize, 9), std.enums.values(ServerTag).len); for (std.enums.values(ServerTag)) |t| switch (t) { - .welcome, .refuse, .frame, .quit, .detach, .set_clipboard, .read_clipboard, .open_link => {}, + .welcome, .refuse, .frame, .quit, .detach, .set_clipboard, .read_clipboard, .open_link, .post => {}, }; } diff --git a/src/file_watch.zig b/src/file_watch.zig index d028488e..8bd9de8b 100644 --- a/src/file_watch.zig +++ b/src/file_watch.zig @@ -70,7 +70,11 @@ pub const Watch = struct { /// Sharing the table also shares directory descriptors correctly when a user /// happens to open that .zon as an ordinary document. pub const theme_slot = pardes.MAX_PANES; -pub const Table = [pardes.MAX_PANES + 1]?Watch; +/// After it, one slot a post chain file (shader_build.zig): marked only so +/// a save there wakes the host, which has the files read again; no +/// generation of theirs is kept here. +pub const shader_slot = theme_slot + 1; +pub const Table = [shader_slot + pardes.config.Runtime.Post.max]?Watch; /// Whether this OS has a watcher at all. Off it every entry point below /// returns the inert answer: `watchPath` installs nothing, so `watches` stays @@ -423,6 +427,13 @@ pub fn watchPane( watchPath(fd, watches, id, path, serial, generation); } +/// Mark the post chain files' directories, one slot each, dropping the +/// marks of files no longer in it. +pub fn watchShaders(fd: c_int, watches: *Table, paths: []const []const u8) void { + for (0..pardes.config.Runtime.Post.max) |i| + watchPath(fd, watches, shader_slot + i, if (i < paths.len) paths[i] else null, 0, .{ .text = 0 }); +} + /// Reconcile one marked pane. A true result requests an immediate second pass: /// the PDF pathname changed between the stat before MuPDF reopened it and the /// stat after, so committing either identity would lose a generation. diff --git a/src/gui/Post.zig b/src/gui/Post.zig index 61ebc2cd..06310b7f 100644 --- a/src/gui/Post.zig +++ b/src/gui/Post.zig @@ -1,10 +1,10 @@ //! The post chain (docs/render-pipeline.md §6): Shadertoy passes over the //! finished frame, each reading the one before it (the frame first) and the //! last one writing the window. A pass is the bundled Crt (shaders/post/, -//! compiled with the build) or a user's file (Shader ), -//! compiled when it joins the chain by the build's own glslc invocation on a -//! thread of its own, never on the frame path. A file whose compile fails -//! keeps its last good pipeline, and glslc missing is said once. +//! compiled with the build) or a user's file (Shader ), whose SPIR-V +//! comes from shader_build.zig: compiled by the process that holds the core, +//! this one or the detached session this GUI is attached to. A file whose +//! compile fails keeps its last good pipeline. //! //! The uniforms are ghostty's (Uniforms), so a shader written for ghostty runs //! here. Their clock is the shell's and moves only when the chain draws: @@ -14,7 +14,6 @@ const std = @import("std"); const libc = std.c; const ghostty_vt = @import("ghostty-vt"); const pardes = @import("../pardes.zig"); -const filesystem = @import("../fs.zig"); const gui = @import("gui.zig"); const c = gui.c; @@ -25,6 +24,7 @@ const Pipeline = c.SDL_GPUGraphicsPipeline; pub const max = Chain.max; const prefix = @embedFile("post-prefix.glsl"); +const Built = @import("../shader_build.zig").Pass; const vert_spv = @embedFile("post.vert.spv"); const bundled_spv = std.EnumArray(Scene, []const u8).init(.{ .crt = @embedFile("post-crt.frag.spv"), @@ -92,28 +92,15 @@ pub const Pass = struct { /// A user's file, owned; empty for a bundled pass. path: []u8 = &.{}, pipeline: ?*Pipeline = null, -}; - -/// One compile of a chain's new files, on its own thread. -const Job = struct { - const Result = union(enum) { none, spirv: []u8, failed: []u8, missing }; - io: std.Io, - gpa: std.mem.Allocator, - paths: [max][]u8 = @splat(&.{}), - results: [max]Result = @splat(.none), - len: usize = 0, - done: std.atomic.Value(bool) = .init(false), - thread: std.Thread = undefined, + /// The SPIR-V revision `pipeline` was made from (shader_build.Pass). + revision: u32 = 0, }; passes: [max]Pass = @splat(.{}), len: usize = 0, -/// The chain generation `passes` follow; null before the first. -generation: ?u32 = null, +/// The chain key `passes` follow (sync); null before the first. +key: ?u32 = null, bundled: std.EnumArray(Scene, ?*Pipeline) = .initFill(null), -job: ?*Job = null, -/// Said once: without glslc, files never compile. -missing_said: bool = false, ping: [2]?*c.SDL_GPUTexture = .{ null, null }, ping_w: u32 = 0, ping_h: u32 = 0, @@ -136,20 +123,17 @@ bloom_up: ?*Pipeline = null, started_ns: ?u64 = null, last_ns: u64 = 0, -/// Brings the passes to the chain the core holds, and takes in a finished -/// compile. Called each loop step, off the frame path. -pub fn sync(post: *Post, gpa: std.mem.Allocator, io: std.Io, device: *c.SDL_GPUDevice, format: c.SDL_GPUTextureFormat, core: *pardes.Pardes) void { - if (post.job) |job| { - if (!job.done.load(.acquire)) return; - job.thread.join(); - post.job = null; - post.collect(gpa, device, format, core, job); - } - const chain = &core.settings.post; - if (post.generation == chain.generation) return; - post.generation = chain.generation; +/// Brings the passes to the chain a shell was given (shader_build.zig: a +/// local core's, or an attached session's over the wire), whose `key` moves +/// whenever the chain or a file's SPIR-V does. A file whose SPIR-V has not +/// moved keeps its pipeline; one the GPU refuses keeps its last, and is said +/// to `core`, or logged where there is none. Each loop step, off the frame +/// path. +pub fn sync(post: *Post, gpa: std.mem.Allocator, device: *c.SDL_GPUDevice, format: c.SDL_GPUTextureFormat, chain: []const Built, key: u32, core: ?*pardes.Pardes) void { + if (post.key == key) return; + post.key = key; var next: [max]Pass = @splat(.{}); - for (chain.list(), 0..) |entry, i| { + for (chain, 0..) |entry, i| { if (entry.scene) |scene| { if (post.bundled.get(scene) == null) post.bundled.set(scene, makePipeline(device, format, bundled_spv.get(scene), if (scene == .bloom) 2 else 1, 4) catch null); if (scene == .bloom and post.bloom_down == null) { @@ -161,11 +145,22 @@ pub fn sync(post: *Post, gpa: std.mem.Allocator, io: std.Io, device: *c.SDL_GPUD } // A file already in the chain keeps its pipeline and its path. for (post.passes[0..post.len]) |*pass| { - if (pass.scene != null or !std.mem.eql(u8, pass.path, entry.path.get())) continue; + if (pass.scene != null or !std.mem.eql(u8, pass.path, entry.path)) continue; next[i] = pass.*; pass.* = .{}; break; - } else next[i] = .{ .path = gpa.dupe(u8, entry.path.get()) catch &.{} }; + } else next[i] = .{ .path = gpa.dupe(u8, entry.path) catch &.{} }; + const pass = &next[i]; + if (pass.revision == entry.revision or entry.spirv.len == 0) continue; + pass.revision = entry.revision; + const made = makePipeline(device, format, entry.spirv, 1, 4) catch { + var buf: [512]u8 = undefined; + const text = std.fmt.bufPrint(&buf, "Shader {s}: the GPU refused it", .{entry.path}) catch "Shader: the GPU refused it"; + if (core) |p| p.setMessage(p.active, text) else std.log.err("{s}", .{text}); + continue; + }; + if (pass.pipeline) |old| c.SDL_ReleaseGPUGraphicsPipeline(device, old); + pass.pipeline = made; } for (post.passes[0..post.len]) |pass| { if (pass.scene == null) if (pass.pipeline) |pipeline| c.SDL_ReleaseGPUGraphicsPipeline(device, pipeline); @@ -179,127 +174,6 @@ pub fn sync(post: *Post, gpa: std.mem.Allocator, io: std.Io, device: *c.SDL_GPUD post.last_ns = 0; post.uniforms.frame = 0; } - // The new files compile together, on a thread of their own. - const job = gpa.create(Job) catch return; - job.* = .{ .io = io, .gpa = gpa }; - for (post.passes[0..post.len]) |pass| { - if (pass.scene != null or pass.pipeline != null or pass.path.len == 0) continue; - job.paths[job.len] = gpa.dupe(u8, pass.path) catch continue; - job.len += 1; - } - if (job.len == 0) return gpa.destroy(job); - job.thread = std.Thread.spawn(.{}, compile, .{job}) catch { - for (job.paths[0..job.len]) |path| gpa.free(path); - return gpa.destroy(job); - }; - post.job = job; -} - -fn collect(post: *Post, gpa: std.mem.Allocator, device: *c.SDL_GPUDevice, format: c.SDL_GPUTextureFormat, core: *pardes.Pardes, job: *Job) void { - defer gpa.destroy(job); - for (job.paths[0..job.len], job.results[0..job.len]) |path, result| { - defer gpa.free(path); - const pass = for (post.passes[0..post.len]) |*pass| { - if (pass.scene == null and std.mem.eql(u8, pass.path, path)) break pass; - } else null; - var buf: [512]u8 = undefined; - switch (result) { - .none => {}, - .missing => if (!post.missing_said) { - post.missing_said = true; - core.setMessage(core.active, "Shader: glslc is not on PATH, so Shadertoy files do not run (Crt does)"); - }, - .failed => |text| { - defer gpa.free(text); - // glslc's first line says where: in the file's own lines. - const first = std.mem.sliceTo(text, '\n'); - core.setMessage(core.active, std.fmt.bufPrint(&buf, "Shader {s}: {s}", .{ path, first[0..@min(first.len, 400)] }) catch "Shader: compile failed"); - }, - .spirv => |spirv| { - defer gpa.free(spirv); - const target = pass orelse continue; - const made = makePipeline(device, format, spirv, 1, 4) catch { - core.setMessage(core.active, std.fmt.bufPrint(&buf, "Shader {s}: the GPU refused it", .{path}) catch "Shader: the GPU refused it"); - continue; - }; - if (target.pipeline) |old| c.SDL_ReleaseGPUGraphicsPipeline(device, old); - target.pipeline = made; - }, - } - } -} - -/// The compile thread: each file behind the prefix, through glslc with the -/// build's own flags (build.zig compileGlsl), source on stdin, SPIR-V on -/// stdout. -fn compile(job: *Job) void { - defer job.done.store(true, .release); - defer { - var event = std.mem.zeroes(c.SDL_Event); - event.type = c.SDL_EVENT_USER; - _ = c.SDL_PushEvent(&event); - } - for (job.paths[0..job.len], 0..) |path, i| job.results[i] = compileOne(job.gpa, job.io, path); -} - -fn compileOne(gpa: std.mem.Allocator, io: std.Io, path: []const u8) Job.Result { - var home_buf: [4096]u8 = undefined; - const expanded = if (std.mem.startsWith(u8, path, "~/")) if (libc.getenv("HOME")) |home| - std.fmt.bufPrint(&home_buf, "{s}/{s}", .{ std.mem.span(home), path[2..] }) catch path - else - path else path; - const body = filesystem.readFile(gpa, expanded) catch |err| - return .{ .failed = std.fmt.allocPrint(gpa, "cannot read it ({t})", .{err}) catch return .none }; - defer gpa.free(body); - // The prefix and the file go to glslc on its stdin: no file of ours is - // written anywhere. std's spawn does every allocation before fork and - // searches PATH on the stack after it (Io/Threaded.zig spawnPosix, - // posixExecv), so a child forked from this thread cannot wedge on a - // lock another thread held (the forkShell hazard). - var child = std.process.spawn(io, .{ - .argv = &.{ "glslc", "-fshader-stage=fragment", "-o", "-", "-" }, - .stdin = .pipe, - .stdout = .pipe, - .stderr = .pipe, - }) catch |err| return switch (err) { - error.FileNotFound => .missing, - else => .{ .failed = std.fmt.allocPrint(gpa, "glslc did not run ({t})", .{err}) catch return .none }, - }; - defer child.kill(io); - // glslc reads all of its input before it writes a byte, so writing it - // first cannot deadlock against a full output pipe. - { - var stdin = child.stdin.?; - child.stdin = null; - defer stdin.close(io); - var buf: [4096]u8 = undefined; - var writer = stdin.writer(io, &buf); - writer.interface.writeAll(prefix) catch {}; - writer.interface.writeAll(body) catch {}; - writer.interface.flush() catch {}; - } - var streams: std.Io.File.MultiReader.Buffer(2) = undefined; - var reader: std.Io.File.MultiReader = undefined; - reader.init(gpa, io, streams.toStreams(), &.{ child.stdout.?, child.stderr.? }); - defer reader.deinit(); - while (reader.fill(64, .none)) |_| { - if (reader.reader(0).buffered().len > 16 << 20 or reader.reader(1).buffered().len > 64 << 10) - return .{ .failed = gpa.dupe(u8, "glslc said too much") catch return .none }; - } else |err| switch (err) { - error.EndOfStream => {}, - else => return .{ .failed = gpa.dupe(u8, "reading glslc failed") catch return .none }, - } - const term = child.wait(io) catch return .{ .failed = gpa.dupe(u8, "glslc did not finish") catch return .none }; - const clean = switch (term) { - .exited => |code| code == 0, - else => false, - }; - if (clean) return .{ .spirv = reader.toOwnedSlice(0) catch return .none }; - const said = reader.toOwnedSlice(1) catch return .none; - // glslc calls its input ; the file is what a person knows. - defer gpa.free(said); - const named = std.mem.replaceOwned(u8, gpa, said, "", path) catch return .{ .failed = gpa.dupe(u8, "glslc failed") catch return .none }; - return .{ .failed = named }; } fn makePipeline(device: *c.SDL_GPUDevice, format: c.SDL_GPUTextureFormat, frag: []const u8, samplers: u32, uniform_buffers: u32) !*Pipeline { @@ -686,17 +560,6 @@ fn bloomStep(cmd: *c.SDL_GPUCommandBuffer, pipeline: *Pipeline, sampler: *c.SDL_ pub fn deinit(post: *Post, gpa: std.mem.Allocator, device: *c.SDL_GPUDevice) void { for (post.bloom_tex) |texture| if (texture) |t| c.SDL_ReleaseGPUTexture(device, t); for ([_]?*Pipeline{ post.bloom_down, post.bloom_up }) |pipeline| if (pipeline) |p| c.SDL_ReleaseGPUGraphicsPipeline(device, p); - if (post.job) |job| { - job.thread.join(); - for (job.paths[0..job.len], job.results[0..job.len]) |path, result| { - gpa.free(path); - switch (result) { - .spirv, .failed => |bytes| gpa.free(bytes), - .none, .missing => {}, - } - } - gpa.destroy(job); - } for (post.passes[0..post.len]) |pass| { if (pass.scene == null) if (pass.pipeline) |pipeline| c.SDL_ReleaseGPUGraphicsPipeline(device, pipeline); gpa.free(pass.path); @@ -801,36 +664,3 @@ test "a moved cursor becomes the previous one, stamped with the time of the move try std.testing.expectEqual([4]f32{ 1.0 / 255.0, 2.0 / 255.0, 3.0 / 255.0, 1 }, post.uniforms.selection_foreground_color); } -test "ghostty's test shaders compile behind the prefix, and its invalid one fails with glslc's words" { - const gpa = std.testing.allocator; - const io = std.testing.io; - // ghostty's own test shaders, from its package in zig-pkg. - var pkg = std.Io.Dir.cwd().openDir(io, "zig-pkg", .{ .iterate = true }) catch return error.SkipZigTest; - defer pkg.close(io); - var it = pkg.iterate(); - const ghostty = while (it.next(io) catch null) |entry| { - if (std.mem.startsWith(u8, entry.name, "ghostty-")) break entry.name; - } else return error.SkipZigTest; - var buf: [512]u8 = undefined; - for ([_][]const u8{ "crt", "focus", "invalid" }) |name| { - const path = try std.fmt.bufPrint(&buf, "zig-pkg/{s}/src/renderer/shaders/test_shadertoy_{s}.glsl", .{ ghostty, name }); - const result = compileOne(gpa, io, path); - switch (result) { - .missing => return error.SkipZigTest, // no glslc here - .spirv => |spirv| { - defer gpa.free(spirv); - try std.testing.expect(!std.mem.eql(u8, name, "invalid")); - // SPIR-V's magic number, little-endian. - try std.testing.expectEqual(@as(u32, 0x07230203), std.mem.readInt(u32, spirv[0..4], .little)); - }, - .failed => |text| { - defer gpa.free(text); - try std.testing.expectEqualStrings("invalid", name); - // Named by the file, not by glslc's . - try std.testing.expect(std.mem.indexOf(u8, text, path) != null); - try std.testing.expect(std.mem.indexOf(u8, text, "") == null); - }, - .none => return error.TestUnexpectedResult, - } - } -} diff --git a/src/gui/gui.zig b/src/gui/gui.zig index 127f9b5d..2d31416b 100644 --- a/src/gui/gui.zig +++ b/src/gui/gui.zig @@ -11,6 +11,7 @@ const config = @import("../config.zig"); const look = @import("../look.zig"); const message = pardes.Messages.Message; const file_watch = @import("../file_watch.zig"); +const shader_build = @import("../shader_build.zig"); const deck = @import("deck.zig"); const Post = @import("Post.zig"); const pet = @import("pet.zig"); @@ -2693,6 +2694,7 @@ fn localSession( .test_hz = if (std.c.getenv("PARDES_TEST_HZ")) |hz| @max(1, std.fmt.parseInt(u64, std.mem.span(hz), 10) catch 60) else 60, }; defer shell.shutdownPtys(); + defer shell.shaders.deinit(gpa, inotify_fd, &watches); // A virtual clock never blinks: goldens and feel series hold still. g.no_blink = shell.test_clock != null; const host = shell.host(); @@ -2862,6 +2864,7 @@ fn attachedLoop(gpa: std.mem.Allocator, g: *Gui, client: *detached_client.Client in.post(.{ .paste = text }); }, .open_link => |url| look.openLink(url), + .post => dirty = true, } } try link; @@ -2877,7 +2880,15 @@ fn attachedLoop(gpa: std.mem.Allocator, g: *Gui, client: *detached_client.Client geom = now; try attachedResize(client, g, now.cols, now.rows); } - if (!dirty) continue; + // The session's chain, its files compiled there. + g.post.sync(gpa, g.device, g.swapchain_format, client.post.list(), client.post_key, null); + if (!dirty) { + // As a local window does: a chain that moves on its own redraws + // alone, once a refresh. + if (g.post.animating(client.post.animation) and g.scene_tex != null and + c.SDL_GetTicksNS() -| g.post.last_ns + std.time.ns_per_ms >= refreshNs(g)) redrawPost(g, gpa); + continue; + } dirty = false; paintAttached(g, gpa, client); } @@ -3993,6 +4004,8 @@ const Shell = struct { pipe_tasks: *PipeTasks, inotify_fd: c_int, watches: *file_watch.Table, + /// The post chain's files as SPIR-V. + shaders: shader_build = .{}, threads_ok: bool = false, test_mode: bool = false, feed: StdinFeed = .{}, @@ -4209,11 +4222,19 @@ const Shell = struct { .files_changed => check_files = true, .fs_ready => {}, }; + if (check_files) s.shaders.recheck(); if (check_files and file_watch.reloadChanged(s.core, s.io, s.gpa, s.watches)) s.queue.push(.files_changed); } }; +/// A post chain compile is done (shader_build.zig): the loop's SDL wait ends. +fn wakeSdl(_: ?*anyopaque) void { + var event = std.mem.zeroes(c.SDL_Event); + event.type = c.SDL_EVENT_USER; + _ = c.SDL_PushEvent(&event); +} + fn wakeFs(ctx: ?*anyopaque) void { const q: *Queue = @ptrCast(@alignCast(ctx.?)); q.push(.fs_ready); @@ -4356,7 +4377,11 @@ fn pollFrame(ctx: ?*anyopaque) void { const geom = windowCells(g); if (updateCoreResize(core, geom.cols, geom.rows, g.cell_w, g.cell_h, g.tagline_width, g.tagline_height)) resetScroll(g); stepScroll(g, core, s.gpa); - g.post.sync(s.gpa, s.io, g.device, g.swapchain_format, core); + _ = s.shaders.sync(s.gpa, s.io, core, s.inotify_fd, s.watches, .{ .call = wakeSdl }); + { + var passes: [Post.max]shader_build.Pass = undefined; + g.post.sync(s.gpa, g.device, g.swapchain_format, s.shaders.view(&core.settings.post, &passes), s.shaders.revision, core); + } if (s.test_mode) writeTestStatus(g, core, s.presented); // Between the core's frames, a chain that moves on its own redraws // alone, once a refresh of the display the window is on (a millisecond @@ -5805,8 +5830,9 @@ fn renderFrame( const win_w: f32 = @floatFromInt(sw); const win_h: f32 = @floatFromInt(sh); - // The post chain runs over a local frame, from the scene texture. - var scene_on = core != null and g.post.ready(); + // The post chain runs from the scene texture, over a local frame or an + // attached session's alike. + var scene_on = g.post.ready(); if (scene_on) ensureSceneTexture(g, sw, sh) catch { g.scene_target_failed = true; scene_on = false; @@ -6179,19 +6205,17 @@ fn renderFrame( c.SDL_EndGPURenderPass(rp); if (scene_on) { - if (core) |p| { - var boxes: [max_cursors]CursorBox = undefined; - const cursors = if (cursors_shown) cursorBoxes(g, surface, layout, win_h, &boxes) else 0; - var spare: [Post.max_spare][4]f32 = undefined; - g.post.describe(.{ - .cursor = if (cursors > 0) boxes[0] else null, - .spare = spare[0..postSpare(surface, layout, &spare)], - .background = chrome.page orelse bg_default, - .foreground = chrome.fg orelse fg_default, - .selection_foreground = p.theme().sel_fg, - .selection_background = p.theme().sel_bg, - }); - } + var boxes: [max_cursors]CursorBox = undefined; + const cursors = if (cursors_shown) cursorBoxes(g, surface, layout, win_h, &boxes) else 0; + var spare: [Post.max_spare][4]f32 = undefined; + g.post.describe(.{ + .cursor = if (cursors > 0) boxes[0] else null, + .spare = spare[0..postSpare(surface, layout, &spare)], + .background = chrome.page orelse bg_default, + .foreground = chrome.fg orelse fg_default, + .selection_foreground = if (core) |p| p.theme().sel_fg else chrome.sel_fg, + .selection_background = if (core) |p| p.theme().sel_bg else chrome.sel_bg, + }); const chain_zone = tracy.zone(@src(), "post chain"); defer chain_zone.end(); g.post.scale = display_scale; diff --git a/src/main.zig b/src/main.zig index 86c302fe..c23f8183 100644 --- a/src/main.zig +++ b/src/main.zig @@ -410,6 +410,7 @@ test { _ = @import("locations_cache.zig"); _ = @import("fs.zig"); _ = @import("detached/wire.zig"); + _ = @import("shader_build.zig"); _ = @import("detached/server.zig"); _ = @import("detached/client.zig"); _ = @import("9p_io.zig"); diff --git a/src/shader_build.zig b/src/shader_build.zig new file mode 100644 index 00000000..8aa7eb5e --- /dev/null +++ b/src/shader_build.zig @@ -0,0 +1,402 @@ +//! The post chain's Shadertoy files as SPIR-V (docs/render-pipeline.md §6), +//! for whichever process holds the core: a local GUI makes its pipelines +//! from them, a detached session sends them to the GUIs attached to it +//! (wire `post`), which never read a disk or run a program themselves. +//! +//! Each file compiles behind the prefix by the build's own glslc invocation, +//! on a thread of its own and never on the frame path, when it joins the +//! chain and again whenever a save changes its bytes: the files' directories +//! are watched (file_watch.watchShaders) and a change there has every file +//! read and hashed, an unchanged one compiling nothing. A compile that fails +//! keeps the last good SPIR-V and is said once, and glslc missing is said +//! once for good. +const std = @import("std"); +const libc = std.c; +const pardes = @import("pardes.zig"); +const file_watch = @import("file_watch.zig"); + +const Build = @This(); +const Chain = pardes.config.Runtime.Post; +const Scene = pardes.config.Runtime.Scene; +pub const max = Chain.max; + +const prefix = @embedFile("post-prefix.glsl"); + +/// A pass as a shell draws it: a bundled scene at its level, or a file with +/// its last good SPIR-V (empty until a compile succeeds), whose `revision` +/// moves each time that SPIR-V does. Slices borrow the build's (or, in an +/// attached GUI, the client's) storage until its next change. +pub const Pass = struct { + scene: ?Scene = null, + level: u8 = 0, + path: []const u8 = &.{}, + spirv: []const u8 = &.{}, + revision: u32 = 0, +}; + +/// Who to wake when a compile is done: the host's loop. +pub const Wake = struct { + ctx: ?*anyopaque = null, + call: ?*const fn (?*anyopaque) void = null, +}; + +const File = struct { + path: []u8 = &.{}, + /// The hash of the source last compiled, good or not: the same bytes + /// saved again compile nothing and say nothing twice. + source: ?u64 = null, + spirv: []u8 = &.{}, + revision: u32 = 0, + /// Wants a compile: new to the chain, or its directory changed. + stale: bool = true, +}; + +const Result = union(enum) { + none, + unchanged, + missing, + failed: struct { text: []u8, source: u64 }, + spirv: struct { bytes: []u8, source: u64 }, +}; + +/// One compile of the stale files, on its own thread. +const Job = struct { + io: std.Io, + gpa: std.mem.Allocator, + wake: Wake, + paths: [max][]u8 = @splat(&.{}), + known: [max]?u64 = @splat(null), + results: [max]Result = @splat(.none), + len: usize = 0, + done: std.atomic.Value(bool) = .init(false), + thread: std.Thread = undefined, +}; + +files: [max]File = @splat(.{}), +len: usize = 0, +/// The chain generation `files` follow; null before the first. +generation: ?u32 = null, +/// Moves whenever what `view` gives does: the chain or a file's SPIR-V. +revision: u32 = 0, +job: ?*Job = null, +missing_said: bool = false, + +/// Brings the files to the chain the core holds, watches their directories, +/// takes in a finished compile and starts the next. Each loop step, off the +/// frame path. True when a compile was taken in: what it said wants a frame. +pub fn sync(b: *Build, gpa: std.mem.Allocator, io: std.Io, core: *pardes.Pardes, fd: c_int, watches: *file_watch.Table, wake: Wake) bool { + var collected = false; + if (b.job) |job| { + if (!job.done.load(.acquire)) return false; + job.thread.join(); + b.job = null; + b.collect(gpa, core, job); + collected = true; + } + const chain = &core.settings.post; + if (b.generation != chain.generation) { + b.generation = chain.generation; + b.revision +%= 1; + var next: [max]File = @splat(.{}); + var len: usize = 0; + var paths: [max][]const u8 = undefined; + for (chain.list()) |entry| { + if (entry.scene != null) continue; + next[len] = for (b.files[0..b.len]) |*file| { + if (!std.mem.eql(u8, file.path, entry.path.get())) continue; + const kept = file.*; + file.* = .{}; + break kept; + } else .{ .path = gpa.dupe(u8, entry.path.get()) catch continue }; + paths[len] = next[len].path; + len += 1; + } + for (b.files[0..b.len]) |file| free(gpa, file); + b.files = next; + b.len = len; + var bufs: [max][4096]u8 = undefined; + var expanded: [max][]const u8 = undefined; + for (paths[0..len], 0..) |path, i| expanded[i] = expand(&bufs[i], path); + file_watch.watchShaders(fd, watches, expanded[0..len]); + } + var stale = false; + for (b.files[0..b.len]) |file| stale = stale or file.stale; + if (!stale) return collected; + const job = gpa.create(Job) catch return collected; + job.* = .{ .io = io, .gpa = gpa, .wake = wake }; + for (b.files[0..b.len]) |*file| { + if (!file.stale) continue; + job.paths[job.len] = gpa.dupe(u8, file.path) catch continue; + job.known[job.len] = file.source; + job.len += 1; + file.stale = false; + } + job.thread = std.Thread.spawn(.{}, compile, .{job}) catch { + for (job.paths[0..job.len]) |path| gpa.free(path); + gpa.destroy(job); + return collected; + }; + b.job = job; + return collected; +} + +/// A watched directory changed: every file is read again at the next sync. +pub fn recheck(b: *Build) void { + for (b.files[0..b.len]) |*file| file.stale = true; +} + +/// The chain as passes, in its order. +pub fn view(b: *const Build, chain: *const Chain, out: *[max]Pass) []const Pass { + for (chain.list(), 0..) |entry, i| { + out[i] = if (entry.scene) |scene| .{ .scene = scene, .level = entry.level } else for (b.files[0..b.len]) |file| { + if (std.mem.eql(u8, file.path, entry.path.get())) break .{ .path = file.path, .spirv = file.spirv, .revision = file.revision }; + } else .{ .path = entry.path.get() }; + } + return out[0..chain.len]; +} + +pub fn deinit(b: *Build, gpa: std.mem.Allocator, fd: c_int, watches: *file_watch.Table) void { + if (b.job) |job| { + job.thread.join(); + freeJob(gpa, job); + } + for (b.files[0..b.len]) |file| free(gpa, file); + b.len = 0; + file_watch.watchShaders(fd, watches, &.{}); +} + +fn free(gpa: std.mem.Allocator, file: File) void { + gpa.free(file.path); + gpa.free(file.spirv); +} + +fn freeJob(gpa: std.mem.Allocator, job: *Job) void { + for (job.paths[0..job.len], job.results[0..job.len]) |path, result| { + gpa.free(path); + switch (result) { + .spirv => |r| gpa.free(r.bytes), + .failed => |r| gpa.free(r.text), + .none, .unchanged, .missing => {}, + } + } + gpa.destroy(job); +} + +fn collect(b: *Build, gpa: std.mem.Allocator, core: *pardes.Pardes, job: *Job) void { + defer gpa.destroy(job); + for (job.paths[0..job.len], job.results[0..job.len]) |path, result| { + defer gpa.free(path); + const file = for (b.files[0..b.len]) |*file| { + if (std.mem.eql(u8, file.path, path)) break file; + } else null; + var buf: [512]u8 = undefined; + switch (result) { + .none, .unchanged => {}, + .missing => if (!b.missing_said) { + b.missing_said = true; + core.setMessage(core.active, "Shader: glslc is not on PATH, so Shadertoy files do not run (Crt does)"); + }, + .failed => |r| { + defer gpa.free(r.text); + if (file) |f| f.source = r.source; + // glslc's first line says where: in the file's own lines. + const first = std.mem.sliceTo(r.text, '\n'); + core.setMessage(core.active, std.fmt.bufPrint(&buf, "Shader {s}: {s}", .{ path, first[0..@min(first.len, 400)] }) catch "Shader: compile failed"); + }, + .spirv => |r| { + const f = file orelse { + gpa.free(r.bytes); + continue; + }; + gpa.free(f.spirv); + f.spirv = r.bytes; + f.source = r.source; + f.revision +%= 1; + b.revision +%= 1; + }, + } + } +} + +/// `~/` is the home directory. +fn expand(buf: []u8, path: []const u8) []const u8 { + if (!std.mem.startsWith(u8, path, "~/")) return path; + const home = libc.getenv("HOME") orelse return path; + return std.fmt.bufPrint(buf, "{s}/{s}", .{ std.mem.span(home), path[2..] }) catch path; +} + +/// The compile thread: each file behind the prefix, through glslc with the +/// build's own flags (build.zig compileGlsl), source on stdin, SPIR-V on +/// stdout. +fn compile(job: *Job) void { + for (job.paths[0..job.len], 0..) |path, i| job.results[i] = compileOne(job.gpa, job.io, path, job.known[i]); + job.done.store(true, .release); + if (job.wake.call) |call| call(job.wake.ctx); +} + +fn compileOne(gpa: std.mem.Allocator, io: std.Io, path: []const u8, known: ?u64) Result { + var home_buf: [4096]u8 = undefined; + // Not fs.zig's readFile: that hands the core's turn over for the read, + // a turn this thread never holds. + const body = std.Io.Dir.cwd().readFileAlloc(io, expand(&home_buf, path), gpa, .limited(1 << 20)) catch |err| + return .{ .failed = .{ .text = std.fmt.allocPrint(gpa, "cannot read it ({t})", .{err}) catch return .none, .source = 0 } }; + defer gpa.free(body); + const source = std.hash.Wyhash.hash(0, body); + if (known == source) return .unchanged; + // The prefix and the file go to glslc on its stdin: no file of ours is + // written anywhere. std's spawn does every allocation before fork and + // searches PATH on the stack after it (Io/Threaded.zig spawnPosix, + // posixExecv), so a child forked from this thread cannot wedge on a + // lock another thread held (the forkShell hazard). + var child = std.process.spawn(io, .{ + .argv = &.{ "glslc", "-fshader-stage=fragment", "-o", "-", "-" }, + .stdin = .pipe, + .stdout = .pipe, + .stderr = .pipe, + }) catch |err| return switch (err) { + error.FileNotFound => .missing, + else => .{ .failed = .{ .text = std.fmt.allocPrint(gpa, "glslc did not run ({t})", .{err}) catch return .none, .source = source } }, + }; + defer child.kill(io); + // glslc reads all of its input before it writes a byte, so writing it + // first cannot deadlock against a full output pipe. + { + var stdin = child.stdin.?; + child.stdin = null; + defer stdin.close(io); + var buf: [4096]u8 = undefined; + var writer = stdin.writer(io, &buf); + writer.interface.writeAll(prefix) catch {}; + writer.interface.writeAll(body) catch {}; + writer.interface.flush() catch {}; + } + var streams: std.Io.File.MultiReader.Buffer(2) = undefined; + var reader: std.Io.File.MultiReader = undefined; + reader.init(gpa, io, streams.toStreams(), &.{ child.stdout.?, child.stderr.? }); + defer reader.deinit(); + const failed = struct { + fn of(a: std.mem.Allocator, text: []const u8, hash: u64) Result { + return .{ .failed = .{ .text = a.dupe(u8, text) catch return .none, .source = hash } }; + } + }.of; + while (reader.fill(64, .none)) |_| { + if (reader.reader(0).buffered().len > 16 << 20 or reader.reader(1).buffered().len > 64 << 10) + return failed(gpa, "glslc said too much", source); + } else |err| switch (err) { + error.EndOfStream => {}, + else => return failed(gpa, "reading glslc failed", source), + } + const term = child.wait(io) catch return failed(gpa, "glslc did not finish", source); + const clean = switch (term) { + .exited => |code| code == 0, + else => false, + }; + if (clean) return .{ .spirv = .{ .bytes = reader.toOwnedSlice(0) catch return .none, .source = source } }; + const said = reader.toOwnedSlice(1) catch return .none; + // glslc calls its input ; the file is what a person knows. + defer gpa.free(said); + const named = std.mem.replaceOwned(u8, gpa, said, "", path) catch return failed(gpa, "glslc failed", source); + return .{ .failed = .{ .text = named, .source = source } }; +} + +test "ghostty's test shaders compile behind the prefix, and its invalid one fails with glslc's words" { + const gpa = std.testing.allocator; + const io = std.testing.io; + // ghostty's own test shaders, from its package in zig-pkg. + var pkg = std.Io.Dir.cwd().openDir(io, "zig-pkg", .{ .iterate = true }) catch return error.SkipZigTest; + defer pkg.close(io); + var it = pkg.iterate(); + const ghostty = while (it.next(io) catch null) |entry| { + if (std.mem.startsWith(u8, entry.name, "ghostty-")) break entry.name; + } else return error.SkipZigTest; + var buf: [512]u8 = undefined; + for ([_][]const u8{ "crt", "focus", "invalid" }) |name| { + const path = try std.fmt.bufPrint(&buf, "zig-pkg/{s}/src/renderer/shaders/test_shadertoy_{s}.glsl", .{ ghostty, name }); + switch (compileOne(gpa, io, path, null)) { + .missing => return error.SkipZigTest, // no glslc here + .spirv => |r| { + defer gpa.free(r.bytes); + try std.testing.expect(!std.mem.eql(u8, name, "invalid")); + // SPIR-V's magic number, little-endian. + try std.testing.expectEqual(@as(u32, 0x07230203), std.mem.readInt(u32, r.bytes[0..4], .little)); + // The same bytes again compile nothing. + try std.testing.expectEqual(Result.unchanged, compileOne(gpa, io, path, r.source)); + }, + .failed => |r| { + defer gpa.free(r.text); + try std.testing.expectEqualStrings("invalid", name); + // Named by the file, not by glslc's . + try std.testing.expect(std.mem.indexOf(u8, r.text, path) != null); + try std.testing.expect(std.mem.indexOf(u8, r.text, "") == null); + }, + .none, .unchanged => return error.TestUnexpectedResult, + } + } +} + +test "a save that changes a file compiles it again, a failed one keeps the last good SPIR-V and is said once" { + const gpa = std.testing.allocator; + const io = std.testing.io; + const core = try pardes.Pardes.init(gpa, .{ .cols = 80, .rows = 24 }); + defer core.deinit(); + _ = try core.newShell(1, ""); + const pane = core.panes[core.active].?; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + var dir_buf: [4096]u8 = undefined; + const dir = dir_buf[0..try tmp.dir.realPath(io, &dir_buf)]; + var path_buf: [4200]u8 = undefined; + const path = try std.fmt.bufPrint(&path_buf, "{s}/wave.glsl", .{dir}); + const good = "void mainImage(out vec4 o, in vec2 p) { o = texture(iChannel0, p / iResolution.xy); }\n"; + try tmp.dir.writeFile(io, .{ .sub_path = "wave.glsl", .data = good }); + try std.testing.expect(core.settings.post.set(null, path, true)); + + const fd = file_watch.init(true); + defer if (fd >= 0) { + _ = libc.close(fd); + }; + var watches: file_watch.Table = @splat(null); + var b: Build = .{}; + defer b.deinit(gpa, fd, &watches); + const settle = struct { + fn run(build: *Build, c: *pardes.Pardes, f: c_int, w: *file_watch.Table) void { + _ = build.sync(std.testing.allocator, std.testing.io, c, f, w, .{}); + while (build.job) |job| { + while (!job.done.load(.acquire)) std.Thread.yield() catch {}; + _ = build.sync(std.testing.allocator, std.testing.io, c, f, w, .{}); + } + } + }.run; + settle(&b, core, fd, &watches); + if (b.missing_said) return error.SkipZigTest; // no glslc here + var out: [max]Pass = undefined; + const first = b.view(&core.settings.post, &out)[0]; + try std.testing.expect(first.spirv.len != 0); + if (file_watch.supported) try std.testing.expect(watches[file_watch.shader_slot] != null); + + // Unchanged bytes: nothing moves. + const at = b.revision; + b.recheck(); + settle(&b, core, fd, &watches); + try std.testing.expectEqual(at, b.revision); + + // A bad save: the last good SPIR-V stays, the error is said, and the + // same bad bytes again say nothing more. + try tmp.dir.writeFile(io, .{ .sub_path = "wave.glsl", .data = "void mainImage(" }); + pane.msg_len = 0; + b.recheck(); + settle(&b, core, fd, &watches); + try std.testing.expectEqual(at, b.revision); + try std.testing.expect(std.mem.startsWith(u8, pane.msg[0..pane.msg_len], "Shader ")); + pane.msg_len = 0; + b.recheck(); + settle(&b, core, fd, &watches); + try std.testing.expectEqual(@as(u16, 0), pane.msg_len); + + // A good save again: new SPIR-V, a new revision. + try tmp.dir.writeFile(io, .{ .sub_path = "wave.glsl", .data = "// saved again\n" ++ good }); + b.recheck(); + settle(&b, core, fd, &watches); + const second = b.view(&core.settings.post, &out)[0]; + try std.testing.expect(second.revision != first.revision and b.revision != at); +} diff --git a/src/tty/tty.zig b/src/tty/tty.zig index c4096faf..c5491a73 100644 --- a/src/tty/tty.zig +++ b/src/tty/tty.zig @@ -2157,6 +2157,8 @@ const Attach = struct { .set_clipboard => |text| copyToClipboard(a.vx, a.tty, a.gpa, text), .read_clipboard => requestClipboard(a.vx, a.tty), .open_link => |url| look.openLink(url), + // A terminal has no post chain to draw through. + .post => {}, } return null; } -- cgit v1.3 From a22129c343d9236277dcc0353c48cb53bc3417ce Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Tue, 29 Sep 2026 18:32:37 -0300 Subject: pardes --wait (-w) in a pane returns only once the pane its file landed in is deleted, so it can be $EDITOR A launch inside a pane forwards its file to the session's look and returned at once, so fish's Ctrl-O (edit_command_buffer), git commit and crontab -e read their still-unedited file back and went on. With --wait, as acme's E against B and read the way plan9port's E reads acme's log, it finds the pane /index names the file by (the one already showing it, if open), follows /log on one connection with 'follow new', reads /index once more to catch a Del that came first, and then blocks with no deadline until that pane's del record: exit 0, or 1 when the connection ends with the session. The 9P client's one-shot requests keep their 2 s deadline; its new follow takes it for the setup only. Outside pardes nothing changes. --help, docs/fs.md, the README and the 9P skill say to set EDITOR='pardes --wait', which GIT_EDITOR follows. Tested in fs.py (it returns within 50 ms of the Del, a second -w waits on the same pane, one whose session is killed exits 1) and end to end: fish 4.8 in a detached session, echo hi, Ctrl-O, the waiting launch idle in poll, the line edited over 9P, Save, Del, and fish ran echo edited. Co-Authored-By: Claude Opus 5.5 --- .agents/skills/pardes-9p/SKILL.md | 4 ++ README.md | 6 +++ docs/fs.md | 9 ++++ src/9p_io.zig | 86 +++++++++++++++++++++++++++++++-------- src/main.zig | 85 ++++++++++++++++++++++++++++++++++++++ test/fs.py | 41 +++++++++++++++++++ 6 files changed, 213 insertions(+), 18 deletions(-) (limited to 'src/main.zig') diff --git a/.agents/skills/pardes-9p/SKILL.md b/.agents/skills/pardes-9p/SKILL.md index 18700589..1d32ce7a 100644 --- a/.agents/skills/pardes-9p/SKILL.md +++ b/.agents/skills/pardes-9p/SKILL.md @@ -34,6 +34,10 @@ cat "$m/pane/$PARDES_PANE/body" From there the editor is files: `cat`, `echo >`, `ls` and shell scripts are the whole interface, and nothing below needs more than they do. +`pardes FILE` run in a pane opens FILE in that session and returns at once; +`pardes --wait FILE` returns when that pane is deleted (1 if the session goes +away), which is what `EDITOR='pardes --wait'` needs (`GIT_EDITOR` follows it). + Entries for dead sessions stay listed and answer `Input/output error` on any access, so name the session you mean rather than globbing or taking the newest. `cat "$m/index"` is the cheapest liveness check, and `cat "$m/status"` reports diff --git a/README.md b/README.md index f60b0ed7..14803aef 100644 --- a/README.md +++ b/README.md @@ -36,6 +36,12 @@ serves the layout: `/layout` lists the columns, their places and panes, and `/tag` and `/col//tag` are the workspace and column tags, editable like a window's ([the tree](docs/fs.md#the-served-tree)). +`pardes FILE` in a pane opens FILE in that session and returns at once. As +`$EDITOR`, use `EDITOR='pardes --wait'` (`GIT_EDITOR` follows it): `--wait` +returns when that pane is deleted, so fish's Ctrl-O, `git commit` and +`crontab -e` read the file after you edit it +([forwarding](docs/fs.md#filesystem)). + plan9port's `9p write` always opens with OTRUNC, so `echo x | 9p write pardes//body` replaces the whole body where acme would append. To append, write through a mount with `>>` (`echo x >> $PARDES_MOUNT//body`). diff --git a/docs/fs.md b/docs/fs.md index 52f991c2..ca02082b 100644 --- a/docs/fs.md +++ b/docs/fs.md @@ -15,6 +15,15 @@ separate editor and withholds `PARDES_PID` from its pane shells, so a pardes started in one of them runs a session of its own; its 9P service stays available. +A forwarded launch returns at once, as acme's `B` does. `--wait` (`-w`) +returns only once the pane the file landed in -- the one already showing +it, if any -- is deleted (exit 0), or the session goes away (exit 1), as +acme's `E` does: what an `$EDITOR` must do, since fish's Ctrl-O +(`edit_command_buffer`), `git commit` and `crontab -e` read the file back +when the editor exits. Set `EDITOR='pardes --wait'`; `GIT_EDITOR` follows +`EDITOR` when unset. Outside pardes `--wait` changes nothing, a session +blocking anyway. + Look resolves the OS filesystem first, then the editor's virtual filesystem. Explicit paths bypass that search: diff --git a/src/9p_io.zig b/src/9p_io.zig index 6f05e3ab..78ff5d59 100644 --- a/src/9p_io.zig +++ b/src/9p_io.zig @@ -1947,14 +1947,8 @@ pub const Client = struct { } }; - fn transact( - s: *Session, - names: []const []const u8, - out: *std.Io.Writer.Allocating, - remote: *RemoteError, - write_bytes: ?[]const u8, - read_limit: usize, - ) !void { + /// Version, attach and a walk to `names`: the fid there and its qid. + fn walkTo(s: *Session, names: []const []const u8, remote: *RemoteError) !struct { fid: u32, qid: ninep.Qid } { _ = try s.ask(.{ .version = .{} }, remote); if (s.cl.msize == 0) return Error.Botch; @@ -1978,6 +1972,20 @@ pub const Client = struct { next = if (next == 1) 2 else 1; i += n; } + return .{ .fid = cur, .qid = here }; + } + + fn transact( + s: *Session, + names: []const []const u8, + out: *std.Io.Writer.Allocating, + remote: *RemoteError, + write_bytes: ?[]const u8, + read_limit: usize, + ) !void { + const at = try walkTo(s, names, remote); + const cur = at.fid; + const here = at.qid; defer s.dropNoWait(cur); const directory = here.type & ninep.qtdir != 0; @@ -2036,15 +2044,20 @@ pub const Client = struct { read_limit: usize, ) ![]u8 { if (comptime !supported) return Error.Dial; + const s = try startSession(gpa, sock, display_path); + defer endSession(gpa, s); + var out: std.Io.Writer.Allocating = .init(gpa); + errdefer out.deinit(); + try transact(s, names, &out, remote, write_bytes, read_limit); + return out.toOwnedSlice(); + } + + /// A connected session whose requests have the usual deadline. + fn startSession(gpa: std.mem.Allocator, sock: Dial, display_path: []const u8) !*Session { const deadline = nowMs() +| budget_ms; const s = try gpa.create(Session); s.* = .{ .fd = -1, .deadline = deadline, .display_path = display_path }; - defer { - if (quic_enabled and s.quic != null) { - s.quic.?.deinit(); - } else if (s.fd >= 0) _ = libc.close(s.fd); - gpa.destroy(s); - } + errdefer endSession(gpa, s); if (sock == .quic) { if (comptime quic_enabled) { s.quic = quic.Connection.dial(sock.quic) catch return Error.Dial; @@ -2052,11 +2065,48 @@ pub const Client = struct { } else return Error.QuicUnavailable; } else s.fd = try connect(sock, deadline); s.cl = .init(.{ .in = &s.in, .out = &s.out }); + return s; + } - var out: std.Io.Writer.Allocating = .init(gpa); - errdefer out.deinit(); - try transact(s, names, &out, remote, write_bytes, read_limit); - return out.toOwnedSlice(); + fn endSession(gpa: std.mem.Allocator, s: *Session) void { + if (quic_enabled and s.quic != null) { + s.quic.?.deinit(); + } else if (s.fd >= 0) _ = libc.close(s.fd); + gpa.destroy(s); + } + + /// Opens `path` on one connection and writes `first` to it (/log's + /// `follow new`), all with the usual deadline; then, once `ready(ctx)` + /// has said it is not done already, reads it with no deadline, a read at + /// a time, until `record(ctx, bytes)` says done. An end of file or a + /// dropped connection is Hangup. What `pardes --wait` blocks on. + pub fn follow( + gpa: std.mem.Allocator, + dial: []const u8, + path: []const u8, + first: []const u8, + ctx: anytype, + comptime ready: fn (@TypeOf(ctx)) bool, + comptime record: fn (@TypeOf(ctx), []const u8) bool, + ) !void { + if (comptime !supported) return error.Unsupported; + var names: [max_depth][]const u8 = undefined; + const n = try elements(path, &names); + var sock_buf: [sun_path_len]u8 = undefined; + const sock = try resolve(&sock_buf, dial); + var remote: RemoteError = .{}; + const s = try startSession(gpa, sock, path); + defer endSession(gpa, s); + const fid = (try walkTo(s, names[0..n], &remote)).fid; + _ = try s.ask(.{ .open = .{ .fid = fid, .mode = ninep.ordwr } }, &remote); + _ = try s.ask(.{ .write = .{ .fid = fid, .offset = 0, .data = first } }, &remote); + if (ready(ctx)) return; + s.deadline = std.math.maxInt(i64); + while (true) { + const data = (try s.ask(.{ .read = .{ .fid = fid, .offset = 0, .count = s.cl.maxRead() } }, &remote)).read; + if (data.len == 0) return Error.Hangup; + if (record(ctx, data)) return; + } } fn connect(sock: Dial, deadline: i64) Error!c_int { diff --git a/src/main.zig b/src/main.zig index aaa237f6..ec2472d7 100644 --- a/src/main.zig +++ b/src/main.zig @@ -58,6 +58,12 @@ const help_text = \\ A FILE argument boots just that file instead. \\ --tty-toggle use Ctrl- to toggle tty/editor mode \\ -l load a dump of another instance (see Dump) + \\ -w, --wait inside a pardes pane, hand FILE to the outer + \\ session and return only once the pane it opened + \\ (or already had) is deleted: 0 then, 1 if the + \\ session goes away. For $EDITOR (acme's E): + \\ EDITOR='pardes --wait', which GIT_EDITOR follows. + \\ Outside pardes a session blocks anyway. \\ --nested run a full session even inside another pardes. \\ Without it, a pardes started inside a pardes \\ hands its FILE argument to the outer one. This @@ -92,6 +98,81 @@ const help_text = \\ ; +/// `--wait` after a forwarded look, as plan9port's E reads acme's log: the +/// pane `path` landed in (the one it already had, if open), then /log +/// followed on one connection until that pane's `del` -- exit 0 -- or the +/// connection ends with the session -- exit 1. +fn waitForDel(io: std.Io, gpa: std.mem.Allocator, dial: []const u8, path: []const u8) noreturn { + const first = ninep_io.Client.read(gpa, dial, "/index", "/index") catch std.process.exit(1); + const serial = paneShowing(first, path) orelse { + std.Io.File.stderr().writeStreamingAll(io, "pardes: --wait: no pane shows that file\n") catch {}; + std.process.exit(1); + }; + gpa.free(first); + const Wait = struct { + gpa: std.mem.Allocator, + dial: []const u8, + serial: u32, + /// Deleted between the look and the follow: /index, read once the + /// follow stands, says so, and a `del` after it is followed. + fn gone(w: *const @This()) bool { + const index = ninep_io.Client.read(w.gpa, w.dial, "/index", "/index") catch return false; + defer w.gpa.free(index); + return !hasPane(index, w.serial); + } + fn deleted(w: *const @This(), bytes: []const u8) bool { + return isDel(bytes, w.serial); + } + }; + const w: Wait = .{ .gpa = gpa, .dial = dial, .serial = serial }; + ninep_io.Client.follow(gpa, dial, "/log", "follow new", &w, Wait.gone, Wait.deleted) catch std.process.exit(1); + std.process.exit(0); +} + +/// Whether log records `bytes` hold `del ...`. +fn isDel(bytes: []const u8, serial: u32) bool { + var records = std.mem.splitScalar(u8, bytes, '\n'); + while (records.next()) |rec| { + if (!std.mem.startsWith(u8, rec, "del ")) continue; + const word = rec[4 .. std.mem.indexOfScalarPos(u8, rec, 4, ' ') orelse rec.len]; + if ((std.fmt.parseInt(u32, word, 10) catch continue) == serial) return true; + } + return false; +} + +/// The serial of /index's first row named `path` (`serial kind dirty name col`). +fn paneShowing(index: []const u8, path: []const u8) ?u32 { + var rows = std.mem.splitScalar(u8, index, '\n'); + while (rows.next()) |row| { + var words = std.mem.splitScalar(u8, row, ' '); + const serial = std.fmt.parseInt(u32, words.first(), 10) catch continue; + _ = words.next() orelse continue; // kind + _ = words.next() orelse continue; // dirty + const rest = words.rest(); + const end = std.mem.lastIndexOfScalar(u8, rest, ' ') orelse continue; + if (std.mem.eql(u8, rest[0..end], path)) return serial; + } + return null; +} + +fn hasPane(index: []const u8, serial: u32) bool { + var rows = std.mem.splitScalar(u8, index, '\n'); + while (rows.next()) |row| { + const first = row[0 .. std.mem.indexOfScalar(u8, row, ' ') orelse row.len]; + if ((std.fmt.parseInt(u32, first, 10) catch continue) == serial) return true; + } + return false; +} + +test "--wait finds the pane /index names a file by, spaces and all, and sees it gone" { + const index = "1 term 0 /home/u 1\n4 text 1 /tmp/a b.txt 2\n"; + try std.testing.expectEqual(@as(?u32, 4), paneShowing(index, "/tmp/a b.txt")); + try std.testing.expectEqual(@as(?u32, null), paneShowing(index, "/tmp/a")); + try std.testing.expect(hasPane(index, 4) and !hasPane(index, 2)); + try std.testing.expect(isDel("new 5 /x\ndel 4 /tmp/a b.txt\n", 4)); + try std.testing.expect(!isDel("del 41 /x\n", 4) and !isDel("undel 4\n", 4)); +} + fn badArgs(io: std.Io, comptime fmt: []const u8, args: anytype) noreturn { var buf: [1024]u8 = undefined; const line = std.fmt.bufPrint(&buf, "pardes: " ++ fmt ++ "\nTry 'pardes --help'.\n", args) catch @@ -159,6 +240,7 @@ fn nativeMain(init: std.process.Init) !void { var detach: ?[]const u8 = null; var attach: ?[]const u8 = null; var positional: ?[:0]const u8 = null; + var wait = false; var i: usize = 1; while (i < args.len) : (i += 1) { const a = args[i]; @@ -239,6 +321,8 @@ fn nativeMain(init: std.process.Init) !void { mounts_len += 1; } else if (std.mem.eql(u8, a, "--nested")) { opts.nested = true; + } else if (std.mem.eql(u8, a, "-w") or std.mem.eql(u8, a, "--wait")) { + wait = true; } else if (std.mem.eql(u8, a, "--detach")) { detach = ""; } else if (std.mem.startsWith(u8, a, "--detach=")) { @@ -328,6 +412,7 @@ fn nativeMain(init: std.process.Init) !void { var command_buf: [8192]u8 = undefined; const command = std.fmt.bufPrint(&command_buf, "{s}{s}\n", .{ path, word[target.path.len..] }) catch break :forwarding; ninep_io.Client.write(arena, parent.dial, look, command) catch break :forwarding; + if (wait) waitForDel(init.io, arena, parent.dial, path); return; } if (positional) |a| { diff --git a/test/fs.py b/test/fs.py index 7401861b..db10f32d 100644 --- a/test/fs.py +++ b/test/fs.py @@ -1224,6 +1224,47 @@ def test(binary, quic=False): cell[0] for cell in local.screen()['cells']) assert client.read('/index') == before + # --wait (acme's E): a launch inside a pane lasts until the pane it + # opened is deleted, as an $EDITOR must; one on a file already open + # waits on that pane; a session that goes away ends it with 1. + with session(binary, root, 'wait') as (client, address): + status = dict(line.split(maxsplit=1) for line in client.read('/status').decode().splitlines()) + env = {k: v for k, v in os.environ.items() if k != 'PARDES_FORWARD_LOOK'} + env.update(PARDES_9P=str(address), PARDES_PANE='1', PARDES_PID=status['pid']) + edited = root / 'wait edit.txt' + edited.write_bytes(b'edit me\n') + + def serials(): + return {int(row.split()[0]) for row in client.read('/index').splitlines()} + + def launch(flag): + before = serials() + child = subprocess.Popen([binary, flag, str(edited)], cwd=root, env=env, + stdout=subprocess.DEVNULL, stderr=subprocess.PIPE) + deadline = time.monotonic() + 3 + while child.poll() is None and not serials() - before and time.monotonic() < deadline: + time.sleep(.01) + return child + + first = launch('--wait') + opened, = serials() - {1} + second = launch('-w') + time.sleep(.5) + assert first.poll() is None and second.poll() is None, (first.stderr.read(), second.stderr.read()) + assert serials() == {1, opened} + client.write(f'/pane/{opened}/body', b'edited\n', truncate=True) + execute(client, opened, 'Save') + client.remove(f'/pane/{opened}') + deleted = time.monotonic() + assert first.wait(timeout=5) == 0 + # Woken by the `del` record, not a poll. + assert time.monotonic() - deleted < .05, time.monotonic() - deleted + assert second.wait(timeout=5) == 0 + assert edited.read_bytes() == b'edited\n' + orphan = launch('--wait') + assert orphan.poll() is None + assert orphan.wait(timeout=5) == 1 + for tty in [False, True]: name = 'lsp-tty' if tty else 'lsp-detached' with session(binary, root, name, tty=tty) as (client, _): -- cgit v1.3 From b3b68f5ca784de3987406584ca75b3767f98695d Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Tue, 29 Sep 2026 19:49:21 -0300 Subject: pardes NEWFILE in a pane opens a pane named it in the session, as acme's B does, and a start with no terminal says so A name that did not exist yet failed resolveOs, so the launch fell through to starting an editor of its own, which on a pty with no controlling terminal (a detached session's) ended in a NoDevice error trace. A new name's directory is now resolved and the name kept: the launch reads pane/new and writes that path to the pane's name, so Save creates the file, and --wait waits on that pane (the git commit case). A standalone start whose /dev/tty will not open prints why and exits 1. fs.py covers both; the known-wrong line in docs/divergences.md goes. Co-Authored-By: Claude Opus 5.5 --- docs/divergences.md | 2 -- src/main.zig | 38 +++++++++++++++++++++++++++++++++----- test/fs.py | 32 ++++++++++++++++++++++++++++++++ 3 files changed, 65 insertions(+), 7 deletions(-) (limited to 'src/main.zig') diff --git a/docs/divergences.md b/docs/divergences.md index 17179029..21e5167e 100644 --- a/docs/divergences.md +++ b/docs/divergences.md @@ -18,7 +18,5 @@ moving a bookmark does not quietly orphan work or hide a failure. ## Known wrong on `main` -- `pardes FILE` in a pane forwards only a FILE that exists; a new file name - starts a separate editor instead of opening a pane in the session. - `Dump` fails `no such directory` when the default `DumpDir`'s parent (`$XDG_DATA_HOME`, or `~/.local/share`) does not exist. diff --git a/src/main.zig b/src/main.zig index ec2472d7..ab6f1527 100644 --- a/src/main.zig +++ b/src/main.zig @@ -408,10 +408,30 @@ fn nativeMain(init: std.process.Init) !void { if (std.mem.indexOfAny(u8, word, "\r\n") != null) break :forwarding; const target = @import("look.zig").parsePathLine(word); var realbuf: [4096]u8 = undefined; - const path = if (pardes.filesystem.isVirtual(target.path)) target.path else (pardes.filesystem.resolveOs(target.path, &realbuf) orelse break :forwarding).path; - var command_buf: [8192]u8 = undefined; - const command = std.fmt.bufPrint(&command_buf, "{s}{s}\n", .{ path, word[target.path.len..] }) catch break :forwarding; - ninep_io.Client.write(arena, parent.dial, look, command) catch break :forwarding; + var newbuf: [4096]u8 = undefined; + const found_path: ?[]const u8 = if (pardes.filesystem.isVirtual(target.path)) target.path else if (pardes.filesystem.resolveOs(target.path, &realbuf)) |r| r.path else null; + const path = found_path orelse named: { + // A name not there yet, as acme's B takes one: its directory + // resolved and the name kept, a pane made for it that Save + // creates the file from. + const base = std.fs.path.basename(target.path); + if (base.len == 0 or std.mem.eql(u8, base, ".") or std.mem.eql(u8, base, "..")) break :forwarding; + const dir = pardes.filesystem.resolveOs(std.fs.path.dirname(target.path) orelse ".", &realbuf) orelse break :forwarding; + break :named std.fmt.bufPrint(&newbuf, "{s}/{s}", .{ std.mem.trimEnd(u8, dir.path, "/"), base }) catch break :forwarding; + }; + if (found_path != null) { + var command_buf: [8192]u8 = undefined; + const command = std.fmt.bufPrint(&command_buf, "{s}{s}\n", .{ path, word[target.path.len..] }) catch break :forwarding; + ninep_io.Client.write(arena, parent.dial, look, command) catch break :forwarding; + } else { + const made = ninep_io.Client.read(arena, parent.dial, "/pane/new", "/pane/new") catch break :forwarding; + const serial = std.fmt.parseInt(u32, std.mem.trim(u8, made, " \n"), 10) catch break :forwarding; + var name_buf: [64]u8 = undefined; + const name = try std.fmt.bufPrint(&name_buf, "/pane/{d}/name", .{serial}); + var line_buf: [4200]u8 = undefined; + const line = std.fmt.bufPrint(&line_buf, "{s}\n", .{path}) catch break :forwarding; + ninep_io.Client.write(arena, parent.dial, name, line) catch break :forwarding; + } if (wait) waitForDel(init.io, arena, parent.dial, path); return; } @@ -468,7 +488,15 @@ fn nativeMain(init: std.process.Init) !void { std.process.exit(1); } switch (pardes.platform) { - .tty => try @import("tty/tty.zig").run(init, opts, attach), + .tty => @import("tty/tty.zig").run(init, opts, attach) catch |err| switch (err) { + // No controlling terminal (a detached pty, a daemon): said, not + // an error trace. + error.NoDevice => { + std.Io.File.stderr().writeStreamingAll(init.io, "pardes: no terminal to draw on: /dev/tty will not open; run it in a terminal, or --detach\n") catch {}; + std.process.exit(1); + }, + else => return err, + }, .gui => try @import("gui/gui.zig").run(init, opts, attach), .web, .macos, .esp32p4 => unreachable, } diff --git a/test/fs.py b/test/fs.py index db10f32d..15f4eb8b 100644 --- a/test/fs.py +++ b/test/fs.py @@ -1261,10 +1261,42 @@ def test(binary, quic=False): assert time.monotonic() - deleted < .05, time.monotonic() - deleted assert second.wait(timeout=5) == 0 assert edited.read_bytes() == b'edited\n' + # A name not there yet opens a pane named it, as acme's B does, + # and Save creates it: git's and fish's temporary files are. + fresh = root / 'wait new.txt' + before = serials() + made = subprocess.Popen([binary, '--wait', fresh.name], cwd=root, env=env, + stdout=subprocess.DEVNULL, stderr=subprocess.PIPE) + deadline = time.monotonic() + 3 + while not serials() - before: + assert made.poll() is None, made.stderr.read() + assert time.monotonic() < deadline, 'a new name opened no pane' + time.sleep(.01) + named, = serials() - before + assert str(fresh).encode() in client.read('/index') + client.write(f'/pane/{named}/body', b'new\n') + execute(client, named, 'Save') + client.remove(f'/pane/{named}') + assert made.wait(timeout=5) == 0 + assert fresh.read_bytes() == b'new\n' orphan = launch('--wait') assert orphan.poll() is None assert orphan.wait(timeout=5) == 1 + # A launch with no terminal to draw on (a pty that is no one's + # controlling terminal) says so and exits 1, no error trace. + master, slave = os.openpty() + try: + 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), TERM='xterm-256color') + result = subprocess.run([binary, '--tty', 'x.txt'], cwd=root, env=env, stdin=slave, stdout=slave, + stderr=subprocess.PIPE, start_new_session=True, timeout=10) + finally: + os.close(master) + os.close(slave) + assert result.returncode == 1, result + assert b'pardes: no terminal to draw on' in result.stderr and b'.zig:' not in result.stderr, result.stderr + for tty in [False, True]: name = 'lsp-tty' if tty else 'lsp-detached' with session(binary, root, name, tty=tty) as (client, _): -- cgit v1.3 From 7d2178022e721f3eac023f3e3be56c1bb1e49927 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Tue, 29 Sep 2026 20:24:56 -0300 Subject: shader_build.zig is ShaderBuild.zig: a file that is a struct (its fields are the post chain's builds) takes a type's name The naming the split agreed on: a file with fields is a type, TitleCase, as Messages.zig and Layer.zig are. Its importers bind it as ShaderBuild; comments and docs/render-pipeline.md name the new file. No behaviour changes. Co-Authored-By: Claude Opus 5.5 --- build.zig | 2 +- docs/render-pipeline.md | 2 +- src/ShaderBuild.zig | 428 ++++++++++++++++++++++++++++++++++++++++++++++++ src/detached/server.zig | 4 +- src/detached/wire.zig | 10 +- src/file_watch.zig | 2 +- src/gui/Post.zig | 12 +- src/gui/gui.zig | 8 +- src/main.zig | 2 +- src/shader_build.zig | 428 ------------------------------------------------ 10 files changed, 449 insertions(+), 449 deletions(-) create mode 100644 src/ShaderBuild.zig delete mode 100644 src/shader_build.zig (limited to 'src/main.zig') diff --git a/build.zig b/build.zig index e549a53e..a69327ae 100644 --- a/build.zig +++ b/build.zig @@ -1083,7 +1083,7 @@ pub fn build(b: *std.Build) void { } // A detached session compiles its attached GUIs' Shadertoy files - // (shader_build.zig), whichever shell it was built for. + // (ShaderBuild.zig), whichever shell it was built for. if (gui_shell_mod != root_mod) root_mod.addAnonymousImport("post-prefix.glsl", .{ .root_source_file = b.path("shaders/post/prefix.glsl") }); diff --git a/docs/render-pipeline.md b/docs/render-pipeline.md index f39504c2..6e1cd455 100644 --- a/docs/render-pipeline.md +++ b/docs/render-pipeline.md @@ -505,7 +505,7 @@ Mirror ghostty 1.3.2 (`zig-pkg/ghostty-*/src/renderer/shadertoy.zig`, (file_watch shader slots): a change there has each file read and hashed, and one whose bytes moved compiles again; the same bytes (good or bad) compile nothing and say nothing twice. The process that holds the core - compiles (shader_build.zig): a local GUI, or a detached session, which + compiles (ShaderBuild.zig): a local GUI, or a detached session, which sends its attached GUIs the chain with each file's SPIR-V (wire `post`, on attach and on every change), so an attached GUI runs the same passes, levels and ShaderAnimation as a local one and still reads no disk and runs diff --git a/src/ShaderBuild.zig b/src/ShaderBuild.zig new file mode 100644 index 00000000..c2610fd7 --- /dev/null +++ b/src/ShaderBuild.zig @@ -0,0 +1,428 @@ +//! The post chain's Shadertoy files as SPIR-V (docs/render-pipeline.md §6), +//! for whichever process holds the core: a local GUI makes its pipelines +//! from them, a detached session sends them to the GUIs attached to it +//! (wire `post`), which never read a disk or run a program themselves. +//! +//! Each file compiles behind the prefix by the build's own glslc invocation, +//! on a thread of its own and never on the frame path, when it joins the +//! chain and again whenever a save changes its bytes: the files' directories +//! are watched (file_watch.watchShaders) and a change there has every file +//! read and hashed, an unchanged one compiling nothing. A compile that fails +//! keeps the last good SPIR-V and is said once, and glslc missing is said +//! once for good. +const std = @import("std"); +const libc = std.c; +const pardes = @import("pardes.zig"); +const file_watch = @import("file_watch.zig"); + +const Build = @This(); +const Chain = pardes.config.Runtime.Post; +const Scene = pardes.config.Runtime.Scene; +pub const max = Chain.max; + +const prefix = @embedFile("post-prefix.glsl"); + +/// A pass as a shell draws it: a bundled scene at its level, or a file with +/// its last good SPIR-V (empty until a compile succeeds), whose `revision` +/// moves each time that SPIR-V does. Slices borrow the build's (or, in an +/// attached GUI, the client's) storage until its next change. +pub const Pass = struct { + scene: ?Scene = null, + level: u8 = 0, + path: []const u8 = &.{}, + spirv: []const u8 = &.{}, + revision: u32 = 0, + /// It moves on its own (reads the clock or the frame count), so the + /// chain redraws while idle; a still pass draws only with a new frame. + animated: bool = false, +}; + +/// The bundled passes that move on their own: the CRT's hum and dither. +pub fn sceneAnimated(scene: Scene) bool { + return scene == .crt; +} + +/// Whether a Shadertoy source moves on its own: it reads the time +/// (iTime, iTimeDelta and the times of a cursor move or a focus change), +/// the frame count or the date. A mention in a comment counts too. +pub fn readsTime(source: []const u8) bool { + for ([_][]const u8{ "iTime", "iFrame", "iDate" }) |name| if (std.mem.indexOf(u8, source, name) != null) return true; + return false; +} + +/// Who to wake when a compile is done: the host's loop. +pub const Wake = struct { + ctx: ?*anyopaque = null, + call: ?*const fn (?*anyopaque) void = null, +}; + +const File = struct { + path: []u8 = &.{}, + /// The hash of the source last compiled, good or not: the same bytes + /// saved again compile nothing and say nothing twice. + source: ?u64 = null, + spirv: []u8 = &.{}, + revision: u32 = 0, + animated: bool = false, + /// Wants a compile: new to the chain, or its directory changed. + stale: bool = true, +}; + +const Result = union(enum) { + none, + unchanged, + missing, + failed: struct { text: []u8, source: u64 }, + spirv: struct { bytes: []u8, source: u64, animated: bool }, +}; + +/// One compile of the stale files, on its own thread. +const Job = struct { + io: std.Io, + gpa: std.mem.Allocator, + wake: Wake, + paths: [max][]u8 = @splat(&.{}), + known: [max]?u64 = @splat(null), + results: [max]Result = @splat(.none), + len: usize = 0, + done: std.atomic.Value(bool) = .init(false), + thread: std.Thread = undefined, +}; + +files: [max]File = @splat(.{}), +len: usize = 0, +/// The chain generation `files` follow; null before the first. +generation: ?u32 = null, +/// Moves whenever what `view` gives does: the chain or a file's SPIR-V. +revision: u32 = 0, +job: ?*Job = null, +missing_said: bool = false, + +/// Brings the files to the chain the core holds, watches their directories, +/// takes in a finished compile and starts the next. Each loop step, off the +/// frame path. True when a compile was taken in: what it said wants a frame. +pub fn sync(b: *Build, gpa: std.mem.Allocator, io: std.Io, core: *pardes.Pardes, fd: c_int, watches: *file_watch.Table, wake: Wake) bool { + var collected = false; + if (b.job) |job| { + if (!job.done.load(.acquire)) return false; + job.thread.join(); + b.job = null; + b.collect(gpa, core, job); + collected = true; + } + const chain = &core.settings.post; + if (b.generation != chain.generation) { + b.generation = chain.generation; + b.revision +%= 1; + var next: [max]File = @splat(.{}); + var len: usize = 0; + var paths: [max][]const u8 = undefined; + for (chain.list()) |entry| { + if (entry.scene != null) continue; + next[len] = for (b.files[0..b.len]) |*file| { + if (!std.mem.eql(u8, file.path, entry.path.get())) continue; + const kept = file.*; + file.* = .{}; + break kept; + } else .{ .path = gpa.dupe(u8, entry.path.get()) catch continue }; + paths[len] = next[len].path; + len += 1; + } + for (b.files[0..b.len]) |file| free(gpa, file); + b.files = next; + b.len = len; + var bufs: [max][4096]u8 = undefined; + var expanded: [max][]const u8 = undefined; + for (paths[0..len], 0..) |path, i| expanded[i] = expand(&bufs[i], path); + file_watch.watchShaders(fd, watches, expanded[0..len]); + } + var stale = false; + for (b.files[0..b.len]) |file| stale = stale or file.stale; + if (!stale) return collected; + const job = gpa.create(Job) catch return collected; + job.* = .{ .io = io, .gpa = gpa, .wake = wake }; + for (b.files[0..b.len]) |*file| { + if (!file.stale) continue; + job.paths[job.len] = gpa.dupe(u8, file.path) catch continue; + job.known[job.len] = file.source; + job.len += 1; + file.stale = false; + } + job.thread = std.Thread.spawn(.{}, compile, .{job}) catch { + for (job.paths[0..job.len]) |path| gpa.free(path); + gpa.destroy(job); + return collected; + }; + b.job = job; + return collected; +} + +/// A watched directory changed: every file is read again at the next sync. +pub fn recheck(b: *Build) void { + for (b.files[0..b.len]) |*file| file.stale = true; +} + +/// The chain as passes, in its order. +pub fn view(b: *const Build, chain: *const Chain, out: *[max]Pass) []const Pass { + for (chain.list(), 0..) |entry, i| { + out[i] = if (entry.scene) |scene| .{ .scene = scene, .level = entry.level, .animated = sceneAnimated(scene) } else for (b.files[0..b.len]) |file| { + if (std.mem.eql(u8, file.path, entry.path.get())) break .{ .path = file.path, .spirv = file.spirv, .revision = file.revision, .animated = file.animated }; + } else .{ .path = entry.path.get() }; + } + return out[0..chain.len]; +} + +pub fn deinit(b: *Build, gpa: std.mem.Allocator, fd: c_int, watches: *file_watch.Table) void { + if (b.job) |job| { + job.thread.join(); + freeJob(gpa, job); + } + for (b.files[0..b.len]) |file| free(gpa, file); + b.len = 0; + file_watch.watchShaders(fd, watches, &.{}); +} + +fn free(gpa: std.mem.Allocator, file: File) void { + gpa.free(file.path); + gpa.free(file.spirv); +} + +fn freeJob(gpa: std.mem.Allocator, job: *Job) void { + for (job.paths[0..job.len], job.results[0..job.len]) |path, result| { + gpa.free(path); + switch (result) { + .spirv => |r| gpa.free(r.bytes), + .failed => |r| gpa.free(r.text), + .none, .unchanged, .missing => {}, + } + } + gpa.destroy(job); +} + +fn collect(b: *Build, gpa: std.mem.Allocator, core: *pardes.Pardes, job: *Job) void { + defer gpa.destroy(job); + for (job.paths[0..job.len], job.results[0..job.len]) |path, result| { + defer gpa.free(path); + const file = for (b.files[0..b.len]) |*file| { + if (std.mem.eql(u8, file.path, path)) break file; + } else null; + var buf: [512]u8 = undefined; + switch (result) { + .none, .unchanged => {}, + .missing => if (!b.missing_said) { + b.missing_said = true; + core.setMessage(core.active, "Shader: glslc is not on PATH, so Shadertoy files do not run (Crt does)"); + }, + .failed => |r| { + defer gpa.free(r.text); + if (file) |f| f.source = r.source; + // glslc's first line says where: in the file's own lines. + const first = std.mem.sliceTo(r.text, '\n'); + core.setMessage(core.active, std.fmt.bufPrint(&buf, "Shader {s}: {s}", .{ path, first[0..@min(first.len, 400)] }) catch "Shader: compile failed"); + }, + .spirv => |r| { + const f = file orelse { + gpa.free(r.bytes); + continue; + }; + gpa.free(f.spirv); + f.spirv = r.bytes; + f.source = r.source; + f.animated = r.animated; + f.revision +%= 1; + b.revision +%= 1; + }, + } + } +} + +/// `~/` is the home directory. +fn expand(buf: []u8, path: []const u8) []const u8 { + if (!std.mem.startsWith(u8, path, "~/")) return path; + const home = libc.getenv("HOME") orelse return path; + return std.fmt.bufPrint(buf, "{s}/{s}", .{ std.mem.span(home), path[2..] }) catch path; +} + +/// The compile thread: each file behind the prefix, through glslc with the +/// build's own flags (build.zig compileGlsl), source on stdin, SPIR-V on +/// stdout. +fn compile(job: *Job) void { + for (job.paths[0..job.len], 0..) |path, i| job.results[i] = compileOne(job.gpa, job.io, path, job.known[i]); + job.done.store(true, .release); + if (job.wake.call) |call| call(job.wake.ctx); +} + +fn compileOne(gpa: std.mem.Allocator, io: std.Io, path: []const u8, known: ?u64) Result { + var home_buf: [4096]u8 = undefined; + // Not fs.zig's readFile: that hands the core's turn over for the read, + // a turn this thread never holds. + const body = std.Io.Dir.cwd().readFileAlloc(io, expand(&home_buf, path), gpa, .limited(1 << 20)) catch |err| + return .{ .failed = .{ .text = std.fmt.allocPrint(gpa, "cannot read it ({t})", .{err}) catch return .none, .source = 0 } }; + defer gpa.free(body); + const source = std.hash.Wyhash.hash(0, body); + if (known == source) return .unchanged; + // The prefix and the file go to glslc on its stdin: no file of ours is + // written anywhere. std's spawn does every allocation before fork and + // searches PATH on the stack after it (Io/Threaded.zig spawnPosix, + // posixExecv), so a child forked from this thread cannot wedge on a + // lock another thread held (the forkShell hazard). + var child = std.process.spawn(io, .{ + .argv = &.{ "glslc", "-fshader-stage=fragment", "-o", "-", "-" }, + .stdin = .pipe, + .stdout = .pipe, + .stderr = .pipe, + }) catch |err| return switch (err) { + error.FileNotFound => .missing, + else => .{ .failed = .{ .text = std.fmt.allocPrint(gpa, "glslc did not run ({t})", .{err}) catch return .none, .source = source } }, + }; + defer child.kill(io); + // glslc reads all of its input before it writes a byte, so writing it + // first cannot deadlock against a full output pipe. + { + var stdin = child.stdin.?; + child.stdin = null; + defer stdin.close(io); + var buf: [4096]u8 = undefined; + var writer = stdin.writer(io, &buf); + writer.interface.writeAll(prefix) catch {}; + writer.interface.writeAll(body) catch {}; + writer.interface.flush() catch {}; + } + var streams: std.Io.File.MultiReader.Buffer(2) = undefined; + var reader: std.Io.File.MultiReader = undefined; + reader.init(gpa, io, streams.toStreams(), &.{ child.stdout.?, child.stderr.? }); + defer reader.deinit(); + const failed = struct { + fn of(a: std.mem.Allocator, text: []const u8, hash: u64) Result { + return .{ .failed = .{ .text = a.dupe(u8, text) catch return .none, .source = hash } }; + } + }.of; + while (reader.fill(64, .none)) |_| { + if (reader.reader(0).buffered().len > 16 << 20 or reader.reader(1).buffered().len > 64 << 10) + return failed(gpa, "glslc said too much", source); + } else |err| switch (err) { + error.EndOfStream => {}, + else => return failed(gpa, "reading glslc failed", source), + } + const term = child.wait(io) catch return failed(gpa, "glslc did not finish", source); + const clean = switch (term) { + .exited => |code| code == 0, + else => false, + }; + if (clean) return .{ .spirv = .{ .bytes = reader.toOwnedSlice(0) catch return .none, .source = source, .animated = readsTime(body) } }; + const said = reader.toOwnedSlice(1) catch return .none; + // glslc calls its input ; the file is what a person knows. + defer gpa.free(said); + const named = std.mem.replaceOwned(u8, gpa, said, "", path) catch return failed(gpa, "glslc failed", source); + return .{ .failed = .{ .text = named, .source = source } }; +} + +test "ghostty's test shaders compile behind the prefix, and its invalid one fails with glslc's words" { + const gpa = std.testing.allocator; + const io = std.testing.io; + // ghostty's own test shaders, from its package in zig-pkg. + var pkg = std.Io.Dir.cwd().openDir(io, "zig-pkg", .{ .iterate = true }) catch return error.SkipZigTest; + defer pkg.close(io); + var it = pkg.iterate(); + const ghostty = while (it.next(io) catch null) |entry| { + if (std.mem.startsWith(u8, entry.name, "ghostty-")) break entry.name; + } else return error.SkipZigTest; + var buf: [512]u8 = undefined; + for ([_][]const u8{ "crt", "focus", "invalid" }) |name| { + const path = try std.fmt.bufPrint(&buf, "zig-pkg/{s}/src/renderer/shaders/test_shadertoy_{s}.glsl", .{ ghostty, name }); + switch (compileOne(gpa, io, path, null)) { + .missing => return error.SkipZigTest, // no glslc here + .spirv => |r| { + defer gpa.free(r.bytes); + try std.testing.expect(!std.mem.eql(u8, name, "invalid")); + // SPIR-V's magic number, little-endian. + try std.testing.expectEqual(@as(u32, 0x07230203), std.mem.readInt(u32, r.bytes[0..4], .little)); + // The same bytes again compile nothing. + try std.testing.expectEqual(Result.unchanged, compileOne(gpa, io, path, r.source)); + }, + .failed => |r| { + defer gpa.free(r.text); + try std.testing.expectEqualStrings("invalid", name); + // Named by the file, not by glslc's . + try std.testing.expect(std.mem.indexOf(u8, r.text, path) != null); + try std.testing.expect(std.mem.indexOf(u8, r.text, "") == null); + }, + .none, .unchanged => return error.TestUnexpectedResult, + } + } +} + +test "a save that changes a file compiles it again, a failed one keeps the last good SPIR-V and is said once" { + const gpa = std.testing.allocator; + const io = std.testing.io; + const core = try pardes.Pardes.init(gpa, .{ .cols = 80, .rows = 24 }); + defer core.deinit(); + _ = try core.newShell(1, ""); + const pane = core.panes[core.active].?; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + var dir_buf: [4096]u8 = undefined; + const dir = dir_buf[0..try tmp.dir.realPath(io, &dir_buf)]; + var path_buf: [4200]u8 = undefined; + const path = try std.fmt.bufPrint(&path_buf, "{s}/wave.glsl", .{dir}); + const good = "void mainImage(out vec4 o, in vec2 p) { o = texture(iChannel0, p / iResolution.xy); }\n"; + try tmp.dir.writeFile(io, .{ .sub_path = "wave.glsl", .data = good }); + try std.testing.expect(core.settings.post.set(null, path, true)); + + const fd = file_watch.init(true); + defer if (fd >= 0) { + _ = libc.close(fd); + }; + var watches: file_watch.Table = @splat(null); + var b: Build = .{}; + defer b.deinit(gpa, fd, &watches); + const settle = struct { + fn run(build: *Build, c: *pardes.Pardes, f: c_int, w: *file_watch.Table) void { + _ = build.sync(std.testing.allocator, std.testing.io, c, f, w, .{}); + while (build.job) |job| { + while (!job.done.load(.acquire)) std.Thread.yield() catch {}; + _ = build.sync(std.testing.allocator, std.testing.io, c, f, w, .{}); + } + } + }.run; + settle(&b, core, fd, &watches); + if (b.missing_said) return error.SkipZigTest; // no glslc here + var out: [max]Pass = undefined; + const first = b.view(&core.settings.post, &out)[0]; + try std.testing.expect(first.spirv.len != 0); + if (file_watch.supported) try std.testing.expect(watches[file_watch.shader_slot] != null); + + // Unchanged bytes: nothing moves. + const at = b.revision; + b.recheck(); + settle(&b, core, fd, &watches); + try std.testing.expectEqual(at, b.revision); + + // A bad save: the last good SPIR-V stays, the error is said, and the + // same bad bytes again say nothing more. + try tmp.dir.writeFile(io, .{ .sub_path = "wave.glsl", .data = "void mainImage(" }); + pane.msg_len = 0; + b.recheck(); + settle(&b, core, fd, &watches); + try std.testing.expectEqual(at, b.revision); + try std.testing.expect(std.mem.startsWith(u8, pane.msg[0..pane.msg_len], "Shader ")); + pane.msg_len = 0; + b.recheck(); + settle(&b, core, fd, &watches); + try std.testing.expectEqual(@as(u16, 0), pane.msg_len); + + // A good save again: new SPIR-V, a new revision. + try tmp.dir.writeFile(io, .{ .sub_path = "wave.glsl", .data = "// saved again\n" ++ good }); + b.recheck(); + settle(&b, core, fd, &watches); + const second = b.view(&core.settings.post, &out)[0]; + try std.testing.expect(second.revision != first.revision and b.revision != at); +} + +test "a pass animates when it reads the clock or the frame count, and only the CRT of the bundled ones" { + try std.testing.expect(readsTime("o = vec4(sin(iTime));")); + try std.testing.expect(readsTime("float f = float(iFrame % 64);")); + try std.testing.expect(readsTime("x = iTimeCursorChange;")); + try std.testing.expect(!readsTime("o = texture(iChannel0, p / iResolution.xy);")); + for (std.enums.values(Scene)) |scene| try std.testing.expectEqual(scene == .crt, sceneAnimated(scene)); +} diff --git a/src/detached/server.zig b/src/detached/server.zig index b536e4a7..de26db13 100644 --- a/src/detached/server.zig +++ b/src/detached/server.zig @@ -11,7 +11,7 @@ const host_io = @import("../host_io.zig"); const selection_pipe = @import("../selection_pipe.zig"); const file_watch = @import("../file_watch.zig"); -const shader_build = @import("../shader_build.zig"); +const ShaderBuild = @import("../ShaderBuild.zig"); const ninep_io = @import("../9p_io.zig"); @@ -177,7 +177,7 @@ pub const Session = struct { ninep_wake: std.atomic.Value(bool) = .init(false), watches: file_watch.Table = @splat(null), /// The post chain's files, compiled here for the GUIs attached. - shaders: shader_build = .{}, + shaders: ShaderBuild = .{}, check_files: bool = false, in_loop: bool = false, greet_deadline_ms: u32 = greet_deadline_default_ms, diff --git a/src/detached/wire.zig b/src/detached/wire.zig index 15d3641c..051e9317 100644 --- a/src/detached/wire.zig +++ b/src/detached/wire.zig @@ -3,7 +3,7 @@ const std = @import("std"); const pardes = @import("../pardes.zig"); const limits = @import("../memory.zig").limits; -const shader_build = @import("../shader_build.zig"); +const ShaderBuild = @import("../ShaderBuild.zig"); const Scene = pardes.config.Runtime.Scene; const ShaderAnimation = pardes.config.Runtime.ShaderAnimation; @@ -364,15 +364,15 @@ pub const ServerMsg = union(enum) { /// The session's post chain, as a GUI attached to it draws it: its passes in /// order, each a bundled scene at its level or a Shadertoy file's SPIR-V -/// (compiled by the session, shader_build.zig: a frontend reads no disk and +/// (compiled by the session, ShaderBuild.zig: a frontend reads no disk and /// runs no program), and when it animates on its own. Slices borrow the /// payload. pub const Post = struct { animation: ShaderAnimation = .on, - passes: [shader_build.max]shader_build.Pass = @splat(.{}), + passes: [ShaderBuild.max]ShaderBuild.Pass = @splat(.{}), len: u8 = 0, - pub fn list(p: *const Post) []const shader_build.Pass { + pub fn list(p: *const Post) []const ShaderBuild.Pass { return p.passes[0..p.len]; } }; @@ -1275,7 +1275,7 @@ pub fn decodeServer(tag: u8, payload: []const u8) Error!ServerMsg { .post => blk: { var p: Post = .{ .animation = try r.getTag(ShaderAnimation) }; p.len = try r.getByte(); - if (p.len > shader_build.max) return error.Overlong; + if (p.len > ShaderBuild.max) return error.Overlong; for (p.passes[0..p.len]) |*pass| { const kind = try r.getByte(); pass.* = .{ diff --git a/src/file_watch.zig b/src/file_watch.zig index 148bc836..6c746e74 100644 --- a/src/file_watch.zig +++ b/src/file_watch.zig @@ -70,7 +70,7 @@ pub const Watch = struct { /// Sharing the table also shares directory descriptors correctly when a user /// happens to open that .zon as an ordinary document. pub const theme_slot = pardes.MAX_PANES; -/// After it, one slot a post chain file (shader_build.zig): marked only so +/// After it, one slot a post chain file (ShaderBuild.zig): marked only so /// a save there wakes the host, which has the files read again; no /// generation of theirs is kept here. pub const shader_slot = theme_slot + 1; diff --git a/src/gui/Post.zig b/src/gui/Post.zig index 602b2790..fc256135 100644 --- a/src/gui/Post.zig +++ b/src/gui/Post.zig @@ -2,7 +2,7 @@ //! finished frame, each reading the one before it (the frame first) and the //! last one writing the window. A pass is the bundled Crt (shaders/post/, //! compiled with the build) or a user's file (Shader ), whose SPIR-V -//! comes from shader_build.zig: compiled by the process that holds the core, +//! comes from ShaderBuild.zig: compiled by the process that holds the core, //! this one or the detached session this GUI is attached to. A file whose //! compile fails keeps its last good pipeline. //! @@ -24,7 +24,7 @@ const Pipeline = c.SDL_GPUGraphicsPipeline; pub const max = Chain.max; const prefix = @embedFile("post-prefix.glsl"); -const Built = @import("../shader_build.zig").Pass; +const Built = @import("../ShaderBuild.zig").Pass; const vert_spv = @embedFile("post.vert.spv"); const bundled_spv = std.EnumArray(Scene, []const u8).init(.{ .crt = @embedFile("post-crt.frag.spv"), @@ -92,9 +92,9 @@ pub const Pass = struct { /// A user's file, owned; empty for a bundled pass. path: []u8 = &.{}, pipeline: ?*Pipeline = null, - /// The SPIR-V revision `pipeline` was made from (shader_build.Pass). + /// The SPIR-V revision `pipeline` was made from (ShaderBuild.Pass). revision: u32 = 0, - /// It moves on its own (shader_build.Pass). + /// It moves on its own (ShaderBuild.Pass). animated: bool = false, }; @@ -125,7 +125,7 @@ bloom_up: ?*Pipeline = null, started_ns: ?u64 = null, last_ns: u64 = 0, -/// Brings the passes to the chain a shell was given (shader_build.zig: a +/// Brings the passes to the chain a shell was given (ShaderBuild.zig: a /// local core's, or an attached session's over the wire), whose `key` moves /// whenever the chain or a file's SPIR-V does. A file whose SPIR-V has not /// moved keeps its pipeline; one the GPU refuses keeps its last, and is said @@ -203,7 +203,7 @@ pub fn ready(post: *const Post) bool { } /// The chain redraws on its own (level A) as ShaderAnimation says. -/// Only a pass that moves on its own (shader_build.Pass.animated) asks for +/// Only a pass that moves on its own (ShaderBuild.Pass.animated) asks for /// frames while idle: a still one (Bloom, Vignette, Grain, a file that reads /// no clock) is drawn again only with a frame of the core's. pub fn animating(post: *const Post, mode: pardes.config.Runtime.ShaderAnimation) bool { diff --git a/src/gui/gui.zig b/src/gui/gui.zig index b34b314d..df565b94 100644 --- a/src/gui/gui.zig +++ b/src/gui/gui.zig @@ -11,7 +11,7 @@ const config = @import("../config.zig"); const look = @import("../look.zig"); const message = pardes.Messages.Message; const file_watch = @import("../file_watch.zig"); -const shader_build = @import("../shader_build.zig"); +const ShaderBuild = @import("../ShaderBuild.zig"); const deck = @import("deck.zig"); const Post = @import("Post.zig"); const pet = @import("pet.zig"); @@ -4016,7 +4016,7 @@ const Shell = struct { inotify_fd: c_int, watches: *file_watch.Table, /// The post chain's files as SPIR-V. - shaders: shader_build = .{}, + shaders: ShaderBuild = .{}, threads_ok: bool = false, test_mode: bool = false, feed: StdinFeed = .{}, @@ -4240,7 +4240,7 @@ const Shell = struct { } }; -/// A post chain compile is done (shader_build.zig): the loop's SDL wait ends. +/// A post chain compile is done (ShaderBuild.zig): the loop's SDL wait ends. fn wakeSdl(_: ?*anyopaque) void { var event = std.mem.zeroes(c.SDL_Event); event.type = c.SDL_EVENT_USER; @@ -4391,7 +4391,7 @@ fn pollFrame(ctx: ?*anyopaque) void { stepScroll(g, core, s.gpa); _ = s.shaders.sync(s.gpa, s.io, core, s.inotify_fd, s.watches, .{ .call = wakeSdl }); { - var passes: [Post.max]shader_build.Pass = undefined; + var passes: [Post.max]ShaderBuild.Pass = undefined; g.post.sync(s.gpa, g.device, g.swapchain_format, s.shaders.view(&core.settings.post, &passes), s.shaders.revision, core); } if (s.test_mode) writeTestStatus(g, core, s.presented); diff --git a/src/main.zig b/src/main.zig index ab6f1527..efc24a11 100644 --- a/src/main.zig +++ b/src/main.zig @@ -524,7 +524,7 @@ test { _ = @import("locations_cache.zig"); _ = @import("fs.zig"); _ = @import("detached/wire.zig"); - _ = @import("shader_build.zig"); + _ = @import("ShaderBuild.zig"); _ = @import("detached/server.zig"); _ = @import("detached/client.zig"); _ = @import("9p_io.zig"); diff --git a/src/shader_build.zig b/src/shader_build.zig deleted file mode 100644 index c2610fd7..00000000 --- a/src/shader_build.zig +++ /dev/null @@ -1,428 +0,0 @@ -//! The post chain's Shadertoy files as SPIR-V (docs/render-pipeline.md §6), -//! for whichever process holds the core: a local GUI makes its pipelines -//! from them, a detached session sends them to the GUIs attached to it -//! (wire `post`), which never read a disk or run a program themselves. -//! -//! Each file compiles behind the prefix by the build's own glslc invocation, -//! on a thread of its own and never on the frame path, when it joins the -//! chain and again whenever a save changes its bytes: the files' directories -//! are watched (file_watch.watchShaders) and a change there has every file -//! read and hashed, an unchanged one compiling nothing. A compile that fails -//! keeps the last good SPIR-V and is said once, and glslc missing is said -//! once for good. -const std = @import("std"); -const libc = std.c; -const pardes = @import("pardes.zig"); -const file_watch = @import("file_watch.zig"); - -const Build = @This(); -const Chain = pardes.config.Runtime.Post; -const Scene = pardes.config.Runtime.Scene; -pub const max = Chain.max; - -const prefix = @embedFile("post-prefix.glsl"); - -/// A pass as a shell draws it: a bundled scene at its level, or a file with -/// its last good SPIR-V (empty until a compile succeeds), whose `revision` -/// moves each time that SPIR-V does. Slices borrow the build's (or, in an -/// attached GUI, the client's) storage until its next change. -pub const Pass = struct { - scene: ?Scene = null, - level: u8 = 0, - path: []const u8 = &.{}, - spirv: []const u8 = &.{}, - revision: u32 = 0, - /// It moves on its own (reads the clock or the frame count), so the - /// chain redraws while idle; a still pass draws only with a new frame. - animated: bool = false, -}; - -/// The bundled passes that move on their own: the CRT's hum and dither. -pub fn sceneAnimated(scene: Scene) bool { - return scene == .crt; -} - -/// Whether a Shadertoy source moves on its own: it reads the time -/// (iTime, iTimeDelta and the times of a cursor move or a focus change), -/// the frame count or the date. A mention in a comment counts too. -pub fn readsTime(source: []const u8) bool { - for ([_][]const u8{ "iTime", "iFrame", "iDate" }) |name| if (std.mem.indexOf(u8, source, name) != null) return true; - return false; -} - -/// Who to wake when a compile is done: the host's loop. -pub const Wake = struct { - ctx: ?*anyopaque = null, - call: ?*const fn (?*anyopaque) void = null, -}; - -const File = struct { - path: []u8 = &.{}, - /// The hash of the source last compiled, good or not: the same bytes - /// saved again compile nothing and say nothing twice. - source: ?u64 = null, - spirv: []u8 = &.{}, - revision: u32 = 0, - animated: bool = false, - /// Wants a compile: new to the chain, or its directory changed. - stale: bool = true, -}; - -const Result = union(enum) { - none, - unchanged, - missing, - failed: struct { text: []u8, source: u64 }, - spirv: struct { bytes: []u8, source: u64, animated: bool }, -}; - -/// One compile of the stale files, on its own thread. -const Job = struct { - io: std.Io, - gpa: std.mem.Allocator, - wake: Wake, - paths: [max][]u8 = @splat(&.{}), - known: [max]?u64 = @splat(null), - results: [max]Result = @splat(.none), - len: usize = 0, - done: std.atomic.Value(bool) = .init(false), - thread: std.Thread = undefined, -}; - -files: [max]File = @splat(.{}), -len: usize = 0, -/// The chain generation `files` follow; null before the first. -generation: ?u32 = null, -/// Moves whenever what `view` gives does: the chain or a file's SPIR-V. -revision: u32 = 0, -job: ?*Job = null, -missing_said: bool = false, - -/// Brings the files to the chain the core holds, watches their directories, -/// takes in a finished compile and starts the next. Each loop step, off the -/// frame path. True when a compile was taken in: what it said wants a frame. -pub fn sync(b: *Build, gpa: std.mem.Allocator, io: std.Io, core: *pardes.Pardes, fd: c_int, watches: *file_watch.Table, wake: Wake) bool { - var collected = false; - if (b.job) |job| { - if (!job.done.load(.acquire)) return false; - job.thread.join(); - b.job = null; - b.collect(gpa, core, job); - collected = true; - } - const chain = &core.settings.post; - if (b.generation != chain.generation) { - b.generation = chain.generation; - b.revision +%= 1; - var next: [max]File = @splat(.{}); - var len: usize = 0; - var paths: [max][]const u8 = undefined; - for (chain.list()) |entry| { - if (entry.scene != null) continue; - next[len] = for (b.files[0..b.len]) |*file| { - if (!std.mem.eql(u8, file.path, entry.path.get())) continue; - const kept = file.*; - file.* = .{}; - break kept; - } else .{ .path = gpa.dupe(u8, entry.path.get()) catch continue }; - paths[len] = next[len].path; - len += 1; - } - for (b.files[0..b.len]) |file| free(gpa, file); - b.files = next; - b.len = len; - var bufs: [max][4096]u8 = undefined; - var expanded: [max][]const u8 = undefined; - for (paths[0..len], 0..) |path, i| expanded[i] = expand(&bufs[i], path); - file_watch.watchShaders(fd, watches, expanded[0..len]); - } - var stale = false; - for (b.files[0..b.len]) |file| stale = stale or file.stale; - if (!stale) return collected; - const job = gpa.create(Job) catch return collected; - job.* = .{ .io = io, .gpa = gpa, .wake = wake }; - for (b.files[0..b.len]) |*file| { - if (!file.stale) continue; - job.paths[job.len] = gpa.dupe(u8, file.path) catch continue; - job.known[job.len] = file.source; - job.len += 1; - file.stale = false; - } - job.thread = std.Thread.spawn(.{}, compile, .{job}) catch { - for (job.paths[0..job.len]) |path| gpa.free(path); - gpa.destroy(job); - return collected; - }; - b.job = job; - return collected; -} - -/// A watched directory changed: every file is read again at the next sync. -pub fn recheck(b: *Build) void { - for (b.files[0..b.len]) |*file| file.stale = true; -} - -/// The chain as passes, in its order. -pub fn view(b: *const Build, chain: *const Chain, out: *[max]Pass) []const Pass { - for (chain.list(), 0..) |entry, i| { - out[i] = if (entry.scene) |scene| .{ .scene = scene, .level = entry.level, .animated = sceneAnimated(scene) } else for (b.files[0..b.len]) |file| { - if (std.mem.eql(u8, file.path, entry.path.get())) break .{ .path = file.path, .spirv = file.spirv, .revision = file.revision, .animated = file.animated }; - } else .{ .path = entry.path.get() }; - } - return out[0..chain.len]; -} - -pub fn deinit(b: *Build, gpa: std.mem.Allocator, fd: c_int, watches: *file_watch.Table) void { - if (b.job) |job| { - job.thread.join(); - freeJob(gpa, job); - } - for (b.files[0..b.len]) |file| free(gpa, file); - b.len = 0; - file_watch.watchShaders(fd, watches, &.{}); -} - -fn free(gpa: std.mem.Allocator, file: File) void { - gpa.free(file.path); - gpa.free(file.spirv); -} - -fn freeJob(gpa: std.mem.Allocator, job: *Job) void { - for (job.paths[0..job.len], job.results[0..job.len]) |path, result| { - gpa.free(path); - switch (result) { - .spirv => |r| gpa.free(r.bytes), - .failed => |r| gpa.free(r.text), - .none, .unchanged, .missing => {}, - } - } - gpa.destroy(job); -} - -fn collect(b: *Build, gpa: std.mem.Allocator, core: *pardes.Pardes, job: *Job) void { - defer gpa.destroy(job); - for (job.paths[0..job.len], job.results[0..job.len]) |path, result| { - defer gpa.free(path); - const file = for (b.files[0..b.len]) |*file| { - if (std.mem.eql(u8, file.path, path)) break file; - } else null; - var buf: [512]u8 = undefined; - switch (result) { - .none, .unchanged => {}, - .missing => if (!b.missing_said) { - b.missing_said = true; - core.setMessage(core.active, "Shader: glslc is not on PATH, so Shadertoy files do not run (Crt does)"); - }, - .failed => |r| { - defer gpa.free(r.text); - if (file) |f| f.source = r.source; - // glslc's first line says where: in the file's own lines. - const first = std.mem.sliceTo(r.text, '\n'); - core.setMessage(core.active, std.fmt.bufPrint(&buf, "Shader {s}: {s}", .{ path, first[0..@min(first.len, 400)] }) catch "Shader: compile failed"); - }, - .spirv => |r| { - const f = file orelse { - gpa.free(r.bytes); - continue; - }; - gpa.free(f.spirv); - f.spirv = r.bytes; - f.source = r.source; - f.animated = r.animated; - f.revision +%= 1; - b.revision +%= 1; - }, - } - } -} - -/// `~/` is the home directory. -fn expand(buf: []u8, path: []const u8) []const u8 { - if (!std.mem.startsWith(u8, path, "~/")) return path; - const home = libc.getenv("HOME") orelse return path; - return std.fmt.bufPrint(buf, "{s}/{s}", .{ std.mem.span(home), path[2..] }) catch path; -} - -/// The compile thread: each file behind the prefix, through glslc with the -/// build's own flags (build.zig compileGlsl), source on stdin, SPIR-V on -/// stdout. -fn compile(job: *Job) void { - for (job.paths[0..job.len], 0..) |path, i| job.results[i] = compileOne(job.gpa, job.io, path, job.known[i]); - job.done.store(true, .release); - if (job.wake.call) |call| call(job.wake.ctx); -} - -fn compileOne(gpa: std.mem.Allocator, io: std.Io, path: []const u8, known: ?u64) Result { - var home_buf: [4096]u8 = undefined; - // Not fs.zig's readFile: that hands the core's turn over for the read, - // a turn this thread never holds. - const body = std.Io.Dir.cwd().readFileAlloc(io, expand(&home_buf, path), gpa, .limited(1 << 20)) catch |err| - return .{ .failed = .{ .text = std.fmt.allocPrint(gpa, "cannot read it ({t})", .{err}) catch return .none, .source = 0 } }; - defer gpa.free(body); - const source = std.hash.Wyhash.hash(0, body); - if (known == source) return .unchanged; - // The prefix and the file go to glslc on its stdin: no file of ours is - // written anywhere. std's spawn does every allocation before fork and - // searches PATH on the stack after it (Io/Threaded.zig spawnPosix, - // posixExecv), so a child forked from this thread cannot wedge on a - // lock another thread held (the forkShell hazard). - var child = std.process.spawn(io, .{ - .argv = &.{ "glslc", "-fshader-stage=fragment", "-o", "-", "-" }, - .stdin = .pipe, - .stdout = .pipe, - .stderr = .pipe, - }) catch |err| return switch (err) { - error.FileNotFound => .missing, - else => .{ .failed = .{ .text = std.fmt.allocPrint(gpa, "glslc did not run ({t})", .{err}) catch return .none, .source = source } }, - }; - defer child.kill(io); - // glslc reads all of its input before it writes a byte, so writing it - // first cannot deadlock against a full output pipe. - { - var stdin = child.stdin.?; - child.stdin = null; - defer stdin.close(io); - var buf: [4096]u8 = undefined; - var writer = stdin.writer(io, &buf); - writer.interface.writeAll(prefix) catch {}; - writer.interface.writeAll(body) catch {}; - writer.interface.flush() catch {}; - } - var streams: std.Io.File.MultiReader.Buffer(2) = undefined; - var reader: std.Io.File.MultiReader = undefined; - reader.init(gpa, io, streams.toStreams(), &.{ child.stdout.?, child.stderr.? }); - defer reader.deinit(); - const failed = struct { - fn of(a: std.mem.Allocator, text: []const u8, hash: u64) Result { - return .{ .failed = .{ .text = a.dupe(u8, text) catch return .none, .source = hash } }; - } - }.of; - while (reader.fill(64, .none)) |_| { - if (reader.reader(0).buffered().len > 16 << 20 or reader.reader(1).buffered().len > 64 << 10) - return failed(gpa, "glslc said too much", source); - } else |err| switch (err) { - error.EndOfStream => {}, - else => return failed(gpa, "reading glslc failed", source), - } - const term = child.wait(io) catch return failed(gpa, "glslc did not finish", source); - const clean = switch (term) { - .exited => |code| code == 0, - else => false, - }; - if (clean) return .{ .spirv = .{ .bytes = reader.toOwnedSlice(0) catch return .none, .source = source, .animated = readsTime(body) } }; - const said = reader.toOwnedSlice(1) catch return .none; - // glslc calls its input ; the file is what a person knows. - defer gpa.free(said); - const named = std.mem.replaceOwned(u8, gpa, said, "", path) catch return failed(gpa, "glslc failed", source); - return .{ .failed = .{ .text = named, .source = source } }; -} - -test "ghostty's test shaders compile behind the prefix, and its invalid one fails with glslc's words" { - const gpa = std.testing.allocator; - const io = std.testing.io; - // ghostty's own test shaders, from its package in zig-pkg. - var pkg = std.Io.Dir.cwd().openDir(io, "zig-pkg", .{ .iterate = true }) catch return error.SkipZigTest; - defer pkg.close(io); - var it = pkg.iterate(); - const ghostty = while (it.next(io) catch null) |entry| { - if (std.mem.startsWith(u8, entry.name, "ghostty-")) break entry.name; - } else return error.SkipZigTest; - var buf: [512]u8 = undefined; - for ([_][]const u8{ "crt", "focus", "invalid" }) |name| { - const path = try std.fmt.bufPrint(&buf, "zig-pkg/{s}/src/renderer/shaders/test_shadertoy_{s}.glsl", .{ ghostty, name }); - switch (compileOne(gpa, io, path, null)) { - .missing => return error.SkipZigTest, // no glslc here - .spirv => |r| { - defer gpa.free(r.bytes); - try std.testing.expect(!std.mem.eql(u8, name, "invalid")); - // SPIR-V's magic number, little-endian. - try std.testing.expectEqual(@as(u32, 0x07230203), std.mem.readInt(u32, r.bytes[0..4], .little)); - // The same bytes again compile nothing. - try std.testing.expectEqual(Result.unchanged, compileOne(gpa, io, path, r.source)); - }, - .failed => |r| { - defer gpa.free(r.text); - try std.testing.expectEqualStrings("invalid", name); - // Named by the file, not by glslc's . - try std.testing.expect(std.mem.indexOf(u8, r.text, path) != null); - try std.testing.expect(std.mem.indexOf(u8, r.text, "") == null); - }, - .none, .unchanged => return error.TestUnexpectedResult, - } - } -} - -test "a save that changes a file compiles it again, a failed one keeps the last good SPIR-V and is said once" { - const gpa = std.testing.allocator; - const io = std.testing.io; - const core = try pardes.Pardes.init(gpa, .{ .cols = 80, .rows = 24 }); - defer core.deinit(); - _ = try core.newShell(1, ""); - const pane = core.panes[core.active].?; - var tmp = std.testing.tmpDir(.{}); - defer tmp.cleanup(); - var dir_buf: [4096]u8 = undefined; - const dir = dir_buf[0..try tmp.dir.realPath(io, &dir_buf)]; - var path_buf: [4200]u8 = undefined; - const path = try std.fmt.bufPrint(&path_buf, "{s}/wave.glsl", .{dir}); - const good = "void mainImage(out vec4 o, in vec2 p) { o = texture(iChannel0, p / iResolution.xy); }\n"; - try tmp.dir.writeFile(io, .{ .sub_path = "wave.glsl", .data = good }); - try std.testing.expect(core.settings.post.set(null, path, true)); - - const fd = file_watch.init(true); - defer if (fd >= 0) { - _ = libc.close(fd); - }; - var watches: file_watch.Table = @splat(null); - var b: Build = .{}; - defer b.deinit(gpa, fd, &watches); - const settle = struct { - fn run(build: *Build, c: *pardes.Pardes, f: c_int, w: *file_watch.Table) void { - _ = build.sync(std.testing.allocator, std.testing.io, c, f, w, .{}); - while (build.job) |job| { - while (!job.done.load(.acquire)) std.Thread.yield() catch {}; - _ = build.sync(std.testing.allocator, std.testing.io, c, f, w, .{}); - } - } - }.run; - settle(&b, core, fd, &watches); - if (b.missing_said) return error.SkipZigTest; // no glslc here - var out: [max]Pass = undefined; - const first = b.view(&core.settings.post, &out)[0]; - try std.testing.expect(first.spirv.len != 0); - if (file_watch.supported) try std.testing.expect(watches[file_watch.shader_slot] != null); - - // Unchanged bytes: nothing moves. - const at = b.revision; - b.recheck(); - settle(&b, core, fd, &watches); - try std.testing.expectEqual(at, b.revision); - - // A bad save: the last good SPIR-V stays, the error is said, and the - // same bad bytes again say nothing more. - try tmp.dir.writeFile(io, .{ .sub_path = "wave.glsl", .data = "void mainImage(" }); - pane.msg_len = 0; - b.recheck(); - settle(&b, core, fd, &watches); - try std.testing.expectEqual(at, b.revision); - try std.testing.expect(std.mem.startsWith(u8, pane.msg[0..pane.msg_len], "Shader ")); - pane.msg_len = 0; - b.recheck(); - settle(&b, core, fd, &watches); - try std.testing.expectEqual(@as(u16, 0), pane.msg_len); - - // A good save again: new SPIR-V, a new revision. - try tmp.dir.writeFile(io, .{ .sub_path = "wave.glsl", .data = "// saved again\n" ++ good }); - b.recheck(); - settle(&b, core, fd, &watches); - const second = b.view(&core.settings.post, &out)[0]; - try std.testing.expect(second.revision != first.revision and b.revision != at); -} - -test "a pass animates when it reads the clock or the frame count, and only the CRT of the bundled ones" { - try std.testing.expect(readsTime("o = vec4(sin(iTime));")); - try std.testing.expect(readsTime("float f = float(iFrame % 64);")); - try std.testing.expect(readsTime("x = iTimeCursorChange;")); - try std.testing.expect(!readsTime("o = texture(iChannel0, p / iResolution.xy);")); - for (std.enums.values(Scene)) |scene| try std.testing.expectEqual(scene == .crt, sceneAnimated(scene)); -} -- cgit v1.3 From 8e144c7b9342f800f0cc5ad6c367b2ab799b683e Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Tue, 29 Sep 2026 20:34:15 -0300 Subject: locations_config.zig and locations_cache.zig fold into locations.zig, the Locations setting and cache beside what uses them Config (75 lines) was re-exported from locations.zig already, and Cache (213) served only its format; locations.zig is 683 lines with them. The cache's own Result, which would be ambiguous beside locations' Result in one file, is Cache.Hit, what its comment already called it. pardes.zig, dump.zig and main.zig import locations.zig. No behaviour changes. Co-Authored-By: Claude Opus 5.5 --- src/dump.zig | 2 +- src/locations.zig | 292 ++++++++++++++++++++++++++++++++++++++++++++++- src/locations_cache.zig | 213 ---------------------------------- src/locations_config.zig | 75 ------------ src/main.zig | 2 +- src/pardes.zig | 8 +- 6 files changed, 296 insertions(+), 296 deletions(-) delete mode 100644 src/locations_cache.zig delete mode 100644 src/locations_config.zig (limited to 'src/main.zig') diff --git a/src/dump.zig b/src/dump.zig index a2efb95d..1eabdae8 100644 --- a/src/dump.zig +++ b/src/dump.zig @@ -278,7 +278,7 @@ pub const State = struct { topbar: []const u8 = "", topbar_custom: ?[]const u8 = null, theme: []const u8 = "dark", - locations_config: @import("locations_config.zig").Config = .{}, + locations_config: @import("locations.zig").Config = .{}, tree_context_tag_style: bool = true, columns: []const Column = &.{}, panes: []const Pane = &.{}, diff --git a/src/locations.zig b/src/locations.zig index b34f7a6f..6a604907 100644 --- a/src/locations.zig +++ b/src/locations.zig @@ -4,7 +4,6 @@ const look = @import("look.zig"); const syntax = @import("syntax.zig"); const filesystem = @import("fs.zig"); -pub const Config = @import("locations_config.zig").Config; const neighbor_context: u8 = 1; const declaration_context: u8 = 2; const declaration_start: u8 = 4; @@ -206,7 +205,7 @@ pub fn format(p: *pardes.Pardes, dir: []const u8, input: []const u8, anchor: ?us // Muted declaration headers do not need a source-color pass. // Exact bytes include unsaved edits and virtual/remote sources. var cached = p.locations_cache.get(p.tree_sitter_gpa, text.path, source, p.locations_config.tscontext, p.locations_config.context > 0) catch - @import("locations_cache.zig").Result{ .analysis = syntax.analyzeSource(arena, text.path, source, p.locations_config.tscontext, p.locations_config.context > 0) catch .{} }; + Cache.Hit{ .analysis = syntax.analyzeSource(arena, text.path, source, p.locations_config.tscontext, p.locations_config.context > 0) catch .{} }; defer cached.deinit(p.tree_sitter_gpa); const analysis = cached.analysis; const source_colors = analysis.colors; @@ -393,3 +392,292 @@ test "locations native results retain the first source tab" { try std.testing.expectEqualStrings("some directory/a.zig", row.path); try std.testing.expectEqualStrings("\t value", text[row.code_start..]); } + +// ---- the Locations setting ---- + +pub const Config = struct { + pub const Layout = enum { @"inline", stacked }; + context: u16 = 0, + tscontext: bool = false, + tslocations: bool = true, + layout: Layout = .stacked, + + /// Apply only supplied fields. A malformed token rejects the whole update. + /// Repeating a field uses its last supplied value. + pub fn parse(current: Config, text: []const u8) !Config { + var result = current; + var tokens = std.mem.tokenizeAny(u8, text, " \t\r\n"); + while (tokens.next()) |token| { + const colon = std.mem.indexOfScalar(u8, token, ':') orelse return error.ExpectedKeyValue; + const key = token[0..colon]; + const value = token[colon + 1 ..]; + var found = false; + inline for (@typeInfo(Config).@"struct".fields) |field| { + if (std.mem.eql(u8, key, field.name)) { + @field(result, field.name) = switch (@typeInfo(field.type)) { + .bool => if (std.mem.eql(u8, value, "on")) true else if (std.mem.eql(u8, value, "off")) false else return error.ExpectedOnOrOff, + .int => std.fmt.parseInt(field.type, value, 10) catch return error.InvalidContext, + .@"enum" => std.meta.stringToEnum(field.type, value) orelse return error.InvalidLayout, + else => @compileError("unsupported location setting type"), + }; + found = true; + } + } + if (!found) return error.UnknownLocationSetting; + } + return result; + } + + pub fn write(config: Config, writer: *std.Io.Writer) !void { + inline for (@typeInfo(Config).@"struct".fields, 0..) |field, index| { + if (index > 0) try writer.writeByte(' '); + try writer.writeAll(field.name ++ ":"); + const value = @field(config, field.name); + switch (@typeInfo(field.type)) { + .bool => try writer.writeAll(if (value) "on" else "off"), + .int => try writer.print("{d}", .{value}), + .@"enum" => try writer.writeAll(@tagName(value)), + else => @compileError("unsupported location setting type"), + } + } + } +}; + +test "LocationsConfig reflection round trip and partial updates" { + var config: Config = .{}; + config = try config.parse("context:5 tscontext:on"); + config = try config.parse("tslocations:off"); + try std.testing.expectEqual(Config{ .context = 5, .tscontext = true, .tslocations = false }, config); + var out: std.Io.Writer.Allocating = .init(std.testing.allocator); + defer out.deinit(); + try config.write(&out.writer); + try std.testing.expectEqualStrings("context:5 tscontext:on tslocations:off layout:stacked", out.written()); + try std.testing.expectEqual(config, try (Config{}).parse(out.written())); + try std.testing.expectEqual(config, try config.parse(" \n\t")); + try std.testing.expectEqual(@as(u16, 2), (try config.parse("context:1 context:2")).context); + try std.testing.expectEqual(Config.Layout.@"inline", (try config.parse("layout:inline")).layout); +} + +test "LocationsConfig rejects invalid updates atomically" { + const config: Config = .{ .context = 3, .tscontext = true }; + try std.testing.expectError(error.UnknownLocationSetting, config.parse("context:5 unknown:on")); + try std.testing.expectError(error.ExpectedOnOrOff, config.parse("context:5 tscontext:true")); + try std.testing.expectError(error.ExpectedKeyValue, config.parse("context")); + try std.testing.expectError(error.InvalidLayout, config.parse("context:5 layout:sideways")); + for ([_][]const u8{ "context:", "context:-1", "context:65536", "context:five" }) |input| + try std.testing.expectError(error.InvalidContext, config.parse(input)); + try std.testing.expectEqual(@as(u16, 3), config.context); +} + +// ---- the analysis cache ---- + +/// Owned source snapshots keep analysis valid across filesystem changes and +/// borrowed editor buffers. Entries are ordered from least to most recent. +pub const Cache = struct { + /// A cache hit borrows its analysis; an entry too large to retain transfers + /// ownership instead. Call deinit after consuming either result. + pub const Hit = struct { + analysis: syntax.SourceAnalysis, + owned: bool = false, + + pub fn deinit(result: *Hit, gpa: std.mem.Allocator) void { + if (result.owned) result.analysis.deinit(gpa); + result.* = undefined; + } + }; + + pub const max_bytes = 64 * 1024 * 1024; + pub const max_entries = 64; + + const Entry = struct { + path: []u8, + source: []u8, + analysis: syntax.SourceAnalysis, + declarations_ready: bool, + colors_ready: bool, + + fn size(entry: Entry) usize { + return entry.path.len + entry.source.len + entry.analysis.colors.len + + entry.analysis.declarations.len * @sizeOf(syntax.ContextDeclaration); + } + + fn deinit(entry: *Entry, gpa: std.mem.Allocator) void { + gpa.free(entry.path); + gpa.free(entry.source); + entry.analysis.deinit(gpa); + } + }; + + entries: [max_entries]Entry = undefined, + len: usize = 0, + bytes: usize = 0, + analyses: usize = 0, + hits: usize = 0, + + pub fn deinit(cache: *Cache, gpa: std.mem.Allocator) void { + for (cache.entries[0..cache.len]) |*entry| entry.deinit(gpa); + cache.* = .{}; + } + + /// Borrowed slices remain valid until the next get or cache deinit; an + /// owned result remains valid until Hit.deinit. All calls for this + /// cache must use the same allocator. Unsupported languages + /// are cached too, including their empty analysis arrays. + pub fn get(cache: *Cache, gpa: std.mem.Allocator, path: []const u8, source: []const u8, want_declarations: bool, want_colors: bool) !Hit { + return cache.getBounded(gpa, path, source, want_declarations, want_colors, max_bytes); + } + + fn getBounded(cache: *Cache, gpa: std.mem.Allocator, path: []const u8, source: []const u8, want_declarations: bool, want_colors: bool, budget: usize) !Hit { + if (source.len > budget or path.len > budget - source.len) return error.SourceTooLarge; + var previous: ?usize = null; + var declarations = want_declarations; + var colors = want_colors; + for (cache.entries[0..cache.len], 0..) |entry, index| { + if (!std.mem.eql(u8, entry.path, path)) continue; + previous = index; + if (!std.mem.eql(u8, entry.source, source)) break; + if ((!want_declarations or entry.declarations_ready) and (!want_colors or entry.colors_ready)) { + // Moving the small ownership record keeps the underlying + // allocations intact and avoids timestamp/overflow state. + std.mem.copyForwards(Entry, cache.entries[index .. cache.len - 1], cache.entries[index + 1 .. cache.len]); + cache.entries[cache.len - 1] = entry; + cache.hits +|= 1; + return .{ .analysis = entry.analysis }; + } + declarations = declarations or entry.declarations_ready; + colors = colors or entry.colors_ready; + break; + } + // A supported full-source color map needs one byte per source byte. + // Reject that known minimum before parsing, so the caller's uncached + // path does not repeat an expensive analysis for oversized inputs. + const input_bytes = path.len + source.len; + if (colors and syntax.supportsPath(path) and source.len > budget - input_bytes) return error.SourceTooLarge; + var analysis = try syntax.analyzeSource(gpa, path, source, declarations, colors); + errdefer analysis.deinit(gpa); + cache.analyses +|= 1; + const analysis_bytes = analysis.colors.len + analysis.declarations.len * @sizeOf(syntax.ContextDeclaration); + if (analysis_bytes > budget - input_bytes) return .{ .analysis = analysis, .owned = true }; + const owned_path = try gpa.dupe(u8, path); + errdefer gpa.free(owned_path); + const owned_source = try gpa.dupe(u8, source); + errdefer gpa.free(owned_source); + const next: Entry = .{ + .path = owned_path, + .source = owned_source, + .analysis = analysis, + .declarations_ready = declarations, + .colors_ready = colors, + }; + // Commit only after every allocation succeeds. A failed refresh leaves + // the previous cached snapshot usable by the next request. + if (previous) |index| cache.remove(gpa, index); + while (cache.len == max_entries or cache.bytes > budget - next.size()) cache.remove(gpa, 0); + cache.entries[cache.len] = next; + cache.len += 1; + cache.bytes += next.size(); + return .{ .analysis = next.analysis }; + } + + fn remove(cache: *Cache, gpa: std.mem.Allocator, index: usize) void { + cache.bytes -= cache.entries[index].size(); + cache.entries[index].deinit(gpa); + std.mem.copyForwards(Entry, cache.entries[index .. cache.len - 1], cache.entries[index + 1 .. cache.len]); + cache.len -= 1; + } +}; + +test "locations cache validates exact source and path and upgrades analysis" { + const gpa = std.testing.allocator; + syntax.start(gpa); + defer syntax.stop(); + var cache: Cache = .{}; + defer cache.deinit(gpa); + const source = "const Thing = struct {\n value: u32,\n};\n"; + _ = try cache.get(gpa, "a.zig", source, true, false); + try std.testing.expectEqual(@as(usize, 1), cache.analyses); + _ = try cache.get(gpa, "a.zig", source, true, false); + try std.testing.expectEqual(@as(usize, 1), cache.analyses); + try std.testing.expectEqual(@as(usize, 1), cache.hits); + _ = try cache.get(gpa, "a.zig", source, false, true); + try std.testing.expectEqual(@as(usize, 2), cache.analyses); + try std.testing.expect(cache.entries[0].declarations_ready and cache.entries[0].colors_ready); + _ = try cache.get(gpa, "a.zig", source, true, true); + try std.testing.expectEqual(@as(usize, 2), cache.analyses); + _ = try cache.get(gpa, "a.zig", "const Thing = struct {\n other: u32,\n};\n", true, true); + try std.testing.expectEqual(@as(usize, 3), cache.analyses); + try std.testing.expectEqual(@as(usize, 1), cache.len); + _ = try cache.get(gpa, "a.txt", source, true, true); + try std.testing.expectEqual(@as(usize, 4), cache.analyses); + try std.testing.expectEqual(@as(usize, 2), cache.len); +} + +test "locations cache bounds memory and entries and evicts least recently used" { + const gpa = std.testing.allocator; + var cache: Cache = .{}; + defer cache.deinit(gpa); + for (0..Cache.max_entries) |index| { + var path: [32]u8 = undefined; + _ = try cache.get(gpa, try std.fmt.bufPrint(&path, "{d}.unknown", .{index}), "source", false, false); + } + _ = try cache.get(gpa, "0.unknown", "source", false, false); + _ = try cache.get(gpa, "new.unknown", "source", false, false); + try std.testing.expectEqual(Cache.max_entries, cache.len); + try std.testing.expectEqualStrings("2.unknown", cache.entries[0].path); + const count = cache.analyses; + _ = try cache.get(gpa, "0.unknown", "source", false, false); + try std.testing.expectEqual(count, cache.analyses); + cache.deinit(gpa); + _ = try cache.getBounded(gpa, "a.unknown", "source", false, false, 40); + _ = try cache.getBounded(gpa, "b.unknown", "source", false, false, 40); + _ = try cache.getBounded(gpa, "c.unknown", "source", false, false, 40); + try std.testing.expectEqual(@as(usize, 2), cache.len); + try std.testing.expect(cache.bytes <= 40); + try std.testing.expectEqualStrings("b.unknown", cache.entries[0].path); + try std.testing.expectError(error.SourceTooLarge, cache.getBounded(gpa, "large.unknown", "x" ** 41, false, false, 40)); + try std.testing.expectEqual(@as(usize, 2), cache.len); + if (syntax.supportsPath("large.zig")) { + const before = cache.analyses; + try std.testing.expectError(error.SourceTooLarge, cache.getBounded(gpa, "large.zig", "x" ** 25, true, true, 40)); + try std.testing.expectEqual(before, cache.analyses); + } + cache.deinit(gpa); + try std.testing.expectEqual(@as(usize, 0), cache.bytes); + try std.testing.expectEqual(@as(usize, 0), cache.len); +} + +test "locations cache keeps its previous snapshot after allocation failure" { + var failing = std.testing.FailingAllocator.init(std.testing.allocator, .{}); + const gpa = failing.allocator(); + var cache: Cache = .{}; + defer cache.deinit(gpa); + _ = try cache.get(gpa, "a.unknown", "old bytes", false, false); + const retained = cache.bytes; + failing.fail_index = failing.alloc_index; + try std.testing.expectError(error.OutOfMemory, cache.get(gpa, "a.unknown", "new bytes", false, false)); + try std.testing.expectEqual(@as(usize, 1), cache.len); + try std.testing.expectEqual(retained, cache.bytes); + try std.testing.expectEqualStrings("old bytes", cache.entries[0].source); + // This succeeds with allocations still disabled because the old entry + // remains valid and the hit path moves ownership records only. + _ = try cache.get(gpa, "a.unknown", "old bytes", false, false); + try std.testing.expectEqual(@as(usize, 1), cache.hits); +} + +test "locations cache transfers oversized completed analysis without reparsing" { + if (!syntax.supportsPath("large.zig")) return error.SkipZigTest; + const gpa = std.testing.allocator; + syntax.start(gpa); + defer syntax.stop(); + var cache: Cache = .{}; + defer cache.deinit(gpa); + const source = "const Thing = struct {\n value: u32,\n};\n"; + const budget = "large.zig".len + source.len; + var result = try cache.getBounded(gpa, "large.zig", source, true, false, budget); + defer result.deinit(gpa); + try std.testing.expect(result.owned); + try std.testing.expect(result.analysis.declarations.len > 0); + try std.testing.expectEqual(@as(usize, 1), cache.analyses); + try std.testing.expectEqual(@as(usize, 0), cache.len); + try std.testing.expectEqual(@as(usize, 0), cache.bytes); +} diff --git a/src/locations_cache.zig b/src/locations_cache.zig deleted file mode 100644 index a079226b..00000000 --- a/src/locations_cache.zig +++ /dev/null @@ -1,213 +0,0 @@ -const std = @import("std"); -const syntax = @import("syntax.zig"); - -/// A cache hit borrows its analysis; an entry too large to retain transfers -/// ownership instead. Call deinit after consuming either result. -pub const Result = struct { - analysis: syntax.SourceAnalysis, - owned: bool = false, - - pub fn deinit(result: *Result, gpa: std.mem.Allocator) void { - if (result.owned) result.analysis.deinit(gpa); - result.* = undefined; - } -}; - -/// Owned source snapshots keep analysis valid across filesystem changes and -/// borrowed editor buffers. Entries are ordered from least to most recent. -pub const Cache = struct { - pub const max_bytes = 64 * 1024 * 1024; - pub const max_entries = 64; - - const Entry = struct { - path: []u8, - source: []u8, - analysis: syntax.SourceAnalysis, - declarations_ready: bool, - colors_ready: bool, - - fn size(entry: Entry) usize { - return entry.path.len + entry.source.len + entry.analysis.colors.len + - entry.analysis.declarations.len * @sizeOf(syntax.ContextDeclaration); - } - - fn deinit(entry: *Entry, gpa: std.mem.Allocator) void { - gpa.free(entry.path); - gpa.free(entry.source); - entry.analysis.deinit(gpa); - } - }; - - entries: [max_entries]Entry = undefined, - len: usize = 0, - bytes: usize = 0, - analyses: usize = 0, - hits: usize = 0, - - pub fn deinit(cache: *Cache, gpa: std.mem.Allocator) void { - for (cache.entries[0..cache.len]) |*entry| entry.deinit(gpa); - cache.* = .{}; - } - - /// Borrowed slices remain valid until the next get or cache deinit; an - /// owned result remains valid until Result.deinit. All calls for this - /// cache must use the same allocator. Unsupported languages - /// are cached too, including their empty analysis arrays. - pub fn get(cache: *Cache, gpa: std.mem.Allocator, path: []const u8, source: []const u8, want_declarations: bool, want_colors: bool) !Result { - return cache.getBounded(gpa, path, source, want_declarations, want_colors, max_bytes); - } - - fn getBounded(cache: *Cache, gpa: std.mem.Allocator, path: []const u8, source: []const u8, want_declarations: bool, want_colors: bool, budget: usize) !Result { - if (source.len > budget or path.len > budget - source.len) return error.SourceTooLarge; - var previous: ?usize = null; - var declarations = want_declarations; - var colors = want_colors; - for (cache.entries[0..cache.len], 0..) |entry, index| { - if (!std.mem.eql(u8, entry.path, path)) continue; - previous = index; - if (!std.mem.eql(u8, entry.source, source)) break; - if ((!want_declarations or entry.declarations_ready) and (!want_colors or entry.colors_ready)) { - // Moving the small ownership record keeps the underlying - // allocations intact and avoids timestamp/overflow state. - std.mem.copyForwards(Entry, cache.entries[index .. cache.len - 1], cache.entries[index + 1 .. cache.len]); - cache.entries[cache.len - 1] = entry; - cache.hits +|= 1; - return .{ .analysis = entry.analysis }; - } - declarations = declarations or entry.declarations_ready; - colors = colors or entry.colors_ready; - break; - } - // A supported full-source color map needs one byte per source byte. - // Reject that known minimum before parsing, so the caller's uncached - // path does not repeat an expensive analysis for oversized inputs. - const input_bytes = path.len + source.len; - if (colors and syntax.supportsPath(path) and source.len > budget - input_bytes) return error.SourceTooLarge; - var analysis = try syntax.analyzeSource(gpa, path, source, declarations, colors); - errdefer analysis.deinit(gpa); - cache.analyses +|= 1; - const analysis_bytes = analysis.colors.len + analysis.declarations.len * @sizeOf(syntax.ContextDeclaration); - if (analysis_bytes > budget - input_bytes) return .{ .analysis = analysis, .owned = true }; - const owned_path = try gpa.dupe(u8, path); - errdefer gpa.free(owned_path); - const owned_source = try gpa.dupe(u8, source); - errdefer gpa.free(owned_source); - const next: Entry = .{ - .path = owned_path, - .source = owned_source, - .analysis = analysis, - .declarations_ready = declarations, - .colors_ready = colors, - }; - // Commit only after every allocation succeeds. A failed refresh leaves - // the previous cached snapshot usable by the next request. - if (previous) |index| cache.remove(gpa, index); - while (cache.len == max_entries or cache.bytes > budget - next.size()) cache.remove(gpa, 0); - cache.entries[cache.len] = next; - cache.len += 1; - cache.bytes += next.size(); - return .{ .analysis = next.analysis }; - } - - fn remove(cache: *Cache, gpa: std.mem.Allocator, index: usize) void { - cache.bytes -= cache.entries[index].size(); - cache.entries[index].deinit(gpa); - std.mem.copyForwards(Entry, cache.entries[index .. cache.len - 1], cache.entries[index + 1 .. cache.len]); - cache.len -= 1; - } -}; - -test "locations cache validates exact source and path and upgrades analysis" { - const gpa = std.testing.allocator; - syntax.start(gpa); - defer syntax.stop(); - var cache: Cache = .{}; - defer cache.deinit(gpa); - const source = "const Thing = struct {\n value: u32,\n};\n"; - _ = try cache.get(gpa, "a.zig", source, true, false); - try std.testing.expectEqual(@as(usize, 1), cache.analyses); - _ = try cache.get(gpa, "a.zig", source, true, false); - try std.testing.expectEqual(@as(usize, 1), cache.analyses); - try std.testing.expectEqual(@as(usize, 1), cache.hits); - _ = try cache.get(gpa, "a.zig", source, false, true); - try std.testing.expectEqual(@as(usize, 2), cache.analyses); - try std.testing.expect(cache.entries[0].declarations_ready and cache.entries[0].colors_ready); - _ = try cache.get(gpa, "a.zig", source, true, true); - try std.testing.expectEqual(@as(usize, 2), cache.analyses); - _ = try cache.get(gpa, "a.zig", "const Thing = struct {\n other: u32,\n};\n", true, true); - try std.testing.expectEqual(@as(usize, 3), cache.analyses); - try std.testing.expectEqual(@as(usize, 1), cache.len); - _ = try cache.get(gpa, "a.txt", source, true, true); - try std.testing.expectEqual(@as(usize, 4), cache.analyses); - try std.testing.expectEqual(@as(usize, 2), cache.len); -} - -test "locations cache bounds memory and entries and evicts least recently used" { - const gpa = std.testing.allocator; - var cache: Cache = .{}; - defer cache.deinit(gpa); - for (0..Cache.max_entries) |index| { - var path: [32]u8 = undefined; - _ = try cache.get(gpa, try std.fmt.bufPrint(&path, "{d}.unknown", .{index}), "source", false, false); - } - _ = try cache.get(gpa, "0.unknown", "source", false, false); - _ = try cache.get(gpa, "new.unknown", "source", false, false); - try std.testing.expectEqual(Cache.max_entries, cache.len); - try std.testing.expectEqualStrings("2.unknown", cache.entries[0].path); - const count = cache.analyses; - _ = try cache.get(gpa, "0.unknown", "source", false, false); - try std.testing.expectEqual(count, cache.analyses); - cache.deinit(gpa); - _ = try cache.getBounded(gpa, "a.unknown", "source", false, false, 40); - _ = try cache.getBounded(gpa, "b.unknown", "source", false, false, 40); - _ = try cache.getBounded(gpa, "c.unknown", "source", false, false, 40); - try std.testing.expectEqual(@as(usize, 2), cache.len); - try std.testing.expect(cache.bytes <= 40); - try std.testing.expectEqualStrings("b.unknown", cache.entries[0].path); - try std.testing.expectError(error.SourceTooLarge, cache.getBounded(gpa, "large.unknown", "x" ** 41, false, false, 40)); - try std.testing.expectEqual(@as(usize, 2), cache.len); - if (syntax.supportsPath("large.zig")) { - const before = cache.analyses; - try std.testing.expectError(error.SourceTooLarge, cache.getBounded(gpa, "large.zig", "x" ** 25, true, true, 40)); - try std.testing.expectEqual(before, cache.analyses); - } - cache.deinit(gpa); - try std.testing.expectEqual(@as(usize, 0), cache.bytes); - try std.testing.expectEqual(@as(usize, 0), cache.len); -} - -test "locations cache keeps its previous snapshot after allocation failure" { - var failing = std.testing.FailingAllocator.init(std.testing.allocator, .{}); - const gpa = failing.allocator(); - var cache: Cache = .{}; - defer cache.deinit(gpa); - _ = try cache.get(gpa, "a.unknown", "old bytes", false, false); - const retained = cache.bytes; - failing.fail_index = failing.alloc_index; - try std.testing.expectError(error.OutOfMemory, cache.get(gpa, "a.unknown", "new bytes", false, false)); - try std.testing.expectEqual(@as(usize, 1), cache.len); - try std.testing.expectEqual(retained, cache.bytes); - try std.testing.expectEqualStrings("old bytes", cache.entries[0].source); - // This succeeds with allocations still disabled because the old entry - // remains valid and the hit path moves ownership records only. - _ = try cache.get(gpa, "a.unknown", "old bytes", false, false); - try std.testing.expectEqual(@as(usize, 1), cache.hits); -} - -test "locations cache transfers oversized completed analysis without reparsing" { - if (!syntax.supportsPath("large.zig")) return error.SkipZigTest; - const gpa = std.testing.allocator; - syntax.start(gpa); - defer syntax.stop(); - var cache: Cache = .{}; - defer cache.deinit(gpa); - const source = "const Thing = struct {\n value: u32,\n};\n"; - const budget = "large.zig".len + source.len; - var result = try cache.getBounded(gpa, "large.zig", source, true, false, budget); - defer result.deinit(gpa); - try std.testing.expect(result.owned); - try std.testing.expect(result.analysis.declarations.len > 0); - try std.testing.expectEqual(@as(usize, 1), cache.analyses); - try std.testing.expectEqual(@as(usize, 0), cache.len); - try std.testing.expectEqual(@as(usize, 0), cache.bytes); -} diff --git a/src/locations_config.zig b/src/locations_config.zig deleted file mode 100644 index 6b23575a..00000000 --- a/src/locations_config.zig +++ /dev/null @@ -1,75 +0,0 @@ -const std = @import("std"); - -pub const Config = struct { - pub const Layout = enum { @"inline", stacked }; - context: u16 = 0, - tscontext: bool = false, - tslocations: bool = true, - layout: Layout = .stacked, - - /// Apply only supplied fields. A malformed token rejects the whole update. - /// Repeating a field uses its last supplied value. - pub fn parse(current: Config, text: []const u8) !Config { - var result = current; - var tokens = std.mem.tokenizeAny(u8, text, " \t\r\n"); - while (tokens.next()) |token| { - const colon = std.mem.indexOfScalar(u8, token, ':') orelse return error.ExpectedKeyValue; - const key = token[0..colon]; - const value = token[colon + 1 ..]; - var found = false; - inline for (@typeInfo(Config).@"struct".fields) |field| { - if (std.mem.eql(u8, key, field.name)) { - @field(result, field.name) = switch (@typeInfo(field.type)) { - .bool => if (std.mem.eql(u8, value, "on")) true else if (std.mem.eql(u8, value, "off")) false else return error.ExpectedOnOrOff, - .int => std.fmt.parseInt(field.type, value, 10) catch return error.InvalidContext, - .@"enum" => std.meta.stringToEnum(field.type, value) orelse return error.InvalidLayout, - else => @compileError("unsupported location setting type"), - }; - found = true; - } - } - if (!found) return error.UnknownLocationSetting; - } - return result; - } - - pub fn write(config: Config, writer: *std.Io.Writer) !void { - inline for (@typeInfo(Config).@"struct".fields, 0..) |field, index| { - if (index > 0) try writer.writeByte(' '); - try writer.writeAll(field.name ++ ":"); - const value = @field(config, field.name); - switch (@typeInfo(field.type)) { - .bool => try writer.writeAll(if (value) "on" else "off"), - .int => try writer.print("{d}", .{value}), - .@"enum" => try writer.writeAll(@tagName(value)), - else => @compileError("unsupported location setting type"), - } - } - } -}; - -test "LocationsConfig reflection round trip and partial updates" { - var config: Config = .{}; - config = try config.parse("context:5 tscontext:on"); - config = try config.parse("tslocations:off"); - try std.testing.expectEqual(Config{ .context = 5, .tscontext = true, .tslocations = false }, config); - var out: std.Io.Writer.Allocating = .init(std.testing.allocator); - defer out.deinit(); - try config.write(&out.writer); - try std.testing.expectEqualStrings("context:5 tscontext:on tslocations:off layout:stacked", out.written()); - try std.testing.expectEqual(config, try (Config{}).parse(out.written())); - try std.testing.expectEqual(config, try config.parse(" \n\t")); - try std.testing.expectEqual(@as(u16, 2), (try config.parse("context:1 context:2")).context); - try std.testing.expectEqual(Config.Layout.@"inline", (try config.parse("layout:inline")).layout); -} - -test "LocationsConfig rejects invalid updates atomically" { - const config: Config = .{ .context = 3, .tscontext = true }; - try std.testing.expectError(error.UnknownLocationSetting, config.parse("context:5 unknown:on")); - try std.testing.expectError(error.ExpectedOnOrOff, config.parse("context:5 tscontext:true")); - try std.testing.expectError(error.ExpectedKeyValue, config.parse("context")); - try std.testing.expectError(error.InvalidLayout, config.parse("context:5 layout:sideways")); - for ([_][]const u8{ "context:", "context:-1", "context:65536", "context:five" }) |input| - try std.testing.expectError(error.InvalidContext, config.parse(input)); - try std.testing.expectEqual(@as(u16, 3), config.context); -} diff --git a/src/main.zig b/src/main.zig index efc24a11..6ea05479 100644 --- a/src/main.zig +++ b/src/main.zig @@ -521,7 +521,7 @@ test { _ = pardes.config.User; _ = @import("crash.zig"); _ = @import("memory.zig"); - _ = @import("locations_cache.zig"); + _ = @import("locations.zig"); _ = @import("fs.zig"); _ = @import("detached/wire.zig"); _ = @import("ShaderBuild.zig"); diff --git a/src/pardes.zig b/src/pardes.zig index 90095556..141b214e 100644 --- a/src/pardes.zig +++ b/src/pardes.zig @@ -9,9 +9,9 @@ pub const look = @import("look.zig"); pub const filesystem = @import("fs.zig"); pub const ctlfs = @import("ninep/tree.zig"); pub const syntax = @import("syntax.zig"); -pub const locations_config = @import("locations_config.zig"); const tracy = @import("tracy.zig"); pub const panes = @import("panes.zig"); +const locations = @import("locations.zig"); pub const tagline = @import("tagline.zig"); pub const exec = @import("exec.zig"); const recent_files = @import("recent.zig"); @@ -766,7 +766,7 @@ test "LocationsConfig command reports partial updates and survives restore" { _ = try p.setTestFile("source\n"); try std.testing.expect(p.executeBuiltinLine(0, "LocationsConfig context:5 tscontext:on")); try std.testing.expect(p.executeBuiltinLine(0, "LocationsConfig tslocations:off")); - const expected: locations_config.Config = .{ .context = 5, .tscontext = true, .tslocations = false }; + const expected: locations.Config = .{ .context = 5, .tscontext = true, .tslocations = false }; try std.testing.expectEqual(expected, p.locations_config); try std.testing.expect(p.executeBuiltinLine(0, "LocationsConfig context:2 unknown:on")); try std.testing.expectEqual(expected, p.locations_config); @@ -4392,8 +4392,8 @@ pub const Pardes = struct { /// (exec.placeNew). A Look click moves the keyboard but not this. active_column: u32 = 0, settings: config.Runtime = .{ .font = .{ .tagline_percent = config.gui_tagline_font_percent } }, - locations_config: locations_config.Config = .{}, - locations_cache: @import("locations_cache.zig").Cache = .{}, + locations_config: locations.Config = .{}, + locations_cache: locations.Cache = .{}, tty_filter_palette: panes.Terminal.FilterPalette = .{}, font_request_taken: bool = false, custom_theme: ?Theme = null, -- cgit v1.3 From 714da820136ac89d6a79ed0141e7325829ab8204 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Tue, 29 Sep 2026 21:44:44 -0300 Subject: F1-F25, Insert and the keypad reach a GUI's terminal panes: one vaxis key map, vaxis_input.zig, for the tty, the gui and the board The vaxis-to-Event key mapping was copied in tty.zig, gui.zig and esp32p4.zig, and the copies had drifted: the gui's (its stdin feed, which test windows and a gui started in a terminal read) had 9 arms against the tty's 26, without the function keys, Insert or the keypad, so they reached a terminal pane as private-use codepoints. vaxis_input.zig holds effCp, mapKey and keyEvent once; the gui posts through postKey, and a test runs F5, Insert and the keypad's Up through it into a terminal pane. Co-Authored-By: Claude Opus 5.5 --- src/esp32p4.zig | 34 +++-------------------- src/gui/gui.zig | 71 ++++++++++++++++++++++++------------------------ src/main.zig | 1 + src/tty/tty.zig | 66 +++++---------------------------------------- src/vaxis_input.zig | 77 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 5 files changed, 123 insertions(+), 126 deletions(-) create mode 100644 src/vaxis_input.zig (limited to 'src/main.zig') diff --git a/src/esp32p4.zig b/src/esp32p4.zig index b7725b81..4e1fe036 100644 --- a/src/esp32p4.zig +++ b/src/esp32p4.zig @@ -32,6 +32,7 @@ const std = @import("std"); const builtin = @import("builtin"); const pardes = @import("pardes.zig"); const vaxis = @import("vaxis"); +const vaxis_input = @import("vaxis_input.zig"); // ------------------------------------------------------------------ what a freestanding root owes // @@ -394,7 +395,7 @@ fn apply(c: *pardes.Pardes, ev: vaxis.Event) void { // text at all, so a line break inside a paste arrives as a bare CR (Key.enter) or, from // a terminal that does not translate them, as ctrl+j. const text = key.text orelse ""; - const cp = mapKey(effCp(key)); + const cp = vaxis_input.mapKey(vaxis_input.effCp(key)); const bytes: []const u8 = if (text.len > 0) text else if (cp == pardes.Key.tab) @@ -406,7 +407,7 @@ fn apply(c: *pardes.Pardes, ev: vaxis.Event) void { if (bytes.len > 0) paste_buf.appendSlice(gpa(), bytes) catch {}; } else { c.update(.{ .key = .{ - .cp = mapKey(effCp(key)), + .cp = vaxis_input.mapKey(vaxis_input.effCp(key)), .text = key.text orelse "", .ctrl = key.mods.ctrl, .alt = key.mods.alt, @@ -529,35 +530,6 @@ fn apply(c: *pardes.Pardes, ev: vaxis.Event) void { } } -/// The effective codepoint the way vaxis's own `Key.matches` sees it: a single-character `text` -/// wins, because the terminal has already resolved shift; otherwise the shifted codepoint. -fn effCp(key: vaxis.Key) u21 { - if (key.text) |t| { - const view = std.unicode.Utf8View.init(t) catch return key.codepoint; - var it = view.iterator(); - if (it.nextCodepoint()) |cp| { - if (it.nextCodepoint() == null) return cp; - } - } - return key.shifted_codepoint orelse key.codepoint; -} - -/// vaxis functional-key codepoints -> core constants. The ASCII ones already coincide, so -/// enter/tab/escape/backspace pass straight through. -fn mapKey(cp: u21) u21 { - return switch (cp) { - vaxis.Key.up => pardes.Key.up, - vaxis.Key.down => pardes.Key.down, - vaxis.Key.left => pardes.Key.left, - vaxis.Key.right => pardes.Key.right, - vaxis.Key.home => pardes.Key.home, - vaxis.Key.end => pardes.Key.end, - vaxis.Key.page_up => pardes.Key.page_up, - vaxis.Key.page_down => pardes.Key.page_down, - vaxis.Key.delete => pardes.Key.delete, - else => cp, - }; -} export fn pardes_esp32p4_tick(now_ms: u64) callconv(.c) void { const c = core orelse return; last_now_ms = now_ms; diff --git a/src/gui/gui.zig b/src/gui/gui.zig index df565b94..8b100cd8 100644 --- a/src/gui/gui.zig +++ b/src/gui/gui.zig @@ -6,6 +6,7 @@ const libc = std.c; const vaxis = @import("vaxis"); // test modes only: the stdin escape-seq parser const ghostty_vt = @import("ghostty-vt"); // 256-color palette for .index cells const pardes = @import("../pardes.zig"); +const vaxis_input = @import("../vaxis_input.zig"); const dump = @import("../dump.zig"); const config = @import("../config.zig"); const look = @import("../look.zig"); @@ -3225,15 +3226,7 @@ const StdinFeed = struct { const event = result.event orelse continue; switch (event) { .key_press => |key| { - var text: []const u8 = ""; - if (key.text) |t| text = f.cache.put(t); - in.post(.{ .key = .{ - .cp = mapKey(effCp(key)), - .text = text, - .ctrl = key.mods.ctrl, - .alt = key.mods.alt, - .shift = key.mods.shift, - } }); + postKey(in, key, if (key.text) |t| f.cache.put(t) else ""); out.n_events += 1; }, .mouse => |m| { @@ -3382,6 +3375,40 @@ fn dumpGrid(gpa: std.mem.Allocator, surface: *pardes.Surface) !void { _ = host_io.writeFd(1, frame); } +/// A key parsed from the stdin a test window reads, posted as the tty +/// posts one (vaxis_input): F-keys, Insert and the keypad included. `text` +/// is the key's text as the feed keeps it. +fn postKey(in: *Input, key: vaxis.Key, text: []const u8) void { + var ev = vaxis_input.keyEvent(key); + ev.key.text = text; + in.post(ev); +} + +test "the GUI's stdin keys reach a terminal pane as the tty's do: F5, Insert and the keypad's Up" { + const gpa = std.testing.allocator; + const core = try pardes.Pardes.init(gpa, .{ .tty_only = true }); + defer core.deinit(); + core.panes[0].?.body.mode = .tty; + while (core.nextEffect()) |_| {} + var in: Input = .{ .core = core }; + var parser: vaxis.Parser = .{}; + var bytes: []const u8 = "\x1b[15~\x1b[2~\x1b[57419u"; + while (bytes.len > 0) { + const result = try parser.parse(bytes, gpa); + bytes = bytes[result.n..]; + if (result.event) |event| switch (event) { + .key_press => |key| postKey(&in, key, key.text orelse ""), + else => {}, + }; + } + var written: std.Io.Writer.Allocating = .init(gpa); + defer written.deinit(); + while (core.nextEffect()) |effect| { + if (effect == .write) try written.writer.writeAll(effect.write.bytes.slice()); + } + try std.testing.expectEqualStrings("\x1b[15~\x1b[2~\x1b[A", written.written()); +} + const Input = struct { core: ?*pardes.Pardes = null, client: ?*detached_client.Client = null, @@ -10439,32 +10466,6 @@ fn miniGlyph(ch: u8) [5]u8 { }; } -fn effCp(key: vaxis.Key) u21 { - if (key.text) |t| { - const view = std.unicode.Utf8View.init(t) catch return key.codepoint; - var it = view.iterator(); - if (it.nextCodepoint()) |cp| { - if (it.nextCodepoint() == null) return cp; - } - } - return key.shifted_codepoint orelse key.codepoint; -} - -fn mapKey(cp: u21) u21 { - return switch (cp) { - vaxis.Key.up => pardes.Key.up, - vaxis.Key.down => pardes.Key.down, - vaxis.Key.left => pardes.Key.left, - vaxis.Key.right => pardes.Key.right, - vaxis.Key.home => pardes.Key.home, - vaxis.Key.end => pardes.Key.end, - vaxis.Key.page_up => pardes.Key.page_up, - vaxis.Key.page_down => pardes.Key.page_down, - vaxis.Key.delete => pardes.Key.delete, - else => cp, - }; -} - fn envU16(env: *std.process.Environ.Map, name: []const u8) ?u16 { const raw = env.get(name) orelse return null; return std.fmt.parseInt(u16, raw, 10) catch null; diff --git a/src/main.zig b/src/main.zig index 6ea05479..17d0fb5f 100644 --- a/src/main.zig +++ b/src/main.zig @@ -525,6 +525,7 @@ test { _ = @import("fs.zig"); _ = @import("detached/wire.zig"); _ = @import("ShaderBuild.zig"); + _ = @import("vaxis_input.zig"); _ = @import("detached/server.zig"); _ = @import("detached/client.zig"); _ = @import("9p_io.zig"); diff --git a/src/tty/tty.zig b/src/tty/tty.zig index 3902271c..3441bc29 100644 --- a/src/tty/tty.zig +++ b/src/tty/tty.zig @@ -5,6 +5,7 @@ const posix = std.posix; const libc = std.c; const vaxis = @import("vaxis"); const pardes = @import("../pardes.zig"); +const vaxis_input = @import("../vaxis_input.zig"); const dump = @import("../dump.zig"); const tracy = @import("../tracy.zig"); const look = @import("../look.zig"); @@ -1510,7 +1511,7 @@ const Shell = struct { const bytes = pasteBytes(key); const room = max_paste_bytes -| s.paste_buf.written().len; s.paste_buf.writer.writeAll(bytes[0..@min(bytes.len, room)]) catch {}; - } else core.update(keyEvent(key)), + } else core.update(vaxis_input.keyEvent(key)), .mouse => |m| { const pdf_before = nativePdfWheelTarget(core, m); if (mouseEvent(m)) |ev| core.update(ev); @@ -2153,72 +2154,17 @@ fn readPty(io: std.Io, gpa: std.mem.Allocator, pty: std.Io.File, id: usize, gen: _ = loop.tryPostEvent(.{ .pty_eof = .{ .id = id, .gen = gen } }) catch {}; } -fn effCp(key: vaxis.Key) u21 { - if (key.text) |t| { - const view = std.unicode.Utf8View.init(t) catch return key.codepoint; - var it = view.iterator(); - if (it.nextCodepoint()) |c| { - if (it.nextCodepoint() == null) return c; - } - } - return key.shifted_codepoint orelse key.codepoint; -} - -fn mapKey(cp: u21) u21 { - return switch (cp) { - vaxis.Key.kp_enter => pardes.Key.enter, - vaxis.Key.up => pardes.Key.up, - vaxis.Key.down => pardes.Key.down, - vaxis.Key.left => pardes.Key.left, - vaxis.Key.right => pardes.Key.right, - vaxis.Key.home => pardes.Key.home, - vaxis.Key.end => pardes.Key.end, - vaxis.Key.page_up => pardes.Key.page_up, - vaxis.Key.page_down => pardes.Key.page_down, - vaxis.Key.delete => pardes.Key.delete, - vaxis.Key.insert => pardes.Key.insert, - vaxis.Key.print_screen => pardes.Key.print_screen, - vaxis.Key.scroll_lock => pardes.Key.scroll_lock, - vaxis.Key.pause => pardes.Key.pause, - vaxis.Key.menu => pardes.Key.menu, - vaxis.Key.f1...vaxis.Key.f25 => pardes.Key.f1 + (cp - vaxis.Key.f1), - // The keypad's own keys, which the kitty keyboard protocol tells - // apart, do what the keys they are named for do. - vaxis.Key.kp_left => pardes.Key.left, - vaxis.Key.kp_right => pardes.Key.right, - vaxis.Key.kp_up => pardes.Key.up, - vaxis.Key.kp_down => pardes.Key.down, - vaxis.Key.kp_page_up => pardes.Key.page_up, - vaxis.Key.kp_page_down => pardes.Key.page_down, - vaxis.Key.kp_home => pardes.Key.home, - vaxis.Key.kp_end => pardes.Key.end, - vaxis.Key.kp_insert => pardes.Key.insert, - vaxis.Key.kp_delete => pardes.Key.delete, - else => cp, - }; -} - const max_paste_bytes: usize = 4 << 20; fn pasteBytes(key: vaxis.Key) []const u8 { const text = key.text orelse ""; if (text.len > 0) return text; - const cp = mapKey(effCp(key)); + const cp = vaxis_input.mapKey(vaxis_input.effCp(key)); if (cp == pardes.Key.tab) return "\t"; if (cp == pardes.Key.enter or (key.mods.ctrl and cp == 'j')) return "\n"; return ""; } -fn keyEvent(key: vaxis.Key) pardes.Event { - return .{ .key = .{ - .cp = mapKey(effCp(key)), - .text = key.text orelse "", - .ctrl = key.mods.ctrl, - .alt = key.mods.alt, - .shift = key.mods.shift, - } }; -} - test "a terminal pane gets function keys as their sequences and lone modifiers not at all" { if (comptime builtin.os.tag == .windows) return error.SkipZigTest; const gpa = std.testing.allocator; @@ -2271,7 +2217,7 @@ test "a terminal pane gets function keys as their sequences and lone modifiers n core.panes[0].?.body.mode = .tty; while (core.nextEffect()) |_| {} while (try loop.tryEvent()) |event| switch (event) { - .key_press => |key| core.update(keyEvent(key)), + .key_press => |key| core.update(vaxis_input.keyEvent(key)), else => {}, }; var written: std.Io.Writer.Allocating = .init(gpa); @@ -2285,7 +2231,7 @@ test "a terminal pane gets function keys as their sequences and lone modifiers n test "keypad Enter matches Return for editor input terminal writes and paste" { for ([_]u21{ vaxis.Key.enter, vaxis.Key.kp_enter }) |codepoint| { const key: vaxis.Key = .{ .codepoint = codepoint }; - const event = keyEvent(key); + const event = vaxis_input.keyEvent(key); try std.testing.expectEqual(pardes.Key.enter, event.key.cp); try std.testing.expectEqualStrings("\n", pasteBytes(key)); { @@ -2757,7 +2703,7 @@ const Attach = struct { const bytes = pasteBytes(key); const room = max_paste_bytes -| a.paste_buf.written().len; a.paste_buf.writer.writeAll(bytes[0..@min(bytes.len, room)]) catch {}; - } else return a.send(keyEvent(key)), + } else return a.send(vaxis_input.keyEvent(key)), .mouse => |m| if (mouseEvent(m)) |ev| return a.send(ev), .paste => |bytes| { defer a.gpa.free(@constCast(bytes)); diff --git a/src/vaxis_input.zig b/src/vaxis_input.zig new file mode 100644 index 00000000..0e25dea1 --- /dev/null +++ b/src/vaxis_input.zig @@ -0,0 +1,77 @@ +//! A key as vaxis parses it from a terminal's bytes, as the core's Event: +//! the one map for every shell that reads a terminal (tty, gui's stdin, +//! esp32p4). Three copies had drifted; the gui's had lost the F-keys, +//! Insert and the keypad. +const std = @import("std"); +const vaxis = @import("vaxis"); +const pardes = @import("pardes.zig"); + +/// The effective codepoint the way vaxis's own `Key.matches` sees it: a +/// single-character `text` wins, the terminal having resolved shift; +/// otherwise the shifted codepoint. +pub fn effCp(key: vaxis.Key) u21 { + if (key.text) |t| { + const view = std.unicode.Utf8View.init(t) catch return key.codepoint; + var it = view.iterator(); + if (it.nextCodepoint()) |c| { + if (it.nextCodepoint() == null) return c; + } + } + return key.shifted_codepoint orelse key.codepoint; +} + +/// vaxis's functional-key codepoints as the core's; the ASCII ones +/// (enter, tab, escape, backspace) already coincide. +pub fn mapKey(cp: u21) u21 { + return switch (cp) { + vaxis.Key.kp_enter => pardes.Key.enter, + vaxis.Key.up => pardes.Key.up, + vaxis.Key.down => pardes.Key.down, + vaxis.Key.left => pardes.Key.left, + vaxis.Key.right => pardes.Key.right, + vaxis.Key.home => pardes.Key.home, + vaxis.Key.end => pardes.Key.end, + vaxis.Key.page_up => pardes.Key.page_up, + vaxis.Key.page_down => pardes.Key.page_down, + vaxis.Key.delete => pardes.Key.delete, + vaxis.Key.insert => pardes.Key.insert, + vaxis.Key.print_screen => pardes.Key.print_screen, + vaxis.Key.scroll_lock => pardes.Key.scroll_lock, + vaxis.Key.pause => pardes.Key.pause, + vaxis.Key.menu => pardes.Key.menu, + vaxis.Key.f1...vaxis.Key.f25 => pardes.Key.f1 + (cp - vaxis.Key.f1), + // The keypad's own keys, which the kitty keyboard protocol tells + // apart, do what the keys they are named for do. + vaxis.Key.kp_left => pardes.Key.left, + vaxis.Key.kp_right => pardes.Key.right, + vaxis.Key.kp_up => pardes.Key.up, + vaxis.Key.kp_down => pardes.Key.down, + vaxis.Key.kp_page_up => pardes.Key.page_up, + vaxis.Key.kp_page_down => pardes.Key.page_down, + vaxis.Key.kp_home => pardes.Key.home, + vaxis.Key.kp_end => pardes.Key.end, + vaxis.Key.kp_insert => pardes.Key.insert, + vaxis.Key.kp_delete => pardes.Key.delete, + else => cp, + }; +} + +/// The key as the core's event, its text the key's own. +pub fn keyEvent(key: vaxis.Key) pardes.Event { + return .{ .key = .{ + .cp = mapKey(effCp(key)), + .text = key.text orelse "", + .ctrl = key.mods.ctrl, + .alt = key.mods.alt, + .shift = key.mods.shift, + } }; +} + +test "F-keys, Insert and the keypad map to the core's keys" { + try std.testing.expectEqual(pardes.Key.f1 + 4, mapKey(vaxis.Key.f5)); + try std.testing.expectEqual(pardes.Key.f1 + 24, mapKey(vaxis.Key.f25)); + try std.testing.expectEqual(pardes.Key.insert, mapKey(vaxis.Key.insert)); + try std.testing.expectEqual(pardes.Key.up, mapKey(vaxis.Key.kp_up)); + try std.testing.expectEqual(pardes.Key.enter, keyEvent(.{ .codepoint = vaxis.Key.kp_enter }).key.cp); + try std.testing.expectEqual(@as(u21, 'a'), mapKey('a')); +} -- cgit v1.3 From 7e8e2655567cab1c28597f44d0aec79e46b0deb8 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Tue, 29 Sep 2026 22:31:27 -0300 Subject: Zig files go to zls as a child process through the protocol client, as every other language does: the in-process ZLS backend goes lsp_zls.zig (1,522 lines), the zls dependency, build.zig's zls wiring and the import graph it baked into the options only for it, and main.zig's reference go. lsp_client's table gains a zls row (PARDES_LSP_ZIG overrides it); Hover, Rename, Diagnostics, WsSymbols, Lspinfo and gd answer through it (checked with lspprobe and the snapshots against zls 0.16.1-dev). What changes for a user: zls must be on PATH; a completion's rows are zls's candidates at the cursor, where the linked analyser gave each one's declaration; document symbols carry no signature. The Zig snapshots (lsp, lspcomplete, lspcompletemoved, lspdebug, lsprelpath) run the real zls now: lspdebug reads the client's explain and report, lsprelpath spells gr's rows where it spelled a completion's, and their goldens are recorded again (stable over three runs). Lspinfo still opens with its backend line. The ReleaseFast tty binary is 105.35 MB to 96.28 MB, the Debug one 296.5 MB to 245.9 MB. docs/lsp.md, web.md, design.typ and the README say so. Co-Authored-By: Claude Opus 5.5 --- README.md | 2 +- build.zig | 72 -- build.zig.zon | 14 - docs/design.typ | 4 +- docs/lsp.md | 19 +- docs/web.md | 4 +- src/lsp/lsp.zig | 17 +- src/lsp/lsp_client.zig | 18 +- src/lsp/lsp_zls.zig | 1522 -------------------------------- src/main.zig | 1 - test/fs.py | 2 +- test/lspbench.zig | 1 - test/snapshot.zig | 2 +- test/snapshots/lsp.golden | 5 +- test/snapshots/lsp.snap | 10 +- test/snapshots/lspcomplete.golden | 20 +- test/snapshots/lspcomplete.snap | 21 +- test/snapshots/lspcompletemoved.golden | 2 +- test/snapshots/lspdebug.golden | 2 + test/snapshots/lspdebug.snap | 23 +- test/snapshots/lsprelpath.golden | 120 +-- test/snapshots/lsprelpath.snap | 34 +- 22 files changed, 154 insertions(+), 1761 deletions(-) delete mode 100644 src/lsp/lsp_zls.zig (limited to 'src/main.zig') diff --git a/README.md b/README.md index 1fe1167d..df03610f 100644 --- a/README.md +++ b/README.md @@ -171,7 +171,7 @@ records one open structural gap against helix and the waiver that proves it. src/ core events (pardes.zig), panes, edit, look, exec, layout, fs, syntax src/ninep/ the 9P control tree src/detached/ the wire, the detached core, the frontend client -src/lsp/ ZLS and external language-server backends +src/lsp/ the language-server client and its seam test/ harnesses, snapshot goldens, helix cases build/ build-time helpers (the snapshot suite) docs/ see above diff --git a/build.zig b/build.zig index e74bf303..fcb4b0b7 100644 --- a/build.zig +++ b/build.zig @@ -30,19 +30,6 @@ const PerfBuild = struct { pub const macos_min_version: std.SemanticVersion = .{ .major = 13, .minor = 0, .patch = 0 }; -const zls_version = "0.16.1-dev+3e0d0820"; - -comptime { - const plus = std.mem.indexOfScalar(u8, zls_version, '+') orelse - @compileError("zls_version must end in +"); - const short = zls_version[plus + 1 ..]; - const url = zon.dependencies.zls.url; - const hash = std.mem.indexOfScalar(u8, url, '#') orelse - @compileError("the zls dependency url must pin a commit with #"); - if (!std.mem.startsWith(u8, url[hash + 1 ..], short)) @compileError( - "zls_version pins commit " ++ short ++ ", build.zig.zon pins " ++ url[hash + 1 ..], - ); -} pub const TreeSitterGrammars = enum { disabled, zig, minimal, full }; const gui_shaders = [_][]const u8{ @@ -280,7 +267,6 @@ pub fn build(b: *std.Build) void { // The conditional dependencies, hoisted so one `wireCore` call at the end // can name them all. The unconditional ones are ordinary consts below. - var zls_mod: ?*std.Build.Module = null; var ts_mod: ?*std.Build.Module = null; var ts_queries_opts: ?*std.Build.Step.Options = null; var mupdf_core_mod: ?*std.Build.Module = null; @@ -308,8 +294,6 @@ pub fn build(b: *std.Build) void { if (target.result.os.tag == .freebsd or target.result.os.tag == .netbsd or target.result.os.tag == .openbsd) root_mod.linkSystemLibrary("util", .{}); - const zls_backend = !freestanding_core; - const esp32p4_cols = b.option(u16, "esp32p4-cols", "the board's grid width in cells (-Dplatform=esp32p4 only)") orelse 56; const esp32p4_rows = b.option(u16, "esp32p4-rows", "the board's grid height in cells (-Dplatform=esp32p4 only)") orelse 14; const theme_animation = b.option(bool, "theme-animation", "animate chrome colors across a theme change (default: off for esp32p4)"); @@ -329,7 +313,6 @@ pub fn build(b: *std.Build) void { const shell_cfg: ShellConfig = .{ .tree_sitter_grammars = tree_sitter_grammars, .tracy = tracy != null, - .zls_backend = zls_backend, .mupdf = enable_mupdf, .esp32p4_cols = esp32p4_cols, .esp32p4_rows = esp32p4_rows, @@ -337,21 +320,11 @@ pub fn build(b: *std.Build) void { .workspace_tag = workspace_tag, .prebuilt_shaders = prebuilt_shaders, .embed_sources = embed_sources, - .zig_lib_dir = b.graph.zig_lib_directory.path orelse "", .commit = if (stamp_commit) gitCommit(b) else null, }; const opts = shellOptions(b, shell_cfg, platform); const gui_opts: ?*std.Build.Step.Options = if (also_gui) shellOptions(b, shell_cfg, .gui) else null; - if (zls_backend) { - const zls_dep = b.dependency("zls", .{ - .target = target, - .optimize = optimize, - .@"version-string" = @as([]const u8, zls_version), - }); - zls_mod = zls_dep.module("zls"); - } - if (tracy) |tracy_path| { for ([_]*std.Build.Module{ root_mod, core_module }) |mod| { mod.addIncludePath(.{ .cwd_relative = tracy_path }); @@ -939,7 +912,6 @@ pub fn build(b: *std.Build) void { // BEFORE the fold below, which reads what these imports put in the table. for (core_mods) |m| wireCore(m, .{ .themes = themes_mod, - .zls = zls_mod, .tree_sitter = ts_mod, .ts_libs = ts_libs.items, .ts_queries = ts_queries_opts, @@ -952,43 +924,6 @@ pub fn build(b: *std.Build) void { .uucode = uucode_mod, }); - var module_count: usize = 0; - { - var it = root_mod.import_table.iterator(); - while (it.next()) |e| { - const lp = e.value_ptr.*.root_source_file orelse continue; - switch (lp) { - .src_path, .cwd_relative => module_count += 1, - else => continue, - } - } - } - const mod_names = b.allocator.alloc([]const u8, module_count) catch @panic("OOM"); - const mod_roots = b.allocator.alloc([]const u8, module_count) catch @panic("OOM"); - var module_index: usize = 0; - { - var it = root_mod.import_table.iterator(); - while (it.next()) |e| { - const lp = e.value_ptr.*.root_source_file orelse continue; - // `generated` is a build artifact (the options modules): it has no - // path until make() runs, and pointing an editor at one is useless - const abs = switch (lp) { - .src_path => |sp| sp.owner.pathFromRoot(sp.sub_path), - .cwd_relative => |cr| cr, - else => continue, - }; - mod_names[module_index] = e.key_ptr.*; - mod_roots[module_index] = abs; - module_index += 1; - } - } - std.debug.assert(module_index == module_count); - for ([_]?*std.Build.Step.Options{ opts, gui_opts }) |maybe| if (maybe) |o| { - o.addOption([]const []const u8, "module_names", mod_names); - o.addOption([]const []const u8, "module_roots", mod_roots); - // Whose imports those are: a .zig file outside this tree has none of them. - o.addOption([]const u8, "project_root", b.build_root.path orelse ""); - }; const iso_off = b.addOptions(); iso_off.addOption(bool, "isolated", false); @@ -1911,7 +1846,6 @@ fn gitCommit(b: *std.Build) ?[]const u8 { const ShellConfig = struct { tree_sitter_grammars: TreeSitterGrammars, tracy: bool, - zls_backend: bool, mupdf: bool, esp32p4_cols: u16, esp32p4_rows: u16, @@ -1923,7 +1857,6 @@ const ShellConfig = struct { workspace_tag: ?bool, prebuilt_shaders: bool, embed_sources: bool, - zig_lib_dir: []const u8, commit: ?[]const u8, }; @@ -1935,19 +1868,16 @@ fn shellOptions(b: *std.Build, cfg: ShellConfig, platform: Platform) *std.Build. o.addOption(bool, "syntax_minimal_grammars", cfg.tree_sitter_grammars == .minimal or cfg.tree_sitter_grammars == .full); o.addOption(bool, "syntax_full_grammars", cfg.tree_sitter_grammars == .full); o.addOption(bool, "enable_tracy", cfg.tracy); - o.addOption(bool, "zls_backend", cfg.zls_backend); o.addOption(bool, "mupdf", cfg.mupdf); o.addOption(u16, "esp32p4_cols", cfg.esp32p4_cols); o.addOption(u16, "esp32p4_rows", cfg.esp32p4_rows); o.addOption(bool, "workspace_tag", cfg.workspace_tag orelse (platform != .macos)); o.addOption(bool, "theme_animation", cfg.theme_animation orelse (platform != .esp32p4)); - o.addOption([]const u8, "zls_version", if (cfg.zls_backend) zls_version else "none"); o.addOption(bool, "embed_sources", cfg.embed_sources); o.addOption([]const u8, "version", zon.version); // ...and the commit it was built from, when there is one and the build // is stamped at all (see `stamp_commit`). Read at configure time. o.addOption(?[]const u8, "commit", cfg.commit); - o.addOption([]const u8, "zig_lib_dir", cfg.zig_lib_dir); return o; } @@ -2032,7 +1962,6 @@ fn vendoredThemes(b: *std.Build, io: std.Io) []const []const u8 { fn wireCore(m: *std.Build.Module, d: struct { themes: ?*std.Build.Module = null, - zls: ?*std.Build.Module = null, tree_sitter: ?*std.Build.Module = null, ts_libs: []const *std.Build.Step.Compile = &.{}, ts_queries: ?*std.Build.Step.Options = null, @@ -2045,7 +1974,6 @@ fn wireCore(m: *std.Build.Module, d: struct { uucode: ?*std.Build.Module = null, }) void { if (d.themes) |x| m.addImport("generated_themes", x); - if (d.zls) |x| m.addImport("zls", x); if (d.tree_sitter) |x| m.addImport("tree-sitter", x); for (d.ts_libs) |lib| m.linkLibrary(lib); if (d.ts_queries) |x| m.addOptions("ts_queries", x); diff --git a/build.zig.zon b/build.zig.zon index e766e158..81b2561a 100644 --- a/build.zig.zon +++ b/build.zig.zon @@ -12,20 +12,6 @@ .url = "git+https://git.sr.ht/~gbrls/cloud9#f35b7ed09d0a170e4ffe55b5286c28f74c9a8760", .hash = "cloud9-0.1.0-yt86quEKHgCwewf5XRlEZji1JCmdsfufsrZYGZqzHj5_", }, - // ZLS as a LIBRARY, not a language server: src/lsp_zls.zig imports the - // `zls` module its build.zig publishes and calls the analyser in - // process — no zls binary, no JSON-RPC, no handshake. - // - // Fetched like every other dependency, so it lands in zig-pkg/ and the - // build is reproducible from the .zon alone. Pinned to a COMMIT on the - // 0.16.x branch rather than a tag: master requires Zig 0.17-dev, and no - // tagged release both builds on 0.16 and exports these internals. - // 0.16.x pins `minimum_zig_version = "0.16.0"` exactly, which is why - // this needs none of the patches an older checkout did. - .zls = .{ - .url = "git+https://github.com/zigtools/zls#3e0d082084be43e36865136a138c1fe2023b33ca", - .hash = "zls-0.16.1-dev-rmm5ftfOJgAzIdWUGVB08ycFbud2O3viKnGF1HZgfKZJ", - }, // Pinned to the exact libvaxis commit ghostty is built against, so it // is compatible with ghostty's uucode configuration (the one we share // with it via `external_uucode` in build.zig). diff --git a/docs/design.typ b/docs/design.typ index ec9bd5c4..80c8bb49 100644 --- a/docs/design.typ +++ b/docs/design.typ @@ -1989,8 +1989,8 @@ rules as Look. Tutor: embedded text as file pane. *Language.* The native host snapshots each request and runs it outside the UI -loop. Zig uses the in-process ZLS backend; configured external language servers -use the JSON-RPC client. Results become output rows or edits, applied only while +loop. Every language's server, Zig's zls included, is a child process the +JSON-RPC client speaks to. Results become output rows or edits, applied only while the request's pane and revision still match. Web and board builds have no language backend. See `docs/lsp.md` for configuration and commands. diff --git a/docs/lsp.md b/docs/lsp.md index 82586344..ae350156 100644 --- a/docs/lsp.md +++ b/docs/lsp.md @@ -1,8 +1,9 @@ # Language intelligence Native hosts, including detached sessions, run language queries on workers. -Zig uses the linked ZLS analyser; other languages use the protocol client in -`src/lsp/lsp_client.zig`. Web and board builds have no language backend. +Every language, Zig included, goes through the protocol client in +`src/lsp/lsp_client.zig`, which runs its server as a child process: Zig's is +`zls`, which must be on PATH. Web and board builds have no language backend. `Lspinfo` (`SPC l i`) reports backend versions, server state, capabilities, recent timings and errors. `Lspwhy` (`SPC l w`) traces resolution at the cursor. @@ -37,14 +38,13 @@ without starting a query. Formatting and same-file rename apply as one undo transaction. A workspace rename spanning other files opens a preview; it does not partially apply the -rename. The linked Zig analyser resolves current-file references and relative -imports, but does not run the build runner to discover dependency modules. +rename. ## Configuration and testing -`PARDES_LSP_RS`, `_C`, `_GO`, `_TS` and `_PY` override the server executable -for each language. An empty value disables that server. `ZIG_LIB_DIR` overrides -the stdlib path recorded at build time. `Lspinfo` shows the effective settings. +`PARDES_LSP_ZIG`, `_RS`, `_C`, `_GO`, `_TS` and `_PY` override the server +executable for each language. An empty value disables that server. `Lspinfo` +shows the effective settings. The protocol client keeps one child server per configured language, negotiates position encoding, and handles both push and pull diagnostics. Startup and @@ -52,8 +52,9 @@ request waits have deadlines; failed starts back off before retrying. Worker status messages reach the host event queue. `zig build lspprobe -- gd :` queries the same backend from -the command line. `zig build lspbench` measures it. Snapshot tests use a Zig -mock server with deterministic answers while exercising the real client, +the command line. `zig build lspbench` measures it. The Zig snapshot tests +(lsp, lspcomplete, lspdebug and the rest) run the real `zls`; the protocol +ones use a Zig mock server with deterministic answers while exercising the real client, including process startup, framing, edits and undo. `zig build fs-test` also checks language-worker delivery in TTY and detached sessions over 9P. diff --git a/docs/web.md b/docs/web.md index bbbed8a3..0a9783c9 100644 --- a/docs/web.md +++ b/docs/web.md @@ -80,7 +80,7 @@ What is genuinely absent is narrower than "no IO". The module has no threads and no host filesystem, so there is no startup config directory, init file, ThemeFile, or DumpThemes; LOOK resolves against the build-generated source archive rather than disk, and no language -BACKEND is compiled in (`zls_backend` is off for wasm — which also means +BACKEND is compiled in (there is none for wasm — which also means `lsp.supports` is empty, so the core never even raises a language query there, and the host leaves `lsp` null). @@ -114,7 +114,7 @@ land in the per-instance fallback, so a pane with no child is SILENT rather than synthetic; `tty_taken` is never taken; any save the page declines resolves against the core's virtual filesystem, which is also where every read comes from — the core reads files itself and never asks a host; `watch_file` records -the request; `lsp` answers an empty row set at once (`zls_backend` is off for +the request; `lsp` answers an empty row set at once (no backend is built for wasm, so the core never raises a query there anyway) and `pipe` answers failure; `wait_input` is null because wasm must never block, and `watch_theme` and `dump_themes` are not reachable without a config directory. Of the diff --git a/src/lsp/lsp.zig b/src/lsp/lsp.zig index 7e5595fd..43f94f95 100644 --- a/src/lsp/lsp.zig +++ b/src/lsp/lsp.zig @@ -33,12 +33,14 @@ pub const Req = struct { root: []const u8 = "", }; -const backends = if (@import("pardes_config").zls_backend) - .{ @import("lsp_zls.zig"), @import("lsp_client.zig") } +/// Every language, Zig's (zls) included, through the protocol client, which +/// runs its server as a child process. None on the web or the board. +const backends = if (@import("pardes_config").platform == .web or @import("pardes_config").platform == .esp32p4) + .{} else - .{}; + .{@import("lsp_client.zig")}; -pub const backend_name = if (backends.len > 1) "zls-inproc+lsp-client" else "zls-inproc"; +pub const backend_name = "lsp-client"; pub const supports: std.EnumSet(Kind) = blk: { var s: std.EnumSet(Kind) = .initEmpty(); @@ -53,6 +55,7 @@ pub fn speaks(path: []const u8) bool { pub fn query(gpa: std.mem.Allocator, arena: std.mem.Allocator, req: Req, out: *std.Io.Writer) !void { if (req.kind == .status) { + try out.print("backend: {s}\n", .{backend_name}); inline for (backends) |b| try b.query(gpa, arena, req, out); return; } @@ -77,7 +80,7 @@ pub fn none(out: *std.Io.Writer, comptime fmt: []const u8, args: anytype) std.Io // Called on server reader threads; the sink must copy text before returning. pub fn setStatusSink(ctx: ?*anyopaque, cb: ?*const fn (ctx: ?*anyopaque, text: []const u8) void) void { - if (@import("pardes_config").zls_backend) backends[1].setStatusSink(ctx, cb); + inline for (backends) |b| b.setStatusSink(ctx, cb); } pub fn rel(base: []const u8, path: []const u8) []const u8 { @@ -164,7 +167,7 @@ test "a question no backend answers for a file says why rather than find nothing defer arena.deinit(); var buf: [256]u8 = undefined; var out: std.Io.Writer = .fixed(&buf); - // The in-process ZLS answers no call hierarchy for a .zig file. - try query(std.testing.allocator, arena.allocator(), .{ .kind = .incoming_calls, .path = "/x/main.zig", .source = "", .offset = 0 }, &out); + // A file no server speaks for is answered, not left empty. + try query(std.testing.allocator, arena.allocator(), .{ .kind = .incoming_calls, .path = "/x/notes.txt", .source = "", .offset = 0 }, &out); try std.testing.expectStringStartsWith(out.buffered(), "@none "); } diff --git a/src/lsp/lsp_client.zig b/src/lsp/lsp_client.zig index 7c1980f6..7704d0ad 100644 --- a/src/lsp/lsp_client.zig +++ b/src/lsp/lsp_client.zig @@ -1,9 +1,8 @@ //! A real Language Server Protocol client: child processes spoken to over //! JSON-RPC 2.0 with `Content-Length` framing. Nothing here knows any single //! language — `specs` is a table of (binary, languageId, extensions, root -//! markers), and rust-analyzer, clangd and gopls are rows in it. The in-process -//! ZLS backend keeps `.zig`; this file is every language pardes highlights but -//! could not answer questions about. +//! markers), and zls, rust-analyzer, clangd and gopls are rows in it: every +//! language pardes answers questions about. //! //! THE PROCESS LIFECYCLE IS THE DESIGN. `lsp.query` is a synchronous call on a //! worker thread, and a language server costs tens of milliseconds to start @@ -103,6 +102,14 @@ const Spec = struct { }; pub const specs = [_]Spec{ + .{ + .name = "zls", + .bin = "zls", + .lang = "zig", + .exts = &.{".zig"}, + .markers = &.{ "build.zig", "build.zig.zon" }, + .env = "PARDES_LSP_ZIG", + }, .{ .name = "rust-analyzer", .bin = "rust-analyzer", @@ -147,8 +154,7 @@ pub const specs = [_]Spec{ }, }; -/// Everything, including the four hierarchy kinds the in-process backend has -/// no analyser for. Whether one SERVER can answer is a capability question +/// Everything. Whether one SERVER can answer is a capability question /// answered per connection; a kind its server never advertised simply returns /// no rows, which the harness reports as CLAIMED-EMPTY per language — honest, /// since the claim here is about the protocol, not about every server. @@ -2175,9 +2181,9 @@ test "rootOf takes the top-most marker and falls back to git then dir" { test "specFor routes extensions and honours the disable env" { try std.testing.expect(specFor("/x/main.rs") != null); - try std.testing.expect(specFor("/x/main.zig") == null); try std.testing.expect(specFor("/x/README.md") == null); try std.testing.expectEqualStrings("rust-analyzer", specs[specFor("/x/main.rs").?].name); + if (getenv("PARDES_LSP_ZIG") == null) try std.testing.expectEqualStrings("zls", specs[specFor("/x/main.zig").?].name); } test "the transport this host actually gives us is a pair, and both ends are close-on-exec" { diff --git a/src/lsp/lsp_zls.zig b/src/lsp/lsp_zls.zig deleted file mode 100644 index 2311ec47..00000000 --- a/src/lsp/lsp_zls.zig +++ /dev/null @@ -1,1522 +0,0 @@ -//! ZLS as a LIBRARY, not a language server. -//! -//! There is no subprocess, no JSON-RPC, no `initialize` handshake and no -//! `Server`. `gd` runs ZLS's own analyser on this thread and comes back with a -//! token; the whole "protocol" is a struct field. ZLS's build.zig already -//! publishes its guts as an importable module (`b.modules.put("zls", ...)`), -//! and everything under `features/` that is not welded to `*Server` is a plain -//! function over (analyser, arena, handle, offset) — so the parts we want are -//! callable and the parts we don't want cost nothing. -//! -//! What that buys and what it costs: -//! -//! - Cold IS warm. There is no server to start, no workspace to index, no -//! handshake to wait for. The first `gd` after launch pays for parsing this -//! file and whatever it imports, and nothing else. -//! - It also means NOTHING IS CACHED between queries. Every call builds a -//! DocumentStore, resolves imports, and throws it all away, because `query` -//! is handed an arena that dies on return and a `req` that is a snapshot of -//! a buffer the user is still typing into. A cache would have to be a global -//! with its own mutex and its own invalidation story; that is a real design, -//! not a line of code, and it is the obvious next step rather than something -//! smuggled in here. -//! - `zig_exe_path` is null on purpose: shelling out to the compiler is the -//! thing this backend exists to avoid. `zig_lib_dir` is the build's own -//! (`b.graph.zig_lib_directory`), which is what makes `std` resolvable — -//! `gd` on `std.mem.count` lands in the real `mem.zig`. -//! -//! The price is DEPENDENCIES, and it is worth being exact about how far it -//! goes. ZLS resolves a non-`std`, non-relative import only through a -//! `BuildFile` whose config came from running `zig build --build-runner`, so -//! with no compiler it resolves none of them. We paper over ONE case of -//! that: `gd` on the import string itself (`moduleRoot`, fed by build.zig). -//! That is a fallback in OUR handler and ZLS cannot see it, so the analyser -//! still cannot type `vaxis`, and `gd` on `vaxis.init` still finds nothing. -//! Making member access work means giving ZLS a real build config — either -//! by letting it run the build runner (a subprocess, and with no cross-query -//! cache that is once PER KEYPRESS) or by synthesizing a BuildConfig and -//! reaching into `BuildFile.impl`. Both are real work; neither is smuggled -//! in here. `@import("builtin")` and `@cImport` are unresolved for the same -//! reason. -const std = @import("std"); -const zls = @import("zls"); -const lsp = @import("lsp.zig"); -const cfg = @import("pardes_config"); - -const Analyser = zls.Analyser; -const DocumentStore = zls.DocumentStore; -const InternPool = zls.analyser.InternPool; -const offsets = zls.offsets; -const Uri = zls.Uri; -const types = zls.lsp.types; -const Ast = std.zig.Ast; - -/// BYTE offsets. ZLS defaults to utf-16 because that is what the wire protocol -/// says; we are not on a wire, and `+Search` rows are byte columns. -const enc: offsets.Encoding = .@"utf-8"; - -/// Guards on the workspace walks (workspace symbols / workspace diagnostics). -/// A language query runs on every keypress of `SPC S`; it may not turn into an -/// unbounded tree walk because someone opened a file in `/`. -const max_files = 512; -const max_rows = 2000; -const max_output_bytes = max_rows * 4096; -const max_trace_bytes = 32 * 1024; -const max_code_action_bytes = max_rows * 1024; - -pub const supports: std.EnumSet(lsp.Kind) = .initMany(&.{ - .definition, - .declaration, - .type_definition, - .implementation, - .references, - .select_refs, - .hover, - .document_symbols, - .workspace_symbols, - .diagnostics, - .workspace_diagnostics, - .rename, - .format, - .code_action, - .completion, - .status, - .explain, -}); - -/// The language gate, hoisted out of `run` so the core can ask it too: a `.zig` -/// file and nothing else. `gd` in a README has to find nothing rather than -/// parse prose as Zig, and insert-mode Tab has to keep indenting there rather -/// than divert into a query that could never answer. -pub fn speaks(path: []const u8) bool { - return std.mem.endsWith(u8, path, ".zig"); -} - -// ------------------------------------------------------------ introspection -// -// Everything below exists because of the contract two lines down: this backend -// never fails loudly. That is right for an editor — a thrown analyser must not -// take the process with it — but it means a broken backend and a correct one -// that found nothing look identical from the outside. So every query leaves a -// record, and `SPC l i` reads them back. - -/// One finished query. Fixed-size and inline: this array is process-global and -/// lives forever, so it must not own heap. -const LogEntry = struct { - used: bool = false, - kind: lsp.Kind = .definition, - us: u64 = 0, - rows: usize = 0, - offset: u32 = 0, - /// the error `run` returned, or empty when it returned normally. THIS is - /// the thing you cannot see any other way. - err: [40]u8 = @splat(0), - err_len: u8 = 0, - /// basename only — a full path would need most of this struct - file: [64]u8 = @splat(0), - file_len: u8 = 0, - - fn errName(e: *const LogEntry) []const u8 { - return e.err[0..e.err_len]; - } - fn fileName(e: *const LogEntry) []const u8 { - return e.file[0..e.file_len]; - } -}; - -const log_cap = 24; -var log_buf: [log_cap]LogEntry = @splat(.{}); -var log_next: usize = 0; -var log_total: u64 = 0; -/// 0.16 has no std.Thread.Mutex; the critical sections here are a memcpy, so -/// spinning on the lock-free one is enough — the same call gui.zig's pty queue -/// makes. Only WORKER threads touch this; the core never does. -var log_mu: std.atomic.Mutex = .unlocked; - -fn logLock() void { - while (!log_mu.tryLock()) std.atomic.spinLoopHint(); -} - -fn record(req: lsp.Req, us: u64, rows: usize, err: []const u8) void { - logLock(); - defer log_mu.unlock(); - const e = &log_buf[log_next]; - e.* = .{ .used = true, .kind = req.kind, .us = us, .rows = rows, .offset = req.offset }; - const base = std.fs.path.basename(req.path); - e.file_len = @intCast(@min(base.len, e.file.len)); - @memcpy(e.file[0..e.file_len], base[0..e.file_len]); - e.err_len = @intCast(@min(err.len, e.err.len)); - @memcpy(e.err[0..e.err_len], err[0..e.err_len]); - log_next = (log_next + 1) % log_cap; - log_total += 1; -} - -/// A duration cannot go in a snapshot golden — it differs every run. The -/// snapshot harness sets PARDES_NOTIME so the two introspection views print `-` -/// instead, the same way it pins PARDES_DUMP for the dump tests. ONE flag, -/// meaning "no wall clock in user-visible text": message.zig reads the same one -/// to blank the transient message row's `HH:MM:SS`. Unset — i.e. every real run -/// — shows real numbers. -fn hideTime() bool { - const v = std.c.getenv("PARDES_NOTIME") orelse return false; - return std.mem.span(v).len != 0; -} - -fn nowUs() u64 { - var ts: std.c.timespec = undefined; - _ = std.c.clock_gettime(.MONOTONIC, &ts); - return @as(u64, @intCast(ts.sec)) *| 1_000_000 +| @as(u64, @intCast(ts.nsec)) / 1000; -} - -/// The narration `SPC l w` prints. It is threaded through the REAL resolution -/// path rather than re-derived beside it: a debug view that reimplements the -/// logic is a debug view that can disagree with it, and the whole point is to -/// find out what actually happened. -const Trace = struct { - on: bool = false, - buf: [max_trace_bytes]u8 = undefined, - len: usize = 0, - - fn note(t: *Trace, comptime fmt: []const u8, args: anytype) void { - if (!t.on or t.len == t.buf.len) return; - var w: std.Io.Writer = .fixed(t.buf[t.len..]); - w.print(fmt ++ "\n", args) catch {}; - t.len += w.buffered().len; - } - - fn written(t: *const Trace) []const u8 { - return t.buf[0..t.len]; - } -}; - -pub fn query(gpa: std.mem.Allocator, arena: std.mem.Allocator, req: lsp.Req, out: *std.Io.Writer) !void { - // status reads the log; recording it would push a real query out of a - // 24-entry ring every time you looked at it. - if (req.kind == .status) return status(arena, req, out); - - const scratch_buf = try gpa.alloc(u8, max_output_bytes); - defer gpa.free(scratch_buf); - var scratch: std.Io.Writer = .fixed(scratch_buf); - - var tr: Trace = .{ .on = req.kind == .explain }; - const t0 = nowUs(); - var err_name: []const u8 = ""; - var failure: ?anyerror = null; - run(gpa, arena, req, &scratch, &tr) catch |e| { - failure = e; - err_name = @errorName(e); - tr.note("ERROR: {s}", .{err_name}); - }; - const us = nowUs() -| t0; - const rows = std.mem.count(u8, scratch.buffered(), "\n"); - record(req, us, rows, err_name); - - if (req.kind != .explain) { - if (failure) |err| return err; - try out.writeAll(scratch.buffered()); - return; - } - try out.print("lsp explain — the definition query at byte {d} of {s}\n\n", .{ - req.offset, if (req.path.len == 0) "(no file)" else std.fs.path.basename(req.path), - }); - try out.writeAll(tr.written()); - if (hideTime()) - try out.print("\n{d} row(s)\n", .{rows}) - else - try out.print("\n{d} row(s) in {d}us\n", .{ rows, us }); -} - -fn run(gpa: std.mem.Allocator, arena: std.mem.Allocator, req: lsp.Req, out: *std.Io.Writer, tr: *Trace) !void { - // The blocking, single-threaded std.Io — the same one look.zig walks - // directories with. ZLS wants an `Io` for every file read; a worker thread - // that is allowed to block wants the one that just does the syscall. - const io = std.Io.Threaded.global_single_threaded.io(); - - // The two workspace kinds are about the PROJECT, not about this buffer, so - // they answer from any pane and never need the analyser, the store or the - // intern pool — a walk and a parse each. - // `explain` narrates the definition query; everywhere below dispatches on - // the effective kind, so the trace follows the code `gd` really runs. - const kind: lsp.Kind = if (req.kind == .explain) .definition else req.kind; - - switch (kind) { - .workspace_symbols => return workspaceSymbols(gpa, arena, io, req, out), - .workspace_diagnostics => return workspaceDiagnostics(gpa, arena, io, req, out), - // Everything else is about THIS file, and this backend speaks Zig. The - // core does not gate the keymap by file type (a pane is a pane), so - // the gate is here: `gd` in a README must find nothing rather than - // parse prose as Zig and confidently resolve a word out of it. - else => if (!speaks(req.path)) { - tr.note("STOP: not a .zig file ({s}) — this backend only reads Zig", .{ - if (req.path.len == 0) "no path: this pane has no file behind it" else req.path, - }); - return; - }, - } - // Pure tree, no analyser. - if (kind == .format) return formatQuery(arena, req, out); - - var env: std.process.Environ.Map = .init(arena); - var lib_dir: ?std.Build.Cache.Directory = null; - if (zigLibPath()) |p| { - if (std.Io.Dir.cwd().openDir(io, p, .{})) |h| { - lib_dir = .{ .handle = h, .path = p }; - tr.note("zig lib dir: {s} (open) — `std` imports resolve", .{p}); - } else |e| tr.note("zig lib dir: {s} FAILED to open ({s}) — nothing in `std` will resolve", .{ p, @errorName(e) }); - } else tr.note("zig lib dir: NOT SET — nothing in `std` will resolve", .{}); - defer if (lib_dir) |d| d.handle.close(io); - - var ip: InternPool = try .init(io, gpa); - defer ip.deinit(gpa); - - var diags: zls.DiagnosticsCollection = .{ .io = io, .allocator = gpa }; - defer diags.deinit(); - - var store: DocumentStore = .{ - .io = io, - .allocator = gpa, - .config = .{ - .environ_map = &env, - // no compiler subprocess: that is the entire point of this backend - .zig_exe_path = null, - .zig_lib_dir = lib_dir, - .build_runner_path = null, - .builtin_path = null, - .global_cache_dir = null, - .wasi_preopens = {}, - }, - .diagnostics_collection = &diags, - }; - defer store.deinit(); - - // The buffer the user is looking at, not the file on disk: `source` is the - // shell's snapshot, so unsaved edits are what gets analysed — except for a - // completion, which is asked ABOUT a half-typed line and has to repair it - // first (see completionSource). - const uri: Uri = try .fromPath(arena, req.path); - try store.openLspSyncedDocument(uri, if (kind == .completion) completionSource(arena, req, tr) else req.source); - const handle = store.getHandle(uri) orelse { - tr.note("STOP: the document store would not take this buffer", .{}); - return; - }; - if (handle.tree.mode == .zon) { - tr.note("STOP: parsed as .zon, not Zig code — there is nothing to resolve", .{}); - return; - } - tr.note("parsed {d} bytes, {d} syntax error(s){s}", .{ - req.source.len, - handle.tree.errors.len, - if (handle.tree.errors.len == 0) "" else " — a broken tree resolves badly or not at all", - }); - - var analyser: Analyser = .init(gpa, arena, &store, &ip, handle); - defer analyser.deinit(); - - const off: usize = @min(req.offset, req.source.len); - - // the rows of the kinds that only ever name THIS file spell it once - const here = lsp.rel(req.root, req.path); - - switch (kind) { - .definition, .implementation => try goto(arena, &analyser, handle, off, .definition, req.root, out, tr), - .declaration => try goto(arena, &analyser, handle, off, .declaration, req.root, out, tr), - .type_definition => try goto(arena, &analyser, handle, off, .type_definition, req.root, out, tr), - .hover => try hover(arena, &analyser, handle, off, out), - .document_symbols => try documentSymbols(gpa, arena, here, &handle.tree, out), - .references, .select_refs => try references(arena, &analyser, handle, off, null, req.root, out), - .rename => try references(arena, &analyser, handle, off, req.arg, req.root, out), - .diagnostics => try diagnostics(gpa, arena, here, &handle.tree, out), - .code_action => try codeActions(gpa, arena, &analyser, handle, off, out), - .completion => try completion(arena, &analyser, handle, off, req.root, req.source, out, tr), - else => {}, - } -} - -/// `SPC l i`. What the backend IS: which ZLS, which stdlib, what it will and -/// will not answer, and the last two dozen queries with their timings and — -/// the point of the whole exercise — the errors that `query` swallowed. -fn status(arena: std.mem.Allocator, req: lsp.Req, out: *std.Io.Writer) !void { - const io = std.Io.Threaded.global_single_threaded.io(); - try out.print("backend: {s}\nzls: {s} (compiled in — no server process, no JSON-RPC)\n", .{ - lsp.backend_name, cfg.zls_version, - }); - - // The single most common cause of "gd does nothing in std": say whether it - // is actually openable, not just what it is set to. - if (zigLibPath()) |p| { - if (std.Io.Dir.cwd().openDir(io, p, .{})) |h| { - var d = h; - d.close(io); - try out.print("zig lib dir: {s} [OK]\n", .{p}); - } else |e| try out.print("zig lib dir: {s} [CANNOT OPEN: {s}] — nothing in `std` will resolve\n", .{ p, @errorName(e) }); - } else try out.print("zig lib dir: NOT SET — nothing in `std` will resolve\n", .{}); - try out.print("offsets: {s} walk caps: {d} files, {d} rows\n", .{ @tagName(enc), max_files, max_rows }); - // The dependency module map, which is the answer to "why does gd work on - // std and not on @import(\"vaxis\")" — if a name is not on this list, the - // build did not import it and nothing can resolve it. - // pardes's own build's imports: listed for a file in its tree, none for - // any other project's file, which does not have them. - if (inProject(req.path)) { - try out.print("\ndependency imports gd can follow ({d}):\n", .{cfg.module_names.len}); - for (cfg.module_names, cfg.module_roots) |n, r| { - try out.print(" {s:<14} {s}\n", .{ n, r }); - } - } else try out.print("\ndependency imports gd can follow: none (this file is not in the tree pardes was built from)\n", .{}); - try out.print("asked from: {s}\n", .{if (req.path.len == 0) "a pane with no file" else req.path}); - - try out.print("\nanswers:", .{}); - var it = supports.iterator(); - var n: usize = 0; - while (it.next()) |k| : (n += 1) { - if (k == .status or k == .explain) continue; // these two are the debugger, not a feature - try out.print("{s}{s}", .{ if (n == 0) " " else ", ", @tagName(k) }); - } - try out.print("\nrefuses: ", .{}); - n = 0; - for (std.enums.values(lsp.Kind)) |k| { - if (supports.contains(k)) continue; - try out.print("{s}{s}", .{ if (n == 0) "" else ", ", @tagName(k) }); - n += 1; - } - if (n == 0) try out.print("(nothing)", .{}); - try out.print("\n", .{}); - - // The log. Oldest first, so it reads like a transcript. - logLock(); - defer log_mu.unlock(); - try out.print("\nlast queries ({d} total, keeping {d}):\n", .{ log_total, log_cap }); - var shown: usize = 0; - for (0..log_cap) |i| { - const e = &log_buf[(log_next + i) % log_cap]; - if (!e.used) continue; - shown += 1; - if (hideTime()) { - try out.print(" {s:<22} {s:<20} @{d:<7} {d:>4} row(s){s}{s}\n", .{ - @tagName(e.kind), e.fileName(), e.offset, e.rows, - if (e.err_len == 0) "" else " ERROR: ", e.errName(), - }); - } else { - try out.print(" {s:<22} {s:<20} @{d:<7} {d:>7}us {d:>4} row(s){s}{s}\n", .{ - @tagName(e.kind), e.fileName(), e.offset, e.us, e.rows, - if (e.err_len == 0) "" else " ERROR: ", e.errName(), - }); - } - } - if (shown == 0) try out.print(" (none yet — press gd somewhere, then ask again)\n", .{}); - _ = arena; -} - -/// The root source file of a module this build imports, or null. -/// -/// ZLS answers `@import("std")` from `zig_lib_dir` and a relative `.zig` path -/// from the filesystem, but ANY OTHER name — every dependency in -/// build.zig.zon — it can only resolve by running `zig build --build-runner` -/// to discover the module graph. This backend sets `zig_exe_path = null` on -/// purpose, so that branch always returned nothing: `gd` worked perfectly into -/// `std` and silently did nothing on `@import("vaxis")`. -/// -/// We never needed the compiler for this. build.zig IS the module graph, so it -/// folds its own `root_mod.import_table` into these two parallel arrays at -/// configure time. Correct by construction: a dependency added or renamed in -/// build.zig cannot forget to appear here. -/// -/// LIMITS, in the order you will hit them: -/// 1. This resolves the IMPORT STRING only. It is consulted from our own -/// `goto`, not from inside ZLS, so the analyser still cannot type the -/// `vaxis` const — `gd` on `vaxis.init` finds nothing. Fixing that means -/// giving ZLS a BuildConfig; see the note at the top of this file. -/// 2. These are THIS build's imports. A file inside a dependency importing -/// that dependency's own internal module name is a miss — that would mean -/// running ITS build.zig. -/// 3. A module whose root source is a GENERATED file is absent from the -/// table: it has no path until make() runs. -/// Whether `path` is in the tree pardes was built from, whose build's -/// imports `cfg.module_names` are. -fn inProject(path: []const u8) bool { - const project = std.mem.trimEnd(u8, cfg.project_root, "/"); - return project.len > 0 and path.len > project.len and std.mem.startsWith(u8, path, project) and path[project.len] == '/'; -} - -test "only a file in pardes's own tree is told pardes's dependency imports" { - var buf: [4096]u8 = undefined; - const inside = try std.fmt.bufPrint(&buf, "{s}/src/main.zig", .{std.mem.trimEnd(u8, cfg.project_root, "/")}); - try std.testing.expect(inProject(inside)); - try std.testing.expect(!inProject("/tmp/elsewhere/main.zig")); -} - -fn moduleRoot(name: []const u8) ?[]const u8 { - comptime std.debug.assert(cfg.module_names.len == cfg.module_roots.len); - for (cfg.module_names, cfg.module_roots) |n, r| { - if (std.mem.eql(u8, n, name)) return r; - } - return null; -} - -/// Why a field access came back empty. Worth its own function because ONE of -/// the reasons is a known, explainable hole rather than "no idea": if the left -/// side starts with a dependency module name, the analyser could not type it -/// because ZLS has no build config, and no amount of staring at the code will -/// reveal that. -fn explainFieldMiss(tr: *Trace, lhs: []const u8) void { - var head: usize = 0; - while (head < lhs.len and (std.ascii.isAlphanumeric(lhs[head]) or lhs[head] == '_')) head += 1; - if (head != 0 and moduleRoot(lhs[0..head]) != null) { - tr.note(" `{s}` IS a build.zig dependency, and this is the known hole: the module", .{lhs[0..head]}); - tr.note(" map is consulted by our @import handler, not by ZLS, so the analyser cannot", .{}); - tr.note(" type it. `gd` on the import string works; `gd` on a member does not.", .{}); - return; - } - tr.note(" (a value whose type needs comptime, an unresolved @import, or genuinely absent)", .{}); -} - -/// The zig lib directory, which is the one thing this backend cannot work out -/// for itself: it is baked in at build time from `b.graph.zig_lib_directory`, -/// i.e. the exact stdlib pardes was compiled against, and ZIG_LIB_DIR wins if -/// the user moved it. Without this, `gd` on anything in `std` finds nothing. -fn zigLibPath() ?[]const u8 { - if (std.c.getenv("ZIG_LIB_DIR")) |p| { - const s = std.mem.span(p); - if (s.len != 0) return s; - } - if (cfg.zig_lib_dir.len != 0) return cfg.zig_lib_dir; - return null; -} - -// ---------------------------------------------------------------- rows - -/// Byte offset -> line, without rescanning the file per row. Built once per -/// query over the file we emit many rows from (symbols, references, -/// diagnostics); a goto that emits two rows just scans. -const Lines = struct { - starts: []const u32, - src: []const u8, - - fn build(arena: std.mem.Allocator, src: []const u8) !Lines { - const count = std.mem.countScalar(u8, src, '\n') + 1; - const starts = try arena.alloc(u32, count); - starts[0] = 0; - var n: usize = 1; - for (src, 0..) |c, i| { - if (c != '\n') continue; - starts[n] = @intCast(i + 1); - n += 1; - } - return .{ .starts = starts, .src = src }; - } - - fn line(l: Lines, n: usize) []const u8 { - if (n >= l.starts.len) return ""; - const a = l.starts[n]; - const b = if (n + 1 < l.starts.len) l.starts[n + 1] - 1 else l.src.len; - return l.src[a..@min(b, l.src.len)]; - } -}; - -/// The source line at a 0-based line number, scanned. For the one-or-two-row -/// answers (a goto lands in a file we opened only to read one line out of). -fn lineAt(src: []const u8, want: usize) []const u8 { - var it = std.mem.splitScalar(u8, src, '\n'); - var i: usize = 0; - while (it.next()) |l| : (i += 1) if (i == want) return l; - return ""; -} - -/// Emit one row for a token in whatever file it lives in — which for a goto -/// into `std` is not the file the cursor was in, so the path comes off the -/// handle's uri rather than off `req`. `base` is `req.root`, the directory the -/// row is written relative to (lsp.rel). -fn rowForToken(arena: std.mem.Allocator, base: []const u8, th: Analyser.TokenWithHandle, out: *std.Io.Writer) !void { - const tree = &th.handle.tree; - if (th.token >= tree.tokens.len) return; - const r = offsets.tokenToRange(tree, th.token, enc); - const path = lsp.rel(base, th.handle.uri.toFsPath(arena) catch return); - try lsp.sourceSpanRow(out, path, r.start.line, r.start.character, r.end.line, r.end.character, lineAt(tree.source, r.start.line)); -} - -// ---------------------------------------------------------------- goto - -const GotoKind = enum { declaration, definition, type_definition }; - -/// `goto.zig:gotoHandler` minus the Server, minus the LSP types, minus the -/// linkSupport branch: dispatch on the position context, resolve to a decl, -/// resolve the decl to a token, print the token's line. The five helix gotos -/// collapse onto three ZLS kinds (`gi` behaves as `gd`, which is what ZLS's -/// own implementation handler does too). -fn goto( - arena: std.mem.Allocator, - analyser: *Analyser, - handle: *DocumentStore.Handle, - off: usize, - kind: GotoKind, - /// req.root: what the rows' paths are written relative to (lsp.rel) - base: []const u8, - out: *std.Io.Writer, - tr: *Trace, -) !void { - const tree = &handle.tree; - const ctx = try Analyser.getPositionContext(arena, tree, off, true); - tr.note("position context: .{s}", .{@tagName(ctx)}); - - const decls = try arena.alloc(Analyser.DeclWithHandle, max_rows); - var decl_count: usize = 0; - switch (ctx) { - .var_access, .test_doctest_name => { - const name_loc = offsets.identifierLocFromIndex(tree, off) orelse { - tr.note("STOP: no identifier under the cursor", .{}); - return; - }; - const name = offsets.locToSlice(tree.source, name_loc); - tr.note("identifier: `{s}` — a plain name, so: innermost scope outward", .{name}); - if (std.mem.eql(u8, name, "_")) { - tr.note("STOP: `_` is the discard, it declares nothing", .{}); - return; - } - if (std.zig.isPrimitive(name)) { - tr.note("STOP: `{s}` is a builtin primitive — it has no declaration in any file", .{name}); - return; - } - const d = try analyser.lookupSymbolGlobal(handle, name, off) orelse { - tr.note("STOP: lookupSymbolGlobal found no `{s}` in scope here", .{name}); - return; - }; - decls[decl_count] = d; - decl_count += 1; - }, - .field_access => |loc| { - const name_loc = offsets.identifierLocFromIndex(tree, off) orelse { - tr.note("STOP: no identifier under the cursor", .{}); - return; - }; - const name = offsets.locToSlice(tree.source, name_loc); - const held = offsets.locMerge(loc, name_loc); - tr.note("field access: `{s}` on `{s}` — needs the TYPE of the left side", .{ - name, offsets.locToSlice(tree.source, loc), - }); - // NOTE both misses: a null result AND an empty one. ZLS returns an - // empty slice when it typed the left side but found no such member, - // and null when it could not type it at all — from the outside both - // are "gd did nothing", so both have to be explained. - const found = try analyser.getSymbolFieldAccesses(arena, handle, off, held, name) orelse { - tr.note("STOP: could not resolve the left side to a type at all", .{}); - explainFieldMiss(tr, offsets.locToSlice(tree.source, loc)); - return; - }; - if (found.len == 0) { - tr.note("STOP: the left side resolved, but nothing named `{s}` was found on it", .{name}); - explainFieldMiss(tr, offsets.locToSlice(tree.source, loc)); - return; - } - decl_count = @min(found.len, decls.len); - @memcpy(decls[0..decl_count], found[0..decl_count]); - }, - .label_access, .label_decl => { - const name_loc = offsets.identifierLocFromIndex(tree, off) orelse return; - const name = offsets.locToSlice(tree.source, name_loc); - const d = try Analyser.lookupLabel(handle, name, off) orelse return; - decls[decl_count] = d; - decl_count += 1; - }, - .enum_literal => { - const name_loc = offsets.identifierLocFromIndex(tree, off) orelse return; - const name = offsets.locToSlice(tree.source, name_loc); - const d = try analyser.getSymbolEnumLiteral(handle, off, name) orelse return; - decls[decl_count] = d; - decl_count += 1; - }, - // `gd` on `@import("foo.zig")` opens foo.zig. Only relative imports - // resolve — a package name needs the build graph we do not run. - .import_string_literal, .embedfile_string_literal => { - const loc = ctx.stringLiteralContentLoc(tree.source); - if (loc.start == loc.end) return; - const str = offsets.locToSlice(tree.source, loc); - tr.note("import string: \"{s}\"", .{str}); - const res = try analyser.store.uriFromImportStr(arena, handle, str); - switch (res) { - .none => { - // ZLS gave up, which for a DEPENDENCY name is not a real - // dead end — it just means it wanted the module graph and - // we would not start a compiler to get one. Our build.zig - // knows the graph and baked it in; consult that. - if (moduleRoot(str)) |path| { - tr.note("`{s}` is a build.zig dependency; resolved from the compiled-in module map", .{str}); - try lsp.row(out, lsp.rel(base, path), 0, 0, str); - return; - } - tr.note("STOP: `{s}` does not resolve to a file. Relative paths, `std` and this", .{str}); - tr.note(" build's own dependencies work; `builtin`, `root` and a dependency's", .{}); - tr.note(" OWN internal module names need the build graph we do not run.", .{}); - return; - }, - .one => |u| try lsp.row(out, lsp.rel(base, u.toFsPath(arena) catch return), 0, 0, str), - .many => |us| for (us) |u| try lsp.row(out, lsp.rel(base, u.toFsPath(arena) catch continue), 0, 0, str), - } - return; - }, - else => { - tr.note("STOP: nothing to resolve in a .{s} context — `gd` only answers on", .{@tagName(ctx)}); - tr.note(" an identifier, a field access, a label, an enum literal or an @import string.", .{}); - return; - }, - } - - tr.note("resolved to {d} declaration(s); asking each for its {s} token", .{ decl_count, @tagName(kind) }); - // One decl that fails to resolve must not swallow the others: a field - // access can name several and a partial answer beats none. - for (decls[0..decl_count]) |d| { - switch (kind) { - .declaration => try rowForToken(arena, base, d.definitionToken(analyser, false) catch continue, out), - .definition => try rowForToken(arena, base, d.definitionToken(analyser, true) catch continue, out), - .type_definition => { - // peel error unions / pointers / optionals the way ZLS does, - // then take the container's own name token - if (try d.resolveType(analyser)) |ty| { - var r = ty; - while (true) { - r = try analyser.resolveUnwrapErrorUnionType(r, .payload) orelse - try analyser.resolveDerefType(r) orelse - try analyser.resolveOptionalUnwrap(r) orelse break; - } - if (r.typeDefinitionToken()) |th| { - try rowForToken(arena, base, th, out); - continue; - } - } - const nd = try d.typeDeclarationNode() orelse continue; - const t2 = &nd.handle.tree; - const rr = offsets.nodeToRange(t2, nd.node, enc); - const path = lsp.rel(base, nd.handle.uri.toFsPath(arena) catch continue); - try lsp.sourceSpanRow(out, path, rr.start.line, rr.start.character, rr.end.line, rr.end.character, lineAt(t2.source, rr.start.line)); - }, - } - } -} - -// ------------------------------------------------------------ completion - -/// The text a completion query actually analyses. -/// -/// The user has just typed the `.`, so the buffer DOES NOT PARSE, and not -/// locally: `switch (e) { . }` loses the entire switch to the parser's error -/// recovery — the tree keeps the function's block and nothing inside it — -/// which takes with it every ancestor an expected-type resolution needs. ZLS -/// answers this with a private token scanner (`getSwitchOrStructInitContext`, -/// ~200 lines welded to a `*Server`) that re-derives the context by hand. This -/// backend instead makes the tree PARSE, by splicing a placeholder in after -/// the dot. Six spellings, because a half-typed line is short of two different -/// things — the identifier the dot needs, and whatever the user has not closed -/// yet — and the second half is not optional: a missing closer makes Zig's -/// recovery discard the whole enclosing declaration, which no placeholder AT -/// the dot can survive. -/// -/// `_p => {},` a switch prong: not a prong at all without its arrow, so -/// no bare identifier can rescue one -/// `_p;` a statement or declaration still missing its terminator, -/// which is what `const z: E = .` is the instant it is typed -/// `_p` everything already closed: `f(.)`, `x = .;`, `.a = .` -/// `_p => {}, }` ...and the same three again for a construct still hanging -/// `_p)` open — `switch (e) {`, `g(`, `.{` with no closer yet, -/// `_p }` which is what the first second of typing looks like -/// -/// No spelling may contain a NEWLINE: the rows depend on line numbers being -/// identical between the repaired copy and the user's buffer (see `completion`). -/// -/// Choosing between them: reachability (is the dot now an `enum_literal` the -/// tree can be walked down to from the root) is a hard FILTER, the parse-error -/// count RANKS what survives it, the earlier spelling wins a tie, and a -/// candidate at ZERO errors ends the search. A buffer that already parses is -/// left alone, and a dot no spelling can reach is the seam's normal "no -/// result". -/// ponytail: one parse per spelling; caching the base parse is the obvious -/// next step if it ever shows up. -fn completionSource(arena: std.mem.Allocator, req: lsp.Req, tr: *Trace) [:0]const u8 { - if (req.offset == 0 or req.offset > req.source.len) return req.source; - if (req.source[req.offset - 1] != '.') return req.source; - var base: Ast = Ast.parse(arena, req.source, .zig) catch return req.source; - // Nothing to repair: a bare `.` is always a parse error, so a clean tree - // means the dot is already part of a node — the placeholder's whole job. - if (base.errors.len == 0) return req.source; - // A field access resolves off the position context and its own tokenizer, - // never off the tree, so `foo.` needs no placeholder and pays no shift. - const ctx = Analyser.getPositionContext(arena, &base, req.offset, false) catch return req.source; - if (ctx != .enum_literal) return req.source; - - var best = req.source; - var chose: []const u8 = ""; - var fewest: usize = std.math.maxInt(usize); - for ([_][]const u8{ "_p => {},", "_p;", "_p", "_p => {}, }", "_p)", "_p }" }) |fill| { - const cand = std.fmt.allocPrintSentinel(arena, "{s}{s}{s}", .{ - req.source[0..req.offset], fill, req.source[req.offset..], - }, 0) catch continue; - var t: Ast = Ast.parse(arena, cand, .zig) catch continue; - if (t.errors.len >= fewest) continue; - const nodes = zls.ast.nodesOverlappingIndex(arena, &t, req.offset) catch continue; - if (nodes.len < 2 or t.nodeTag(nodes[0]) != .enum_literal) continue; - fewest = t.errors.len; - best = cand; - chose = fill; - if (fewest == 0) break; - } - if (chose.len == 0) - tr.note("STOP: no placeholder made the dot reachable in the tree ({d} parse error(s))", .{base.errors.len}) - else - tr.note("placeholder `{s}`: the dot is an enum_literal again, {d} parse error(s) left (was {d})", .{ chose, fewest, base.errors.len }); - return best; -} - -/// ZLS's collector takes a growable list. This equivalent writes directly into -/// the query's row-bounded slice and stops in declaration order when it fills. -fn collectContainerDecls( - analyser: *Analyser, - container_type: Analyser.Type, - original_handle: *DocumentStore.Handle, - instance_access: bool, - out: []Analyser.DeclWithHandle, - len: *usize, -) !void { - const info = switch (container_type.data) { - .container => |info| info, - .either => |entries| { - for (entries) |entry| { - if (len.* == out.len) return; - const ty: Analyser.Type = .{ - .data = entry.type_data, - .is_type_val = container_type.is_type_val, - }; - try collectContainerDecls(analyser, ty, original_handle, instance_access, out, len); - } - return; - }, - else => return, - }; - const container_scope = info.scope_handle; - const handle = container_scope.handle; - const tree = &handle.tree; - const document_scope = try handle.getDocumentScope(); - const main_token = tree.nodeMainToken(container_scope.toNode()); - const is_enum = tree.tokenTag(main_token) == .keyword_enum; - - for (document_scope.getScopeDeclarationsConst(container_scope.scope)) |decl_index| { - if (len.* == out.len) return; - const decl = document_scope.declarations.get(@intFromEnum(decl_index)); - const candidate: Analyser.DeclWithHandle = .{ - .decl = decl, - .handle = handle, - .container_type = container_type, - }; - if (handle != original_handle and !candidate.isPublic()) continue; - - switch (decl) { - .ast_node => |node| switch (tree.nodeTag(node)) { - .container_field_init, .container_field_align, .container_field => { - if (is_enum) { - if (instance_access) continue; - const field_name = offsets.tokenToSlice(tree, tree.nodeMainToken(node)); - if (std.mem.eql(u8, field_name, "_")) continue; - } else if (!instance_access) continue; - }, - .fn_proto, - .fn_proto_multi, - .fn_proto_one, - .fn_proto_simple, - .fn_decl, - .global_var_decl, - .local_var_decl, - .simple_var_decl, - .aligned_var_decl, - => { - if (instance_access) { - const alias_type = try candidate.resolveType(analyser) orelse continue; - const func_ty = try analyser.resolveFuncProtoOfCallable(alias_type) orelse continue; - if (!analyser.firstParamIs(func_ty, .{ - .data = .{ .container = info }, - .is_type_val = true, - })) continue; - } - }, - else => unreachable, - }, - .label => continue, - else => {}, - } - out[len.*] = candidate; - len.* += 1; - } -} - -/// Tab after a `.`. NOT an autocomplete popup: the seam answers with -/// locations, so the question it asks is "what could go here, and where is -/// each of those DEFINED" — one `+Search` row per candidate, pointing at its -/// declaration, the same rows `gr` emits and the same `n`/`N` that step them. -/// Nothing is inserted; picking is looking at a row. -/// -/// A dot has two meanings and both come off the public analyser: -/// `foo.` a field access — resolve the left side's type, list its members. -/// `.` an enum literal — resolve the type EXPECTED at this position (a -/// switch's condition, a call's parameter, a variable's annotation, -/// an initialiser's field) and list that type's members. -/// The second exists only because `completionSource` made the tree parse. -fn completion( - arena: std.mem.Allocator, - analyser: *Analyser, - handle: *DocumentStore.Handle, - off: usize, - /// req.root: what the rows' paths are written relative to (lsp.rel) - base: []const u8, - /// the buffer as the USER has it, before completionSource repaired it. The - /// rows are read out of THIS one; the handle's tree is the repaired copy - /// and its text is not what is on screen. - orig: []const u8, - out: *std.Io.Writer, - tr: *Trace, -) !void { - const tree = &handle.tree; - // lookahead FALSE, the way ZLS's own completion asks: the cursor sits at - // the END of what was typed and there is nothing to its right to read. - const ctx = try Analyser.getPositionContext(arena, tree, off, false); - tr.note("position context: .{s}", .{@tagName(ctx)}); - // naming a field INSIDE an initialiser (`.{ .`, `S{ .`) rather than - // writing a whole value — a different question with a different answer, - // and the only one the ancestors cannot state for themselves - var in_init = false; - const found: ?Analyser.Type = switch (ctx) { - .field_access => |loc| try analyser.getFieldAccessType(handle, off, loc), - .enum_literal => blk: { - const nodes = try zls.ast.nodesOverlappingIndex(arena, tree, off); - if (nodes.len == 0) break :blk null; - if (try analyser.resolveExpressionTypeFromAncestors(handle, nodes[0], nodes[1..])) |t| break :blk t; - // `.{ .` and `S{ .` parse as an ARRAY init holding one enum - // literal, and an array's ELEMENT type is not what is being named - // there — the user is naming a FIELD, so the type wanted is the - // initialiser's own. - var buf: [2]Ast.Node.Index = undefined; - if (nodes.len > 1 and tree.fullArrayInit(&buf, nodes[1]) != null) { - in_init = true; - break :blk try analyser.resolveExpressionType(handle, nodes[1], nodes[2..]); - } - break :blk null; - }, - // a dot in a comment or a string is a dot in prose - else => null, - }; - var ty = found orelse { - tr.note("STOP: nothing expected here that this backend can name", .{}); - return; - }; - // the same peel `gy` does: what can go in a `?E`, an `E!T` or a `*E` slot - // is what can go in an `E` one - while (true) { - ty = try analyser.resolveUnwrapErrorUnionType(ty, .payload) orelse - try analyser.resolveDerefType(ty) orelse - try analyser.resolveOptionalUnwrap(ty) orelse break; - } - // `instance_access` is the collector's one knob and it - // means different things per container kind: it is what hides an enum's - // members and what reveals a struct's fields. So: a field access asks - // whichever side the left-hand expression already was; a field named - // inside an initialiser asks the instance side, which is where fields - // live; and everywhere else — a switch arm, an argument, `= .` — asks the - // type side, which is where an enum's members are. A union is a struct - // whose fields are also its tags, so it wants the instance side wherever - // it appears. - const value_pos = ctx == .enum_literal and !in_init; - const decls = try arena.alloc(Analyser.DeclWithHandle, max_rows); - var decl_count: usize = 0; - try collectContainerDecls(analyser, ty, handle, switch (ctx) { - .field_access => !ty.is_type_val, - else => in_init or ty.isUnionType(), - }, decls, &decl_count); - tr.note("{d} candidate(s) in scope", .{decl_count}); - // What completionSource spliced in at `off`, which the ROWS have to take - // back out. The tree being read is the REPAIRED copy, so for a candidate - // declared in this same file two things are wrong with the naive row: its - // line text is the repaired line, so the user reads `= ._p;` back out of a - // file that says no such thing; and every column on the cursor's line to - // the right of the dot is `pad` too far right, so a look on the row - // selects `", "` where it should select `qq`. Line numbers need no - // correction at all — no spelling contains a newline — and a candidate in - // ANOTHER file is untouched by any of this. - const pad = tree.source.len - orig.len; - const dot = lsp.lineCol(orig, off); - var n: usize = 0; - for (decls[0..decl_count]) |d| { - if (n >= max_rows) return; - // In a value position the answer is the container's MEMBERS plus its - // DECL LITERALS (`.empty`, `.init`) — never a method, an unrelated - // const or a type ALIAS, none of which can go after that dot, and - // offering one is worse than offering nothing. So every non-member - // decl is resolved, called, and kept only if what comes back IS this - // container. `typeOf` on both sides is what excludes the alias: a - // `pub const Alias = E` resolves to a TYPE VALUE, whose type is - // `type` and not the container. (ZLS's own rule, and its own reason.) - const member = d.decl == .ast_node and d.handle.tree.nodeTag(d.decl.ast_node).isContainerField(); - if (value_pos and !member) { - var lit = try d.resolveType(analyser) orelse continue; - lit = try analyser.resolveReturnType(lit) orelse lit; - lit = lit.resolveDeclLiteralResultType(); - if (!(try lit.typeOf(analyser)).eql(try ty.typeOf(analyser))) continue; - } - // The WORD, off the decl's own name token. Not the definition token - // below it: `definitionToken` resolves an ALIAS through to what it - // names, so for `pub const base64 = @import("base64.zig")` it lands on - // base64.zig's first token and the "name" would come out as that file's - // doc comment. What goes after the dot is what the container calls it. - const name_tok = d.nameToken(); - if (name_tok >= d.handle.tree.tokens.len) continue; - const name = offsets.tokenToSlice(&d.handle.tree, name_tok); - - const th = d.definitionToken(analyser, true) catch continue; - const dtree = &th.handle.tree; - if (th.token >= dtree.tokens.len) continue; - var r = offsets.tokenToRange(dtree, th.token, enc); - const path = lsp.rel(base, th.handle.uri.toFsPath(arena) catch continue); - // The name, then its declaration line: "what goes here" before "where - // does it come from", which is the order the question was asked in — - // every other kind here answers a WHERE, this one answers a WHAT and - // the location is the evidence. Two spaces rather than a padded column, - // because the `path:LINE:COL-END` in front of it is already ragged and - // there is nothing to align to. - const text = try std.fmt.allocPrint(arena, "{s} {s}", .{ - name, - std.mem.trim(u8, lineAt(if (th.handle == handle) orig else dtree.source, r.start.line), " \t\r\n"), - }); - if (th.handle == handle and pad != 0 and r.start.line == dot.line and - @as(usize, r.start.character) >= dot.col + pad) - { - r.start.character -= @intCast(pad); - if (r.end.line == r.start.line) r.end.character -= @intCast(pad); - } - try lsp.spanRow(out, path, r.start.line, r.start.character, r.end.line, r.end.character, text); - n += 1; - } -} - -// ---------------------------------------------------------------- hover - -/// `hover.hover` is already Server-free, so this is a call and a reformat: the -/// `+Hover` buffer holds prose, not locations, so the markdown comes through -/// as lines and nothing arms the n/N stepper. Fenced-code markers are dropped -/// because a plain-text pane has nothing to do with them. -fn hover( - arena: std.mem.Allocator, - analyser: *Analyser, - handle: *DocumentStore.Handle, - off: usize, - out: *std.Io.Writer, -) !void { - const h = try zls.hover.hover(analyser, arena, handle, off, .markdown, enc) orelse return; - const text = switch (h.contents) { - .markup_content => |m| m.value, - else => return, - }; - var it = std.mem.splitScalar(u8, text, '\n'); - while (it.next()) |ln| { - if (std.mem.startsWith(u8, ln, "```")) continue; - try out.print("{s}\n", .{std.mem.trimEnd(u8, ln, " \t\r")}); - } -} - -// ---------------------------------------------------------------- symbols - -/// `document_symbol.getDocumentSymbols` needs an arena, a tree and an encoding -/// — no store, no analyser, no intern pool. That makes `SPC s` the cheapest -/// thing in this file: a parse and a walk. -fn documentSymbols( - gpa: std.mem.Allocator, - arena: std.mem.Allocator, - path: []const u8, - tree: *const Ast, - out: *std.Io.Writer, -) !void { - const syms = try zls.document_symbol.getDocumentSymbols(arena, tree, enc); - var n: usize = 0; - try emitSymbols(gpa, arena, path, syms, "", &n, out); -} - -/// Depth-first so the rows read in source order, with the parent's name as a -/// qualifier — `Pardes.update` rather than a bare `update`, -/// because a flat list of method names is not navigable. -fn emitSymbols( - gpa: std.mem.Allocator, - arena: std.mem.Allocator, - path: []const u8, - syms: []const types.DocumentSymbol, - prefix: []const u8, - n: *usize, - out: *std.Io.Writer, -) !void { - for (syms) |s| { - if (n.* >= max_rows) return; - n.* += 1; - const name = if (prefix.len == 0) - s.name - else - try std.fmt.allocPrint(arena, "{s}.{s}", .{ prefix, s.name }); - const text = if (s.detail) |d| - try std.fmt.allocPrint(arena, "{s} {s}", .{ name, d }) - else - name; - try lsp.spanRow(out, path, s.selectionRange.start.line, s.selectionRange.start.character, s.selectionRange.end.line, s.selectionRange.end.character, text); - if (s.children) |kids| try emitSymbols(gpa, arena, path, kids, name, n, out); - } -} - -/// `SPC S`: every `.zig` under the pane's directory, parsed, walked, filtered -/// by substring. ZLS's own workspace symbols would only see files already in -/// the DocumentStore (which is one), so this walks the tree itself — and -/// because `getDocumentSymbols` needs nothing but a tree, it never has to open -/// a store or resolve an import to do it. -fn workspaceSymbols( - gpa: std.mem.Allocator, - arena: std.mem.Allocator, - io: std.Io, - req: lsp.Req, - out: *std.Io.Writer, -) !void { - if (req.arg.len == 0) return; - const files = try collectZigFiles(arena, io, req.root); - var n: usize = 0; - for (files) |path| { - if (n >= max_rows) return; - const src = readFileZ(arena, io, path) catch continue; - var tree: Ast = Ast.parse(arena, src, .zig) catch continue; - defer tree.deinit(arena); - const syms = zls.document_symbol.getDocumentSymbols(arena, &tree, enc) catch continue; - try filterSymbols(gpa, arena, lsp.rel(req.root, path), syms, "", req.arg, &n, out); - } -} - -fn filterSymbols( - gpa: std.mem.Allocator, - arena: std.mem.Allocator, - path: []const u8, - syms: []const types.DocumentSymbol, - prefix: []const u8, - needle: []const u8, - n: *usize, - out: *std.Io.Writer, -) !void { - for (syms) |s| { - if (n.* >= max_rows) return; - const name = if (prefix.len == 0) - s.name - else - try std.fmt.allocPrint(arena, "{s}.{s}", .{ prefix, s.name }); - if (containsIgnoreCase(s.name, needle)) { - n.* += 1; - try lsp.spanRow(out, path, s.selectionRange.start.line, s.selectionRange.start.character, s.selectionRange.end.line, s.selectionRange.end.character, name); - } - if (s.children) |kids| try filterSymbols(gpa, arena, path, kids, name, needle, n, out); - } -} - -fn containsIgnoreCase(hay: []const u8, needle: []const u8) bool { - if (needle.len == 0) return true; - if (needle.len > hay.len) return false; - var i: usize = 0; - outer: while (i + needle.len <= hay.len) : (i += 1) { - for (needle, 0..) |c, j| - if (std.ascii.toLower(hay[i + j]) != std.ascii.toLower(c)) continue :outer; - return true; - } - return false; -} - -// ------------------------------------------------------------- references - -/// `gr` / `SPC h` / `SPC r`. ZLS's `symbolReferences` is private and its -/// `referencesHandler` takes a `*Server`, so this is the same algorithm from -/// the outside: find the decl under the cursor, then offer every identifier -/// token in the file that spells the same name back to the analyser and keep -/// the ones that resolve to the same decl. Resolving rather than matching is -/// what makes a shadowed local not a reference to the outer one. -/// -/// LIMIT: this file only. A workspace-wide answer means loading every project -/// file into the store and running the analyser over each — seconds, not -/// milliseconds, on every keypress, and the store's own workspace iteration -/// has the same restriction (it can only see handles that were loaded). -/// -/// `new_name` non-null makes it a rename EDIT: the same resolved tokens become -/// half-open byte ranges. The core owns the replacement text and applies every -/// range in one undo transaction after checking the source revision. -fn references( - arena: std.mem.Allocator, - analyser: *Analyser, - handle: *DocumentStore.Handle, - off: usize, - new_name: ?[]const u8, - /// req.root: what the rows' paths are written relative to (lsp.rel) - base: []const u8, - out: *std.Io.Writer, -) !void { - const tree = &handle.tree; - const target = try declAt(arena, analyser, handle, off) orelse return; - // The decl's name token indexes ITS OWN file, which after an alias resolve - // is not necessarily this one — and on a half-typed file it is not - // necessarily an identifier either, which `identifierTokenToNameSlice` - // asserts. Both of those are crashes on a keystroke, so both are checked. - const decl_tree = &target.handle.tree; - const name_tok = target.nameToken(); - if (name_tok >= decl_tree.tokens.len) return; - if (decl_tree.tokenTag(name_tok) != .identifier) return; - const want = offsets.identifierTokenToNameSlice(decl_tree, name_tok); - if (want.len == 0) return; - - // Rename consumes exact byte ranges. Reference rows need the source line - // and displayed path; avoid building either for the mutating response. - const lines: ?Lines = if (new_name == null) try .build(arena, tree.source) else null; - const path = if (new_name == null) lsp.rel(base, handle.uri.toFsPath(arena) catch return) else ""; - var n: usize = 0; - for (0..tree.tokens.len) |i| { - if (new_name == null and n >= max_rows) return; - const tok: Ast.TokenIndex = @intCast(i); - if (tree.tokenTag(tok) != .identifier) continue; - if (!std.mem.eql(u8, offsets.identifierTokenToNameSlice(tree, tok), want)) continue; - const at = tree.tokenStart(tok); - const d = (declAt(arena, analyser, handle, at) catch |err| { - if (new_name != null) return err; - continue; - }) orelse continue; - if (!d.eql(target)) continue; - if (n >= max_rows) return error.TooManyEdits; - n += 1; - if (new_name != null) { - try lsp.edit(out, at, at + want.len); - } else { - const r = offsets.tokenToRange(tree, tok, enc); - try lsp.sourceSpanRow(out, path, r.start.line, r.start.character, r.end.line, r.end.character, lines.?.line(r.start.line)); - } - } -} - -/// The decl under a byte offset, whatever the surrounding syntax is. Shared by -/// references and by rename, which is references with a label on it. -fn declAt( - arena: std.mem.Allocator, - analyser: *Analyser, - handle: *DocumentStore.Handle, - off: usize, -) !?Analyser.DeclWithHandle { - const tree = &handle.tree; - const ctx = try Analyser.getPositionContext(arena, tree, off, true); - const name_loc = offsets.identifierLocFromIndex(tree, off) orelse return null; - const name = offsets.locToSlice(tree.source, name_loc); - const d = switch (ctx) { - .var_access, .test_doctest_name => try analyser.lookupSymbolGlobal(handle, name, off), - .field_access => |loc| blk: { - const found = try analyser.getSymbolFieldAccesses(arena, handle, off, offsets.locMerge(loc, name_loc), name) orelse break :blk null; - break :blk if (found.len != 0) found[0] else null; - }, - .label_access, .label_decl => try Analyser.lookupLabel(handle, name, off), - .enum_literal => try analyser.getSymbolEnumLiteral(handle, off, name), - else => null, - } orelse return null; - return try analyser.resolveVarDeclAlias(d) orelse d; -} - -// ------------------------------------------------------------ diagnostics - -/// `SPC d` and the list `]d`/`[d` step. ZLS's `getAstCheckDiagnostics` prefers -/// spawning `zig ast-check`; its OTHER branch runs `std.zig.AstGen` in this -/// process, which is the branch a subprocess-free backend wants, so that is -/// what is inlined here (it is ten lines and needs a `*Server` only for the -/// config it reads). -/// -/// A clean file emits ONE row saying so. Silence already means "no backend" in -/// this seam — `lspResponse` opens nothing for zero rows — so a `SPC d` that -/// checked and found nothing has to be able to say the difference. -fn diagnostics( - gpa: std.mem.Allocator, - arena: std.mem.Allocator, - path: []const u8, - tree: *const Ast, - out: *std.Io.Writer, -) !void { - const n = try treeDiagnostics(gpa, arena, path, tree, out); - if (n == 0) try lsp.row(out, path, 0, 0, "no diagnostics"); -} - -/// `zig ast-check`, in this process. ZLS spawns the compiler for this when it -/// has one; its fallback branch is `std.zig.AstGen` directly, and that fallback -/// is this backend's only branch. Caller owns the bundle. -fn astCheck(gpa: std.mem.Allocator, path: []const u8, tree: *const Ast) !std.zig.ErrorBundle { - if (tree.errors.len != 0) return .empty; - var zir = std.zig.AstGen.generate(gpa, tree.*) catch return .empty; - defer zir.deinit(gpa); - if (!zir.hasCompileErrors()) return .empty; - var wip: std.zig.ErrorBundle.Wip = undefined; - try wip.init(gpa); - defer wip.deinit(); - wip.addZirErrorMessages(zir, tree.*, tree.source, path) catch return .empty; - return wip.toOwnedBundle("") catch .empty; -} - -/// Parse errors first (AstGen cannot run on a tree that did not parse), then -/// the AstGen pass. Returns how many rows were emitted. -fn treeDiagnostics( - gpa: std.mem.Allocator, - arena: std.mem.Allocator, - path: []const u8, - tree: *const Ast, - out: *std.Io.Writer, -) !usize { - var n: usize = 0; - if (tree.errors.len != 0) { - const lines: Lines = try .build(arena, tree.source); - for (tree.errors) |e| { - if (n >= max_rows) return n; - var count_buf: [256]u8 = undefined; - var counting: std.Io.Writer.Discarding = .init(&count_buf); - tree.renderError(e, &counting.writer) catch continue; - const size = std.math.cast(usize, counting.fullCount()) orelse continue; - const rendered = try arena.alloc(u8, size); - var w: std.Io.Writer = .fixed(rendered); - tree.renderError(e, &w) catch continue; - const at = tree.tokenStart(e.token); - const lc = lsp.lineCol(tree.source, at); - n += 1; - try lsp.row(out, path, lc.line, lc.col, try std.fmt.allocPrint(arena, "error: {s} {s}", .{ - w.buffered(), std.mem.trim(u8, lines.line(lc.line), " \t"), - })); - } - return n; - } - - var bundle = try astCheck(gpa, path, tree); - defer bundle.deinit(gpa); - if (bundle.errorMessageCount() == 0) return n; - for (bundle.getMessages()) |m| { - if (n >= max_rows) return n; - const em = bundle.getErrorMessage(m); - if (em.src_loc == .none) continue; - const sl = bundle.getSourceLocation(em.src_loc); - n += 1; - try lsp.row(out, path, sl.line, sl.column, try std.fmt.allocPrint(arena, "error: {s}", .{ - bundle.nullTerminatedString(em.msg), - })); - } - return n; -} - -/// `SPC D`: the same check over every `.zig` under the pane's directory. No -/// analyser and no store — AstGen is a per-file pass — so this is bounded by -/// how fast Zig can parse the tree, which for pardes's own `src/` is tens of -/// milliseconds. -fn workspaceDiagnostics( - gpa: std.mem.Allocator, - arena: std.mem.Allocator, - io: std.Io, - req: lsp.Req, - out: *std.Io.Writer, -) !void { - const files = try collectZigFiles(arena, io, req.root); - var total: usize = 0; - for (files) |path| { - const src = readFileZ(arena, io, path) catch continue; - var tree: Ast = Ast.parse(arena, src, .zig) catch continue; - defer tree.deinit(arena); - total += try treeDiagnostics(gpa, arena, lsp.rel(req.root, path), &tree, out); - if (total >= max_rows) return; - } - if (total == 0) try lsp.row(out, lsp.rel(req.root, req.path), 0, 0, try std.fmt.allocPrint(arena, "no diagnostics in {d} file(s)", .{files.len})); -} - -// ----------------------------------------------------------- code actions - -/// `SPC a`. `code_actions.Builder` is one of the Server-free ones — it wants -/// an arena, an analyser, a handle and an ErrorBundle — so the only missing -/// piece is the bundle, which `astCheck` above produces without a compiler. -/// -/// It lists what could be done, and does none of it: the seam hands back rows, -/// not edits, so there is no channel through which a backend could apply a -/// fix. `+Lsp` is prose, so these are lines rather than locations. -fn codeActions( - gpa: std.mem.Allocator, - arena: std.mem.Allocator, - analyser: *Analyser, - handle: *DocumentStore.Handle, - off: usize, - out: *std.Io.Writer, -) !void { - const tree = &handle.tree; - if (tree.errors.len != 0) { - try out.print("no code actions: file does not parse\n", .{}); - return; - } - var bundle = try astCheck(gpa, "", tree); - defer bundle.deinit(gpa); - - // The external builder owns growable collections internally. Confine all - // of them and their payloads to one preallocated query-local region. - const action_storage = try arena.alloc(u8, max_code_action_bytes); - var action_fba: std.heap.FixedBufferAllocator = .init(action_storage); - var builder: zls.code_actions.Builder = .{ - .arena = action_fba.allocator(), - .analyser = analyser, - .handle = handle, - .offset_encoding = enc, - .only_kinds = null, - }; - builder.generateCodeAction(bundle) catch {}; - const at = offsets.locToRange(tree.source, .{ .start = off, .end = off }, enc); - builder.generateCodeActionsInRange(at) catch {}; - - for (builder.actions.items[0..@min(builder.actions.items.len, max_rows)]) |a| { - try out.print("{s}\n", .{a.title}); - } - if (builder.actions.items.len == 0) try out.print("no code actions\n", .{}); -} - -// ---------------------------------------------------------------- format - -/// `=`. The response is `@put` edit records (see lsp.put): one span covering -/// everything `zig fmt` would change, which the core substitutes as a single -/// undo step — so `=` FORMATS, exactly like helix. The two answers that are -/// not edits stay prose rows in `+Lsp`: a file that does not parse cannot be -/// formatted, and a file already formatted has nothing to apply. -fn formatQuery(arena: std.mem.Allocator, req: lsp.Req, out: *std.Io.Writer) !void { - const path = lsp.rel(req.root, req.path); - var tree: Ast = try .parse(arena, req.source, .zig); - defer tree.deinit(arena); - if (tree.errors.len != 0) { - try lsp.row(out, path, 0, 0, "cannot format: file does not parse"); - return; - } - var count_buf: [4096]u8 = undefined; - var counting: std.Io.Writer.Discarding = .init(&count_buf); - try tree.render(arena, &counting.writer, .{}); - const size = std.math.cast(usize, counting.fullCount()) orelse return; - const render_buf = try arena.alloc(u8, size); - var w: std.Io.Writer = .fixed(render_buf); - try tree.render(arena, &w, .{}); - const formatted = w.buffered(); - if (std.mem.eql(u8, formatted, req.source)) { - try lsp.row(out, path, 0, 0, "already formatted"); - return; - } - // one record, spanning only what changed: the common prefix and suffix - // stay untouched, which is also what keeps the cursor mapping tight - var lo: usize = 0; - const min_len = @min(req.source.len, formatted.len); - while (lo < min_len and req.source[lo] == formatted[lo]) lo += 1; - var src_hi = req.source.len; - var fmt_hi = formatted.len; - while (src_hi > lo and fmt_hi > lo and req.source[src_hi - 1] == formatted[fmt_hi - 1]) { - src_hi -= 1; - fmt_hi -= 1; - } - try lsp.put(out, lo, src_hi, formatted[lo..fmt_hi]); -} - -// ------------------------------------------------------------------ files - -/// Every `.zig` under `root`, skipping the directories a source walk has no -/// business in. Capped, because this runs on a keypress. -fn collectZigFiles(arena: std.mem.Allocator, io: std.Io, root: []const u8) ![]const []const u8 { - const files = try arena.alloc([]const u8, max_files); - var len: usize = 0; - if (root.len == 0) return files[0..0]; - var dir = std.Io.Dir.cwd().openDir(io, root, .{ .iterate = true }) catch return files[0..0]; - defer dir.close(io); - var w = dir.walkSelectively(arena) catch return files[0..0]; - defer w.deinit(); - while (len < files.len) { - const e = (w.next(io) catch break) orelse break; - switch (e.kind) { - .directory => { - if (e.basename.len != 0 and e.basename[0] == '.') continue; - if (std.mem.eql(u8, e.basename, "zig-out")) continue; - if (std.mem.eql(u8, e.basename, "zig-cache")) continue; - w.enter(io, e) catch {}; - }, - .file => { - if (!std.mem.endsWith(u8, e.basename, ".zig")) continue; - files[len] = std.fs.path.join(arena, &.{ root, e.path }) catch continue; - len += 1; - }, - else => {}, - } - } - return files[0..len]; -} - -fn readFileZ(arena: std.mem.Allocator, io: std.Io, path: []const u8) ![:0]u8 { - return std.Io.Dir.cwd().readFileAllocOptions(io, path, arena, .limited(4 * 1024 * 1024), .of(u8), 0); -} - -test "LSP ZLS format propagates output failure and preserves successful encoding" { - const gpa = std.testing.allocator; - const req: lsp.Req = .{ .kind = .format, .path = "/file.zig", .source = "const value=1;\n", .offset = 6 }; - const expected = "@put 11 12 %20=%20\n"; - var buffer: [128]u8 = undefined; - for ([_]usize{ 0, expected.len - 1, expected.len }) |capacity| { - var arena: std.heap.ArenaAllocator = .init(gpa); - defer arena.deinit(); - var out: std.Io.Writer = .fixed(buffer[0..capacity]); - const result = query(gpa, arena.allocator(), req, &out); - if (capacity < expected.len) { - try std.testing.expectError(error.WriteFailed, result); - } else { - try result; - try std.testing.expectEqualStrings(expected, out.buffered()); - } - } -} - -test "LSP ZLS rename refuses a partial edit set beyond its row budget" { - const gpa = std.testing.allocator; - for ([_]usize{ max_rows - 1, max_rows }) |references_count| { - var arena: std.heap.ArenaAllocator = .init(gpa); - defer arena.deinit(); - var source: std.Io.Writer.Allocating = .init(gpa); - defer source.deinit(); - try source.writer.writeAll("const value: u32 = 1;\nfn use() void {\n"); - for (0..references_count) |_| try source.writer.writeAll(" _ = value;\n"); - try source.writer.writeAll("}\n"); - const text = try gpa.dupeZ(u8, source.written()); - defer gpa.free(text); - var out: std.Io.Writer.Allocating = .init(gpa); - defer out.deinit(); - const result = query(gpa, arena.allocator(), .{ - .kind = .rename, - .path = "/rename.zig", - .source = text, - .offset = 6, - .arg = "renamed", - }, &out.writer); - if (references_count < max_rows) { - try result; - try std.testing.expectEqual(max_rows, std.mem.count(u8, out.written(), "@edit ")); - } else { - try std.testing.expectError(error.TooManyEdits, result); - try std.testing.expectEqual(@as(usize, 0), out.written().len); - } - } -} - -test "LSP source snippets retain native definition and reference indentation" { - const source = "const Outer = struct {\n" ++ - "\t const value: u32 = 1;\n" ++ - "\t fn use() void {\n" ++ - "\t\t_ = value;\n" ++ - "\t }\n" ++ - "};\n"; - const gpa = std.testing.allocator; - for ([_]lsp.Kind{ .definition, .declaration, .references }) |kind| { - var arena: std.heap.ArenaAllocator = .init(gpa); - defer arena.deinit(); - var out: std.Io.Writer.Allocating = .init(gpa); - defer out.deinit(); - try query(gpa, arena.allocator(), .{ - .kind = kind, - .path = "/source-snippet.zig", - .root = "/", - .source = source, - .offset = @intCast(std.mem.lastIndexOf(u8, source, "value").?), - }, &out.writer); - const definition = "source-snippet.zig:2:10-14 \t const value: u32 = 1;\n"; - try std.testing.expectEqualStrings(if (kind == .references) - definition ++ "source-snippet.zig:4:7-11 \t\t_ = value;\n" - else - definition, out.written()); - } -} diff --git a/src/main.zig b/src/main.zig index 17d0fb5f..0e2ba954 100644 --- a/src/main.zig +++ b/src/main.zig @@ -535,7 +535,6 @@ test { _ = @import("host_io.zig").Lsp; _ = @import("lsp/lsp_client.zig"); _ = @import("lsp/lsp.zig"); - if (comptime @import("pardes_config").zls_backend) _ = @import("lsp/lsp_zls.zig"); if (comptime pardes.platform == .tty) { _ = @import("tty/tty.zig"); _ = @import("tty/panel_compositor.zig"); diff --git a/test/fs.py b/test/fs.py index 06643385..6f1165e5 100644 --- a/test/fs.py +++ b/test/fs.py @@ -1327,7 +1327,7 @@ def test(binary, quic=False): time.sleep(.005) assert len(matches) == 1, matches result = client.read(f'/pane/{matches[0]}/body') - assert result.startswith(b'backend: zls-inproc+lsp-client\n'), result + assert result.startswith(b'backend: lsp-client\n'), result assert b'protocol servers (lsp-client):' in result, result assert client.read('/pane/1/body') == b'initial\n' assert '+Lsp' in ''.join(cell[0] for cell in client.screen()['cells']) diff --git a/test/lspbench.zig b/test/lspbench.zig index 36969680..e094ed69 100644 --- a/test/lspbench.zig +++ b/test/lspbench.zig @@ -40,7 +40,6 @@ const anchors = [_]Anchor{ .{ .file = "src/lsp/lsp.zig", .needle = "pub const Kind", .at = 11, .kind = .workspace_symbols, .expect = "" }, .{ .file = "test/lspfixture/broken.zig", .needle = "unused_local", .at = 0, .kind = .workspace_diagnostics, .expect = "broken.zig" }, .{ .file = "src/lsp/lsp.zig", .needle = "std.mem.count(u8", .at = 4, .kind = .completion, .expect = "std.zig" }, - .{ .file = "src/lsp/lsp_zls.zig", .needle = ".declaration => try rowForToken", .at = 1, .kind = .completion, .expect = "type_definition" }, .{ .file = "src/normal.zig", .needle = ".definition => .definition,", .at = 1, .kind = .completion, .expect = "" }, // The repeated name proves the result includes the declaration, not just the cursor line. .{ .file = "test/lspfixture/dotcomplete.zig", .needle = "return switch (s) {\n .", .at = 29, .kind = .completion, .expect = "verdigris verdigris," }, diff --git a/test/snapshot.zig b/test/snapshot.zig index 0514d8d8..a176da7a 100644 --- a/test/snapshot.zig +++ b/test/snapshot.zig @@ -580,7 +580,7 @@ fn runScript(arena: std.mem.Allocator, exe_z: [:0]const u8, script_path: []const _ = setenv("LC_ALL", "C", 1); // a wall clock cannot live in a golden; everything that would print one // prints fixed characters instead when this is set — the lsp introspection - // views' durations (lsp_zls.zig hideTime) and the transient message row's + // views' durations and the transient message row's // time of day (message.zig stamp) _ = setenv("PARDES_NOTIME", "1", 1); // A virtual core clock: animation moves a frame per timed-out wait, diff --git a/test/snapshots/lsp.golden b/test/snapshots/lsp.golden index be0090fb..88291324 100644 --- a/test/snapshots/lsp.golden +++ b/test/snapshots/lsp.golden @@ -14,6 +14,7 @@ | 10 == snap cursor grid=120x41 cursor=17,10 == snap definition grid=120x41 cursor=15,5 +|3: 1 const std = @import("std"); --:--:-- lsp zls ready — /tmp/pardes-snap/lsp/cwd == snap hover grid=120x41 cursor=15,5 |3: 1 const std = @import("std"); Hover |12: /tmp/pardes-snap/lsp/cwd/+Hover Save Tty Collapse Del @@ -26,9 +27,9 @@ |16: 1 a.zig:1:7-9 |17: 2 std |18: 3 a.zig:3:4-9 -|19: 4 helper fn helper(x: u32) u32 +|19: 4 helper |20: 5 a.zig:7:8-11 -|21: 6 main fn main() void +|21: 6 main |22: 7 == snap step grid=120x41 cursor=15,3 |3: 1 const std = @import("std"); diff --git a/test/snapshots/lsp.snap b/test/snapshots/lsp.snap index b40484ee..97fcf7ed 100644 --- a/test/snapshots/lsp.snap +++ b/test/snapshots/lsp.snap @@ -1,11 +1,11 @@ # Language intelligence end to end: the helix keymap, the async round trip and # the two dispositions of an answer. # -# The backend behind the seam here is ZLS linked in as a LIBRARY -# (src/lsp_zls.zig) — no server process, no JSON-RPC — so `gd` is a function -# call on a worker thread whose result comes back as an ordinary event, the -# same shape a pty read already had. Nothing in this script knows that: it -# presses keys and reads the grid, which is the point of the seam. +# The backend behind the seam here is zls, run as a child process by the +# protocol client (it must be on PATH): `gd` is a request on a worker thread +# whose result comes back as an ordinary event, the same shape a pty read +# already had. Nothing in this script knows that: it presses keys and reads +# the grid, which is the point of the seam. # # a.zig is deliberately self-contained — a definition, a call site, and not one # symbol from std — so these goldens do not encode this machine's stdlib diff --git a/test/snapshots/lspcomplete.golden b/test/snapshots/lspcomplete.golden index 0b29034f..77f844ac 100644 --- a/test/snapshots/lspcomplete.golden +++ b/test/snapshots/lspcomplete.golden @@ -19,16 +19,18 @@ |2: ^* /tmp/pardes-snap/lspcomplete/cwd/a.zig Save Tty Collapse Del TreeContext |12: 10 } == snap commentindent grid=120x41 cursor=19,14 +|3: 1 const Shade = enum { --:--:-- lsp zls ready — /tmp/pardes-snap/lspcomplete/cwd |14: 12 // note. see below == snap athedot grid=120x41 cursor=16,10 +|3: 1 const Shade = enum { |10: 8 . == snap completion grid=120x41 cursor=16,10 |15: /tmp/pardes-snap/lspcomplete/cwd/+Search Save Tty Collapse Del -|16: 1 a.zig:2:5-13 verdigris verdigris, -|17: 2 a.zig:3:5-12 cinnabar cinnabar, +|16: 1 a.zig:8:10 verdigris +|17: 2 a.zig:8:10 cinnabar |18: 3 == snap refill grid=120x41 cursor=16,10 -== snap step grid=120x41 cursor=19,4 +== snap step grid=120x41 cursor=16,10 |2: * /tmp/pardes-snap/lspcomplete/cwd/a.zig Save Tty Collapse Del TreeContext == snap txtindent grid=120x41 cursor=15,3 |Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit @@ -40,7 +42,7 @@ |Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit | New Tty Find Grep Joincol Delcol |^* /tmp/pardes-snap/lspcomplete/cwd/c.zig Save Tty Collapse Del TreeContext -| 1 const Shade = enum { +| 1 const Shade = enum { --:--:-- lsp zls ready — /tmp/pardes-snap/lspcomplete/cwd | 2 verdigris, | 3 cinnabar, | 4 }; @@ -49,14 +51,14 @@ | 7 const z: Shade = . | 8 } | /tmp/pardes-snap/lspcomplete/cwd/+Search Save Tty Collapse Del -| 1 c.zig:2:5-13 verdigris verdigris, -| 2 c.zig:3:5-12 cinnabar cinnabar, +| 1 c.zig:7:23 verdigris Shade +| 2 c.zig:7:23 cinnabar Shade | 3 == snap nobrace grid=100x19 cursor=16,10 |Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit | New Tty Find Grep Joincol Delcol |^* /tmp/pardes-snap/lspcomplete/cwd/d.zig Save Tty Collapse Del TreeContext -| 1 const Shade = enum { +| 1 const Shade = enum { --:--:-- lsp zls ready — /tmp/pardes-snap/lspcomplete/cwd | 2 verdigris, | 3 cinnabar, | 4 }; @@ -64,6 +66,6 @@ | 6 pub fn nobrace(s: Shade) void { | 7 switch (s) { | /tmp/pardes-snap/lspcomplete/cwd/+Search Save Tty Collapse Del -| 1 d.zig:2:5-13 verdigris verdigris, -| 2 d.zig:3:5-12 cinnabar cinnabar, +| 1 d.zig:8:10 verdigris +| 2 d.zig:8:10 cinnabar | 3 diff --git a/test/snapshots/lspcomplete.snap b/test/snapshots/lspcomplete.snap index 53ce7ef9..d9e165a1 100644 --- a/test/snapshots/lspcomplete.snap +++ b/test/snapshots/lspcomplete.snap @@ -1,6 +1,7 @@ -# Tab after a dot in insert mode: "what could go here, and where is each of -# those defined". The answer is a `+Search` buffer of DEFINITION rows, the same -# rows `gr` fills it with — nothing is inserted and nothing pops up. +# Tab after a dot in insert mode: "what could go here". The answer is a +# `+Search` buffer of zls's candidates, one row each at the cursor (a +# completion item names no declaration) — nothing is inserted and nothing pops +# up. # # a.zig is std-free for the reason lsp.snap's is: these goldens must not encode # this machine's stdlib version or its install path. Its enum members are @@ -58,12 +59,10 @@ text . stable 400 5000 snap athedot key tab -# The row that proves it: `a.zig:2:` is `verdigris`'s own declaration line. -# The cursor is on line 8; nothing about line 2 is reachable from the text -# under it, so this row can only have come from resolving the switch's -# condition to `Shade` and asking `Shade` what it declares. Line 8 still reads -# `.` and nothing else — a completion INSERTS NOTHING. -wait 15000 a.zig:2: +# The rows that prove it: `verdigris` and `cinnabar` can only have come from +# resolving the switch's condition to `Shade` and asking what it declares. +# Line 8 still reads `.` and nothing else — a completion INSERTS NOTHING. +wait 15000 +Search stable 700 15000 snap completion # Two more Tabs. Every one of them answers, and every answer REFILLS the one @@ -128,7 +127,7 @@ key end text . stable 400 5000 key tab -wait 15000 c.zig:2: +wait 15000 +Search stable 700 15000 snap nosemi # ...and a construct still hanging OPEN. The switch has no closing brace at @@ -149,6 +148,6 @@ key end text . stable 400 5000 key tab -wait 15000 d.zig:2: +wait 15000 +Search stable 700 15000 snap nobrace diff --git a/test/snapshots/lspcompletemoved.golden b/test/snapshots/lspcompletemoved.golden index a033ed56..c6db1812 100644 --- a/test/snapshots/lspcompletemoved.golden +++ b/test/snapshots/lspcompletemoved.golden @@ -2,7 +2,7 @@ |Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit | New Tty Find Grep Joincol Delcol |^* /tmp/pardes-snap/lspcompletemoved/cwd/a.zig Save Tty Collapse Del TreeContext -| 1 const Shade = enum { +| 1 const Shade = enum { --:--:-- lsp zls ready — /tmp/pardes-snap/lspcompletemoved/cwd | 2 verdigris, | 3 cinnabar, | 4 }; diff --git a/test/snapshots/lspdebug.golden b/test/snapshots/lspdebug.golden index cf2eb097..1db8b0b9 100644 --- a/test/snapshots/lspdebug.golden +++ b/test/snapshots/lspdebug.golden @@ -14,6 +14,8 @@ | 10 } | 11 == snap ctrlclick grid=120x45 cursor=15,5 +|3: 1 const std = @import("std"); --:--:-- lsp zls ready — /tmp/pardes-snap/lspdebug/cwd == snap plainclick grid=120x45 cursor=21,10 +|3: 1 const std = @import("std"); == snap why-closed grid=120x45 cursor=7,5 == snap report-closed grid=120x45 cursor=7,5 diff --git a/test/snapshots/lspdebug.snap b/test/snapshots/lspdebug.snap index ab330a76..3aca07cc 100644 --- a/test/snapshots/lspdebug.snap +++ b/test/snapshots/lspdebug.snap @@ -21,10 +21,8 @@ snap plainclick text 3gg1g| stable 400 10000 key space l w -wait 10000 parsed 122 bytes, 0 syntax error(s) -wait 10000 position context: .empty -wait 10000 STOP: nothing to resolve -wait 10000 0 row(s) +wait 10000 lsp explain — the definition query +wait 10000 row(s) key space w j key space d stable 700 15000 @@ -32,20 +30,15 @@ snap why-closed # Check the report's answers, not installed compiler paths or dependency counts. key space l i -wait 10000 backend: zls-inproc+lsp-client -wait 10000 compiled in -wait 10000 [OK] -wait 10000 offsets: utf-8 +wait 10000 backend: lsp-client +wait 10000 protocol servers (lsp-client): +wait 10000 zls key space w j key / -text last queries +text client queries key enter -wait 10000 last queries -wait 10000 definition z.zig -# The results pane the search opened takes the bottom half, which leaves the -# report one row short of its second query: step the cursor past it. -key j j j -wait 10000 explain z.zig +wait 10000 client queries +wait 10000 definition # the report sits between the source and the results, so Del asks where its # rows go: k, back to the source above key space d diff --git a/test/snapshots/lsprelpath.golden b/test/snapshots/lsprelpath.golden index 201f6dd4..80064f00 100644 --- a/test/snapshots/lsprelpath.golden +++ b/test/snapshots/lsprelpath.golden @@ -1,48 +1,49 @@ -== snap absrow grid=100x35 cursor=16,7 +== snap absrow grid=100x35 cursor=21,16 |Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit | New Tty Find Grep Joincol Delcol -|^* /tmp/pardes-snap/lsprelpath/cwd/sub/parent.zig Save Tty Collapse Del TreeContext -| 1 const shade = @import("../shade.zig"); +| /tmp/pardes-snap/lsprelpath/cwd/sub/parent.zig Save Tty Collapse Del TreeContext +| 1 const shade = @import("../shad --:--:-- lsp zls ready — /tmp/pardes-snap/lsprelpath/cwd/sub | 2 | 3 pub fn pick(s: shade.Shade) u8 { | 4 return switch (s) { -| 5 . +| 5 | 6 }; | 7 } -| /tmp/pardes-snap/lsprelpath/cwd/sub/+Search Save Tty Collapse Del -| 1 /tmp/pardes-snap/lsprelpath/cwd/shade.zig:2:5-13 verdigris verdigris, -| 2 /tmp/pardes-snap/lsprelpath/cwd/shade.zig:3:5-12 cinnabar cinnabar, -| 3 -== snap abslook grid=100x35 cursor=19,15 -|2: * /tmp/pardes-snap/lsprelpath/cwd/sub/parent.zig Save Tty Collapse Del TreeContext -|13: /tmp/pardes-snap/lsprelpath/cwd/shade.zig Save Tty Collapse Del TreeContext -|14: 1 pub const Shade = enum { -|15: 2 verdigris, -|16: 3 cinnabar, -|17: 4 }; -|18: 5 +| /tmp/pardes-snap/lsprelpath/cwd/sub/+Search Save Tty Collapse Del LocationsConfig +| 1 /tmp/pardes-snap/lsprelpath/cwd/shade.zig:1:11-15 +| 2 pub const Shade = enum { +| 3 parent.zig:3:22-26 +| 4 pub fn pick(s: shade.Shade) u8 { +| /tmp/pardes-snap/lsprelpath/cwd/shade.zig Save Tty Collapse Del TreeContext +| 1 pub const Shade = enum { +| 2 verdigris, +| 3 cinnabar, +| 4 }; +| 5 +== snap abslook grid=100x35 cursor=32,5 +|3: 1 const shade = @import("../shade.zig"); == style abslook grid=100x35 |0: 0-99 #b2c3b8,#1d2824, |1: 0-1 d,#887455, 2-2 d,#314738, 3-99 #becfc4,#314738, -|2: 0-0 d,#496656, 1-1 #000000,#f9cb70,b 2-2 #000000,#1d2824, 3-38 #b2c3b8,#1d2824, 39-49 #d3b0d9,#1d2824, 50-99 #b2c3b8,#1d2824, +|2: 0-1 d,#add38a, 2-2 d,#314738, 3-38 #becfc4,#314738, 39-49 #dfbce5,#314738, 50-99 #becfc4,#314738, |3: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-20 #e5eee5,#0d1410, 21-27 #c9a7ed,#0d1410, 28-28 #e5eee5,#0d1410, 29-42 #b8d88a,#0d1410, 43-99 #e5eee5,#0d1410, |4: 0-0 d,#608269, 1-4 d,#0d1410, 5-99 #59675c,#0d1410, -|5: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-10 #e5eee5,#0d1410, 11-13 #c9a7ed,#0d1410, 14-99 #e5eee5,#0d1410, +|5: 0-0 d,#608269, 1-1 d,#0d1410, 2-4 d,#0d1410,b 5-6 #616f64,#0d1410,b 7-10 #e5eee5,#0d1410, 11-13 #c9a7ed,#0d1410, 14-27 #e5eee5,#0d1410, 28-32 #f5f7ee,#3c614a, 33-99 #e5eee5,#0d1410, |6: 0-0 d,#608269, 1-4 d,#0d1410, 5-10 #59675c,#0d1410, 11-24 #c9a7ed,#0d1410, 25-99 #e5eee5,#0d1410, -|7: 0-0 d,#608269, 1-4 d,#0d1410, 5-14 #59675c,#0d1410, 15-99 #e5eee5,#0d1410, +|7: 0-0 d,#608269, 1-4 d,#0d1410, 5-99 #59675c,#0d1410, |8: 0-0 d,#608269, 1-4 d,#0d1410, 5-10 #59675c,#0d1410, 11-99 #e5eee5,#0d1410, |9: 0-0 d,#152019, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-99 #e5eee5,#0d1410, |10: 0-1 d,#496656, 2-2 d,#1d2824, 3-38 #b2c3b8,#1d2824, 39-46 #d3b0d9,#1d2824, 47-99 #b2c3b8,#1d2824, -|11: 0-0 d,#608269, 1-4 d,#0d1410, 5-55 #59675c,#0d1410, 56-99 #e5eee5,#0d1410, -|12: 0-0 d,#152019, 1-4 d,#0d1410, 5-55 #59675c,#0d1410, 56-99 #e5eee5,#0d1410, -|13: 0-1 d,#add38a, 2-2 d,#314738, 3-34 #becfc4,#314738, 35-44 #dfbce5,#314738, 45-99 #becfc4,#314738, -|14: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-24 #e5eee5,#0d1410, 25-29 #c9a7ed,#0d1410, 30-99 #e5eee5,#0d1410, -|15: 0-0 d,#608269, 1-1 d,#0d1410, 2-4 d,#0d1410,b 5-6 #616f64,#0d1410,b 7-10 #616f64,#0d1410, 11-19 #f5f7ee,#3c614a, 20-99 #e5eee5,#0d1410, -|16: 0-0 d,#608269, 1-4 d,#0d1410, 5-10 #59675c,#0d1410, 11-99 #e5eee5,#0d1410, -|17: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-99 #e5eee5,#0d1410, -|18: 0-0 d,#608269, 1-4 d,#0d1410, 5-99 #59675c,#0d1410, -|19: 0-0 d,#608269, 1-99 d,#0d1410, -|20: 0-0 d,#608269, 1-99 d,#0d1410, +|11: 0-0 d,#608269, 1-4 d,#0d1410, 5-99 #59675c,#0d1410, +|12: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-16 #e5eee5,#0d1410, 17-21 #f7e4a5,#5e4923, 22-22 #f7e4a5,#0d1410, 23-24 #e5eee5,#0d1410, 25-29 #c9a7ed,#0d1410, 30-99 #e5eee5,#0d1410, +|13: 0-0 d,#608269, 1-4 d,#0d1410, 5-99 #59675c,#0d1410, +|14: 0-0 d,#152019, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-10 #e5eee5,#0d1410, 11-13 #c9a7ed,#0d1410, 14-27 #e5eee5,#0d1410, 28-32 #f7e4a5,#5e4923, 33-99 #e5eee5,#0d1410, +|15: 0-1 d,#496656, 2-2 d,#1d2824, 3-34 #b2c3b8,#1d2824, 35-44 #d3b0d9,#1d2824, 45-99 #b2c3b8,#1d2824, +|16: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-16 #e5eee5,#0d1410, 17-21 #f5f7ee,#3c614a, 22-22 #f5f7ee,#0d1410, 23-24 #e5eee5,#0d1410, 25-29 #c9a7ed,#0d1410, 30-99 #e5eee5,#0d1410, +|17: 0-0 d,#608269, 1-4 d,#0d1410, 5-10 #59675c,#0d1410, 11-99 #e5eee5,#0d1410, +|18: 0-0 d,#608269, 1-4 d,#0d1410, 5-10 #59675c,#0d1410, 11-99 #e5eee5,#0d1410, +|19: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-99 #e5eee5,#0d1410, +|20: 0-0 d,#608269, 1-4 d,#0d1410, 5-99 #59675c,#0d1410, |21: 0-0 d,#608269, 1-99 d,#0d1410, |22: 0-0 d,#608269, 1-99 d,#0d1410, |23: 0-0 d,#608269, 1-99 d,#0d1410, @@ -57,51 +58,52 @@ |32: 0-0 d,#608269, 1-99 d,#0d1410, |33: 0-0 d,#608269, 1-99 d,#0d1410, |34: 0-0 d,#608269, 1-99 d,#0d1410, -== snap subrow grid=100x35 cursor=16,7 +== snap subrow grid=100x35 cursor=20,16 |Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit | New Tty Find Grep Joincol Delcol -|^* /tmp/pardes-snap/lsprelpath/cwd/sub/subdir.zig Save Tty Collapse Del TreeContext -| 1 const tint = @import("inner/tint.zig"); +| /tmp/pardes-snap/lsprelpath/cwd/sub/subdir.zig Save Tty Collapse Del TreeContext +| 1 const tint = @import("inner/ti --:--:-- lsp zls ready — /tmp/pardes-snap/lsprelpath/cwd/sub | 2 | 3 pub fn hue(t: tint.Tint) u8 { | 4 return switch (t) { -| 5 . +| 5 | 6 }; | 7 } -| /tmp/pardes-snap/lsprelpath/cwd/sub/+Search Save Tty Collapse Del -| 1 inner/tint.zig:2:5-9 ochre ochre, -| 2 inner/tint.zig:3:5-10 indigo indigo, -| 3 -== snap sublook grid=100x35 cursor=15,15 -|2: * /tmp/pardes-snap/lsprelpath/cwd/sub/subdir.zig Save Tty Collapse Del TreeContext -|13: /tmp/pardes-snap/lsprelpath/cwd/sub/inner/tint.zig Save Tty Collapse Del TreeContext -|14: 1 pub const Tint = enum { -|15: 2 ochre, -|16: 3 indigo, -|17: 4 }; -|18: 5 +| /tmp/pardes-snap/lsprelpath/cwd/sub/+Search Save Tty Collapse Del LocationsConfig +| 1 inner/tint.zig:1:11-14 +| 2 pub const Tint = enum { +| 3 subdir.zig:3:20-23 +| 4 pub fn hue(t: tint.Tint) u8 { +| /tmp/pardes-snap/lsprelpath/cwd/sub/inner/tint.zig Save Tty Collapse Del TreeContext +| 1 pub const Tint = enum { +| 2 ochre, +| 3 indigo, +| 4 }; +| 5 +== snap sublook grid=100x35 cursor=29,5 +|3: 1 const tint = @import("inner/tint.zig"); == style sublook grid=100x35 |0: 0-99 #b2c3b8,#1d2824, |1: 0-1 d,#887455, 2-2 d,#314738, 3-99 #becfc4,#314738, -|2: 0-0 d,#496656, 1-1 #000000,#f9cb70,b 2-2 #000000,#1d2824, 3-38 #b2c3b8,#1d2824, 39-49 #d3b0d9,#1d2824, 50-99 #b2c3b8,#1d2824, +|2: 0-1 d,#add38a, 2-2 d,#314738, 3-38 #becfc4,#314738, 39-49 #dfbce5,#314738, 50-99 #becfc4,#314738, |3: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-19 #e5eee5,#0d1410, 20-26 #c9a7ed,#0d1410, 27-27 #e5eee5,#0d1410, 28-43 #b8d88a,#0d1410, 44-99 #e5eee5,#0d1410, |4: 0-0 d,#608269, 1-4 d,#0d1410, 5-99 #59675c,#0d1410, -|5: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-10 #e5eee5,#0d1410, 11-13 #c9a7ed,#0d1410, 14-99 #e5eee5,#0d1410, +|5: 0-0 d,#608269, 1-1 d,#0d1410, 2-4 d,#0d1410,b 5-6 #616f64,#0d1410,b 7-10 #e5eee5,#0d1410, 11-13 #c9a7ed,#0d1410, 14-25 #e5eee5,#0d1410, 26-29 #f5f7ee,#3c614a, 30-99 #e5eee5,#0d1410, |6: 0-0 d,#608269, 1-4 d,#0d1410, 5-10 #59675c,#0d1410, 11-24 #c9a7ed,#0d1410, 25-99 #e5eee5,#0d1410, -|7: 0-0 d,#608269, 1-4 d,#0d1410, 5-14 #59675c,#0d1410, 15-99 #e5eee5,#0d1410, +|7: 0-0 d,#608269, 1-4 d,#0d1410, 5-99 #59675c,#0d1410, |8: 0-0 d,#608269, 1-4 d,#0d1410, 5-10 #59675c,#0d1410, 11-99 #e5eee5,#0d1410, |9: 0-0 d,#152019, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-99 #e5eee5,#0d1410, |10: 0-1 d,#496656, 2-2 d,#1d2824, 3-38 #b2c3b8,#1d2824, 39-46 #d3b0d9,#1d2824, 47-99 #b2c3b8,#1d2824, -|11: 0-0 d,#608269, 1-4 d,#0d1410, 5-27 #59675c,#0d1410, 28-99 #e5eee5,#0d1410, -|12: 0-0 d,#152019, 1-4 d,#0d1410, 5-28 #59675c,#0d1410, 29-99 #e5eee5,#0d1410, -|13: 0-1 d,#add38a, 2-2 d,#314738, 3-44 #becfc4,#314738, 45-53 #dfbce5,#314738, 54-99 #becfc4,#314738, -|14: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-23 #e5eee5,#0d1410, 24-28 #c9a7ed,#0d1410, 29-99 #e5eee5,#0d1410, -|15: 0-0 d,#608269, 1-1 d,#0d1410, 2-4 d,#0d1410,b 5-6 #616f64,#0d1410,b 7-10 #616f64,#0d1410, 11-15 #f5f7ee,#3c614a, 16-99 #e5eee5,#0d1410, -|16: 0-0 d,#608269, 1-4 d,#0d1410, 5-10 #59675c,#0d1410, 11-99 #e5eee5,#0d1410, -|17: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-99 #e5eee5,#0d1410, -|18: 0-0 d,#608269, 1-4 d,#0d1410, 5-99 #59675c,#0d1410, -|19: 0-0 d,#608269, 1-99 d,#0d1410, -|20: 0-0 d,#608269, 1-99 d,#0d1410, +|11: 0-0 d,#608269, 1-4 d,#0d1410, 5-99 #59675c,#0d1410, +|12: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-16 #e5eee5,#0d1410, 17-20 #f7e4a5,#5e4923, 21-21 #f7e4a5,#0d1410, 22-23 #e5eee5,#0d1410, 24-28 #c9a7ed,#0d1410, 29-99 #e5eee5,#0d1410, +|13: 0-0 d,#608269, 1-4 d,#0d1410, 5-99 #59675c,#0d1410, +|14: 0-0 d,#152019, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-10 #e5eee5,#0d1410, 11-13 #c9a7ed,#0d1410, 14-25 #e5eee5,#0d1410, 26-29 #f7e4a5,#5e4923, 30-99 #e5eee5,#0d1410, +|15: 0-1 d,#496656, 2-2 d,#1d2824, 3-44 #b2c3b8,#1d2824, 45-53 #d3b0d9,#1d2824, 54-99 #b2c3b8,#1d2824, +|16: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-16 #e5eee5,#0d1410, 17-20 #f5f7ee,#3c614a, 21-21 #f5f7ee,#0d1410, 22-23 #e5eee5,#0d1410, 24-28 #c9a7ed,#0d1410, 29-99 #e5eee5,#0d1410, +|17: 0-0 d,#608269, 1-4 d,#0d1410, 5-10 #59675c,#0d1410, 11-99 #e5eee5,#0d1410, +|18: 0-0 d,#608269, 1-4 d,#0d1410, 5-10 #59675c,#0d1410, 11-99 #e5eee5,#0d1410, +|19: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-99 #e5eee5,#0d1410, +|20: 0-0 d,#608269, 1-4 d,#0d1410, 5-99 #59675c,#0d1410, |21: 0-0 d,#608269, 1-99 d,#0d1410, |22: 0-0 d,#608269, 1-99 d,#0d1410, |23: 0-0 d,#608269, 1-99 d,#0d1410, @@ -116,4 +118,4 @@ |32: 0-0 d,#608269, 1-99 d,#0d1410, |33: 0-0 d,#608269, 1-99 d,#0d1410, |34: 0-0 d,#608269, 1-99 d,#0d1410, -== snap clicked grid=100x35 cursor=16,16 +== snap clicked grid=100x35 cursor=15,12 diff --git a/test/snapshots/lsprelpath.snap b/test/snapshots/lsprelpath.snap index 1d662f8a..667c2fc8 100644 --- a/test/snapshots/lsprelpath.snap +++ b/test/snapshots/lsprelpath.snap @@ -7,9 +7,8 @@ # to read pushed off the right edge, and a path outside the tree has nothing # short to be called. # -# lspcomplete.snap already covers the easy middle case, a candidate in the SAME -# directory, which shortens to a bare basename. The two that a prefix strip can -# actually get wrong are here, one app each: +# A row in the SAME directory shortens to a bare basename; the two that a +# prefix strip can actually get wrong are here, one app each, as `gr` rows: # # PARENT the enum is one level UP from the asking file, so nothing is # stripped and the row carries `/tmp/.../cwd/shade.zig`. This is @@ -33,16 +32,14 @@ file sub/subdir.zig const tint = @import("inner/tint.zig");\n\npub fn hue(t: tin start 35 100 sub/parent.zig wait 8000 fn pick stable 700 20000 -# file line 5 (grid row 6, 1-based click row 7) is the switch's empty body -press left 8 8 -release left 8 8 +# `gr` on `Shade` in the signature (file line 3, click row 6): its +# declaration's row is in the parent directory. +press left 31 6 +release left 31 6 stable 400 5000 -key i -key end -text . -stable 400 5000 -key tab -wait 15000 cwd/shade.zig:2: +key g +key r +wait 15000 cwd/shade.zig:1: stable 700 15000 snap absrow key esc @@ -58,15 +55,12 @@ snapstyle abslook start 35 100 sub/subdir.zig wait 8000 fn hue stable 700 20000 -press left 8 8 -release left 8 8 -stable 400 5000 -key i -key end -text . +press left 29 6 +release left 29 6 stable 400 5000 -key tab -wait 15000 inner/tint.zig:2: +key g +key r +wait 15000 inner/tint.zig:1: stable 700 15000 snap subrow key esc -- cgit v1.3 From fc8e1abf361ab2151109e68e5c88a0ed45650b38 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Wed, 30 Sep 2026 11:48:22 -0300 Subject: pardes NEWFILE in a pane forwards even when its directory is missing, and Save makes the directories fs.md said FILE must already exist, while `pardes new.txt` in fact forwarded, making a pane named for it that Save creates. With a missing directory (`pardes notes/new.txt`) the launch gave up forwarding and started a nested editor inside the pane. Now the name is made absolute as written and forwarded the same way. A name written to a pane's name file that goes into a directory not there has its Save make the directories, as Config's pane does. A Save into a missing directory still fails ENOENT. The Forwarding section now says what a new FILE does. fs.py launches one into a missing directory and saves it. Co-Authored-By: Claude Opus 5.5 --- docs/fs.md | 11 +++++++---- src/main.zig | 10 +++++++++- src/ninep/pane.zig | 18 ++++++++++++++++++ test/fs.py | 16 ++++++++++++++++ 4 files changed, 50 insertions(+), 5 deletions(-) (limited to 'src/main.zig') diff --git a/docs/fs.md b/docs/fs.md index 75f9fd14..2a618173 100644 --- a/docs/fs.md +++ b/docs/fs.md @@ -18,9 +18,11 @@ and `PARDES_PANE` (their pane's serial). **Forwarding.** `pardes FILE` run in a pane (a live `PARDES_PID`, with `PARDES_9P` and `PARDES_PANE`) writes FILE to that pane's `look` and returns -at once, as acme's `B` does. FILE must already exist; a name that does not -resolve, or a missing `PARDES_9P`/`PARDES_PANE`, starts a separate editor -instead. Bare `pardes` in a pane refuses and names `--nested`. +at once, as acme's `B` does. A FILE not there yet (`pardes notes/new.txt`) +opens a new pane named for it, empty, and its Save creates the file, making +its directories first when they are not there either. A missing +`PARDES_9P`/`PARDES_PANE` starts a separate editor instead. Bare `pardes` in +a pane refuses and names `--nested`. `--wait` (`-w`) returns when the pane that shows FILE is deleted (exit 0) or the session goes away (exit 1), as acme's `E` does. Use @@ -342,7 +344,8 @@ are ENOSPC, for this open and for a look, exec, `New` or `Tty` alike. **`name`** reads the file name (a terminal's directory); a write renames the buffer (relative to the pane's directory) and marks nothing dirty; `Save` -then writes under the new name. A name is one line; refused (EINVAL) are a +then writes under the new name, making its directories first when the name +went into one not there. A name is one line; refused (EINVAL) are a second line, a blank at either end, control bytes and non-UTF-8 (`bad character in file name: a blank at its start`, ...). Up to 255 bytes a component. diff --git a/src/main.zig b/src/main.zig index 0e2ba954..6bdf2bfd 100644 --- a/src/main.zig +++ b/src/main.zig @@ -416,7 +416,15 @@ fn nativeMain(init: std.process.Init) !void { // creates the file from. const base = std.fs.path.basename(target.path); if (base.len == 0 or std.mem.eql(u8, base, ".") or std.mem.eql(u8, base, "..")) break :forwarding; - const dir = pardes.filesystem.resolveOs(std.fs.path.dirname(target.path) orelse ".", &realbuf) orelse break :forwarding; + const dir = pardes.filesystem.resolveOs(std.fs.path.dirname(target.path) orelse ".", &realbuf) orelse { + // Its directory not there either: the name made absolute as + // written, and the pane's Save makes the directories (a + // name into a missing one says so, pane.zig writeName). + var cwd_buf: [4096]u8 = undefined; + if (std.c.getcwd(&cwd_buf, cwd_buf.len) == null) break :forwarding; + const cwd = std.mem.sliceTo(&cwd_buf, 0); + break :named std.fs.path.resolvePosix(arena, &.{ cwd, target.path }) catch break :forwarding; + }; break :named std.fmt.bufPrint(&newbuf, "{s}/{s}", .{ std.mem.trimEnd(u8, dir.path, "/"), base }) catch break :forwarding; }; if (found_path != null) { diff --git a/src/ninep/pane.zig b/src/ninep/pane.zig index de7f7cd4..6a0fbba5 100644 --- a/src/ninep/pane.zig +++ b/src/ninep/pane.zig @@ -867,6 +867,11 @@ fn writeName(p: *Pardes, req: Req, id: usize, pane: *Pane) Reply { error.OutOfMemory => E.NOMEM, else => E.INVAL, }); + // A name into a directory not there yet asks for it, as Config's pane + // does: its Save makes the directories (`pardes new/dir/f` forwarded). + if (comptime pardes.hosted) if (fs.localPath(std.fs.path.dirname(full) orelse "/")) |local| { + if (!exec.isDirectory(local)) fileOf(pane).?.make_dirs = true; + }; return .{ .tag = req.tag, .written = @intCast(req.data.len) }; } @@ -1387,6 +1392,19 @@ test "a name with a component over 255 bytes is refused, and a long path's faile try testing.expect(std.mem.endsWith(u8, late, "/f.txt: no such directory")); } +test "a name into a directory not there has Save make it; one into a directory there does not" { + if (comptime !pardes.hosted) return error.SkipZigTest; + const p = try withFile(testing.allocator, "x\n"); + defer p.deinit(); + const serial = serialOf(p); + const f = fileOf(p.panes[p.paneBySerial(serial).?].?).?; + try testing.expectEqual(Status.ok, wr(p, Node.of(serial, .name), "/tmp/pardes-no-such-dir-mk/sub/f.txt\n").reply.status); + try testing.expect(f.make_dirs); + f.make_dirs = false; + try testing.expectEqual(Status.ok, wr(p, Node.of(serial, .name), "/tmp/f.txt\n").reply.status); + try testing.expect(!f.make_dirs); +} + test "a name cut across writes is one name, applied once at its newline or its close" { const p = try withFile(testing.allocator, "x\n"); defer p.deinit(); diff --git a/test/fs.py b/test/fs.py index 6f1165e5..a6cd332e 100644 --- a/test/fs.py +++ b/test/fs.py @@ -1294,6 +1294,22 @@ def test(binary, quic=False): client.remove(f'/pane/{named}') assert made.wait(timeout=5) == 0 assert fresh.read_bytes() == b'new\n' + # ...in a directory not there either: forwarded all the same, and + # Save makes the directories. + deep = root / 'wait-missing' / 'sub' / 'new.txt' + before = serials() + made = subprocess.Popen([binary, 'wait-missing/sub/new.txt'], cwd=root, env=env, + stdout=subprocess.DEVNULL, stderr=subprocess.PIPE) + assert made.wait(timeout=5) == 0, made.stderr.read() + deadline = time.monotonic() + 3 + while str(deep).encode() not in client.read('/index'): + assert time.monotonic() < deadline, 'a name in a missing directory opened no pane named it' + time.sleep(.01) + named, = serials() - before + client.write(f'/pane/{named}/body', b'deep\n') + execute(client, named, 'Save') + client.remove(f'/pane/{named}') + assert deep.read_bytes() == b'deep\n' orphan = launch('--wait') assert orphan.poll() is None assert orphan.wait(timeout=5) == 1 -- cgit v1.3 From dc37b4ea777b7eb881a993e737457c18699c5b2c Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Wed, 30 Sep 2026 13:05:18 -0300 Subject: pardes FILE in a pane whose session answers never falls back to a nested editor: the refusal is printed, exit 1, and no stray pane is left When the environment named a live session that answered, several failures broke out of forwarding and started a whole editor inside the pane that asked: a refused name, a pane the session has not, a failed look write. Its screen was drawn over the shell. Now, once the session answers (Client.probe), every refusal is printed as `pardes: : `, in the session's own words (the Rerror, now kept by the client), and the launch exits 1, as acme's B does. A new name the session refuses deletes the pane made for it, so no empty +New is left. A missing environment or a session that does not answer still starts a separate editor. fs.py checks a refused name and a stale PARDES_PANE. Co-Authored-By: Claude Opus 5.5 --- docs/fs.md | 9 ++++++--- src/9p_io.zig | 17 +++++++++++++++-- src/main.zig | 60 ++++++++++++++++++++++++++++++++++++++++++----------------- test/fs.py | 17 ++++++++++++++++- 4 files changed, 80 insertions(+), 23 deletions(-) (limited to 'src/main.zig') diff --git a/docs/fs.md b/docs/fs.md index 6a82b633..2660bada 100644 --- a/docs/fs.md +++ b/docs/fs.md @@ -20,9 +20,12 @@ and `PARDES_PANE` (their pane's serial). `PARDES_9P` and `PARDES_PANE`) writes FILE to that pane's `look` and returns at once, as acme's `B` does. A FILE not there yet (`pardes notes/new.txt`) opens a new pane named for it, empty, and its Save creates the file, making -its directories first when they are not there either. A missing -`PARDES_9P`/`PARDES_PANE` starts a separate editor instead. Bare `pardes` in -a pane refuses and names `--nested`. +its directories first when they are not there either. A session that +answers never gets a nested editor in its pane: what it refuses (a bad +name, a pane it has not) is printed, `pardes: : `, and the +launch exits 1, leaving no pane behind. A missing `PARDES_9P`/`PARDES_PANE`, +or a session that does not answer, starts a separate editor instead. Bare +`pardes` in a pane refuses and names `--nested`. `--wait` (`-w`) returns when the pane that shows FILE is deleted (exit 0) or the session goes away (exit 1), as acme's `E` does. Use diff --git a/src/9p_io.zig b/src/9p_io.zig index d1b2099c..5a68238c 100644 --- a/src/9p_io.zig +++ b/src/9p_io.zig @@ -1808,7 +1808,17 @@ pub const Client = struct { var sock_buf: [sun_path_len]u8 = undefined; const sock = try resolve(&sock_buf, dial); var remote: RemoteError = .{}; - return fetchBytes(gpa, sock, names[0..n], &remote, null, display_path, @min(max_bytes, limits.max_file_bytes)); + return fetchBytes(gpa, sock, names[0..n], &remote, null, display_path, @min(max_bytes, limits.max_file_bytes)) catch |err| { + if (err == error.Remote) said = remote; + return err; + }; + } + + /// The peer's own words for the last error.Remote a read or write here + /// got (its Rerror), for a caller that says why. + var said: RemoteError = .{}; + pub fn lastSaid() []const u8 { + return said.buf[0..said.len]; } /// Whether a peer answers at `dial`: a version and attach, and its root @@ -1828,7 +1838,10 @@ pub const Client = struct { var sock_buf: [sun_path_len]u8 = undefined; const sock = try resolve(&sock_buf, dial); var remote: RemoteError = .{}; - const result = try fetchBytes(gpa, sock, names[0..n], &remote, bytes, path, limits.max_file_bytes); + const result = fetchBytes(gpa, sock, names[0..n], &remote, bytes, path, limits.max_file_bytes) catch |err| { + if (err == error.Remote) said = remote; + return err; + }; gpa.free(result); } diff --git a/src/main.zig b/src/main.zig index 6bdf2bfd..576efc8e 100644 --- a/src/main.zig +++ b/src/main.zig @@ -390,6 +390,19 @@ fn nativeMain(init: std.process.Init) !void { // leave a stale environment variable able to lock someone out of their // own editor. const parent = found orelse break :forwarding; + // Does it answer? One that answers takes the file or says why not, + // as acme's B does: from here on never a nested editor, whose + // screen would be drawn inside the pane that asked. + ninep_io.Client.probe(arena, parent.dial) catch break :forwarding; + const Refuse = struct { + fn with(io: std.Io, what: []const u8, err: anyerror) noreturn { + const why = if (err == error.Remote) ninep_io.Client.lastSaid() else @errorName(err); + var buf: [8192]u8 = undefined; + const text = std.fmt.bufPrint(&buf, "pardes: {s}: {s}\n", .{ what[0..@min(what.len, 4096)], why }) catch "pardes: refused\n"; + std.Io.File.stderr().writeStreamingAll(io, text) catch {}; + std.process.exit(1); + } + }; // The pane's `look` file: one line, and the line is the clicked text // itself, which is what a right click in that pane would have been. var look_buf: [64]u8 = undefined; @@ -397,15 +410,12 @@ fn nativeMain(init: std.process.Init) !void { const word = positional orelse { var tag_buf: [64]u8 = undefined; const tag = try std.fmt.bufPrint(&tag_buf, "/pane/{d}/tag", .{parent.serial}); - const contents = ninep_io.Client.read(arena, parent.dial, tag, tag) catch break :forwarding; + const contents = ninep_io.Client.read(arena, parent.dial, tag, tag) catch |err| Refuse.with(init.io, tag, err); arena.free(contents); try std.Io.File.stderr().writeStreamingAll(init.io, nested_text); std.process.exit(1); }; - // A word this launch cannot turn into a path is an argument problem - // rather than a nesting one: fall through and let the session that - // starts report it, the way `pardes typo` outside pardes does. - if (std.mem.indexOfAny(u8, word, "\r\n") != null) break :forwarding; + if (std.mem.indexOfAny(u8, word, "\r\n") != null) Refuse.with(init.io, "a file name", error.NotOneLine); const target = @import("look.zig").parsePathLine(word); var realbuf: [4096]u8 = undefined; var newbuf: [4096]u8 = undefined; @@ -415,30 +425,46 @@ fn nativeMain(init: std.process.Init) !void { // resolved and the name kept, a pane made for it that Save // creates the file from. const base = std.fs.path.basename(target.path); - if (base.len == 0 or std.mem.eql(u8, base, ".") or std.mem.eql(u8, base, "..")) break :forwarding; + if (base.len == 0 or std.mem.eql(u8, base, ".") or std.mem.eql(u8, base, "..")) Refuse.with(init.io, word, error.NotAFileName); const dir = pardes.filesystem.resolveOs(std.fs.path.dirname(target.path) orelse ".", &realbuf) orelse { // Its directory not there either: the name made absolute as - // written, and the pane's Save makes the directories (a - // name into a missing one says so, pane.zig writeName). + // written, and the pane's Save makes the directories. var cwd_buf: [4096]u8 = undefined; - if (std.c.getcwd(&cwd_buf, cwd_buf.len) == null) break :forwarding; + if (std.c.getcwd(&cwd_buf, cwd_buf.len) == null) Refuse.with(init.io, word, error.NoWorkingDirectory); const cwd = std.mem.sliceTo(&cwd_buf, 0); - break :named std.fs.path.resolvePosix(arena, &.{ cwd, target.path }) catch break :forwarding; + break :named std.fs.path.resolvePosix(arena, &.{ cwd, target.path }) catch |err| Refuse.with(init.io, word, err); }; - break :named std.fmt.bufPrint(&newbuf, "{s}/{s}", .{ std.mem.trimEnd(u8, dir.path, "/"), base }) catch break :forwarding; + break :named std.fmt.bufPrint(&newbuf, "{s}/{s}", .{ std.mem.trimEnd(u8, dir.path, "/"), base }) catch |err| Refuse.with(init.io, word, err); }; if (found_path != null) { var command_buf: [8192]u8 = undefined; - const command = std.fmt.bufPrint(&command_buf, "{s}{s}\n", .{ path, word[target.path.len..] }) catch break :forwarding; - ninep_io.Client.write(arena, parent.dial, look, command) catch break :forwarding; + const command = std.fmt.bufPrint(&command_buf, "{s}{s}\n", .{ path, word[target.path.len..] }) catch |err| Refuse.with(init.io, word, err); + ninep_io.Client.write(arena, parent.dial, look, command) catch |err| Refuse.with(init.io, word, err); } else { - const made = ninep_io.Client.read(arena, parent.dial, "/pane/new", "/pane/new") catch break :forwarding; - const serial = std.fmt.parseInt(u32, std.mem.trim(u8, made, " \n"), 10) catch break :forwarding; + const made = ninep_io.Client.read(arena, parent.dial, "/pane/new", "/pane/new") catch |err| Refuse.with(init.io, word, err); + const serial = std.fmt.parseInt(u32, std.mem.trim(u8, made, " \n"), 10) catch |err| Refuse.with(init.io, word, err); var name_buf: [64]u8 = undefined; const name = try std.fmt.bufPrint(&name_buf, "/pane/{d}/name", .{serial}); var line_buf: [4200]u8 = undefined; - const line = std.fmt.bufPrint(&line_buf, "{s}\n", .{path}) catch break :forwarding; - ninep_io.Client.write(arena, parent.dial, name, line) catch break :forwarding; + const line = std.fmt.bufPrint(&line_buf, "{s}\n", .{path}) catch |err| Refuse.with(init.io, word, err); + ninep_io.Client.write(arena, parent.dial, name, line) catch |err| { + // The name refused: the pane made for it goes too, no + // stray +New left behind. + var ctl_buf: [64]u8 = undefined; + const ctl = std.fmt.bufPrint(&ctl_buf, "/pane/{d}/ctl", .{serial}) catch unreachable; + var why_buf: [256]u8 = undefined; + const said = ninep_io.Client.lastSaid(); + const why = why_buf[0..@min(said.len, why_buf.len)]; + @memcpy(why, said[0..why.len]); + ninep_io.Client.write(arena, parent.dial, ctl, "delete\n") catch {}; + if (err == error.Remote) { + var buf: [8192]u8 = undefined; + const text = std.fmt.bufPrint(&buf, "pardes: {s}: {s}\n", .{ word[0..@min(word.len, 4096)], why }) catch "pardes: refused\n"; + std.Io.File.stderr().writeStreamingAll(init.io, text) catch {}; + std.process.exit(1); + } + Refuse.with(init.io, word, err); + }; } if (wait) waitForDel(init.io, arena, parent.dial, path); return; diff --git a/test/fs.py b/test/fs.py index a6cd332e..98f46900 100644 --- a/test/fs.py +++ b/test/fs.py @@ -1219,11 +1219,18 @@ def test(binary, quic=False): assert client.read('/index') == before assert client.read('/pane/1/body') == b'initial\n' + # A session that answers takes the file or says why, as acme's B + # does: a pane it has not is its refusal and exit 1, never a + # nested editor drawn inside the pane that asked. + gone = subprocess.run([binary, '--tty', str(spaced)], cwd=root, + env=dict(env, PARDES_PANE='4294967295'), stdin=subprocess.DEVNULL, + stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=10) + assert gone.returncode == 1 and gone.stderr.startswith(b'pardes: '), gone + assert client.read('/index') == before for name, identity, word in [ ('stale-file', dict(inherited, PARDES_9P=str(root / 'absent.sock')), str(spaced)), ('stale-missing', dict(inherited, PARDES_9P=str(root / 'absent.sock')), 'missing-child-file.txt'), ('stale-noarg', dict(inherited, PARDES_9P=str(root / 'absent.sock')), None), - ('stale-pane', dict(inherited, PARDES_PANE='4294967295'), str(spaced)), # No pid means "not inside a pardes at all", which is what # --nested withholds and what a plain shell has. ('not-nested', {k: v for k, v in inherited.items() if k != 'PARDES_PID'}, str(spaced)), @@ -1310,6 +1317,14 @@ def test(binary, quic=False): execute(client, named, 'Save') client.remove(f'/pane/{named}') assert deep.read_bytes() == b'deep\n' + # A name the session refuses: its reason and exit 1, as B's, + # never a nested editor, and no pane left for it. + before = serials() + refused = subprocess.run([binary, 'bad\x01name.txt'], cwd=root, env=env, + stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=10) + assert refused.returncode == 1, refused + assert b'bad character in file name' in refused.stderr, refused.stderr + assert serials() == before, (serials(), before) orphan = launch('--wait') assert orphan.poll() is None assert orphan.wait(timeout=5) == 1 -- cgit v1.3 From 864407b240b812743d6f57a56daf9706b36fc027 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Wed, 30 Sep 2026 15:14:00 -0300 Subject: pardes --wait for a new name waits on the pane it made, by serial, and a pane closed before it looks is done, not a failure fs.py's `pardes --wait 'wait new.txt'` failed two runs in three on the 0.0.8 merge. The stress case repeats the test's steps: 4 of 50 failed under load, each with "pardes: --wait: no pane shows that file". A new name's launch makes its pane, names it, then found it again by path in /index. The script had already seen the name, saved and removed the pane by then, so the lookup missed and --wait exited 1. Now the launch hands --wait the serial pane/new gave it. After a look, finding no pane on the file means that pane is already closed, which is the end --wait waits for: exit 0. The follow with its /index recheck covers a close in between, as before. Under the same load the stress case went 0 of 100. The same load showed a test race too, at fs.py's second Restore. The exec write is answered before the hang-up, but the client's clunk after it can meet the connection already cut. The test now requires the answer and tolerates the reset. Co-Authored-By: Claude Opus 5.5 --- src/main.zig | 21 ++++++++++++++------- test/fs.py | 13 +++++++++++-- 2 files changed, 25 insertions(+), 9 deletions(-) (limited to 'src/main.zig') diff --git a/src/main.zig b/src/main.zig index 576efc8e..859e6fb3 100644 --- a/src/main.zig +++ b/src/main.zig @@ -102,13 +102,18 @@ const help_text = /// pane `path` landed in (the one it already had, if open), then /log /// followed on one connection until that pane's `del` -- exit 0 -- or the /// connection ends with the session -- exit 1. -fn waitForDel(io: std.Io, gpa: std.mem.Allocator, dial: []const u8, path: []const u8) noreturn { - const first = ninep_io.Client.read(gpa, dial, "/index", "/index") catch std.process.exit(1); - const serial = paneShowing(first, path) orelse { - std.Io.File.stderr().writeStreamingAll(io, "pardes: --wait: no pane shows that file\n") catch {}; - std.process.exit(1); +fn waitForDel(io: std.Io, gpa: std.mem.Allocator, dial: []const u8, path: []const u8, known: ?u32) noreturn { + _ = io; + // The pane this launch made (a name not there yet) is known by its + // serial; one a look opened or went to is found by its file. Found by + // none after the look went there, it was closed already: that is the + // end being waited for, not a failure (a pane closed between the look + // and this read made `--wait` exit 1 before). + const serial = known orelse found: { + const first = ninep_io.Client.read(gpa, dial, "/index", "/index") catch std.process.exit(1); + defer gpa.free(first); + break :found paneShowing(first, path) orelse std.process.exit(0); }; - gpa.free(first); const Wait = struct { gpa: std.mem.Allocator, dial: []const u8, @@ -436,6 +441,7 @@ fn nativeMain(init: std.process.Init) !void { }; break :named std.fmt.bufPrint(&newbuf, "{s}/{s}", .{ std.mem.trimEnd(u8, dir.path, "/"), base }) catch |err| Refuse.with(init.io, word, err); }; + var made_serial: ?u32 = null; if (found_path != null) { var command_buf: [8192]u8 = undefined; const command = std.fmt.bufPrint(&command_buf, "{s}{s}\n", .{ path, word[target.path.len..] }) catch |err| Refuse.with(init.io, word, err); @@ -443,6 +449,7 @@ fn nativeMain(init: std.process.Init) !void { } else { const made = ninep_io.Client.read(arena, parent.dial, "/pane/new", "/pane/new") catch |err| Refuse.with(init.io, word, err); const serial = std.fmt.parseInt(u32, std.mem.trim(u8, made, " \n"), 10) catch |err| Refuse.with(init.io, word, err); + made_serial = serial; var name_buf: [64]u8 = undefined; const name = try std.fmt.bufPrint(&name_buf, "/pane/{d}/name", .{serial}); var line_buf: [4200]u8 = undefined; @@ -466,7 +473,7 @@ fn nativeMain(init: std.process.Init) !void { Refuse.with(init.io, word, err); }; } - if (wait) waitForDel(init.io, arena, parent.dial, path); + if (wait) waitForDel(init.io, arena, parent.dial, path, made_serial); return; } if (positional) |a| { diff --git a/test/fs.py b/test/fs.py index b02b9e45..3f11269a 100644 --- a/test/fs.py +++ b/test/fs.py @@ -1117,7 +1117,15 @@ def test(binary, quic=False): except OSError as refused: assert 'Modified' in str(refused), refused assert old.read('/pane/1/body') == b'changed after dump\n' - execute(old, control, 'Restore ' + str(saved)) + # Answered before the hang-up: the write's reply comes; the + # clunk after it may meet the connection already cut. + restore = old.open(f'/pane/{control}/exec', 1) + line = ('Restore ' + str(saved) + '\n').encode() + old.rpc(118, struct.pack(' Date: Wed, 30 Sep 2026 14:53:46 -0300 Subject: A path typed with a leading ~ is the home directory, at every entry point that takes one, through one helper Only DumpDir (dump.zig) and ShaderBuild expanded `~/`, each its own way. So a look at `~/notes.txt`, `name ~/x`, `Save ~/x`, ThemeFile, Restore and a quoted `pardes '~/x'` all took `~` as a directory of that name under the pane's. There is now one rule, filesystem.expandHome. A leading `~`, alone or before `/` or `:`, is $HOME, else the passwd entry's home; `~user` is that user's (getpwnam). As in a shell, it applies even beside a file named `~`, and `./~` names that file. Every entry point runs its typed path through it: - look, B3 and 9P, before any parsing, so `~/x:12`, `~/x:12:3` and `~/x:/re/` all work; - name, and a tag's rename; - Save ; - ThemeFile, DumpDir, Restore and ShaderBuild's shader files; - the forwarding launch. Recent rows are not shown with `~` and need nothing. How names are shown is unchanged. Tests: expandHome's cases, and HOME unset (passwd), with HOME passed in rather than set, since setenv moves the environ a spawned child reads. fs.py covers Save into missing directories under `~`, `name ~/x`, a look at `~/x:3`, and a forwarded `pardes '~/x'`. Co-Authored-By: Claude Opus 5.5 --- docs/fs.md | 6 +++++- src/ShaderBuild.zig | 8 +++----- src/builtins.zig | 3 ++- src/dump.zig | 7 ++----- src/exec.zig | 3 ++- src/fs.zig | 57 ++++++++++++++++++++++++++++++++++++++++++++++++++++- src/look.zig | 5 ++++- src/main.zig | 7 +++++-- src/ninep/pane.zig | 3 ++- src/tagline.zig | 3 ++- test/fs.py | 22 +++++++++++++++++++++ 11 files changed, 105 insertions(+), 19 deletions(-) (limited to 'src/main.zig') diff --git a/docs/fs.md b/docs/fs.md index b37511dd..146ff17b 100644 --- a/docs/fs.md +++ b/docs/fs.md @@ -199,7 +199,11 @@ A line written to `look` is a right click on it: selects line 12, newline included; `file:12:5` puts the caret at line 12, byte column 5; `file:` takes any address (below), **evaluated from the file's dot**: `file:/re/` finds the next match after the selection, - `file:0/re/` the first. `:addr` addresses the pane itself. + `file:0/re/` the first. `:addr` addresses the pane itself. A leading `~` + is the home directory ($HOME, else the passwd entry's; `~user` that + user's) here and wherever a path is typed (`name`, `Save`, `ThemeFile`, + `DumpDir`, `Restore`, `pardes '~/x'`), even beside a file named `~`: write + `./~` for that. - `@p:` addresses a pane by serial, a terminal's logical lines too. - a directory types `ls` into a terminal idle there, else opens one there. diff --git a/src/ShaderBuild.zig b/src/ShaderBuild.zig index c2610fd7..b50999a5 100644 --- a/src/ShaderBuild.zig +++ b/src/ShaderBuild.zig @@ -236,11 +236,9 @@ fn collect(b: *Build, gpa: std.mem.Allocator, core: *pardes.Pardes, job: *Job) v } } -/// `~/` is the home directory. -fn expand(buf: []u8, path: []const u8) []const u8 { - if (!std.mem.startsWith(u8, path, "~/")) return path; - const home = libc.getenv("HOME") orelse return path; - return std.fmt.bufPrint(buf, "{s}/{s}", .{ std.mem.span(home), path[2..] }) catch path; +/// `~` is the home directory (the one rule, filesystem.expandHome). +fn expand(buf: *[4096]u8, path: []const u8) []const u8 { + return pardes.filesystem.expandHome(path, buf); } /// The compile thread: each file behind the prefix, through glslc with the diff --git a/src/builtins.zig b/src/builtins.zig index ba67766d..6aabba8d 100644 --- a/src/builtins.zig +++ b/src/builtins.zig @@ -818,7 +818,8 @@ pub const ThemeFile = struct { pub const enabled = pardes.hosted; pub fn run(c: Ctx) void { if (comptime !enabled) unreachable; - const arg = std.mem.trim(u8, c.arg orelse return, " \t\r\n"); + var home_buf: [4096]u8 = undefined; + const arg = pardes.filesystem.expandHome(std.mem.trim(u8, c.arg orelse return, " \t\r\n"), &home_buf); // Said with why, not "invalid theme path". if (!std.mem.endsWith(u8, arg, ".zon")) { var said: [320]u8 = undefined; diff --git a/src/dump.zig b/src/dump.zig index 1cc115be..8e767240 100644 --- a/src/dump.zig +++ b/src/dump.zig @@ -100,13 +100,10 @@ fn hostEnv(name: [*:0]const u8) ?[*:0]u8 { /// setting when set (a leading `~/` is the home directory), else the default. pub fn directory(buf: []u8, dir_setting: []const u8) ?[]const u8 { if (dir_setting.len == 0) return defaultDirectory(buf); - var joined: [2048]u8 = undefined; + var joined: [4096]u8 = undefined; // `~/x`, else a relative one from the directory pardes started in: the // same place however it was written, and shown so. - const raw = if (std.mem.startsWith(u8, dir_setting, "~/")) (if (hostEnv("HOME")) |h| - std.fmt.bufPrint(&joined, "{s}/{s}", .{ std.mem.span(h), dir_setting[2..] }) catch return null - else - dir_setting) else dir_setting; + const raw = pardes.filesystem.expandHome(dir_setting, &joined); var fba_buf: [4096]u8 = undefined; var fba = std.heap.FixedBufferAllocator.init(&fba_buf); var cwd_buf: [1024]u8 = undefined; diff --git a/src/exec.zig b/src/exec.zig index 7d682d74..d114dbf8 100644 --- a/src/exec.zig +++ b/src/exec.zig @@ -295,9 +295,10 @@ pub fn saveTo(p: *Pardes, id: usize, path: []const u8) void { if (path.len == 0 or path[path.len - 1] == '/' or std.mem.indexOfScalar(u8, path, '\n') != null) return p.reportError(id, "save", error.NoFilename); + var home_buf: [4096]u8 = undefined; const full = std.fs.path.resolvePosix( p.scratch.allocator(), - &.{ Pardes.paneDir(pane), path }, + &.{ Pardes.paneDir(pane), @import("fs.zig").expandHome(path, &home_buf) }, ) catch return; if (!std.fs.path.isAbsolute(full)) return p.reportError(id, "save", error.NoDirectory); if (full.len > Pardes.SavePath.cap) return p.reportError(id, "save", error.PathTooLong); diff --git a/src/fs.zig b/src/fs.zig index 30ad9c43..7695d497 100644 --- a/src/fs.zig +++ b/src/fs.zig @@ -732,6 +732,59 @@ pub fn dotRelative(word: []const u8) bool { /// Where a path really is on the host, and whether it is a directory. The /// path may lie in a mount this editor serves, so the turn is given up for /// the syscalls: another thread answers them. +/// A path's leading `~` -- alone, or before `/` or `:` (`~/x:12`) -- is the +/// home directory: $HOME, else the passwd entry's. `~user/...` is that +/// user's. As in a shell, `~` is home even beside a file named `~` in the +/// current directory. Every entry point that takes a path the user typed +/// runs it through here: look (B3 and 9P), name, Save, ThemeFile, DumpDir, +/// Restore, a forwarded `pardes ~/x`. The path itself when there is no +/// `~` to expand, or no home for it. +pub fn expandHome(path: []const u8, out: *[4096]u8) []const u8 { + if (comptime !pardes.hosted) return path; + return expandHomeFrom(path, out, std.c.getenv("HOME")); +} + +/// expandHome with HOME given (null: unset), so a test need not change the +/// process's environment, which a child spawned later reads. +fn expandHomeFrom(path: []const u8, out: *[4096]u8, env_home: ?[*:0]const u8) []const u8 { + if (path.len == 0 or path[0] != '~') return path; + const end = std.mem.indexOfAny(u8, path, "/:") orelse path.len; + const home = (if (end == 1) homeDir(env_home) else userHome(path[1..end])) orelse return path; + const trimmed = std.mem.trimEnd(u8, home, "/"); + const rest = path[end..]; + if (trimmed.len == 0 and (rest.len == 0 or rest[0] != '/')) return std.fmt.bufPrint(out, "/{s}", .{rest}) catch path; + return std.fmt.bufPrint(out, "{s}{s}", .{ trimmed, rest }) catch path; +} + +fn homeDir(env_home: ?[*:0]const u8) ?[]const u8 { + if (env_home) |h| if (h[0] != 0) return std.mem.span(h); + const pw = std.c.getpwuid(std.c.getuid()) orelse return null; + return std.mem.span(pw.dir orelse return null); +} + +fn userHome(name: []const u8) ?[]const u8 { + var z: [256]u8 = undefined; + const name_z = std.fmt.bufPrintSentinel(&z, "{s}", .{name}, 0) catch return null; + const pw = std.c.getpwnam(name_z) orelse return null; + return std.mem.span(pw.dir orelse return null); +} + +test "a leading ~ is home, from HOME or else the passwd entry" { + var out: [4096]u8 = undefined; + const home = homeDir(std.c.getenv("HOME")) orelse return error.SkipZigTest; + var want: [4096]u8 = undefined; + try std.testing.expectEqualStrings(try std.fmt.bufPrint(&want, "{s}/x:12", .{std.mem.trimEnd(u8, home, "/")}), expandHome("~/x:12", &out)); + try std.testing.expectEqualStrings(std.mem.trimEnd(u8, home, "/"), expandHome("~", &out)); + try std.testing.expectEqualStrings("a/~/b", expandHome("a/~/b", &out)); + try std.testing.expectEqualStrings("~no-such-user-pardes/x", expandHome("~no-such-user-pardes/x", &out)); + try std.testing.expectEqualStrings("/", expandHome("~root", &out)[0..1]); + + // HOME unset: the passwd entry's home. + const pw = std.c.getpwuid(std.c.getuid()) orelse return error.SkipZigTest; + var from_passwd: [4096]u8 = undefined; + try std.testing.expectEqualStrings(try std.fmt.bufPrint(&from_passwd, "{s}/y", .{std.mem.trimEnd(u8, std.mem.span(pw.dir.?), "/")}), expandHomeFrom("~/y", &out, null)); +} + pub fn resolveOs(path: []const u8, out: *[4096]u8) ?Resolved { if (comptime !platform_has_fs) return null; var z: [4096]u8 = undefined; @@ -1171,7 +1224,9 @@ pub fn readFile(gpa: std.mem.Allocator, path: []const u8) ![]u8 { /// Restore first tries a relative argument under the default dump directory, /// then preserves the ordinary file lookup. Absolute paths remain verbatim. -pub fn readRestore(gpa: std.mem.Allocator, path: []const u8, dir_setting: []const u8) ![]u8 { +pub fn readRestore(gpa: std.mem.Allocator, typed: []const u8, dir_setting: []const u8) ![]u8 { + var home_buf: [4096]u8 = undefined; + const path = expandHome(typed, &home_buf); var dir_buf: [4096]u8 = undefined; const dir = @import("dump.zig").directory(&dir_buf, dir_setting); return readRestoreIn(gpa, path, dir); diff --git a/src/look.zig b/src/look.zig index de51804d..357a9c63 100644 --- a/src/look.zig +++ b/src/look.zig @@ -1499,8 +1499,11 @@ fn isRecentList(pane: *const Pane) bool { return std.meta.eql(o.from, panes.Output.Origin{ .cmd = .Recent }) or std.meta.eql(o.from, panes.Output.Origin{ .cmd = .Jumplist }); } -pub fn lookAt(p: *Pardes, id: usize, operand: []const u8) void { +pub fn lookAt(p: *Pardes, id: usize, operand_raw: []const u8) void { const pane = p.panes[id] orelse return; + // `~/x`, `~/x:12`, `~/x:/re/`: home, before anything reads the text. + var home_buf: [4096]u8 = undefined; + const operand = filesystem.expandHome(std.mem.trim(u8, operand_raw, " \t\r\n"), &home_buf); // A +Recent row is a remembered place: reopened and clamped to the file // as it is now, never a miss for a line the file no longer has. if (isRecentList(pane)) { diff --git a/src/main.zig b/src/main.zig index 576efc8e..dfeed52d 100644 --- a/src/main.zig +++ b/src/main.zig @@ -407,7 +407,7 @@ fn nativeMain(init: std.process.Init) !void { // itself, which is what a right click in that pane would have been. var look_buf: [64]u8 = undefined; const look = try std.fmt.bufPrint(&look_buf, "/pane/{d}/look", .{parent.serial}); - const word = positional orelse { + const typed_word = positional orelse { var tag_buf: [64]u8 = undefined; const tag = try std.fmt.bufPrint(&tag_buf, "/pane/{d}/tag", .{parent.serial}); const contents = ninep_io.Client.read(arena, parent.dial, tag, tag) catch |err| Refuse.with(init.io, tag, err); @@ -415,7 +415,10 @@ fn nativeMain(init: std.process.Init) !void { try std.Io.File.stderr().writeStreamingAll(init.io, nested_text); std.process.exit(1); }; - if (std.mem.indexOfAny(u8, word, "\r\n") != null) Refuse.with(init.io, "a file name", error.NotOneLine); + if (std.mem.indexOfAny(u8, typed_word, "\r\n") != null) Refuse.with(init.io, "a file name", error.NotOneLine); + // `pardes '~/x'`, quoted so the shell left it: home, as a look's. + var home_buf: [4096]u8 = undefined; + const word = pardes.filesystem.expandHome(typed_word, &home_buf); const target = @import("look.zig").parsePathLine(word); var realbuf: [4096]u8 = undefined; var newbuf: [4096]u8 = undefined; diff --git a/src/ninep/pane.zig b/src/ninep/pane.zig index dc8b4b10..7526075b 100644 --- a/src/ninep/pane.zig +++ b/src/ninep/pane.zig @@ -860,7 +860,8 @@ fn writeName(p: *Pardes, req: Req, id: usize, pane: *Pane) Reply { "rename not allowed: a terminal is named by its shell's directory; cd there, or Tty in another" else "rename not allowed: an image or PDF is named by the file it shows"); - const full = std.fs.path.resolvePosix(p.scratch.allocator(), &.{ pardes.Pardes.paneDir(pane), name }) catch + var home_buf: [4096]u8 = undefined; + const full = std.fs.path.resolvePosix(p.scratch.allocator(), &.{ pardes.Pardes.paneDir(pane), fs.expandHome(name, &home_buf) }) catch return Reply.fail(req.tag, E.NOMEM); if (!std.fs.path.isAbsolute(full) or full.len >= 4096) return tree.failText(req.tag, E.INVAL, "invalid file name: longer than a path may be"); nameBuffer(p, id, full, false) catch |err| return Reply.fail(req.tag, switch (err) { diff --git a/src/tagline.zig b/src/tagline.zig index 1923871a..dc7d10d4 100644 --- a/src/tagline.zig +++ b/src/tagline.zig @@ -344,7 +344,8 @@ pub fn commitTagName(p: *Pardes, pane: *Pane) bool { p.reportError(id, "name", error.InvalidName); return false; }; - const full = std.fs.path.resolvePosix(p.scratch.allocator(), &.{ Pardes.paneDir(pane), name }) catch |err| { + var home_buf: [4096]u8 = undefined; + const full = std.fs.path.resolvePosix(p.scratch.allocator(), &.{ Pardes.paneDir(pane), pardes.filesystem.expandHome(name, &home_buf) }) catch |err| { p.reportError(id, "name", err); return false; }; diff --git a/test/fs.py b/test/fs.py index b02b9e45..55ec3257 100644 --- a/test/fs.py +++ b/test/fs.py @@ -383,6 +383,19 @@ def discovery(binary, embedded=False): client.remove(f'/pane/{scratch}') # A Save makes the directories its file goes in, whatever names # it: the pane's own name or Save's path. + # `~` is home (this session's HOME, the test's root) wherever a + # path is typed: Save, name, a look, with an address or not. + tilde = new_pane(client, b'one\ntwo\nthree\n') + client.write(f'/pane/{tilde}/ctl', b'Save ~/tilde-made/sub/x.txt\n') + assert (root / 'tilde-made/sub/x.txt').read_bytes() == b'one\ntwo\nthree\n' + client.write(f'/pane/{tilde}/name', b'~/tilde-named.txt\n') + assert client.read(f'/pane/{tilde}/name') == f'{root}/tilde-named.txt\n'.encode() + client.remove(f'/pane/{tilde}') + client.write('/look', b'~/tilde-made/sub/x.txt:3\n') + looked = [row for row in client.read('/index').decode().splitlines() if row.split()[3] == f'{root}/tilde-made/sub/x.txt'] + assert len(looked) == 1, client.read('/index') + assert client.read(f'/pane/{looked[0].split()[0]}/addr').startswith(b'8 '), client.read(f'/pane/{looked[0].split()[0]}/addr') + client.remove(f'/pane/{looked[0].split()[0]}') made_dirs = new_pane(client, b'deep\n') client.write(f'/pane/{made_dirs}/ctl', f'Save {root}/save-made/a/b/x.txt\n'.encode()) assert (root / 'save-made/a/b/x.txt').read_bytes() == b'deep\n' @@ -1333,6 +1346,15 @@ def test(binary, quic=False): execute(client, named, 'Save') client.remove(f'/pane/{named}') assert deep.read_bytes() == b'deep\n' + # `pardes '~/x'`, quoted so the shell left the `~`: home all the + # same: the launching shell's HOME. + before = serials() + quoted = subprocess.run([binary, '~/fwd-tilde.txt'], cwd=root, env=dict(env, HOME=str(root)), + stdout=subprocess.DEVNULL, stderr=subprocess.PIPE, timeout=10) + assert quoted.returncode == 0, quoted.stderr + assert f'{root}/fwd-tilde.txt'.encode() in client.read('/index'), client.read('/index') + for serial in serials() - before: + client.remove(f'/pane/{serial}') # A name the session refuses: its reason and exit 1, as B's, # never a nested editor, and no pane left for it. before = serials() -- cgit v1.3 From 27f8f6e0a5bb2751e1642db1e7e68b2cf72e50b0 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Wed, 30 Sep 2026 21:13:57 -0300 Subject: Forwarding to a running pardes says why in words: a name with a newline is "a file name is one line", never NotOneLine The forwarding refusal printed the error's name for anything the session itself did not answer: NotOneLine, NotAFileName, NoWorkingDirectory. Those are now sentences, a dial failure is said as the message row says one, and any other error is its name's words. Co-Authored-By: Claude Opus 5.5 --- src/main.zig | 27 ++++++++++++++++++++++++++- test/fs.py | 8 ++++++++ 2 files changed, 34 insertions(+), 1 deletion(-) (limited to 'src/main.zig') diff --git a/src/main.zig b/src/main.zig index 101a5be3..6c5eaba1 100644 --- a/src/main.zig +++ b/src/main.zig @@ -98,6 +98,30 @@ const help_text = \\ ; +/// A forwarding failure in words, never an error's name: the ones this +/// file raises said outright, any other as its name's words (`NotFound`, +/// `not found`), a dial's as Messages says it. +fn forwardWords(err: anyerror, buf: []u8) []const u8 { + return switch (err) { + error.NotOneLine => "a file name is one line, and this one holds a newline", + error.NotAFileName => "names a directory, not a file", + error.NoWorkingDirectory => "this shell's working directory is gone", + else => if (pardes.Messages.dialReason(err)) |why| why else words: { + var n: usize = 0; + for (@errorName(err), 0..) |c, i| { + if (n + 2 > buf.len) break; + if (std.ascii.isUpper(c) and i > 0) { + buf[n] = ' '; + n += 1; + } + buf[n] = std.ascii.toLower(c); + n += 1; + } + break :words buf[0..n]; + }, + }; +} + /// `--wait` after a forwarded look, as plan9port's E reads acme's log: the /// pane `path` landed in (the one it already had, if open), then /log /// followed on one connection until that pane's `del` -- exit 0 -- or the @@ -401,7 +425,8 @@ fn nativeMain(init: std.process.Init) !void { ninep_io.Client.probe(arena, parent.dial) catch break :forwarding; const Refuse = struct { fn with(io: std.Io, what: []const u8, err: anyerror) noreturn { - const why = if (err == error.Remote) ninep_io.Client.lastSaid() else @errorName(err); + var words_buf: [128]u8 = undefined; + const why = if (err == error.Remote) ninep_io.Client.lastSaid() else forwardWords(err, &words_buf); var buf: [8192]u8 = undefined; const text = std.fmt.bufPrint(&buf, "pardes: {s}: {s}\n", .{ what[0..@min(what.len, 4096)], why }) catch "pardes: refused\n"; std.Io.File.stderr().writeStreamingAll(io, text) catch {}; diff --git a/test/fs.py b/test/fs.py index 9392ffb7..eba5a5fa 100644 --- a/test/fs.py +++ b/test/fs.py @@ -1391,6 +1391,14 @@ def test(binary, quic=False): assert refused.returncode == 1, refused assert b'bad character in file name' in refused.stderr, refused.stderr assert serials() == before, (serials(), before) + # A name with a newline is said in words, not an error's name. + for word, said in (('two\nlines.txt', b'a file name is one line'),): + refused = subprocess.run([binary, word], cwd=root, env=env, + stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=10) + assert refused.returncode == 1, refused + assert said in refused.stderr, refused.stderr + assert b'NotOneLine' not in refused.stderr and b'NoSuchPane' not in refused.stderr + assert serials() == before, (serials(), before) orphan = launch('--wait') assert orphan.poll() is None assert orphan.wait(timeout=5) == 1 -- cgit v1.3 From a2c719779c9ce0f676fb159135675df6275e77bf Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Wed, 30 Sep 2026 21:14:06 -0300 Subject: Forwarding pardes @pN for a pane the session has not is refused, "this session has no such pane", exit 1 and no pane made; one it has is looked at @p999:1 was taken as a new file's name, so a pane named /@p999 was made and the launch succeeded; an @pN the session did have was the same stray pane. A pane address is now checked against the session: one it has is a look at it, one it has not is refused with the reason and exit 1, as a refused name is. Co-Authored-By: Claude Opus 5.5 --- src/main.zig | 16 ++++++++++++++++ test/fs.py | 11 +++++++++-- 2 files changed, 25 insertions(+), 2 deletions(-) (limited to 'src/main.zig') diff --git a/src/main.zig b/src/main.zig index 6c5eaba1..3218fef1 100644 --- a/src/main.zig +++ b/src/main.zig @@ -106,6 +106,8 @@ fn forwardWords(err: anyerror, buf: []u8) []const u8 { error.NotOneLine => "a file name is one line, and this one holds a newline", error.NotAFileName => "names a directory, not a file", error.NoWorkingDirectory => "this shell's working directory is gone", + error.NotAPaneAddress => "not a pane address: @p and a pane's number", + error.NoSuchPane => "this session has no such pane", else => if (pardes.Messages.dialReason(err)) |why| why else words: { var n: usize = 0; for (@errorName(err), 0..) |c, i| { @@ -450,6 +452,20 @@ fn nativeMain(init: std.process.Init) !void { var home_buf: [4096]u8 = undefined; const word = pardes.filesystem.expandHome(typed_word, &home_buf); const target = @import("look.zig").parsePathLine(word); + // `@pN[:addr]` addresses a pane of this session: one it has is + // looked at, one it has not is refused, never a file of that name. + if (std.mem.startsWith(u8, target.path, pardes.config.pane_addr)) { + const digits = word[pardes.config.pane_addr.len .. std.mem.indexOfScalar(u8, word, ':') orelse word.len]; + const serial = std.fmt.parseInt(u32, digits, 10) catch Refuse.with(init.io, word, error.NotAPaneAddress); + var name_buf: [64]u8 = undefined; + const name = try std.fmt.bufPrint(&name_buf, "/pane/{d}/name", .{serial}); + const named = ninep_io.Client.read(arena, parent.dial, name, name) catch Refuse.with(init.io, word, error.NoSuchPane); + arena.free(named); + var command_buf: [4200]u8 = undefined; + const command = std.fmt.bufPrint(&command_buf, "{s}\n", .{word}) catch |err| Refuse.with(init.io, word, err); + ninep_io.Client.write(arena, parent.dial, look, command) catch |err| Refuse.with(init.io, word, err); + return; + } var realbuf: [4096]u8 = undefined; var newbuf: [4096]u8 = undefined; const found_path: ?[]const u8 = if (pardes.filesystem.isVirtual(target.path)) target.path else if (pardes.filesystem.resolveOs(target.path, &realbuf)) |r| r.path else null; diff --git a/test/fs.py b/test/fs.py index eba5a5fa..7061c61f 100644 --- a/test/fs.py +++ b/test/fs.py @@ -1391,14 +1391,21 @@ def test(binary, quic=False): assert refused.returncode == 1, refused assert b'bad character in file name' in refused.stderr, refused.stderr assert serials() == before, (serials(), before) - # A name with a newline is said in words, not an error's name. - for word, said in (('two\nlines.txt', b'a file name is one line'),): + # A pane address the session has not is refused in words, exit + # 1, no pane made for a file of that name; one it has is looked + # at. A name with a newline is said in words, not an error name. + for word, said in (('@p999:1', b'pardes: @p999:1: this session has no such pane'), + ('two\nlines.txt', b'a file name is one line')): refused = subprocess.run([binary, word], cwd=root, env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=10) assert refused.returncode == 1, refused assert said in refused.stderr, refused.stderr assert b'NotOneLine' not in refused.stderr and b'NoSuchPane' not in refused.stderr assert serials() == before, (serials(), before) + looked = subprocess.run([binary, '@p1:1'], cwd=root, env=env, + stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=10) + assert looked.returncode == 0, looked.stderr + assert serials() == before, (serials(), before) orphan = launch('--wait') assert orphan.poll() is None assert orphan.wait(timeout=5) == 1 -- cgit v1.3 From afaa2428b346f6dd1d165abe1396dce9150fa05c Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Wed, 30 Sep 2026 23:29:17 -0300 Subject: Forwarding pardes FILE for a new name in a directory it may not read or write is refused with words, not a pane that only fails at Save A new name forwarded into a directory that is there but locked opened an empty pane named for it, and the failure came only at its Save, long after the launch. The directory is checked first: one that cannot be read, written and entered is refused, exit 1, no pane made. Co-Authored-By: Claude Opus 5.5 --- src/main.zig | 10 ++++++++++ test/fs.py | 13 +++++++++++++ 2 files changed, 23 insertions(+) (limited to 'src/main.zig') diff --git a/src/main.zig b/src/main.zig index 3218fef1..9dce559f 100644 --- a/src/main.zig +++ b/src/main.zig @@ -106,6 +106,7 @@ fn forwardWords(err: anyerror, buf: []u8) []const u8 { error.NotOneLine => "a file name is one line, and this one holds a newline", error.NotAFileName => "names a directory, not a file", error.NoWorkingDirectory => "this shell's working directory is gone", + error.DirectoryNotWritable => "its directory may not be read or written, so it could never be saved", error.NotAPaneAddress => "not a pane address: @p and a pane's number", error.NoSuchPane => "this session has no such pane", else => if (pardes.Messages.dialReason(err)) |why| why else words: { @@ -483,6 +484,15 @@ fn nativeMain(init: std.process.Init) !void { const cwd = std.mem.sliceTo(&cwd_buf, 0); break :named std.fs.path.resolvePosix(arena, &.{ cwd, target.path }) catch |err| Refuse.with(init.io, word, err); }; + // A directory that is there but may not be read or written: a + // pane for the name could only fail at its Save, so refused now. + var dir_z_buf: [4096]u8 = undefined; + if (std.fmt.bufPrintSentinel(&dir_z_buf, "{s}", .{dir.path}, 0)) |dir_z| { + const R_OK = 4; + const W_OK = 2; + const X_OK = 1; + if (std.c.access(dir_z.ptr, R_OK | W_OK | X_OK) != 0) Refuse.with(init.io, word, error.DirectoryNotWritable); + } else |_| {} break :named std.fmt.bufPrint(&newbuf, "{s}/{s}", .{ std.mem.trimEnd(u8, dir.path, "/"), base }) catch |err| Refuse.with(init.io, word, err); }; var made_serial: ?u32 = null; diff --git a/test/fs.py b/test/fs.py index 8d830c48..0821b117 100644 --- a/test/fs.py +++ b/test/fs.py @@ -1403,6 +1403,19 @@ def test(binary, quic=False): # A pane address the session has not is refused in words, exit # 1, no pane made for a file of that name; one it has is looked # at. A name with a newline is said in words, not an error name. + # A new name in a directory there but not writable: refused now, + # not a pane that only fails at Save. + shut = root / 'shut-dir' + shut.mkdir() + shut.chmod(0o500) + try: + refused = subprocess.run([binary, 'shut-dir/new.txt'], cwd=root, env=env, + stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=10) + assert refused.returncode == 1, refused + assert b'may not be read or written' in refused.stderr, refused.stderr + assert serials() == before, (serials(), before) + finally: + shut.chmod(0o755) for word, said in (('@p999:1', b'pardes: @p999:1: this session has no such pane'), ('two\nlines.txt', b'a file name is one line')): refused = subprocess.run([binary, word], cwd=root, env=env, -- cgit v1.3 From 3815a0bfad5818e2caf85a00c0c2d3aecc13bd1c Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Wed, 30 Sep 2026 23:58:54 -0300 Subject: pardes - reads stdin into a +Pager pane, and is a terminal's PAGER and GIT_PAGER, Pager pardes|off to opt out; command panes page through cat A paging command in a terminal, or run through its pty/run, sat in less, and a pty/run never answered. `pardes -` now reads stdin to its end, strips terminal escapes (colour, OSC, overstrike), and shows it: inside a session as a clean /+Pager pane made through pane/new and back at once, outside one as a new editor whose first pane it is, as `vim -` does. A terminal's shell gets PAGER and GIT_PAGER set to this pardes's own path and `-` where the user's environment sets neither; `Pager off`, a setting in /ctl, init and DumpConfig, leaves terminals started after it to the environment. A command pane's one-shot shell keeps cat, its output being a pane already. Co-Authored-By: Claude Opus 5.5 --- src/config.zig | 11 ++++- src/host_io.zig | 66 +++++++++++++++++++++++++---- src/main.zig | 122 ++++++++++++++++++++++++++++++++++++++++++++++++++++-- src/ninep/ctl.zig | 11 +++++ src/pardes.zig | 16 +++++++ test/fs.py | 51 +++++++++++++++++++++++ 6 files changed, 265 insertions(+), 12 deletions(-) (limited to 'src/main.zig') diff --git a/src/config.zig b/src/config.zig index 86951e27..5a9cf070 100644 --- a/src/config.zig +++ b/src/config.zig @@ -81,6 +81,7 @@ pub const leader_path = paths: { .Placement = "cp", .BootShell = null, .LookWord = null, + .Pager = null, .Debug = "td", .Msg = null, .Colors = "tc", @@ -754,13 +755,18 @@ pub const Runtime = struct { /// next place in that pane, wrapping; `list`, what pardes did before, /// lists every place in a +Search pane (look.zig, lookWord). look_word: LookWord = .search, + /// What a terminal's shell pages through (host_io.ChildEnv): `pardes`, + /// PAGER and GIT_PAGER set to `pardes -`, a +Pager pane, where the + /// user's environment set neither; `off`, the environment as it is. + pager: Pager = .pardes, pub const ShaderAnimation = enum { off, on, always }; pub const Placement = enum { acme, pardes }; pub const BootShell = enum { keep, replace }; pub const LookWord = enum { search, list }; + pub const Pager = enum { pardes, off }; /// A setting that is one of a few words, each an enum field of Runtime. - pub const Choice = enum { placement, boot_shell, look_word }; + pub const Choice = enum { placement, boot_shell, look_word, pager }; /// shadow: a soft drop shadow. rim: a light hairline along the top of /// the focused pane's tag rows. auto: a shadow on a light page; on a @@ -1025,6 +1031,7 @@ pub const Runtime = struct { .{ .word = "Placement", .action = .{ .choice = .placement }, .doc = "Where a new pane goes: acme, as makenewwindow does, or pardes, the older rules." }, .{ .word = "BootShell", .action = .{ .choice = .boot_shell }, .doc = "A document dropped where a lone untouched shell stands: keep the shell, or replace it." }, .{ .word = "LookWord", .action = .{ .choice = .look_word }, .doc = "A plain word looked at: search selects its next place in the pane, list lists every place in a +Search." }, + .{ .word = "Pager", .action = .{ .choice = .pager }, .doc = "What a terminal's commands page through: pardes, a +Pager pane (pardes -), or off, the environment's own; for terminals started after it." }, }; pub fn find(name: []const u8) ?Setting { @@ -1699,6 +1706,7 @@ pub const Runtime = struct { .placement => "pardes", .boot_shell => "replace", .look_word => "list", + .pager => "off", }, .lift => "rim", .motion => "playful", @@ -1768,6 +1776,7 @@ pub const Runtime = struct { .placement => "Placement pardes\n", .boot_shell => "BootShell replace\n", .look_word => "LookWord list\n", + .pager => "Pager off\n", }, .lift => "Lift rim\n", .motion => "Motion playful\n", diff --git a/src/host_io.zig b/src/host_io.zig index 8ddb0c90..4ebac9ee 100644 --- a/src/host_io.zig +++ b/src/host_io.zig @@ -1255,7 +1255,12 @@ pub const ChildEnv = struct { return line[0 .. std.mem.indexOfScalar(u8, line, '=') orelse line.len]; } - pub fn build(slots: *Slots) ?[*:null]const ?[*:0]const u8 { + /// Which pager a child is given where the user's environment names none: + /// a command pane's one-shot shell `cat` (its output is a pane already), + /// a terminal's shell `pardes -` (a +Pager pane) unless `Pager off`. + pub const Paging = enum { command, terminal, terminal_off }; + + pub fn build(slots: *Slots, paging: Paging) ?[*:null]const ?[*:0]const u8 { var n: usize = 0; var i: usize = 0; while (libc.environ[i]) |entry| : (i += 1) { @@ -1268,9 +1273,15 @@ pub const ChildEnv = struct { slots[n] = entry; n += 1; } - // No pager to wait in: a pty/run or a command pane's output is read - // whole, and less would hold it at its first screen for ever. Only - // where the inherited environment chose none. + // No pager to wait in (less holds a run at its first screen for + // ever): a command pane's output is read whole, through cat; a + // terminal's goes to a +Pager pane. Only where the inherited + // environment chose none. + const defaults: []const [*:0]const u8 = switch (paging) { + .command => &cat_pagers, + .terminal => pardesPagers(), + .terminal_off => &.{}, + }; for (defaults) |default| { const set = for (libc.environ[0..i]) |entry| { if (std.mem.eql(u8, name(entry.?), name(default))) break true; @@ -1288,8 +1299,27 @@ pub const ChildEnv = struct { return @ptrCast(slots); } - /// Set for a pane's child only when the user's environment has none. - const defaults = [_][*:0]const u8{ "PAGER=cat", "GIT_PAGER=cat" }; + const cat_pagers = [_][*:0]const u8{ "PAGER=cat", "GIT_PAGER=cat" }; + + /// `PAGER=' -'`, its own path so no PATH lookup can find + /// another; plain `pardes -` where the path cannot be read or quoted. + fn pardesPagers() []const [*:0]const u8 { + const S = struct { + var pager: [std.fs.max_path_bytes + 16:0]u8 = undefined; + var git_pager: [std.fs.max_path_bytes + 16:0]u8 = undefined; + var entries: [2][*:0]const u8 = undefined; + var ready = false; + }; + if (!S.ready) { + var exe_buf: [std.fs.max_path_bytes]u8 = undefined; + const n = if (comptime builtin.os.tag == .linux) libc.readlink("/proc/self/exe", &exe_buf, exe_buf.len) else -1; + const exe: []const u8 = if (n > 0 and @as(usize, @intCast(n)) < exe_buf.len and std.mem.indexOfScalar(u8, exe_buf[0..@intCast(n)], '\'') == null) exe_buf[0..@intCast(n)] else "pardes"; + S.entries[0] = if (std.fmt.bufPrintSentinel(&S.pager, "PAGER='{s}' -", .{exe}, 0)) |t| t.ptr else |_| "PAGER=pardes -"; + S.entries[1] = if (std.fmt.bufPrintSentinel(&S.git_pager, "GIT_PAGER='{s}' -", .{exe}, 0)) |t| t.ptr else |_| "GIT_PAGER=pardes -"; + S.ready = true; + } + return &S.entries; + } }; test "the child environment replaces the launcher's terminal identity exactly once" { @@ -1314,7 +1344,24 @@ test "the child environment replaces the launcher's terminal identity exactly on defer _ = unsetenv("PARDES_CHILD_ENV_PROBE"); var slots: ChildEnv.Slots = undefined; - const envp = ChildEnv.build(&slots) orelse return error.EnvironmentTooLarge; + // Where the user named no pager: a terminal's shell pages into a + // +Pager pane (`pardes -`), or, Pager off, as the environment says; a + // command pane's through cat. A pager the user named is kept. + for ([_]ChildEnv.Paging{ .terminal, .terminal_off }) |paging| { + var shell_slots: ChildEnv.Slots = undefined; + const shell_envp = ChildEnv.build(&shell_slots, paging) orelse return error.EnvironmentTooLarge; + var said: usize = 0; + var j: usize = 0; + while (shell_envp[j]) |entry| : (j += 1) { + const line = std.mem.span(entry); + if (std.mem.startsWith(u8, line, "PAGER=") and std.c.getenv("PAGER") == null) { + try std.testing.expect(paging == .terminal and std.mem.endsWith(u8, line, " -")); + said += 1; + } + } + if (std.c.getenv("PAGER") == null) try std.testing.expectEqual(@as(usize, if (paging == .terminal) 1 else 0), said); + } + const envp = ChildEnv.build(&slots, .command) orelse return error.EnvironmentTooLarge; var terms: usize = 0; var colorterms: usize = 0; var probes: usize = 0; @@ -1442,7 +1489,10 @@ pub fn forkShell( // not call setenv, whose malloc can deadlock against a pty reader thread // that held the heap when the fork took its snapshot. var env_slots: ChildEnv.Slots = undefined; - const envp = ChildEnv.build(&env_slots); + const paging: ChildEnv.Paging = if (one_line != null) + .command + else if (core) |c| (if (c.settings.pager == .off) .terminal_off else .terminal) else .terminal; + const envp = ChildEnv.build(&env_slots, paging); const ws = posix.winsize{ .row = rows, .col = cols, .xpixel = 0, .ypixel = 0 }; // The child says here why it could not become the shell (its chdir or // its exec failed, as for a script whose interpreter is not there): the diff --git a/src/main.zig b/src/main.zig index 9dce559f..8818645e 100644 --- a/src/main.zig +++ b/src/main.zig @@ -46,11 +46,13 @@ pub const debug = if (is_emscripten) struct {} else struct { }; const help_text = - \\Usage: pardes [options] [file|dir] + \\Usage: pardes [options] [file|dir|-] \\ \\With no arguments the shell pane starts in tty mode. A FILE argument \\(optionally file:LINE) opens it alone, filling the window; a DIRECTORY - \\argument becomes the cwd shells spawn in. + \\argument becomes the cwd shells spawn in. `-` reads stdin, its terminal + \\escapes stripped, into a +Pager pane: inside a pardes pane the outer + \\session's, returning at once (a terminal's PAGER), else a new editor's. \\ \\Options: \\ --tty start as one shell pane already in tty mode @@ -98,6 +100,95 @@ const help_text = \\ ; +/// Stdin to its end, its terminal escapes stripped (a pager's input is +/// coloured for a terminal; a text pane shows text), at most a file's +/// limit, a longer one cut there and said so at its end. +fn readStdinText(gpa: std.mem.Allocator) ![]u8 { + const limit = pardes.memory.limits.max_file_bytes; + var raw: std.ArrayList(u8) = .empty; + var chunk: [64 * 1024]u8 = undefined; + var cut = false; + while (true) { + const n = std.c.read(0, &chunk, chunk.len); + if (n < 0) { + if (std.posix.errno(n) == .INTR) continue; + return error.ReadFailed; + } + if (n == 0) break; + const got: usize = @intCast(n); + if (raw.items.len + got > limit) { + try raw.appendSlice(gpa, chunk[0 .. limit - raw.items.len]); + cut = true; + break; + } + try raw.appendSlice(gpa, chunk[0..got]); + } + var text = try stripEscapes(gpa, raw.items); + if (cut) { + const said = "\n[pardes: the rest of stdin is cut: a pane holds at most a file's limit]\n"; + text = try std.mem.concat(gpa, u8, &.{ text, said }); + } + return text; +} + +/// `bytes` without terminal escapes: CSI (`ESC [` ... a final byte, SGR +/// colour among them), OSC (`ESC ]` ... BEL or `ESC \`), any other +/// two-byte `ESC x`, and a man page's overstrike (`x BS x`, `_ BS x`). +pub fn stripEscapes(gpa: std.mem.Allocator, bytes: []const u8) ![]u8 { + var out = try std.ArrayList(u8).initCapacity(gpa, bytes.len); + var i: usize = 0; + while (i < bytes.len) { + const c = bytes[i]; + if (c == 0x1b and i + 1 < bytes.len) { + const kind = bytes[i + 1]; + i += 2; + if (kind == '[') { + while (i < bytes.len and !(bytes[i] >= 0x40 and bytes[i] <= 0x7e)) i += 1; + i += 1; + } else if (std.mem.indexOfScalar(u8, "()*+", kind) != null) { + i += 1; // a charset's name after it + } else if (kind == ']') { + while (i < bytes.len) : (i += 1) { + if (bytes[i] == 0x07) { + i += 1; + break; + } + if (bytes[i] == 0x1b and i + 1 < bytes.len and bytes[i + 1] == '\\') { + i += 2; + break; + } + } + } + continue; + } + // Overstrike: the byte before a backspace is struck over. + if (c == 0x08) { + if (out.items.len > 0) _ = out.pop(); + i += 1; + continue; + } + out.appendAssumeCapacity(c); + i += 1; + } + return out.toOwnedSlice(gpa); +} + +test "stripEscapes takes out colour, other escapes and overstrike, and keeps the text" { + const gpa = std.testing.allocator; + const cases = [_][2][]const u8{ + .{ "\x1b[33mcommit abc\x1b[m\n", "commit abc\n" }, + .{ "a\x1b]8;;http://x\x1b\\link\x1b]8;;\x07b", "alinkb" }, + .{ "N\x08NA\x08AM\x08ME\x08E _\x08u", "NAME u" }, + .{ "plain\ttext\n", "plain\ttext\n" }, + .{ "\x1b(Bdone", "done" }, + }; + for (cases) |c| { + const got = try stripEscapes(gpa, c[0]); + defer gpa.free(got); + try std.testing.expectEqualStrings(c[1], got); + } +} + /// A forwarding failure in words, never an error's name: the ones this /// file raises said outright, any other as its name's words (`NotFound`, /// `not found`), a dial's as Messages says it. @@ -369,7 +460,8 @@ fn nativeMain(init: std.process.Init) !void { } else if (std.mem.eql(u8, a, "--version")) { try std.Io.File.stdout().writeStreamingAll(init.io, version_text); return; - } else if (a.len > 0 and a[0] != '-' and positional == null) { + } else if (a.len > 0 and (a[0] != '-' or std.mem.eql(u8, a, "-")) and positional == null) { + // `-` is stdin, as for cat and vim: a text to show. session_only = false; positional = a; } else if (a.len == 0) { @@ -440,6 +532,24 @@ fn nativeMain(init: std.process.Init) !void { // itself, which is what a right click in that pane would have been. var look_buf: [64]u8 = undefined; const look = try std.fmt.bufPrint(&look_buf, "/pane/{d}/look", .{parent.serial}); + // `pardes -`: stdin read to its end, a +Pager pane of the session + // made of it (as acme's `B` has no stdin, through pane/new, a name + // and the body), and back at once: the PAGER a pane's shell gets. + if (positional) |word| if (std.mem.eql(u8, word, "-")) { + const text = readStdinText(arena) catch |err| Refuse.with(init.io, "stdin", err); + const made = ninep_io.Client.read(arena, parent.dial, "/pane/new", "/pane/new") catch |err| Refuse.with(init.io, "-", err); + const serial = std.fmt.parseInt(u32, std.mem.trim(u8, made, " \n"), 10) catch |err| Refuse.with(init.io, "-", err); + var cwd_buf: [4096]u8 = undefined; + const cwd = if (std.c.getcwd(&cwd_buf, cwd_buf.len)) |c| std.mem.span(@as([*:0]u8, @ptrCast(c))) else "/"; + var path_buf: [64]u8 = undefined; + var line_buf: [4200]u8 = undefined; + const name_line = std.fmt.bufPrint(&line_buf, "{s}/+Pager\n", .{std.mem.trimEnd(u8, cwd, "/")}) catch "/+Pager\n"; + ninep_io.Client.write(arena, parent.dial, try std.fmt.bufPrint(&path_buf, "/pane/{d}/name", .{serial}), name_line) catch |err| Refuse.with(init.io, "-", err); + if (text.len > 0) ninep_io.Client.write(arena, parent.dial, try std.fmt.bufPrint(&path_buf, "/pane/{d}/body", .{serial}), text) catch |err| Refuse.with(init.io, "-", err); + // Shown, not edited: nothing to ask about at Exit. + ninep_io.Client.write(arena, parent.dial, try std.fmt.bufPrint(&path_buf, "/pane/{d}/ctl", .{serial}), "clean\n") catch {}; + return; + }; const typed_word = positional orelse { var tag_buf: [64]u8 = undefined; const tag = try std.fmt.bufPrint(&tag_buf, "/pane/{d}/tag", .{parent.serial}); @@ -530,6 +640,12 @@ fn nativeMain(init: std.process.Init) !void { if (wait) waitForDel(init.io, arena, parent.dial, path, made_serial); return; } + // `pardes -` outside a session: an editor whose first pane holds stdin, + // as `vim -` does; the terminal is /dev/tty, never stdin. + if (positional) |a| if (std.mem.eql(u8, a, "-")) { + opts.stdin_text = readStdinText(arena) catch |err| badArgs(init.io, "stdin: {s}", .{@errorName(err)}); + positional = null; + }; if (positional) |a| { const target = @import("look.zig").parsePathLine(a); if (std.mem.eql(u8, target.path, "/n") or std.mem.startsWith(u8, target.path, "/n/") or diff --git a/src/ninep/ctl.zig b/src/ninep/ctl.zig index e0c4b21b..87339b70 100644 --- a/src/ninep/ctl.zig +++ b/src/ninep/ctl.zig @@ -1812,6 +1812,17 @@ test "a look at a file it may not read fails the write naming the file" { try testing.expectEqualStrings(expected, refused.reply.ename); } +test "Pager is a setting of the root ctl: pardes by default, off taken, anything else refused with its choices" { + const p = try withFile(testing.allocator, "x\n"); + defer p.deinit(); + const root_ctl = @intFromEnum(tree.TopFile.ctl); + try testing.expect(std.mem.indexOf(u8, rd(p, root_ctl, 0, 1 << 16).bytes, "Pager pardes\n") != null); + try testing.expectEqual(Status.ok, wr(p, root_ctl, "Pager off\n").reply.status); + try testing.expectEqual(config.Runtime.Pager.off, p.settings.pager); + try testing.expect(std.mem.indexOf(u8, rd(p, root_ctl, 0, 1 << 16).bytes, "Pager off\n") != null); + try testing.expectEqualStrings("bad value in control message; takes pardes, off \"Pager\"", wr(p, root_ctl, "Pager less\n").reply.ename); +} + test "a refused Del written back through event fails that write, EIO, with its err" { const gpa = testing.allocator; const p = try withFile(gpa, "text\n"); diff --git a/src/pardes.zig b/src/pardes.zig index 47ebf8fa..aa2c252c 100644 --- a/src/pardes.zig +++ b/src/pardes.zig @@ -4180,6 +4180,8 @@ pub const Boot = enum { document, /// a Look that found nothing: reported, not opened missing, + /// `pardes -`: stdin's text in a +Pager pane, as `vim -` shows it + stdin, /// the firmware's boot buffer, the only pane a board has embedded, /// the bare tty startup: one shell in raw tty mode, with an empty text @@ -4196,6 +4198,7 @@ pub const Boot = enum { if (opts.boot) |named| return named; if (opts.file != null) return .document; if (opts.missing != null) return .missing; + if (opts.stdin_text != null) return .stdin; if (comptime platform == .esp32p4) return .embedded; if (opts.tty_only) return .tty_shell; // ponytail: 1 and 3 are the only shell counts anyone asked for @@ -4215,6 +4218,8 @@ pub const Options = struct { file: ?[]const u8 = null, file_line: usize = 0, missing: ?struct { word: []const u8, dir: []const u8 } = null, + /// `pardes -`: stdin, its escapes stripped, for a +Pager pane at boot. + stdin_text: ?[]const u8 = null, tty_toggle: u21 = config.tty_toggle_default, /// load a dump of another instance instead of spawning shells (acme -l) load_path: ?[]const u8 = null, @@ -4626,6 +4631,17 @@ pub const Pardes = struct { _ = try panes.Output.open(p, 0, missing.dir, .errors, "", content); p.oneColumn(); }, + .stdin => { + const content = try gpa.dupe(u8, opts.stdin_text.?); + errdefer gpa.free(content); + const dir = p.sessionDir(); + const shown = try panes.Output.open(p, 0, dir, .{ .cmd = .New }, "", content); + // Named +Pager, as `pardes -` inside a session names its pane. + const named = try std.fs.path.join(gpa, &.{ dir, "+Pager" }); + gpa.free(shown.file.?.path); + shown.file.?.path = named; + p.oneColumn(); + }, .embedded => { const content = try p.gpa.dupe(u8, boot_buffer); errdefer p.gpa.free(content); diff --git a/test/fs.py b/test/fs.py index 23647b45..282cca8b 100644 --- a/test/fs.py +++ b/test/fs.py @@ -479,6 +479,22 @@ def run_file(binary): assert run(client, term, b'fi\n') == b'error not run\n' # a syntax error runs nothing assert run(client, term, b"echo 'open\n") == b'error not run\n' # nor does an open quote assert run(client, term, b'true\n') == b'exit 0\n' # ...and the shell is clear after + # A paging command run through pty/run does not wait in less: the + # terminal's PAGER is `pardes -`, and its text is a +Pager pane. + if shutil.which('git'): + repo = root / 'pagedrepo' + repo.mkdir() + git = ['git', '-C', str(repo), '-c', 'user.name=p', '-c', 'user.email=p@x'] + subprocess.run(git + ['init', '-q'], check=True, env=dict(os.environ, HOME=str(root))) + (repo / 'f').write_text('x\n') + subprocess.run(git + ['add', 'f'], check=True, env=dict(os.environ, HOME=str(root))) + subprocess.run(git + ['commit', '-qm', 'paged-commit-subject'], check=True, env=dict(os.environ, HOME=str(root))) + assert run(client, term, b'git -C pagedrepo log\n').startswith(b'exit 0\n') + pager = [r.split()[0].decode() for r in client.read('/index').splitlines() if r.split()[3:4] == [f'{repo}/+Pager'.encode()]] # git -C runs it in the repo + assert len(pager) == 1, client.read('/index') + assert b'paged-commit-subject' in client.read(f'/pane/{pager[0]}/body') + assert b'\x1b' not in client.read(f'/pane/{pager[0]}/body') + client.remove(f'/pane/{pager[0]}') # A pty is not given one row (it loses the prompt's input mark, # and the shell would read busy for ever): refused, and said. try: @@ -1421,6 +1437,17 @@ def test(binary, quic=False): # A pane address the session has not is refused in words, exit # 1, no pane made for a file of that name; one it has is looked # at. A name with a newline is said in words, not an error name. + # `pardes -` (a terminal's PAGER): stdin, its escapes stripped, in a + # +Pager pane of the session, clean, and back at once. + fed = subprocess.run([binary, '-'], cwd=root, env=env, input=b'\x1b[1mbold\x1b[0m text\n', + stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=10) + assert fed.returncode == 0, fed.stderr + made_now, = serials() - before + assert client.read(f'/pane/{made_now}/name') == f'{root}/+Pager\n'.encode() + assert client.read(f'/pane/{made_now}/body') == b'bold text\n' + row = [r for r in client.read('/index').splitlines() if r.split()[0] == str(made_now).encode()][0] + assert row.split()[2] == b'0', row # clean: nothing to ask at Exit + client.remove(f'/pane/{made_now}') # A new name in a directory there but not writable: refused now, # not a pane that only fails at Save. shut = root / 'shut-dir' @@ -1450,6 +1477,30 @@ def test(binary, quic=False): assert orphan.poll() is None assert orphan.wait(timeout=5) == 1 + # `pardes -` outside a session: an editor whose first pane is a + # +Pager of stdin, as `vim -`; here a detached one, to read it. + outside_env = {k: v for k, v in os.environ.items() if not k.startswith('PARDES_')} + outside_env.update(HOME=str(root), XDG_RUNTIME_DIR=str(root), PARDES_NOTIME='1') + boot = subprocess.Popen([binary, '--detach=stdinboot', '-'], cwd=root, env=outside_env, + stdin=subprocess.PIPE, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE, + start_new_session=True) + try: + boot.stdin.write(b'\x1b[32mfrom stdin\x1b[m\nsecond\n') + boot.stdin.close() + sock = root / 'pardes-9p-stdinboot.sock' + deadline = time.monotonic() + 10 + while not sock.exists(): + assert boot.poll() is None, boot.stderr.read() + assert time.monotonic() < deadline, 'the stdin boot never listened' + time.sleep(.05) + with Client(str(sock)) as booted: + first = booted.read('/index').split(b'\n')[0].split() + assert first[3] == f'{root}/+Pager'.encode(), first + assert booted.read(f'/pane/{first[0].decode()}/body') == b'from stdin\nsecond\n' + finally: + boot.terminate() + boot.wait(timeout=10) + # Killed with SIGTERM or SIGHUP, a tty editor puts its terminal # back (main screen, cooked mode) before it dies: a nested one # killed in a pane leaves that pane usable. -- cgit v1.3 From 77bda7e14e0ea81db5da54c233fc30d218773f47 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Thu, 1 Oct 2026 01:14:37 -0300 Subject: pardes - keeps one +Pager per directory, refilled, named so from its first log record; streams the text in bounded writes; never loses it; handles \r, NUL and BEL as a terminal does Each paged command made another +Pager until placement failed, and then git's text was lost with exit 0; a 130 MB page timed out half written and dirty; a directory whose name held a newline left a stray +New; and the log said new +New then rename. The root ctl's `pager ` now makes the directory's +Pager (named before it is announced, placed without the keyboard) or empties the one there; the text goes into it a line-ended 8 MiB chunk a write, one undo step, up to the file limit and its note, and is left clean. A directory a ctl line cannot name pages into the session's. Any failure prints the text to stderr with why and exits 1. A carriage return keeps a progress line's last state and CRLF is a newline; NUL, BEL, SO and SI go; empty stdin makes no pane. Co-Authored-By: Claude Opus 5.5 --- src/Output.zig | 43 +++++++++++++++++++++++++++ src/main.zig | 88 ++++++++++++++++++++++++++++++++++++++++++++++++------- src/ninep/ctl.zig | 12 ++++++++ test/fs.py | 25 ++++++++++++++++ 4 files changed, 157 insertions(+), 11 deletions(-) (limited to 'src/main.zig') diff --git a/src/Output.zig b/src/Output.zig index 1160c455..e6448e36 100644 --- a/src/Output.zig +++ b/src/Output.zig @@ -666,6 +666,49 @@ pub fn openUnsaved(p: *Pardes, id: usize, content: []u8) void { p.active = id; } +/// `pardes -`'s pane: the one `/+Pager`, emptied for the next paged +/// text when it is there (a directory's paged commands refill it, as its +/// command pane is reused), else made, named so before it is announced, +/// and placed wherever there is room without taking the keyboard. `dir` +/// empty (or not absolute): the session's directory. Its id; NoPaneRoom +/// or NoPaneSlots when it has no room at all. +pub fn openPager(p: *Pardes, from: usize, dir_arg: []const u8) !usize { + const dir = if (dir_arg.len > 0 and dir_arg[0] == '/') dir_arg else p.sessionDir(); + const path = try std.fs.path.join(p.gpa, &.{ dir, "+Pager" }); + for (p.panes, 0..) |slot, i| { + const pane = slot orelse continue; + const f = if (pane.file) |*file| file else continue; + if (!std.mem.eql(u8, f.path, path)) continue; + p.gpa.free(path); + File.setContent(p, f, try p.gpa.alloc(u8, 0)); + resetBody(p, pane); + f.saved_revision = f.revision; + return i; + } + const free = p.freeSlot() orelse { + p.gpa.free(path); + return error.NoPaneSlots; + }; + const empty = p.gpa.alloc(u8, 0) catch |err| { + p.gpa.free(path); + return err; + }; + const pane = open(p, free, dir, .{ .cmd = .New }, "", empty) catch |err| { + p.gpa.free(path); + return err; + }; + // The pane owns the name from here. + p.gpa.free(pane.file.?.path); + pane.file.?.path = path; + const keyboard = p.active; + exec.placeNew(p, from, null, free, .fs); + if (p.unplaced.isSet(free)) return error.NoPaneRoom; + // Shown, not asked for: the keyboard stays where it was, as a command + // pane's does. + if (p.panes[keyboard] != null) p.active = keyboard; + return free; +} + /// Pane `gone` closed: its row goes from +Unsaved, which lists only panes /// still there to lose. pub fn dropUnsaved(p: *Pardes, gone: *const Pane) void { diff --git a/src/main.zig b/src/main.zig index 8818645e..6627bece 100644 --- a/src/main.zig +++ b/src/main.zig @@ -100,6 +100,58 @@ const help_text = \\ ; +/// `pardes -` inside a session: `text` into the directory's one +Pager +/// (root ctl `pager `, refilled when it is there), streamed into its +/// body a bounded chunk at a time as one undo step, and left clean. A text +/// the session would not take is never lost: it goes to stderr, with why, +/// and the exit is 1. +fn pageInto(io: std.Io, gpa: std.mem.Allocator, dial: []const u8, text: []const u8) void { + const Fail = struct { + fn with(o: std.Io, t: []const u8, what: []const u8, err: anyerror) noreturn { + var words_buf: [128]u8 = undefined; + const why = if (err == error.Remote) ninep_io.Client.lastSaid() else forwardWords(err, &words_buf); + var buf: [512]u8 = undefined; + const head = std.fmt.bufPrint(&buf, "pardes: -: {s}: {s}; the text follows\n", .{ what, why }) catch "pardes: -: refused; the text follows\n"; + std.Io.File.stderr().writeStreamingAll(o, head) catch {}; + std.Io.File.stderr().writeStreamingAll(o, t) catch {}; + std.process.exit(1); + } + }; + // The pane's directory: this one, unless its name could not be one line + // of a ctl (a newline, a control byte): then the session's. + var cwd_buf: [4096]u8 = undefined; + const cwd: []const u8 = if (std.c.getcwd(&cwd_buf, cwd_buf.len)) |c| std.mem.span(@as([*:0]u8, @ptrCast(c))) else ""; + const plain = for (cwd) |c| { + if (c < ' ' or c == 0x7f) break false; + } else true; + var line_buf: [4200]u8 = undefined; + const ctl_line = std.fmt.bufPrint(&line_buf, "pager {s}\n", .{if (plain) cwd else ""}) catch "pager\n"; + ninep_io.Client.write(gpa, dial, "/ctl", ctl_line) catch |err| Fail.with(io, text, "no +Pager pane", err); + const answer = ninep_io.Client.read(gpa, dial, "/exec", "/exec") catch |err| Fail.with(io, text, "no +Pager pane", err); + const serial = std.fmt.parseInt(u32, std.mem.trim(u8, answer, " \n"), 10) catch |err| Fail.with(io, text, "no +Pager pane", err); + var path_buf: [64]u8 = undefined; + const mark = std.fmt.bufPrint(&path_buf, "/pane/{d}/mark", .{serial}) catch unreachable; + // One undo step for the whole text, however many writes carry it. + ninep_io.Client.write(gpa, dial, mark, "0\n") catch |err| Fail.with(io, text, "the +Pager pane went", err); + var body_buf: [64]u8 = undefined; + const body = std.fmt.bufPrint(&body_buf, "/pane/{d}/body", .{serial}) catch unreachable; + // A chunk ends on a line's end (never inside a character), each its own + // write with its own deadline, so a large text arrives whole. + const chunk_max = 8 * 1024 * 1024; + var at: usize = 0; + while (at < text.len) { + var end = @min(text.len, at + chunk_max); + if (end < text.len) if (std.mem.lastIndexOfScalar(u8, text[at..end], '\n')) |nl| { + end = at + nl + 1; + }; + ninep_io.Client.write(gpa, dial, body, text[at..end]) catch |err| Fail.with(io, text[at..], "the +Pager pane would not take it", err); + at = end; + } + ninep_io.Client.write(gpa, dial, mark, "1\n") catch {}; + var ctl_buf: [64]u8 = undefined; + ninep_io.Client.write(gpa, dial, std.fmt.bufPrint(&ctl_buf, "/pane/{d}/ctl", .{serial}) catch unreachable, "clean\n") catch {}; +} + /// Stdin to its end, its terminal escapes stripped (a pager's input is /// coloured for a terminal; a text pane shows text), at most a file's /// limit, a longer one cut there and said so at its end. @@ -167,6 +219,23 @@ pub fn stripEscapes(gpa: std.mem.Allocator, bytes: []const u8) ![]u8 { i += 1; continue; } + // A carriage return: CRLF is a newline; alone, the line starts + // over, as on a terminal, so a progress line keeps its last state. + if (c == '\r') { + if (i + 1 < bytes.len and bytes[i + 1] == '\n') { + i += 1; + continue; + } + const line_start = if (std.mem.lastIndexOfScalar(u8, out.items, '\n')) |nl| nl + 1 else 0; + out.shrinkRetainingCapacity(line_start); + i += 1; + continue; + } + // Bytes a terminal acts on and never shows: NUL, BEL, SO, SI. + if (c == 0 or c == 0x07 or c == 0x0e or c == 0x0f) { + i += 1; + continue; + } out.appendAssumeCapacity(c); i += 1; } @@ -181,6 +250,9 @@ test "stripEscapes takes out colour, other escapes and overstrike, and keeps the .{ "N\x08NA\x08AM\x08ME\x08E _\x08u", "NAME u" }, .{ "plain\ttext\n", "plain\ttext\n" }, .{ "\x1b(Bdone", "done" }, + .{ "a\r\nb\r\n", "a\nb\n" }, + .{ "10%\r50%\r100%\ndone\n", "100%\ndone\n" }, + .{ "x\x00y\x07z\x0e\x0f\n", "xyz\n" }, }; for (cases) |c| { const got = try stripEscapes(gpa, c[0]); @@ -537,17 +609,9 @@ fn nativeMain(init: std.process.Init) !void { // and the body), and back at once: the PAGER a pane's shell gets. if (positional) |word| if (std.mem.eql(u8, word, "-")) { const text = readStdinText(arena) catch |err| Refuse.with(init.io, "stdin", err); - const made = ninep_io.Client.read(arena, parent.dial, "/pane/new", "/pane/new") catch |err| Refuse.with(init.io, "-", err); - const serial = std.fmt.parseInt(u32, std.mem.trim(u8, made, " \n"), 10) catch |err| Refuse.with(init.io, "-", err); - var cwd_buf: [4096]u8 = undefined; - const cwd = if (std.c.getcwd(&cwd_buf, cwd_buf.len)) |c| std.mem.span(@as([*:0]u8, @ptrCast(c))) else "/"; - var path_buf: [64]u8 = undefined; - var line_buf: [4200]u8 = undefined; - const name_line = std.fmt.bufPrint(&line_buf, "{s}/+Pager\n", .{std.mem.trimEnd(u8, cwd, "/")}) catch "/+Pager\n"; - ninep_io.Client.write(arena, parent.dial, try std.fmt.bufPrint(&path_buf, "/pane/{d}/name", .{serial}), name_line) catch |err| Refuse.with(init.io, "-", err); - if (text.len > 0) ninep_io.Client.write(arena, parent.dial, try std.fmt.bufPrint(&path_buf, "/pane/{d}/body", .{serial}), text) catch |err| Refuse.with(init.io, "-", err); - // Shown, not edited: nothing to ask about at Exit. - ninep_io.Client.write(arena, parent.dial, try std.fmt.bufPrint(&path_buf, "/pane/{d}/ctl", .{serial}), "clean\n") catch {}; + // Nothing paged: no pane, and done. + if (text.len == 0) return; + pageInto(init.io, arena, parent.dial, text); return; }; const typed_word = positional orelse { @@ -644,6 +708,8 @@ fn nativeMain(init: std.process.Init) !void { // as `vim -` does; the terminal is /dev/tty, never stdin. if (positional) |a| if (std.mem.eql(u8, a, "-")) { opts.stdin_text = readStdinText(arena) catch |err| badArgs(init.io, "stdin: {s}", .{@errorName(err)}); + // Nothing paged: nothing to show. + if (opts.stdin_text.?.len == 0) return; positional = null; }; if (positional) |a| { diff --git a/src/ninep/ctl.zig b/src/ninep/ctl.zig index fd3418a1..82001f32 100644 --- a/src/ninep/ctl.zig +++ b/src/ninep/ctl.zig @@ -642,6 +642,18 @@ pub fn writeRoot(p: *Pardes, req: Req) Reply { var it = Messages.init(p, req.data); while (it.next()) |line| { if (line.len == 0 or exec_line.isComment(line)) continue; + // `pardes -`'s: the directory's +Pager made or emptied, its + // serial what /exec reads back. + if (std.mem.startsWith(u8, line, "pager ") or std.mem.eql(u8, line, "pager")) { + if (!apply) continue; + const id = pardes.panes.Output.openPager(p, p.active, std.mem.trim(u8, line["pager".len..], " \t")) catch |err| + return tree.failText(req.tag, if (err == error.NoPaneRoom or err == error.NoPaneSlots) E.NOSPC else E.IO, switch (err) { + error.NoPaneRoom, error.NoPaneSlots => "pager: no space for a +Pager pane", + else => "pager: could not make a +Pager pane", + }); + noteResult(p, p.panes[id].?.serial); + continue; + } if (std.mem.startsWith(u8, line, "size ") or std.mem.eql(u8, line, "size")) { const size = sizeOf(line) orelse return refuse(p, req, e_size, line); // A frontend's window is the size; only a session none is diff --git a/test/fs.py b/test/fs.py index fce315fc..b2f52c3e 100644 --- a/test/fs.py +++ b/test/fs.py @@ -1456,7 +1456,32 @@ def test(binary, quic=False): assert client.read(f'/pane/{made_now}/body') == b'bold text\n' row = [r for r in client.read('/index').splitlines() if r.split()[0] == str(made_now).encode()][0] assert row.split()[2] == b'0', row # clean: nothing to ask at Exit + # Its `new` record names it as it is: no +New and a rename. + log_now = client.read('/log').decode() + assert f'\nnew {made_now} {root}/+Pager\n' in '\n' + log_now, log_now[-400:] + assert f'\nrename {made_now} ' not in '\n' + log_now + # The directory's one +Pager: the next paged text refills it. + fed = subprocess.run([binary, '-'], cwd=root, env=env, input=b'again\r\nprogress 10%\rprogress 100%\n', + stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=10) + assert fed.returncode == 0, fed.stderr + assert serials() - before == {made_now}, (serials(), before) + assert client.read(f'/pane/{made_now}/body') == b'again\nprogress 100%\n' client.remove(f'/pane/{made_now}') + # From a directory whose name could not be a ctl line: the + # session's directory's +Pager, the text whole, no stray +New. + odd = root / 'two\nlines' + odd.mkdir() + fed = subprocess.run([binary, '-'], cwd=odd, env=env, input=b'odd dir text\n', + stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=10) + assert fed.returncode == 0, fed.stderr + odd_pane, = serials() - before + assert client.read(f'/pane/{odd_pane}/name') == f'{root}/+Pager\n'.encode() + assert client.read(f'/pane/{odd_pane}/body') == b'odd dir text\n' + client.remove(f'/pane/{odd_pane}') + # Nothing on stdin: no pane, and done. + fed = subprocess.run([binary, '-'], cwd=root, env=env, input=b'', + stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=10) + assert fed.returncode == 0 and serials() == before, (fed, serials()) # A new name in a directory there but not writable: refused now, # not a pane that only fails at Save. shut = root / 'shut-dir' -- cgit v1.3 From 803f2a2678a8aa8f89b0663a84a60721d36f5831 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Thu, 1 Oct 2026 02:33:14 -0300 Subject: pardes - writes the whole text through one open of the body, so a page over 8 MiB arrives whole, not as its last chunk Each 8 MiB chunk went in by its own Client.write, which opens a body with OTRUNC, so every chunk replaced the one before and a long page kept only its tail, with exit 0. The text now goes in through one open, truncated once and written at rising offsets; a long write is timed by its progress, each 9P write answered within 30 s rather than the whole transfer within 2. fs.py pages 11 MiB of numbered lines and compares the body byte for byte, and pages past the 256 MiB cap and checks the first 256 MiB and the cut note. Co-Authored-By: Claude Opus 5.5 --- src/9p_io.zig | 8 ++++++++ src/main.zig | 24 +++++------------------- test/fs.py | 23 +++++++++++++++++++++++ 3 files changed, 36 insertions(+), 19 deletions(-) (limited to 'src/main.zig') diff --git a/src/9p_io.zig b/src/9p_io.zig index 6cf75c99..d80d7b30 100644 --- a/src/9p_io.zig +++ b/src/9p_io.zig @@ -1937,6 +1937,8 @@ test "9P shell environment states being inside pardes apart from how to reach it pub const Client = struct { pub const budget_ms: i64 = 2000; + /// Each write of a long one has this long to be answered (transact). + pub const write_budget_ms: i64 = 30_000; pub const max_depth: usize = 2 * ninep.max_welem; @@ -2211,6 +2213,12 @@ pub const Client = struct { const count = (try s.ask(.{ .write = .{ .fid = cur, .offset = written, .data = chunk } }, remote)).write; if (count == 0 or count > chunk.len) return Error.Botch; written += count; + // A long write is timed by its progress: each answer gives + // the next its own budget, so a large body (`pardes -`) goes + // in through one open, whole, however long it takes. The + // budget is a write's: a server putting in tens of MiB it + // held (pane.zig batchFor) answers that one write late. + s.deadline = nowMs() +| write_budget_ms; } return; } diff --git a/src/main.zig b/src/main.zig index 6627bece..1075b596 100644 --- a/src/main.zig +++ b/src/main.zig @@ -101,8 +101,8 @@ const help_text = ; /// `pardes -` inside a session: `text` into the directory's one +Pager -/// (root ctl `pager `, refilled when it is there), streamed into its -/// body a bounded chunk at a time as one undo step, and left clean. A text +/// (root ctl `pager `, refilled when it is there), written into its +/// body through one open, as one undo step, and left clean. A text /// the session would not take is never lost: it goes to stderr, with why, /// and the exit is 1. fn pageInto(io: std.Io, gpa: std.mem.Allocator, dial: []const u8, text: []const u8) void { @@ -129,25 +129,11 @@ fn pageInto(io: std.Io, gpa: std.mem.Allocator, dial: []const u8, text: []const ninep_io.Client.write(gpa, dial, "/ctl", ctl_line) catch |err| Fail.with(io, text, "no +Pager pane", err); const answer = ninep_io.Client.read(gpa, dial, "/exec", "/exec") catch |err| Fail.with(io, text, "no +Pager pane", err); const serial = std.fmt.parseInt(u32, std.mem.trim(u8, answer, " \n"), 10) catch |err| Fail.with(io, text, "no +Pager pane", err); - var path_buf: [64]u8 = undefined; - const mark = std.fmt.bufPrint(&path_buf, "/pane/{d}/mark", .{serial}) catch unreachable; - // One undo step for the whole text, however many writes carry it. - ninep_io.Client.write(gpa, dial, mark, "0\n") catch |err| Fail.with(io, text, "the +Pager pane went", err); + // The whole text through one open of the body (truncated once, then + // written at rising offsets): one undo step, and every byte of it. var body_buf: [64]u8 = undefined; const body = std.fmt.bufPrint(&body_buf, "/pane/{d}/body", .{serial}) catch unreachable; - // A chunk ends on a line's end (never inside a character), each its own - // write with its own deadline, so a large text arrives whole. - const chunk_max = 8 * 1024 * 1024; - var at: usize = 0; - while (at < text.len) { - var end = @min(text.len, at + chunk_max); - if (end < text.len) if (std.mem.lastIndexOfScalar(u8, text[at..end], '\n')) |nl| { - end = at + nl + 1; - }; - ninep_io.Client.write(gpa, dial, body, text[at..end]) catch |err| Fail.with(io, text[at..], "the +Pager pane would not take it", err); - at = end; - } - ninep_io.Client.write(gpa, dial, mark, "1\n") catch {}; + ninep_io.Client.write(gpa, dial, body, text) catch |err| Fail.with(io, text, "the +Pager pane would not take it", err); var ctl_buf: [64]u8 = undefined; ninep_io.Client.write(gpa, dial, std.fmt.bufPrint(&ctl_buf, "/pane/{d}/ctl", .{serial}) catch unreachable, "clean\n") catch {}; } diff --git a/test/fs.py b/test/fs.py index b2f52c3e..789021bd 100644 --- a/test/fs.py +++ b/test/fs.py @@ -1467,6 +1467,29 @@ def test(binary, quic=False): assert serials() - before == {made_now}, (serials(), before) assert client.read(f'/pane/{made_now}/body') == b'again\nprogress 100%\n' client.remove(f'/pane/{made_now}') + # More than one 8 MiB write's worth arrives whole, byte for byte, + # in the one +Pager (each write once replaced the last). + big = b''.join(b'line %08d of the paged text\n' % i for i in range(400000)) # ~11 MiB + assert len(big) > 8 * 1024 * 1024 + fed = subprocess.run([binary, '-'], cwd=root, env=env, input=big, + stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=120) + assert fed.returncode == 0, fed.stderr + big_pane, = serials() - before + assert client.read(f'/pane/{big_pane}/body') == big, 'the paged body is not the text' + # Past the 256 MiB cap: the first 256 MiB, then the cut note. + cap = 256 * 1024 * 1024 + huge = subprocess.Popen(['sh', '-c', f'yes 0123456789abcdef | head -c {cap + 4096}'], stdout=subprocess.PIPE) + fed = subprocess.run([binary, '-'], cwd=root, env=env, stdin=huge.stdout, + stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=600) + huge.wait() + assert fed.returncode == 0, fed.stderr + assert serials() - before == {big_pane} + got = client.read(f'/pane/{big_pane}/body') + note = b'\n[pardes: the rest of stdin is cut: a pane holds at most a file\'s limit]\n' + assert got.endswith(note) and len(got) == cap + len(note), (len(got), got[-120:]) + assert got[:cap] == (b'0123456789abcdef\n' * (cap // 17 + 1))[:cap] + del got, big + client.remove(f'/pane/{big_pane}') # From a directory whose name could not be a ctl line: the # session's directory's +Pager, the text whole, no stray +New. odd = root / 'two\nlines' -- cgit v1.3 From 8dc84e6f9f1c3802f1d28de4d49907381cdf224b Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Thu, 1 Oct 2026 04:00:32 -0300 Subject: pardes - asks /pager for its +Pager and reads the serial on the same open: another client's exec meanwhile can never take the text into its pane pardes - wrote `pager ` to /ctl, then read /exec on a fresh open, which answers the session's last answer: a client that exec'd in between had its pane overwritten by the paged text. /pager takes the directory and answers the +Pager's serial on the open that wrote it, as /pane/new answers its own open; the ctl verb is gone. Client.ask writes and reads on one open. The README's look recipe reads its answer on its own open too. Co-Authored-By: Claude Opus 5.5 --- src/9p_io.zig | 26 ++++++++++++++++++++++++++ src/fs-help.txt | 3 ++- src/main.zig | 9 +++++---- src/ninep/ctl.zig | 53 +++++++++++++++++++++++++++++++++++++++++------------ src/ninep/tree.zig | 26 +++++++++++++++----------- test/fs.py | 2 +- 6 files changed, 90 insertions(+), 29 deletions(-) (limited to 'src/main.zig') diff --git a/src/9p_io.zig b/src/9p_io.zig index b11a4997..9fc19df9 100644 --- a/src/9p_io.zig +++ b/src/9p_io.zig @@ -2319,6 +2319,32 @@ pub const Client = struct { gpa.destroy(s); } + /// Writes `request` to `path` and reads the answer on the same open, + /// as /pane/new answers its own open: a session's last answer, from + /// another client, can never be what comes back. `exec 3<>file`. + pub fn ask(gpa: std.mem.Allocator, dial: []const u8, path: []const u8, request: []const u8) ![]u8 { + if (comptime !supported) return error.Unsupported; + var names: [max_depth][]const u8 = undefined; + const n = try elements(path, &names); + var sock_buf: [sun_path_len]u8 = undefined; + const sock = try resolve(&sock_buf, dial); + var remote: RemoteError = .{}; + errdefer said = remote; + const s = try startSession(gpa, sock, path); + defer endSession(gpa, s); + const fid = (try walkTo(s, names[0..n], &remote)).fid; + _ = try s.ask(.{ .open = .{ .fid = fid, .mode = ninep.ordwr } }, &remote); + _ = try s.ask(.{ .write = .{ .fid = fid, .offset = 0, .data = request } }, &remote); + var out: std.ArrayList(u8) = .empty; + errdefer out.deinit(gpa); + while (true) { + const data = (try s.ask(.{ .read = .{ .fid = fid, .offset = out.items.len, .count = s.cl.maxRead() } }, &remote)).read; + if (data.len == 0) return out.toOwnedSlice(gpa); + if (out.items.len + data.len > 4096) return Error.FileTooLarge; + try out.appendSlice(gpa, data); + } + } + /// Opens `path` on one connection and writes `first` to it (/log's /// `follow new`), all with the usual deadline; then, once `ready(ctx)` /// has said it is not done already, reads it with no deadline, a read at diff --git a/src/fs-help.txt b/src/fs-help.txt index 83aa536f..aea3af5b 100644 --- a/src/fs-help.txt +++ b/src/fs-help.txt @@ -5,6 +5,7 @@ index a line per pane: serial kind(text|term|pdf|image) dirty name column; status pid, version and pane count look write a line: a right click on it at the active pane; read: the serials it touched (this open's) exec write a line: a middle click, a builtin or a shell line; read the same (every exec file) +pager write a directory: its one +Pager, made or emptied; read the same open: its serial (pardes -) log events: new del rename save newcol delcol run exit send ask answer changed dump restore restored restoredcol msg err screen the rendered screen as JSON, frozen from open to close listeners the session's dial addresses @@ -22,7 +23,7 @@ os/, src/ the host filesystem; the editor's own sources $m below: $NINE_MOUNT/pardes/ under 9ns --mntgen; $NINE_MOUNT under 9ns --unix; $PARDES_MOUNT in a Tty9p shell. cat $m/index which panes exist - echo /etc/hosts:3 > $m/look; cat $m/look open a file, see the pane it went to + exec 3<>$m/look; echo /etc/hosts:3 >&3; cat <&3 open a file, see the pane it went to (a fresh open reads the last anyone's) n=$(cat $m/pane/new) make a pane (each open makes one), take its serial printf 'text\n' >> $m/pane/$n/body append to it (> replaces it all) echo 'Msg hello' > $m/exec show text in the editor diff --git a/src/main.zig b/src/main.zig index 1075b596..6c46b22c 100644 --- a/src/main.zig +++ b/src/main.zig @@ -101,7 +101,7 @@ const help_text = ; /// `pardes -` inside a session: `text` into the directory's one +Pager -/// (root ctl `pager `, refilled when it is there), written into its +/// (/pager, refilled when it is there), written into its /// body through one open, as one undo step, and left clean. A text /// the session would not take is never lost: it goes to stderr, with why, /// and the exit is 1. @@ -125,9 +125,10 @@ fn pageInto(io: std.Io, gpa: std.mem.Allocator, dial: []const u8, text: []const if (c < ' ' or c == 0x7f) break false; } else true; var line_buf: [4200]u8 = undefined; - const ctl_line = std.fmt.bufPrint(&line_buf, "pager {s}\n", .{if (plain) cwd else ""}) catch "pager\n"; - ninep_io.Client.write(gpa, dial, "/ctl", ctl_line) catch |err| Fail.with(io, text, "no +Pager pane", err); - const answer = ninep_io.Client.read(gpa, dial, "/exec", "/exec") catch |err| Fail.with(io, text, "no +Pager pane", err); + const dir_line = std.fmt.bufPrint(&line_buf, "{s}\n", .{if (plain) cwd else ""}) catch "\n"; + // Its serial read back on the open that asked: another client's exec + // meanwhile can never send this text into that client's pane. + const answer = ninep_io.Client.ask(gpa, dial, "/pager", dir_line) catch |err| Fail.with(io, text, "no +Pager pane", err); const serial = std.fmt.parseInt(u32, std.mem.trim(u8, answer, " \n"), 10) catch |err| Fail.with(io, text, "no +Pager pane", err); // The whole text through one open of the body (truncated once, then // written at rising offsets): one undo step, and every byte of it. diff --git a/src/ninep/ctl.zig b/src/ninep/ctl.zig index 42b88b91..bcf9ffd6 100644 --- a/src/ninep/ctl.zig +++ b/src/ninep/ctl.zig @@ -640,6 +640,23 @@ pub fn readRoot(p: *Pardes, req: Req) Reply { return tree.stagedReply(p, req); } +/// /pager, `pardes -`'s: the directory written (empty, or not absolute: the +/// session's) gets its one +Pager, made or emptied; the serial is what a +/// read of this same open answers, never another client's. +pub fn writePager(p: *Pardes, req: Req) Reply { + var it = Messages.init(p, req.data); + const line = it.next() orelse ""; + if (it.next() != null) return tree.failText(req.tag, E.INVAL, "pager: one directory a write"); + p.fs.results_len = 0; + const id = pardes.panes.Output.openPager(p, p.active, std.mem.trim(u8, line, " \t")) catch |err| + return tree.failText(req.tag, if (err == error.NoPaneRoom or err == error.NoPaneSlots) E.NOSPC else E.IO, switch (err) { + error.NoPaneRoom, error.NoPaneSlots => "pager: no space for a +Pager pane", + else => "pager: could not make a +Pager pane", + }); + noteResult(p, p.panes[id].?.serial); + return .{ .tag = req.tag, .written = @intCast(req.data.len) }; +} + /// One session builtin a line, at whichever pane has the keyboard as each /// runs, as the root's look and exec click there; all are checked first. pub fn writeRoot(p: *Pardes, req: Req) Reply { @@ -648,18 +665,6 @@ pub fn writeRoot(p: *Pardes, req: Req) Reply { var it = Messages.init(p, req.data); while (it.next()) |line| { if (line.len == 0 or exec_line.isComment(line)) continue; - // `pardes -`'s: the directory's +Pager made or emptied, its - // serial what /exec reads back. - if (std.mem.startsWith(u8, line, "pager ") or std.mem.eql(u8, line, "pager")) { - if (!apply) continue; - const id = pardes.panes.Output.openPager(p, p.active, std.mem.trim(u8, line["pager".len..], " \t")) catch |err| - return tree.failText(req.tag, if (err == error.NoPaneRoom or err == error.NoPaneSlots) E.NOSPC else E.IO, switch (err) { - error.NoPaneRoom, error.NoPaneSlots => "pager: no space for a +Pager pane", - else => "pager: could not make a +Pager pane", - }); - noteResult(p, p.panes[id].?.serial); - continue; - } if (std.mem.startsWith(u8, line, "size ") or std.mem.eql(u8, line, "size")) { // The offending word is the value: `size 5 5` quotes "5 5". const value = std.mem.trim(u8, line["size".len..], " \t"); @@ -3999,3 +4004,27 @@ test "a refused Delcol changes nothing: no pane, no focus" { try testing.expectEqual(active_column, p.active_column); try testing.expect(th.logHas(p, "unsaved ")); } + +test "pager answers its +Pager on the open that asked, whatever another client exec'd meanwhile" { + const p = try withFile(testing.allocator, "x\n"); + defer p.deinit(); + const pager = @intFromEnum(tree.TopFile.pager); + const exec = @intFromEnum(tree.TopFile.exec); + const asked = call(p, .{ .tag = 1, .op = .open, .node = pager, .omode = 2 }).reply.handle; + try testing.expectEqual(Status.ok, call(p, .{ .tag = 2, .op = .write, .node = pager, .handle = asked, .data = "/tmp/pager-race\n" }).reply.status); + const paged = for (p.panes) |slot| { + const pn = slot orelse continue; + if (pn.file) |f| if (std.mem.eql(u8, f.path, "/tmp/pager-race/+Pager")) break pn.serial; + } else return error.NoPager; + // Another client execs between the request and its read: a pane of its own. + const racer = call(p, .{ .tag = 3, .op = .open, .node = exec, .omode = 2 }).reply.handle; + try testing.expectEqual(Status.ok, call(p, .{ .tag = 4, .op = .write, .node = exec, .handle = racer, .data = "New\n" }).reply.status); + var line: [16]u8 = undefined; + const want = try std.fmt.bufPrint(&line, "{d}\n", .{paged}); + // A fresh open reads the session's last answer, the racer's pane: what + // `pardes -` once read, and wrote its text into. + try testing.expect(!std.mem.eql(u8, want, rd(p, exec, 0, 64).bytes)); + try testing.expectEqualStrings(want, call(p, .{ .tag = 5, .op = .read, .node = pager, .handle = asked, .size = 64 }).bytes); + // One directory a write. + try testing.expectEqual(E.INVAL, wr(p, pager, "/a\n/b\n").errno()); +} diff --git a/src/ninep/tree.zig b/src/ninep/tree.zig index cc8f938a..9c3e1e9c 100644 --- a/src/ninep/tree.zig +++ b/src/ninep/tree.zig @@ -233,6 +233,9 @@ pub const TopFile = enum(u5) { /// The files opened lately, closed ones too, a line each: /// `open|closed `, most recent first. recent, + /// `pardes -`'s: a directory written, its +Pager made or emptied; a + /// read of the same open answers its serial. + pager, pub fn fileName(f: TopFile) []const u8 { return if (f == .root) "/" else @tagName(f); @@ -241,7 +244,7 @@ pub const TopFile = enum(u5) { pub fn mode(f: TopFile) u16 { return switch (f) { .root, .pane, .col => 0o755, - .look, .exec, .log, .focus, .ctl, .tag, .tagexec => 0o666, + .look, .exec, .log, .focus, .ctl, .tag, .tagexec, .pager => 0o666, .README, .index, .status, .screen, .listeners, .new, .commands, .layout, .recent => 0o444, }; } @@ -645,7 +648,7 @@ fn topSize(p: *Pardes, f: TopFile) u64 { .tag => cols.headerText(p, null).?.len, .README => fs.help.len, .status => ctl.statusLen(p), - .look, .exec, .tagexec => ctl.resultsLen(p), + .look, .exec, .tagexec, .pager => ctl.resultsLen(p), // A stream: a length would read as its end to a kernel that caches // one (a 9ns mount's splice), and a follower's reads go past it. .log => 0, @@ -749,7 +752,7 @@ fn readdir(p: *Pardes, req: Req, target: Target) Reply { .root => { // The guide, then what describes the session, then the // files that act, then the directories. - inline for (.{ TopFile.README, TopFile.index, TopFile.status, TopFile.focus, TopFile.ctl, TopFile.commands, TopFile.recent, TopFile.look, TopFile.exec, TopFile.log, TopFile.screen, TopFile.listeners, TopFile.layout, TopFile.tag, TopFile.tagexec, TopFile.pane, TopFile.col }) |t| { + inline for (.{ TopFile.README, TopFile.index, TopFile.status, TopFile.focus, TopFile.ctl, TopFile.commands, TopFile.recent, TopFile.look, TopFile.exec, TopFile.pager, TopFile.log, TopFile.screen, TopFile.listeners, TopFile.layout, TopFile.tag, TopFile.tagexec, TopFile.pane, TopFile.col }) |t| { if (skip > 0) skip -= 1 else stageDirent(out, p.gpa, @intFromEnum(t), t.dir(), t.fileName()); } if (skip > 0) skip -= 1 else stageDirent(out, p.gpa, fs.os_root, true, "os"); @@ -1066,7 +1069,7 @@ fn readFile(p: *Pardes, req: Req, target: Target) Reply { break :index stagedReply(p, req); }, .status => ctl.readStatus(p, req), - .look, .exec, .tagexec => ctl.readResults(p, req), + .look, .exec, .tagexec, .pager => ctl.readResults(p, req), .log => events.readLog(p, req), .screen => screen.readSnapshot(p, req, null), .listeners => screen.readListeners(p, req), @@ -1125,7 +1128,7 @@ fn readFile(p: *Pardes, req: Req, target: Target) Reply { /// The files whose writes are lines of commands, run as each line is whole. fn linesFile(target: Target) bool { return switch (target) { - .top => |f| f == .look or f == .exec or f == .ctl or f == .tagexec, + .top => |f| f == .look or f == .exec or f == .ctl or f == .tagexec or f == .pager, .col => |c| c.file == .ctl or c.file == .exec, // `name` too: one name, however its writes cut it, applied once // its newline comes, or with its write when that is whole. @@ -1136,7 +1139,7 @@ fn linesFile(target: Target) bool { /// The ones of those a read answers with the panes a write touched. fn resultsFile(target: Target) bool { return switch (target) { - .top => |f| f == .look or f == .exec or f == .tagexec, + .top => |f| f == .look or f == .exec or f == .tagexec or f == .pager, .col => |c| c.file == .exec, .pane => |t| t.file == .look or t.file == .exec or t.file == .tagexec, }; @@ -1225,6 +1228,7 @@ fn writeNow(p: *Pardes, req: Req, target: Target) Reply { .log => events.writeLog(p, req), .focus => ctl.writeFocus(p, req), .ctl => ctl.writeRoot(p, req), + .pager => ctl.writePager(p, req), .tag => cols.write(p, req, null), .tagexec => cols.writeExec(p, req, null), else => Reply.fail(req.tag, E.PERM), @@ -1420,13 +1424,13 @@ test "readdir lists the root and a pane directory without creating anything" { @memcpy(top_bytes[0..top_reply.bytes.len], top_reply.bytes); const top = th.dirents(top_bytes[0..top_reply.bytes.len], &buf); try testing.expect(top.len >= 10); - for ([_][]const u8{ "README", "index", "status", "focus", "ctl", "commands", "recent", "look", "exec", "log", "screen", "listeners", "layout", "tag", "tagexec", "pane", "col", "os" }, 0..) |name, i| { + for ([_][]const u8{ "README", "index", "status", "focus", "ctl", "commands", "recent", "look", "exec", "pager", "log", "screen", "listeners", "layout", "tag", "tagexec", "pane", "col", "os" }, 0..) |name, i| { try testing.expectEqualStrings(name, top[i].name); - try testing.expectEqual(i >= 15, top[i].dir); + try testing.expectEqual(i >= 16, top[i].dir); } - try testing.expectEqual(@intFromEnum(TopFile.pane), top[15].node); - try testing.expectEqual(@intFromEnum(TopFile.col), top[16].node); - try testing.expectEqual(fs.os_root, top[17].node); + try testing.expectEqual(@intFromEnum(TopFile.pane), top[16].node); + try testing.expectEqual(@intFromEnum(TopFile.col), top[17].node); + try testing.expectEqual(fs.os_root, top[18].node); var idbuf: [16]u8 = undefined; try testing.expect(th.nameAt(top, try std.fmt.bufPrint(&idbuf, "{d}", .{serial})) == null); try testing.expect(th.nameAt(top, "self") == null); diff --git a/test/fs.py b/test/fs.py index 2507e4f8..fcd779d1 100644 --- a/test/fs.py +++ b/test/fs.py @@ -164,7 +164,7 @@ def discovery(binary, embedded=False): top = client.list('/') # A set: which files the root holds, not the order a listing gives. assert set(top) - {'src', 'shaders'} == {'README', 'index', 'status', 'focus', 'ctl', 'commands', 'recent', - 'look', 'exec', 'log', 'screen', 'listeners', 'layout', 'tag', 'tagexec', + 'look', 'exec', 'pager', 'log', 'screen', 'listeners', 'layout', 'tag', 'tagexec', 'pane', 'col', 'os'}, top assert 'self' not in top and 'cons' not in top and 'new' not in top, top assert ('src' in top) == embedded, (top, embedded) -- cgit v1.3 From 9ac223e5436a9f5831c97382270dedbf9f13277d Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Thu, 1 Oct 2026 04:00:33 -0300 Subject: --wait waits on the pane its look answered, read on the look's own open, not one found again by name in /index The forwarded look was a write and nothing more, and --wait then looked its file up in /index. /index shows names escaped (`\\` for a backslash, `\xNN`), so a file named with one matched no pane and --wait exited 0 at once, as if the pane were already closed. The look is now asked on one open (Client.ask) and its answer is the pane waited on; /index by name stays only for a look that answers none. Co-Authored-By: Claude Opus 5.5 --- src/main.zig | 17 +++++++++++------ test/fs.py | 16 ++++++++++++++++ 2 files changed, 27 insertions(+), 6 deletions(-) (limited to 'src/main.zig') diff --git a/src/main.zig b/src/main.zig index 6c46b22c..de501047 100644 --- a/src/main.zig +++ b/src/main.zig @@ -281,11 +281,12 @@ fn forwardWords(err: anyerror, buf: []u8) []const u8 { /// connection ends with the session -- exit 1. fn waitForDel(io: std.Io, gpa: std.mem.Allocator, dial: []const u8, path: []const u8, known: ?u32) noreturn { _ = io; - // The pane this launch made (a name not there yet) is known by its - // serial; one a look opened or went to is found by its file. Found by - // none after the look went there, it was closed already: that is the - // end being waited for, not a failure (a pane closed between the look - // and this read made `--wait` exit 1 before). + // The pane this launch made (a name not there yet), or the one its + // look answered, is known by its serial; one the look answered none + // for is found by its file. Found by none after the look went there, + // it was closed already: that is the end being waited for, not a + // failure (a pane closed between the look and this read made `--wait` + // exit 1 before). const serial = known orelse found: { const first = ninep_io.Client.read(gpa, dial, "/index", "/index") catch std.process.exit(1); defer gpa.free(first); @@ -660,7 +661,11 @@ fn nativeMain(init: std.process.Init) !void { if (found_path != null) { var command_buf: [8192]u8 = undefined; const command = std.fmt.bufPrint(&command_buf, "{s}{s}\n", .{ path, word[target.path.len..] }) catch |err| Refuse.with(init.io, word, err); - ninep_io.Client.write(arena, parent.dial, look, command) catch |err| Refuse.with(init.io, word, err); + // The pane it went to, read on the open that asked (another + // client's look meanwhile is not this one's): what --wait waits on. + const went = ninep_io.Client.ask(arena, parent.dial, look, command) catch |err| Refuse.with(init.io, word, err); + var rows = std.mem.tokenizeAny(u8, went, " \n"); + if (rows.next()) |row| made_serial = std.fmt.parseInt(u32, row, 10) catch null; } else { const made = ninep_io.Client.read(arena, parent.dial, "/pane/new", "/pane/new") catch |err| Refuse.with(init.io, word, err); const serial = std.fmt.parseInt(u32, std.mem.trim(u8, made, " \n"), 10) catch |err| Refuse.with(init.io, word, err); diff --git a/test/fs.py b/test/fs.py index fcd779d1..483ef320 100644 --- a/test/fs.py +++ b/test/fs.py @@ -1395,6 +1395,22 @@ def test(binary, quic=False): assert time.monotonic() - deleted < .05, time.monotonic() - deleted assert second.wait(timeout=5) == 0 assert edited.read_bytes() == b'edited\n' + # --wait waits on the pane its look answered, on the look's own + # open: a name /index shows escaped (a backslash is `\\` there) + # is still the pane waited on, not one already gone. + odd = root / 'wait\\odd.txt' + odd.write_bytes(b'odd\n') + before = serials() + waiting = subprocess.Popen([binary, '--wait', str(odd)], cwd=root, env=env, + stdout=subprocess.DEVNULL, stderr=subprocess.PIPE) + deadline = time.monotonic() + 3 + while not serials() - before and time.monotonic() < deadline: + time.sleep(.01) + odd_pane, = serials() - before + time.sleep(.5) + assert waiting.poll() is None, waiting.stderr.read() + client.remove(f'/pane/{odd_pane}') + assert waiting.wait(timeout=5) == 0 # A name not there yet opens a pane named it, as acme's B does, # and Save creates it: git's and fish's temporary files are. fresh = root / 'wait new.txt' -- cgit v1.3 From 36fe45e3a4a7ce9b61ab7bf2df07f0132a9170c1 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Thu, 1 Oct 2026 04:58:25 -0300 Subject: `--` ends pardes's options: `pardes -- -dash.txt` opens the file named -dash.txt It said `no such option: --`. What follows `--` is a name, one at most, as for any other positional. Co-Authored-By: Claude Opus 5.5 --- src/main.zig | 9 +++++++++ test/fs.py | 9 +++++++++ 2 files changed, 18 insertions(+) (limited to 'src/main.zig') diff --git a/src/main.zig b/src/main.zig index de501047..a7d354b5 100644 --- a/src/main.zig +++ b/src/main.zig @@ -520,6 +520,15 @@ fn nativeMain(init: std.process.Init) !void { } else if (std.mem.eql(u8, a, "--version")) { try std.Io.File.stdout().writeStreamingAll(init.io, version_text); return; + } else if (std.mem.eql(u8, a, "--")) { + // The end of options: what follows is a name, `-dash.txt` too. + for (args[i + 1 ..]) |name| { + if (name.len == 0) badArgs(init.io, "an empty argument names nothing", .{}); + if (positional != null) badArgs(init.io, "one file or directory at a time, and '{s}' is the second", .{name}); + session_only = false; + positional = name; + } + break; } else if (a.len > 0 and (a[0] != '-' or std.mem.eql(u8, a, "-")) and positional == null) { // `-` is stdin, as for cat and vim: a text to show. session_only = false; diff --git a/test/fs.py b/test/fs.py index f24e2550..6c6bcbef 100644 --- a/test/fs.py +++ b/test/fs.py @@ -989,6 +989,7 @@ def test(binary, quic=False): for options, message in [ (['--fs'], b'no such option'), (['--fs9'], b'no such option'), + (['--', 'a', 'b'], b'is the second'), (['--9p'], b'--9p needs a socket name'), (['--9p='], b'invalid 9P socket name'), (['--9p=a/b'], b'invalid 9P socket name'), @@ -1396,6 +1397,14 @@ def test(binary, quic=False): assert time.monotonic() - deleted < .05, time.monotonic() - deleted assert second.wait(timeout=5) == 0 assert edited.read_bytes() == b'edited\n' + # `--` ends the options: a name starting with a dash is a name. + dash = root / '-dash.txt' + dash.write_bytes(b'dash\n') + before = serials() + assert subprocess.run([binary, '--', dash.name], cwd=root, env=env, capture_output=True, timeout=10).returncode == 0 + dashed, = serials() - before + assert client.read(f'/pane/{dashed}/name').rstrip(b'\n') == str(dash).encode() + client.remove(f'/pane/{dashed}') # --wait waits on the pane its look answered, on the look's own # open: a name /index shows escaped (a backslash is `\\` there) # is still the pane waited on, not one already gone. -- cgit v1.3 From 250db41743f77ce3d8421f729bdea0065aa6bc79 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Thu, 1 Oct 2026 05:01:31 -0300 Subject: A name under a directory that may not be searched or written is refused, permission denied, and a Save there says so, not no such directory `pardes noperm/a/b/c` and `pardes /proc/1/root/x` took the missing directory for one Save would make, opened a pane and exited 0; its Save then said "no such directory". fs.deniedAbove finds the nearest directory there and asks whether it may be searched and written: forwarding refuses such a name, exit 1, "permission denied", and a failed Save says "permission denied", which the writer's 9P error carries as EPERM (9ns: EACCES). Co-Authored-By: Claude Opus 5.5 --- src/9p_io.zig | 2 +- src/fs.zig | 20 ++++++++++++++++++++ src/main.zig | 8 ++++++-- src/ninep/ctl.zig | 9 +++++++++ src/ninep/pane.zig | 6 ++++-- src/pardes.zig | 6 +++++- test/fs.py | 11 +++++++++++ 7 files changed, 56 insertions(+), 6 deletions(-) (limited to 'src/main.zig') diff --git a/src/9p_io.zig b/src/9p_io.zig index 9fc19df9..ea3f799c 100644 --- a/src/9p_io.zig +++ b/src/9p_io.zig @@ -328,7 +328,7 @@ pub const Listener = struct { // builtin's failure saying so is (ctl.failureErrno). const errno = if (std.mem.indexOf(u8, late, "no such") != null or std.mem.indexOf(u8, late, "not found") != null) pardes.ctlfs.E.NOENT - else if (std.mem.indexOf(u8, late, "no space") != null) pardes.ctlfs.E.NOSPC else pardes.ctlfs.E.IO; + else if (std.mem.indexOf(u8, late, "no space") != null) pardes.ctlfs.E.NOSPC else if (std.mem.indexOf(u8, late, "permission denied") != null) pardes.ctlfs.E.PERM else pardes.ctlfs.E.IO; const failed = pardes.ctlfs.failText(req.tag, errno, late); // Its err record says it (the path in it), the one record: it // was said with no msg while this waited (fs.write_waits). diff --git a/src/fs.zig b/src/fs.zig index 965eb47c..e5980fe9 100644 --- a/src/fs.zig +++ b/src/fs.zig @@ -685,6 +685,26 @@ pub fn makeDirs(dir: []const u8) void { _ = libc.mkdir(z[0..dir.len :0], 0o755); } +/// Whether `dir` is not there to make because one above it refuses: its +/// nearest ancestor that is there may not be searched or written (EACCES: +/// `noperm/a/b`, `/proc/1/root/x`). +pub fn deniedAbove(dir: []const u8) bool { + if (comptime !platform_has_fs) return false; + var at: ?[]const u8 = dir; + while (at) |d| : (at = std.fs.path.dirname(d)) { + var z: [4096]u8 = undefined; + const dz = std.fmt.bufPrintSentinel(&z, "{s}", .{d}, 0) catch return false; + if (libc.access(dz.ptr, 0) != 0) continue; // F_OK + return libc.access(dz.ptr, 2 | 1) != 0; // W_OK | X_OK + } + return false; +} + +test "a directory under one that may not be searched or written is denied, one merely missing is not" { + try std.testing.expect(deniedAbove("/proc/1/root/x/y")); + try std.testing.expect(!deniedAbove("/tmp/pardes-surely-missing-dir/a/b")); +} + pub fn localPath(path: []const u8) ?[]const u8 { if (std.mem.eql(u8, path, "/n/os")) return "/"; if (std.mem.startsWith(u8, path, "/n/os/")) return path[5..]; diff --git a/src/main.zig b/src/main.zig index a7d354b5..86558bae 100644 --- a/src/main.zig +++ b/src/main.zig @@ -256,7 +256,7 @@ fn forwardWords(err: anyerror, buf: []u8) []const u8 { error.NotOneLine => "a file name is one line, and this one holds a newline", error.NotAFileName => "names a directory, not a file", error.NoWorkingDirectory => "this shell's working directory is gone", - error.DirectoryNotWritable => "its directory may not be read or written, so it could never be saved", + error.DirectoryNotWritable => "permission denied: its directory may not be read or written, so it could never be saved", error.NotAPaneAddress => "not a pane address: @p and a pane's number", error.NoSuchPane => "this session has no such pane", else => if (pardes.Messages.dialReason(err)) |why| why else words: { @@ -653,7 +653,11 @@ fn nativeMain(init: std.process.Init) !void { var cwd_buf: [4096]u8 = undefined; if (std.c.getcwd(&cwd_buf, cwd_buf.len) == null) Refuse.with(init.io, word, error.NoWorkingDirectory); const cwd = std.mem.sliceTo(&cwd_buf, 0); - break :named std.fs.path.resolvePosix(arena, &.{ cwd, target.path }) catch |err| Refuse.with(init.io, word, err); + const absolute = std.fs.path.resolvePosix(arena, &.{ cwd, target.path }) catch |err| Refuse.with(init.io, word, err); + // Missing because one above may not be searched or written: + // its Save could never make it, so refused now. + if (pardes.filesystem.deniedAbove(std.fs.path.dirname(absolute) orelse "/")) Refuse.with(init.io, word, error.DirectoryNotWritable); + break :named absolute; }; // A directory that is there but may not be read or written: a // pane for the name could only fail at its Save, so refused now. diff --git a/src/ninep/ctl.zig b/src/ninep/ctl.zig index c88eb328..d6d7a6ee 100644 --- a/src/ninep/ctl.zig +++ b/src/ninep/ctl.zig @@ -4056,3 +4056,12 @@ test "a command pane an exec open was answered is leased to it while it stays op try testing.expectEqual(Status.ok, wr(p, exec, "echo c\n").reply.status); try testing.expectEqual(a_pane, p.paneBySerial(p.fs.results[0]).?); } + +test "a Save whose directory is missing because one above refuses says permission denied, not no such directory" { + const p = try withFile(testing.allocator, "x\n"); + defer p.deinit(); + p.saveFailed(0, "/proc/1/root/x/f.txt", error.FileNotFound); + try testing.expect(th.logHas(p, "Save /proc/1/root/x/f.txt: permission denied")); + p.saveFailed(0, "/tmp/pardes-surely-missing-dir/f.txt", error.FileNotFound); + try testing.expect(th.logHas(p, "no such directory")); +} diff --git a/src/ninep/pane.zig b/src/ninep/pane.zig index b9fa2857..3963c605 100644 --- a/src/ninep/pane.zig +++ b/src/ninep/pane.zig @@ -1535,13 +1535,15 @@ test "a name with a component over 255 bytes is refused, and a long path's faile try testing.expectEqual(Status.ok, wr(p, Node.of(serial, .name), "/tmp/" ++ "c" ** 255 ++ "\n").reply.status); // A Save of a 3000-byte path the host refuses: the waiting write's // reason is at the end, the path giving up its middle. - const long = "/nonexistent-pardes-root/" ++ ("d" ** 200 ++ "/") ** 15 ++ "f.txt"; + // (Under /tmp: under / a user's Save is refused permission, not + // missing.) + const long = "/tmp/nonexistent-pardes-root/" ++ ("d" ** 200 ++ "/") ** 15 ++ "f.txt"; const id = p.paneBySerial(serial).?; try nameBuffer(p, id, long, false); p.fs.late_failure_len = 0; p.saveFailed(@intCast(id), long, error.AccessDenied); const late = p.fs.late_failure[0..p.fs.late_failure_len]; - try testing.expect(std.mem.startsWith(u8, late, "Save /nonexistent-pardes-root/")); + try testing.expect(std.mem.startsWith(u8, late, "Save /tmp/nonexistent-pardes-root/")); try testing.expect(std.mem.endsWith(u8, late, "/f.txt: no such directory")); } diff --git a/src/pardes.zig b/src/pardes.zig index 945fcafa..f5001797 100644 --- a/src/pardes.zig +++ b/src/pardes.zig @@ -5541,7 +5541,11 @@ pub const Pardes = struct { const parent = std.fs.path.dirname(path) orelse "/"; const no_dir = err == error.FileNotFound or err == error.NotDir or (if (comptime hosted) (if (filesystem.localPath(parent)) |local| !exec.isDirectory(local) else false) else false); - if (no_dir) + // Not there because one above refuses: that is the reason, EACCES. + const denied = no_dir and (if (comptime hosted) (if (filesystem.localPath(parent)) |local| filesystem.deniedAbove(local) else false) else false); + if (denied) + p.reportFailure(id, std.fmt.bufPrint(&what, "Save {s}: permission denied", .{path}) catch "Save: permission denied") + else if (no_dir) p.reportFailure(id, std.fmt.bufPrint(&what, "Save {s}: no such directory", .{path}) catch "Save: no such directory") else p.reportError(id, std.fmt.bufPrint(&what, "Save {s}", .{path}) catch "Save", err); diff --git a/test/fs.py b/test/fs.py index 6c6bcbef..2ccd0690 100644 --- a/test/fs.py +++ b/test/fs.py @@ -1405,6 +1405,17 @@ def test(binary, quic=False): dashed, = serials() - before assert client.read(f'/pane/{dashed}/name').rstrip(b'\n') == str(dash).encode() client.remove(f'/pane/{dashed}') + # A name under a directory that may not be searched is refused, + # permission denied, exit 1, no pane: its Save could never be. + (root / 'noperm').mkdir() + (root / 'noperm').chmod(0) + before = serials() + try: + denied = subprocess.run([binary, 'noperm/a/b/c'], cwd=root, env=env, capture_output=True, timeout=10) + finally: + (root / 'noperm').chmod(0o755) + assert denied.returncode == 1 and b'permission denied' in denied.stderr, denied + assert serials() == before # --wait waits on the pane its look answered, on the look's own # open: a name /index shows escaped (a backslash is `\\` there) # is still the pane waited on, not one already gone. -- cgit v1.3 From c9e5c77eb9a20d7012ee972727f250f3a2fb95cc Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Thu, 1 Oct 2026 06:28:40 -0300 Subject: /pager resolves its directory, `~` and `..` alike, and refuses one that may not be written, permission denied; `pardes -` from such a directory pages into the session's `/tmp/../etc` named a +Pager `/tmp/../etc/+Pager`, a second one beside `/etc/+Pager`, and `~/x` was refused as relative. The directory is now home-expanded and resolved before it is checked, and one that may not be written is refused as a file's name there is (fs.deniedAbove). `pardes -` run in such a directory (`git log` under /usr/src) asks for the session's +Pager instead, so its text is still paged. Co-Authored-By: Claude Opus 5.5 --- src/main.zig | 4 +++- src/ninep/ctl.zig | 14 +++++++++++++- 2 files changed, 16 insertions(+), 2 deletions(-) (limited to 'src/main.zig') diff --git a/src/main.zig b/src/main.zig index 86558bae..99e94889 100644 --- a/src/main.zig +++ b/src/main.zig @@ -121,9 +121,11 @@ fn pageInto(io: std.Io, gpa: std.mem.Allocator, dial: []const u8, text: []const // of a ctl (a newline, a control byte): then the session's. var cwd_buf: [4096]u8 = undefined; const cwd: []const u8 = if (std.c.getcwd(&cwd_buf, cwd_buf.len)) |c| std.mem.span(@as([*:0]u8, @ptrCast(c))) else ""; + // ...or the session's when this one may not be written (`git log` in + // /usr/src), which /pager refuses: the text is paged all the same. const plain = for (cwd) |c| { if (c < ' ' or c == 0x7f) break false; - } else true; + } else !pardes.filesystem.deniedAbove(cwd); var line_buf: [4200]u8 = undefined; const dir_line = std.fmt.bufPrint(&line_buf, "{s}\n", .{if (plain) cwd else ""}) catch "\n"; // Its serial read back on the open that asked: another client's exec diff --git a/src/ninep/ctl.zig b/src/ninep/ctl.zig index 89d438df..fa6310bb 100644 --- a/src/ninep/ctl.zig +++ b/src/ninep/ctl.zig @@ -654,7 +654,11 @@ pub fn writePager(p: *Pardes, req: Req) Reply { const line = it.next() orelse ""; // Words 9ns maps back to EINVAL (`invalid`), as every refusal here. if (it.next() != null) return tree.failText(req.tag, E.INVAL, "pager: invalid write: one directory a write"); - const dir = std.mem.trim(u8, line, " \t"); + // `~` is home, and `/tmp/../etc` is `/etc`: the +Pager is named in the + // directory it is, as any other pane's name is. + var home_buf: [4096]u8 = undefined; + const typed = pardes.filesystem.expandHome(std.mem.trim(u8, line, " \t"), &home_buf); + const dir = if (typed.len > 0 and typed[0] == '/') std.fs.path.resolvePosix(p.scratch.allocator(), &.{typed}) catch typed else typed; // A directory that is there, or none (the session's): never a +Pager // named into one missing, nor a relative one quietly taken for none. if (dir.len > 0 and dir[0] != '/') { @@ -663,6 +667,9 @@ pub fn writePager(p: *Pardes, req: Req) Reply { } if (comptime pardes.hosted) if (dir.len > 0) if (pardes.filesystem.localPath(dir)) |local| if (!exec_line.isDirectory(local)) return tree.failText(req.tag, E.NOENT, std.fmt.bufPrint(&p.fs.ename, "pager: {s}: no such directory", .{dir[0..@min(dir.len, 256)]}) catch "pager: no such directory"); + // Nor one that may not be written, as a file's name there is refused. + if (comptime pardes.hosted) if (dir.len > 0) if (pardes.filesystem.localPath(dir)) |local| if (pardes.filesystem.deniedAbove(local)) + return tree.failText(req.tag, E.PERM, std.fmt.bufPrint(&p.fs.ename, "pager: {s}: permission denied", .{dir[0..@min(dir.len, 256)]}) catch "pager: permission denied"); const id = pardes.panes.Output.openPager(p, p.active, dir) catch |err| return tree.failText(req.tag, if (err == error.NoPaneRoom or err == error.NoPaneSlots) E.NOSPC else E.IO, switch (err) { error.NoPaneRoom, error.NoPaneSlots => "pager: no space for a +Pager pane", @@ -4049,6 +4056,11 @@ test "pager answers its +Pager on the open that asked, whatever another client e // Refused, the same open answers nothing, not its last answer. try testing.expectEqual(E.INVAL, call(p, .{ .tag = 6, .op = .write, .node = pager, .handle = asked, .data = "relative\n" }).errno()); try testing.expectEqualStrings("", call(p, .{ .tag = 7, .op = .read, .node = pager, .handle = asked, .size = 64 }).bytes); + // Resolved: `/tmp/../tmp/.` is /tmp's +Pager, the one made above. + try testing.expectEqual(Status.ok, call(p, .{ .tag = 8, .op = .write, .node = pager, .handle = asked, .data = "/tmp/../tmp/.\n" }).reply.status); + try testing.expectEqualStrings(want, call(p, .{ .tag = 9, .op = .read, .node = pager, .handle = asked, .size = 64 }).bytes); + // One that may not be written is refused, permission denied. + try testing.expectEqual(E.PERM, wr(p, pager, "/proc/1\n").errno()); // One directory a write, absolute, and there. try testing.expectEqual(E.INVAL, wr(p, pager, "/a\n/b\n").errno()); const relative = wr(p, pager, "relative\n"); -- cgit v1.3 From 4178fdf514b637cafde6325086e0ce66e2cafaa2 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Thu, 1 Oct 2026 06:52:47 -0300 Subject: A file name with a newline is refused naming it once: `pardes: two\nlines.txt: a file name is one line...`, not `a file name: a file name ...` The refusal's subject was the words "a file name", and its reason began with them again. It now names the name given, its newline shown `\n`, as /log and /index show one. Co-Authored-By: Claude Opus 5.5 --- src/main.zig | 7 ++++++- test/fs.py | 2 +- 2 files changed, 7 insertions(+), 2 deletions(-) (limited to 'src/main.zig') diff --git a/src/main.zig b/src/main.zig index 99e94889..08ead756 100644 --- a/src/main.zig +++ b/src/main.zig @@ -621,7 +621,12 @@ fn nativeMain(init: std.process.Init) !void { try std.Io.File.stderr().writeStreamingAll(init.io, nested_text); std.process.exit(1); }; - if (std.mem.indexOfAny(u8, typed_word, "\r\n") != null) Refuse.with(init.io, "a file name", error.NotOneLine); + // Named as it was given, its newline shown `\n`, so the refusal says + // which name and why once. + if (std.mem.indexOfAny(u8, typed_word, "\r\n") != null) { + var shown_buf: [4 * 4096]u8 = undefined; + Refuse.with(init.io, pardes.ctlfs.events.shown(typed_word[0..@min(typed_word.len, 4096)], &shown_buf), error.NotOneLine); + } // `pardes '~/x'`, quoted so the shell left it: home, as a look's. var home_buf: [4096]u8 = undefined; const word = pardes.filesystem.expandHome(typed_word, &home_buf); diff --git a/test/fs.py b/test/fs.py index 2ccd0690..270ac367 100644 --- a/test/fs.py +++ b/test/fs.py @@ -1561,7 +1561,7 @@ def test(binary, quic=False): finally: shut.chmod(0o755) for word, said in (('@p999:1', b'pardes: @p999:1: this session has no such pane'), - ('two\nlines.txt', b'a file name is one line')): + ('two\nlines.txt', b'pardes: two\\nlines.txt: a file name is one line')): refused = subprocess.run([binary, word], cwd=root, env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=10) assert refused.returncode == 1, refused -- cgit v1.3 From 6c82d06cd2a15d724b8e82e1128fa15dc9e35d05 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Thu, 1 Oct 2026 07:56:48 -0300 Subject: Restore reads a clean file from disk, and an unsaved one whose file changed since the Dump is said changed, its first Save asking before overwriting it A Restore put back the dump's copy of every file pane and armed the watch with the disk as it now was, so a file changed on disk after the Dump came back as its old text, marked clean, and the next Save wrote the old text over the new without a word. A clean file pane's text is now not in the dump: Restore reads its file (an older dump's copy is read past too, and used only when the file is gone). An unsaved pane keeps its text once, base64, the plain copy beside it dropped, with the hash of the file it was read against (`disk_hash`); a Restore that finds another there says the file changed on disk, and Save asks once before overwriting it, as for a change seen while it was open. file_watch.zig's own tests were never collected (no test root imported it): main.zig's test block does now, and the restored watch test says what a clean restore now reads. Co-Authored-By: Claude Opus 5.5 --- src/File.zig | 40 +++++++++++++++++++++++++++++++++++----- src/dump.zig | 8 ++++++++ src/file_watch.zig | 11 +++++++---- src/main.zig | 2 ++ src/ninep/ctl.zig | 40 ++++++++++++++++++++++++++++++++++++++++ test/fs_namespace.zig | 3 ++- 6 files changed, 94 insertions(+), 10 deletions(-) (limited to 'src/main.zig') diff --git a/src/File.zig b/src/File.zig index c738ee58..d41007c3 100644 --- a/src/File.zig +++ b/src/File.zig @@ -105,6 +105,7 @@ pub const State = struct { pub const NodeStep = struct { ranges: []modal.Selection, primary: usize }; pub fn dumpPane( + p: *Pardes, arena: std.mem.Allocator, pane: *const Pane, file: *const State, @@ -114,6 +115,18 @@ pub fn dumpPane( origin: []const u8, origin_arg: []const u8, ) !dump.Pane { + const dirty = file.revision != file.saved_revision; + const on_disk = onDisk(file.path); + // A clean file's text is its file's: read from disk when restored, so + // a change made there since is what comes back. Any other is kept, once. + const from_disk = file.output == null and !dirty and on_disk; + // What an unsaved pane's text was read against: the disk as it is, or, + // when a change there was seen already, something it is not. + const disk_hash: ?u64 = if (file.output != null or !dirty or !on_disk) null else if (file.disk_newer) |newer| newer +% 1 else blk: { + const bytes = filesystem.read(p, file.path) catch break :blk null; + defer p.gpa.free(bytes); + break :blk std.hash.Wyhash.hash(0, bytes); + }; return .{ .kind = .file, .tag = tag, @@ -127,10 +140,10 @@ pub fn dumpPane( .tree_context = file.tree_context, .location_rows = try dumpLocationRows(arena, file.location_rows), .path = file.path, - .content = file.content, - .content_b64 = try dump.encodeBytes(arena, file.content), - .dirty = file.revision != file.saved_revision, - .on_disk = onDisk(file.path), + .content_b64 = if (from_disk) "" else try dump.encodeBytes(arena, file.content), + .dirty = dirty, + .disk_hash = disk_hash, + .on_disk = on_disk, .origin = origin, .origin_arg = origin_arg, .mini_source = if (file.mini) |mini| mini.source else "", @@ -855,7 +868,16 @@ pub fn restore(p: *Pardes, id: usize, src: dump.Pane) !*Pane { saved.content_b64.len > encoded_limit or saved.mini_colors_b64.len > encoded_limit) return error.InvalidMini; } - const content: []u8 = if (saved.content_b64.len > 0) + // A clean file's text is read from its file: one changed on disk since + // the dump comes back changed, never as the old text marked clean (and + // a dump from before, which kept it, is read so too). Gone from disk, the + // dump's text if it kept one. + const from_disk: ?[]u8 = if (Output.fromWord(saved.origin) == null and !saved.dirty and saved.on_disk and + saved.mini_source.len == 0 and filesystem.localPath(saved.path) != null) + filesystem.read(p, saved.path) catch null + else + null; + const content: []u8 = if (from_disk) |bytes| bytes else if (saved.content_b64.len > 0) try dump.decodeBytes(p.gpa, saved.content_b64) else try p.gpa.dupe(u8, saved.content); @@ -923,6 +945,14 @@ pub fn restore(p: *Pardes, id: usize, src: dump.Pane) !*Pane { // One never on disk (Config's new file, a name not yet saved) is // restored as it was: clean, and nothing deleted. if (output == null and saved.on_disk and !onDisk(path)) deleted(p, @intCast(id)); + // Unsaved, and its file changed on disk since the text was read: said, + // and its first Save asks before overwriting the newer file. + if (saved.disk_hash) |read_against| if (output == null and onDisk(path)) { + if (filesystem.read(p, path)) |bytes| { + defer p.gpa.free(bytes); + if (std.hash.Wyhash.hash(0, bytes) != read_against) changed(p, @intCast(id), bytes); + } else |_| {} + }; return pane; } diff --git a/src/dump.zig b/src/dump.zig index ca3751f2..1420ea8f 100644 --- a/src/dump.zig +++ b/src/dump.zig @@ -208,9 +208,16 @@ pub const LocationRow = struct { pub const File = struct { path: []const u8 = "", + /// The text, in older dumps plain and base64 both; now base64 alone, + /// and only for a pane whose text is not its file's on disk (unsaved, + /// an output, a file never written): a clean file's is read from disk. content: []const u8 = "", content_b64: []const u8 = "", dirty: bool = false, + /// An unsaved pane's: the hash of the file on disk its text was read + /// against. A Restore that finds another there says it changed, and + /// Save asks before overwriting it. + disk_hash: ?u64 = null, /// Its file was on disk when dumped: one gone by the Restore is said /// deleted, one never written (Config's new file) is not. True in /// older dumps. @@ -728,6 +735,7 @@ pub fn dumpState(p: *Pardes) !void { const body = try body_layer.bodyText(p, arena, pane); const scroll: usize = @intCast(@max(0, pane.scroll())); var dp: Pane = if (pane.file) |*f| try pardes.panes.File.dumpPane( + p, arena, pane, f, diff --git a/src/file_watch.zig b/src/file_watch.zig index 6c746e74..46764a73 100644 --- a/src/file_watch.zig +++ b/src/file_watch.zig @@ -687,11 +687,14 @@ test "restored file watches preserve snapshots and accept later disk changes" { else => {}, }; try std.testing.expect(armed and watches[id] != null); - try std.testing.expectEqualStrings("restored snapshot\n", pane.file.?.content); + // A clean pane's text is its file's, read at the Restore: a dump + // that kept other text (an older dump) is not what comes back. + const restored: []const u8 = if (case.dirty) "restored snapshot\n" else "disk baseline\n"; + try std.testing.expectEqualStrings(restored, pane.file.?.content); try std.testing.expectEqual(@as(usize, 0), pane.file.?.history.undo_len); try std.testing.expectEqual(case.dirty, pane.file.?.revision != pane.file.?.saved_revision); _ = reloadChanged(core, io, gpa, &watches); - try std.testing.expectEqualStrings("restored snapshot\n", pane.file.?.content); + try std.testing.expectEqualStrings(restored, pane.file.?.content); try tmp.dir.writeFile(io, .{ .sub_path = "watched", .data = "later disk save\n" }); _ = reloadChanged(core, io, gpa, &watches); @@ -704,9 +707,9 @@ test "restored file watches preserve snapshots and accept later disk changes" { } try std.testing.expectEqualStrings("later disk save\n", pane.file.?.content); pardes.panes.File.undo(core, pane); - try std.testing.expectEqualStrings("restored snapshot\n", pane.file.?.content); + try std.testing.expectEqualStrings(restored, pane.file.?.content); _ = reloadChanged(core, io, gpa, &watches); - try std.testing.expectEqualStrings("restored snapshot\n", pane.file.?.content); + try std.testing.expectEqualStrings(restored, pane.file.?.content); } } diff --git a/src/main.zig b/src/main.zig index 08ead756..5dd6a8e6 100644 --- a/src/main.zig +++ b/src/main.zig @@ -822,6 +822,8 @@ test { _ = @import("host_io.zig"); _ = @import("host_io.zig").Shell; _ = @import("host_io.zig").Lsp; + // Its tests too: imported by the hosts only, it was never collected. + _ = @import("file_watch.zig"); _ = @import("lsp/lsp_client.zig"); _ = @import("lsp/lsp.zig"); if (comptime pardes.platform == .tty) { diff --git a/src/ninep/ctl.zig b/src/ninep/ctl.zig index f4aff960..1a2dbdbc 100644 --- a/src/ninep/ctl.zig +++ b/src/ninep/ctl.zig @@ -4213,3 +4213,43 @@ test "Petscii, Palette and Ascii take the state their tag word names, set rather _ = wr(p, ctl_node, "Petscii maybe\n"); try testing.expect(th.logHas(p, "Petscii takes on or off")); } + +test "a Restore reads a clean file from disk; an unsaved one whose file changed since is said so, and its first Save asks" { + if (comptime !pardes.hosted) return; + const gpa = testing.allocator; + var tmp = testing.tmpDir(.{}); + defer tmp.cleanup(); + try tmp.dir.writeFile(testing.io, .{ .sub_path = "a.txt", .data = "one\n" }); + var dir_buf: [4096]u8 = undefined; + const dir = dir_buf[0..try tmp.dir.realPath(testing.io, &dir_buf)]; + var path_buf: [4200]u8 = undefined; + const path = try std.fmt.bufPrint(&path_buf, "{s}/a.txt", .{dir}); + const p = try Pardes.init(gpa, .{ .file = path, .tty_only = true, .cols = 80, .rows = 24 }); + defer p.deinit(); + // Clean: the dump keeps no text, and the newer disk is what comes back. + try pardes.dump.dumpState(p); + try testing.expect(std.mem.indexOf(u8, p.dump_out.?, "b25lCg==") == null); // "one\n" in base64 + try tmp.dir.writeFile(testing.io, .{ .sub_path = "a.txt", .data = "two\n" }); + { + const restored = try pardes.dump.restore(p, p.dump_out.?, "/tmp/pardes.dump.zon"); + defer restored.deinit(); + const f = pane_files.fileOf(restored.panes[0].?).?; + try testing.expectEqualStrings("two\n", f.content); + try testing.expectEqual(f.saved_revision, f.revision); + } + // Unsaved: its text comes back, the disk changed under it is said, and + // Save asks once before overwriting it. + const f = pane_files.fileOf(p.panes[0].?).?; + const edited = try gpa.dupe(u8, "edited\n"); + pardes.panes.File.setContent(p, f, edited); + try testing.expect(f.revision != f.saved_revision); + try pardes.dump.dumpState(p); + try tmp.dir.writeFile(testing.io, .{ .sub_path = "a.txt", .data = "three\n" }); + const restored = try pardes.dump.restore(p, p.dump_out.?, "/tmp/pardes.dump.zon"); + defer restored.deinit(); + const rf = pane_files.fileOf(restored.panes[0].?).?; + try testing.expectEqualStrings("edited\n", rf.content); + try testing.expect(rf.disk_newer != null); + pardes.exec.saveFile(restored, 0); + try testing.expect(th.logHas(restored, "modified on disk since read (Save again to overwrite)")); +} diff --git a/test/fs_namespace.zig b/test/fs_namespace.zig index bd620c2d..5bce9eda 100644 --- a/test/fs_namespace.zig +++ b/test/fs_namespace.zig @@ -206,7 +206,8 @@ test "explicit OS file opens and restores keep their names and request watches" .kind = .file, .tag = path, .body = "", - .file = .{ .path = path, .content = "const unsaved = 2;\n" }, + // Unsaved text: kept (a clean pane's is read from disk). + .file = .{ .path = path, .content = "const unsaved = 2;\n", .dirty = true }, }); try std.testing.expectEqualStrings(path, copy.file.?.path); try std.testing.expectEqualStrings("const unsaved = 2;\n", copy.file.?.content); -- cgit v1.3 From 94f6090603e9c9f611a01335bd4eca480b00db76 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Thu, 1 Oct 2026 08:44:40 -0300 Subject: `pardes --wait FILE` with $PARDES_9P set but no pane of its own (an agent's or a script's EDITOR) asks that session and waits there, not a screen of its own Forwarding asked for $PARDES_PID and $PARDES_PANE, which only a pane's shell has, so a client that talks to a session from outside its panes got a full editor drawn in its terminal. With --wait and $PARDES_9P alone, the file is looked at through the session's root look and the wait is for that pane's del. Co-Authored-By: Claude Opus 5.5 --- src/main.zig | 20 +++++++++++++++----- test/fs.py | 16 ++++++++++++++++ 2 files changed, 31 insertions(+), 5 deletions(-) (limited to 'src/main.zig') diff --git a/src/main.zig b/src/main.zig index 5dd6a8e6..e998accc 100644 --- a/src/main.zig +++ b/src/main.zig @@ -563,16 +563,23 @@ fn nativeMain(init: std.process.Init) !void { // process is a shell that outlived its editor (a daemon started from a // pane, a stale environment carried into a new terminal), which is not // nested at all. - const owner = std.mem.span(std.c.getenv("PARDES_PID") orelse break :forwarding); - const pid = std.fmt.parseInt(std.c.pid_t, owner, 10) catch break :forwarding; - if (pid <= 0 or std.c.kill(pid, @enumFromInt(0)) != 0) break :forwarding; + // `--wait` with only $PARDES_9P (a script or agent that talks to a + // session from outside its panes, EDITOR='pardes --wait') is asked + // of that session too: what it waits on is a pane there. + const outside = wait and std.c.getenv("PARDES_PID") == null and std.c.getenv("PARDES_9P") != null; + if (!outside) { + const owner = std.mem.span(std.c.getenv("PARDES_PID") orelse break :forwarding); + const pid = std.fmt.parseInt(std.c.pid_t, owner, 10) catch break :forwarding; + if (pid <= 0 or std.c.kill(pid, @enumFromInt(0)) != 0) break :forwarding; + } // Can I reach it? That is the other two, and it is a separate answer. const Parent = struct { dial: []const u8, serial: u32 }; const found: ?Parent = reaching: { const dial = std.mem.span(std.c.getenv("PARDES_9P") orelse break :reaching null); ninep_io.Client.validateDial(dial) catch break :reaching null; - const pane_text = std.mem.span(std.c.getenv("PARDES_PANE") orelse break :reaching null); + // No pane of its own (`outside`): the session's root look, 0. + const pane_text = std.mem.span(std.c.getenv("PARDES_PANE") orelse if (outside) break :reaching .{ .dial = dial, .serial = 0 } else break :reaching null); for (pane_text) |byte| if (!std.ascii.isDigit(byte)) break :reaching null; const serial = std.fmt.parseInt(u32, pane_text, 10) catch break :reaching null; if (serial == 0) break :reaching null; @@ -602,7 +609,7 @@ fn nativeMain(init: std.process.Init) !void { // The pane's `look` file: one line, and the line is the clicked text // itself, which is what a right click in that pane would have been. var look_buf: [64]u8 = undefined; - const look = try std.fmt.bufPrint(&look_buf, "/pane/{d}/look", .{parent.serial}); + const look = if (parent.serial == 0) "/look" else try std.fmt.bufPrint(&look_buf, "/pane/{d}/look", .{parent.serial}); // `pardes -`: stdin read to its end, a +Pager pane of the session // made of it (as acme's `B` has no stdin, through pane/new, a name // and the body), and back at once: the PAGER a pane's shell gets. @@ -613,6 +620,9 @@ fn nativeMain(init: std.process.Init) !void { pageInto(init.io, arena, parent.dial, text); return; }; + // From outside the session's panes there is no pane to say it is + // nested in: `--wait` with no file opens nothing there. + if (parent.serial == 0 and positional == null) break :forwarding; const typed_word = positional orelse { var tag_buf: [64]u8 = undefined; const tag = try std.fmt.bufPrint(&tag_buf, "/pane/{d}/tag", .{parent.serial}); diff --git a/test/fs.py b/test/fs.py index 270ac367..11233e80 100644 --- a/test/fs.py +++ b/test/fs.py @@ -1397,6 +1397,22 @@ def test(binary, quic=False): assert time.monotonic() - deleted < .05, time.monotonic() - deleted assert second.wait(timeout=5) == 0 assert edited.read_bytes() == b'edited\n' + # --wait from outside the session's panes, $PARDES_9P alone (an + # agent's EDITOR): asked of the session, not a screen of its own. + outside_env = {k: v for k, v in env.items() if k not in ('PARDES_PANE', 'PARDES_PID')} + far = root / 'wait far.txt' + far.write_bytes(b'far\n') + before = serials() + waiting = subprocess.Popen([binary, '--wait', str(far)], cwd=root, env=outside_env, + stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE) + deadline = time.monotonic() + 5 + while not serials() - before and time.monotonic() < deadline: + time.sleep(.01) + far_pane, = serials() - before + time.sleep(.3) + assert waiting.poll() is None, waiting.stderr.read() + client.remove(f'/pane/{far_pane}') + assert waiting.wait(timeout=5) == 0 # `--` ends the options: a name starting with a dash is a name. dash = root / '-dash.txt' dash.write_bytes(b'dash\n') -- cgit v1.3 From edad6d960dc0fc1165cbb3b801e0538045b2247f Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Thu, 1 Oct 2026 10:09:54 -0300 Subject: A +Pager keeps its program's colours: the session parses what /pager is written after its directory with ghostty-vt, SGR becomes spans drawn over the plain text, every other escape is dropped, and PagerColor off pages it plain --- src/9p_io.zig | 28 ++- src/File.zig | 40 ++++- src/config.zig | 8 +- src/fs.zig | 7 + src/main.zig | 129 +++----------- src/ninep/ctl.zig | 103 +++++++++-- src/ninep/tree.zig | 58 +++++- src/pager.zig | 373 +++++++++++++++++++++++++++++++++++++++ src/pardes.zig | 12 +- test/fs.py | 20 +++ test/selfmount.py | 14 ++ test/snapshots/pagercolor.golden | 120 +++++++++++++ test/snapshots/pagercolor.snap | 24 +++ 13 files changed, 806 insertions(+), 130 deletions(-) create mode 100644 src/pager.zig create mode 100644 test/snapshots/pagercolor.golden create mode 100644 test/snapshots/pagercolor.snap (limited to 'src/main.zig') diff --git a/src/9p_io.zig b/src/9p_io.zig index 9a38b438..57df0c5f 100644 --- a/src/9p_io.zig +++ b/src/9p_io.zig @@ -266,6 +266,7 @@ pub const Listener = struct { const restores = pardes.turn.restores; // Asked first: a release that runs a held line has none after. const changes = pardes.ctlfs.changesPane(core, req); + const fills = pardes.ctlfs.holdsPage(core, req); const reply = core.serveFs(req); if (req.op == .release and quiet) l.collectOs(); // A read with nothing yet stays parked in the engine, and the core @@ -299,6 +300,13 @@ pub const Listener = struct { // file written. A change carries no payload, so the reply is still // whole after the wait. l.kick(); + // A read that put a /pager open's text in (ctl.fillPager), or a + // close that handed it to the editor's step, waits on nothing the + // editor performs: its answer goes now, while the turn still keeps + // a read's payload whole. Waiting would hang a close through a + // mount: 9ns answers nothing else on it while a clunk is out, and + // the editor's step may be out opening a file through that mount. + if (fills) return conn.reply(&reply, core.fsPayload(reply)); // A refusal answers at once: its text may be in the core's one // buffer for it, which a request run while this one waited would // write over. @@ -2341,10 +2349,12 @@ pub const Client = struct { gpa.destroy(s); } - /// Writes `request` to `path` and reads the answer on the same open, - /// as /pane/new answers its own open: a session's last answer, from - /// another client, can never be what comes back. `exec 3<>file`. - pub fn ask(gpa: std.mem.Allocator, dial: []const u8, path: []const u8, request: []const u8) ![]u8 { + /// Writes `request`, then `more`, to `path` and reads the answer on the + /// same open, as /pane/new answers its own open: a session's last + /// answer, from another client, can never be what comes back. `exec + /// 3<>file`. `more` (`pardes -`'s text after its /pager line) goes in + /// Twrites at rising offsets, each answer giving the next its budget. + pub fn ask(gpa: std.mem.Allocator, dial: []const u8, path: []const u8, request: []const u8, more: []const u8) ![]u8 { if (comptime !supported) return error.Unsupported; var names: [max_depth][]const u8 = undefined; const n = try elements(path, &names); @@ -2356,7 +2366,15 @@ pub const Client = struct { defer endSession(gpa, s); const fid = (try walkTo(s, names[0..n], &remote)).fid; _ = try s.ask(.{ .open = .{ .fid = fid, .mode = ninep.ordwr } }, &remote); - _ = try s.ask(.{ .write = .{ .fid = fid, .offset = 0, .data = request } }, &remote); + var written: usize = 0; + while (written < request.len + more.len) { + const from = if (written < request.len) request[written..] else more[written - request.len ..]; + const chunk = from[0..@min(from.len, s.cl.maxWrite())]; + const count = (try s.ask(.{ .write = .{ .fid = fid, .offset = written, .data = chunk } }, &remote)).write; + if (count == 0 or count > chunk.len) return Error.Botch; + written += count; + s.deadline = nowMs() +| write_budget_ms; + } var out: std.ArrayList(u8) = .empty; errdefer out.deinit(gpa); while (true) { diff --git a/src/File.zig b/src/File.zig index 4fac0073..b3c28290 100644 --- a/src/File.zig +++ b/src/File.zig @@ -75,6 +75,11 @@ pub const State = struct { /// A +Pager pane (`pardes -`) whose text is a diff (`git diff`, `show`, /// `log -p`): drawn and looked at as a diff (Pane.colorAlgo). pager_diff: bool = false, + /// A +Pager's colours, as its program printed them (pager.zig): drawn + /// over its text by recolorSyntax, never read over 9P. ponytail: any + /// edit drops them (setContentSpan); shifting them through the splice, + /// as pane.zig's shiftOne moves dot, would keep them. + pager_spans: []pardes.pager.Span = &.{}, /// Seconds of the last content change, for the filesystem's stat; zero until edited. mtime: u32 = 0, /// Non-null for a generated output buffer rather than an on-disk file. @@ -982,6 +987,7 @@ pub fn deinit(p: *Pardes, pane: *Pane, file: *State) void { if (file.mini) |*mini| mini.deinit(p.gpa); if (file.line_starts.len > 0) p.gpa.free(file.line_starts); 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); if (file.node_tree) |tree| syntax.freeTree(tree); @@ -1010,6 +1016,8 @@ pub fn setContent(p: *Pardes, f: *State, new: []u8) void { pub fn setContentSpan(p: *Pardes, f: *State, new: []u8, span: ?Span) void { locations.freeRows(p.gpa, f.location_rows); f.location_rows = &.{}; + p.gpa.free(f.pager_spans); + f.pager_spans = &.{}; for (p.panes) |slot| if (slot) |pane| { if (pane.file) |*file| if (file == f) { for (0..pane.sel.len) |button| { @@ -1483,7 +1491,8 @@ fn synStyle(p: *Pardes, sy: syntax.Syn) ?SynStyle { pub fn recolorSyntax(p: *Pardes, s: *Surface, pane: *Pane, f: *State, r: pardes.Rect, tx: u16, tw: u16, body_h: u16) void { const highlights = if (f.mini) |mini| mini.colors else f.highlights; const highlight_start = if (f.mini != null) 0 else f.highlight_start; - if (highlights.len == 0 and f.output == null) return; + const spans = f.pager_spans; + if (highlights.len == 0 and f.output == null and spans.len == 0) return; const prefix_width = gutterWidth(pane); const tz_recolor = tracy.zone(@src(), "synRecolor"); defer tz_recolor.end(); @@ -1526,6 +1535,14 @@ pub fn recolorSyntax(p: *Pardes, s: *Surface, pane: *Pane, f: *State, r: pardes. else null else null; if (tint) |t| if (prefix_width < tw) tintRow(s, tx + @as(u16, @intCast(prefix_width)), body_y + vr, tx + tw, t.bg); + // A +Pager's own colours (pager.zig) on every row but one the diff + // look tints: an added or removed line is drawn as pardes draws a + // diff, and git's red and green on it would only fight the tint. + var span_at = if (tint != null) spans.len else std.sort.partitionPoint(pardes.pager.Span, spans, base + hs, struct { + fn before(at: usize, span: pardes.pager.Span) bool { + return span.end <= at; + } + }.before); var c: usize = 0; var screen_c: usize = 0; while (hs + c < limit and prefix_width + screen_c < tw) { @@ -1562,6 +1579,27 @@ pub fn recolorSyntax(p: *Pardes, s: *Surface, pane: *Pane, f: *State, r: pardes. if (style.bg != .default) cell.style.bg = style.bg; } } + while (span_at < spans.len and spans[span_at].end <= idx) span_at += 1; + if (span_at < spans.len and spans[span_at].start <= idx) { + const st = spans[span_at].style; + var fill: usize = 0; + while (fill < cells and prefix_width + screen_c + fill < tw) : (fill += 1) { + const cell = s.at(tx + @as(u16, @intCast(prefix_width + screen_c + fill)), body_y + vr); + if (cell.default) continue; + // A palette colour through the theme's sixteen, as a + // terminal pane's cell; truecolor as it is. + if (st.fg != .default) cell.style.fg = if (st.fg == .index) terminal.palColor(p, st.fg.index) else st.fg; + if (st.bg != .default) cell.style.bg = if (st.bg == .index) terminal.palColor(p, st.bg.index) else st.bg; + cell.style.bold = cell.style.bold or st.bold; + cell.style.dim = st.dim; + cell.style.italic = st.italic; + cell.style.blink = st.blink; + cell.style.reverse = st.reverse; + cell.style.invisible = st.invisible; + cell.style.strikethrough = st.strikethrough; + if (st.ul != .off) cell.style.ul = st.ul; + } + } screen_c += cells; c = grapheme_end - hs; } diff --git a/src/config.zig b/src/config.zig index 7559d481..86baa9fe 100644 --- a/src/config.zig +++ b/src/config.zig @@ -82,6 +82,7 @@ pub const leader_path = paths: { .BootShell = null, .LookWord = null, .Pager = null, + .PagerColor = null, .TermImages = null, .Debug = "td", .Msg = null, @@ -762,6 +763,9 @@ pub const Runtime = struct { /// PAGER and GIT_PAGER set to `pardes -`, a +Pager pane, where the /// user's environment set neither; `off`, the environment as it is. pager: Pager = .pardes, + /// A +Pager keeps its program's colours (SGR, as spans over the text, + /// pager.zig), or is plain; for the next text paged. + pager_color: bool = true, /// How a new terminal pane draws the kitty graphics its program sends /// (yazi's previews): `real`, as pixels where the shell can, or /// `petscii`, as glyph art. The Petscii builtin flips one pane. @@ -939,7 +943,7 @@ pub const Runtime = struct { /// The message timings a setting word sets, each in milliseconds. pub const MessageTime = enum { linger, fall, dissolve }; - pub const Toggle = enum { colors, wrap, tree_context_tag_style, tag_bottom, debug, focus_tint, syntax_bold, verbose, message_animation, ligatures, cursor_blink, selection_glow, hover_glow, occlusion, parallax, jump_trail, chip_shadow, thumb_flash }; + pub const Toggle = enum { colors, wrap, tree_context_tag_style, tag_bottom, debug, focus_tint, syntax_bold, pager_color, verbose, message_animation, ligatures, cursor_blink, selection_glow, hover_glow, occlusion, parallax, jump_trail, chip_shadow, thumb_flash }; /// A bundled post pass, a Shadertoy file in shaders/post/: the CRT, and /// G4's bloom, vignette and grain (docs/effects.md). pub const Scene = enum { crt, bloom, vignette, grain }; @@ -1040,6 +1044,7 @@ pub const Runtime = struct { .{ .word = "BootShell", .action = .{ .choice = .boot_shell }, .doc = "A document dropped where a lone untouched shell stands: keep the shell, or replace it." }, .{ .word = "LookWord", .action = .{ .choice = .look_word }, .doc = "A plain word looked at: search selects its next place in the pane, list lists every place in a +Search." }, .{ .word = "Pager", .action = .{ .choice = .pager }, .doc = "What a terminal's commands page through: pardes, a +Pager pane (pardes -), or off, the environment's own; for terminals started after it." }, + .{ .word = "PagerColor", .action = .{ .toggle = .pager_color }, .doc = "A +Pager keeps its program's colours, on or off; for the next text paged." }, .{ .word = "TermImages", .action = .{ .choice = .term_images }, .doc = "How a new terminal draws its program's kitty graphics: real, as pixels where it can, or petscii, as glyph art." }, }; @@ -1748,6 +1753,7 @@ pub const Runtime = struct { .debug => "Debug on\n", .focus_tint => "FocusTint off\n", .syntax_bold => "SyntaxBold on\n", + .pager_color => "PagerColor off\n", .verbose => "Verbose off\n", .message_animation => "MessageAnimation off\n", .ligatures => "Ligatures off\n", diff --git a/src/fs.zig b/src/fs.zig index 9eb3fd0f..4a243b10 100644 --- a/src/fs.zig +++ b/src/fs.zig @@ -1631,6 +1631,11 @@ pub const Namespace = struct { /// append to `body`, an insert at `data`'s address), held and put in /// as one edit when anything else comes (ninep/pane.zig flushBatch): a /// 10 MB write in 8 KB pieces is one copy and one undo step, not 1280. + /// The text of /pager opens closed before a read put it in, each with + /// its +Pager's serial, for the editor's step to put in (ctl.fillPager): + /// a close through a mount may not wait for the editor to be quiet, + /// as 9ns answers nothing else on that mount while a clunk is out. + pages: std.ArrayList(struct { serial: u32, bytes: std.ArrayList(u8) }) = .empty, batch: struct { serial: u32 = 0, node: u64 = 0, @@ -1678,6 +1683,8 @@ pub const Namespace = struct { for (st.os_paths.items) |entry| gpa.free(entry.path); st.os_paths.deinit(gpa); for (&st.opens) |*o| o.deinit(gpa); + for (st.pages.items) |*page| page.bytes.deinit(gpa); + st.pages.deinit(gpa); st.log.deinit(gpa); st.out.deinit(gpa); } diff --git a/src/main.zig b/src/main.zig index e998accc..6d895307 100644 --- a/src/main.zig +++ b/src/main.zig @@ -50,9 +50,10 @@ const help_text = \\ \\With no arguments the shell pane starts in tty mode. A FILE argument \\(optionally file:LINE) opens it alone, filling the window; a DIRECTORY - \\argument becomes the cwd shells spawn in. `-` reads stdin, its terminal - \\escapes stripped, into a +Pager pane: inside a pardes pane the outer - \\session's, returning at once (a terminal's PAGER), else a new editor's. + \\argument becomes the cwd shells spawn in. `-` reads stdin into a +Pager + \\pane, its colours kept (PagerColor) and every other escape dropped: + \\inside a pardes pane the outer session's, returning at once (a + \\terminal's PAGER), else a new editor's. \\ \\Options: \\ --tty start as one shell pane already in tty mode @@ -100,11 +101,12 @@ const help_text = \\ ; -/// `pardes -` inside a session: `text` into the directory's one +Pager -/// (/pager, refilled when it is there), written into its -/// body through one open, as one undo step, and left clean. A text -/// the session would not take is never lost: it goes to stderr, with why, -/// and the exit is 1. +/// `pardes -` inside a session: `text`, stdin as it came, escapes and all, +/// into the directory's one +Pager (/pager, refilled when it is there): +/// written after the directory on that one open, the session parses it +/// (pager.zig) and puts it in as one undo step, left clean. A text the +/// session would not take is never lost: it goes to stderr, a terminal, +/// with why, and the exit is 1. fn pageInto(io: std.Io, gpa: std.mem.Allocator, dial: []const u8, text: []const u8) void { const Fail = struct { fn with(o: std.Io, t: []const u8, what: []const u8, err: anyerror) noreturn { @@ -128,22 +130,16 @@ fn pageInto(io: std.Io, gpa: std.mem.Allocator, dial: []const u8, text: []const } else !pardes.filesystem.deniedAbove(cwd); var line_buf: [4200]u8 = undefined; const dir_line = std.fmt.bufPrint(&line_buf, "{s}\n", .{if (plain) cwd else ""}) catch "\n"; - // Its serial read back on the open that asked: another client's exec - // meanwhile can never send this text into that client's pane. - const answer = ninep_io.Client.ask(gpa, dial, "/pager", dir_line) catch |err| Fail.with(io, text, "no +Pager pane", err); - const serial = std.fmt.parseInt(u32, std.mem.trim(u8, answer, " \n"), 10) catch |err| Fail.with(io, text, "no +Pager pane", err); - // The whole text through one open of the body (truncated once, then - // written at rising offsets): one undo step, and every byte of it. - var body_buf: [64]u8 = undefined; - const body = std.fmt.bufPrint(&body_buf, "/pane/{d}/body", .{serial}) catch unreachable; - ninep_io.Client.write(gpa, dial, body, text) catch |err| Fail.with(io, text, "the +Pager pane would not take it", err); - var ctl_buf: [64]u8 = undefined; - ninep_io.Client.write(gpa, dial, std.fmt.bufPrint(&ctl_buf, "/pane/{d}/ctl", .{serial}) catch unreachable, "clean\n") catch {}; + // Its serial read back on the open that asked, once the text is in: + // another client's exec meanwhile can never send it into that + // client's pane. + const answer = ninep_io.Client.ask(gpa, dial, "/pager", dir_line, text) catch |err| Fail.with(io, text, "no +Pager pane", err); + _ = std.fmt.parseInt(u32, std.mem.trim(u8, answer, " \n"), 10) catch |err| Fail.with(io, text, "no +Pager pane", err); } -/// Stdin to its end, its terminal escapes stripped (a pager's input is -/// coloured for a terminal; a text pane shows text), at most a file's -/// limit, a longer one cut there and said so at its end. +/// Stdin to its end, as it came (its escapes are the session's to parse, +/// pager.zig), at most a file's limit, a longer one cut there and said so +/// at its end. fn readStdinText(gpa: std.mem.Allocator) ![]u8 { const limit = pardes.memory.limits.max_file_bytes; var raw: std.ArrayList(u8) = .empty; @@ -164,90 +160,13 @@ fn readStdinText(gpa: std.mem.Allocator) ![]u8 { } try raw.appendSlice(gpa, chunk[0..got]); } - var text = try stripEscapes(gpa, raw.items); if (cut) { - const said = "\n[pardes: the rest of stdin is cut: a pane holds at most a file's limit]\n"; - text = try std.mem.concat(gpa, u8, &.{ text, said }); - } - return text; -} - -/// `bytes` without terminal escapes: CSI (`ESC [` ... a final byte, SGR -/// colour among them), OSC (`ESC ]` ... BEL or `ESC \`), any other -/// two-byte `ESC x`, and a man page's overstrike (`x BS x`, `_ BS x`). -pub fn stripEscapes(gpa: std.mem.Allocator, bytes: []const u8) ![]u8 { - var out = try std.ArrayList(u8).initCapacity(gpa, bytes.len); - var i: usize = 0; - while (i < bytes.len) { - const c = bytes[i]; - if (c == 0x1b and i + 1 < bytes.len) { - const kind = bytes[i + 1]; - i += 2; - if (kind == '[') { - while (i < bytes.len and !(bytes[i] >= 0x40 and bytes[i] <= 0x7e)) i += 1; - i += 1; - } else if (std.mem.indexOfScalar(u8, "()*+", kind) != null) { - i += 1; // a charset's name after it - } else if (kind == ']') { - while (i < bytes.len) : (i += 1) { - if (bytes[i] == 0x07) { - i += 1; - break; - } - if (bytes[i] == 0x1b and i + 1 < bytes.len and bytes[i + 1] == '\\') { - i += 2; - break; - } - } - } - continue; - } - // Overstrike: the byte before a backspace is struck over. - if (c == 0x08) { - if (out.items.len > 0) _ = out.pop(); - i += 1; - continue; - } - // A carriage return: CRLF is a newline; alone, the line starts - // over, as on a terminal, so a progress line keeps its last state. - if (c == '\r') { - if (i + 1 < bytes.len and bytes[i + 1] == '\n') { - i += 1; - continue; - } - const line_start = if (std.mem.lastIndexOfScalar(u8, out.items, '\n')) |nl| nl + 1 else 0; - out.shrinkRetainingCapacity(line_start); - i += 1; - continue; - } - // Bytes a terminal acts on and never shows: NUL, BEL, SO, SI. - if (c == 0 or c == 0x07 or c == 0x0e or c == 0x0f) { - i += 1; - continue; - } - out.appendAssumeCapacity(c); - i += 1; - } - return out.toOwnedSlice(gpa); -} - -test "stripEscapes takes out colour, other escapes and overstrike, and keeps the text" { - const gpa = std.testing.allocator; - const cases = [_][2][]const u8{ - .{ "\x1b[33mcommit abc\x1b[m\n", "commit abc\n" }, - .{ "a\x1b]8;;http://x\x1b\\link\x1b]8;;\x07b", "alinkb" }, - .{ "N\x08NA\x08AM\x08ME\x08E _\x08u", "NAME u" }, - .{ "plain\ttext\n", "plain\ttext\n" }, - .{ "\x1b(Bdone", "done" }, - .{ "a\r\nb\r\n", "a\nb\n" }, - .{ "10%\r50%\r100%\ndone\n", "100%\ndone\n" }, - .{ "x\x00y\x07z\x0e\x0f\n", "xyz\n" }, - }; - for (cases) |c| { - const got = try stripEscapes(gpa, c[0]); - defer gpa.free(got); - try std.testing.expectEqualStrings(c[1], got); + // CAN ends an escape the cut left half sent, and SGR 0 its colour, + // so the note is never swallowed or tinted. + const said = "\x18\x1b[m\n[pardes: the rest of stdin is cut: a pane holds at most a file's limit]\n"; + try raw.appendSlice(gpa, said); } + return raw.toOwnedSlice(gpa); } /// A forwarding failure in words, never an error's name: the ones this @@ -693,7 +612,7 @@ fn nativeMain(init: std.process.Init) !void { const command = std.fmt.bufPrint(&command_buf, "{s}{s}\n", .{ path, word[target.path.len..] }) catch |err| Refuse.with(init.io, word, err); // The pane it went to, read on the open that asked (another // client's look meanwhile is not this one's): what --wait waits on. - const went = ninep_io.Client.ask(arena, parent.dial, look, command) catch |err| Refuse.with(init.io, word, err); + const went = ninep_io.Client.ask(arena, parent.dial, look, command, "") catch |err| Refuse.with(init.io, word, err); var rows = std.mem.tokenizeAny(u8, went, " \n"); if (rows.next()) |row| made_serial = std.fmt.parseInt(u32, row, 10) catch null; } else { diff --git a/src/ninep/ctl.zig b/src/ninep/ctl.zig index cd8bc6c9..d4751191 100644 --- a/src/ninep/ctl.zig +++ b/src/ninep/ctl.zig @@ -650,7 +650,8 @@ pub fn readRoot(p: *Pardes, req: Req) Reply { /// /pager, `pardes -`'s: the directory written (empty, or not absolute: the /// session's) gets its one +Pager, made or emptied; the serial is what a -/// read of this same open answers, never another client's. +/// read of this same open answers, never another client's. What the open +/// writes after that line is the text, held by tree.zig for `fillPager`. pub fn writePager(p: *Pardes, req: Req) Reply { // A refused write leaves its open no answer, not the last one's. p.fs.results_len = 0; @@ -690,6 +691,35 @@ pub fn writePager(p: *Pardes, req: Req) Reply { return .{ .tag = req.tag, .written = @intCast(req.data.len) }; } +/// The text a /pager open wrote after its directory (`held`), a program's +/// output for a terminal, put in the +Pager `serial` as `pardes -` once +/// wrote it to the body: through ghostty-vt (pager.zig), its colours kept +/// as the pane's spans unless PagerColor is off, one undo step, and left +/// clean. Reads of the pane are its plain text. The held bytes go either way. +pub fn fillPager(p: *Pardes, serial: u32, held: *std.ArrayList(u8)) error{OutOfMemory}!void { + if (held.items.len == 0) return; + defer held.clearAndFree(p.gpa); + const id = p.paneBySerial(serial) orelse return; + const pane = p.panes[id].?; + const f = if (pane.file) |*file| file else return; + const page = try pardes.pager.parse(p.gpa, held.items, p.settings.pager_color); + held.clearAndFree(p.gpa); + if (page.text.len == 0 and f.content.len == 0) return page.deinit(p.gpa); + if (!pane.fs.nomark) panes.File.pushUndo(p, pane); + panes.File.setContent(p, f, page.text); + f.pager_spans = page.spans; + f.saved_revision = f.revision; +} + +/// The editor's step: the text of /pager opens closed unread goes in. +pub fn fillClosedPagers(p: *Pardes) void { + for (p.fs.pages.items) |*page| { + fillPager(p, page.serial, &page.bytes) catch {}; + page.bytes.deinit(p.gpa); + } + p.fs.pages.clearRetainingCapacity(); +} + /// One session builtin a line, at whichever pane has the keyboard as each /// runs, as the root's look and exec click there; all are checked first. pub fn writeRoot(p: *Pardes, req: Req) Reply { @@ -4088,21 +4118,26 @@ test "pager answers its +Pager on the open that asked, whatever another client e // `pardes -` once read, and wrote its text into. try testing.expect(!std.mem.eql(u8, want, rd(p, exec, 0, 64).bytes)); try testing.expectEqualStrings(want, call(p, .{ .tag = 5, .op = .read, .node = pager, .handle = asked, .size = 64 }).bytes); - // Refused, the same open answers nothing, not its last answer. - try testing.expectEqual(E.INVAL, call(p, .{ .tag = 6, .op = .write, .node = pager, .handle = asked, .data = "relative\n" }).errno()); - try testing.expectEqualStrings("", call(p, .{ .tag = 7, .op = .read, .node = pager, .handle = asked, .size = 64 }).bytes); + _ = call(p, .{ .tag = 6, .op = .release, .node = pager, .handle = asked, .opened = true }); + // Refused, an open answers nothing, not the session's last answer. + const refused = call(p, .{ .tag = 7, .op = .open, .node = pager, .omode = 2 }).reply.handle; + try testing.expectEqual(E.INVAL, call(p, .{ .tag = 8, .op = .write, .node = pager, .handle = refused, .data = "relative\n" }).errno()); + try testing.expectEqualStrings("", call(p, .{ .tag = 9, .op = .read, .node = pager, .handle = refused, .size = 64 }).bytes); + _ = call(p, .{ .tag = 10, .op = .release, .node = pager, .handle = refused, .opened = true }); // Resolved: `/tmp/../tmp/.` is /tmp's +Pager, the one made above. - const again = call(p, .{ .tag = 8, .op = .open, .node = pager, .omode = 2 }).reply.handle; - try testing.expectEqual(Status.ok, call(p, .{ .tag = 8, .op = .write, .node = pager, .handle = again, .data = "/tmp/../tmp/.\n" }).reply.status); - try testing.expectEqualStrings(want, call(p, .{ .tag = 9, .op = .read, .node = pager, .handle = again, .size = 64 }).bytes); - _ = call(p, .{ .tag = 9, .op = .release, .node = pager, .handle = again }); + const resolved = call(p, .{ .tag = 11, .op = .open, .node = pager, .omode = 2 }).reply.handle; + try testing.expectEqual(Status.ok, call(p, .{ .tag = 12, .op = .write, .node = pager, .handle = resolved, .data = "/tmp/../tmp/.\n" }).reply.status); + try testing.expectEqualStrings(want, call(p, .{ .tag = 13, .op = .read, .node = pager, .handle = resolved, .size = 64 }).bytes); + _ = call(p, .{ .tag = 14, .op = .release, .node = pager, .handle = resolved, .opened = true }); // One that may not be written is refused, permission denied. try testing.expectEqual(E.PERM, wr(p, pager, "/proc/1\n").errno()); // One directory a write, absolute, and there. try testing.expectEqual(E.INVAL, wr(p, pager, "/a\n/b\n").errno()); - // A second line on an open that asked already, as a mount sends two. + // One directory an open: one refused is not followed by another, as a + // mount sends two lines in two writes. (After one taken, what follows + // is the paged text: the test below.) const twice = call(p, .{ .tag = 20, .op = .open, .node = pager, .omode = 2 }).reply.handle; - try testing.expectEqual(Status.ok, call(p, .{ .tag = 21, .op = .write, .node = pager, .handle = twice, .data = "/tmp\n" }).reply.status); + try testing.expectEqual(E.INVAL, call(p, .{ .tag = 21, .op = .write, .node = pager, .handle = twice, .data = "relative\n" }).errno()); try testing.expectEqual(E.INVAL, call(p, .{ .tag = 22, .op = .write, .node = pager, .handle = twice, .data = "/tmp\n" }).errno()); _ = call(p, .{ .tag = 23, .op = .release, .node = pager, .handle = twice }); const relative = wr(p, pager, "relative\n"); @@ -4112,6 +4147,54 @@ test "pager answers its +Pager on the open that asked, whatever another client e try testing.expectEqual(E.NOTDIR, wr(p, pager, "/etc/passwd\n").errno()); } +test "what a /pager open writes after its directory is the text: plain in the body, its colours the pane's, clean, in by the read" { + const p = try withFile(testing.allocator, "x\n"); + defer p.deinit(); + const pager = @intFromEnum(tree.TopFile.pager); + const asked = call(p, .{ .tag = 1, .op = .open, .node = pager, .omode = 2 }).reply.handle; + // The directory and the text's start in one write, escapes and all, a + // second line no directory; the rest in writes after it. + try testing.expectEqual(Status.ok, call(p, .{ .tag = 2, .op = .write, .node = pager, .handle = asked, .data = "/tmp\n\x1b[31mred\x1b[m /a\n" }).reply.status); + try testing.expectEqual(Status.ok, call(p, .{ .tag = 3, .op = .write, .node = pager, .handle = asked, .data = "\x1b]0;title\x07N\x08Next\r\n" }).reply.status); + const id = for (p.panes, 0..) |slot, i| { + const pn = slot orelse continue; + if (pn.file) |f| if (std.mem.eql(u8, f.path, "/tmp/+Pager")) break i; + } else return error.NoPager; + const pn = p.panes[id].?; + try testing.expectEqualStrings("", pn.file.?.content); + // The read that answers the pane finds the text in. + var line: [16]u8 = undefined; + try testing.expectEqualStrings(try std.fmt.bufPrint(&line, "{d}\n", .{pn.serial}), call(p, .{ .tag = 4, .op = .read, .node = pager, .handle = asked, .size = 64 }).bytes); + _ = call(p, .{ .tag = 5, .op = .release, .node = pager, .handle = asked, .opened = true }); + const f = &pn.file.?; + try testing.expectEqualStrings("red /a\nNext\n", f.content); + try testing.expectEqualStrings("red /a\nNext\n", rd(p, Node.of(pn.serial, .body), 0, 64).bytes); + try testing.expectEqual(f.revision, f.saved_revision); + try testing.expectEqual(@as(usize, 2), f.pager_spans.len); + try testing.expectEqualStrings("red", f.content[f.pager_spans[0].start..f.pager_spans[0].end]); + try testing.expectEqual(pardes.Color{ .index = 1 }, f.pager_spans[0].style.fg); + try testing.expect(f.pager_spans[1].style.bold); + // One undo step back to the empty pane. + try testing.expect(f.history.undo_len > 0); + try testing.expectEqualStrings("", f.history.undo[f.history.undo_len - 1].content); + // An edit drops the colours (pager.zig's ponytail). + try testing.expectEqual(Status.ok, call(p, .{ .tag = 6, .op = .write, .node = Node.of(pn.serial, .body), .data = "more\n" }).reply.status); + try testing.expectEqual(@as(usize, 0), f.pager_spans.len); + + // PagerColor off, and an open closed with no read: the same text, plain, + // in at the editor's next step (a close through a mount never waits). + p.settings.pager_color = false; + const shut = call(p, .{ .tag = 7, .op = .open, .node = pager, .omode = 1 }).reply.handle; + try testing.expectEqual(Status.ok, call(p, .{ .tag = 8, .op = .write, .node = pager, .handle = shut, .data = "/tmp\n" }).reply.status); + try testing.expectEqual(Status.ok, call(p, .{ .tag = 9, .op = .write, .node = pager, .handle = shut, .data = "\x1b[1;32mgreen\x1b[m\n" }).reply.status); + _ = call(p, .{ .tag = 10, .op = .release, .node = pager, .handle = shut, .opened = true }); + try testing.expectEqualStrings("", f.content); + fillClosedPagers(p); + try testing.expectEqualStrings("green\n", f.content); + try testing.expectEqual(@as(usize, 0), f.pager_spans.len); + try testing.expectEqual(f.revision, f.saved_revision); +} + test "a command pane an exec open was answered is leased to it while it stays open: another client's command gets a pane of its own" { const p = try withFile(testing.allocator, "x\n"); defer p.deinit(); diff --git a/src/ninep/tree.zig b/src/ninep/tree.zig index 40543ecf..5499a337 100644 --- a/src/ninep/tree.zig +++ b/src/ninep/tree.zig @@ -89,6 +89,7 @@ pub fn needsQuiet(p: *Pardes, req: Req) bool { return switch (req.op) { .write, .setattr => true, .release => req.remove or holdsLines(p, req), + .read => holdsPage(p, req), else => false, }; } @@ -99,8 +100,9 @@ pub fn changesPane(p: *Pardes, req: Req) bool { return switch (req.op) { .write, .setattr => true, .open => req.node == @intFromEnum(TopFile.new), - .release => req.remove or holdsLines(p, req), - .lookup, .getattr, .read, .readdir => false, + .release => req.remove or holdsLines(p, req) or holdsPage(p, req), + .read => holdsPage(p, req), + .lookup, .getattr, .readdir => false, }; } @@ -138,6 +140,10 @@ pub const Open = struct { /// `/listeners`, a ctl opened to read) frozen at the open, as /// `/screen` is: reads in several chunks never splice two moments. frozen: []const u8, + /// A /pager open past its directory line: the +Pager's serial, the + /// text after that line held in `pending` until its read puts it + /// in (ctl.fillPager), or its close hands it to the editor's step. + pager: u32, } = .{ .snapshot = null }, /// What a write to a file of command lines left unfinished: a last line /// with no newline yet, or an Edit block still open. A write through a @@ -194,7 +200,7 @@ pub const Open = struct { gpa.free(run.line); }, .frozen => |bytes| gpa.free(bytes), - .event, .pty_data, .ctl, .lines, .writes => {}, + .event, .pty_data, .ctl, .lines, .writes, .pager => {}, } o.pending.deinit(gpa); if (o.replay) |r| gpa.free(r.bytes); @@ -899,7 +905,7 @@ fn open(p: *Pardes, req: Req, target: Target) Reply { pn.fs.event_reader = pn.fs.event_reader or reader; }, .pty_data => pane_of.?.fs.pty_reader = true, - .run, .ctl, .lines, .writes => {}, + .run, .ctl, .lines, .writes, .pager => {}, } return .{ .tag = req.tag, .handle = @intCast(i + 1) }; } @@ -961,6 +967,12 @@ fn releaseHandle(p: *Pardes, req: Req) void { if (t == .col and t.col.file == .tag) cols.released(p, t.col.serial); if (t == .top and t.top == .tag) cols.released(p, null); const o = openOf(p, req) orelse return; + // A /pager open's text, not read for, goes in at the editor's next + // step (ctl.fillClosedPagers): this close need not wait for quiet. + if (o.what == .pager and o.pending.items.len > 0) { + p.fs.pages.append(p.gpa, .{ .serial = o.what.pager, .bytes = o.pending }) catch o.pending.deinit(p.gpa); + o.pending = .empty; + } // The last line an open wrote with no newline after it runs now. if (o.pending.items.len > 0) { const rest = p.scratch.allocator().dupe(u8, o.pending.items) catch ""; @@ -990,7 +1002,7 @@ fn releaseHandle(p: *Pardes, req: Req) void { .ctl => if (pn.fs.lock == req.handle) { pn.fs.lock = null; }, - .snapshot, .log, .lines, .writes, .frozen => {}, + .snapshot, .log, .lines, .writes, .frozen, .pager => {}, }; o.deinit(p.gpa); } @@ -1014,6 +1026,8 @@ fn setattr(p: *Pardes, req: Req, target: Target) Reply { } fn read(p: *Pardes, req: Req, target: Target) Reply { + // A /pager open's text goes in before its read answers the pane. + if (openOf(p, req)) |o| if (o.what == .pager) ctl.fillPager(p, o.what.pager, &o.pending) catch return Reply.fail(req.tag, E.NOMEM); // A listing reads what it was at the open. if (openOf(p, req)) |o| if (o.what == .frozen) { const bytes = o.what.frozen; @@ -1158,7 +1172,7 @@ fn linesOpen(target: Target, req: Req) bool { /// A release that will run a line its open held back. fn holdsLines(p: *Pardes, req: Req) bool { const o = openOf(p, req) orelse return false; - return o.pending.items.len > 0; + return o.pending.items.len > 0 and o.what != .pager; } /// A line held back longer than this is refused rather than kept growing. @@ -1173,7 +1187,39 @@ fn ctlFile(target: Target) bool { }; } +/// /pager on an open: its first line names the directory and runs as any +/// line does; what follows it, in that write and the open's later ones, is +/// a program's output, escapes and all, held whole and never run as lines. fn write(p: *Pardes, req: Req, target: Target) Reply { + const o = (if (target == .top and target.top == .pager) openOf(p, req) else null) orelse return writeLines(p, req, target); + if (o.what == .pager) { + if (o.pending.items.len + req.data.len > pager_cap) return failText(req.tag, E.NOSPC, "pager: no space: the text is over a file's limit"); + o.pending.appendSlice(p.gpa, req.data) catch return Reply.fail(req.tag, E.NOMEM); + return .{ .tag = req.tag, .written = @intCast(req.data.len) }; + } + const nl = std.mem.indexOfScalar(u8, req.data, '\n') orelse return writeLines(p, req, target); + var head = req; + head.data = req.data[0 .. nl + 1]; + const reply = writeLines(p, head, target); + if (reply.status != .ok or o.results.len == 0) return reply; + o.what = .{ .pager = o.results.list[0] }; + o.pending.clearRetainingCapacity(); + o.pending.appendSlice(p.gpa, req.data[nl + 1 ..]) catch return Reply.fail(req.tag, E.NOMEM); + return .{ .tag = req.tag, .written = @intCast(req.data.len) }; +} + +/// The most a /pager open holds: a file's limit, and `pardes -`'s note +/// that its stdin was cut there. +const pager_cap = @import("../memory.zig").limits.max_file_bytes + 4096; + +/// A /pager open holding text: its read puts it in (ctl.fillPager), its +/// close hands it to the editor's step. +pub fn holdsPage(p: *Pardes, req: Req) bool { + const o = openOf(p, req) orelse return false; + return o.what == .pager and o.pending.items.len > 0; +} + +fn writeLines(p: *Pardes, req: Req, target: Target) Reply { // A command line holds no control character but a tab: the whole write // is refused at once, not held to fail unseen at the close. if (resultsFile(target) or ctlFile(target)) for (req.data) |c| if ((c < ' ' and c != '\t' and c != '\n' and c != '\r') or c == 0x7f) return failText(req.tag, E.INVAL, ctl.e_control); diff --git a/src/pager.zig b/src/pager.zig new file mode 100644 index 00000000..30418623 --- /dev/null +++ b/src/pager.zig @@ -0,0 +1,373 @@ +//! A program's output, paged into a +Pager (`pardes -`): the text it +//! prints, and its SGR colours as spans over that text. ghostty-vt, which +//! terminal panes already drive, parses every escape; this keeps what is +//! printed and how SGR styles it, and drops every other control (cursor +//! motion, OSC titles and hyperlinks, modes). The spans are display state +//! of the pane only: no 9P file reads them (File.recolorSyntax draws them). +const std = @import("std"); +const pardes = @import("pardes.zig"); +const CellStyle = @import("surface.zig").CellStyle; +const ghostty_vt = if (pardes.terminal_panes) @import("ghostty-vt") else struct {}; + +/// Bytes `start..end` of the text, drawn in `style`. A palette colour stays +/// `.index`, resolved through the theme as it is drawn (terminal.palColor), +/// and `.default` is the pane's own. +pub const Span = struct { start: u32, end: u32, style: CellStyle }; + +/// ponytail: past this many spans the rest of a page is plain, rather than +/// ~100 MB of spans for a 256 MiB coloured log; a packed style if it matters. +pub const max_spans = 4 << 20; + +pub const Page = struct { + text: []u8, + spans: []Span, + + pub fn deinit(page: Page, gpa: std.mem.Allocator) void { + gpa.free(page.text); + gpa.free(page.spans); + } +}; + +/// `raw`, a program's output for a terminal, as text and, `colour` on +/// (PagerColor), its spans. Both are `gpa`'s. +pub fn parse(gpa: std.mem.Allocator, raw: []const u8, colour: bool) !Page { + // ponytail: no ghostty-vt on esp32p4 (no terminal panes, no PAGER): + // the text is taken as sent. + if (comptime !pardes.terminal_panes) return .{ .text = try gpa.dupe(u8, raw), .spans = &.{} }; + var h: Handler = .{ .gpa = gpa, .colour = colour }; + errdefer h.text.deinit(gpa); + errdefer h.spans.deinit(gpa); + try h.text.ensureTotalCapacity(gpa, raw.len); + var stream: ghostty_vt.Stream(*Handler) = .init(&h); + defer stream.deinit(); + stream.nextSlice(raw); + if (h.failed) return error.OutOfMemory; + const text = try h.text.toOwnedSlice(gpa); + errdefer gpa.free(text); + return .{ .text = text, .spans = try h.spans.toOwnedSlice(gpa) }; +} + +const Handler = struct { + gpa: std.mem.Allocator, + colour: bool, + text: std.ArrayList(u8) = .empty, + spans: std.ArrayList(Span) = .empty, + /// What SGR has set so far. + style: CellStyle = .{}, + /// Where the line being printed starts, and its last character. + line_start: usize = 0, + last: usize = 0, + /// A carriage return not yet followed by a newline: the line starts + /// over at the next print, as on a terminal, so a progress line keeps + /// its last state. + cr: bool = false, + /// A backspace: the next print strikes over the character before it. + bs: bool = false, + failed: bool = false, + + const Action = ghostty_vt.StreamAction; + + pub fn vt(h: *Handler, comptime action: Action.Tag, value: Action.Value(action)) void { + switch (action) { + .print => h.print(value.cp), + .print_slice => h.printRun(value.cps), + // CSI b repeats the last character, as a terminal draws it; + // a terminal stops at its edge, and this at a line's worth. + .print_repeat => if (h.text.items.len > h.last) { + const cp = std.unicode.utf8Decode(h.text.items[h.last..]) catch return; + for (0..@min(value, 1024)) |_| h.print(cp); + }, + .set_attribute => if (h.colour) h.attribute(value), + .linefeed => { + h.append("\n"); + h.line_start = h.text.items.len; + h.last = h.line_start; + h.cr = false; + h.bs = false; + }, + .carriage_return => h.cr = true, + .backspace => h.bs = h.text.items.len > h.line_start, + .horizontal_tab => for (0..@min(value, 64)) |_| h.print('\t'), + else => {}, + } + } + + pub fn deinit(_: *Handler) void {} + + // ponytail: bytes that are not UTF-8 reach here as U+FFFD (ghostty's + // decoder replaces them, as a terminal shows them); a raw-byte pass + // through the stream if a +Pager must keep them. + fn print(h: *Handler, cp: u21) void { + // A control a terminal acts on and never draws: ghostty's fast path + // hands those past 0x0f (CAN, DEL, the C1 set) on as printed text. + // A tab is HT's, printed here. + if ((cp < 0x20 and cp != '\t') or (cp >= 0x7f and cp < 0xa0)) return; + if (h.cr) { + h.text.shrinkRetainingCapacity(h.line_start); + h.cut(h.line_start); + h.last = h.line_start; + h.cr = false; + h.bs = false; + } + var buf: [4]u8 = undefined; + const n = std.unicode.utf8Encode(cp, &buf) catch std.unicode.utf8Encode(0xfffd, &buf) catch unreachable; + if (h.bs) { + // A man page's overstrike: a character struck over itself is + // bold, one struck with `_` (either way round) is underlined; + // any other is replaced, as on a terminal. + h.bs = false; + const prev = h.text.items[h.last..]; + var struck = h.style; + if (std.mem.eql(u8, prev, buf[0..n])) { + struck.bold = true; + } else if (std.mem.eql(u8, prev, "_")) { + h.text.shrinkRetainingCapacity(h.last); + h.append(buf[0..n]); + struck.ul = .single; + } else if (cp == '_') { + struck.ul = .single; + } else { + h.text.shrinkRetainingCapacity(h.last); + h.cut(h.last); + h.last = h.text.items.len; + h.append(buf[0..n]); + h.span(h.last, h.style); + return; + } + h.cut(h.last); + h.span(h.last, struck); + return; + } + h.last = h.text.items.len; + h.append(buf[0..n]); + h.span(h.last, h.style); + } + + /// A run of printed characters (most of a page): the first as `print` + /// takes it, a pending return or backspace and all, the rest straight + /// on, as one span. A 256 MiB page goes through here. + fn printRun(h: *Handler, cps: []const u32) void { + if (cps.len == 0) return; + h.print(@intCast(cps[0])); + const rest = cps[1..]; + if (rest.len == 0) return; + var need: usize = 0; + for (rest) |cp| need += if (cp < 0x80) 1 else std.unicode.utf8CodepointSequenceLength(@intCast(cp)) catch 3; + h.text.ensureUnusedCapacity(h.gpa, need) catch { + h.failed = true; + return; + }; + const from = h.text.items.len; + for (rest) |cp| { + if (cp < 0x20 or (cp >= 0x7f and cp < 0xa0)) continue; + h.last = h.text.items.len; + if (cp < 0x80) { + h.text.appendAssumeCapacity(@intCast(cp)); + continue; + } + var buf: [4]u8 = undefined; + const n = std.unicode.utf8Encode(@intCast(cp), &buf) catch std.unicode.utf8Encode(0xfffd, &buf) catch unreachable; + h.text.appendSliceAssumeCapacity(buf[0..n]); + } + h.span(from, h.style); + } + + fn append(h: *Handler, bytes: []const u8) void { + h.text.appendSlice(h.gpa, bytes) catch { + h.failed = true; + }; + } + + /// `from` to the text's end drawn in `style`: the span before it goes + /// on when it ends there in the same style. + fn span(h: *Handler, from: usize, style: CellStyle) void { + if (!h.colour or std.meta.eql(style, CellStyle{})) return; + const end: u32 = @intCast(h.text.items.len); + if (h.spans.items.len > 0) { + const tail = &h.spans.items[h.spans.items.len - 1]; + if (tail.end == from and std.meta.eql(tail.style, style)) { + tail.end = end; + return; + } + } + if (h.spans.items.len >= max_spans) return; + h.spans.append(h.gpa, .{ .start = @intCast(from), .end = end, .style = style }) catch { + h.failed = true; + }; + } + + /// No span reaches past `at` any more: the text there is gone. + fn cut(h: *Handler, at: usize) void { + while (h.spans.items.len > 0) { + const tail = &h.spans.items[h.spans.items.len - 1]; + if (tail.end <= at) return; + if (tail.start < at) { + tail.end = @intCast(at); + return; + } + _ = h.spans.pop(); + } + } + + fn attribute(h: *Handler, attr: ghostty_vt.Attribute) void { + const s = &h.style; + switch (attr) { + .unset => s.* = .{}, + .bold => s.bold = true, + // SGR 22 ends faint as well as bold. + .reset_bold => { + s.bold = false; + s.dim = false; + }, + .faint => s.dim = true, + .italic => s.italic = true, + .reset_italic => s.italic = false, + .underline => |u| s.ul = switch (u) { + .none => .off, + .single => .single, + .double => .double, + .curly => .curly, + .dotted => .dotted, + .dashed => .dashed, + }, + .blink => s.blink = true, + .reset_blink => s.blink = false, + .inverse => s.reverse = true, + .reset_inverse => s.reverse = false, + .invisible => s.invisible = true, + .reset_invisible => s.invisible = false, + .strikethrough => s.strikethrough = true, + .reset_strikethrough => s.strikethrough = false, + .direct_color_fg => |c| s.fg = .{ .rgb = .{ c.r, c.g, c.b } }, + .direct_color_bg => |c| s.bg = .{ .rgb = .{ c.r, c.g, c.b } }, + .@"8_fg", .@"8_bright_fg" => |name| s.fg = .{ .index = @intFromEnum(name) }, + .@"8_bg", .@"8_bright_bg" => |name| s.bg = .{ .index = @intFromEnum(name) }, + .@"256_fg" => |i| s.fg = .{ .index = i }, + .@"256_bg" => |i| s.bg = .{ .index = i }, + .reset_fg => s.fg = .default, + .reset_bg => s.bg = .default, + // A cell has no overline and no underline colour to take. + .overline, .reset_overline, .underline_color, .@"256_underline_color", .reset_underline_color, .unknown => {}, + } + } +}; + +// ---- tests ---- + +const testing = std.testing; + +/// The text `raw` pages to, and its spans as `text[start..end]=style` lines. +fn expectPage(raw: []const u8, text: []const u8, spans: []const struct { []const u8, CellStyle }) !void { + if (comptime !pardes.terminal_panes) return error.SkipZigTest; + const page = try parse(testing.allocator, raw, true); + defer page.deinit(testing.allocator); + try testing.expectEqualStrings(text, page.text); + for (spans, 0..) |want, i| { + if (i >= page.spans.len) { + std.debug.print("missing span {d}: \"{s}\"\n", .{ i, want[0] }); + return error.TestExpectedEqual; + } + const got = page.spans[i]; + try testing.expectEqualStrings(want[0], page.text[got.start..got.end]); + try testing.expectEqualDeep(want[1], got.style); + } + try testing.expectEqual(spans.len, page.spans.len); +} + +test "git log --color: the commit line yellow, the rest plain" { + try expectPage( + "\x1b[33mcommit 0123abc\x1b[m\x1b[33m (\x1b[m\x1b[1;36mHEAD -> \x1b[m\x1b[1;32mmain\x1b[m\x1b[33m)\x1b[m\nAuthor: a \n\n subject\n", + "commit 0123abc (HEAD -> main)\nAuthor: a \n\n subject\n", + &.{ + .{ "commit 0123abc (", .{ .fg = .{ .index = 3 } } }, + .{ "HEAD -> ", .{ .fg = .{ .index = 6 }, .bold = true } }, + .{ "main", .{ .fg = .{ .index = 2 }, .bold = true } }, + .{ ")", .{ .fg = .{ .index = 3 } } }, + }, + ); +} + +test "ls --color=always: 01;34 directories and 01;32 executables, reset by 0 and none" { + try expectPage( + "\x1b[0m\x1b[01;34mdir\x1b[0m\n\x1b[01;32mrun.sh\x1b[0m\nplain.txt\n", + "dir\nrun.sh\nplain.txt\n", + &.{ + .{ "dir", .{ .fg = .{ .index = 4 }, .bold = true } }, + .{ "run.sh", .{ .fg = .{ .index = 2 }, .bold = true } }, + }, + ); +} + +test "grep --color=always: the match, the file name and the separator, and EL dropped" { + try expectPage( + "\x1b[35m\x1b[Ka.txt\x1b[m\x1b[K\x1b[36m\x1b[K:\x1b[m\x1b[Kone \x1b[01;31m\x1b[Kfoo\x1b[m\x1b[K two\n", + "a.txt:one foo two\n", + &.{ + .{ "a.txt", .{ .fg = .{ .index = 5 } } }, + .{ ":", .{ .fg = .{ .index = 6 } } }, + .{ "foo", .{ .fg = .{ .index = 1 }, .bold = true } }, + }, + ); +} + +test "a man page's overstrike: bold and underline, and a stray backspace" { + try expectPage( + "N\x08NA\x08AM\x08ME\x08E _\x08u_\x08s x\x08_ a\x08b\x08\n", + "NAME us x b\n", + &.{ + .{ "NAME", .{ .bold = true } }, + .{ "us", .{ .ul = .single } }, + .{ "x", .{ .ul = .single } }, + }, + ); +} + +test "truecolor, 256 colours, background, italic, faint, inverse and curly underline" { + try expectPage( + "\x1b[38;2;255;128;0mo\x1b[48;5;236mb\x1b[0;3;2mi\x1b[7mr\x1b[0;4:3mc\x1b[m.\n", + "obirc.\n", + &.{ + .{ "o", .{ .fg = .{ .rgb = .{ 255, 128, 0 } } } }, + .{ "b", .{ .fg = .{ .rgb = .{ 255, 128, 0 } }, .bg = .{ .index = 236 } } }, + .{ "i", .{ .italic = true, .dim = true } }, + .{ "r", .{ .italic = true, .dim = true, .reverse = true } }, + .{ "c", .{ .ul = .curly } }, + }, + ); +} + +test "every other escape is dropped, and a stray or broken one loses no text after it" { + const cases = [_][2][]const u8{ + .{ "a\x1b]8;;http://x\x1b\\link\x1b]8;;\x07b", "alinkb" }, + .{ "\x1b]0;title\x07\x1b[2J\x1b[H\x1b[?1049hdone\n", "done\n" }, + .{ "\x1b(Bdone", "done" }, + .{ "plain\ttext\n", "plain\ttext\n" }, + .{ "a\r\nb\r\n", "a\nb\n" }, + .{ "10%\r50%\r\x1b[K100%\ndone\n", "100%\ndone\n" }, + .{ "x\x00y\x07z\x0e\x0f\n", "xyz\n" }, + // Controls ghostty's fast path prints: CAN, FS, DEL and a C1. + .{ "x\x18y\x1cz\x7f!\u{85}?\n", "xyz!?\n" }, + // A broken CSI: its parameter bytes are eaten up to a final byte, as + // a terminal eats them; CAN abandons one, and the text goes on. + .{ "a\x1b[31;\x18b\x1b[m\n", "ab\n" }, + // An unknown SGR changes nothing; an ESC at the very end is dropped. + .{ "\x1b[99mz\x1b", "z" }, + }; + for (cases) |c| try expectPage(c[0], c[1], &.{}); +} + +test "bytes that are not UTF-8 page as U+FFFD, the text around them kept" { + try expectPage("caf\xe9 \xff\xfe ok\n", "caf\u{fffd} \u{fffd}\u{fffd} ok\n", &.{}); +} + +test "PagerColor off: the same text, no spans, overstrike included" { + if (comptime !pardes.terminal_panes) return error.SkipZigTest; + const page = try parse(testing.allocator, "\x1b[31mred\x1b[m N\x08N\n", false); + defer page.deinit(testing.allocator); + try testing.expectEqualStrings("red N\n", page.text); + try testing.expectEqual(@as(usize, 0), page.spans.len); +} + +test "a carriage return's rewrite takes the spans of what it rewrote with it" { + try expectPage("\x1b[31m10%\r\x1b[32m100%\x1b[m\n", "100%\n", &.{.{ "100%", .{ .fg = .{ .index = 2 } } }}); +} diff --git a/src/pardes.zig b/src/pardes.zig index c6850451..5d9f8606 100644 --- a/src/pardes.zig +++ b/src/pardes.zig @@ -11,6 +11,7 @@ pub const ctlfs = @import("ninep/tree.zig"); pub const syntax = @import("syntax.zig"); const tracy = @import("tracy.zig"); pub const panes = @import("panes.zig"); +pub const pager = @import("pager.zig"); const locations = @import("locations.zig"); pub const tagline = @import("tagline.zig"); pub const exec = @import("exec.zig"); @@ -496,6 +497,7 @@ test { _ = @import("recent.zig"); _ = @import("Presentation.zig"); _ = @import("animation.zig"); + _ = @import("pager.zig"); } pub const Builtin = builtins.registry.Builtin(); @@ -4221,7 +4223,8 @@ pub const Options = struct { file: ?[]const u8 = null, file_line: usize = 0, missing: ?struct { word: []const u8, dir: []const u8 } = null, - /// `pardes -`: stdin, its escapes stripped, for a +Pager pane at boot. + /// `pardes -`: stdin as it came, for a +Pager pane at boot (pager.zig + /// parses it). stdin_text: ?[]const u8 = null, tty_toggle: u21 = config.tty_toggle_default, /// load a dump of another instance instead of spawning shells (acme -l) @@ -4638,7 +4641,9 @@ pub const Pardes = struct { p.oneColumn(); }, .stdin => { - const content = try gpa.dupe(u8, opts.stdin_text.?); + const page = try pager.parse(gpa, opts.stdin_text.?, p.settings.pager_color); + errdefer gpa.free(page.spans); + const content = page.text; errdefer gpa.free(content); const dir = p.sessionDir(); const shown = try panes.Output.open(p, 0, dir, .{ .cmd = .New }, "", content); @@ -4647,6 +4652,7 @@ pub const Pardes = struct { gpa.free(shown.file.?.path); shown.file.?.path = named; shown.file.?.pager_diff = panes.File.looksLikeDiff(content[0..@min(content.len, 64 * 1024)]); + shown.file.?.pager_spans = page.spans; p.oneColumn(); }, .embedded => { @@ -5748,6 +5754,8 @@ pub const Pardes = struct { if (v.now) |clock| p.advance(clock(h.ctx)); // What a 9P open wrote in a row goes in once the writes pause. ctlfs.pane.flushPausedBatch(p); + // ...and what a /pager open was written before its close. + ctlfs.ctl.fillClosedPagers(p); while (p.nextQueued()) |ev| p.update(ev); while (p.nextEffect()) |e| p.perform(e); turn.settle(); diff --git a/test/fs.py b/test/fs.py index 8eed2e29..33abb835 100644 --- a/test/fs.py +++ b/test/fs.py @@ -1529,6 +1529,26 @@ def test(binary, quic=False): log_now = client.read('/log').decode() assert f'\nnew {made_now} {root}/+Pager\n' in '\n' + log_now, log_now[-400:] assert f'\nrename {made_now} ' not in '\n' + log_now + # Its colours are the pane's, drawn and never read: the body is + # the plain text, and the screen shows `red` in the theme's red + # and `rgb` in the colour given, the rest in the pane's ink. + fed = subprocess.run([binary, '-'], cwd=root, env=env, + input=b'\x1b]0;title\x07\x1b[31mred\x1b[m \x1b[38;2;1;2;3mrgb\x1b[m plain\n', + stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=10) + assert fed.returncode == 0, fed.stderr + assert client.read(f'/pane/{made_now}/body') == b'red rgb plain\n' + screen = client.screen() + for row in range(screen['rows']): + cells = screen['cells'][row * screen['cols']:(row + 1) * screen['cols']] + text = ''.join(cell[0] for cell in cells) + at = text.find('red rgb plain') + if at >= 0: + break + else: + raise AssertionError(('the paged text is not on the screen', screen)) + ink = [screen['styles'][cells[at + i][1]]['fg'] for i in (0, 4, 8)] + assert ink[1] == {'rgb': [1, 2, 3]}, ink + assert ink[0] != ink[2] and ink[0] != ink[1], ink # The directory's one +Pager: the next paged text refills it. fed = subprocess.run([binary, '-'], cwd=root, env=env, input=b'again\r\nprogress 10%\rprogress 100%\n', stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=10) diff --git a/test/selfmount.py b/test/selfmount.py index ddfb77dc..57dfffa8 100644 --- a/test/selfmount.py +++ b/test/selfmount.py @@ -182,6 +182,20 @@ def run(binary): log = client.read('/log').decode() check(log.count('over 1 MiB') == 1 and 'unknown control message' not in log and 'after-long' in log, 'a 1.1 MiB line is refused once, its tail never a line, the next line runs') + # `pardes -` by hand through the mount: the directory, then a + # program's output, escapes and all, on one open of /pager; the + # +Pager reads back the plain text. + got = run(f"{{ pwd; printf '\\033[31mred\\033[m\\n'; }} > {mount}/pager\n".encode()) + rows = [row.rsplit(maxsplit=1)[0].split(maxsplit=3) for row in client.read('/index').decode().splitlines()] + paged = [row[0] for row in rows if len(row) == 4 and row[3].endswith('/+Pager')] + check(got == '0' and len(paged) == 1, f'a +Pager made through the mount ({got!r}, {paged!r})') + if paged: + # The text goes in at the open's close, and a mount's close + # (FUSE's release) comes after close(2) has returned. + deadline = time.monotonic() + 5 + while (said := client.read(f'/pane/{paged[0]}/body')) != b'red\n' and time.monotonic() < deadline: + time.sleep(.05) + check(said == b'red\n', f'its body is the plain text ({said!r})') # Forty event reads held through the mount, a follower each, and # the mount still answers the rest: 9ns keeps workers past what # the editor holds (128), so `cat layout` is not queued behind diff --git a/test/snapshots/pagercolor.golden b/test/snapshots/pagercolor.golden new file mode 100644 index 00000000..811d3d96 --- /dev/null +++ b/test/snapshots/pagercolor.golden @@ -0,0 +1,120 @@ +== snap pager grid=100x50 cursor=4,5 +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit +| New Tty Find Grep Joincol Delcol +|$ /tmp/pardes-snap/pagercolor/cwd Tty+bash Save Mode Filter Collapse Del +| $ printf '\033]0;title\007\033[31mred\033[m \033[1;32mbold green\033[m \033[38;2;200;100;0mrgb\033 +| [m \033[4mul\033[m N\bNA\bAM\bME\bE _\bu_\bs plain\n' | $(readlink /proc/$PPID/exe) - +| $ +| +| +| +| +| +| +| +| +| +| +| +| +| +| +| +| +| +| +| +| +| +| +| +| +| +| +| +| +| /tmp/pardes-snap/pagercolor/cwd/+New Save Tty Collapse Del +| 1 +| +| +| +| +| +| +| /tmp/pardes-snap/pagercolor/cwd/+Pager Save Tty Collapse Del +| 1 red bold green rgb ul NAME us plain +| 2 +== style pager-colours grid=100x50 +|0: 0-99 #b2c3b8,#1d2824, +|1: 0-1 d,#887455, 2-2 d,#314738, 3-99 #becfc4,#314738, +|2: 0-1 #000000,#add38a, 2-2 #000000,#314738, 3-34 #becfc4,#314738, 35-43 #dfbce5,#314738, 44-99 #becfc4,#314738, +|3: 0-0 d,#608269, 1-1 d,#0d1410, 2-99 #e5eee5,#0d1410, +|4: 0-0 d,#608269, 1-1 d,#0d1410, 2-99 #e5eee5,#0d1410, +|5: 0-0 d,#608269, 1-1 d,#0d1410, 2-99 #e5eee5,#0d1410, +|6: 0-0 d,#608269, 1-99 d,#0d1410, +|7: 0-0 d,#608269, 1-99 d,#0d1410, +|8: 0-0 d,#608269, 1-99 d,#0d1410, +|9: 0-0 d,#608269, 1-99 d,#0d1410, +|10: 0-0 d,#608269, 1-99 d,#0d1410, +|11: 0-0 d,#608269, 1-99 d,#0d1410, +|12: 0-0 d,#608269, 1-99 d,#0d1410, +|13: 0-0 d,#608269, 1-99 d,#0d1410, +|14: 0-0 d,#608269, 1-99 d,#0d1410, +|15: 0-0 d,#608269, 1-99 d,#0d1410, +|16: 0-0 d,#608269, 1-99 d,#0d1410, +|17: 0-0 d,#608269, 1-99 d,#0d1410, +|18: 0-0 d,#608269, 1-99 d,#0d1410, +|19: 0-0 d,#608269, 1-99 d,#0d1410, +|20: 0-0 d,#608269, 1-99 d,#0d1410, +|21: 0-0 d,#608269, 1-99 d,#0d1410, +|22: 0-0 d,#608269, 1-99 d,#0d1410, +|23: 0-0 d,#608269, 1-99 d,#0d1410, +|24: 0-0 d,#608269, 1-99 d,#0d1410, +|25: 0-0 d,#608269, 1-99 d,#0d1410, +|26: 0-0 d,#608269, 1-99 d,#0d1410, +|27: 0-0 d,#608269, 1-99 d,#0d1410, +|28: 0-0 d,#608269, 1-99 d,#0d1410, +|29: 0-0 d,#608269, 1-99 d,#0d1410, +|30: 0-0 d,#608269, 1-99 d,#0d1410, +|31: 0-0 d,#608269, 1-99 d,#0d1410, +|32: 0-0 d,#608269, 1-99 d,#0d1410, +|33: 0-0 d,#608269, 1-99 d,#0d1410, +|34: 0-1 d,#496656, 2-2 d,#1d2824, 3-34 #b2c3b8,#1d2824, 35-39 #d3b0d9,#1d2824, 40-99 #b2c3b8,#1d2824, +|35: 0-0 d,#608269, 1-4 d,#0d1410, 5-99 #59675c,#0d1410, +|36: 0-0 d,#608269, 1-99 d,#0d1410, +|37: 0-0 d,#608269, 1-99 d,#0d1410, +|38: 0-0 d,#608269, 1-99 d,#0d1410, +|39: 0-0 d,#608269, 1-99 d,#0d1410, +|40: 0-0 d,#608269, 1-99 d,#0d1410, +|41: 0-0 d,#608269, 1-99 d,#0d1410, +|42: 0-1 d,#496656, 2-2 d,#1d2824, 3-34 #b2c3b8,#1d2824, 35-41 #d3b0d9,#1d2824, 42-99 #b2c3b8,#1d2824, +|43: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-10 #f1a39b,#0d1410, 11-20 #b6ce94,#0d1410,b 21-21 #b6ce94,#0d1410, 22-25 #c86400,#0d1410, 26-27 #e5eee5,#0d1410,u 28-28 #e5eee5,#0d1410, 29-32 #e5eee5,#0d1410,b 33-33 #e5eee5,#0d1410, 34-35 #e5eee5,#0d1410,u 36-99 #e5eee5,#0d1410, +|44: 0-0 d,#608269, 1-4 d,#0d1410, 5-99 #59675c,#0d1410, +|45: 0-0 d,#608269, 1-99 d,#0d1410, +|46: 0-0 d,#608269, 1-99 d,#0d1410, +|47: 0-0 d,#608269, 1-99 d,#0d1410, +|48: 0-0 d,#608269, 1-99 d,#0d1410, +|49: 0-0 d,#608269, 1-99 d,#0d1410, +== snap pager-diff grid=100x50 cursor=4,8 +|5: $ printf '\033[33mcommit 0123\033[33mabc\033[m\n\033[1mdiff --git a/x b/x\033[m\n\033[1m--- a/x\03 +|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: $ +|43: 1 commit 0123abc +|44: 2 diff --git a/x b/x +|45: 3 --- a/x +|46: 4 +++ b/x +|47: 5 @@ -1 +1 @@ +|48: 6 -old +|49: 7 +new +== style pager-diff-colours grid=100x50 +|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, +|43: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-99 #e9c680,#0d1410, +|44: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-24 #b9f480,#0d1410,b 25-99 #b9f480,#0d1410, +|45: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-13 #b9f480,#0d1410,b 14-99 #b9f480,#0d1410, +|46: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-13 #b9f480,#0d1410,b 14-99 #b9f480,#0d1410, +|47: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-99 #b6c59e,#0d1410, +|48: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-7 #f1a39b,#302b25,b 8-99 #f8c082,#302b25, +|49: 0-0 d,#152019, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-7 #b6ce94,#263025,b 8-99 #b8d88a,#263025, diff --git a/test/snapshots/pagercolor.snap b/test/snapshots/pagercolor.snap new file mode 100644 index 00000000..650792b3 --- /dev/null +++ b/test/snapshots/pagercolor.snap @@ -0,0 +1,24 @@ +# `pardes -` keeps a program's colours (PagerColor, on by default): its SGR +# becomes the +Pager's own colours over the plain text (red through the +# theme's palette, truecolor as given, bold and underline, a man page's +# overstrike), and every other escape (the OSC title) is dropped. The +# needles waited for are split by escapes in the typed line, so only the +# paged text holds them. +start 50 100 +wait 8000 $ +stable 700 20000 +text printf '\033]0;title\007\033[31mred\033[m \033[1;32mbold green\033[m \033[38;2;200;100;0mrgb\033[m \033[4mul\033[m N\bNA\bAM\bME\bE _\bu_\bs plain\n' | $(readlink /proc/$PPID/exe) - +key enter +wait 20000 red bold green +stable 700 20000 +snap pager +snapstyle pager-colours +# A coloured diff: the rows pardes tints as added or removed are drawn as +# its own diff, and git's colours stay on the rest (the bold header, the +# cyan hunk line, the yellow commit line). +text printf '\033[33mcommit 0123\033[33mabc\033[m\n\033[1mdiff --git a/x b/x\033[m\n\033[1m--- a/x\033[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' | $(readlink /proc/$PPID/exe) - +key enter +wait 20000 0123abc +stable 700 20000 +snap pager-diff +snapstyle pager-diff-colours -- cgit v1.3 From 25844b54fd08dd9cadff2275f2161ee5dd316395 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Thu, 1 Oct 2026 10:38:06 -0300 Subject: `pardes --wait` whose $PARDES_9P no longer answers says the session is gone, exit 1, instead of drawing a screen of its own in the asker's terminal Co-Authored-By: Claude Opus 5.5 --- src/main.zig | 12 +++++++++++- test/fs.py | 5 +++++ 2 files changed, 16 insertions(+), 1 deletion(-) (limited to 'src/main.zig') diff --git a/src/main.zig b/src/main.zig index 6d895307..f6a3a3ec 100644 --- a/src/main.zig +++ b/src/main.zig @@ -514,7 +514,17 @@ fn nativeMain(init: std.process.Init) !void { // Does it answer? One that answers takes the file or says why not, // as acme's B does: from here on never a nested editor, whose // screen would be drawn inside the pane that asked. - ninep_io.Client.probe(arena, parent.dial) catch break :forwarding; + ninep_io.Client.probe(arena, parent.dial) catch { + // `--wait` is someone's EDITOR waiting on that session: a screen + // of its own drawn in their terminal is no answer. Said, exit 1. + if (wait) { + var buf: [4300]u8 = undefined; + const text = std.fmt.bufPrint(&buf, "pardes: --wait: the session at {s} does not answer; it is gone\n", .{parent.dial[0..@min(parent.dial.len, 4096)]}) catch "pardes: --wait: the session does not answer\n"; + std.Io.File.stderr().writeStreamingAll(init.io, text) catch {}; + std.process.exit(1); + } + break :forwarding; + }; const Refuse = struct { fn with(io: std.Io, what: []const u8, err: anyerror) noreturn { var words_buf: [128]u8 = undefined; diff --git a/test/fs.py b/test/fs.py index 33abb835..204f4b37 100644 --- a/test/fs.py +++ b/test/fs.py @@ -1424,6 +1424,11 @@ def test(binary, quic=False): assert waiting.poll() is None, waiting.stderr.read() client.remove(f'/pane/{far_pane}') assert waiting.wait(timeout=5) == 0 + # --wait with a $PARDES_9P that answers no more: said, exit 1, + # never a screen of its own drawn in the asker's terminal. + dead_env = dict(outside_env, PARDES_9P=str(root / 'pardes-9p-gone.sock')) + gone = subprocess.run([binary, '--wait', str(far)], cwd=root, env=dead_env, capture_output=True, timeout=10) + assert gone.returncode == 1 and b'does not answer' in gone.stderr, gone # `--` ends the options: a name starting with a dash is a name. dash = root / '-dash.txt' dash.write_bytes(b'dash\n') -- cgit v1.3 From 6637d8df988f8cff9d054c39d3781f4a1ede3b8e Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Fri, 2 Oct 2026 00:56:05 -0300 Subject: pardes --wait with no FILE says it needs one; --detach over a name another session's socket holds (a plain session is named by its pid) says so plainly, and any other failure of it in words, never a Zig error trace Co-Authored-By: Claude Opus 5.5 --- src/main.zig | 17 ++++++++++++++++- test/fs.py | 3 +++ 2 files changed, 19 insertions(+), 1 deletion(-) (limited to 'src/main.zig') diff --git a/src/main.zig b/src/main.zig index f6a3a3ec..ed70b624 100644 --- a/src/main.zig +++ b/src/main.zig @@ -466,6 +466,10 @@ fn nativeMain(init: std.process.Init) !void { opts.mounts = mounts[0..mounts_len]; if (detach != null and attach != null) badArgs(init.io, "--detach and --attach are opposites: one runs the session, the other joins one", .{}); + // --wait waits on the pane a FILE opens: with none there is nothing to + // wait for (EDITOR=pardes --wait is given the file). + if (wait and positional == null) + badArgs(init.io, "--wait needs a FILE: it returns when that file's pane is closed", .{}); if (opts.ninep_name.len != 0 and attach != null) badArgs(init.io, "--9p names a session's own socket, and --attach has none of its own", .{}); if (opts.ninep_tcp != null and attach != null) @@ -709,7 +713,18 @@ fn nativeMain(init: std.process.Init) !void { name else try std.fmt.allocPrint(arena, "{d}", .{@as(u32, @intCast(std.c.getpid()))}); - return @import("detached/server.zig").run(init, opts, named); + // Said plainly, never a Zig error trace: a name another session's + // socket holds already (a plain session is named by its pid too). + return @import("detached/server.zig").run(init, opts, named) catch |err| { + var words: [128]u8 = undefined; + var said: [512]u8 = undefined; + const why = if (err == error.ListenFailed) + "its socket is taken: another session (a plain one is named by its pid) holds that name; choose another" + else + pardes.Messages.errorWords(err, &words); + std.Io.File.stderr().writeStreamingAll(init.io, std.fmt.bufPrint(&said, "pardes: --detach={s}: {s}\n", .{ named, why }) catch "pardes: --detach failed\n") catch {}; + std.process.exit(1); + }; } if (attach != null and pardes.platform != .tty and pardes.platform != .gui) { try std.Io.File.stderr().writeStreamingAll(init.io, "pardes: --attach needs the tty or gui shell\n"); diff --git a/test/fs.py b/test/fs.py index f954b508..97af9e6b 100644 --- a/test/fs.py +++ b/test/fs.py @@ -1595,6 +1595,9 @@ def test(binary, quic=False): dead_env = dict(outside_env, PARDES_9P=str(root / 'pardes-9p-gone.sock')) gone = subprocess.run([binary, '--wait', str(far)], cwd=root, env=dead_env, capture_output=True, timeout=10) assert gone.returncode == 1 and b'does not answer' in gone.stderr, gone + # --wait with no FILE says it needs one, and waits on nothing. + bare = subprocess.run([binary, '--wait'], cwd=root, env=env, capture_output=True, timeout=10) + assert bare.returncode == 1 and b'--wait needs a FILE' in bare.stderr, bare # `--` ends the options: a name starting with a dash is a name. dash = root / '-dash.txt' dash.write_bytes(b'dash\n') -- cgit v1.3 From 046979b877f02a91cf52cc86b84c5619cb9363d3 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Tue, 6 Oct 2026 19:06:32 -0300 Subject: Def and Refs in a language-served file's tag, a diff viewer's tinted word edits, context rows that hold still under a scroll, and the pardes skill Def and Refs (gd, gr, Ctrl-click; chorded 2-1 at the selection) for a file a language server speaks for; hunks.zig stacks a unified diff as a diff viewer does, its changed words on a tinted ground as delta's do; the tree-sitter context rows stay put while the body glides under a scroll; .agents/skills gains the pardes skill beside pardes-9p. --- .agents/skills/pardes-9p/SKILL.md | 110 +++-- .agents/skills/pardes/SKILL.md | 131 ++++++ docs/typ/builtins-gui.json | 6 +- docs/typ/builtins-tty.json | 6 +- docs/typ/guide.typ | 15 +- docs/typ/reference.typ | 27 +- docs/typ/setup.typ | 2 +- src/CHANGELOG.md | 6 + src/File.zig | 69 ++- src/Output.zig | 90 +++- src/builtins.zig | 49 +- src/config.zig | 27 +- src/edit_cmd.zig | 2 + src/gui/gui.zig | 69 ++- src/hunks.zig | 808 +++++++++++++++++++++++++++++++++ src/locations.zig | 4 +- src/look.zig | 12 + src/main.zig | 2 +- src/mouse.zig | 2 +- src/ninep/ctl.zig | 41 +- src/ninep/tree.zig | 2 +- src/normal.zig | 17 +- src/pardes.zig | 115 ++++- src/syntax.zig | 17 +- src/tagline.zig | 18 +- src/terminal.zig | 42 +- test/snapshots/diffview.golden | 6 +- test/snapshots/lsp-client-edit.golden | 8 +- test/snapshots/lsp-client.golden | 4 +- test/snapshots/lsp-rename-files.golden | 4 +- test/snapshots/lsp-rename.golden | 6 +- test/snapshots/lsp.golden | 4 +- test/snapshots/lspcomplete.golden | 10 +- test/snapshots/lspcompletemoved.golden | 2 +- test/snapshots/lspdebug.golden | 2 +- test/snapshots/lsprelpath.golden | 8 +- test/snapshots/ninep.golden | 18 +- test/snapshots/pagercolor.golden | 35 +- test/snapshots/selregex.golden | 6 +- test/snapshots/syntax.golden | 30 +- 40 files changed, 1625 insertions(+), 207 deletions(-) create mode 100644 .agents/skills/pardes/SKILL.md create mode 100644 src/hunks.zig (limited to 'src/main.zig') diff --git a/.agents/skills/pardes-9p/SKILL.md b/.agents/skills/pardes-9p/SKILL.md index 06edbdf2..2b80c975 100644 --- a/.agents/skills/pardes-9p/SKILL.md +++ b/.agents/skills/pardes-9p/SKILL.md @@ -1,54 +1,104 @@ --- name: pardes-9p -description: Inspect and drive a running Pardes editor through its virtual filesystem (served over 9P), or exercise its panes, builtins, terminal input and rendered output in an isolated session. Use for Pardes interaction, plugin development and end-to-end debugging. +description: Script and drive a running pardes session through its virtual filesystem (served over 9P), or exercise its panes, builtins, terminals, events and rendered screen in an isolated session. Use for reading or editing panes, opening files at places, running commands and reading their output, event helpers and tag words, plugin development and end-to-end debugging. For what pardes is and its keys, use the pardes skill. --- -# Pardes over 9P +# pardes over 9P -Pardes is files: `cat`, `echo >`, `ls` and shell scripts are the whole -interface. The recipes are in the Scripting chapter -([docs/typ/scripting.typ](../../../docs/typ/scripting.typ)), every file's -semantics in the Reference chapter -([docs/typ/reference.typ](../../../docs/typ/reference.typ)), and a running -session serves a summary at `$m/README`. Paths are relative to the -repository root. +pardes is files: `cat`, `echo >`, `ls` and shell scripts are the whole +interface. The recipes and traps are the Scripting chapter +(`docs/typ/scripting.typ`), every file's semantics, refusals and limits the +Reference chapter (`docs/typ/reference.typ`; its "The tree" lists every +file), and a running session serves a one-screen summary at `$m/README`. +Paths are relative to the pardes source tree, the repository this skill +lives in (`readlink -f` this skill's directory if it is reached through a +symlink). ## Find the session +First check that you run inside a live session (the pardes skill's "Am I +in a pardes session?"); a session merely listed under `$NINE_MOUNT/pardes/` +is someone's, not yours to script. + ```sh m=${PARDES_MOUNT:-} [ -n "$m" ] || echo 'no mount: use 9p -a "unix!$PARDES_9P" read index' -cat "$m/index" +cat "$m/index" # serial kind(text|term|cmd|pdf|image) dirty name column ``` Under `9ns --mntgen` every pane gets `$PARDES_MOUNT`, its session as a -directory (also in a `Tty9p` shell). `$PARDES_9P` is the session socket of -the pane you run in, `$PARDES_PANE` that pane's serial. A dead session's -entry answers `Input/output error`: name the session, never glob. Without a -mount, plan9port's `9p -a "unix!$PARDES_9P"` works, and `test/ninep.py` in the source tree (Reference, "Other ways in"). +directory (also in a `Tty9p` shell). `$PARDES_9P` is the session socket, +`$PARDES_PANE` the serial of the pane the shell runs in, `$winid` the pane +a command was clicked in. Without a mount, `cat $m/x` is +`9p -a "unix!$PARDES_9P" read x` (its `write` truncates: on `body` it +replaces the text), and `test/ninep.py` is a Python client for holding a +fid open (Reference, "Other ways in"). A dead session's registry entry +answers `Input/output error`: name the session, never glob. + +## Recipes + +Work through a pane of your own, its own `look` and `exec`: + +```sh +n=$(cat $m/pane/new); p=$m/pane/$n # read pane/new once: each open makes a pane +exec 3<>$p/look; echo "$PWD/main.zig:120" >&3; cat <&3; exec 3<&- # open at a place; read: its pane +printf 'hello\n' > $p/body; echo "$PWD/x.txt" > $p/name; echo Save > $p/ctl +echo 'Msg hello' > $p/exec # a builtin, or else a shell line +echo 'Edit ,x/foo/c/bar/' > $p/ctl # sam's Edit, one undo step +echo /old/ > $p/addr && printf new > $p/data # replace the next match +t=$(awk '$2=="term"{print $1; exit}' $m/index) # a shell (bash or fish) +exec 3<>$m/pane/$t/pty/run; echo make >&3; cat <&3; exec 3<&- # exit N, then output +exec 3<>$m/log; echo 'follow new' >&3; timeout 30 cat <&3; exec 3<&- +rmdir $p # close it +``` + +The Scripting chapter has the rest: a command pane's output, typing into +a terminal, the language server, a tag word on `PATH` (`Fmt`), and event +helpers that own clicks through `pane//event`. ## Traps - A refused write says only `Invalid argument` or `Input/output error`; `grep '^err' $m/log | tail -1` says why. Not the log's last line: after - a refused Del, Exit or Restore that may be `+Unsaved`'s `new`. -- Work through a pane of your own (`n=$(cat $m/pane/new)`) and its own - `look` and `exec`: the root's act at the pane with the keyboard, which another - client, an idle shell or an event helper may own. -- `head` on `index`, `layout`, `log` or `recent` through 9ns says `Illegal - seek`: use `sed -n 1p`. In `index`, `term` is a shell, `cmd` a command's - pane. + a refused Del, Exit or Restore that may be `+Unsaved`'s `new`. A write + that succeeds logs nothing. +- The root `look` and `exec` act at the pane with the keyboard, which + another client, an idle shell or an event helper may own: use a pane's. +- Read `look`, `exec` or `pager` on the open you wrote (`exec 3<>…`): a + fresh open reads the session's last answer, from whichever client. +- A command pane your `exec` open was answered is yours while that open + stays open: read its `body` before you close it. - `addr` is the pane's and moves on: each `/re/` searches from the last address, and a `data` write leaves it just past the text. Write `addr` before each replacement; a failed address leaves none. - An Edit `x` that matches nothing succeeds: check the text afterwards. -- Each open of `pane/new` makes a pane: read it once. -- Through a mount, `printf 'a\nb\n' > ctl` arrives one write per line: send - a block as one write (`cat block > $p/ctl`), ending in a newline. +- Through a mount, `printf 'a\nb\n' > ctl` arrives one write per line: + send a block as one write, ending in a newline (a last line without one + runs after the close, its failure only in the log). +- Read `event` on a descriptor your shell owns (`exec 3<>$p/event`), + never `cat $p/event | while read`: the `cat` outlives the loop and + swallows the next click. +- The session has 64 open records shared by every client (held reads, + write opens of command files, snapshots): close what you open. +- `head` on `index`, `layout`, `log` or `recent` through 9ns says `Illegal + seek`: use `sed -n 1p`. - Pane words (`Save`, `Undo`, `Del`) go to `pane//ctl`, settings and - session words to `$m/ctl`. -- `Exit`, `Restore`, `Del` and `get` refuse once over unsaved text. -- Never experiment on a session someone is using: strip every `PARDES_*` - variable and start your own (Scripting, "An isolated session"); build - with `-Dplatform=tty`, since a bare `zig build` installs over - `~/.local/bin`. + session words to `$m/ctl`. `Exit`, `Restore`, `Del` and `get` refuse once + over unsaved text; the same word again discards. + +## An isolated session + +Never experiment on a session someone is using. Under `9ns --mntgen`: + +```sh +env -i PATH="$PATH" HOME="$(mktemp -d)" XDG_RUNTIME_DIR="$XDG_RUNTIME_DIR" SHELL=/usr/bin/bash pardes --detach=try & +m=$NINE_MOUNT/pardes/try; cat $m/index +echo Exit > $m/exec +``` + +Keep `SHELL` (bash or fish): without it the terminals run `/bin/sh`, +which gets no OSC 133 prompt marks, and `pty/run` answers `error no +prompt marks`. + +To test a change, build with `-Dplatform=tty` (it installs into +`zig-out`): a bare `zig build` installs over `~/.local/bin`. diff --git a/.agents/skills/pardes/SKILL.md b/.agents/skills/pardes/SKILL.md new file mode 100644 index 00000000..d49f8e50 --- /dev/null +++ b/.agents/skills/pardes/SKILL.md @@ -0,0 +1,131 @@ +--- +name: pardes +description: What the pardes editor is and how to use it, with a small cheatsheet (mouse, modes, keys, Look addresses, tags, sessions, config) and a map of its book. Use whenever the user mentions pardes, asks how to do something in it, wants a file opened or text paged in the editor, and to check whether you are running inside a pardes session ($PARDES_PID, $PARDES_9P, $PARDES_PANE, $PARDES_MOUNT) before acting on the user's editor. For scripting or driving a session through its 9P files, use pardes-9p. +--- + +# pardes + +pardes is acme's idea (text is the interface: any word can be looked at or +run) with helix's modal keys, VT terminals and PDFs in panes. Two builtins +carry it: Look (right-click, B3, or Enter in normal mode) opens what the +text names (a file, `file:line`, a directory, a URL), else finds the word's +next place; Exec (middle-click, B2, or Tab) runs the builtin a word names, +else runs it as a shell line. Every session is also a virtual filesystem +served over 9P, so any program that opens files can script it (pardes-9p). + +Paths below are relative to the pardes source tree, the repository this +skill lives in (`readlink -f` this skill's directory if it is reached +through a symlink). + +## Am I in a pardes session? + +Check this first: it decides whether "open it", "show me" or "run it" +can mean the user's editor. Every shell and command pane pardes starts +gets these, and every program started from it (an agent too) inherits them: + +| Variable | | +|---|---| +| `PARDES_PID` | the session's pid (what `status` says) | +| `PARDES_9P` | the session's 9P socket | +| `PARDES_PANE` | the serial of the pane this shell runs in | +| `PARDES_MOUNT` | the session as a directory, only under `9ns --mntgen` or in a `Tty9p` shell | +| `winid` | the pane a command was clicked in (command panes only) | + +A variable can outlive its session (a `--detach` session quit, a shell +moved under tmux), so check that it is live, not just set: + +```sh +if [ -n "${PARDES_9P:-}" ] && [ -S "$PARDES_9P" ] && kill -0 "${PARDES_PID:-}" 2>/dev/null; then + echo "in pardes: session $PARDES_PID, pane $PARDES_PANE, mount ${PARDES_MOUNT:-none}" +else + echo "not in pardes" +fi +``` + +With a mount, `sed -n 1p "$PARDES_MOUNT/status"` answers `pid +$PARDES_PID`. Sessions listed under `$NINE_MOUNT/pardes/` are not proof: +that lists every running session, the user's included, whether or not you +run inside one. Not in a session: say so, and touch no session you merely +found there. + +## Words + +- **tag**: the editable line of words above the workspace, each column and + each pane. A pane's starts with its path. Any word runs from any tag. +- **serial**: a pane's number, never reused (`@p3:12`, `pane/3/`). +- **command pane**: a terminal running one command line; its tag ends in + `running`, then `exit N`. +- **`+` names**: panes pardes makes: `+New` (scratch), `+Search`, `+Pager`, + `+Errors`, `+Unsaved`, `+Diff`. +- **active column**: where the next new pane goes. + +## Cheatsheet + +| Mouse | | +|---|---| +| B1 | select; give the pane the keyboard | +| B2 | Exec the word or sweep | +| B3 | Look at the word or sweep | +| B1+B2 / B1+B3 / B1+B2+B3 | cut / paste / copy (chords) | +| B2+B1 | Exec with the B1 selection as argument | +| Alt-click / Super-click | B2 / B3 for one button | + +| Modes (the box left of a tag) | | +|---|---| +| ` ` normal | helix keys: motions select, edits act on the selection | +| `^` insert | `i a o`…; Esc back to normal | +| `$` raw, terminals | keys go to the program; Ctrl-b toggles raw/normal | +| Esc in normal | back to the previous pane (unlike helix) | + +| Keys pardes adds or changes | | +|---|---| +| `SPC ?` | Help: every builtin, its leader path and keys | +| `:` | to the pane's tag and back | +| `Ctrl-w h/j/k/l` | focus a neighbour | +| `Ctrl-o` / `Ctrl-i` | jump list back / forward | +| `Alt-n` / `Alt-c` | new terminal below / pane to a new column | +| `SPC f s`, `SPC d`, `SPC q` | Save, Del, Exit | +| `SPC f f`, `SPC f g`, `SPC f r` | Find, Grep, Recent | +| `12G`, `n` in a command pane | line 12; next `file:line` error | + +| Look addresses (B3 or Enter) | | +|---|---| +| `file:12`, `file:12:5` | line, byte column | +| `file:/re/`, `file:0/re/` | next match, first match | +| `:40` | line 40 of the pane looked from | +| `@p3:12` | pane 3 by serial | +| `src/` | a directory pane | + +Addresses are sam's (`#n /re/ ?re? $ a,b`). + +| Common words | | +|---|---| +| `Save` `Del` `Get` `Undo` `Edit` | pane; Del/Exit/Restore refuse once over unsaved text, again discards | +| `New` `Tty` `Tty+bash` `Newcol` `Delcol` | panes and columns | +| `Find name` `Grep text` `Recent` | listings in a `+Search` | +| `Kill make` `Repl python` `Filter` `Mode` | terminals and commands | +| `Dump` `Restore` `Config` `DumpConfig` `Theme x` | workspace and settings | + +## From a shell inside pardes + +```sh +pardes notes.txt # open it in this session, return at once +pardes --wait notes.txt # return when its pane closes (EDITOR='pardes --wait') +git log | pardes - # page text into a +Pager +pardes --detach=work & # a session with no screen; --attach=work shows it +``` + +These act on the user's session: do them when asked. Anything more (read +panes, run commands, react to clicks) is the pardes-9p skill. Config is +`~/.config/pardes/init`, a builtin a line; keys are compiled in +(`src/config.zig`). `$NINE_MOUNT/agents`, where present, is cloud9's +read-only view of running coding agents. + +## The book + +`docs/typ/` holds it, one file a chapter, in reading order: `guide.typ` +(day to day), `setup.typ` (9ns, EDITOR, pager, language servers), +`cheatsheet.typ`, `scripting.typ`, `reference.typ` (every 9P file), +`themes.typ`, `building.typ`. `docs/typ/README` says how they build into +the A4 cheatsheet, the book and the website. In the editor: `Help` +(`SPC ?`) and `Tutor` (`SPC h t`). diff --git a/docs/typ/builtins-gui.json b/docs/typ/builtins-gui.json index b42f9c72..83a410dc 100644 --- a/docs/typ/builtins-gui.json +++ b/docs/typ/builtins-gui.json @@ -20,12 +20,15 @@ {"name": "Crt", "leader": "SPC t r", "also": [], "arg": true, "scope": "root", "setting": true, "choices": "on, off, 0-3", "doc": "The bundled CRT post pass over the window, on or off."}, {"name": "CursorBlink", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": "on, off", "doc": "The cursor blinks, solid while typing, on or off."}, {"name": "Debug", "leader": "SPC t d", "also": ["topbar"], "arg": true, "scope": "root", "setting": true, "choices": "on, off", "doc": "A small box of frame statistics at the top right, on or off."}, + {"name": "Def", "leader": null, "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "Go to the definition of the symbol under the cursor; with an argument (a 2-1 chord's selection), of that symbol, where it is nearest."}, {"name": "Del", "leader": "SPC d", "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "Close the pane."}, {"name": "DelAbove", "leader": null, "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Close the pane, giving its rows to the pane above it."}, {"name": "DelBelow", "leader": null, "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Close the pane, giving its rows to the pane below it."}, {"name": "Delcol", "leader": "SPC c d", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Close this column and its panes, refusing once over unsaved text."}, {"name": "Detach", "leader": "SPC s D", "also": [], "arg": false, "scope": "root", "setting": false, "choices": null, "doc": "Detach this pardes from its terminal, leaving the session running."}, {"name": "Diagnostics", "leader": "SPC l d", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "List the file's diagnostics from the language server."}, + {"name": "Diff", "leader": null, "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Stack a diff's hunks as a diff viewer shows them, each under its place and the declarations around it, in a +Diff; on a +Diff, show the diff itself as text."}, + {"name": "DiffLook", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": "hunks, text", "doc": "A .diff or .patch looked at: hunks, a +Diff stacking its hunks, or text, the file itself; Diff goes from one to the other."}, {"name": "DirLook", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": "pane, terminal", "doc": "A directory looked at: pane, a pane listing it as acme's directory window, or terminal, ls in a terminal there."}, {"name": "Down", "leader": "SPC w j", "also": ["C-w j", "C-w down"], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Move the keyboard to the pane below, off a tag onto the pane under it."}, {"name": "Dump", "leader": "SPC s d", "also": ["topbar"], "arg": false, "scope": "root", "setting": false, "choices": null, "doc": "Write the session's panes and layout to a dump file, for Restore."}, @@ -36,7 +39,7 @@ {"name": "EffectCode", "leader": null, "also": [], "arg": true, "scope": "root", "setting": false, "choices": null, "doc": "Open the source of a panel transition or post shader, by name."}, {"name": "Exec", "leader": null, "also": ["tab", "middle-click"], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "Execute its argument as a middle click on it would, a builtin or a shell command."}, {"name": "Exit", "leader": "SPC q", "also": ["topbar"], "arg": false, "scope": "root", "setting": false, "choices": null, "doc": "Quit the editor, refusing once while a pane holds unsaved text: an Exit with nothing edited since discards it."}, - {"name": "Filter", "leader": null, "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Recolour a terminal's program colours to the theme, or show them as sent, flipping between them."}, + {"name": "Filter", "leader": null, "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Recolour a terminal's or a +Pager's program colours to the theme, or show them as sent, flipping between them."}, {"name": "Find", "leader": "SPC f f", "also": ["topbar"], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "List the files below this pane's directory whose names hold its argument, in a +Search."}, {"name": "FocusTint", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": "on, off", "doc": "The focused pane's and column's tags are tinted, on or off."}, {"name": "Font", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": null, "doc": "The body font, by name or path, and its size."}, @@ -103,6 +106,7 @@ {"name": "Putall", "leader": null, "also": [], "arg": false, "scope": "root", "setting": false, "choices": null, "doc": "acme's Putall: every pane holding unsaved edits to a file is saved, each as its own Save; one that is refused (changed on disk since, a write that fails) says so and the rest are saved all the same."}, {"name": "Recent", "leader": "SPC f r", "also": [], "arg": false, "scope": "root", "setting": false, "choices": null, "doc": "List the files opened lately, closed ones too, each a place to open again."}, {"name": "Redo", "leader": null, "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Redo the last undone edit."}, + {"name": "Refs", "leader": null, "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "List the references to the symbol under the cursor; with an argument (a 2-1 chord's selection), to that symbol, where it is nearest."}, {"name": "Rename", "leader": "SPC l r", "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "Rename the symbol under the cursor everywhere, to its argument."}, {"name": "Repl", "leader": null, "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "Binds this terminal as a language's REPL, so an exec on that language's files is typed into it instead of run."}, {"name": "Restore", "leader": "SPC s r", "also": [], "arg": true, "scope": "root", "setting": false, "choices": null, "doc": "Replace every pane with those of a dump file, the last one Dump wrote when bare."}, diff --git a/docs/typ/builtins-tty.json b/docs/typ/builtins-tty.json index 53bcf033..35e12875 100644 --- a/docs/typ/builtins-tty.json +++ b/docs/typ/builtins-tty.json @@ -17,12 +17,15 @@ {"name": "Colors", "leader": "SPC t c", "also": [], "arg": true, "scope": "root", "setting": true, "choices": "on, off", "doc": "Syntax colours in text panes, on or off."}, {"name": "Config", "leader": "SPC f c", "also": ["topbar"], "arg": false, "scope": "root", "setting": false, "choices": null, "doc": "Open the startup file, `init`, in a pane: its pane when it is open, else the file, else a pane of that name for Save to make it and its directory."}, {"name": "Debug", "leader": "SPC t d", "also": ["topbar"], "arg": true, "scope": "root", "setting": true, "choices": "on, off", "doc": "A small box of frame statistics at the top right, on or off."}, + {"name": "Def", "leader": null, "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "Go to the definition of the symbol under the cursor; with an argument (a 2-1 chord's selection), of that symbol, where it is nearest."}, {"name": "Del", "leader": "SPC d", "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "Close the pane."}, {"name": "DelAbove", "leader": null, "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Close the pane, giving its rows to the pane above it."}, {"name": "DelBelow", "leader": null, "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Close the pane, giving its rows to the pane below it."}, {"name": "Delcol", "leader": "SPC c d", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Close this column and its panes, refusing once over unsaved text."}, {"name": "Detach", "leader": "SPC s D", "also": [], "arg": false, "scope": "root", "setting": false, "choices": null, "doc": "Detach this pardes from its terminal, leaving the session running."}, {"name": "Diagnostics", "leader": "SPC l d", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "List the file's diagnostics from the language server."}, + {"name": "Diff", "leader": null, "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Stack a diff's hunks as a diff viewer shows them, each under its place and the declarations around it, in a +Diff; on a +Diff, show the diff itself as text."}, + {"name": "DiffLook", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": "hunks, text", "doc": "A .diff or .patch looked at: hunks, a +Diff stacking its hunks, or text, the file itself; Diff goes from one to the other."}, {"name": "DirLook", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": "pane, terminal", "doc": "A directory looked at: pane, a pane listing it as acme's directory window, or terminal, ls in a terminal there."}, {"name": "Down", "leader": "SPC w j", "also": ["C-w j", "C-w down"], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Move the keyboard to the pane below, off a tag onto the pane under it."}, {"name": "Dump", "leader": "SPC s d", "also": ["topbar"], "arg": false, "scope": "root", "setting": false, "choices": null, "doc": "Write the session's panes and layout to a dump file, for Restore."}, @@ -33,7 +36,7 @@ {"name": "EffectCode", "leader": null, "also": [], "arg": true, "scope": "root", "setting": false, "choices": null, "doc": "Open the source of a panel transition or post shader, by name."}, {"name": "Exec", "leader": null, "also": ["tab", "middle-click"], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "Execute its argument as a middle click on it would, a builtin or a shell command."}, {"name": "Exit", "leader": "SPC q", "also": ["topbar"], "arg": false, "scope": "root", "setting": false, "choices": null, "doc": "Quit the editor, refusing once while a pane holds unsaved text: an Exit with nothing edited since discards it."}, - {"name": "Filter", "leader": null, "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Recolour a terminal's program colours to the theme, or show them as sent, flipping between them."}, + {"name": "Filter", "leader": null, "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Recolour a terminal's or a +Pager's program colours to the theme, or show them as sent, flipping between them."}, {"name": "Find", "leader": "SPC f f", "also": ["topbar"], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "List the files below this pane's directory whose names hold its argument, in a +Search."}, {"name": "FocusTint", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": "on, off", "doc": "The focused pane's and column's tags are tinted, on or off."}, {"name": "Forward", "leader": "SPC j i", "also": ["C-i"], "arg": false, "scope": "root", "setting": false, "choices": null, "doc": "Ctrl-i: one step forward again, up to wherever Back started."}, @@ -90,6 +93,7 @@ {"name": "Putall", "leader": null, "also": [], "arg": false, "scope": "root", "setting": false, "choices": null, "doc": "acme's Putall: every pane holding unsaved edits to a file is saved, each as its own Save; one that is refused (changed on disk since, a write that fails) says so and the rest are saved all the same."}, {"name": "Recent", "leader": "SPC f r", "also": [], "arg": false, "scope": "root", "setting": false, "choices": null, "doc": "List the files opened lately, closed ones too, each a place to open again."}, {"name": "Redo", "leader": null, "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Redo the last undone edit."}, + {"name": "Refs", "leader": null, "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "List the references to the symbol under the cursor; with an argument (a 2-1 chord's selection), to that symbol, where it is nearest."}, {"name": "Rename", "leader": "SPC l r", "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "Rename the symbol under the cursor everywhere, to its argument."}, {"name": "Repl", "leader": null, "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "Binds this terminal as a language's REPL, so an exec on that language's files is typed into it instead of run."}, {"name": "Restore", "leader": "SPC s r", "also": [], "arg": true, "scope": "root", "setting": false, "choices": null, "doc": "Replace every pane with those of a dump file, the last one Dump wrote when bare."}, diff --git a/docs/typ/guide.typ b/docs/typ/guide.typ index 90e72303..89323766 100644 --- a/docs/typ/guide.typ +++ b/docs/typ/guide.typ @@ -202,8 +202,8 @@ takes the rows: #key("k") above, #key("j") below. = Reviewing diffs -`git diff` run as a command, or a `.diff` or `.patch` opened, is drawn as -a diff, each hunk in its file's language. #btn("B3") on: +`git diff` run as a command, or a `.diff` or `.patch` shown as text (below), +is drawn as a diff, each hunk in its file's language. #btn("B3") on: #pairs( [`diff --git`, `---`, `+++`], [the file], @@ -211,6 +211,17 @@ a diff, each hunk in its file's language. #btn("B3") on: [a line's `+`, `-` or space], [that line in the new file], ) +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` +(`n`/`N` 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 +message and diffstat above. The files are found from the diff's directory +or one above it. #word("Diff") on a `+Diff` shows the diff itself as +text (a paged one's `+Pager` is folded under it), and on the text stacks +it again; #word("DiffLook") `text` in the startup file opens the text +first. + = `pardes FILE` and `--wait` In a pane's shell: diff --git a/docs/typ/reference.typ b/docs/typ/reference.typ index ed88905a..909c1e1a 100644 --- a/docs/typ/reference.typ +++ b/docs/typ/reference.typ @@ -22,7 +22,7 @@ index a line per pane: serial kind dirty name column @ru status pid, version, panes @other-files look write a line: a #word("Look") at the pane with the keyboard; read: the serials touched @look-and-exec exec write a line: an #word("Exec") there; read: the serials touched @look-and-exec -pager write a directory: its one +Pager, made or emptied; read: its serial @pardes-stdin +pager write a directory: a new +Pager there; read: its serial @pardes-stdin log the event log; write follow to wait for more @log screen the rendered screen as JSON @on-screen listeners dial addresses @other-files @@ -252,7 +252,9 @@ A line written to #file("exec") is #word("Exec"): silently, here and in every ctl. - The language server's words ask about a file pane's text at its cursor (set it with #file("addr") and `dot=addr` first): #word("Hover") fills - `+Hover`; #word("Rename") `new` renames the symbol in the file and says how many + `+Hover`; #word("Def") and #word("Refs"), in the tag of a file a server + speaks for, are `gd` and `gr`, and given a symbol (a 2-1 chord's + selection) ask at its occurrence nearest the cursor; #word("Rename") `new` renames the symbol in the file and says how many ranges it changed (on the message row, and so in the log) without listing them, and fails when there is nothing to rename. One that reaches other files applies nothing: it opens a `+Search` preview of the edits, which @@ -457,7 +459,7 @@ may lower the contrast of text, the selection or a focus indicator. build embeds them. Resting the pointer on text for about 32 ms (`look_preview_delay_frames`, -2 frames, in `src/config.zig`; `null` turns it off) tints what #word("Look") would take, with no other effect. A terminal's +2 frames, in `src/config.zig`; `null` turns it off) tints what #word("Look") would take, with no other effect. A terminal's or a `+Pager`'s #word("Filter") keeps each foreground at least `tty_filter_min_contrast` (WCAG 1.5, `src/config.zig`) against its background. @@ -889,10 +891,10 @@ at 200, ending in `…`. Control characters become spaces. line is the session's; one not there is refused ENOENT, a relative one EINVAL, one you may not write `permission denied`, a regular file `not a directory`, ENOTDIR), one line; what follows that line, on the same open, is the text to - page, escapes and all. A read of that open answers the serial of the - directory's one `+Pager`, made or emptied for it, once the text is in. This is what - `pardes -` uses; from a directory you may not write, it pages into the - session's `+Pager`. + page, escapes and all. A read of that open answers the serial of a new + `+Pager` in the directory, once the text is in. This is what + `pardes -` uses; from a directory you may not write, it pages into a + `+Pager` of the session's. - #file("/listeners"): the session's dial addresses, a line each (#doc("building", section: "listeners")). - #file("/os/"): existing regular files take read, write and truncation to @@ -993,12 +995,13 @@ it was. = pardes - -`pardes -` reads stdin to its end and shows it in the directory's one -`+Pager` pane, made or emptied for it and left clean, opening at its top; -the next paged text refills it. The session parses the text with +`pardes -` reads stdin to its end and shows it in a new `+Pager` pane of +the directory, left clean, opening at its top, with no line numbers; a +`+Pager` already there keeps its page. The session parses the text with ghostty-vt: SGR colours become the `+Pager`'s own display, never part of -its body or any read (#word("PagerColor") `off` pages plain), and every other -escape is dropped; a carriage return keeps a progress line's last state, +its body or any read (#word("PagerColor") `off` pages plain), mapped +through the theme as a terminal's are until its #word("Filter") shows them +as sent; every other escape is dropped; a carriage return keeps a progress line's last state, and CRLF becomes LF. Empty stdin shows nothing. Inside a pardes pane it returns at once; a text the session cannot take is printed to stderr with why, and the exit is 1. From a directory whose name holds a newline or control byte, the pane is the session diff --git a/docs/typ/setup.typ b/docs/typ/setup.typ index df99a45f..f49c9075 100644 --- a/docs/typ/setup.typ +++ b/docs/typ/setup.typ @@ -59,7 +59,7 @@ fi = A pager -#cmd("ls --color=always | pardes - # into the directory's +Pager, colours kept") +#cmd("ls --color=always | pardes - # into a new +Pager there, colours kept") With #word("Pager") `pardes` (the default) a terminal's shell gets `PAGER`, `GIT_PAGER` and `SYSTEMD_PAGER` set to it (and diff --git a/src/CHANGELOG.md b/src/CHANGELOG.md index 6be39c7a..ce2cedc8 100644 --- a/src/CHANGELOG.md +++ b/src/CHANGELOG.md @@ -2,6 +2,12 @@ ## 0.23 +- A file a language server speaks for (by its extension) has `Def` and + `Refs` in its tag: the definition and the references of the symbol at + the cursor, which `gd`, `gr` and a Ctrl-click run too. Chorded 2-1, they + ask at the selected symbol instead, its occurrence nearest the cursor. +- A scroll in the window never moves the tree-sitter context rows: the + body glides under them. - A look at a directory opens a pane listing it, as acme's directory window does: its entries in columns, a directory's marked `/`. A look at an entry opens it from there, and `Get` or a look at it again reads it diff --git a/src/File.zig b/src/File.zig index 875d0f46..31392ebd 100644 --- a/src/File.zig +++ b/src/File.zig @@ -154,8 +154,11 @@ pub const State = struct { /// Its file was deleted on disk: said once (`deleted`) until it is /// written or found again. disk_gone: bool = false, - /// A +Pager pane (`pardes -`) whose text is a diff (`git diff`, `show`, - /// `log -p`): drawn and looked at as a diff (Pane.colorAlgo). + /// A +Pager pane (`pardes -`): no line numbers, its program's colours + /// through Filter until it is toggled off. + pager: bool = false, + /// A +Pager whose text is a diff (`git diff`, `show`, `log -p`): drawn + /// and looked at as a diff (Pane.colorAlgo). pager_diff: bool = false, /// A +Pager's colours, as its program printed them (pager.zig): drawn /// over its text by recolorSyntax, never read over 9P. ponytail: any @@ -562,6 +565,10 @@ pub fn byteAtRowDisplay(pane: *const Pane, row: i32, from_raw: i32, display_col: pub fn gutterWidth(pane: *const Pane) u16 { if (pane.file == null) return 0; const file = &pane.file.?; + // A +Pager, and a +Diff (hunks.zig), show no line numbers, as a + // pager and delta show none. + if (file.pager) return 0; + if (file.output) |o| if (std.meta.eql(o.from, Output.Origin{ .cmd = .Diff })) return 0; var lines = if (file.line_starts.len > 0) file.line_starts.len else lineCount(file.content); var digits: u16 = 1; while (lines >= 10) : (lines /= 10) digits += 1; @@ -1164,7 +1171,7 @@ pub fn setContentSpan(p: *Pardes, f: *State, new: []u8, span_in: ?Span) void { f.highlights = &.{}; f.highlight_start = 0; f.syntax_dirty = true; - if (std.mem.endsWith(u8, f.path, "/+Pager")) f.pager_diff = looksLikeDiff(new[0..@min(new.len, 64 * 1024)]); + if (f.pager) f.pager_diff = looksLikeDiff(new[0..@min(new.len, 64 * 1024)]); for (twins[0..ntwins], 0..) |id, i| { const t = p.panes[id].?; const tf = &t.file.?; @@ -1434,6 +1441,7 @@ test "a +Pager pane holding a diff is drawn and looked at as one; holding other const f = &pane.file.?; p.gpa.free(f.path); f.path = try p.gpa.dupe(u8, "/tmp/+Pager"); + f.pager = true; setContent(p, f, try p.gpa.dupe(u8, "commit abc\n\ndiff --git a/x b/x\n--- a/x\n+++ b/x\n@@ -1 +1 @@\n-a\n+b\n")); try std.testing.expect(pane.colorAlgo() == .diff); try std.testing.expect(pardes.look.diffLines(p, pane) != null); @@ -1715,7 +1723,7 @@ fn fillBody(dst: ?[]u8, pane: *Pane, f: *State, width: usize, record_wrap: bool) var lbuf: [@max(config.PREFIX_W, 32)]u8 = undefined; const prefix = lbuf[0..prefix_width]; @memset(prefix, ' '); - if (at == 0) { + if (at == 0 and prefix.len > 0) { var lineno = row + 1; var digit: usize = prefix.len - 1; while (true) { @@ -1790,6 +1798,12 @@ const SynStyle = struct { fg: [3]u8, bold: bool }; pub const DiffTints = struct { added_bg: [3]u8, removed_bg: [3]u8, + /// The words a changed line changed (hunks.zig), on a stronger ground. + added_emph_bg: [3]u8, + removed_emph_bg: [3]u8, + /// A +Diff line added or removed whole: a faint ground. + added_line_bg: [3]u8, + removed_line_bg: [3]u8, added_fg: [3]u8, removed_fg: [3]u8, @@ -1804,6 +1818,10 @@ pub const DiffTints = struct { return .{ .added_bg = added_bg, .removed_bg = removed_bg, + .added_emph_bg = Colors.mixOklab(page, green, 0.28), + .removed_emph_bg = Colors.mixOklab(page, red, 0.28), + .added_line_bg = Colors.mixOklab(page, green, 0.07), + .removed_line_bg = Colors.mixOklab(page, red, 0.07), .added_fg = legible(green, ink, added_bg), .removed_fg = legible(red, ink, removed_bg), }; @@ -1818,9 +1836,9 @@ pub const DiffTints = struct { /// The row ground and prefix ink for a line's style byte, if it is an /// added or removed line. - pub fn forStyle(t: *const DiffTints, style: u8) ?struct { bg: [3]u8, fg: [3]u8 } { - if (style & syntax.diff_added != 0) return .{ .bg = t.added_bg, .fg = t.added_fg }; - if (style & syntax.diff_removed != 0) return .{ .bg = t.removed_bg, .fg = t.removed_fg }; + pub fn forStyle(t: *const DiffTints, style: u8) ?struct { bg: [3]u8, fg: [3]u8, emph_bg: [3]u8, line_bg: [3]u8 } { + if (style & syntax.diff_added != 0) return .{ .bg = t.added_bg, .fg = t.added_fg, .emph_bg = t.added_emph_bg, .line_bg = t.added_line_bg }; + if (style & syntax.diff_removed != 0) return .{ .bg = t.removed_bg, .fg = t.removed_fg, .emph_bg = t.removed_emph_bg, .line_bg = t.removed_line_bg }; return null; } }; @@ -1855,7 +1873,17 @@ pub fn recolorSyntax(p: *Pardes, s: *Surface, pane: *Pane, f: *State, r: pardes. const prefix_width = gutterWidth(pane); const tz_recolor = tracy.zone(@src(), "synRecolor"); defer tz_recolor.end(); - const tints: ?DiffTints = if (pane.colorAlgo() == .diff and highlights.len > 0) DiffTints.of(p) else null; + // A diff's rows, and a +Diff's (hunks.zig): their markers coloured. + // A diff's whole row is tinted; a +Diff tints only the words a + // changed line changed. + const algo = pane.colorAlgo(); + const tints: ?DiffTints = if ((algo == .diff or algo == .locations) and highlights.len > 0) DiffTints.of(p) else null; + const row_tint = algo == .diff; + var filtered_storage: terminal.FilteredColors = undefined; + const filtered: ?*terminal.FilteredColors = if (comptime terminal.enabled) (if (pane.tty_filter and spans.len > 0) blk: { + filtered_storage = .init(p, null); + break :blk &filtered_storage; + } else null) else null; // indexed start, same as bodyText — an empty tail simply paints nothing var flines = std.mem.splitScalar(u8, f.content[lineStart(p.gpa, f, f.scroll)..], '\n'); const total = nlines(p.gpa, f); @@ -1893,7 +1921,11 @@ pub fn recolorSyntax(p: *Pardes, s: *Surface, pane: *Pane, f: *State, r: pardes. t.forStyle(highlights[base - highlight_start]) else null else null; - if (tint) |t| if (prefix_width < tw) tintRow(s, tx + @as(u16, @intCast(prefix_width)), body_y + vr, tx + tw, t.bg); + if (tint) |t| if (prefix_width < tw) { + // A +Diff line added or removed whole: faintly (hunks.zig). + const whole = highlights[base - highlight_start] & syntax.diff_whole != 0; + if (row_tint or whole) tintRow(s, tx + @as(u16, @intCast(prefix_width)), body_y + vr, tx + tw, if (row_tint) t.bg else t.line_bg); + }; // A +Pager's own colours (pager.zig) on every row but one the diff // look tints: an added or removed line is drawn as pardes draws a // diff, and git's red and green on it would only fight the tint. @@ -1924,6 +1956,11 @@ pub fn recolorSyntax(p: *Pardes, s: *Surface, pane: *Pane, f: *State, r: pardes. cell.style.bold = ss.bold; } } + if (tint) |t| if (highlights[hidx] & syntax.diff_emph != 0) { + var fill: usize = 0; + while (fill < cells and prefix_width + screen_c + fill < tw) : (fill += 1) + s.at(tx + @as(u16, @intCast(prefix_width + screen_c + fill)), body_y + vr).style.bg = .{ .rgb = t.emph_bg }; + }; } } // Results keep their exact live text. Only the location, @@ -1945,10 +1982,16 @@ pub fn recolorSyntax(p: *Pardes, s: *Surface, pane: *Pane, f: *State, r: pardes. while (fill < cells and prefix_width + screen_c + fill < tw) : (fill += 1) { const cell = s.at(tx + @as(u16, @intCast(prefix_width + screen_c + fill)), body_y + vr); if (cell.default) continue; - // A palette colour through the theme's sixteen, as a - // terminal pane's cell; truecolor as it is. - if (st.fg != .default) cell.style.fg = if (st.fg == .index) terminal.palColor(p, st.fg.index) else st.fg; - if (st.bg != .default) cell.style.bg = if (st.bg == .index) terminal.palColor(p, st.bg.index) else st.bg; + // As a terminal pane's cell: through Filter, or a + // palette colour through the theme's sixteen and + // truecolor as it is. + if (filtered) |colors| { + if (st.fg != .default) cell.style.fg = colors.spanColor(st.fg, false); + if (st.bg != .default) cell.style.bg = colors.spanColor(st.bg, true); + } else { + if (st.fg != .default) cell.style.fg = if (st.fg == .index) terminal.palColor(p, st.fg.index) else st.fg; + if (st.bg != .default) cell.style.bg = if (st.bg == .index) terminal.palColor(p, st.bg.index) else st.bg; + } cell.style.bold = cell.style.bold or st.bold; cell.style.dim = st.dim; cell.style.italic = st.italic; diff --git a/src/Output.zig b/src/Output.zig index 3bae9ecf..9e194615 100644 --- a/src/Output.zig +++ b/src/Output.zig @@ -15,6 +15,8 @@ const build_options = @import("pardes_config"); const lsp = @import("lsp/lsp.zig"); const look = @import("look.zig"); const locations = @import("locations.zig"); +const layout = @import("layout.zig"); +const hunks = @import("hunks.zig"); const Pane = panes.Pane; const File = panes.File; @@ -538,6 +540,17 @@ pub fn fillResults(p: *Pardes, id: usize, dir: []const u8, from: Origin, arg: [] result_rows = formatted.rows; anchor = formatted.anchor; } + _ = try fillRows(p, id, dir, from, arg, result_content, result_rows, anchor); +} + +/// Rows already laid out (`content`, `rows` its metadata, both taken +/// when it succeeds, the caller's still when it fails) into the pane they +/// belong in: the one a run of `from` with `arg` in `dir` showed last, +/// refilled, else a new one placed by pane `id`. Its id. +pub fn fillRows(p: *Pardes, id: usize, dir: []const u8, from: Origin, arg: []const u8, result_content: []u8, result_rows: []locations.Row, anchor: ?usize) !usize { + const pane = p.panes[id] orelse return error.MissingPane; + if (arg.len > max_arg) return error.ArgumentTooLong; + const by_arg = std.meta.activeTag(from) != .query; for (p.panes, 0..) |slot, i| { const rp = slot orelse continue; const rf = if (rp.file) |*f| f else continue; @@ -578,7 +591,7 @@ pub fn fillResults(p: *Pardes, id: usize, dir: []const u8, from: Origin, arg: [] pane.search_row = anchor; look.armLookWalk(p, i); } - return; + return i; } const free = p.freeSlot() orelse return error.NoPaneSlots; const np = try open(p, free, dir, from, arg, result_content); @@ -590,6 +603,57 @@ pub fn fillResults(p: *Pardes, id: usize, dir: []const u8, from: Origin, arg: [] pane.search_row = anchor; look.armLookWalk(p, free); } + return free; +} + +/// Diff: `content`, the diff at `path` (a file, a +Pager), stacked as a +/// diff viewer shows it (hunks.zig), in a +Diff where its files are found +/// (hunks.sourceRoot), placed by pane `id`, refilled when it is there. Its +/// arg names the diff (its base name, or its whole path when the +Diff +/// stands elsewhere), for Diff to go back to it. The +Diff's id; +/// NoHunks when there is none in it. +pub fn openDiff(p: *Pardes, id: usize, path: []const u8, content: []const u8) !usize { + const dir = std.fs.path.dirname(path) orelse p.sessionDir(); + const root = hunks.sourceRoot(p, dir, content); + const result = try hunks.format(p, root, content); + errdefer { + p.gpa.free(result.content); + locations.freeRows(p.gpa, result.rows); + } + var has_hunk = false; + for (result.rows) |row| has_hunk = has_hunk or row.kind == .match; + if (!has_hunk) return error.NoHunks; + const arg = if (std.mem.eql(u8, root, dir) or path.len > max_arg) std.fs.path.basename(path) else path; + return fillRows(p, id, root, .{ .cmd = .Diff }, arg, result.content, result.rows, null); +} + +/// Diff on a +Diff: the diff it stacks, as text. A pane holding it +/// already (the newest: a +Pager folded under its +Diff unfolds) is +/// shown; else the file is opened as text, whatever DiffLook says. +pub fn showDiffText(p: *Pardes, id: usize, source: []const u8) void { + var newest: ?usize = null; + for (p.panes, 0..) |slot, i| { + const f = (slot orelse continue).file orelse continue; + if (!std.mem.eql(u8, f.path, source)) continue; + if (newest == null or p.panes[newest.?].?.serial < slot.?.serial) newest = i; + } + if (newest) |i| { + if (p.panes[i].?.collapsed) layout.toggleCollapse(p, i); + p.active = i; + return; + } + p.look_text = true; + defer p.look_text = false; + look.lookAt(p, id, source); +} + +/// The diff a +Diff stacks (openDiff's arg): its path. +pub fn diffSource(p: *Pardes, f: *const File.State) ?[]const u8 { + const o = f.output orelse return null; + if (!std.meta.eql(o.from, Origin{ .cmd = .Diff })) return null; + const arg = o.arg(); + if (arg.len > 0 and arg[0] == '/') return arg; + return std.fs.path.join(p.scratch.allocator(), &.{ std.fs.path.dirname(f.path) orelse "", arg }) catch null; } pub fn openJumps(p: *Pardes, id: usize) !void { @@ -685,25 +749,15 @@ pub fn openUnsaved(p: *Pardes, id: usize, content: []u8) void { p.active = id; } -/// `pardes -`'s pane: the one `/+Pager`, emptied for the next paged -/// text when it is there (a directory's paged commands refill it, as its -/// command pane is reused), else made, named so before it is announced, -/// and placed wherever there is room without taking the keyboard. `dir` -/// empty (or not absolute): the session's directory. Its id; NoPaneRoom -/// or NoPaneSlots when it has no room at all. +/// `pardes -`'s pane: a new `/+Pager` for each paged text, as each +/// run of a pager is its own (one already there keeps its page), named so +/// before it is announced, its colours through Filter, and placed wherever +/// there is room without taking the keyboard. `dir` empty (or not +/// absolute): the session's directory. Its id; NoPaneRoom or NoPaneSlots +/// when it has no room at all. pub fn openPager(p: *Pardes, from: usize, dir_arg: []const u8) !usize { const dir = if (dir_arg.len > 0 and dir_arg[0] == '/') dir_arg else p.sessionDir(); const path = try std.fs.path.join(p.gpa, &.{ dir, "+Pager" }); - for (p.panes, 0..) |slot, i| { - const pane = slot orelse continue; - const f = if (pane.file) |*file| file else continue; - if (!std.mem.eql(u8, f.path, path)) continue; - p.gpa.free(path); - File.setContent(p, f, try p.gpa.alloc(u8, 0)); - resetBody(p, pane); - f.saved_revision = f.revision; - return i; - } const free = p.freeSlot() orelse { p.gpa.free(path); return error.NoPaneSlots; @@ -719,6 +773,8 @@ pub fn openPager(p: *Pardes, from: usize, dir_arg: []const u8) !usize { // The pane owns the name from here. p.gpa.free(pane.file.?.path); pane.file.?.path = path; + pane.file.?.pager = true; + pane.tty_filter = true; const keyboard = p.active; exec.placeNew(p, from, null, free, .fs); if (p.unplaced.isSet(free)) return error.NoPaneRoom; diff --git a/src/builtins.zig b/src/builtins.zig index 77e1169d..c1424b2f 100644 --- a/src/builtins.zig +++ b/src/builtins.zig @@ -46,6 +46,10 @@ pub const PaneKind = enum { /// An image pane, or a terminal, whose program's kitty graphics are /// pictures too. picture, + /// A terminal, or a +Pager: a program's colours. + program_colors, + /// A text pane showing a diff: a .diff, a .patch, a +Pager holding one. + diff, pub fn has(kind: PaneKind, pane: *const panes.Pane) bool { return switch (kind) { @@ -53,6 +57,9 @@ pub const PaneKind = enum { .pdf => pane.hasPdf(), .image => pane.image != null, .picture => pane.image != null or pane.isTerminal(), + .program_colors => pane.isTerminal() or (pane.file != null and pane.file.?.pager), + .diff => if (pane.file) |f| pane.colorAlgo() == .diff or + (f.output != null and std.meta.eql(f.output.?.from, panes.Output.Origin{ .cmd = .Diff })) else false, }; } @@ -62,6 +69,8 @@ pub const PaneKind = enum { .pdf => "a PDF", .image => "an image", .picture => "an image or a terminal", + .program_colors => "a terminal or a +Pager", + .diff => "a diff or a +Diff", }; } }; @@ -1336,14 +1345,28 @@ pub const Del = struct { } }; -/// Recolour a terminal's program colours to the theme, or show them as sent, flipping between them. +/// Recolour a terminal's or a +Pager's program colours to the theme, or show them as sent, flipping between them. pub const Filter = struct { - pub const needs: PaneKind = .terminal; + pub const needs: PaneKind = .program_colors; pub fn run(c: Ctx) void { c.pane.tty_filter = !c.pane.tty_filter; } }; +/// Stack a diff's hunks as a diff viewer shows them, each under its place and the declarations around it, in a +Diff; on a +Diff, show the diff itself as text. +pub const Diff = struct { + pub const needs: PaneKind = .diff; + pub const output: OutputTraits = .{ .name = config.diff_buffer, .steps = true, .locations = true }; + pub fn run(c: Ctx) void { + const f = &c.pane.file.?; + if (panes.Output.diffSource(c.p, f)) |source| return panes.Output.showDiffText(c.p, c.id, source); + _ = panes.Output.openDiff(c.p, c.id, f.path, f.content) catch |err| switch (err) { + error.NoHunks => c.p.reportFailure(c.id, "Diff: no hunk in it"), + else => c.p.reportError(c.id, "hunks", err), + }; + } +}; + /// Cycle the pane's input modes: terminals add raw tty mode to normal/insert. pub const Mode = struct { pub fn run(c: Ctx) void { @@ -1851,6 +1874,28 @@ pub const Jumplist = struct { // ---- the language group ---- +/// Go to the definition of the symbol under the cursor; with an argument +/// (a 2-1 chord's selection), of that symbol, where it is nearest. +pub const Def = struct { + pub const takes_arg = true; + /// Its answer says what it found, a jump or a list or why not; its + /// name would only stack above it, as gd never did. + pub const quiet = true; + pub fn run(c: Ctx) void { + c.p.lspRequest(c.id, .definition, std.mem.trim(u8, c.arg orelse "", " \t\r\n")); + } +}; + +/// List the references to the symbol under the cursor; with an argument +/// (a 2-1 chord's selection), to that symbol, where it is nearest. +pub const Refs = struct { + pub const takes_arg = true; + pub const quiet = true; // as Def + pub fn run(c: Ctx) void { + c.p.lspRequest(c.id, .references, std.mem.trim(u8, c.arg orelse "", " \t\r\n")); + } +}; + /// Ask the language server about the symbol under the cursor. pub const Hover = struct { pub fn run(c: Ctx) void { diff --git a/src/config.zig b/src/config.zig index d6ea7358..c2f51b36 100644 --- a/src/config.zig +++ b/src/config.zig @@ -32,6 +32,8 @@ pub const leader_path = paths: { var table = std.EnumArray(Builtin, ?[]const u8).initDefault(@as(?[]const u8, undecided), .{ .Help = &[_]u8{leader_help}, .Hover = "lk", + .Def = null, // gd + .Refs = null, // gr .Rename = "lr", .CodeAction = "la", .SelectRefs = "lh", @@ -49,6 +51,7 @@ pub const leader_path = paths: { .DelAbove = null, .DelBelow = null, .Filter = null, + .Diff = null, .Mode = null, .Togglettymode = null, .Collapse = null, @@ -87,6 +90,7 @@ pub const leader_path = paths: { .BootShell = null, .LookWord = null, .DirLook = null, + .DiffLook = null, .Pager = null, .PagerColor = null, .TermImages = null, @@ -301,6 +305,16 @@ pub const topbar_str = "Newcol Joincol Find Grep Help Changelog Tutor Dump Theme pub const pane_builtins_str = "Tty Collapse Del"; pub const pdf_pane_builtins_str = "Tty PdfSections PdfTint Collapse Del"; pub const file_pane_builtins_str = "Save Tty Collapse Del"; +/// After a file's, on one a language server speaks for. +pub const lsp_pane_builtins_str = "Def Refs"; +/// A diff's (a .diff, a .patch, a +Pager holding one): Diff. +pub const diff_pane_builtins_str = "Save Tty Diff Collapse Del"; +/// A +Pager's (`pardes -`): Filter, as a terminal's. +pub const pager_pane_builtins_str = "Save Tty Filter Collapse Del"; +/// A +Pager holding a diff (`git show`): Diff too. +pub const pager_diff_pane_builtins_str = "Save Tty Filter Diff Collapse Del"; +/// A +Diff's: Diff again, the diff it stacks as text. +pub const diff_view_builtins_str = "Save Tty Diff Collapse Del"; pub const terminal_pane_builtins_str = "Tty Save Mode Filter Collapse Del"; pub const command_pane_builtins_str = "Kill Save Collapse Del"; /// A directory pane's (Dir.zig): Get reads it again, as acme's does. @@ -500,6 +514,7 @@ pub const unsaved_buffer = "+Unsaved"; pub const themes_buffer = "+Themes"; pub const fonts_buffer = "+Fonts"; pub const pdf_sections_buffer = "+PdfSections"; +pub const diff_buffer = "+Diff"; pub const pdf_links_buffer = "+Links"; pub const hover_buffer = "+Hover"; pub const lsp_buffer = "+Lsp"; @@ -794,6 +809,10 @@ pub const Runtime = struct { /// A directory looked at: `pane`, acme's, a pane listing it (Dir.zig); /// `terminal`, what pardes did before, `ls` in a terminal there. dir_look: DirLook = .pane, + /// A .diff or .patch looked at (a look, `pardes FILE`, `--wait`): + /// `hunks`, a +Diff stacking its hunks (hunks.zig); `text`, the file + /// itself, as pardes showed it before. Diff goes from one to the other. + diff_look: DiffLook = .hunks, /// What a terminal's shell pages through (host_io.ChildEnv): `pardes`, /// PAGER and GIT_PAGER set to `pardes -`, a +Pager pane, where the /// user's environment set neither; `off`, the environment as it is. @@ -818,11 +837,12 @@ pub const Runtime = struct { pub const BootShell = enum { keep, replace }; pub const LookWord = enum { search, list }; pub const DirLook = enum { pane, terminal }; + pub const DiffLook = enum { hunks, text }; pub const Pager = enum { pardes, off }; pub const TermImages = enum { real, petscii }; pub const JumpScope = enum { file, all }; /// A setting that is one of a few words, each an enum field of Runtime. - pub const Choice = enum { placement, boot_shell, look_word, dir_look, pager, term_images, jump_scope }; + pub const Choice = enum { placement, boot_shell, look_word, dir_look, diff_look, pager, term_images, jump_scope }; /// shadow: a soft drop shadow. rim: a light hairline along the top of /// the focused pane's tag rows. auto: a shadow on a light page; on a @@ -1088,6 +1108,7 @@ pub const Runtime = struct { .{ .word = "Placement", .action = .{ .choice = .placement }, .doc = "Where a new pane goes: acme, as makenewwindow does, or pardes, the older rules." }, .{ .word = "BootShell", .action = .{ .choice = .boot_shell }, .doc = "A document dropped where a lone untouched shell stands: keep the shell, or replace it." }, .{ .word = "LookWord", .action = .{ .choice = .look_word }, .doc = "A plain word looked at: search selects its next place in the pane, list lists every place in a +Search." }, + .{ .word = "DiffLook", .action = .{ .choice = .diff_look }, .doc = "A .diff or .patch looked at: hunks, a +Diff stacking its hunks, or text, the file itself; Diff goes from one to the other." }, .{ .word = "DirLook", .action = .{ .choice = .dir_look }, .doc = "A directory looked at: pane, a pane listing it as acme's directory window, or terminal, ls in a terminal there." }, .{ .word = "Pager", .action = .{ .choice = .pager }, .doc = "What a terminal's commands page through: pardes, a +Pager pane (pardes -), or off, the environment's own; for terminals started after it." }, .{ .word = "PagerColor", .action = .{ .toggle = .pager_color }, .doc = "A +Pager keeps its program's colours, on or off; for the next text paged." }, @@ -1787,6 +1808,7 @@ pub const Runtime = struct { .boot_shell => "replace", .look_word => "list", .dir_look => "terminal", + .diff_look => "text", .pager => "off", .term_images => "petscii", .jump_scope => "all", @@ -1862,6 +1884,7 @@ pub const Runtime = struct { .boot_shell => "BootShell replace\n", .look_word => "LookWord list\n", .dir_look => "DirLook terminal\n", + .diff_look => "DiffLook text\n", .pager => "Pager off\n", .term_images => "TermImages petscii\n", .jump_scope => "JumpScope all\n", @@ -2235,7 +2258,7 @@ const doc_typ = struct { if (w.end > 0) w.writeByte(' ') catch return false; w.writeAll(x[0 .. std.mem.indexOfScalar(u8, x, '+') orelse x.len]) catch return false; } - const tags = [_][]const u8{ topbar_str, @import("tagline.zig").column_tag_default, pane_builtins_str, pdf_pane_builtins_str, file_pane_builtins_str, terminal_pane_builtins_str, command_pane_builtins_str, dir_pane_builtins_str }; + const tags = [_][]const u8{ topbar_str, @import("tagline.zig").column_tag_default, pane_builtins_str, pdf_pane_builtins_str, file_pane_builtins_str, diff_pane_builtins_str, pager_pane_builtins_str, pager_diff_pane_builtins_str, diff_view_builtins_str, terminal_pane_builtins_str, command_pane_builtins_str, dir_pane_builtins_str }; for (tags) |d| if (std.mem.eql(u8, d, w.buffered())) return true; return false; } diff --git a/src/edit_cmd.zig b/src/edit_cmd.zig index ebeae223..d3377e09 100644 --- a/src/edit_cmd.zig +++ b/src/edit_cmd.zig @@ -97,7 +97,9 @@ const World = struct { // A look opens it, or finds it open, where a look would; the // keyboard stays where the Edit ran. const was = p.active; + p.look_text = true; look.lookAt(p, w.from, path); + p.look_text = false; if (p.panes[was] != null) p.active = was; for (p.panes, 0..) |slot, id| { const pane = slot orelse continue; diff --git a/src/gui/gui.zig b/src/gui/gui.zig index 65b3f926..5a026664 100644 --- a/src/gui/gui.zig +++ b/src/gui/gui.zig @@ -1873,6 +1873,7 @@ const Gui = struct { scroll_rect: pardes.Rect = .{ .x = 0, .y = 0, .w = 0, .h = 0 }, scroll_body_y: u16 = 0, // that rect's first BODY row (Tagbottom moves it) scroll_body_h: u16 = 0, // and its BODY rows, which a taller tag leaves fewer of + scroll_held_px: f32 = 0, // its tree-sitter context band, which never moves scroll_col: u16 = 0, // where the wheel turned: crossed rows are delivered scroll_row: u16 = 0, // THERE, not wherever the pointer has drifted to since scroll_delta: f32 = 0, // finite raw distance waiting for the render batch @@ -5367,7 +5368,7 @@ fn stepGlide(g: *Gui, core: *pardes.Pardes, gpa: std.mem.Allocator) void { /// The glide's picture: the pane's body rows moved by the offset, and in /// the gap it opens the rows that left, as `emitScrollRows` draws a /// touchpad's fraction. -fn emitGlideRows(g: *Gui, instances: [*]CellInstance, base: u32, surface: *pardes.Surface, layout: CellLayout, win_w: f32, win_h: f32, page: Ground) u32 { +fn emitGlideRows(g: *Gui, instances: [*]CellInstance, base: u32, surface: *pardes.Surface, layout: CellLayout, win_w: f32, win_h: f32, page: Ground, held: u16) u32 { const glide = &g.glide; for (surface.panelTracks()) |track| if (track.active() and track.pane == glide.pane) return 0; @@ -5383,10 +5384,12 @@ fn emitGlideRows(g: *Gui, instances: [*]CellInstance, base: u32, surface: *parde g.scroll_body_h = bh; var shifted = layout; shifted.y_off -= glide.offset * layout.h; + const kept = holdContext(g, surface, glide.pane, held, bh, layout); + shifted.y_off += kept.lift; const cursor_idx: u32 = if (surface.cursor) |cu| @as(u32, cu.y) * surface.cols + cu.x else std.math.maxInt(u32); const cursor_bar = if (surface.cursor) |cu| cu.bar else false; var n: u32 = 0; - var row = y0; + var row = y0 + kept.rows; while (row < y0 + bh) : (row += 1) { const line = surface.cells[@as(usize, row) * surface.cols ..][0..surface.cols]; const row_cursor: ?usize = if (surface.cursor) |cu| if (cu.y == row) cu.x else null else null; @@ -5400,9 +5403,9 @@ fn emitGlideRows(g: *Gui, instances: [*]CellInstance, base: u32, surface: *parde // The gap: rows past the top while the picture lags a move down, past // the bottom for one up; as many as it opens. const gap: u16 = @intFromFloat(@min(@ceil(@abs(glide.offset)), @as(f32, @floatFromInt(bh)))); - const kept = if (glide.offset < 0) glide.nabove else glide.nbelow; + const nkept = if (glide.offset < 0) glide.nabove else glide.nbelow; const rows = if (glide.offset < 0) glide.above else glide.below; - for (0..@min(gap, kept)) |i| { + for (0..@min(gap, nkept)) |i| { const cells = rows[i * bw ..][0..bw]; // Row -1 - i above the body, or bh + i below it, in grid rows. const at_row: i32 = if (glide.offset < 0) @as(i32, y0) - 1 - @as(i32, @intCast(i)) else @as(i32, y0) + bh + @as(i32, @intCast(i)); @@ -5560,8 +5563,9 @@ fn stepScroll(g: *Gui, core: *pardes.Pardes, gpa: std.mem.Allocator) void { if (g.scroll_lag == 0) resetScroll(g); } -fn emitScrollRows(g: *Gui, instances: [*]CellInstance, base: u32, surface: *pardes.Surface, layout: CellLayout, win_w: f32, win_h: f32, page: Ground) u32 { - if (g.glide.offset != 0) return emitGlideRows(g, instances, base, surface, layout, win_w, win_h, page); +fn emitScrollRows(g: *Gui, instances: [*]CellInstance, base: u32, surface: *pardes.Surface, layout: CellLayout, win_w: f32, win_h: f32, page: Ground, held: u16) u32 { + g.scroll_held_px = 0; + if (g.glide.offset != 0) return emitGlideRows(g, instances, base, surface, layout, win_w, win_h, page, held); const scroll_pane = g.scroll_pane orelse return 0; if (g.scroll_lag == 0) return 0; for (surface.panelTracks()) |track| @@ -5575,10 +5579,12 @@ fn emitScrollRows(g: *Gui, instances: [*]CellInstance, base: u32, surface: *pard if (x0 + bw > surface.cols or y0 + bh > surface.rows) return 0; // resized under us var shifted = layout; shifted.y_off -= g.scroll_lag * layout.h; + const kept = holdContext(g, surface, scroll_pane, held, bh, layout); + shifted.y_off += kept.lift; const cursor_idx: u32 = if (surface.cursor) |cu| @as(u32, cu.y) * surface.cols + cu.x else std.math.maxInt(u32); const cursor_bar = if (surface.cursor) |cu| cu.bar else false; var n: u32 = 0; - var row = y0; + var row = y0 + kept.rows; while (row < y0 + bh) : (row += 1) { const line = surface.cells[@as(usize, row) * surface.cols ..][0..surface.cols]; const row_cursor: ?usize = if (surface.cursor) |cu| if (cu.y == row) cu.x else null else null; @@ -5600,12 +5606,52 @@ fn emitScrollRows(g: *Gui, instances: [*]CellInstance, base: u32, surface: *pard return n; } +/// A scrolling body's tree-sitter context rows hold still: the shifted +/// rows start under them and are clipped below their band, and where a +/// body layer stacks them at the tagline's height (TreeContextTagStyle) +/// the rows under them are drawn up to meet them, where the layer has them. +fn holdContext(g: *Gui, surface: *const pardes.Surface, id: usize, held: u16, bh: u16, layout: CellLayout) struct { rows: u16, lift: f32 } { + const rows = @min(held, bh); + const layered = id < surface.body_layers.len and surface.body_layers[id].rows != 0 and surface.body_layers[id].context_rows != 0; + const row_px = if (layered) std.math.clamp(@as(f32, @floatFromInt(g.tagline_height)), 1, @max(1, layout.h)) else layout.h; + g.scroll_held_px = @as(f32, @floatFromInt(rows)) * row_px; + return .{ .rows = rows, .lift = @as(f32, @floatFromInt(rows)) * (row_px - layout.h) }; +} + +test "a scroll's shifted rows start under the context rows, and its scissor below their band" { + var surface: pardes.Surface = .{}; + var g: Gui = undefined; + g.tagline_height = 12; + g.scroll_rect = .{ .x = 0, .y = 0, .w = 40, .h = 20 }; + g.scroll_body_y = 1; + g.scroll_body_h = 19; + const layout: CellLayout = .{ .w = 10, .h = 20, .x_off = 0, .y_off = 0 }; + // On the grid, three body-high rows are held, and nothing moves up. + const grid = holdContext(&g, &surface, 0, 3, 19, layout); + try std.testing.expectEqual(@as(u16, 3), grid.rows); + try std.testing.expectEqual(@as(f32, 0), grid.lift); + const clip = scrollScissor(&g, layout, 400, 400); + try std.testing.expectEqual(@as(c_int, 20 + 3 * 20), clip.y); + try std.testing.expectEqual(@as(c_int, 16 * 20), clip.h); + // In a body layer they are tagline-high: the rows under them move up + // by what each is shorter, to where the layer draws them. + surface.body_layers[0].rows = 30; + surface.body_layers[0].context_rows = 3; + const layered = holdContext(&g, &surface, 0, 3, 19, layout); + try std.testing.expectEqual(@as(f32, 3 * (12 - 20)), layered.lift); + try std.testing.expectEqual(@as(c_int, 20 + 3 * 12), scrollScissor(&g, layout, 400, 400).y); + // None held: the whole body moves. + surface.body_layers[0].rows = 0; + try std.testing.expectEqual(@as(u16, 0), holdContext(&g, &surface, 0, 0, 19, layout).rows); + try std.testing.expectEqual(@as(c_int, 20), scrollScissor(&g, layout, 400, 400).y); +} + fn scrollScissor(g: *const Gui, layout: CellLayout, sw: u32, sh: u32) c.SDL_Rect { const r = g.scroll_rect; const px = layout.x_off + @as(f32, @floatFromInt(r.x + config.GUTTER)) * layout.w; - const py = layout.y_off + @as(f32, @floatFromInt(g.scroll_body_y)) * layout.h; + const py = layout.y_off + @as(f32, @floatFromInt(g.scroll_body_y)) * layout.h + g.scroll_held_px; const pw = @as(f32, @floatFromInt(r.w - config.GUTTER)) * layout.w; - const ph = @as(f32, @floatFromInt(g.scroll_body_h)) * layout.h; + const ph = @max(0, @as(f32, @floatFromInt(g.scroll_body_h)) * layout.h - g.scroll_held_px); const x0 = std.math.clamp(@as(i32, @intFromFloat(@floor(px))), 0, @as(i32, @intCast(sw))); const y0 = std.math.clamp(@as(i32, @intFromFloat(@floor(py))), 0, @as(i32, @intCast(sh))); const x1 = std.math.clamp(@as(i32, @intFromFloat(@ceil(px + pw))), x0, @as(i32, @intCast(sw))); @@ -6426,7 +6472,10 @@ fn renderFrame( } for (groups.items[0..groups.len], 0..) |group, index| std.debug.assert(cell_next[index] == group.cell_start + group.cell_count); - shifted = emitScrollRows(g, instances, cell_total, surface, layout, win_w, win_h, page); + // The body's context rows, which its scroll leaves where they are. + const scrolling: ?usize = if (g.glide.offset != 0) g.glide.pane else g.scroll_pane; + const held: u16 = if (core) |p| if (scrolling) |id| if (p.panes[id]) |pane| pane.context_rows else 0 else 0 else 0; + shifted = emitScrollRows(g, instances, cell_total, surface, layout, win_w, win_h, page, held); // Over a theme's plaques a see-through cell with no ink blends to // the plaque under it, so it draws nothing: its quad goes, and the // cells are drawn unblended (a third of the GPU's frame at 4K) diff --git a/src/hunks.zig b/src/hunks.zig new file mode 100644 index 00000000..73c0654a --- /dev/null +++ b/src/hunks.zig @@ -0,0 +1,808 @@ +//! A unified diff (`.diff`, `.patch`, a paged `git show`) stacked as a +//! diff viewer shows it (Diff): each hunk under its `path:line`, the +//! declarations around it from tree-sitter as a result's context +//! (locations.zig), its lines behind their `+`/`-` markers drawn red and +//! green, coloured as their file, and the words a changed line changed on +//! a tinted ground as delta emphasises them (its edits.rs and align.rs, here as `inferEdits` +//! and `Alignment`). +const std = @import("std"); +const pardes = @import("pardes.zig"); +const diff = @import("diff.zig"); +const syntax = @import("syntax.zig"); +const locations = @import("locations.zig"); + +const Pardes = pardes.Pardes; +const Row = locations.Row; + +/// The rows `content`, a diff, stacks to, for a pane in `dir`, with each +/// row's metadata (Output.fillRows). Text and rows are `p.gpa`'s; all else +/// is the step's scratch. +pub fn format(p: *Pardes, dir: []const u8, content: []const u8) !locations.Result { + const arena = p.scratch.allocator(); + const styles = try syntax.highlightDiff(arena, content, 0, content.len); + var out: Out = .{ .p = p, .text = .init(p.gpa) }; + errdefer out.deinit(); + var walk: diff.Walk = .{}; + var hunk: Hunk = .{}; + var source: SourceMemo = .{}; + var at: usize = 0; + // The empty text after a last newline is no line. + while (at < content.len) { + const nl = std.mem.indexOfScalarPos(u8, content, at, '\n') orelse content.len; + const raw = content[at..nl]; + const got = walk.step(raw); + const line = std.mem.trimEnd(u8, raw, "\r"); + switch (got.kind) { + .context, .added, .removed => { + const skip = @intFromBool(line.len > 0 and std.mem.indexOfScalar(u8, " +-", line[0]) != null); + try hunk.lines.append(arena, .{ + .kind = got.kind, + .code = line[skip..], + .styles = styles[at + skip ..][0 .. line.len - skip], + .old = got.old, + .new = got.new, + }); + }, + // A `\ No newline` belongs to the line above, as delta shows it. + .no_newline => {}, + else => { + try flush(&out, &hunk, &source, dir); + switch (got.kind) { + .hunk => hunk = .{ + .path = walk.path(), + .deleted = walk.deleted(), + .old_start = got.old, + .new_start = got.new, + .header = gitContext(line), + }, + // What is said around the hunks, a mailed patch's + // headers, message and diffstat, as it was written. + .other => try out.row(line, "", .{ .kind = .context, .at = .{} }), + // A section's own words (a new file's mode, a rename, + // `Binary files ... differ`), muted; its `diff` and + // `index` lines say nothing the labels do not. + .meta => if (!std.mem.startsWith(u8, line, "diff ") and !std.mem.startsWith(u8, line, "index ")) + try out.row(line, "", .{ .kind = .context, .declaration = true, .at = .{} }), + else => {}, + } + }, + } + at = nl + 1; + } + try flush(&out, &hunk, &source, dir); + const rows = try out.rows.toOwnedSlice(p.gpa); + errdefer locations.freeRows(p.gpa, rows); + return .{ .content = try out.text.toOwnedSlice(), .rows = rows, .anchor = null }; +} + +const HunkLine = struct { + kind: diff.Kind, + code: []const u8, + /// Its code's style bytes, as the diff pane paints them (syntax.zig + /// highlightDiff), the emphasis bit added by `inferEdits`. + styles: []u8, + old: usize, + new: usize, + /// Paired with a line it changed (inferEdits): its words show that; + /// unpaired, the whole line was added or removed. + paired: bool = false, +}; + +const Hunk = struct { + path: []const u8 = "", + deleted: bool = false, + old_start: usize = 0, + new_start: usize = 0, + /// What git wrote after the `@@`'s second marker (its function line). + header: []const u8 = "", + lines: std.ArrayList(HunkLine) = .empty, +}; + +/// `@@ -a,b +c,d @@ fn foo()`: `fn foo()`. +fn gitContext(line: []const u8) []const u8 { + const close = std.mem.indexOfPos(u8, line, 2, "@@") orelse return ""; + return std.mem.trim(u8, line[close + 2 ..], " \t"); +} + +const Out = struct { + p: *Pardes, + text: std.Io.Writer.Allocating, + rows: std.ArrayList(Row) = .empty, + + fn deinit(out: *Out) void { + out.text.deinit(); + for (out.rows.items) |r| { + out.p.gpa.free(r.path); + out.p.gpa.free(r.colors); + } + out.rows.deinit(out.p.gpa); + } + + const Meta = struct { + kind: @FieldType(Row, "kind"), + declaration: bool = false, + at: @FieldType(Row, "at"), + location_end: usize = 0, + code_start: usize = 0, + colors: []const u8 = &.{}, + }; + + /// One row: its text, a newline, and its metadata. + fn row(out: *Out, text: []const u8, path: []const u8, meta: Meta) !void { + const gpa = out.p.gpa; + try out.text.writer.writeAll(text); + try out.text.writer.writeByte('\n'); + const owned_path = try gpa.dupe(u8, path); + errdefer gpa.free(owned_path); + const colors = try gpa.dupe(u8, meta.colors); + errdefer gpa.free(colors); + try out.rows.append(gpa, .{ + .kind = meta.kind, + .declaration = meta.declaration, + .path = owned_path, + .at = meta.at, + .location_end = meta.location_end, + .code_start = meta.code_start, + .colors = colors, + }); + } +}; + +/// The file a diff section names, as found from the pane's directory or +/// one above it (a patch kept in a subdirectory of its repository). +const SourceMemo = struct { + path: []const u8 = "", + /// The name a look from the pane's directory resolves; null when the + /// file is nowhere to be found. + shown: ?[]const u8 = null, + lines: []const []const u8 = &.{}, + declarations: []const syntax.ContextDeclaration = &.{}, +}; + +/// Where a +Diff of `content`, a diff in `dir`, stands: the directory its +/// first file is found from (`dir` or one above it, as `findSource` looks), +/// so its rows name their files as the diff does; `dir` when none is found. +pub fn sourceRoot(p: *Pardes, dir: []const u8, content: []const u8) []const u8 { + var walk: diff.Walk = .{}; + var lines = std.mem.splitScalar(u8, content, '\n'); + const path = while (lines.next()) |line| { + if (walk.step(line).kind == .hunk and walk.path().len > 0) break walk.path(); + } else return dir; + var base: []const u8 = dir; + for (0..8) |_| { + if (locations.sourceText(p, p.scratch.allocator(), base, path) != null) return base; + base = std.fs.path.dirname(base) orelse return dir; + } + return dir; +} + +fn findSource(p: *Pardes, memo: *SourceMemo, dir: []const u8, path: []const u8) !void { + if (std.mem.eql(u8, memo.path, path)) return; + const arena = p.scratch.allocator(); + memo.* = .{ .path = path }; + // ponytail: eight directories up; a repository deeper than that under + // its patch is looked for from the patch's own directory only. + var base: []const u8 = dir; + for (0..8) |_| { + if (locations.sourceText(p, arena, base, path)) |text| { + memo.shown = if (base.ptr == dir.ptr) path else try std.fs.path.relativePosix(arena, "/", dir, text.path); + var lines: std.ArrayList([]const u8) = .empty; + var split = std.mem.splitScalar(u8, text.bytes, '\n'); + while (split.next()) |line| try lines.append(arena, std.mem.trimEnd(u8, line, "\r")); + memo.lines = lines.items; + var hit = p.locations_cache.get(p.tree_sitter_gpa, text.path, text.bytes, true, false) catch + locations.Cache.Hit{ .analysis = syntax.analyzeSource(arena, text.path, text.bytes, true, false) catch .{} }; + defer hit.deinit(p.tree_sitter_gpa); + // The cache's may go at its next use: kept for the section. + memo.declarations = try arena.dupe(syntax.ContextDeclaration, hit.analysis.declarations); + return; + } + base = std.fs.path.dirname(base) orelse return; + } +} + +/// Which side of the hunk the file on disk holds, the new one (the patch +/// applied) or the old one, and how far the file has moved it from where +/// the hunk says (`shift`, lines), as patch finds a hunk in a file edited +/// since. A file edited inside the hunk too still holds most of its lines: +/// the place holding the most of them wins (the nearer on a tie) if it +/// holds at least half. Only some, at the nearest place, could be a sibling +/// with the same lines (two functions with one signature's tail). The rows +/// are counted on that side, so moved. +const Side = enum { new, old, neither }; +const OnDisk = struct { side: Side, shift: i64 = 0 }; + +/// ponytail: a hunk moved more than this many lines is not looked for; +/// each try compares the hunk's lines, so a wider search costs that more. +const max_shift = 200; + +fn sideOnDisk(memo: *const SourceMemo, hunk: *const Hunk) OnDisk { + if (memo.shown == null) return .{ .side = .neither }; + var best: OnDisk = .{ .side = .neither }; + var best_held: usize = 0; + var best_of: usize = 1; + var shift: i64 = 0; + while (shift <= max_shift) : (shift += 1) { + for ([2]i64{ shift, -shift }) |by| { + inline for (.{ Side.new, Side.old }) |side| { + const start: i64 = @as(i64, @intCast((if (side == .new) hunk.new_start else hunk.old_start) -| 1)) + by; + if (start >= 0) { + const got = heldAt(memo, hunk, side, @intCast(start)); + if (got.held == got.of) return .{ .side = side, .shift = by }; + // A larger share only: the nearer keeps a tie. + if (got.held * best_of > best_held * got.of) { + best = .{ .side = side, .shift = by }; + best_held = got.held; + best_of = got.of; + } + } + } + if (shift == 0) break; + } + } + return if (best_held > 0 and best_held * 2 >= best_of) best else .{ .side = .neither }; +} + +/// How many of the hunk's `side` lines the file holds from row `start` on, +/// of how many: blank lines, which match anywhere, count for neither. +fn heldAt(memo: *const SourceMemo, hunk: *const Hunk, comptime side: Side, start: usize) struct { held: usize, of: usize } { + var row = start; + var held: usize = 0; + var of: usize = 0; + for (hunk.lines.items) |line| { + const skipped = if (side == .new) line.kind == .removed else line.kind == .added; + if (skipped) continue; + defer row += 1; + if (std.mem.trim(u8, line.code, " \t").len == 0) continue; + of += 1; + if (row < memo.lines.len and std.mem.eql(u8, memo.lines[row], line.code)) held += 1; + } + return .{ .held = held, .of = @max(of, 1) }; +} + +fn flush(out: *Out, hunk: *Hunk, memo: *SourceMemo, dir: []const u8) !void { + defer hunk.* = .{}; + if (hunk.path.len == 0 or hunk.lines.items.len == 0) return; + const p = out.p; + const arena = p.scratch.allocator(); + try findSource(p, memo, dir, hunk.path); + const disk = sideOnDisk(memo, hunk); + const side = disk.side; + // A line number of the hunk's, where the file has it now. + const moved = struct { + fn by(n: usize, shift: i64) usize { + return @intCast(@max(0, @as(i64, @intCast(n)) + shift)); + } + }.by; + const shown = if (side == .neither) hunk.path else memo.shown.?; + const lines = hunk.lines.items; + + // Where the hunk changes something, on the side its rows count: the + // place its label opens. + const first_change = for (lines) |line| { + if (line.kind != .context) break line; + } else lines[0]; + const on_old = side == .old or (side == .neither and hunk.deleted); + const start_row = moved(if (on_old) hunk.old_start else hunk.new_start, disk.shift) -| 1; + const change_row = moved(if (on_old) first_change.old else first_change.new, disk.shift) -| 1; + + // The declarations it stands in, outermost first, as a result's + // tree-sitter context: each one's header rows above the hunk. + var depth: usize = 0; + if (side != .neither) for (memo.declarations) |declaration| { + if (declaration.start_line >= start_row) break; + if (declaration.end_line < change_row) continue; + depth += 1; + var row = declaration.start_line; + while (row <= declaration.header_end_line and row < start_row) : (row += 1) { + const at: @FieldType(Row, "at") = .{ .line = row + 1 }; + if (row == declaration.start_line and p.locations_config.tslocations) { + const label = try std.fmt.allocPrint(arena, "{s}:{d}", .{ shown, row + 1 }); + try out.row(label, shown, .{ .kind = .context, .declaration = true, .at = at, .location_end = label.len, .code_start = label.len }); + } + // A blank where a hunk line has its marker: the code aligns. + try out.row(try std.fmt.allocPrint(arena, " {s}", .{memo.lines[row]}), shown, .{ .kind = .context, .declaration = true, .at = at }); + } + }; + + // The hunk's label: a step for n and N, and a look's place. + const line_no = change_row + 1; + var label: std.Io.Writer.Allocating = .init(arena); + try label.writer.print("{s}:{d}", .{ shown, line_no }); + const location_end = label.written().len; + if (depth > 0) { + try label.writer.writeByte(' '); + try label.writer.splatByteAll('*', depth); + } + try out.row(label.written(), shown, .{ .kind = .match, .at = .{ .line = line_no }, .location_end = location_end, .code_start = label.written().len }); + // No file to read declarations from: git's own function line, muted + // the same way. With one, git's guess (the last line before the hunk + // that looked like a function) would only contradict it. + if (side == .neither and hunk.header.len > 0) + try out.row(try std.fmt.allocPrint(arena, " {s}", .{hunk.header}), shown, .{ .kind = .context, .declaration = true, .at = .{ .line = line_no } }); + + // Each run of removed lines and the added lines after it: the words + // they changed. + var i: usize = 0; + while (i < lines.len) { + if (lines[i].kind == .context) { + i += 1; + continue; + } + const minus_start = i; + while (i < lines.len and lines[i].kind == .removed) i += 1; + const plus_start = i; + while (i < lines.len and lines[i].kind == .added) i += 1; + try inferEdits(arena, lines[minus_start..plus_start], lines[plus_start..i]); + } + + // Each line behind its marker, `+`, `-` or a blank, as the diff + // has it: the marker coloured, the line as its file's. + for (lines) |line| { + const flag: u8 = switch (line.kind) { + .added => syntax.diff_added, + .removed => syntax.diff_removed, + else => 0, + } | @as(u8, if (line.kind != .context and !line.paired) syntax.diff_whole else 0); + const text = try std.fmt.allocPrint(arena, "{c}{s}", .{ @as(u8, switch (line.kind) { + .added => '+', + .removed => '-', + else => ' ', + }), line.code }); + const colors = try arena.alloc(u8, text.len); + colors[0] = flag; + @memcpy(colors[1..], line.styles); + const on = moved(if (on_old) line.old else line.new, disk.shift); + try out.row(text, shown, .{ .kind = .preview, .at = .{ .line = @max(1, on) }, .colors = colors }); + } +} + +// ---- the words a changed line changed (delta's edits.rs) ---- + +/// delta's `max-line-distance`: a removed and an added line further apart +/// than this are not one line changed, and neither is emphasised. +const max_line_distance = 0.6; + +/// ponytail: a run of more removed or added lines than this, or a pair +/// whose token table is bigger than `max_cells`, is shown unemphasised +/// rather than aligned at a quadratic cost (delta aligns them all). +const max_run = 256; +const max_cells = 1 << 16; + +/// Pair each removed line with the first added line after the last one +/// paired that is near enough to it, in order, and emphasise in both the +/// tokens one has and the other has not. +fn inferEdits(arena: std.mem.Allocator, minus: []HunkLine, plus: []HunkLine) !void { + if (minus.len == 0 or plus.len == 0 or minus.len > max_run or plus.len > max_run) return; + var plus_index: usize = 0; + for (minus) |*m| { + const m_tokens = try tokenize(arena, m.code); + var j = plus_index; + while (j < plus.len) : (j += 1) { + const p_tokens = try tokenize(arena, plus[j].code); + if ((m_tokens.len + 1) * (p_tokens.len + 1) > max_cells) continue; + var alignment = try Alignment.init(arena, m_tokens, p_tokens); + const marks = try annotate(arena, &alignment, m.code, plus[j].code); + if (marks.distance > max_line_distance) continue; + for (marks.minus) |r| for (m.styles[r[0]..r[1]]) |*b| { + b.* |= syntax.diff_emph; + }; + for (marks.plus) |r| for (plus[j].styles[r[0]..r[1]]) |*b| { + b.* |= syntax.diff_emph; + }; + m.paired = true; + plus[j].paired = true; + plus_index = j + 1; + break; + } + } +} + +/// delta's tokenize with its default `\w+`: a leading empty token, each +/// run of word characters one token, and every other character one. A +/// line starting with no word gets a second empty token, as delta's does. +/// ponytail: any byte past ASCII counts as a word character, close to +/// Unicode `\w` for letters; a non-ASCII punctuation mark joins a word. +fn tokenize(arena: std.mem.Allocator, line: []const u8) ![]const []const u8 { + var tokens: std.ArrayList([]const u8) = .empty; + try tokens.append(arena, ""); + if (line.len > 0 and !isWord(line[0])) try tokens.append(arena, ""); + var at: usize = 0; + while (at < line.len) { + var end = at + 1; + // A byte past ASCII is a word's, so what is left is one byte. + if (isWord(line[at])) while (end < line.len and isWord(line[end])) { + end += 1; + }; + try tokens.append(arena, line[at..end]); + at = end; + } + return tokens.items; +} + +fn isWord(c: u8) bool { + return std.ascii.isAlphanumeric(c) or c == '_' or c >= 0x80; +} + +const Op = enum(u2) { noop, deletion, insertion }; + +/// delta's align.rs: a Needleman-Wunsch table over two token lists, a +/// change costing more where it starts a new run, so changes group. +const Alignment = struct { + x: []const []const u8, + y: []const []const u8, + cells: []Cell, + width: usize, + + const Cell = struct { parent: u32, op: Op, cost: u32 }; + const deletion_cost = 2; + const insertion_cost = 2; + const initial_mismatch_penalty = 1; + const never = std.math.maxInt(u32); + + fn init(arena: std.mem.Allocator, x: []const []const u8, y: []const []const u8) !Alignment { + const width = x.len + 1; + const cells = try arena.alloc(Cell, width * (y.len + 1)); + @memset(cells, .{ .parent = 0, .op = .noop, .cost = 0 }); + var a: Alignment = .{ .x = x, .y = y, .cells = cells, .width = width }; + for (1..width) |i| cells[i] = .{ .parent = 0, .op = .deletion, .cost = @intCast(i * deletion_cost + initial_mismatch_penalty) }; + for (1..y.len + 1) |j| cells[j * width] = .{ .parent = 0, .op = .insertion, .cost = @intCast(j * insertion_cost + initial_mismatch_penalty) }; + for (x, 0..) |x_i, i| for (y, 0..) |y_j, j| { + const left = a.index(i, j + 1); + const diag = a.index(i, j); + const up = a.index(i + 1, j); + // Ties go to the first: an insertion, then a deletion, then a + // match, so a moved token reads as removed then added. + const candidates = [3]Cell{ + .{ .parent = @intCast(up), .op = .insertion, .cost = a.mismatchCost(up, insertion_cost) }, + .{ .parent = @intCast(left), .op = .deletion, .cost = a.mismatchCost(left, deletion_cost) }, + .{ .parent = @intCast(diag), .op = .noop, .cost = if (std.mem.eql(u8, x_i, y_j)) cells[diag].cost else never }, + }; + var best = candidates[0]; + for (candidates[1..]) |c| if (c.cost < best.cost) { + best = c; + }; + cells[a.index(i + 1, j + 1)] = best; + }; + return a; + } + + fn mismatchCost(a: *const Alignment, parent: usize, basic: u32) u32 { + const cell = a.cells[parent]; + return cell.cost +| basic +| @as(u32, if (cell.op == .noop) initial_mismatch_penalty else 0); + } + + fn index(a: *const Alignment, i: usize, j: usize) usize { + return j * a.width + i; + } + + /// The operations read back from the table's far corner, in order, + /// each run as one (op, count). + fn coalesced(a: *const Alignment, arena: std.mem.Allocator) ![]const struct { Op, usize } { + var ops: std.ArrayList(Op) = .empty; + var cell = a.cells[a.index(a.x.len, a.y.len)]; + while (true) { + try ops.append(arena, cell.op); + if (cell.parent == 0) break; + cell = a.cells[cell.parent]; + } + std.mem.reverse(Op, ops.items); + var runs: std.ArrayList(struct { Op, usize }) = .empty; + for (ops.items) |op| { + if (runs.items.len > 0 and runs.items[runs.items.len - 1][0] == op) { + runs.items[runs.items.len - 1][1] += 1; + } else try runs.append(arena, .{ op, 1 }); + } + return runs.items; + } +}; + +const Marks = struct { + /// Byte ranges of the removed and the added line to emphasise. + minus: []const [2]usize, + plus: []const [2]usize, + distance: f64, +}; + +/// delta's annotate: walk the alignment's runs over both lines, marking +/// what each deleted and inserted, and a run of blanks between two changes +/// with them; the distance is the changed width over the whole width (a +/// kept section counting on both lines). +fn annotate(arena: std.mem.Allocator, a: *const Alignment, minus_line: []const u8, plus_line: []const u8) !Marks { + var minus: std.ArrayList([2]usize) = .empty; + var plus: std.ArrayList([2]usize) = .empty; + var x_off: usize = 0; + var y_off: usize = 0; + var m_byte: usize = 0; + var p_byte: usize = 0; + var numer: usize = 0; + var denom: usize = 0; + var minus_prev: Op = .noop; + var plus_prev: Op = .noop; + const Take = struct { + fn section(tokens: []const []const u8, off: *usize, byte: *usize, n: usize, line: []const u8) [2]usize { + const start = byte.*; + const end_tok = @min(tokens.len, off.* + n); + for (tokens[@min(off.*, end_tok)..end_tok]) |t| byte.* += t.len; + off.* = end_tok; + byte.* = @min(byte.*, line.len); + return .{ start, byte.* }; + } + }; + for (try a.coalesced(arena)) |run| { + const op, const n = run; + switch (op) { + .deletion => { + const r = Take.section(a.x, &x_off, &m_byte, n, minus_line); + const w = trimmedWidth(minus_line[r[0]..r[1]]); + numer += w; + denom += w; + try minus.append(arena, r); + minus_prev = .deletion; + }, + .noop => { + const r = Take.section(a.x, &x_off, &m_byte, n, minus_line); + const section = minus_line[r[0]..r[1]]; + denom += 2 * trimmedWidth(section); + const is_space = std.mem.trim(u8, section, " \t").len == 0; + const coalesce = is_space and + ((minus_prev == .deletion and plus_prev == .insertion and + (x_off < a.x.len -| 1 or y_off < a.y.len -| 1)) or + (minus_prev == .noop and plus_prev == .noop)); + if (coalesce and minus_prev == .deletion) try minus.append(arena, r); + const pr = Take.section(a.y, &y_off, &p_byte, n, plus_line); + if (coalesce and plus_prev == .insertion) try plus.append(arena, pr); + minus_prev = .noop; + plus_prev = .noop; + }, + .insertion => { + const r = Take.section(a.y, &y_off, &p_byte, n, plus_line); + const w = trimmedWidth(plus_line[r[0]..r[1]]); + numer += w; + denom += w; + try plus.append(arena, r); + plus_prev = .insertion; + }, + } + } + const distance: f64 = if (denom > 0) @as(f64, @floatFromInt(numer)) / @as(f64, @floatFromInt(denom)) else 0; + return .{ .minus = minus.items, .plus = plus.items, .distance = distance }; +} + +fn trimmedWidth(section: []const u8) usize { + return pardes.panes.File.displayWidth(std.mem.trim(u8, section, " \t")); +} + +// ---- tests ---- + +const testing = std.testing; + +fn emphasised(line: HunkLine) ![]const u8 { + var out: std.ArrayList(u8) = .empty; + for (line.code, line.styles) |c, s| try out.append(testing.allocator, if (s & syntax.diff_emph != 0) c else '.'); + return out.toOwnedSlice(testing.allocator); +} + +fn expectEmphasis(minus: []const u8, plus: []const u8, want_minus: []const u8, want_plus: []const u8) !void { + var arena_state: std.heap.ArenaAllocator = .init(testing.allocator); + defer arena_state.deinit(); + const arena = arena_state.allocator(); + var m = [_]HunkLine{.{ .kind = .removed, .code = minus, .styles = try arena.alloc(u8, minus.len), .old = 1, .new = 1 }}; + var p = [_]HunkLine{.{ .kind = .added, .code = plus, .styles = try arena.alloc(u8, plus.len), .old = 2, .new = 1 }}; + @memset(m[0].styles, 0); + @memset(p[0].styles, 0); + try inferEdits(arena, &m, &p); + const got_minus = try emphasised(m[0]); + defer testing.allocator.free(got_minus); + const got_plus = try emphasised(p[0]); + defer testing.allocator.free(got_plus); + try testing.expectEqualStrings(want_minus, got_minus); + try testing.expectEqualStrings(want_plus, got_plus); +} + +test "delta's emphasis: the word a line changed, in both lines" { + try expectEmphasis(" let x = foo(1);", " let x = bar(1);", "............foo....", "............bar...."); + try expectEmphasis("a b c", "a x c", "..b..", "..x.."); +} + +test "delta's emphasis: lines too far apart are no change of one another" { + try expectEmphasis("completely different text", "nothing alike here at all", ".........................", "........................."); +} + +test "delta's emphasis: a word added keeps the rest plain" { + try expectEmphasis("fn run(a: u32)", "fn run(a: u32, b: u32)", "..............", "............., b: u32."); +} + +test "delta's alignment: kitten to sitting, as align.rs has it" { + var arena_state: std.heap.ArenaAllocator = .init(testing.allocator); + defer arena_state.deinit(); + const arena = arena_state.allocator(); + // One token a letter, as delta's test splits them, behind the empty one. + const x = [_][]const u8{ "", "k", "i", "t", "t", "e", "n" }; + const y = [_][]const u8{ "", "s", "i", "t", "t", "i", "n", "g" }; + const a = try Alignment.init(arena, &x, &y); + var ops: std.ArrayList(Op) = .empty; + for (try a.coalesced(arena)) |run| for (0..run[1]) |_| try ops.append(arena, run[0]); + try testing.expectEqualSlices(Op, &.{ .noop, .deletion, .insertion, .noop, .noop, .noop, .deletion, .insertion, .noop, .insertion }, ops.items); +} + +test "a diff stacks to a label a hunk and its lines, markers gone, tinted and stepped" { + const p = try Pardes.init(testing.allocator, .{ .tty_only = true }); + defer p.deinit(); + const patch = + \\diff --git a/nowhere/x.txt b/nowhere/x.txt + \\--- a/nowhere/x.txt + \\+++ b/nowhere/x.txt + \\@@ -1,3 +1,3 @@ section one + \\ keep + \\-old value + \\+new value + \\ tail + \\ + ; + const result = try format(p, "/pardes-surely-missing-dir", patch); + defer p.gpa.free(result.content); + defer locations.freeRows(p.gpa, result.rows); + try testing.expectEqualStrings("nowhere/x.txt:2\n section one\n keep\n-old value\n+new value\n tail\n", result.content); + try testing.expectEqual(@as(usize, 6), result.rows.len); + try testing.expectEqual(.match, result.rows[0].kind); + try testing.expectEqual(@as(usize, "nowhere/x.txt:2".len), result.rows[0].location_end); + try testing.expect(result.rows[1].declaration); + const removed = result.rows[3]; + try testing.expect(removed.colors[0] & syntax.diff_removed != 0); + // Paired with the line it changed: no whole-line tint. + try testing.expect(removed.colors[0] & syntax.diff_whole == 0); + try testing.expect(removed.colors[1] & syntax.diff_emph != 0); + try testing.expect(removed.colors[5] & syntax.diff_emph == 0); + try testing.expect(result.rows[4].colors[0] & syntax.diff_added != 0); + try testing.expect(result.rows[2].colors[0] & (syntax.diff_added | syntax.diff_removed) == 0); +} + +test "a hunk the file has moved since is found where it went, inside its declaration" { + if (!syntax.supportsPath("a.zig")) return error.SkipZigTest; + const p = try Pardes.init(testing.allocator, .{ .tty_only = true }); + defer p.deinit(); + var tmp = testing.tmpDir(.{}); + defer tmp.cleanup(); + // Two lines more above it than the patch knows of. + try tmp.dir.writeFile(testing.io, .{ .sub_path = "a.zig", .data = "// one\n// two\nconst S = struct {\n fn f() void {\n a();\n b();\n }\n};\n" }); + var buf: [std.fs.max_path_bytes]u8 = undefined; + const dir = buf[0..try tmp.dir.realPath(testing.io, &buf)]; + const patch = + \\--- a.zig + \\+++ a.zig + \\@@ -3,3 +3,3 @@ git's guess + \\ fn f() void { + \\- c(); + \\+ a(); + \\ b(); + \\ + ; + const result = try format(p, dir, patch); + defer p.gpa.free(result.content); + defer locations.freeRows(p.gpa, result.rows); + try testing.expect(std.mem.indexOf(u8, result.content, "a.zig:3\n const S = struct {\na.zig:5 *\n") != null); + try testing.expect(std.mem.indexOf(u8, result.content, "git's guess") == null); +} + +test "a mailed patch keeps its headers, message and diffstat above its hunks" { + const p = try Pardes.init(testing.allocator, .{ .tty_only = true }); + defer p.deinit(); + const patch = + \\From 0123 Mon Sep 17 00:00:00 2001 + \\Subject: [PATCH] change x + \\ + \\Why it changed. + \\--- + \\ x.txt | 2 +- + \\ + \\diff --git a/x.txt b/x.txt + \\index 1..2 100644 + \\--- a/x.txt + \\+++ b/x.txt + \\@@ -1 +1 @@ + \\-a + \\+b + \\ + ; + const result = try format(p, "/pardes-surely-missing-dir", patch); + defer p.gpa.free(result.content); + defer locations.freeRows(p.gpa, result.rows); + try testing.expectEqualStrings("From 0123 Mon Sep 17 00:00:00 2001\nSubject: [PATCH] change x\n\nWhy it changed.\n---\n x.txt | 2 +-\n\nx.txt:1\n-a\n+b\n", result.content); +} + +test "DiffLook hunks: a .patch looked at opens its +Diff; Diff goes to the text and back; DiffLook text opens the text" { + const p = try Pardes.init(testing.allocator, .{ .tty_only = true }); + defer p.deinit(); + var tmp = testing.tmpDir(.{}); + defer tmp.cleanup(); + try tmp.dir.writeFile(testing.io, .{ .sub_path = "x.txt", .data = "b\n" }); + try tmp.dir.writeFile(testing.io, .{ .sub_path = "c.patch", .data = "--- x.txt\n+++ x.txt\n@@ -1 +1 @@\n-a\n+b\n" }); + var buf: [std.fs.max_path_bytes]u8 = undefined; + const dir = buf[0..try tmp.dir.realPath(testing.io, &buf)]; + const patch = try std.fs.path.join(testing.allocator, &.{ dir, "c.patch" }); + defer testing.allocator.free(patch); + const hunks_path = try std.fs.path.join(testing.allocator, &.{ dir, "+Diff" }); + defer testing.allocator.free(hunks_path); + const Count = struct { + fn of(pp: *Pardes, path: []const u8) usize { + var n: usize = 0; + for (pp.panes) |slot| if (slot) |pane| if (pane.file) |f| { + n += @intFromBool(std.mem.eql(u8, f.path, path)); + }; + return n; + } + }; + try testing.expectEqual(pardes.config.Runtime.DiffLook.hunks, p.settings.diff_look); + pardes.look.lookAt(p, 0, patch); + try testing.expectEqual(@as(usize, 1), Count.of(p, hunks_path)); + try testing.expectEqual(@as(usize, 0), Count.of(p, patch)); + const hid = p.active; + try testing.expectEqualStrings(hunks_path, p.panes[hid].?.file.?.path); + try testing.expectEqualStrings("x.txt:1\n-a\n+b\n", p.panes[hid].?.file.?.content); + // Diff on it: the patch as text. + try testing.expect(p.executeBuiltinLine(hid, "Diff")); + try testing.expectEqual(@as(usize, 1), Count.of(p, patch)); + const raw = p.active; + try testing.expectEqualStrings(patch, p.panes[raw].?.file.?.path); + // Diff on the text: the +Diff again, refilled, not another. + try testing.expect(p.executeBuiltinLine(raw, "Diff")); + try testing.expectEqual(@as(usize, 1), Count.of(p, hunks_path)); + // DiffLook text: a look opens the text (here the pane already open). + try testing.expect(p.executeBuiltinLine(0, "DiffLook text")); + try p.removePane(raw, null); + pardes.look.lookAt(p, 0, patch); + try testing.expectEqual(@as(usize, 1), Count.of(p, patch)); +} + +test "a hunk edited since, beside siblings with its signature's tail, is found in its own function" { + if (!syntax.supportsPath("a.rs")) return error.SkipZigTest; + const p = try Pardes.init(testing.allocator, .{ .tty_only = true }); + defer p.deinit(); + var tmp = testing.tmpDir(.{}); + defer tmp.cleanup(); + // Three functions ending in one signature's tail; the patch is for the + // third, which has moved down a line and had a line inside it edited. + try tmp.dir.writeFile(testing.io, .{ .sub_path = "a.rs", .data = + \\// moved + \\fn one( + \\ limit: usize, + \\) -> u32 { + \\ 1 + \\} + \\fn two( + \\ limit: usize, + \\) -> u32 { + \\ 2 + \\} + \\fn three( + \\ limit: usize, + \\) -> u32 { + \\ let guard = enter(); + \\ let a = 3; + \\ let b = a + 1; + \\ let c = b * 2; // edited since + \\ c + \\} + \\ + }); + var buf: [std.fs.max_path_bytes]u8 = undefined; + const dir = buf[0..try tmp.dir.realPath(testing.io, &buf)]; + const patch = + \\--- a.rs + \\+++ a.rs + \\@@ -12,7 +12,8 @@ git's guess + \\ limit: usize, + \\ ) -> u32 { + \\+ let guard = enter(); + \\ let a = 3; + \\ let b = a + 1; + \\ let c = b * 2; + \\ c + \\ + ; + const result = try format(p, dir, patch); + defer p.gpa.free(result.content); + 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); +} diff --git a/src/locations.zig b/src/locations.zig index 6a604907..7755f6fd 100644 --- a/src/locations.zig +++ b/src/locations.zig @@ -159,7 +159,9 @@ const Pending = struct { const Source = struct { path: []const u8, bytes: []const u8 }; -fn sourceText(p: *pardes.Pardes, arena: std.mem.Allocator, dir: []const u8, path: []const u8) ?Source { +/// A file's text as a look from `dir` finds it: an open pane's, unsaved +/// edits and all, else the disk's. Null for a PDF or one not there. +pub fn sourceText(p: *pardes.Pardes, arena: std.mem.Allocator, dir: []const u8, path: []const u8) ?Source { if (std.ascii.eqlIgnoreCase(std.fs.path.extension(path), ".pdf")) return null; const lexical = std.fs.path.resolvePosix(arena, &.{ dir, path }) catch return null; var pathbuf: [4096]u8 = undefined; diff --git a/src/look.zig b/src/look.zig index 41cfdc0c..6ba6a8d0 100644 --- a/src/look.zig +++ b/src/look.zig @@ -1869,6 +1869,18 @@ pub fn lookAt(p: *Pardes, id: usize, operand_raw: []const u8) void { const before = p.active; var opened: ?usize = null; if (!focusPaneByPath(p, target.path, target.at)) { + // A .diff or .patch looked at bare: its hunks stacked in a + // +Diff (DiffLook hunks), which takes the keyboard as the + // file would; one with none in it opens as text. + if (p.settings.diff_look == .hunks and !p.look_text and target.at.line == 0 and + (std.mem.endsWith(u8, target.path, ".diff") or std.mem.endsWith(u8, target.path, ".patch"))) + if (filesystem.read(p, target.path)) |bytes| { + defer p.gpa.free(bytes); + if (panes.Output.openDiff(p, id, target.path, bytes)) |hid| { + p.active = hid; + return; + } else |_| {} + } else |_| {}; const free = p.freeSlot() orelse return p.reportError(id, "look", error.NoPaneSlots); const nt = panes.File.open(p, free, target.path, target.at.line) catch |err| return lookOpenFailed(p, id, target.path, err); diff --git a/src/main.zig b/src/main.zig index ed70b624..26259b43 100644 --- a/src/main.zig +++ b/src/main.zig @@ -102,7 +102,7 @@ const help_text = ; /// `pardes -` inside a session: `text`, stdin as it came, escapes and all, -/// into the directory's one +Pager (/pager, refilled when it is there): +/// into a new +Pager of the directory (/pager): /// written after the directory on that one open, the session parses it /// (pager.zig) and puts it in as one undo step, left clean. A text the /// session would not take is never lost: it goes to stderr, a terminal, diff --git a/src/mouse.zig b/src/mouse.zig index 8020fda8..733479dd 100644 --- a/src/mouse.zig +++ b/src/mouse.zig @@ -1288,7 +1288,7 @@ fn dragRelease(p: *Pardes, button: Mouse.Button) void { pane.sel[sel_slot].state = .none; pane.body.vsel = .{ .active = true, .row = @intCast(a.row), .col = @intCast(a.col), .explicit = true }; }; - if (s.ctrl) p.lspRequest(s.id, .definition, ""); + if (s.ctrl) exec.runBuiltin(p, .Def, s.id, "", null); } } else { const clk = pane.sel[b]; diff --git a/src/ninep/ctl.zig b/src/ninep/ctl.zig index c9ce41e1..e6e738a5 100644 --- a/src/ninep/ctl.zig +++ b/src/ninep/ctl.zig @@ -682,7 +682,7 @@ pub fn readRoot(p: *Pardes, req: Req) Reply { } /// /pager, `pardes -`'s: the directory written (empty, or not absolute: the -/// session's) gets its one +Pager, made or emptied; the serial is what a +/// session's) gets a new +Pager; the serial is what a /// read of this same open answers, never another client's. What the open /// writes after that line is the text, held by tree.zig for `fillPager`. pub fn writePager(p: *Pardes, req: Req) Reply { @@ -742,6 +742,16 @@ pub fn fillPager(p: *Pardes, serial: u32, held: *std.ArrayList(u8)) error{OutOfM panes.File.setContent(p, f, page.text); f.pager_spans = page.spans; f.saved_revision = f.revision; + // A diff paged (`git show`, difftui's patches): its hunks stacked in a + // +Diff (DiffLook hunks), the +Pager folded to its tag under it for + // Diff to bring back. The keyboard stays where it was, as a page's. + if (f.pager_diff and p.settings.diff_look == .hunks) { + const keyboard = p.active; + if (panes.Output.openDiff(p, id, f.path, f.content)) |_| { + if (!pane.collapsed) pardes.layout.toggleCollapse(p, id); + } else |_| {} + if (p.panes[keyboard] != null) p.active = keyboard; + } } /// The editor's step: the text of /pager opens closed unread goes in. @@ -2258,7 +2268,8 @@ test "a builtin for one kind of pane is refused on another, and still acts on it .{ "Petscii\n", "Petscii: only an image or a terminal pane takes it" }, .{ "Palette\n", "Palette: only an image pane takes it" }, .{ "Ascii\n", "Ascii: only an image pane takes it" }, - .{ "Filter\n", "Filter: only a terminal pane takes it" }, + .{ "Filter\n", "Filter: only a terminal or a +Pager pane takes it" }, + .{ "Diff\n", "Diff: only a diff or a +Diff pane takes it" }, .{ "Togglettymode\n", "Togglettymode: only a terminal pane takes it" }, }; for (cases) |case| { @@ -4607,10 +4618,15 @@ test "pager answers its +Pager on the open that asked, whatever another client e try testing.expectEqual(E.INVAL, call(p, .{ .tag = 8, .op = .write, .node = pager, .handle = refused, .data = "relative\n" }).errno()); try testing.expectEqualStrings("", call(p, .{ .tag = 9, .op = .read, .node = pager, .handle = refused, .size = 64 }).bytes); _ = call(p, .{ .tag = 10, .op = .release, .node = pager, .handle = refused, .opened = true }); - // Resolved: `/tmp/../tmp/.` is /tmp's +Pager, the one made above. + // Resolved: `/tmp/../tmp/.` is /tmp, a +Pager of its own beside the + // one made above, which keeps its page. const resolved = call(p, .{ .tag = 11, .op = .open, .node = pager, .omode = 2 }).reply.handle; try testing.expectEqual(Status.ok, call(p, .{ .tag = 12, .op = .write, .node = pager, .handle = resolved, .data = "/tmp/../tmp/.\n" }).reply.status); - try testing.expectEqualStrings(want, call(p, .{ .tag = 13, .op = .read, .node = pager, .handle = resolved, .size = 64 }).bytes); + const second = call(p, .{ .tag = 13, .op = .read, .node = pager, .handle = resolved, .size = 64 }).bytes; + try testing.expect(!std.mem.eql(u8, want, second)); + const second_pane = p.panes[p.paneBySerial(try std.fmt.parseInt(u32, std.mem.trim(u8, second, "\n"), 10)).?].?; + try testing.expectEqualStrings("/tmp/+Pager", second_pane.file.?.path); + try testing.expect(p.paneBySerial(paged) != null); _ = call(p, .{ .tag = 14, .op = .release, .node = pager, .handle = resolved, .opened = true }); // One that may not be written is refused, permission denied. try testing.expectEqual(E.PERM, wr(p, pager, "/proc/1\n").errno()); @@ -4667,15 +4683,24 @@ test "what a /pager open writes after its directory is the text: plain in the bo // PagerColor off, and an open closed with no read: the same text, plain, // in at the editor's next step (a close through a mount never waits). p.settings.pager_color = false; + const kept = try testing.allocator.dupe(u8, f.content); + defer testing.allocator.free(kept); const shut = call(p, .{ .tag = 7, .op = .open, .node = pager, .omode = 1 }).reply.handle; try testing.expectEqual(Status.ok, call(p, .{ .tag = 8, .op = .write, .node = pager, .handle = shut, .data = "/tmp\n" }).reply.status); try testing.expectEqual(Status.ok, call(p, .{ .tag = 9, .op = .write, .node = pager, .handle = shut, .data = "\x1b[1;32mgreen\x1b[m\n" }).reply.status); _ = call(p, .{ .tag = 10, .op = .release, .node = pager, .handle = shut, .opened = true }); - try testing.expectEqualStrings("", f.content); + // A new +Pager: the first keeps its page. + try testing.expectEqualStrings(kept, f.content); + const next = for (p.panes) |slot| { + const other = slot orelse continue; + if (other == pn) continue; + if (other.file) |*of| if (std.mem.eql(u8, of.path, "/tmp/+Pager")) break of; + } else return error.NoPager; + try testing.expectEqualStrings("", next.content); fillClosedPagers(p); - try testing.expectEqualStrings("green\n", f.content); - try testing.expectEqual(@as(usize, 0), f.pager_spans.len); - try testing.expectEqual(f.revision, f.saved_revision); + try testing.expectEqualStrings("green\n", next.content); + try testing.expectEqual(@as(usize, 0), next.pager_spans.len); + try testing.expectEqual(next.revision, next.saved_revision); } test "a command pane an exec open was answered is leased to it while it stays open: another client's command gets a pane of its own" { diff --git a/src/ninep/tree.zig b/src/ninep/tree.zig index c78a1aa2..eedab43b 100644 --- a/src/ninep/tree.zig +++ b/src/ninep/tree.zig @@ -258,7 +258,7 @@ pub const TopFile = enum(u5) { /// The files opened lately, closed ones too, a line each: /// `open|closed `, most recent first. recent, - /// `pardes -`'s: a directory written, its +Pager made or emptied; a + /// `pardes -`'s: a directory written, a new +Pager made there; a /// read of the same open answers its serial. pager, diff --git a/src/normal.zig b/src/normal.zig index 93487e88..aec6b983 100644 --- a/src/normal.zig +++ b/src/normal.zig @@ -743,14 +743,15 @@ fn executeNormalAction(p: *Pardes, t: *Text, semantic: modal.Normal.Action) void .undo => return edit.doUndo(p, t), .redo => return edit.doRedo(p, t), }, - .lsp => |request| return p.lspRequest(p.active, switch (request) { - .definition => .definition, - .declaration => .declaration, - .type_definition => .type_definition, - .implementation => .implementation, - .references => .references, - .format => .format, - }, ""), + // gd and gr are the Def and Refs a tag shows, run as a click runs them. + .lsp => |request| return switch (request) { + .definition => exec.runBuiltin(p, .Def, p.active, "", null), + .references => exec.runBuiltin(p, .Refs, p.active, "", null), + .declaration => p.lspRequest(p.active, .declaration, ""), + .type_definition => p.lspRequest(p.active, .type_definition, ""), + .implementation => p.lspRequest(p.active, .implementation, ""), + .format => p.lspRequest(p.active, .format, ""), + }, .adjust_number => |delta| return edit.normalAdjustNumber(p, t, delta), .leader => if (p.macro.replaying == 0) { p.leader_on = true; diff --git a/src/pardes.zig b/src/pardes.zig index 2a74e441..29192c33 100644 --- a/src/pardes.zig +++ b/src/pardes.zig @@ -480,6 +480,7 @@ pub const Loc = struct { test { _ = @import("tagline.zig"); + _ = @import("hunks.zig"); _ = @import("builtins_json.zig"); _ = @import("exec.zig"); _ = @import("look.zig"); @@ -864,7 +865,7 @@ test "TreeContext command and custom tag survive a workspace round trip" { p.gpa.free(pane.file.?.path); pane.file.?.path = path; if (!panes.File.supportsContext(pane)) return error.SkipZigTest; - try std.testing.expectEqualStrings(tagline.context_pane_tail, tagline.curTail(pane)); + try std.testing.expectEqualStrings(if (lsp.speaks("/test.zig")) tagline.lsp_context_pane_tail else tagline.context_pane_tail, tagline.curTail(pane)); try std.testing.expect(!pane.file.?.tree_context); try std.testing.expect(p.executeBuiltinLine(0, "TreeContext on")); try std.testing.expect(pane.file.?.tree_context); @@ -920,7 +921,7 @@ test "Togglettymode builtin and keyboard chord share mode transitions including try std.testing.expectEqualStrings("unchanged\n", file.file.?.content); } -test "Filter is ordered after Del and toggles only its terminal pane" { +test "Filter is ordered after Del and toggles only its terminal or +Pager pane" { const testing = std.testing; const del = std.meta.stringToEnum(Builtin, "Del") orelse return error.MissingDelBuiltin; const filter = std.meta.stringToEnum(Builtin, "Filter") orelse return error.MissingFilterBuiltin; @@ -954,6 +955,17 @@ test "Filter is ordered after Del and toggles only its terminal pane" { try testing.expect(p.executeBuiltinLine(0, "Filter")); try testing.expect(first.tty_filter); try testing.expect(!second.tty_filter); + + // A +Pager opens filtered, with Filter on its tag and no line numbers; + // a second is a pane of its own. + const pager_id = try panes.Output.openPager(p, 0, "/tmp"); + const pager_pane = p.panes[pager_id].?; + try testing.expect(pager_pane.tty_filter); + try testing.expectEqualStrings(tagline.pager_pane_tail, tagline.curTail(pager_pane)); + try testing.expectEqual(@as(u16, 0), panes.File.gutterWidth(pager_pane)); + try testing.expect(p.executeBuiltinLine(pager_id, "Filter")); + try testing.expect(!pager_pane.tty_filter); + try testing.expect(try panes.Output.openPager(p, 0, "/tmp") != pager_id); } test "compact tag commands stay beside their own prefix across layout changes" { @@ -1194,6 +1206,73 @@ test "Lspwhy after a Hover asks to explain that hover, in its file at its place, try std.testing.expect(seen); } +test "Def and Refs are a speaking file's tag words; gd, gr and a 2-1 chord all run them" { + if (!lsp.supports.contains(.definition)) return error.SkipZigTest; + const p = try Pardes.init(std.testing.allocator, .{ .cols = 100, .rows = 24, .tty_only = true }); + defer p.deinit(); + const pane = try p.setTestFile("const alpha = 1;\nconst beta = alpha;\n"); + // A .txt has no server: no Def, no Refs. + try std.testing.expect(std.mem.indexOf(u8, tagline.curTail(pane), "Def") == null); + const f = &pane.file.?; + p.gpa.free(f.path); + f.path = try p.gpa.dupe(u8, "/tmp/x.zig"); + try std.testing.expect(std.mem.endsWith(u8, tagline.curTail(pane), " Def Refs")); + p.sync(); + while (p.nextEffect()) |_| {} + const Asked = struct { + fn one(q: *Pardes, kind: lsp.Kind) !u32 { + var at: ?u32 = null; + while (q.nextEffect()) |e| if (e == .lsp) { + try std.testing.expectEqual(kind, e.lsp.kind); + try std.testing.expectEqualStrings("", e.lsp.arg.slice()); + try std.testing.expect(at == null); + at = e.lsp.offset; + }; + q.lsp_wait = null; + return at orelse error.NothingAsked; + } + }; + // gd and gr: at the cursor, on `alpha`'s declaration. + pane.body.cur_row = 0; + pane.body.cur_col = 8; + p.update(.{ .key = .{ .cp = 'g' } }); + p.update(.{ .key = .{ .cp = 'd' } }); + try std.testing.expectEqual(@as(u32, 8), try Asked.one(p, .definition)); + p.update(.{ .key = .{ .cp = 'g' } }); + p.update(.{ .key = .{ .cp = 'r' } }); + try std.testing.expectEqual(@as(u32, 8), try Asked.one(p, .references)); + + const r = p.rects[0]; + const x0 = r.x + config.GUTTER + panes.File.gutterWidth(pane); + const use_y = p.bodyTop(pane, r) + 1; + const tag = try tagline.tagText(p, p.scratch.allocator(), pane); + for ([_]struct { word: []const u8, kind: lsp.Kind }{ .{ .word = " Def ", .kind = .definition }, .{ .word = " Refs", .kind = .references } }) |w| { + // B1 sweeps the use of `alpha` on the second line (bytes 30..35), + // leaving the cursor at its far end. + p.update(.{ .mouse = .{ .button = config.select_button, .kind = .press, .col = x0 + 13, .row = use_y } }); + p.update(.{ .mouse = .{ .button = config.select_button, .kind = .drag, .col = x0 + 17, .row = use_y } }); + p.update(.{ .mouse = .{ .button = config.select_button, .kind = .release, .col = x0 + 17, .row = use_y } }); + // B2 on the tag word, B1 clicked while it is held: the sweep is its + // argument, and it asks at the start of `alpha`, not at the cursor. + const wx = r.x + TAG_TEXT_INSET + @as(u16, @intCast(std.mem.indexOf(u8, tag, w.word).? + 1)); + p.update(.{ .mouse = .{ .button = config.exec_button, .kind = .press, .col = wx, .row = r.y } }); + p.update(.{ .mouse = .{ .button = config.select_button, .kind = .press, .col = wx, .row = r.y } }); + p.update(.{ .mouse = .{ .button = config.select_button, .kind = .release, .col = wx, .row = r.y } }); + p.update(.{ .mouse = .{ .button = config.exec_button, .kind = .release, .col = wx, .row = r.y } }); + try std.testing.expectEqual(@as(u32, 30), try Asked.one(p, w.kind)); + // Clicked bare, it asks at the cursor, where the sweep left it. + pane.body.cur_row = 0; + pane.body.cur_col = 2; + p.update(.{ .mouse = .{ .button = config.exec_button, .kind = .press, .col = wx, .row = r.y } }); + p.update(.{ .mouse = .{ .button = config.exec_button, .kind = .release, .col = wx, .row = r.y } }); + try std.testing.expectEqual(@as(u32, 2), try Asked.one(p, w.kind)); + } + // A symbol the file does not hold is said, and nothing is asked. + exec.runBuiltin(p, .Def, 0, "", "gamma"); + try std.testing.expectError(error.NothingAsked, Asked.one(p, .definition)); + try std.testing.expectEqualStrings("Def: no gamma in this file", pane.msg[0..pane.msg_len]); +} + test "the Tutor pane is named +Tutor in the session's directory, never a bare path at the root" { const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true }); defer p.deinit(); @@ -4508,6 +4587,9 @@ pub const Pardes = struct { chord_hold: bool = false, /// The look just run found nothing (look.zig missed). look_missed: bool = false, + /// The look being run opens a .diff or .patch as text whatever DiffLook + /// says: Diff going back from a +Diff, Edit's B (it edits the file). + look_text: bool = false, look_hover_wait: ?look.LookHoverWait = null, /// The place a look-hover last found nothing to open: the pointer /// resting there does not ask again every frame (look.noteLookHover). @@ -4748,6 +4830,8 @@ pub const Pardes = struct { const named = try std.fs.path.join(gpa, &.{ dir, "+Pager" }); gpa.free(shown.file.?.path); shown.file.?.path = named; + shown.file.?.pager = true; + shown.tty_filter = true; shown.file.?.pager_diff = panes.File.looksLikeDiff(content[0..@min(content.len, 64 * 1024)]); shown.file.?.pager_spans = page.spans; p.oneColumn(); @@ -6674,7 +6758,8 @@ pub const Pardes = struct { pub const SavePath = Effect.Buf(effect_path_cap); - pub fn lspRequest(p: *Pardes, asked: usize, kind: lsp.Kind, arg: []const u8) void { + pub fn lspRequest(p: *Pardes, asked: usize, kind: lsp.Kind, arg_in: []const u8) void { + var arg = arg_in; if (!normal.multiOnce(p)) return; // one question per keystroke, from the primary // Lspwhy narrates the last query where it was asked -- that pane's // file, place and argument -- from wherever it is run. @@ -6697,10 +6782,30 @@ pub const Pardes = struct { (!zig_buf and std.mem.indexOfAny(u8, arg, " \t\r\n\"\\") != null)) return p.reportFailure(id, std.fmt.bufPrint(&said, "Rename: {s} is no name", .{arg}) catch "Rename: no name"); } - const off = if (pane.file) |f| modal.offsetAt(f.content, .{ + var off = if (pane.file) |f| modal.offsetAt(f.content, .{ .row = @intCast(@max(0, pane.body.cur_row)), .col = @intCast(@max(0, pane.body.cur_col)), }) else 0; + // Def or Refs given a symbol (a 2-1 chord's selection) asks at its + // occurrence nearest the cursor, which a sweep leaves at one end of + // what it selected; the server is asked at a place, never a name. + if ((kind == .definition or kind == .references) and arg.len > 0) { + const content = pane.file.?.content; + var nearest: ?usize = null; + var best: usize = 0; + var from: usize = 0; + while (std.mem.indexOfPos(u8, content, from, arg)) |at_hit| : (from = at_hit + 1) { + const d = if (at_hit > off) at_hit - off else off -| (at_hit + arg.len); + if (nearest != null and at_hit > off and d >= best) break; + if (nearest == null or d < best) { + nearest = at_hit; + best = d; + } + } + off = nearest orelse + return p.reportFailure(id, std.fmt.bufPrint(&said, "{s}: no {s} in this file", .{ lspWord(kind), arg }) catch "no such symbol in this file"); + arg = ""; + } // Lspwhy asks the last query again, narrated: its kind and argument, // at its place when asked from its pane. None yet: a definition. var explained: [160]u8 = undefined; @@ -6858,6 +6963,8 @@ pub const Pardes = struct { fn lspWord(kind: lsp.Kind) []const u8 { return switch (kind) { .hover => "Hover", + .definition => "Def", + .references => "Refs", .explain => "Lspwhy", .incoming_calls => "Callers", .outgoing_calls => "Callees", diff --git a/src/syntax.zig b/src/syntax.zig index b7406b04..89d96239 100644 --- a/src/syntax.zig +++ b/src/syntax.zig @@ -854,7 +854,13 @@ pub fn highlightLocationRows(gpa: std.mem.Allocator, content: []const u8, rows: if (comptime @hasField(@TypeOf(row), "location_end")) { address_only = row.location_end > 0 and source_start == end; } - if (!address_only) { + // A row its producer coloured whole is coloured below: no + // fragment of it to parse. + var coloured = false; + if (comptime @hasField(@TypeOf(row), "colors")) { + coloured = row.colors.len > 0 and row.colors.len >= end - source_start; + } + if (!address_only and !coloured) { sources[source_count] = .{ .index = index, .start = source_start, .len = end - source_start }; source_count += 1; } @@ -1037,10 +1043,15 @@ fn childOfKind(node: ts.Node, kind: []const u8) ?ts.Node { /// A diff line's style byte carries whether the line was added or removed /// over its syntax style (the low bits), so the painter can tint its row -/// and mark its prefix. +/// and mark its prefix; Diff marks the words a changed line changed +/// (hunks.zig), drawn on a stronger tint. pub const diff_added: u8 = 0x80; pub const diff_removed: u8 = 0x40; -pub const syn_bits: u8 = 0x3f; +pub const diff_emph: u8 = 0x20; +/// A +Diff line added or removed whole, paired with no line it changed: +/// its row takes a faint tint, on its marker's byte. +pub const diff_whole: u8 = 0x10; +pub const syn_bits: u8 = 0x0f; /// A file section's hunks are parsed together, each side as one text, in /// pieces: a piece takes whole hunks until it holds `diff_piece_lines` diff --git a/src/tagline.zig b/src/tagline.zig index d13f3c5f..cf0b17fd 100644 --- a/src/tagline.zig +++ b/src/tagline.zig @@ -21,6 +21,13 @@ pub const pdf_pane_tail = " " ++ config.pdf_pane_builtins_str; pub const file_pane_tail = " " ++ config.file_pane_builtins_str; pub const context_pane_tail = file_pane_tail ++ " TreeContext"; pub const locations_pane_tail = file_pane_tail ++ " LocationsConfig"; +/// A file a language server speaks for (by its extension): its jumps too. +pub const lsp_pane_tail = file_pane_tail ++ " " ++ config.lsp_pane_builtins_str; +pub const lsp_context_pane_tail = context_pane_tail ++ " " ++ config.lsp_pane_builtins_str; +pub const pager_pane_tail = " " ++ config.pager_pane_builtins_str; +pub const diff_pane_tail = " " ++ config.diff_pane_builtins_str; +pub const pager_diff_pane_tail = " " ++ config.pager_diff_pane_builtins_str; +pub const diff_view_tail = " " ++ config.diff_view_builtins_str ++ " LocationsConfig"; pub const terminal_pane_tail = " " ++ config.terminal_pane_builtins_str; pub const command_pane_tail = " " ++ config.command_pane_builtins_str; pub const dir_pane_tail = " " ++ config.dir_pane_builtins_str; @@ -164,10 +171,15 @@ pub fn curTail(pane: *Pane) []const u8 { pub fn defaultTail(pane: *const Pane) []const u8 { if (comptime pdf_enabled) if (pane.pdf != null) return pdf_pane_tail; if (pane.file) |file| if (file.listing != null) return dir_pane_tail; - if (pane.file) |file| if (file.output) |out| + if (pane.file) |file| if (file.pager) return if (file.pager_diff) pager_diff_pane_tail else pager_pane_tail; + if (pane.file != null and pane.colorAlgo() == .diff) return diff_pane_tail; + if (pane.file) |file| if (file.output) |out| { + if (std.meta.eql(out.from, panes.Output.Origin{ .cmd = .Diff })) return diff_view_tail; if (panes.Output.usesLocationsConfig(out.from)) return locations_pane_tail; - if (panes.File.supportsContext(pane)) return context_pane_tail; - if (pane.file != null) return file_pane_tail; + }; + const speaks = if (pane.file) |file| file.output == null and file.mini == null and pardes.lsp.speaks(file.path) else false; + if (panes.File.supportsContext(pane)) return if (speaks) lsp_context_pane_tail else context_pane_tail; + if (pane.file != null) return if (speaks) lsp_pane_tail else file_pane_tail; if (pane.command != null) return command_pane_tail; if (pane.isTerminal()) return if (pane.shell_tail_len > 0) pane.shell_tail[0..pane.shell_tail_len] else terminal_pane_tail; return pane_tail; diff --git a/src/terminal.zig b/src/terminal.zig index 3bb1fbda..3190c6e3 100644 --- a/src/terminal.zig +++ b/src/terminal.zig @@ -2041,7 +2041,7 @@ pub fn recolorAnsi(p: *Pardes, s: *Surface, pane: *Pane, r: pardes.Rect, tx: u16 const filtered: ?*FilteredColors = if (pane.tty_filter) blk: { const tz_filter = tracy.zone(@src(), "filterInit"); defer tz_filter.end(); - filtered_storage = FilteredColors.init(p, pane); + filtered_storage = FilteredColors.init(p, &pane.terminal.?.vt); break :blk &filtered_storage; } else null; // DECSCNM, read once: the filtered palette folds it in itself, the raw @@ -2192,7 +2192,9 @@ fn cellStyle(p: *Pardes, ci: ghostty_vt.PageList.Cell, filtered: ?*FilteredColor return cs; } -const FilteredColors = struct { +/// A program's colours mapped to the theme (Filter): a terminal's cells, or +/// a +Pager's spans (`vt` null, the program's palette xterm's own). +pub const FilteredColors = if (enabled) struct { source: GColor.Palette, target: *const GColor.Palette, theme_bg: GColor.RGB, @@ -2212,16 +2214,18 @@ const FilteredColors = struct { cache_key: [256]u8 = undefined, cache_valid: [256]bool = @splat(false), - fn init(p: *Pardes, pane: *const Pane) FilteredColors { + pub fn init(p: *Pardes, vt: ?*const ghostty_vt.Terminal) FilteredColors { var source = GColor.default; - for (&source, 0..) |*rgb, i| - rgb.* = pane.terminal.?.vt.colorForXterm(.{ .palette = @intCast(i) }) orelse rgb.*; + if (vt) |t| { + for (&source, 0..) |*rgb, i| + rgb.* = t.colorForXterm(.{ .palette = @intCast(i) }) orelse rgb.*; + } const theme = p.theme(); var theme_bg = asGhostRgb(theme.bg orelse theme.tag_bg); var theme_fg = asGhostRgb(theme.fg orelse theme.tag_fg); - var dynamic_bg = pane.terminal.?.vt.colorForXterm(.{ .dynamic = .background }); - var dynamic_fg = pane.terminal.?.vt.colorForXterm(.{ .dynamic = .foreground }); - if (pane.terminal.?.vt.modes.get(.reverse_colors)) { + var dynamic_bg = if (vt) |t| t.colorForXterm(.{ .dynamic = .background }) else null; + var dynamic_fg = if (vt) |t| t.colorForXterm(.{ .dynamic = .foreground }) else null; + if (vt != null and vt.?.modes.get(.reverse_colors)) { std.mem.swap(GColor.RGB, &theme_bg, &theme_fg); std.mem.swap(?GColor.RGB, &dynamic_bg, &dynamic_fg); } @@ -2280,6 +2284,18 @@ const FilteredColors = struct { return asPardesColor(self.keyedRgb(style.bg(cell, &self.source).?)); } + /// A +Pager span's colour (pager.zig), as `fg` and `bg` map a cell's. + pub fn spanColor(self: *FilteredColors, color: pardes.Color, is_bg: bool) pardes.Color { + return switch (color) { + .default => color, + .index => |idx| if (is_bg) self.bg_for_palette[idx] else self.fg_for_palette[idx], + .rgb => |rgb| blk: { + const keyed = self.keyedRgb(asGhostRgb(rgb)); + break :blk asPardesColor(if (is_bg) keyed else self.legible(keyed)); + }, + }; + } + fn legible(self: *const FilteredColors, rgb: GColor.RGB) GColor.RGB { if (contrastOf(luminanceOf(rgb), self.default_bg_luminance) >= config.tty_filter_min_contrast) return rgb; @@ -2317,7 +2333,7 @@ const FilteredColors = struct { self.cache_valid[slot] = true; return best; } -}; +} else struct {}; const channel_luminance: [256]f64 = blk: { @setEvalBranchQuota(20000); @@ -2570,7 +2586,7 @@ test "terminal Filter maps the default roles before it maps anything else" { // the null-page fallback that only the legacy dark theme exercises. for (0..9) |t| { p.settings.theme = @intCast(t); - const stage_one = FilteredColors.init(p, pane); + const stage_one = FilteredColors.init(p, &pane.terminal.?.vt); // `dark` declares no background of its own, which is exactly why the // resolver reads the tag colours as the fallback rather than `.?`. const theme = p.theme(); @@ -2584,7 +2600,7 @@ test "terminal Filter maps the default roles before it maps anything else" { p.settings.theme = 0; p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b]11;#5f5f5f\x1b\\" } }); - var moved = FilteredColors.init(p, pane); + var moved = FilteredColors.init(p, &pane.terminal.?.vt); try testing.expect(!moved.default_bg.eql(moved.theme_bg)); try testing.expect(moved.default_bg.eql(moved.keyedRgb(.{ .r = 0x5f, .g = 0x5f, .b = 0x5f }))); } @@ -2609,7 +2625,7 @@ test "terminal Filter refuses a foreground that would collapse onto the page" { for (0..9) |t| { p.settings.theme = @intCast(t); - var fc = FilteredColors.init(p, pane); + var fc = FilteredColors.init(p, &pane.terminal.?.vt); const page = asPardesColor(fc.default_bg); const rescued = asPardesColor(fc.fallback_fg); _ = frame.reset(.retain_capacity); @@ -2661,7 +2677,7 @@ test "terminal Filter holds every projected foreground off the page" { for (0..9) |t| { p.settings.theme = @intCast(t); - var fc = FilteredColors.init(p, pane); + var fc = FilteredColors.init(p, &pane.terminal.?.vt); var refused: usize = 0; for (fc.target, 0..) |projected, key| { const ink = fc.legible(projected); diff --git a/test/snapshots/diffview.golden b/test/snapshots/diffview.golden index 9e171fd8..868e5e85 100644 --- a/test/snapshots/diffview.golden +++ b/test/snapshots/diffview.golden @@ -1,7 +1,7 @@ == snap diff-pane grid=100x31 cursor=7,3 |Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol -| /tmp/pardes-snap/diffview/cwd/change.diff Save Tty Collapse Del +| /tmp/pardes-snap/diffview/cwd/change.diff Save Tty Diff Collapse Del | 1 diff --git a/src/shape.zig b/src/shape.zig | 2 index 1111111..2222222 100644 | 3 --- a/src/shape.zig @@ -55,7 +55,7 @@ |29: 0-0 d,#608269, 1-99 d,#0d1410, |30: 0-0 d,#608269, 1-99 d,#0d1410, == snap look-added-line grid=100x31 cursor=55,22 -|16: /tmp/pardes-snap/diffview/cwd/src/shape.zig Save Tty Collapse Del TreeContext +|16: /tmp/pardes-snap/diffview/cwd/src/shape.zig Save Tty Collapse Del TreeContext Def Refs |17: 1 const std = @import("std"); |18: 2 |19: 3 pub const Shape = union(enum) { @@ -134,7 +134,7 @@ |30: 0-0 d,#152019, 1-99 d,#0d1410, == snap command-look grid=100x31 cursor=23,10 |3: 1 cat change.diff -|5: /tmp/pardes-snap/diffview/cwd/src/shape.zig Save Tty Collapse Del TreeContext +|5: /tmp/pardes-snap/diffview/cwd/src/shape.zig Save Tty Collapse Del TreeContext Def Refs |6: 1 const std = @import("std"); |7: 2 |8: 3 pub const Shape = union(enum) { diff --git a/test/snapshots/lsp-client-edit.golden b/test/snapshots/lsp-client-edit.golden index c36d15be..c9d93379 100644 --- a/test/snapshots/lsp-client-edit.golden +++ b/test/snapshots/lsp-client-edit.golden @@ -1,7 +1,7 @@ == snap formatted grid=100x25 cursor=7,4 |Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol -| * /tmp/pardes-snap/lsp-client-edit/cwd/main.rs Save Tty Collapse Del TreeContext +| * /tmp/pardes-snap/lsp-client-edit/cwd/main.rs Save Tty Collapse Del TreeContext Def Refs | 1 // formatted by mock formatted 1 range(s) | 2 mod lib; | 3 @@ -12,7 +12,7 @@ | 8 } | 9 == snap unformatted grid=100x25 cursor=7,3 -|2: /tmp/pardes-snap/lsp-client-edit/cwd/main.rs Save Tty Collapse Del TreeContext +|2: /tmp/pardes-snap/lsp-client-edit/cwd/main.rs Save Tty Collapse Del TreeContext Def Refs |3: 1 mod lib; |4: 2 |5: 3 fn main() { @@ -23,12 +23,12 @@ |10: 8 |11: == snap renamed grid=100x25 cursor=12,5 -|2: * /tmp/pardes-snap/lsp-client-edit/cwd/main.rs Save Tty Collapse Del TreeContext +|2: * /tmp/pardes-snap/lsp-client-edit/cwd/main.rs Save Tty Collapse Del TreeContext Def Refs |3: 1 mod lib; renamed 2 range(s) |6: 4 let x = sum(1, 2); |7: 5 let y = sum(3, 4); == snap unrenamed grid=100x25 cursor=12,5 -|2: /tmp/pardes-snap/lsp-client-edit/cwd/main.rs Save Tty Collapse Del TreeContext +|2: /tmp/pardes-snap/lsp-client-edit/cwd/main.rs Save Tty Collapse Del TreeContext Def Refs |3: 1 mod lib; |6: 4 let x = add(1, 2); |7: 5 let y = add(3, 4); diff --git a/test/snapshots/lsp-client.golden b/test/snapshots/lsp-client.golden index 23d86e11..13771394 100644 --- a/test/snapshots/lsp-client.golden +++ b/test/snapshots/lsp-client.golden @@ -1,7 +1,7 @@ == snap gd-jumped grid=100x25 cursor=16,12 |Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol -| /tmp/pardes-snap/lsp-client/cwd/main.rs Save Tty Collapse Del TreeContext +| /tmp/pardes-snap/lsp-client/cwd/main.rs Save Tty Collapse Del TreeContext Def Refs | 1 mod lib; --:--:-- lsp rust-analyzer: ready | 2 | 3 fn main() { @@ -9,7 +9,7 @@ | 5 let y = add(3, 4); | 6 let _ = x + y; | 7 } -| /tmp/pardes-snap/lsp-client/cwd/lib.rs Save Tty Collapse Del TreeContext +| /tmp/pardes-snap/lsp-client/cwd/lib.rs Save Tty Collapse Del TreeContext Def Refs | 1 // mock fixture | 2 pub fn add(a: i32, b: i32) -> i32 { | 3 a + b diff --git a/test/snapshots/lsp-rename-files.golden b/test/snapshots/lsp-rename-files.golden index ea093dbf..4f71424e 100644 --- a/test/snapshots/lsp-rename-files.golden +++ b/test/snapshots/lsp-rename-files.golden @@ -1,12 +1,12 @@ == snap opened grid=100x25 cursor=7,8 |Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol -| /tmp/pardes-snap/lsp-rename-files/cwd/lib.rs Save Tty Collapse Del TreeContext +| /tmp/pardes-snap/lsp-rename-files/cwd/lib.rs Save Tty Collapse Del TreeContext Def Refs | 1 // main.rs | 2 pub fn add(a: i32, b: i32) -> i32 { | 3 a + b | 4 } -| /tmp/pardes-snap/lsp-rename-files/cwd/main.rs Save Tty Collapse Del TreeContext +| /tmp/pardes-snap/lsp-rename-files/cwd/main.rs Save Tty Collapse Del TreeContext Def Refs | 1 mod lib; | 2 | 3 fn main() { diff --git a/test/snapshots/lsp-rename.golden b/test/snapshots/lsp-rename.golden index ba19d8f0..6b85822c 100644 --- a/test/snapshots/lsp-rename.golden +++ b/test/snapshots/lsp-rename.golden @@ -1,7 +1,7 @@ == snap renamed grid=110x25 cursor=17,10 |Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol -| * /tmp/pardes-snap/lsp-rename/cwd/rename.zig Save Tty Collapse Del TreeContext +| * /tmp/pardes-snap/lsp-rename/cwd/rename.zig Save Tty Collapse Del TreeContext Def Refs | 1 const std = @import("std"); renamed 2 range(s) | 2 | 3 fn renamed_helper(x: u32) u32 { @@ -18,11 +18,11 @@ | 14 } | 15 == snap undone grid=110x25 cursor=17,10 -|2: /tmp/pardes-snap/lsp-rename/cwd/rename.zig Save Tty Collapse Del TreeContext +|2: /tmp/pardes-snap/lsp-rename/cwd/rename.zig Save Tty Collapse Del TreeContext Def Refs |3: 1 const std = @import("std"); |5: 3 fn helper(x: u32) u32 { |10: 8 _ = helper(41); == snap redone grid=110x25 cursor=17,10 -|2: * /tmp/pardes-snap/lsp-rename/cwd/rename.zig Save Tty Collapse Del TreeContext +|2: * /tmp/pardes-snap/lsp-rename/cwd/rename.zig Save Tty Collapse Del TreeContext Def Refs |5: 3 fn renamed_helper(x: u32) u32 { |10: 8 _ = renamed_helper(41); diff --git a/test/snapshots/lsp.golden b/test/snapshots/lsp.golden index 048d1ed3..2225de00 100644 --- a/test/snapshots/lsp.golden +++ b/test/snapshots/lsp.golden @@ -1,7 +1,7 @@ == snap opened grid=120x41 cursor=7,3 |Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol -| /tmp/pardes-snap/lsp/cwd/a.zig Save Tty Collapse Del TreeContext +| /tmp/pardes-snap/lsp/cwd/a.zig Save Tty Collapse Del TreeContext Def Refs | 1 const std = @import("std"); | 2 | 3 fn helper(x: u32) u32 { @@ -34,4 +34,4 @@ == snap step grid=120x41 cursor=15,3 |3: 1 const std = @import("std"); == snap nothing grid=120x41 cursor=7,5 -|3: 1 const std = @import("std"); definition: not found +|3: 1 const std = @import("std"); Def: not found diff --git a/test/snapshots/lspcomplete.golden b/test/snapshots/lspcomplete.golden index a56101e8..85c26e30 100644 --- a/test/snapshots/lspcomplete.golden +++ b/test/snapshots/lspcomplete.golden @@ -1,7 +1,7 @@ == snap opened grid=120x41 cursor=7,3 |Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol -| /tmp/pardes-snap/lspcomplete/cwd/a.zig Save Tty Collapse Del TreeContext +| /tmp/pardes-snap/lspcomplete/cwd/a.zig Save Tty Collapse Del TreeContext Def Refs | 1 const Shade = enum { | 2 verdigris, | 3 cinnabar, @@ -16,7 +16,7 @@ | 12 // note. see below | 13 == snap indent grid=120x41 cursor=11,12 -|2: ^* /tmp/pardes-snap/lspcomplete/cwd/a.zig Save Tty Collapse Del TreeContext +|2: ^* /tmp/pardes-snap/lspcomplete/cwd/a.zig Save Tty Collapse Del TreeContext Def Refs |12: 10 } == snap commentindent grid=120x41 cursor=19,14 |3: 1 const Shade = enum { --:--:-- lsp zls ready — /tmp/pardes-snap/lspcomplete/cwd @@ -31,7 +31,7 @@ |18: 3 == snap refill grid=120x41 cursor=16,10 == snap step grid=120x41 cursor=16,10 -|2: * /tmp/pardes-snap/lspcomplete/cwd/a.zig Save Tty Collapse Del TreeContext +|2: * /tmp/pardes-snap/lspcomplete/cwd/a.zig Save Tty Collapse Del TreeContext Def Refs == snap txtindent grid=120x41 cursor=15,3 |Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol @@ -41,7 +41,7 @@ == snap nosemi grid=100x19 cursor=29,9 |Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol -|^* /tmp/pardes-snap/lspcomplete/cwd/c.zig Save Tty Collapse Del TreeContext +|^* /tmp/pardes-snap/lspcomplete/cwd/c.zig Save Tty Collapse Del TreeContext Def Refs | 1 const Shade = enum { --:--:-- lsp zls ready — /tmp/pardes-snap/lspcomplete/cwd | 2 verdigris, | 3 cinnabar, @@ -57,7 +57,7 @@ == snap nobrace grid=100x19 cursor=16,10 |Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol -|^* /tmp/pardes-snap/lspcomplete/cwd/d.zig Save Tty Collapse Del TreeContext +|^* /tmp/pardes-snap/lspcomplete/cwd/d.zig Save Tty Collapse Del TreeContext Def Refs | 1 const Shade = enum { --:--:-- lsp zls ready — /tmp/pardes-snap/lspcomplete/cwd | 2 verdigris, | 3 cinnabar, diff --git a/test/snapshots/lspcompletemoved.golden b/test/snapshots/lspcompletemoved.golden index c83e3038..403c6931 100644 --- a/test/snapshots/lspcompletemoved.golden +++ b/test/snapshots/lspcompletemoved.golden @@ -1,7 +1,7 @@ == snap typedthrough grid=120x21 cursor=16,14 |Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol -|^* /tmp/pardes-snap/lspcompletemoved/cwd/a.zig Save Tty Collapse Del TreeContext +|^* /tmp/pardes-snap/lspcompletemoved/cwd/a.zig Save Tty Collapse Del TreeContext Def Refs | 1 const Shade = enum { --:--:-- lsp zls ready — /tmp/pardes-snap/lspcompletemoved/cwd | 2 verdigris, | 3 cinnabar, diff --git a/test/snapshots/lspdebug.golden b/test/snapshots/lspdebug.golden index 75fba98f..4beda019 100644 --- a/test/snapshots/lspdebug.golden +++ b/test/snapshots/lspdebug.golden @@ -1,7 +1,7 @@ == snap opened grid=120x45 cursor=7,3 |Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol -| /tmp/pardes-snap/lspdebug/cwd/z.zig Save Tty Collapse Del TreeContext +| /tmp/pardes-snap/lspdebug/cwd/z.zig Save Tty Collapse Del TreeContext Def Refs | 1 const std = @import("std"); | 2 | 3 fn helper() u32 { diff --git a/test/snapshots/lsprelpath.golden b/test/snapshots/lsprelpath.golden index b4022b1d..a3760316 100644 --- a/test/snapshots/lsprelpath.golden +++ b/test/snapshots/lsprelpath.golden @@ -1,7 +1,7 @@ == snap absrow grid=100x35 cursor=21,16 |Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol -| /tmp/pardes-snap/lsprelpath/cwd/sub/parent.zig Save Tty Collapse Del TreeContext +| /tmp/pardes-snap/lsprelpath/cwd/sub/parent.zig Save Tty Collapse Del TreeContext Def Refs | 1 const shade = @import("../shad --:--:-- lsp zls ready — /tmp/pardes-snap/lsprelpath/cwd/sub | 2 | 3 pub fn pick(s: shade.Shade) u8 { @@ -14,7 +14,7 @@ | 2 pub const Shade = enum { | 3 parent.zig:3:22-26 | 4 pub fn pick(s: shade.Shade) u8 { -| /tmp/pardes-snap/lsprelpath/cwd/shade.zig Save Tty Collapse Del TreeContext +| /tmp/pardes-snap/lsprelpath/cwd/shade.zig Save Tty Collapse Del TreeContext Def Refs | 1 pub const Shade = enum { | 2 verdigris, | 3 cinnabar, @@ -61,7 +61,7 @@ == snap subrow grid=100x35 cursor=20,16 |Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol -| /tmp/pardes-snap/lsprelpath/cwd/sub/subdir.zig Save Tty Collapse Del TreeContext +| /tmp/pardes-snap/lsprelpath/cwd/sub/subdir.zig Save Tty Collapse Del TreeContext Def Refs | 1 const tint = @import("inner/ti --:--:-- lsp zls ready — /tmp/pardes-snap/lsprelpath/cwd/sub | 2 | 3 pub fn hue(t: tint.Tint) u8 { @@ -74,7 +74,7 @@ | 2 pub const Tint = enum { | 3 subdir.zig:3:20-23 | 4 pub fn hue(t: tint.Tint) u8 { -| /tmp/pardes-snap/lsprelpath/cwd/sub/inner/tint.zig Save Tty Collapse Del TreeContext +| /tmp/pardes-snap/lsprelpath/cwd/sub/inner/tint.zig Save Tty Collapse Del TreeContext Def Refs | 1 pub const Tint = enum { | 2 ochre, | 3 indigo, diff --git a/test/snapshots/ninep.golden b/test/snapshots/ninep.golden index c6b5f0af..e524fa30 100644 --- a/test/snapshots/ninep.golden +++ b/test/snapshots/ninep.golden @@ -1,7 +1,7 @@ == snap opened grid=90x15 cursor=7,3 |Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol -| /tmp/pardes-snap/ninep/cwd/demo.zig Save Tty Collapse Del TreeContext +| /tmp/pardes-snap/ninep/cwd/demo.zig Save Tty Collapse Del TreeContext Def Refs | 1 const greeting = "café λ 界 é"; | 2 | 3 pub fn choose(ok: bool) u32 { @@ -30,8 +30,8 @@ @0: 0-74 #b2c3b8,#1d2824,,tagline 75-89 d,#1d2824,,tagline |1: New Tty Find Grep Joincol Delcol @1: 0-1 #ffffff,#887455,,tagline 2-2 d,#314738,,tagline 3-34 #becfc4,#314738,,tagline 35-89 d,#314738,,tagline -|2: /tmp/pardes-snap/ninep/cwd/demo.zig Save Tty Collapse Del TreeContext -@2: 0-1 #000000,#add38a,,tagline 2-2 d,#314738,,tagline 3-29 #becfc4,#314738,,tagline 30-37 #dfbce5,#314738,,tagline 38-71 #becfc4,#314738,,tagline 72-89 d,#314738,,tagline +|2: /tmp/pardes-snap/ninep/cwd/demo.zig Save Tty Collapse Del TreeContext Def Refs +@2: 0-1 #000000,#add38a,,tagline 2-2 d,#314738,,tagline 3-29 #becfc4,#314738,,tagline 30-37 #dfbce5,#314738,,tagline 38-80 #becfc4,#314738,,tagline 81-89 d,#314738,,tagline |3: 1 const greeting = "café λ 界 é"; +3: 28="é" 30="λ" 32="界" 33="" 35="é" @3: 0-0 d,#608269,,body 1-1 d,#0d1410,,body 2-6 #616f64,#0d1410,b,body 7-23 #e5eee5,#0d1410,,body 24-36 #b8d88a,#0d1410,,body 37-37 #e5eee5,#0d1410,,body 38-89 d,#0d1410,,body @@ -73,7 +73,7 @@ |7: 5 return 7; @7: 0-0 d,#608269,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-19 #e5eee5,#0d1410,,body 20-89 d,#0d1410,,body == snap edited-with-colors-off grid=90x15 cursor=7,4 -|2: * /tmp/pardes-snap/ninep/cwd/demo.zig Save Tty Collapse Del TreeContext +|2: * /tmp/pardes-snap/ninep/cwd/demo.zig Save Tty Collapse Del TreeContext Def Refs |3: 1 // café λ 界 |4: 2 const greeting = "café λ 界 é"; |5: 3 @@ -83,8 +83,8 @@ |9: 7 } |10: 8 == 9p edited-with-colors-off grid=90x15 cursor=7,4,block -|2: * /tmp/pardes-snap/ninep/cwd/demo.zig Save Tty Collapse Del TreeContext -@2: 0-0 #000000,#add38a,,tagline 1-1 #000000,#f9cb70,b,tagline 2-2 d,#314738,,tagline 3-29 #becfc4,#314738,,tagline 30-37 #dfbce5,#314738,,tagline 38-71 #becfc4,#314738,,tagline 72-89 d,#314738,,tagline +|2: * /tmp/pardes-snap/ninep/cwd/demo.zig Save Tty Collapse Del TreeContext Def Refs +@2: 0-0 #000000,#add38a,,tagline 1-1 #000000,#f9cb70,b,tagline 2-2 d,#314738,,tagline 3-29 #becfc4,#314738,,tagline 30-37 #dfbce5,#314738,,tagline 38-80 #becfc4,#314738,,tagline 81-89 d,#314738,,tagline |3: 1 // café λ 界 +3: 13="é" 15="λ" 17="界" 18="" @3: 0-0 d,#608269,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-18 #e5eee5,#0d1410,,body 19-89 d,#0d1410,,body @@ -152,8 +152,8 @@ @0: 0-74 #b2c3b8,#1d2824,,tagline 75-104 d,#1d2824,,tagline |1: New Tty Find Grep Joincol Delcol @1: 0-1 #ffffff,#887455,,tagline 2-2 d,#314738,,tagline 3-34 #becfc4,#314738,,tagline 35-104 d,#314738,,tagline -|2: * /tmp/pardes-snap/ninep/cwd/demo.zig Save Tty Collapse Del TreeContext -@2: 0-0 #000000,#add38a,,tagline 1-1 #000000,#f9cb70,b,tagline 2-2 d,#314738,,tagline 3-29 #becfc4,#314738,,tagline 30-37 #dfbce5,#314738,,tagline 38-71 #becfc4,#314738,,tagline 72-104 d,#314738,,tagline +|2: * /tmp/pardes-snap/ninep/cwd/demo.zig Save Tty Collapse Del TreeContext Def Refs +@2: 0-0 #000000,#add38a,,tagline 1-1 #000000,#f9cb70,b,tagline 2-2 d,#314738,,tagline 3-29 #becfc4,#314738,,tagline 30-37 #dfbce5,#314738,,tagline 38-80 #becfc4,#314738,,tagline 81-104 d,#314738,,tagline |3: 1 // café λ 界 Colors +3: 13="é" 15="λ" 17="界" 18="" @3: 0-0 d,#608269,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-18 #b9f480,#0d1410,,body 19-96 d,#0d1410,,body 97-97 d,#1d2824,,tagline 98-103 #b2c3b8,#1d2824,,tagline 104-104 d,#1d2824,,tagline @@ -193,7 +193,7 @@ == snap resized grid=105x20 cursor=7,4 |Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol -| * /tmp/pardes-snap/ninep/cwd/demo.zig Save Tty Collapse Del TreeContext +| * /tmp/pardes-snap/ninep/cwd/demo.zig Save Tty Collapse Del TreeContext Def Refs | 1 // café λ 界 Colors | 2 const greeting = "café λ 界 é"; | 3 diff --git a/test/snapshots/pagercolor.golden b/test/snapshots/pagercolor.golden index 811d3d96..abd264d1 100644 --- a/test/snapshots/pagercolor.golden +++ b/test/snapshots/pagercolor.golden @@ -41,9 +41,8 @@ | | | -| /tmp/pardes-snap/pagercolor/cwd/+Pager Save Tty Collapse Del -| 1 red bold green rgb ul NAME us plain -| 2 +| /tmp/pardes-snap/pagercolor/cwd/+Pager Save Tty Filter Collapse Del +| red bold green rgb ul NAME us plain == style pager-colours grid=100x50 |0: 0-99 #b2c3b8,#1d2824, |1: 0-1 d,#887455, 2-2 d,#314738, 3-99 #becfc4,#314738, @@ -88,8 +87,8 @@ |40: 0-0 d,#608269, 1-99 d,#0d1410, |41: 0-0 d,#608269, 1-99 d,#0d1410, |42: 0-1 d,#496656, 2-2 d,#1d2824, 3-34 #b2c3b8,#1d2824, 35-41 #d3b0d9,#1d2824, 42-99 #b2c3b8,#1d2824, -|43: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-10 #f1a39b,#0d1410, 11-20 #b6ce94,#0d1410,b 21-21 #b6ce94,#0d1410, 22-25 #c86400,#0d1410, 26-27 #e5eee5,#0d1410,u 28-28 #e5eee5,#0d1410, 29-32 #e5eee5,#0d1410,b 33-33 #e5eee5,#0d1410, 34-35 #e5eee5,#0d1410,u 36-99 #e5eee5,#0d1410, -|44: 0-0 d,#608269, 1-4 d,#0d1410, 5-99 #59675c,#0d1410, +|43: 0-0 d,#608269, 1-1 d,#0d1410, 2-5 #f1a39b,#0d1410, 6-15 #b6ce94,#0d1410,b 16-16 #b6ce94,#0d1410, 17-20 #c5917e,#0d1410, 21-22 #e5eee5,#0d1410,u 23-23 #e5eee5,#0d1410, 24-27 #e5eee5,#0d1410,b 28-28 #e5eee5,#0d1410, 29-30 #e5eee5,#0d1410,u 31-99 #e5eee5,#0d1410, +|44: 0-0 d,#608269, 1-99 d,#0d1410, |45: 0-0 d,#608269, 1-99 d,#0d1410, |46: 0-0 d,#608269, 1-99 d,#0d1410, |47: 0-0 d,#608269, 1-99 d,#0d1410, @@ -100,21 +99,19 @@ |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: $ -|43: 1 commit 0123abc -|44: 2 diff --git a/x b/x -|45: 3 --- a/x -|46: 4 +++ b/x -|47: 5 @@ -1 +1 @@ -|48: 6 -old -|49: 7 +new +|9: /tmp/pardes-snap/pagercolor/cwd/+Diff Save Tty Diff Collapse Del LocationsConfig +|10: commit 0123abc +|11: x:1 +|12: -old +|13: +new +|49: /tmp/pardes-snap/pagercolor/cwd/+Pager Save Tty Filter Diff Collapse Del == style pager-diff-colours grid=100x50 |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, -|43: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-99 #e9c680,#0d1410, -|44: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-24 #b9f480,#0d1410,b 25-99 #b9f480,#0d1410, -|45: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-13 #b9f480,#0d1410,b 14-99 #b9f480,#0d1410, -|46: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-13 #b9f480,#0d1410,b 14-99 #b9f480,#0d1410, -|47: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-99 #b6c59e,#0d1410, -|48: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-7 #f1a39b,#302b25,b 8-99 #f8c082,#302b25, -|49: 0-0 d,#152019, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-7 #b6ce94,#263025,b 8-99 #b8d88a,#263025, +|9: 0-1 d,#496656, 2-2 d,#1d2824, 3-34 #b2c3b8,#1d2824, 35-40 #d3b0d9,#1d2824, 41-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, +|13: 0-0 d,#608269, 1-1 d,#0d1410, 2-2 #b6ce94,#171f18,b 3-99 #b8d88a,#171f18, +|49: 0-1 d,#496656, 2-2 d,#1d2824, 3-34 #b2c3b8,#1d2824, 35-41 #d3b0d9,#1d2824, 42-99 #b2c3b8,#1d2824, diff --git a/test/snapshots/selregex.golden b/test/snapshots/selregex.golden index e3f3b2d7..480ad8a2 100644 --- a/test/snapshots/selregex.golden +++ b/test/snapshots/selregex.golden @@ -1,7 +1,7 @@ == snap prompt-armed grid=160x25 cursor=159,3 |Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol -| /tmp/pardes-snap/selregex/cwd/m.zig Save Tty Collapse Del TreeContext +| /tmp/pardes-snap/selregex/cwd/m.zig Save Tty Collapse Del TreeContext Def Refs | 1 const one = 1; Select / | 2 const two = 2; | 3 const three = 3; @@ -51,12 +51,12 @@ |4: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-10 #f5f7ee,#243a2d, 11-11 #3c614a,#f5f7ee, 12-12 #3c614a,#0d1410, 13-18 #e5eee5,#0d1410, 19-19 #f8c082,#0d1410, 20-159 #e5eee5,#0d1410, |5: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-10 #f5f7ee,#243a2d, 11-11 #3c614a,#f5f7ee, 12-12 #3c614a,#0d1410, 13-20 #e5eee5,#0d1410, 21-21 #f8c082,#0d1410, 22-159 #e5eee5,#0d1410, == snap commented grid=160x25 cursor=14,3 -|2: * /tmp/pardes-snap/selregex/cwd/m.zig Save Tty Collapse Del TreeContext +|2: * /tmp/pardes-snap/selregex/cwd/m.zig Save Tty Collapse Del TreeContext Def Refs |3: 1 // const one = 1; |4: 2 // const two = 2; |5: 3 // const three = 3; == snap uncommented grid=160x25 cursor=11,3 -|2: /tmp/pardes-snap/selregex/cwd/m.zig Save Tty Collapse Del TreeContext +|2: /tmp/pardes-snap/selregex/cwd/m.zig Save Tty Collapse Del TreeContext Def Refs |3: 1 const one = 1; |4: 2 const two = 2; |5: 3 const three = 3; diff --git a/test/snapshots/syntax.golden b/test/snapshots/syntax.golden index 2f7a6b74..43bfe485 100644 --- a/test/snapshots/syntax.golden +++ b/test/snapshots/syntax.golden @@ -1,11 +1,12 @@ -== snap zig-open grid=150x31 cursor=7,7 +== snap zig-open grid=150x31 cursor=7,8 |Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/syntax/cwd Tty+bash Save Mode Filter Collapse Del /tmp/pardes-snap/syntax/cwd Tty+bash Save Mode Filter Collapse Del | ls ls | demo.zig demo.zig | -| /tmp/pardes-snap/syntax/cwd/demo.zig Save Tty Collapse Del TreeContext +| /tmp/pardes-snap/syntax/cwd/demo.zig Save Tty Collapse Del TreeContext D +| ef Refs | 1 const std = @import("std"); // greet | 2 pub fn main() void { | 3 var x: u32 = 42; @@ -15,7 +16,6 @@ | | | -| | /tmp/pardes-snap/syntax/cwd Tty+bash Save Mode Filter Collapse Del | ls | demo.zig @@ -27,12 +27,12 @@ |4: 0-0 d,#608269, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 #e5eee5,#608269, 76-149 #e5eee5,#0d1410, |5: 0-0 d,#608269, 1-74 d,#0d1410, 75-75 d,#608269, 76-149 d,#0d1410, |6: 0-1 d,#add38a, 2-2 d,#314738, 3-30 #becfc4,#314738, 31-39 #dfbce5,#314738, 40-74 #becfc4,#314738, 75-75 #becfc4,#608269, 76-149 #becfc4,#0d1410, -|7: 0-0 d,#608269, 1-1 d,#0d1410, 2-4 d,#0d1410,b 5-6 #616f64,#0d1410,b 7-18 #e5eee5,#0d1410, 19-25 #c9a7ed,#0d1410, 26-26 #e5eee5,#0d1410, 27-31 #b8d88a,#0d1410, 32-34 #e5eee5,#0d1410, 35-74 #b9f480,#0d1410, 75-75 #b9f480,#608269, 76-149 #b9f480,#0d1410, -|8: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-10 #e5eee5,#0d1410, 11-13 #c9a7ed,#0d1410, 14-74 #e5eee5,#0d1410, 75-75 #e5eee5,#608269, 76-149 #e5eee5,#0d1410, -|9: 0-0 d,#608269, 1-4 d,#0d1410, 5-10 #59675c,#0d1410, 11-23 #e5eee5,#0d1410, 24-25 #f8c082,#0d1410, 26-74 #e5eee5,#0d1410, 75-75 #e5eee5,#608269, 76-149 #e5eee5,#0d1410, -|10: 0-0 d,#608269, 1-4 d,#0d1410, 5-10 #59675c,#0d1410, 11-74 #e5eee5,#0d1410, 75-75 #e5eee5,#608269, 76-149 #e5eee5,#0d1410, -|11: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-74 #e5eee5,#0d1410, 75-75 #e5eee5,#608269, 76-149 #e5eee5,#0d1410, -|12: 0-0 d,#608269, 1-74 d,#0d1410, 75-75 d,#608269, 76-149 d,#0d1410, +|7: 0-2 d,#314738, 3-74 #becfc4,#314738, 75-75 #becfc4,#608269, 76-149 #becfc4,#0d1410, +|8: 0-0 d,#608269, 1-1 d,#0d1410, 2-4 d,#0d1410,b 5-6 #616f64,#0d1410,b 7-18 #e5eee5,#0d1410, 19-25 #c9a7ed,#0d1410, 26-26 #e5eee5,#0d1410, 27-31 #b8d88a,#0d1410, 32-34 #e5eee5,#0d1410, 35-74 #b9f480,#0d1410, 75-75 #b9f480,#608269, 76-149 #b9f480,#0d1410, +|9: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-10 #e5eee5,#0d1410, 11-13 #c9a7ed,#0d1410, 14-74 #e5eee5,#0d1410, 75-75 #e5eee5,#608269, 76-149 #e5eee5,#0d1410, +|10: 0-0 d,#608269, 1-4 d,#0d1410, 5-10 #59675c,#0d1410, 11-23 #e5eee5,#0d1410, 24-25 #f8c082,#0d1410, 26-74 #e5eee5,#0d1410, 75-75 #e5eee5,#608269, 76-149 #e5eee5,#0d1410, +|11: 0-0 d,#608269, 1-4 d,#0d1410, 5-10 #59675c,#0d1410, 11-74 #e5eee5,#0d1410, 75-75 #e5eee5,#608269, 76-149 #e5eee5,#0d1410, +|12: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-74 #e5eee5,#0d1410, 75-75 #e5eee5,#608269, 76-149 #e5eee5,#0d1410, |13: 0-0 d,#608269, 1-74 d,#0d1410, 75-75 d,#608269, 76-149 d,#0d1410, |14: 0-0 d,#608269, 1-74 d,#0d1410, 75-75 d,#608269, 76-149 d,#0d1410, |15: 0-0 d,#608269, 1-74 d,#0d1410, 75-75 d,#608269, 76-149 d,#0d1410, @@ -52,10 +52,10 @@ |29: 0-0 d,#608269, 1-74 d,#0d1410, 75-75 d,#608269, 76-149 d,#0d1410, |30: 0-0 d,#608269, 1-74 d,#0d1410, 75-75 d,#608269, 76-149 d,#0d1410, == style colors-off grid=150x31 -|7: 0-0 d,#608269, 1-1 d,#0d1410, 2-4 d,#0d1410,b 5-6 #616f64,#0d1410,b 7-66 #e5eee5,#0d1410, 67-67 #e5eee5,#1d2824, 68-74 #b2c3b8,#1d2824, 75-75 #b2c3b8,#608269, 76-149 #b2c3b8,#0d1410, -|8: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-74 #e5eee5,#0d1410, 75-75 #e5eee5,#608269, 76-149 #e5eee5,#0d1410, -|9: 0-0 d,#608269, 1-4 d,#0d1410, 5-10 #59675c,#0d1410, 11-74 #e5eee5,#0d1410, 75-75 #e5eee5,#608269, 76-149 #e5eee5,#0d1410, +|8: 0-0 d,#608269, 1-1 d,#0d1410, 2-4 d,#0d1410,b 5-6 #616f64,#0d1410,b 7-66 #e5eee5,#0d1410, 67-67 #e5eee5,#1d2824, 68-74 #b2c3b8,#1d2824, 75-75 #b2c3b8,#608269, 76-149 #b2c3b8,#0d1410, +|9: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-74 #e5eee5,#0d1410, 75-75 #e5eee5,#608269, 76-149 #e5eee5,#0d1410, +|10: 0-0 d,#608269, 1-4 d,#0d1410, 5-10 #59675c,#0d1410, 11-74 #e5eee5,#0d1410, 75-75 #e5eee5,#608269, 76-149 #e5eee5,#0d1410, == style colors-on grid=150x31 -|7: 0-0 d,#608269, 1-1 d,#0d1410, 2-4 d,#0d1410,b 5-6 #616f64,#0d1410,b 7-18 #e5eee5,#0d1410, 19-25 #c9a7ed,#0d1410, 26-26 #e5eee5,#0d1410, 27-31 #b8d88a,#0d1410, 32-34 #e5eee5,#0d1410, 35-66 #b9f480,#0d1410, 67-67 #b9f480,#1d2824, 68-74 #b2c3b8,#1d2824, 75-75 #b2c3b8,#608269, 76-149 #b2c3b8,#0d1410, -|8: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-10 #e5eee5,#0d1410, 11-13 #c9a7ed,#0d1410, 14-74 #e5eee5,#0d1410, 75-75 #e5eee5,#608269, 76-149 #e5eee5,#0d1410, -|9: 0-0 d,#608269, 1-4 d,#0d1410, 5-10 #59675c,#0d1410, 11-23 #e5eee5,#0d1410, 24-25 #f8c082,#0d1410, 26-74 #e5eee5,#0d1410, 75-75 #e5eee5,#608269, 76-149 #e5eee5,#0d1410, +|8: 0-0 d,#608269, 1-1 d,#0d1410, 2-4 d,#0d1410,b 5-6 #616f64,#0d1410,b 7-18 #e5eee5,#0d1410, 19-25 #c9a7ed,#0d1410, 26-26 #e5eee5,#0d1410, 27-31 #b8d88a,#0d1410, 32-34 #e5eee5,#0d1410, 35-66 #b9f480,#0d1410, 67-67 #b9f480,#1d2824, 68-74 #b2c3b8,#1d2824, 75-75 #b2c3b8,#608269, 76-149 #b2c3b8,#0d1410, +|9: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-10 #e5eee5,#0d1410, 11-13 #c9a7ed,#0d1410, 14-74 #e5eee5,#0d1410, 75-75 #e5eee5,#608269, 76-149 #e5eee5,#0d1410, +|10: 0-0 d,#608269, 1-4 d,#0d1410, 5-10 #59675c,#0d1410, 11-23 #e5eee5,#0d1410, 24-25 #f8c082,#0d1410, 26-74 #e5eee5,#0d1410, 75-75 #e5eee5,#608269, 76-149 #e5eee5,#0d1410, -- cgit v1.3 From bc3d18d27f9fc1155db7fac3946c4d38774f9e65 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Wed, 21 Oct 2026 14:35:15 -0300 Subject: Build with Zig 0.17 ghostty, libvaxis and uucode move to ghostty's 0.17 pins, cloud9 to its 0.17 main, SDL to castholm's release-3.4.x (3.4.18), zstbi and tree-sitter to forks with 0.17 build files (see build.zig.zon). A bare zig build copies the binaries into ~/.local/bin (-Dhome-install=false leaves it out): 0.17 keeps the prefix from build scripts. A terminal's edited copy goes when the program clears the screen. tinywin.snap is gone; perf baselines are re-recorded. Co-Authored-By: Claude Opus 5.5 --- README.md | 2 +- build.zig | 289 +++++++++++++++----------------- build.zig.zon | 45 ++--- build/snap.zig | 6 +- docs/typ/building.typ | 12 +- docs/typ/install.typ | 2 +- mupdf.zig | 6 +- src/9p_io.zig | 14 +- src/CHANGELOG.md | 8 + src/Layer.zig | 4 +- src/Messages.zig | 14 +- src/TerminalImages.zig | 82 ++++++++- src/builtins.zig | 26 +-- src/colors.zig | 70 ++++---- src/config.zig | 21 ++- src/detached/client.zig | 8 +- src/detached/wire.zig | 39 +++-- src/draw.zig | 22 +-- src/dump.zig | 24 +-- src/esp32p4.zig | 2 +- src/esp32p4/input_rescue.zig | 2 +- src/esp32p4/selftest.zig | 2 +- src/fs.zig | 8 +- src/gui/Post.zig | 14 +- src/gui/gui.zig | 20 +-- src/host_io.zig | 14 +- src/image.zig | 6 +- src/linux/v9fs.zig | 4 +- src/locations.zig | 24 +-- src/look.zig | 6 +- src/lsp/lsp.zig | 2 +- src/lsp/lsp_client.zig | 2 +- src/macos.zig | 26 +-- src/main.zig | 6 + src/memory.zig | 2 +- src/modal.zig | 2 +- src/ninep/addr.zig | 2 +- src/ninep/cols.zig | 10 +- src/ninep/ctl.zig | 14 +- src/ninep/events.zig | 10 +- src/ninep/pane.zig | 11 +- src/ninep/pty.zig | 6 +- src/ninep/screen.zig | 2 +- src/ninep/tree.zig | 16 +- src/normal.zig | 2 +- src/pager.zig | 2 +- src/panes.zig | 2 +- src/pardes.zig | 32 ++-- src/pdf.zig | 10 +- src/regexp.zig | 12 +- src/sam_edit.zig | 2 +- src/syntax.zig | 2 +- src/terminal.zig | 30 +++- src/tty/tty.zig | 22 +-- test/deck/replay.zig | 5 +- test/deck/schema.zig | 10 +- test/e2e_harness.zig | 2 +- test/fs_bench.zig | 4 +- test/history.zig | 10 +- test/hxdiff.zig | 14 +- test/image_harness.zig | 2 +- test/lspbench.zig | 2 +- test/monkey.zig | 2 +- test/panes.zig | 50 +++--- test/pdf.zig | 8 +- test/pdf_scroll_bench.zig | 2 +- test/pdf_sections_bench.zig | 2 +- test/perf-baseline-gui-Debug.json | 1 - test/perf-baseline-gui-debug.json | 1 + test/perf-baseline-tty-Debug.json | 1 - test/perf-baseline-tty-ReleaseFast.json | 1 - test/perf-baseline-tty-debug.json | 1 + test/perf-baseline-tty-fast.json | 1 + test/perf.zig | 15 +- test/snapshot.zig | 40 ++--- test/snapshots/exec.golden | 8 +- test/snapshots/tinywin.golden | 83 --------- test/snapshots/tinywin.snap | 31 ---- test/unit_profile_test.zig | 7 +- tools/gen_themes.zig | 15 +- 80 files changed, 664 insertions(+), 677 deletions(-) delete mode 100644 test/perf-baseline-gui-Debug.json create mode 100644 test/perf-baseline-gui-debug.json delete mode 100644 test/perf-baseline-tty-Debug.json delete mode 100644 test/perf-baseline-tty-ReleaseFast.json create mode 100644 test/perf-baseline-tty-debug.json create mode 100644 test/perf-baseline-tty-fast.json delete mode 100644 test/snapshots/tinywin.golden delete mode 100644 test/snapshots/tinywin.snap (limited to 'src/main.zig') diff --git a/README.md b/README.md index 3a566d2a..0a03bdba 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,7 @@ looks; the keys are helix's; every session is a virtual filesystem, served over 9P, that any program can drive. Get the source with `git clone https://git.sr.ht/~gbrls/pardes && cd pardes` -(also at https://git.0x4200.cafe/pardes). Install with Zig 0.16: +(also at https://git.0x4200.cafe/pardes). Install with Zig 0.17: `zig build -Dplatform=tty --prefix ~/.local` for `pardes` in a terminal, or `-Dplatform=gui` for the `pardes-gui` window. The terminal should report the mouse; Shift-Esc needs the kitty keyboard diff --git a/build.zig b/build.zig index 0246d55f..ddd41a03 100644 --- a/build.zig +++ b/build.zig @@ -59,13 +59,14 @@ pub fn build(b: *std.Build) void { const requested_platform = b.option(Platform, "platform", "which shell to build (tty, gui, web, macos, esp32p4); absent builds the tty cli and the SDL gui together"); const platform = requested_platform orelse .tty; const also_gui = requested_platform == null; - const home_install = also_gui and prefixIsUntouched(b); - if (home_install) { - if (b.graph.environ_map.get("HOME")) |home| { - b.resolveInstallPrefix(b.pathJoin(&.{ home, ".local" }), .{}); - std.debug.print("pardes: installing into {s} (override with --prefix)\n", .{b.install_prefix}); - } - } + // 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)) + if (b.graph.environ_map.get("HOME")) |home| b.pathJoin(&.{ home, ".local", "bin" }) else null + else + null; + const home_install = home_bin != null; const esp32p4_target: std.Target.Query = .{ .cpu_arch = .riscv32, .os_tag = .freestanding, @@ -114,18 +115,18 @@ pub fn build(b: *std.Build) void { const is_web_target = target.result.cpu.arch == .wasm32 and target.result.os.tag == .freestanding; const is_esp32p4_target = target.result.cpu.arch == .riscv32 and target.result.os.tag == .freestanding; const optimize = if (is_web) - .ReleaseSmall - else if (is_esp32p4_target and requested_optimize == .Debug) - .ReleaseFast + .small + else if (is_esp32p4_target and requested_optimize == .debug) + .fast else requested_optimize; const test_build = b.step("test-build", "compile unit-test programs without running them"); const doc_typ_opts = b.addOptions(); - doc_typ_opts.addOption([]const u8, "dir", b.pathFromRoot("docs/typ")); + doc_typ_opts.addOptionPathUntracked("dir", b.path("docs/typ")); // The docs (docs/typ, docs/site): each output is one typst run, and each // reads docs/typ/builtins-*.json; `builtins-json` refreshes this build's from the // registry first (the tool is wired below, once the core module is). - const typst_bin: ?[]const u8 = b.findProgram(&.{"typst"}, &.{}) catch null; + const typst_bin: ?[]const u8 = b.findProgram(.{ .names = &.{"typst"} }); var doc_renders: [3]?*std.Build.Step.Run = @splat(null); const cheatsheet_step = b.step("cheatsheet", "render docs/typ/cheatsheet-a4.typ to /share/doc/pardes/cheatsheet.pdf (needs typst)"); const book_step = b.step("book", "render docs/typ/book.typ to /share/doc/pardes/pardes.pdf (needs typst)"); @@ -139,11 +140,13 @@ pub fn build(b: *std.Build) void { sheet.addFileArg(b.path("docs/typ/cheatsheet-a4.typ")); sheet.has_side_effects = true; cheatsheet_step.dependOn(&b.addInstallFile(sheet.addOutputFileArg("cheatsheet.pdf"), "share/doc/pardes/cheatsheet.pdf").step); - const book = b.addSystemCommand(&.{ typst, "compile", "--ignore-system-fonts", "--root", b.pathFromRoot(".") }); + const book = b.addSystemCommand(&.{ typst, "compile", "--ignore-system-fonts", "--root", "." }); + book.setCwd(b.path(".")); book.addFileArg(b.path("docs/typ/book.typ")); book.has_side_effects = true; book_step.dependOn(&b.addInstallFile(book.addOutputFileArg("pardes.pdf"), "share/doc/pardes/pardes.pdf").step); - const site = b.addSystemCommand(&.{ typst, "compile", "--format", "bundle", "--features", "bundle,html", "--root", b.pathFromRoot(".") }); + const site = b.addSystemCommand(&.{ typst, "compile", "--format", "bundle", "--features", "bundle,html", "--root", "." }); + site.setCwd(b.path(".")); site.addFileArg(b.path("docs/site/site.typ")); const site_dir = site.addOutputDirectoryArg("site"); site.has_side_effects = true; @@ -168,7 +171,7 @@ pub fn build(b: *std.Build) void { .root_source_file = b.path("test/unit_profile.zig"), }), }); - const c_optimize: std.builtin.OptimizeMode = if (optimize == .Debug) .ReleaseFast else optimize; + const c_optimize: std.lang.Optimize = if (optimize == .debug) .fast else optimize; const default_grammars: TreeSitterGrammars = if (is_web) .zig else if (is_esp32p4) .disabled else .full; const requested_grammars = b.option(TreeSitterGrammars, "tree-sitter", "tree-sitter grammar set: disabled, zig, minimal (c/c++/zig), full"); const tree_sitter_grammars = requested_grammars orelse default_grammars; @@ -321,7 +324,7 @@ pub fn build(b: *std.Build) void { .name = "pardes-gen-themes", .root_module = b.createModule(.{ .target = b.graph.host, - .optimize = .Debug, + .optimize = .debug, .root_source_file = b.path("tools/gen_themes.zig"), }), }); @@ -353,7 +356,7 @@ pub fn build(b: *std.Build) void { // `pardes ` alone, like a tarball build; -Dstamp-commit=true // stamps one anyway. const stamp_commit = b.option(bool, "stamp-commit", "embed the git commit in --version and crash records (default: release builds and the ~/.local install)") orelse - (optimize != .Debug or home_install); + (optimize != .debug or home_install); const shell_cfg: ShellConfig = .{ .tree_sitter_grammars = tree_sitter_grammars, .tracy = tracy != null, @@ -391,9 +394,7 @@ pub fn build(b: *std.Build) void { if (tree_sitter_grammars != .disabled) { const tree_sitter_mod = b.dependency("tree_sitter", .{ .target = target, .optimize = c_optimize }).module("tree_sitter"); if (is_web) { - const web_libc_include: std.Build.LazyPath = .{ - .cwd_relative = b.path("src/web/libc/include").getPath(b), - }; + const web_libc_include = b.path("src/web/libc/include"); for (tree_sitter_mod.link_objects.items) |link_object| switch (link_object) { .other_step => |lib| { lib.root_module.link_libc = false; @@ -417,12 +418,11 @@ pub fn build(b: *std.Build) void { (tree_sitter_grammars == .zig and g.tier == .zig)) { const dep = b.dependency(g.dep, .{}); - const query_path = dep.path(g.query); - const query = std.Io.Dir.cwd().readFileAlloc(io, query_path.getPath(b), b.allocator, .limited(0x100000)) catch @panic("read " ++ g.name ++ " highlights"); + const query = configureRead(b, io, dep.builder.root, g.query, 0x100000) catch @panic("read " ++ g.name ++ " highlights"); ts_queries.addOption([]const u8, g.name ++ "_highlights", query); // helix's textobject queries, vendored (vendor/queries); a // grammar without one gets none - const objects = std.Io.Dir.cwd().readFileAlloc(io, b.pathFromRoot("vendor/queries/" ++ g.name ++ "/textobjects.scm"), b.allocator, .limited(0x100000)) catch ""; + const objects = configureRead(b, io, b.root, "vendor/queries/" ++ g.name ++ "/textobjects.scm", 0x100000) catch ""; ts_queries.addOption([]const u8, g.name ++ "_textobjects", objects); const lib = b.addLibrary(.{ @@ -438,8 +438,9 @@ pub fn build(b: *std.Build) void { const ts_cflags = [_][]const u8{ "-fno-sanitize=function", "-DTREE_SITTER_REUSE_ALLOCATOR", + // Relative to the build root, the compiler's working directory. "-include", - b.path("src/tree_sitter_heap.h").getPath(b), + "src/tree_sitter_heap.h", }; lib.root_module.addCSourceFile(.{ .file = dep.path(g.src ++ "/parser.c"), .flags = &ts_cflags }); if (g.scanner) lib.root_module.addCSourceFile(.{ .file = dep.path(g.src ++ "/scanner.c"), .flags = &ts_cflags }); @@ -467,7 +468,7 @@ pub fn build(b: *std.Build) void { // (src/regexp.zig). A bump that moves the anchor stops the build. const mvzr_mod = mvzr: { const dep = b.dependency("mvzr", .{ .target = target, .optimize = optimize }); - const src = std.Io.Dir.cwd().readFileAlloc(io, dep.path("src/mvzr.zig").getPath(b), b.allocator, .limited(1 << 20)) catch @panic("read mvzr"); + const src = configureRead(b, io, dep.builder.root, "src/mvzr.zig", 1 << 20) catch @panic("read mvzr"); const anchor = "fn matchPattern(patt: []const RegOp, sets: []const CharSet, haystack: []const u8, i_in: usize) ?OpMatch {\n"; const at = (std.mem.indexOf(u8, src, anchor) orelse @panic("mvzr's matchPattern changed: redo its step budget in build.zig")) + anchor.len; const spend = @@ -536,7 +537,17 @@ pub fn build(b: *std.Build) void { \\ ; if (std.mem.count(u8, backed, end_anchor) != 1) @panic("mvzr's parser changed: redo its `$` before `|` in build.zig"); - const patched = std.mem.replaceOwned(u8, b.allocator, backed, end_anchor, end_before_alt) catch @panic("OOM"); + var patched = std.mem.replaceOwned(u8, b.allocator, backed, end_anchor, end_before_alt) catch @panic("OOM"); + // Zig 0.17 removed `**`; mvzr still has it (its PR #16 replaces it upstream). + for ([_][3][]const u8{ + .{ "[1]RegOp{.{ .unused = {} }} ** ops", "@splat(.{ .unused = {} })", "1" }, + .{ "[1]CharSet{.{ .low = 0, .hi = 0 }} ** char_sets", "@splat(.{ .low = 0, .hi = 0 })", "1" }, + .{ "\"a\" ** 2048", "&@as([2048]u8, @splat('a'))", "2" }, + .{ "\"12345,\" ** 255", "std.mem.asBytes(&@as([255][6]u8, @splat(\"12345,\".*)))", "1" }, + }) |edit| { + if (std.mem.count(u8, patched, edit[0]) != std.fmt.parseInt(usize, edit[2], 10) catch unreachable) std.debug.panic("mvzr changed at `{s}`: redo its `**` patch in build.zig", .{edit[0]}); + patched = std.mem.replaceOwned(u8, b.allocator, patched, edit[0], edit[1]) catch @panic("OOM"); + } break :mvzr b.createModule(.{ .root_source_file = b.addWriteFiles().add("mvzr.zig", patched), .target = target, .optimize = optimize }); }; @@ -582,6 +593,7 @@ pub fn build(b: *std.Build) void { }); mupdf.linkTo(mupdf_mod); mupdf_mod.addImport("c_heap", c_heap_mod); + mupdf_mod.addImport("pdf_c", b.addTranslateC(.{ .root_source_file = b.path("src/pdf_bridge.h"), .target = target, .optimize = optimize }).createModule()); mupdf_mod.addIncludePath(b.path("src")); mupdf_mod.addCSourceFile(.{ .file = b.path("src/pdf_bridge.c"), @@ -599,12 +611,13 @@ pub fn build(b: *std.Build) void { const pdf_bench_mod = b.createModule(.{ .target = target, - .optimize = .ReleaseFast, + .optimize = .fast, .root_source_file = b.path("src/pdf.zig"), .link_libc = true, }); mupdf.linkTo(pdf_bench_mod); pdf_bench_mod.addImport("c_heap", c_heap_mod); + pdf_bench_mod.addImport("pdf_c", b.addTranslateC(.{ .root_source_file = b.path("src/pdf_bridge.h"), .target = target, .optimize = .fast }).createModule()); pdf_bench_mod.addIncludePath(b.path("src")); pdf_bench_mod.addCSourceFile(.{ .file = b.path("src/pdf_bridge.c"), @@ -614,14 +627,14 @@ pub fn build(b: *std.Build) void { .name = "pardes-pdf-bench", .root_module = b.createModule(.{ .target = target, - .optimize = .ReleaseFast, + .optimize = .fast, .root_source_file = b.path("test/pdf_bench.zig"), .link_libc = true, }), }); pdf_bench.root_module.addImport("mupdf", pdf_bench_mod); const run_pdf_bench = b.addRunArtifact(pdf_bench); - if (b.args) |args| run_pdf_bench.addArgs(args); + run_pdf_bench.addPassthruArgs(); run_pdf_bench.setCwd(b.path(".")); pdf_bench_step.dependOn(&run_pdf_bench.step); @@ -629,7 +642,7 @@ pub fn build(b: *std.Build) void { .name = "pardes-pdf-sections-bench", .root_module = b.createModule(.{ .target = target, - .optimize = .ReleaseFast, + .optimize = .fast, .root_source_file = b.path("test/pdf_sections_bench.zig"), .link_libc = true, }), @@ -637,10 +650,10 @@ pub fn build(b: *std.Build) void { pdf_sections_bench.root_module.addImport("pardes", core_module); pdf_sections_bench.root_module.addImport("mupdf", mupdf_mod); const sections_bench_opts = b.addOptions(); - sections_bench_opts.addOption(bool, "release_fast_core", optimize == .ReleaseFast); + sections_bench_opts.addOption(bool, "release_fast_core", optimize == .fast); pdf_sections_bench.root_module.addOptions("pdf_sections_bench_config", sections_bench_opts); const run_pdf_sections_bench = b.addRunArtifact(pdf_sections_bench); - if (b.args) |args| run_pdf_sections_bench.addArgs(args); + run_pdf_sections_bench.addPassthruArgs(); run_pdf_sections_bench.setCwd(b.path(".")); pdf_sections_bench_step.dependOn(&run_pdf_sections_bench.step); @@ -648,7 +661,7 @@ pub fn build(b: *std.Build) void { .name = "pardes-pdf-pointer-bench", .root_module = b.createModule(.{ .target = target, - .optimize = .ReleaseFast, + .optimize = .fast, .root_source_file = b.path("test/pdf_pointer_bench.zig"), .link_libc = true, }), @@ -656,7 +669,7 @@ pub fn build(b: *std.Build) void { pdf_pointer_bench.root_module.addImport("pardes", core_module); pdf_pointer_bench.root_module.addImport("mupdf", mupdf_mod); const run_pdf_pointer_bench = b.addRunArtifact(pdf_pointer_bench); - if (b.args) |args| run_pdf_pointer_bench.addArgs(args); + run_pdf_pointer_bench.addPassthruArgs(); run_pdf_pointer_bench.setCwd(b.path(".")); pdf_pointer_bench_step.dependOn(&run_pdf_pointer_bench.step); @@ -672,11 +685,11 @@ pub fn build(b: *std.Build) void { pdf_scroll_bench.root_module.addImport("pardes", core_module); pdf_scroll_bench.root_module.addImport("mupdf", mupdf_mod); const scroll_bench_opts = b.addOptions(); - scroll_bench_opts.addOption(bool, "release_fast_core", optimize == .ReleaseFast); + scroll_bench_opts.addOption(bool, "release_fast_core", optimize == .fast); scroll_bench_opts.addOption([]const u8, "core_optimize", @tagName(optimize)); pdf_scroll_bench.root_module.addOptions("pdf_scroll_bench_config", scroll_bench_opts); const run_pdf_scroll_bench = b.addRunArtifact(pdf_scroll_bench); - if (b.args) |args| run_pdf_scroll_bench.addArgs(args); + run_pdf_scroll_bench.addPassthruArgs(); run_pdf_scroll_bench.setCwd(b.path(".")); pdf_scroll_bench_step.dependOn(&run_pdf_scroll_bench.step); } @@ -712,15 +725,13 @@ pub fn build(b: *std.Build) void { // - An X10 mouse report and a kitty graphics reply cut short by a read // wait for their rest: the first became three bytes of text, the // second sliced past its input. - // - A malformed color or clipboard reply is dropped instead of failing - // the parse, which stopped input; so is a byte no UTF-8 starts with. - // - An OSC reply ends at its first terminator: one ended by BEL ran on to - // the next sequence's ESC and left what lay between as text. + // - A byte no UTF-8 starts with is dropped instead of failing the parse, + // which stopped input. (vaxis itself now drops a malformed color or + // clipboard reply and ends an OSC at its first terminator.) // - A device report's fields are sought in the sequence, not past it. // A bump that moves an anchor stops the build. { - const parser_path = vaxis_dep.path("src/Parser.zig").getPath(b); - var src = std.Io.Dir.cwd().readFileAlloc(io, parser_path, b.allocator, .limited(1 << 20)) catch @panic("read vaxis Parser.zig"); + var src = configureRead(b, io, vaxis_dep.builder.root, "src/Parser.zig", 1 << 20) catch @panic("read vaxis Parser.zig"); const edits = [_]struct { anchor: []const u8, with: []const u8, count: usize = 1 }{ .{ .anchor = @@ -731,7 +742,7 @@ pub fn build(b: *std.Build) void { \\ 0x5F => return parseApc(input), \\ // pardes's patch (its build.zig): ESC before a key's sequence is Alt on the key. \\ 0x1B => if (input.len > 2 and (input[2] == '[' or input[2] == 'O')) { - \\ var inner = if (input[2] == '[') parseCsi(input[1..], &self.buf) else parseSs3(input[1..]); + \\ var inner = if (input[2] == '[') parseCsi(input[1..], &self.buf, self.cursor_position_requests) else parseSs3(input[1..]); \\ if (inner.n == 0) return inner; \\ if (inner.event) |*event| switch (event.*) { \\ .key_press, .key_release => |*key| key.mods.alt = true, @@ -765,71 +776,17 @@ pub fn build(b: *std.Build) void { \\ switch (input[2]) { , }, - .{ - .anchor = - \\ const esc_result = skipUntilST(input); - \\ if (esc_result.n > 0) break :blk esc_result.n; - \\ - \\ // No escape, could be BEL terminated - \\ const bel = std.mem.indexOfScalarPos(u8, input, 2, 0x07) orelse return .{ - \\ .event = null, - \\ .n = 0, - \\ }; - \\ bel_terminated = true; - \\ break :blk bel + 1; - , - .with = - \\ // pardes's patch (its build.zig): whichever terminator comes first ends it. - \\ const esc = std.mem.indexOfScalarPos(u8, input, 2, 0x1b); - \\ const bel = std.mem.indexOfScalarPos(u8, input, 2, 0x07); - \\ if (bel != null and (esc == null or bel.? < esc.?)) { - \\ bel_terminated = true; - \\ break :blk bel.? + 1; - \\ } - \\ const esc_result = skipUntilST(input); - \\ if (esc_result.n > 0) break :blk esc_result.n; - \\ return .{ .event = null, .n = 0 }; - , - }, - .{ - .anchor = " const color = try Color.rgbFromSpec(color_spec);\n", - .with = " const color = Color.rgbFromSpec(color_spec) catch return null_event; // pardes's patch (its build.zig)\n", - .count = 2, - }, - .{ - .anchor = - \\ if (input[semicolon_idx + 1] != 'c') return null_event; - \\ const payload = if (bel_terminated) - \\ input[semicolon_idx + 3 .. sequence.len - 1] - \\ else - \\ input[semicolon_idx + 3 .. sequence.len - 2]; - \\ const decoder = std.base64.standard.Decoder; - \\ const text = try paste_allocator.?.alloc(u8, try decoder.calcSizeForSlice(payload)); - \\ try decoder.decode(text, payload); - , - .with = - \\ // pardes's patch (its build.zig): a malformed reply is dropped. - \\ const body_end = if (bel_terminated) sequence.len - 1 else sequence.len - 2; - \\ if (semicolon_idx + 3 > body_end or input[semicolon_idx + 1] != 'c') return null_event; - \\ const payload = input[semicolon_idx + 3 .. body_end]; - \\ const decoder = std.base64.standard.Decoder; - \\ const gpa = paste_allocator orelse return null_event; - \\ const text = gpa.alloc(u8, decoder.calcSizeForSlice(payload) catch return null_event) catch return null_event; - \\ decoder.decode(text, payload) catch { - \\ gpa.free(text); - \\ return null_event; - \\ }; - , - }, .{ .anchor = \\ 'A', 'B', 'C', 'D', 'E', 'F', 'H', 'P', 'Q', 'R', 'S' => { + \\ // Legacy keys \\ , .with = \\ 'A', 'B', 'C', 'D', 'E', 'F', 'H', 'P', 'Q', 'R', 'S' => { \\ // pardes's patch (its build.zig): a cursor position report is no key. \\ if (final == 'R' and cursorReport(sequence)) return null_event; + \\ // Legacy keys \\ , }, @@ -882,8 +839,7 @@ pub fn build(b: *std.Build) void { // (InactiveDim on a focus change) sent every blank of every pane it // touched again: 7 KB a click for three shell panes. The terminal // keeps the old ink there, and so does vaxis's last frame. - const render_path = vaxis_dep.path("src/Vaxis.zig").getPath(b); - var render_src = std.Io.Dir.cwd().readFileAlloc(io, render_path, b.allocator, .limited(1 << 20)) catch @panic("read vaxis Vaxis.zig"); + var render_src = configureRead(b, io, vaxis_dep.builder.root, "src/Vaxis.zig", 1 << 20) catch @panic("read vaxis Vaxis.zig"); const render_anchor = \\ if ((!self.refresh and \\ last.eql(cell) and @@ -941,7 +897,7 @@ pub fn build(b: *std.Build) void { var ghostty_vt_for_snap: ?*std.Build.Module = null; const ghostty_simd = !freestanding_core and (!target.result.os.tag.isDarwin() or b.graph.host.result.os.tag.isDarwin()); - const ghostty_optimize: std.builtin.OptimizeMode = if (optimize == .Debug) .ReleaseSafe else optimize; + const ghostty_optimize: std.lang.Optimize = if (optimize == .debug) .safe else optimize; const ghostty_dep = if (is_esp32p4) null else b.lazyDependency("ghostty", .{ .target = target, .optimize = ghostty_optimize, .simd = ghostty_simd, .@"app-runtime" = .none, .@"emit-xcframework" = false }); if (ghostty_dep) |dep| { const ghostty_vt = dep.module("ghostty-vt"); @@ -1017,6 +973,17 @@ pub fn build(b: *std.Build) void { const sdl_lib = dep.artifact("SDL3"); gm.linkLibrary(sdl_lib); gm.addIncludePath(dep.path("include")); + // gui.zig's `c`: SDL and the font shim, which @cImport gave it before Zig 0.17. + const header = b.addWriteFiles().add("gui_c.h", + \\#define SDL_DISABLE_OLD_NAMES 1 + \\#include + \\#include "font.h" + \\ + ); + 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()); } gm.linkLibrary(freetype.?); // HarfBuzz from source, like FreeType: its FreeType integration @@ -1105,7 +1072,7 @@ pub fn build(b: *std.Build) void { }) |file| web_step.dependOn(&b.addInstallFileWithDir(b.path(file[0]), .{ .custom = "web" }, file[1]).step); const run_web_harness = b.addSystemCommand(&.{ "node", "test/web_harness.mjs" }); - run_web_harness.addArg(b.getInstallPath(.{ .custom = "web" }, "")); + run_web_harness.addDirectoryArg(installed("web")); run_web_harness.step.dependOn(web_step); b.step("web-harness", "run the dependency-free JS/WASM DOM harness").dependOn(&run_web_harness.step); b.getInstallStep().dependOn(web_step); @@ -1149,9 +1116,9 @@ pub fn build(b: *std.Build) void { const min_version = b.fmt("{d}.{d}", .{ macos_min_version.major, macos_min_version.minor }); const swift_mode: []const u8 = switch (optimize) { - .Debug => "-Onone", - .ReleaseSmall => "-Osize", - .ReleaseFast, .ReleaseSafe => "-O", + .debug => "-Onone", + .small => "-Osize", + .fast, .safe => "-O", }; const link = b.addSystemCommand(&.{ "swiftc", swift_mode, "-target", triple, "-import-objc-header" }); @@ -1218,7 +1185,8 @@ pub fn build(b: *std.Build) void { const sign = b.addSystemCommand(&.{ "codesign", "--force", "--sign", macos_identity }); if (!std.mem.eql(u8, macos_identity, "-")) sign.addArgs(&.{ "--options", "runtime", "--timestamp" }); - sign.addArg(b.getInstallPath(.prefix, "pardes.app")); + sign.setCwd(installed("")); + sign.addArg("pardes.app"); sign.has_side_effects = true; sign.step.dependOn(&install_app_bin.step); sign.step.dependOn(&install_plist.step); @@ -1227,8 +1195,8 @@ pub fn build(b: *std.Build) void { app_step.dependOn(&sign.step); const dmg = b.addSystemCommand(&.{ "hdiutil", "create", "-volname", "pardes", "-ov", "-format", "UDZO", "-srcfolder" }); - dmg.addArg(b.getInstallPath(.prefix, "pardes.app")); - dmg.addArg(b.getInstallPath(.prefix, "pardes.dmg")); + dmg.setCwd(installed("")); + dmg.addArgs(&.{ "pardes.app", "pardes.dmg" }); dmg.has_side_effects = true; dmg.step.dependOn(&sign.step); dmg_step.dependOn(&dmg.step); @@ -1267,7 +1235,7 @@ pub fn build(b: *std.Build) void { const run_e2e = std.Build.Step.Run.create(b, "run macos-e2e"); run_e2e.addFileArg(runnable); run_e2e.setCwd(b.path(".")); - if (b.args) |args| run_e2e.addArgs(args); + run_e2e.addPassthruArgs(); run_e2e.has_side_effects = true; e2e_step.dependOn(&run_e2e.step); } else e2e_step.dependOn(&b.addFail("macos-e2e needs a Darwin host and target").step); @@ -1290,7 +1258,7 @@ pub fn build(b: *std.Build) void { .linkage = if (static) .static else null, .root_module = root_mod, }); - b.installArtifact(exe); + installHome(b, exe, home_bin); if (gui_mod) |gm| { var gui_name: []const u8 = "pardes-gui"; if (target.result.os.tag != .linux or target.result.cpu.arch != .x86_64) @@ -1300,7 +1268,7 @@ pub fn build(b: *std.Build) void { .linkage = if (static) .static else null, .root_module = gm, }); - b.installArtifact(gui_exe); + installHome(b, gui_exe, home_bin); } const run = b.addRunArtifact(exe); b.step("run", "descend to the pardes").dependOn(&run.step); @@ -1312,7 +1280,7 @@ pub fn build(b: *std.Build) void { }); const run_iso = b.addRunArtifact(iso_exe); // Something to look at on arrival, read out of the binary itself. - if (b.args) |args| run_iso.addArgs(args) else run_iso.addArg("src/pardes.zig"); + run_iso.addPassthruArgs(); const iso_step = b.step("run-isolated", "descend to a pardes with no host but the terminal"); iso_step.dependOn(&run_iso.step); } @@ -1370,15 +1338,9 @@ pub fn build(b: *std.Build) void { hxdiff.root_module.addImport("pardes", core_module); const run_hxdiff = b.addRunArtifact(hxdiff); run_hxdiff.has_side_effects = true; - if (b.args) |args| run_hxdiff.addArgs(args) else { - run_hxdiff.addArgs(&.{ - "--strict", - "test/hxcases/cases.jsonl", - "test/hxcases/goldens.jsonl", - "test/hxcases/waivers.jsonl", - }); - run_hxdiff.setCwd(b.path(".")); - } + // Bare, it runs the checked-in suite (test/hxdiff.zig). + run_hxdiff.addPassthruArgs(); + run_hxdiff.setCwd(b.path(".")); const hxdiff_step = b.step("hxdiff", "compare Helix results (-- --strict cases reference [waivers]; cases alone emits)"); hxdiff_step.dependOn(&run_hxdiff.step); @@ -1403,16 +1365,8 @@ pub fn build(b: *std.Build) void { const run_hxparity = b.addRunArtifact(hxdiff); run_hxparity.has_side_effects = true; run_hxparity.addArg("--parity"); - if (b.args) |args| run_hxparity.addArgs(args) else { - run_hxparity.addArgs(&.{ - "--strict", - "--waivers", - "test/hxcases/parity-waivers.jsonl", - "test/hxcases/cases.jsonl", - "test/hxcases/parity.jsonl", - }); - run_hxparity.setCwd(b.path(".")); - } + run_hxparity.addPassthruArgs(); + run_hxparity.setCwd(b.path(".")); const hxparity_step = b.step("hxparity", "run the file-vs-pty editing parity suite (-- [--waivers w.jsonl] ...)"); hxparity_step.dependOn(&run_hxparity.step); @@ -1427,21 +1381,21 @@ pub fn build(b: *std.Build) void { .name = "pardes-lspbench", .root_module = b.createModule(.{ .target = target, - .optimize = .ReleaseFast, + .optimize = .fast, .root_source_file = b.path("test/lspbench.zig"), .link_libc = true, }), }); lspbench.root_module.addImport("pardes", core_module); const run_lspbench = b.addRunArtifact(lspbench); - if (b.args) |args| run_lspbench.addArgs(args); + run_lspbench.addPassthruArgs(); run_lspbench.setCwd(b.path(".")); run_lspbench.has_side_effects = true; const lspbench_step = b.step("lspbench", "language-backend latency + feature matrix (-- [--json] [--check] [repo-root]), or one query (-- probe : [arg] [--reps N])"); lspbench_step.dependOn(&run_lspbench.step); const run_lspbench_check = b.addRunArtifact(lspbench); run_lspbench_check.addArg("--check"); - if (b.args) |args| run_lspbench_check.addArgs(args); + run_lspbench_check.addPassthruArgs(); run_lspbench_check.setCwd(b.path(".")); run_lspbench_check.has_side_effects = true; const lspbench_check_step = b.step("lspbench-check", "require every configured language probe to complete correctly"); @@ -1449,12 +1403,12 @@ pub fn build(b: *std.Build) void { const locations_bench_step = b.step("locations-bench", "measure cold/warm result formatting (-Doptimize=ReleaseFast; CSV on stderr)"); - if (optimize != .ReleaseFast) { + if (optimize != .fast) { locations_bench_step.dependOn(&b.addFail("locations-bench requires -Doptimize=ReleaseFast").step); } else { const locations_bench_module = b.createModule(.{ .target = target, - .optimize = .ReleaseFast, + .optimize = .fast, .root_source_file = b.path("test/locations_bench.zig"), .link_libc = true, }); @@ -1465,7 +1419,7 @@ pub fn build(b: *std.Build) void { locations_bench_step.dependOn(&run_locations_bench.step); } - const perf_optimize: std.builtin.OptimizeMode = .ReleaseFast; + const perf_optimize: std.lang.Optimize = .fast; const perf_options = b.addOptions(); const perf_target = std.Target.Query.fromTarget(&target.result); perf_options.addOption(PerfBuild, "identity", .{ @@ -1499,7 +1453,7 @@ pub fn build(b: *std.Build) void { perf.root_module.addOptions("perf_options", perf_options); const run_perf = b.addRunArtifact(perf); run_perf.has_side_effects = true; - if (b.args) |args| run_perf.addArgs(args); + run_perf.addPassthruArgs(); run_perf.setCwd(b.path(".")); const perf_step = b.step("perf", "gesture latency or bounded terminal stress (-- [--json] [--reps N] [--base old.json] [--terminal-mib N])"); perf_step.dependOn(&run_perf.step); @@ -1536,7 +1490,7 @@ pub fn build(b: *std.Build) void { .name = "pardes-fs-bench", .root_module = b.createModule(.{ .target = target, - .optimize = .ReleaseFast, + .optimize = .fast, .root_source_file = b.path("test/fs_bench.zig"), .link_libc = true, }), @@ -1544,7 +1498,7 @@ pub fn build(b: *std.Build) void { fs_bench.root_module.addImport("pardes", core_module); const run_fs_bench = b.addRunArtifact(fs_bench); run_fs_bench.has_side_effects = true; - if (b.args) |args| run_fs_bench.addArgs(args); + run_fs_bench.addPassthruArgs(); run_fs_bench.setCwd(b.path(".")); const fs_bench_step = b.step("fs-bench", "9P filesystem request cost and allocation count (-- [--json] [--reps N])"); fs_bench_step.dependOn(&run_fs_bench.step); @@ -1581,11 +1535,11 @@ pub fn build(b: *std.Build) void { }); syntax_runner.root_module.addImport("syntax", syntax_module); const run_syntax = b.addRunArtifact(syntax_runner); - if (b.args) |args| run_syntax.addArgs(args); + run_syntax.addPassthruArgs(); b.step("syntax", "emit deterministic syntax snapshots").dependOn(&run_syntax.step); const run_syntax_bench = b.addRunArtifact(syntax_runner); run_syntax_bench.addArg("--bench"); - if (b.args) |args| run_syntax_bench.addArgs(args); + run_syntax_bench.addPassthruArgs(); run_syntax_bench.has_side_effects = true; b.step("syntax-bench", "measure highlighting latency and allocations").dependOn(&run_syntax_bench.step); const syntax_test = b.addTest(.{ @@ -1611,7 +1565,7 @@ pub fn build(b: *std.Build) void { // part of fs-test; the long run is manual. const run_monkey9p = b.addSystemCommand(&.{ "python3", "-B", "test/monkey9p.py" }); run_monkey9p.addArtifactArg(exe); - if (b.args) |args| run_monkey9p.addArgs(args); + run_monkey9p.addPassthruArgs(); run_monkey9p.setCwd(b.path(".")); run_monkey9p.has_side_effects = true; b.step("monkey-9p", "random 9P operations checking the documented rules (-- [--seed N]... [--steps M] [--replay F] [--shrink F] [--no-shrink])").dependOn(&run_monkey9p.step); @@ -1622,7 +1576,7 @@ pub fn build(b: *std.Build) void { if (platform == .gui) { const run_monkey_gui = b.addSystemCommand(&.{ "python3", "-B", "test/gui_monkey.py" }); run_monkey_gui.addArtifactArg(exe); - if (b.args) |args| run_monkey_gui.addArgs(args); + run_monkey_gui.addPassthruArgs(); run_monkey_gui.setCwd(b.path(".")); run_monkey_gui.has_side_effects = true; monkey_gui_step.dependOn(&run_monkey_gui.step); @@ -1653,7 +1607,7 @@ pub fn build(b: *std.Build) void { }), }); // Ordinary executable; each launch asks sudo inside its own PTY. - b.installArtifact(v9fs_helper); + installHome(b, v9fs_helper, home_bin); const run_v9fs = b.addSystemCommand(&.{ "python3", "-B", "test/v9fs.py" }); run_v9fs.addArtifactArg(exe); run_v9fs.addArtifactArg(v9fs_helper); @@ -1688,7 +1642,7 @@ pub fn build(b: *std.Build) void { }), }); const run_history = b.addRunArtifact(history); - if (b.args) |args| run_history.addArgs(args); + run_history.addPassthruArgs(); run_history.has_side_effects = true; b.step("history", "compare command output and test/build runtime across jj revisions").dependOn(&run_history.step); @@ -1843,7 +1797,7 @@ pub fn build(b: *std.Build) void { if (unit_match) |check| check.addArtifactArg(shell_test); const run_profile = b.addRunArtifact(unit_profile); run_profile.addArtifactArg(shell_test); - if (b.args) |args| run_profile.addArgs(args); + run_profile.addPassthruArgs(); run_profile.has_side_effects = true; b.step("unit-profile", "report test request time and process memory as JSONL (-- optional filter, --timeout-ms=N)").dependOn(&run_profile.step); const profile_test = b.addExecutable(.{ @@ -1876,19 +1830,38 @@ fn testMatch(b: *std.Build, profiler: *std.Build.Step.Compile, filters: []const return check; } -fn prefixIsUntouched(b: *std.Build) bool { - if (b.dest_dir != null) return false; - const zig_out = b.build_root.join(b.allocator, &.{"zig-out"}) catch @panic("OOM"); - if (!std.mem.eql(u8, b.install_prefix, zig_out)) return false; - return std.mem.eql(u8, b.exe_dir, b.pathJoin(&.{ b.install_path, "bin" })) and - std.mem.eql(u8, b.lib_dir, b.pathJoin(&.{ b.install_path, "lib" })) and - std.mem.eql(u8, b.h_dir, b.pathJoin(&.{ b.install_path, "include" })); +/// Installs `artifact` in the prefix and, given `home_bin`, copies it there +/// too (`install` unlinks first, so a running binary is replaced). +fn installHome(b: *std.Build, artifact: *std.Build.Step.Compile, home_bin: ?[]const u8) void { + b.installArtifact(artifact); + const dir = home_bin orelse return; + const copy = b.addSystemCommand(&.{ "install", "-Dm755" }); + copy.addArtifactArg(artifact); + copy.addArg(b.pathJoin(&.{ dir, artifact.name })); + copy.has_side_effects = true; + b.getInstallStep().dependOn(©.step); +} + +/// A file read while configuring, under a package's root. A dependency's is +/// hash-addressed and never changes under the same pin; this repo's are not +/// tracked one by one, since the configure runs again on every build anyway +/// (findProgram and gitCommit poison its cache). +// ponytail: untracked repo reads; b.dependOnFileContents each one if the configure cache ever stays pure. +fn configureRead(b: *std.Build, io: std.Io, root: std.Build.Cache.Path, sub: []const u8, limit: usize) ![]u8 { + return root.root_dir.handle.readFileAlloc(io, b.pathJoin(&.{ root.subPathOrDot(), sub }), b.allocator, .limited(limit)); +} + +/// `sub` under the install prefix, known only when the build runs. +fn installed(sub: []const u8) std.Build.LazyPath { + return .{ .relative = .{ .base = .install_prefix, .sub_path = sub } }; } fn gitCommit(b: *std.Build) ?[]const u8 { + // HEAD is not a file the configure cache can track. + b.graph.poisonCache(); var code: u8 = 0; const out = b.runAllowFail( - &.{ "git", "-C", b.build_root.path orelse ".", "rev-parse", "--short=12", "HEAD" }, + &.{ "git", "rev-parse", "--short=12", "HEAD" }, &code, .ignore, ) catch return null; @@ -1985,7 +1958,7 @@ fn compileGlsl(b: *std.Build, name: []const u8) std.Build.LazyPath { fn vendoredThemes(b: *std.Build, io: std.Io) []const []const u8 { var count: usize = 0; { - var dir = b.build_root.handle.openDir(io, "vendor/themes", .{ .iterate = true }) catch @panic("open vendor/themes"); + var dir = b.root.root_dir.handle.openDir(io, "vendor/themes", .{ .iterate = true }) catch @panic("open vendor/themes"); defer dir.close(io); var it = dir.iterate(); while (it.next(io) catch @panic("read vendor/themes")) |e| { @@ -1995,7 +1968,7 @@ fn vendoredThemes(b: *std.Build, io: std.Io) []const []const u8 { } const names = b.allocator.alloc([]const u8, count) catch @panic("OOM"); - var dir = b.build_root.handle.openDir(io, "vendor/themes", .{ .iterate = true }) catch @panic("open vendor/themes"); + var dir = b.root.root_dir.handle.openDir(io, "vendor/themes", .{ .iterate = true }) catch @panic("open vendor/themes"); defer dir.close(io); var it = dir.iterate(); var index: usize = 0; diff --git a/build.zig.zon b/build.zig.zon index b1f501fe..a2fc90dd 100644 --- a/build.zig.zon +++ b/build.zig.zon @@ -9,52 +9,59 @@ // read-only HTTPS URL is what a manifest can carry. Re-pin with // `zig fetch --save=cloud9 git+https://git.sr.ht/~gbrls/cloud9#`. .cloud9 = .{ - .url = "git+https://git.sr.ht/~gbrls/cloud9#fe9772b178575fcab93de09fc61c2f13db7db1a8", - .hash = "cloud9-0.1.0-yt86qh4qHgC6OpG4gZE9yoQaO8huc5mnQCaqGwuJ0OU1", + .url = "git+https://git.sr.ht/~gbrls/cloud9#d5c37d9122240fe95d308fbe15874e14dd786c5a", + .hash = "cloud9-0.1.0-yt86qnAvHgB1dEWGakukcJ54GZ7J3mv_lm_kApzAuEOY", }, // Pinned to the exact libvaxis commit ghostty is built against, so it // is compatible with ghostty's uucode configuration (the one we share // with it via `external_uucode` in build.zig). .vaxis = .{ - .url = "git+https://github.com/rockorager/libvaxis.git#1dbbe575dff4586fe51e3217aa5c3fecdcbb6089", - .hash = "vaxis-0.6.0-BWNV_CrbCQCscGpzsAlR402rYQ_tV3aAl081c2iRRkka", + .url = "git+https://github.com/rockorager/libvaxis.git#6fd944a27fb3d6f596e981076381a3131f2448b4", + .hash = "vaxis-0.6.0-BWNV_MafDAAEzkVUvrW9NFUqnnMUoeHqrs2mecnD6D7w", }, .ghostty = .{ - .url = "git+https://github.com/ghostty-org/ghostty.git#82e53e3f6e219e0cf0499fe29c82d925ea26cd5e", - .hash = "ghostty-1.3.2-dev-5UdBCzeJJQXw_vG5Hsfx0DYUmF7Exs_9yctijqOIfp7W", + .url = "git+https://github.com/ghostty-org/ghostty.git#521cf2c5d30bd48028ca61546c64e7913764073d", + .hash = "ghostty-1.3.2-dev-5UdBC6WZfwXgQ6HmA5DH6dGNAUqtDMLrhhrHiBX-99J0", }, // Same uucode commit ghostty and vaxis both depend on. We build it // ourselves (with uucode_config.zig) so ghostty-vt and vaxis can share // a single uucode module. See build.zig for the why. .uucode = .{ - .url = "git+https://github.com/jacobsandlund/uucode#2826a37a4562284fdacd8fa029d49509cc9bffcd", - .hash = "uucode-0.2.0-ZZjBPlK5VADj7fdoq7G8LIHzD5o6FSkcBXXrRWr4jnrA", + .url = "git+https://github.com/jacobsandlund/uucode#ea62149739404a73c202b48a33bf6dd2af4bd9b0", + .hash = "uucode-0.2.0-ZZjBPoGFVgCiflJNFc6Io8xzC67B6PA5bUkk4LT0kCxg", }, + // Pivok7's fork: zig-gamedev/zstbi PR #16, "Upgrade to zig 0.17.0" + // (two lines of build.zig). Back to upstream once it is merged. .zstbi = .{ - .url = "git+https://github.com/zig-gamedev/zstbi#3813f5f113b26f644cfa01a30155cc76b3526e91", - .hash = "zstbi-0.11.0-dev-L0Ea_3GWBwAh7m54XX055vwLKPTPij5hyqyeq92MXPE2", + .url = "git+https://github.com/Pivok7/zstbi#bc96f28d341f9c7fb9cbc5dc65aa4c5cf0c8f007", + .hash = "zstbi-0.11.0-dev-L0Ea_3GWBwCpNHVwGU4MPR_oDd0FoQOYNrGodwvJ6Z45", }, - // SDL3 (castholm/SDL zig bindings) — only fetched/compiled when `-Dsdl` - // is set. Lazy so the default vaxis build never touches it. The sdl + // SDL3 (castholm/SDL zig bindings, its release-3.4.x branch for Zig + // 0.17; david-vanderson's fork, pinned before, has no 0.17 build) — only + // fetched/compiled when `-Dsdl` is set. Lazy so the default vaxis build never touches it. The sdl // package resolves its own linux deps from its own build.zig.zon. .sdl = .{ - .url = "git+https://github.com/david-vanderson/SDL#5bbcf665494fe14acadf50601edf6d5f74ebf96a", - .hash = "sdl-0.4.2+3.4.4-SDL--tB1pQFLgwvCakiiOSoZIuVaz6a6-_gOZC66AGRD", + .url = "git+https://github.com/castholm/SDL#dbcb19aa3583c318556ecae3ecbeb29b102d37c5", + .hash = "sdl-0.6.0+3.4.18-SDL--p-gqAGWpnfTLlhs0dgjDtc4P4_CHeNLGY_SX_Fv", .lazy = true, }, // tree-sitter: Zig bindings + the C runtime, plus grammars (parser.c // we link, highlights.scm we read at build time into the ts_queries module). + // pierrelgol's forks of zig-tree-sitter (here) and tree-sitter-c + // (ts_c), which pin a fork of the tree-sitter core: upstream's + // build.zig files still use APIs Zig 0.17 removed. Their diffs touch + // only the build files and tests. Back to upstream once it moves. .tree_sitter = .{ - .url = "git+https://github.com/tree-sitter/zig-tree-sitter#b55d4977d61330390fc733944da06106ff972660", - .hash = "tree_sitter-0.26.0-8heIf3CaAQB4SSumoGzq3gLSz2rkvXxcKFyskRWqDGBz", + .url = "git+https://github.com/pierrelgol/zig-tree-sitter#2ffef82a12d0305e646ade0e67c693cabc661e05", + .hash = "tree_sitter-0.26.0-8heIf1HEAQCVBaR2wlDhGTw16Ttn1bzERVIwlzNcyO6b", }, .ts_rust = .{ .url = "git+https://github.com/tree-sitter/tree-sitter-rust#77a3747266f4d621d0757825e6b11edcbf991ca5", .hash = "N-V-__8AAHJYbgAipcanYj2A6rnj9wtGzjGzANkrOsqiFAxm", }, .ts_c = .{ - .url = "git+https://github.com/tree-sitter/tree-sitter-c#b780e47fc780ddc8da13afa35a3f4ed5c157823d", - .hash = "tree_sitter_c-0.24.2-y5boS-ptQADHoCoVfjGT_nFtFQ5LbomIkW0fxG3_cmdB", + .url = "git+https://github.com/pierrelgol/tree-sitter-c#67949e4c8dc630c18a522919f2bde2e025a0d025", + .hash = "tree_sitter_c-0.24.2-y5boS-htQACe3pz6jHq4tpS8dB6WIo4-zk_ct7lAjvQT", }, .ts_typst = .{ .url = "git+https://github.com/uben0/tree-sitter-typst#13863ddcbaa7b68ee6221cea2e3143415e64aea4", @@ -185,7 +192,7 @@ .lazy = true, }, }, - .minimum_zig_version = "0.16.0", + .minimum_zig_version = "0.17.0", .paths = .{""}, .fingerprint = 0x41dc46101fc764d8, } diff --git a/build/snap.zig b/build/snap.zig index 7aa06884..35a246ad 100644 --- a/build/snap.zig +++ b/build/snap.zig @@ -44,7 +44,7 @@ pub fn addTty(b: *std.Build, opts: struct { const run_snap = b.addRunArtifact(snap); run_snap.addArtifactArg(opts.exe); run_snap.addPrefixedFileArg("--lspmock=", lspmock.getEmittedBin()); - if (b.args) |args| run_snap.addArgs(args); + run_snap.addPassthruArgs(); // scripts fork children and drive real ptys: never cached, never "up to date" run_snap.has_side_effects = true; const snap_step = b.step("snap", "run the snapshot parity suite (-- --update regenerates goldens)"); @@ -63,7 +63,7 @@ pub fn addTty(b: *std.Build, opts: struct { const run_monkey = b.addRunArtifact(monkey); run_monkey.addArtifactArg(snap); run_monkey.addArtifactArg(opts.exe); - if (b.args) |args| run_monkey.addArgs(args); + run_monkey.addPassthruArgs(); run_monkey.has_side_effects = true; b.step("monkey", "random snapshot scripts hunting panics (-- [steps] [--from=N] [--out=DIR])").dependOn(&run_monkey.step); const monkey_tests = b.addTest(.{ .root_module = monkey.root_module }); @@ -101,7 +101,7 @@ pub fn addWeb(b: *std.Build) void { run_web_snap.step.dependOn(&build_web_snap.step); run_web_snap.step.dependOn(&driver_test.step); run_web_snap.has_side_effects = true; - if (b.args) |args| run_web_snap.addArgs(args); + run_web_snap.addPassthruArgs(); b.step("web-snap", "run browser highlighting, touch, Look, resize and scroll checks").dependOn(&run_web_snap.step); b.step("web-e2e", "run the Chrome-driven DOM end-to-end suite").dependOn(&run_web_snap.step); } diff --git a/docs/typ/building.typ b/docs/typ/building.typ index ae2f3a60..8d7524f9 100644 --- a/docs/typ/building.typ +++ b/docs/typ/building.typ @@ -9,7 +9,7 @@ pieces fit. To install it, see #doc("setup", section: "install"). = Platforms -Zig *0.16.0* (`build.zig.zon` pins `minimum_zig_version`). Dependencies are +Zig *0.17.0* (`build.zig.zon` pins `minimum_zig_version`). Dependencies are fetched and pinned by the manifest; the terminal build needs no system package. The SDL shell builds SDL3 and FreeType from source. PDF support builds MuPDF and is on by default (`-Dmupdf=false` drops it). 9P over QUIC @@ -24,10 +24,11 @@ builds MuPDF and is on by default (`-Dmupdf=false` drops it). 9P over QUIC [`zig build -Dplatform=esp32p4`], [a freestanding riscv32 editor object for the ESP32-P4, with a 384 KiB heap], ) -A bare `zig build` installs into `~/.local`; `--prefix ` installs -elsewhere, except `--prefix zig-out`, which counts as no prefix. With -`-Dplatform` the default prefix is `zig-out`, so always pass `-Dplatform` -while developing. Test, benchmark and run steps build what they need +A bare `zig build` installs into the prefix (`zig-out`, or `--prefix +`) 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 without installing. `pardes --version` prints `pardes ` (from `build.zig.zon`), plus the commit for release builds and the `~/.local` install; `pardes --help` lists every flag. @@ -50,6 +51,7 @@ there; its namespace is in `src/esp32p4_gpio.zig`. [`-Djpx`], [bool, `true`: JPEG 2000, and with it scanned PDFs], [`-Dtree-sitter`], [`disabled`, `zig`, `minimal`, `full`; `full` natively, `zig` for web, `disabled` for esp32p4], [`-Dembed-sources`], [bool, `false`: serve the sources under #file("/src")], + [`-Dhome-install`], [bool: a bare `zig build` also copies the binaries into `~/.local/bin`; default true], [`-Dstamp-commit`], [bool: the git commit in `--version` and crash records; on for release builds and the `~/.local` install], [`-Dtheme-animation`], [bool; on except for esp32p4], [`-Dworkspace-tag`], [bool: draw the workspace tag row; on except for macOS, whose menu bar carries it], diff --git a/docs/typ/install.typ b/docs/typ/install.typ index 9758777d..d97d30f7 100644 --- a/docs/typ/install.typ +++ b/docs/typ/install.typ @@ -18,7 +18,7 @@ #let first = project.mirrors.first() #cmd("git clone " + first.clone + " && cd pardes") -With Zig 0.16 (the build fetches everything else; once that is +With Zig 0.17 (the build fetches everything else; once that is downloaded, a first build from a clean cache took 62 seconds on 16 cores): #cmd("# pardes, in a terminal\nzig build -Dplatform=tty --prefix ~/.local") #cmd("# pardes-gui, its own window\nzig build -Dplatform=gui --prefix ~/.local") diff --git a/mupdf.zig b/mupdf.zig index eeadaa5d..761fef92 100644 --- a/mupdf.zig +++ b/mupdf.zig @@ -293,7 +293,7 @@ fn configureModule(module: *std.Build.Module, dependency: *std.Build.Dependency, } fn flatCSources(b: *std.Build, io: std.Io, dependency: *std.Build.Dependency, relative_dir: []const u8) []const []const u8 { - var dir = std.Io.Dir.cwd().openDir(io, dependency.path(relative_dir).getPath(b), .{ .iterate = true }) catch + var dir = dependency.builder.root.root_dir.handle.openDir(io, relative_dir, .{ .iterate = true }) catch std.debug.panic("MuPDF source directory is missing: {s}", .{relative_dir}); defer dir.close(io); @@ -317,9 +317,9 @@ fn flatCSources(b: *std.Build, io: std.Io, dependency: *std.Build.Dependency, re } fn readMakelists(b: *std.Build, io: std.Io, dependency: *std.Build.Dependency) []const u8 { - return std.Io.Dir.cwd().readFileAlloc( + return dependency.builder.root.root_dir.handle.readFileAlloc( io, - dependency.path("Makelists").getPath(b), + "Makelists", b.allocator, .limited(1024 * 1024), ) catch @panic("read MuPDF Makelists"); diff --git a/src/9p_io.zig b/src/9p_io.zig index 18c51ece..27d79b93 100644 --- a/src/9p_io.zig +++ b/src/9p_io.zig @@ -1553,7 +1553,7 @@ test "a socket path too long for sun_path is no listener, and leaves the editor' } else { _ = unsetenv("XDG_RUNTIME_DIR"); }; - const long = "n" ** 120; + const long = &@as([120]u8, @splat('n')); try testing.expect(listen(testing.io, testing.allocator, p, long, "", null, null) == null); try testing.expect(pardes.turn.answer_held == null); try testing.expect(pardes.turn.wake_parked == null); @@ -1567,7 +1567,7 @@ test "a listening editor posts itself into the 9P registry and unposts on stop" _ = try std.fmt.bufPrintSentinel(&directory, "/tmp/pardes-post-XXXXXX", .{}, 0); if (mkdtemp(&directory) == null) return error.TempDirectoryFailed; const dir = std.mem.span(@as([*:0]const u8, &directory)); - const old_runtime = if (libc.getenv("XDG_RUNTIME_DIR")) |v| try gpa.dupeZ(u8, std.mem.span(v)) else null; + const old_runtime = if (libc.getenv("XDG_RUNTIME_DIR")) |v| try gpa.dupeSentinel(u8, std.mem.span(v), 0) else null; defer { if (old_runtime) |v| { _ = setenv("XDG_RUNTIME_DIR", v, 1); @@ -1628,7 +1628,7 @@ test "Unix TCP and QUIC share one listener through reads writes reconnects and r if (mkdtemp(&directory) == null) return error.TempDirectoryFailed; // What the listener posted and left inside goes with it. defer std.Io.Dir.cwd().deleteTree(testing.io, std.mem.sliceTo(&directory, 0)) catch |err| std.debug.print("deleteTree: {s}\n", .{@errorName(err)}); - const old_runtime = if (libc.getenv("XDG_RUNTIME_DIR")) |v| try gpa.dupeZ(u8, std.mem.span(v)) else null; + const old_runtime = if (libc.getenv("XDG_RUNTIME_DIR")) |v| try gpa.dupeSentinel(u8, std.mem.span(v), 0) else null; defer { if (old_runtime) |v| { _ = setenv("XDG_RUNTIME_DIR", v, 1); @@ -1749,7 +1749,7 @@ test "a change waits while the editor is out mid-step, a read does not, and the if (mkdtemp(&directory) == null) return error.TempDirectoryFailed; // What the listener posted and left inside goes with it. defer std.Io.Dir.cwd().deleteTree(testing.io, std.mem.sliceTo(&directory, 0)) catch |err| std.debug.print("deleteTree: {s}\n", .{@errorName(err)}); - const old_runtime = if (libc.getenv("XDG_RUNTIME_DIR")) |v| try gpa.dupeZ(u8, std.mem.span(v)) else null; + const old_runtime = if (libc.getenv("XDG_RUNTIME_DIR")) |v| try gpa.dupeSentinel(u8, std.mem.span(v), 0) else null; defer { if (old_runtime) |v| { _ = setenv("XDG_RUNTIME_DIR", v, 1); @@ -1824,7 +1824,7 @@ test "a held read is answered when the log has news, and a flushed one spends no if (mkdtemp(&directory) == null) return error.TempDirectoryFailed; // What the listener posted and left inside goes with it. defer std.Io.Dir.cwd().deleteTree(testing.io, std.mem.sliceTo(&directory, 0)) catch |err| std.debug.print("deleteTree: {s}\n", .{@errorName(err)}); - const old_runtime = if (libc.getenv("XDG_RUNTIME_DIR")) |v| try gpa.dupeZ(u8, std.mem.span(v)) else null; + const old_runtime = if (libc.getenv("XDG_RUNTIME_DIR")) |v| try gpa.dupeSentinel(u8, std.mem.span(v), 0) else null; defer { if (old_runtime) |v| { _ = setenv("XDG_RUNTIME_DIR", v, 1); @@ -2051,7 +2051,7 @@ test "a pane's PARDES_MOUNT is the session's directory under 9ns --mntgen, and u const names = [_][*:0]const u8{ "NINE_MNTGEN", "NINE_MOUNT", "PARDES_MOUNT" }; var saved: [names.len]?[:0]u8 = @splat(null); for (names, &saved) |name, *value| { - if (libc.getenv(name)) |old| value.* = try testing.allocator.dupeZ(u8, std.mem.span(old)); + if (libc.getenv(name)) |old| value.* = try testing.allocator.dupeSentinel(u8, std.mem.span(old), 0); } defer for (names, saved) |name, value| { if (value) |old| { @@ -2073,7 +2073,7 @@ test "9P shell environment states being inside pardes apart from how to reach it const names = [_][*:0]const u8{ "XDG_RUNTIME_DIR", "HOME", "PARDES_PID", "PARDES_9P", "PARDES_PANE" }; var saved: [names.len]?[:0]u8 = @splat(null); for (names, &saved) |name, *value| { - if (libc.getenv(name)) |old| value.* = try testing.allocator.dupeZ(u8, std.mem.span(old)); + if (libc.getenv(name)) |old| value.* = try testing.allocator.dupeSentinel(u8, std.mem.span(old), 0); } defer for (names, saved) |name, value| { if (value) |old| { diff --git a/src/CHANGELOG.md b/src/CHANGELOG.md index 4fe0760c..c6c2eadd 100644 --- a/src/CHANGELOG.md +++ b/src/CHANGELOG.md @@ -17,6 +17,14 @@ - A diff paged into a session (`git show | pardes -`) opens its `+Diff` alone; the `+Pager` no longer stays folded under it. +- Built with Zig 0.17. A bare `zig build` still puts the binaries in + `~/.local/bin`, now as a copy beside the prefix, which `--prefix` no + longer prevents; `-Dhome-install=false` does. ghostty, libvaxis, uucode + and SDL (3.4.18) move to their Zig 0.17 versions, and tree-sitter to a + 0.28 development snapshot. +- A terminal's edited copy goes when the program clears the screen, + instead of staying where its rows were. + - n/N follow Helix search registers, counts, wrapping and select mode. `*` sets a search from the selection; `Alt-*` omits word boundaries. The location ring remains as LookNext/LookPrev (Space j n/p). diff --git a/src/Layer.zig b/src/Layer.zig index 7a5fcf7e..ba45bc88 100644 --- a/src/Layer.zig +++ b/src/Layer.zig @@ -51,7 +51,7 @@ cols: u16 = 0, rows: u16 = 0, /// A body's compact rows, from its top. context_rows: u16 = 0, -context_separators: std.bit_set.StaticBitSet(limits.wrap_rows) = .initEmpty(), +context_separators: std.bit_set.StaticBitSet(limits.wrap_rows) = .empty, /// `rows * cols`, row after row. cells: []pardes.Cell = &.{}, cursor: ?struct { x: u16, y: u16, bar: bool = false } = null, @@ -72,7 +72,7 @@ pub fn capacity(layer: *const Layer, metrics: Metrics) u16 { } pub fn setContextLines(layer: *Layer, lines: []const i32) void { - layer.context_separators = .initEmpty(); + layer.context_separators = .empty; const count = @min(lines.len, layer.context_rows); var index: usize = 0; while (index + 1 < count and index < limits.wrap_rows) : (index += 1) { diff --git a/src/Messages.zig b/src/Messages.zig index 2314939f..b67a8402 100644 --- a/src/Messages.zig +++ b/src/Messages.zig @@ -519,20 +519,20 @@ pub fn errorWords(err: anyerror, buf: []u8) []const u8 { /// A ZON parse failure in a person's words: the first error the parser /// found and its line, `line 3: expected ','`. pub fn zonWhy(diag: *const std.zon.parse.Diagnostics, buf: []u8) []const u8 { - var errors = diag.iterateErrors(); - const first = errors.next() orelse return "not valid ZON"; - const loc = first.getLocation(diag); - return std.fmt.bufPrint(buf, "line {d}: {f}", .{ loc.line + 1, first.fmtMessage(diag) }) catch "not valid ZON"; + if (diag.errors.len == 0) return "not valid ZON"; + const first = diag.errors[0]; + return std.fmt.bufPrint(buf, "line {d}: {s}", .{ first.loc.line + 1, first.msg }) catch "not valid ZON"; } test "errors are said in words, and a ZON failure names its line" { var buf: [128]u8 = undefined; try std.testing.expectEqualStrings("file not found", errorWords(error.FileNotFound, &buf)); try std.testing.expectEqualStrings("too large", errorWords(error.FileTooLarge, &buf)); - var diag: std.zon.parse.Diagnostics = .{}; - defer diag.deinit(std.testing.allocator); + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + var diag: std.zon.parse.Diagnostics = undefined; const T = struct { a: u8 }; - try std.testing.expectError(error.ParseZon, std.zon.parse.fromSliceAlloc(T, std.testing.allocator, ".{\n .a = 1,\n .b = 2 }", &diag, .{})); + try std.testing.expectError(error.ParseZon, std.zon.parse.fromSlice(T, .{ .gpa = std.testing.allocator, .arena = arena.allocator(), .source = ".{\n .a = 1,\n .b = 2 }", .diagnostics = &diag })); try std.testing.expect(std.mem.startsWith(u8, zonWhy(&diag, &buf), "line 3: ")); } diff --git a/src/TerminalImages.zig b/src/TerminalImages.zig index bc1b2ea8..4140813f 100644 --- a/src/TerminalImages.zig +++ b/src/TerminalImages.zig @@ -38,6 +38,72 @@ const GlyphKey = struct { id: u32, generation: u64, src: PixelRect, cols: u16 }; /// left corner (above or left of it is negative). const Rect = struct { x: i64, y: i64, w: i64, h: i64 }; +/// The runs of Kitty placeholder cells between two pins, one row's run at a +/// time, as ghostty's own `kitty.graphics.unicode.placementIterator` gave +/// them before it moved into its RenderState, which pardes does not keep. +const PlaceholderRuns = struct { + rows: ghostty_vt.PageList.RowIterator, + row: ?ghostty_vt.Pin, + /// Where the scan of `row` resumes: a run ended by an incompatible + /// placeholder starts the next one there. + x: usize = 0, + + fn init(top: ghostty_vt.Pin, bottom: ghostty_vt.Pin) PlaceholderRuns { + var rows = top.rowIterator(.right_down, bottom); + const row = rows.next(); + return .{ .rows = rows, .row = row }; + } + + fn next(self: *PlaceholderRuns) ?gfx.unicode.Placement { + while (self.row) |row| { + if (!row.rowAndCell().row.kitty_virtual_placeholder) { + self.advance(); + continue; + } + var run: ?gfx.unicode.IncompletePlacement = null; + var start: usize = 0; + const cells = row.cells(.all); + while (self.x < cells.len) : (self.x += 1) { + const cell = &cells[self.x]; + if (cell.codepoint() != gfx.unicode.placeholder) { + if (run) |done| return complete(row, start, done); + continue; + } + const style = row.style(cell); + const curr: gfx.unicode.IncompletePlacement = .init(&style, row.grapheme(cell) orelse &.{}); + if (run) |*prev| { + if (!prev.append(&curr)) return complete(row, start, prev.*); + } else { + run = curr.start(); + start = self.x; + } + } + self.advance(); + if (run) |done| return complete(row, start, done); + } + return null; + } + + fn advance(self: *PlaceholderRuns) void { + self.row = self.rows.next(); + self.x = 0; + } + + fn complete(row: ghostty_vt.Pin, x: usize, run: gfx.unicode.IncompletePlacement) gfx.unicode.Placement { + var pin = row; + pin.x = @intCast(x); + return .{ + .pin = pin, + .image_id = run.imageId(), + .placement_id = run.placement_id orelse 0, + .col = run.col.?, + .row = run.row.?, + .width = run.width, + .height = 1, + }; + } +}; + pub fn deinit(ti: *TerminalImages, gpa: std.mem.Allocator) void { var conv = ti.converted.valueIterator(); while (conv.next()) |c| gpa.free(c.rgba); @@ -91,7 +157,7 @@ pub fn draw( // Virtual placements: shown through the placeholder cells, one run of // them on a row at a time. The placeholders themselves are not text. - var runs = gfx.unicode.placementIterator(top, bottom); + var runs: PlaceholderRuns = .init(top, bottom); while (runs.next()) |run| { const at = pages.pointFromPin(.viewport, run.pin) orelse continue; const v = at.viewport.y; @@ -104,7 +170,8 @@ pub fn draw( cell.len = 1; } const img = storage.imageById(run.image_id) orelse continue; - const rp = run.renderPlacement(storage, &img, cw, ch) catch continue; + const target = storage.placeholderTarget(run.image_id, run.placement_id) orelse continue; + const rp = run.renderPlacement(&target.placement, &img, cw, ch) catch continue; if (rp.dest_width == 0 or rp.dest_height == 0 or rp.source_width == 0 or rp.source_height == 0) continue; ctx.place(img, .{ .x = rp.source_x, .y = rp.source_y, .w = rp.source_width, .h = rp.source_height }, .{ .x = @as(i64, at.viewport.x) * cw + rp.offset_x, @@ -122,7 +189,8 @@ pub fn draw( const placed = entry.value_ptr.*; const pin = switch (placed.location) { .pin => |pin| pin, - .virtual => continue, + // ponytail: a placement relative to another (P=/Q=, new in ghostty) is not drawn; resolve its chain if a program needs it. + .virtual, .relative => continue, }; const img = storage.images.get(entry.key_ptr.image_id) orelse continue; const at = pages.pointFromPin(.screen, pin.*) orelse continue; @@ -221,7 +289,8 @@ const Ctx = struct { fn pixelsOf(ti: *TerminalImages, gpa: std.mem.Allocator, img: gfx.Image) ?[]const u8 { const n = @as(usize, img.width) * img.height; if (n == 0) return null; - if (img.format == .rgba) return if (img.data.len == n * 4) img.data else null; + const data = img.data.bytes() orelse return null; + if (img.format == .rgba) return if (data.len == n * 4) data else null; const gop = ti.converted.getOrPut(gpa, img.id) catch return null; if (gop.found_existing) { if (gop.value_ptr.generation == img.generation) { @@ -247,10 +316,11 @@ fn convert(gpa: std.mem.Allocator, img: gfx.Image, n: usize) ?[]u8 { .gray => 1, else => return null, }; - if (img.data.len != n * depth) return null; + const data = img.data.bytes() orelse return null; + if (data.len != n * depth) return null; const out = gpa.alloc(u8, n * 4) catch return null; for (0..n) |i| { - const px = img.data[i * depth ..][0..depth]; + const px = data[i * depth ..][0..depth]; out[i * 4 ..][0..4].* = switch (depth) { 3 => .{ px[0], px[1], px[2], 255 }, 2 => .{ px[0], px[0], px[0], px[1] }, diff --git a/src/builtins.zig b/src/builtins.zig index f73c5982..d9cef8c9 100644 --- a/src/builtins.zig +++ b/src/builtins.zig @@ -98,11 +98,11 @@ fn isEnabled(comptime T: type) bool { /// word that is one here, or in no build. pub fn absentWhy(name: []const u8) ?[]const u8 { @setEvalBranchQuota(20000); - inline for (@typeInfo(@This()).@"struct".decls) |d| { - if (comptime @TypeOf(@field(@This(), d.name)) == type) { - const T = @field(@This(), d.name); + inline for (@typeInfo(@This()).@"struct".decl_names) |d| { + if (comptime @TypeOf(@field(@This(), d)) == type) { + const T = @field(@This(), d); if (comptime @typeInfo(T) == .@"struct" and @hasDecl(T, "run") and !isEnabled(T)) { - if (std.mem.eql(u8, d.name, name)) return if (@hasDecl(T, "gui_only")) "GUI-only" else "not in this build"; + if (std.mem.eql(u8, d, name)) return if (@hasDecl(T, "gui_only")) "GUI-only" else "not in this build"; } } } @@ -112,12 +112,12 @@ pub fn absentWhy(name: []const u8) ?[]const u8 { fn manualBuiltinCount() comptime_int { comptime { var count = 0; - for (@typeInfo(@This()).@"struct".decls) |d| { - if (@TypeOf(@field(@This(), d.name)) != type) continue; - const T = @field(@This(), d.name); + for (@typeInfo(@This()).@"struct".decl_names) |d| { + if (@TypeOf(@field(@This(), d)) != type) continue; + const T = @field(@This(), d); if (@typeInfo(T) != .@"struct" or !@hasDecl(T, "run") or !isEnabled(T)) continue; if (@TypeOf(T.run) != fn (Ctx) void) - @compileError(d.name ++ ".run must have signature fn (Ctx) void"); + @compileError(d ++ ".run must have signature fn (Ctx) void"); count += 1; } return count; @@ -129,9 +129,9 @@ fn manualBuiltinList() [manualBuiltinCount()]type { @setEvalBranchQuota(4000); var list: [manualBuiltinCount()]type = undefined; var count = 0; - for (@typeInfo(@This()).@"struct".decls) |d| { - if (@TypeOf(@field(@This(), d.name)) != type) continue; - const T = @field(@This(), d.name); + for (@typeInfo(@This()).@"struct".decl_names) |d| { + if (@TypeOf(@field(@This(), d)) != type) continue; + const T = @field(@This(), d); if (@typeInfo(T) != .@"struct" or !@hasDecl(T, "run") or !isEnabled(T)) continue; list[count] = T; count += 1; @@ -317,7 +317,7 @@ test "Exit over a ctl write or a click names every pane it asks about, a second first.file.?.saved_hash = 0; // edited: what it had is not what it has p.newScratchBelow(p.active); const second = p.panes[p.active].?; - panes.File.setContent(p, &second.file.?, try std.testing.allocator.dupe(u8, "x" ** 120)); + panes.File.setContent(p, &second.file.?, try std.testing.allocator.dupe(u8, &@as([120]u8, @splat('x')))); try std.testing.expect(second.file.?.revision != second.file.?.saved_revision); // A ctl write, or a click through exec (ctl.captured). if (clicked) p.fs.capturing = true else p.fs.no_prompt = true; @@ -341,7 +341,7 @@ test "Exit over a ctl write or a click names every pane it asks about, a second try std.testing.expect(noticed); // Edited since: only that one is named again (acme's rule). p.fs.failure_len = 0; - panes.File.setContent(p, &second.file.?, try std.testing.allocator.dupe(u8, "y" ** 120)); + panes.File.setContent(p, &second.file.?, try std.testing.allocator.dupe(u8, &@as([120]u8, @splat('y')))); try std.testing.expect(p.executeBuiltinLine(p.active, "Exit")); try std.testing.expect(!p.quit); const again = p.fs.failure[0..p.fs.failure_len]; diff --git a/src/colors.zig b/src/colors.zig index 379d1301..dd0d8938 100644 --- a/src/colors.zig +++ b/src/colors.zig @@ -205,7 +205,7 @@ const name_tint_chroma: f32 = 0.06; /// ink where that hue holds, the name reads on its ground (nameTintFloor) /// and it stands off the ink. Null when no colour of the theme will do. fn derivedNameTint(th: *const Theme, ink: [3]u8, ground: [3]u8) ?[3]u8 { - const pal = th.palette orelse [_][3]u8{th.kw} ** 16; + const pal = th.palette orelse @as([16][3]u8, @splat(th.kw)); const sources = [_][3]u8{ th.kw, pal[4], pal[5], pal[6], pal[3], pal[2], pal[1], th.num, th.str, th.box } ++ [_][3]u8{ th.column_box orelse th.num, th.box_dirty orelse th.num, th.sel_bg, th.search_bg orelse th.num } ++ [_][3]u8{ th.diagnostic_info orelse th.num, th.diagnostic_hint orelse th.num, th.diagnostic_warning orelse th.num } ++ @@ -468,28 +468,29 @@ const curated = struct { pub const dark = @import("themes/dark.zig"); }; -fn fold(comptime C: type) [@typeInfo(C).@"struct".decls.len]Theme { +fn fold(comptime C: type) [@typeInfo(C).@"struct".decl_names.len]Theme { comptime { @setEvalBranchQuota(400000); - var out: [@typeInfo(C).@"struct".decls.len]Theme = undefined; - for (@typeInfo(C).@"struct".decls, 0..) |d, i| { + var out: [@typeInfo(C).@"struct".decl_names.len]Theme = undefined; + const theme_info = @typeInfo(Theme).@"struct"; + for (@typeInfo(C).@"struct".decl_names, 0..) |d, i| { var t: Theme = undefined; - const source = @field(C, d.name).theme; - for (@typeInfo(Theme).@"struct".fields) |f| { - @field(t, f.name) = if (f.type == ?Decor and @hasField(@TypeOf(source), f.name)) decor: { + const source = @field(C, d).theme; + for (theme_info.field_names, theme_info.field_types, theme_info.field_attrs) |name, T, attrs| { + @field(t, name) = if (T == ?Decor and @hasField(@TypeOf(source), name)) decor: { // A nested literal is folded field by field too. var decor: Decor = .{}; - const given = @field(source, f.name); - for (@typeInfo(Decor).@"struct".fields) |g| if (@hasField(@TypeOf(given), g.name)) { - @field(decor, g.name) = @field(given, g.name); + const given = @field(source, name); + for (@typeInfo(Decor).@"struct".field_names) |g| if (@hasField(@TypeOf(given), g)) { + @field(decor, g) = @field(given, g); }; break :decor decor; - } else if (@hasField(@TypeOf(source), f.name)) - @field(source, f.name) - else if (f.default_value_ptr) |ptr| - @as(*const f.type, @ptrCast(@alignCast(ptr))).* + } else if (@hasField(@TypeOf(source), name)) + @field(source, name) + else if (attrs.defaultValue(T)) |value| + value else - @compileError("theme " ++ d.name ++ " is missing " ++ f.name); + @compileError("theme " ++ d ++ " is missing " ++ name); } out[i] = t; } @@ -501,7 +502,7 @@ fn fold(comptime C: type) [@typeInfo(C).@"struct".decls.len]Theme { /// takes: a faithful port (`dracula`) keeps the plain name, and helix's /// looser copy of it is still there as `dracula_helix` (the zed ones already /// carry `_zed`). -fn foldImports(comptime ours: anytype, comptime C: type) [@typeInfo(C).@"struct".decls.len]Theme { +fn foldImports(comptime ours: anytype, comptime C: type) [@typeInfo(C).@"struct".decl_names.len]Theme { comptime { @setEvalBranchQuota(400000); var out = fold(C); @@ -514,7 +515,7 @@ fn foldImports(comptime ours: anytype, comptime C: type) [@typeInfo(C).@"struct" pub const themes = fold(curated) ++ foldImports(fold(curated), @import("generated_themes")); /// The first `native_count` of `themes` are pardes's own; the rest imported. -pub const native_count = @typeInfo(curated).@"struct".decls.len; +pub const native_count = @typeInfo(curated).@"struct".decl_names.len; /// The picker's sections (`Themes`), in ring order, each running from /// the theme it names to the next section's; `NextColor` and `Theme` still @@ -677,8 +678,8 @@ pub const ChromeTheme = struct { pub fn interpolate(from: ChromeTheme, to: ChromeTheme, step: u16, steps: u16) ChromeTheme { var out: ChromeTheme = undefined; const t = @as(f32, @floatFromInt(@min(step, steps))) / @as(f32, @floatFromInt(@max(1, steps))); - inline for (@typeInfo(ChromeTheme).@"struct".fields) |field| - @field(out, field.name) = if (step == 0) @field(from, field.name) else if (step >= steps) @field(to, field.name) else mixOklab(@field(from, field.name), @field(to, field.name), t); + inline for (@typeInfo(ChromeTheme).@"struct".field_names) |name| + @field(out, name) = if (step == 0) @field(from, name) else if (step >= steps) @field(to, name) else mixOklab(@field(from, name), @field(to, name), t); return out; } }; @@ -801,14 +802,16 @@ pub fn loadThemeFile(p: *Pardes, generation: u32, bytes: []const u8, animate: bo themeFileError(p, request, error.ThemeFileTooLarge); return false; } - const source = p.gpa.dupeZ(u8, bytes) catch |err| { + const source = p.gpa.dupeSentinel(u8, bytes, 0) catch |err| { themeFileError(p, request, err); return false; }; defer p.gpa.free(source); - var diagnostics: std.zon.parse.Diagnostics = .{}; - defer diagnostics.deinit(p.gpa); - const parsed = std.zon.parse.fromSliceAlloc(Theme, p.gpa, source, &diagnostics, .{}) catch |err| { + // The parse's results live in `arena`; the theme kept owns only its name. + var arena: std.heap.ArenaAllocator = .init(p.gpa); + defer arena.deinit(); + var diagnostics: std.zon.parse.Diagnostics = undefined; + var parsed = std.zon.parse.fromSlice(Theme, .{ .gpa = p.gpa, .arena = arena.allocator(), .source = source, .diagnostics = &diagnostics }) catch |err| { if (err != error.ParseZon) themeFileError(p, request, err) else { // Which line, and what the parser wanted there. var why: [200]u8 = undefined; @@ -817,10 +820,13 @@ pub fn loadThemeFile(p: *Pardes, generation: u32, bytes: []const u8, animate: bo return false; }; if (parsed.name.len == 0 or parsed.name.len > 255) { - std.zon.parse.free(p.gpa, parsed); themeFileError(p, request, error.InvalidThemeName); return false; } + parsed.name = p.gpa.dupe(u8, parsed.name) catch |err| { + themeFileError(p, request, err); + return false; + }; const target_chrome = ChromeTheme.fromTheme(&parsed); if (animate and p.animate_theme_changes) @@ -829,7 +835,7 @@ pub fn loadThemeFile(p: *Pardes, generation: u32, bytes: []const u8, animate: bo p.chrome_animation.snap(target_chrome); const old = p.custom_theme; p.custom_theme = parsed; - if (old) |theme_value| std.zon.parse.free(p.gpa, theme_value); + if (old) |theme_value| p.gpa.free(theme_value.name); var settled: [limits.host_path_cap]u8 = undefined; @memcpy(settled[0..request.path.len], request.path); _ = p.theme_file_loaded.set(settled[0..request.path.len]); @@ -847,7 +853,7 @@ pub fn carryTheme(p: *Pardes, old: *const Pardes, index: bool) !void { const t = old.custom_theme orelse return; var copy = t; copy.name = try p.gpa.dupe(u8, t.name); - if (p.custom_theme) |mine| std.zon.parse.free(p.gpa, mine); + if (p.custom_theme) |mine| p.gpa.free(mine.name); p.custom_theme = copy; _ = p.theme_file_loaded.set(old.theme_file_loaded.get()); } @@ -931,7 +937,7 @@ fn likeness(theme_name: []const u8, name: []const u8) usize { in_order += 1; pos = at + 1; } - const inside: usize = if (name.len > 0 and std.ascii.indexOfIgnoreCase(theme_name, name) != null) name.len * 4 else 0; + const inside: usize = if (name.len > 0 and std.ascii.findIgnoreCase(theme_name, name) != null) name.len * 4 else 0; return prefix * 3 + in_order + inside; } @@ -952,7 +958,7 @@ pub fn setThemeIndex(p: *Pardes, index: usize) void { p.chrome_animation.snap(target_chrome); if (p.custom_theme) |theme_value| { p.custom_theme = null; - std.zon.parse.free(p.gpa, theme_value); + p.gpa.free(theme_value.name); } p.theme_file_loaded.clear(); if (p.theme_file_path.get().len > 0) { @@ -1264,10 +1270,12 @@ test "legacy ThemeFile documents inherit Pardes UI roles without new fields" { rest = rest[at + std.mem.indexOfScalar(u8, rest[at..], '}').? + 1 ..]; rest = std.mem.trimStart(u8, rest, " ,"); } - const source = try std.testing.allocator.dupeZ(u8, legacy.items); + const source = try std.testing.allocator.dupeSentinel(u8, legacy.items, 0); defer std.testing.allocator.free(source); - const parsed = try std.zon.parse.fromSliceAlloc(Theme, std.testing.allocator, source, null, .{}); - defer std.zon.parse.free(std.testing.allocator, parsed); + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + var diagnostics: std.zon.parse.Diagnostics = undefined; + const parsed = try std.zon.parse.fromSlice(Theme, .{ .gpa = std.testing.allocator, .arena = arena.allocator(), .source = source, .diagnostics = &diagnostics }); try std.testing.expectEqual(@as(?[3]u8, null), parsed.tag_active_bg); try std.testing.expectEqual(@as(?[3]u8, null), parsed.tag_name_fg); try std.testing.expectEqual(@as(?[3]u8, null), parsed.tag_active_name_fg); diff --git a/src/config.zig b/src/config.zig index 50009660..8166954d 100644 --- a/src/config.zig +++ b/src/config.zig @@ -2170,10 +2170,12 @@ pub const User = struct { defer gpa.free(one_path); const bytes = try std.Io.Dir.cwd().readFileAlloc(io, one_path, gpa, .limited(4096)); defer gpa.free(bytes); - const source = try gpa.dupeZ(u8, bytes); + const source = try gpa.dupeSentinel(u8, bytes, 0); defer gpa.free(source); - const parsed = try std.zon.parse.fromSliceAlloc(Sample, gpa, source, null, .{}); - defer std.zon.parse.free(gpa, parsed); + var arena: std.heap.ArenaAllocator = .init(gpa); + defer arena.deinit(); + var diagnostics: std.zon.parse.Diagnostics = undefined; + const parsed = try std.zon.parse.fromSlice(Sample, .{ .gpa = gpa, .arena = arena.allocator(), .source = source, .diagnostics = &diagnostics }); try std.testing.expectEqualStrings("one", parsed.name); try std.testing.expectEqual([3]u8{ 1, 2, 3 }, parsed.rgb); } @@ -2239,25 +2241,26 @@ const doc_typ = struct { fn hasChordField(T: type) bool { if (@typeInfo(T) != .array or @typeInfo(@typeInfo(T).array.child) != .@"struct") return false; - for (@typeInfo(@typeInfo(T).array.child).@"struct".fields) |f| if (f.type == Chord) return true; + for (@typeInfo(@typeInfo(T).array.child).@"struct".field_types) |F| if (F == Chord) return true; return false; } /// Bound somewhere in this file: a binding, a prefix or a key list. fn bound(c: Chord) bool { const config = @import("config.zig"); - inline for (@typeInfo(config).@"struct".decls) |d| { - const v = @field(config, d.name); + inline for (@typeInfo(config).@"struct".decl_names) |d| { + const v = @field(config, d); const T = @TypeOf(v); if (T == []const Chord) { for (v) |b| if (same(b, c)) return true; } else if (T == comptime_int or T == u21 or T == u8) { // a prefix or a bare key; only the tty toggle carries Ctrl - const plain = !c.alt and !c.shift and (!c.ctrl or comptime std.mem.indexOf(u8, d.name, "toggle") != null); + const plain = !c.alt and !c.shift and (!c.ctrl or comptime std.mem.indexOf(u8, d, "toggle") != null); if (plain and v >= 0x20 and v < 0x7f and v == c.cp) return true; } else if (comptime hasChordField(T)) { - for (v) |e| inline for (@typeInfo(@TypeOf(e)).@"struct".fields) |f| - if (f.type == Chord and same(@field(e, f.name), c)) return true; + const info = @typeInfo(@TypeOf(v[0])).@"struct"; + for (v) |e| inline for (info.field_names, info.field_types) |name, F| + if (F == Chord and same(@field(e, name), c)) return true; } } return false; diff --git a/src/detached/client.zig b/src/detached/client.zig index 69ab2fdd..cf1842d9 100644 --- a/src/detached/client.zig +++ b/src/detached/client.zig @@ -1182,12 +1182,12 @@ test "detached session: a frontend is never asked to fork, write, or watch" { // One: the union a frontend decodes into has no other variant. Named // rather than counted, so re-adding `spawn` fails with the name in it. - const fields = @typeInfo(wire.ServerMsg).@"union".fields; - inline for (fields) |f| { + const fields = @typeInfo(wire.ServerMsg).@"union".field_names; + inline for (fields) |name| { for (allowed) |ok| { - if (std.mem.eql(u8, f.name, ok)) break; + if (std.mem.eql(u8, name, ok)) break; } else { - std.debug.print("ServerMsg.{s} is not an effect a frontend may perform\n", .{f.name}); + std.debug.print("ServerMsg.{s} is not an effect a frontend may perform\n", .{name}); return error.MachineLocalEffectOnTheWire; } } diff --git a/src/detached/wire.zig b/src/detached/wire.zig index c9d9b578..f1b7a1b3 100644 --- a/src/detached/wire.zig +++ b/src/detached/wire.zig @@ -20,9 +20,10 @@ const chrome_layout: u64 = 0x5e758b47fb0cf8da; comptime { @setEvalBranchQuota(10_000); var hash = std.hash.Fnv1a_64.init(); - for (@typeInfo(pardes.Chrome).@"struct".fields) |field| { - hash.update(field.name); - hash.update(@typeName(field.type)); + const info = @typeInfo(pardes.Chrome).@"struct"; + for (info.field_names, info.field_types) |name, T| { + hash.update(name); + hash.update(@typeName(T)); } if (hash.final() != chrome_layout) @compileError(std.fmt.comptimePrint("pardes.Chrome changed (layout 0x{x}): bump wire.version, then chrome_layout", .{hash.final()})); } @@ -285,21 +286,22 @@ pub const Frame = struct { region.clip > region.rect.w or region.thumb_y > region.rect.h or region.thumb_h > region.rect.h - region.thumb_y) return error.BadValue; regions.appendAssumeCapacity(region); } - inline for (@typeInfo(pardes.Chrome).@"struct".fields) |field| { - const rgb = &@field(chrome, field.name); - if (field.type == ?[3]u8) { + const info = @typeInfo(pardes.Chrome).@"struct"; + inline for (info.field_names, info.field_types) |name, T| { + const rgb = &@field(chrome, name); + if (T == ?[3]u8) { if (try r.getBool()) { rgb.* = .{ 0, 0, 0 }; for (&rgb.*.?) |*channel| channel.* = try r.getByte(); } - } else if (field.type == u8) { + } else if (T == u8) { rgb.* = try r.getByte(); - } else if (field.type == u32) { + } else if (T == u32) { rgb.* = try r.getU32(); - } else if (field.type == f32) { + } else if (T == f32) { rgb.* = @bitCast(try r.getU32()); if (!std.math.isFinite(rgb.*)) return error.BadValue; - } else if (field.type == [8]f32) { + } else if (T == [8]f32) { for (rgb) |*value| { value.* = @bitCast(try r.getU32()); if (!std.math.isFinite(value.*)) return error.BadValue; @@ -781,7 +783,7 @@ pub fn layersBound(layers: []const pardes.Layer, tags: []const pardes.Layer, reg const region_len = 1 + 1 + 4 + 8 + 1 + 2 + 2 + 1 + 2 + 4 + 4; /// The palette: each colour three bytes, a theme's optional ones a flag /// before them. -const chrome_len = @typeInfo(pardes.Chrome).@"struct".fields.len * 4 + 8 * 4; +const chrome_len = @typeInfo(pardes.Chrome).@"struct".field_names.len * 4 + 8 * 4; pub fn encodeFrameLayers(out: []u8, cols: u16, rows: u16, cursor: ?Cursor, pointer_shape: pardes.Surface.PointerShape, cells: []const pardes.Cell, prev: []const pardes.Cell, layers: []const pardes.Layer, tags: []const pardes.Layer, regions: []const pardes.Region, chrome: pardes.Chrome) Error![]const u8 { // The protocol's ceiling, enforced by the ENCODER too, and BEFORE the @@ -865,18 +867,19 @@ pub fn encodeFrameLayers(out: []u8, cols: u16, rows: u16, cursor: ?Cursor, point try w.putU32(@bitCast(region.lift)); try w.putU32(@bitCast(region.line)); } - inline for (@typeInfo(pardes.Chrome).@"struct".fields) |field| { - const rgb = @field(chrome, field.name); - if (field.type == ?[3]u8) { + const info = @typeInfo(pardes.Chrome).@"struct"; + inline for (info.field_names, info.field_types) |name, T| { + const rgb = @field(chrome, name); + if (T == ?[3]u8) { try w.putBool(rgb != null); if (rgb) |value| for (value) |channel| try w.putByte(channel); - } else if (field.type == u8) { + } else if (T == u8) { try w.putByte(rgb); - } else if (field.type == u32) { + } else if (T == u32) { try w.putU32(rgb); - } else if (field.type == f32) { + } else if (T == f32) { try w.putU32(@bitCast(rgb)); - } else if (field.type == [8]f32) { + } else if (T == [8]f32) { for (rgb) |value| try w.putU32(@bitCast(value)); } else for (rgb) |channel| try w.putByte(channel); } diff --git a/src/draw.zig b/src/draw.zig index b35d55e8..e6420ed4 100644 --- a/src/draw.zig +++ b/src/draw.zig @@ -1598,7 +1598,7 @@ test "a tag of three rows has its grip on the first, and band under it that stil test "place puts every part where the painters and layers put it, in every layout" { const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 100, .rows = 30 }); defer p.deinit(); - _ = try p.setTestFile("placed\n" ** 80); + _ = try p.setTestFile(std.mem.asBytes(&@as([80][7]u8, @splat("placed\n".*)))); p.newColumn(0); p.newScratchIn(0, p.activeColumn().?); p.newScratchBelow(0); @@ -1713,7 +1713,7 @@ test "a notice wider than its band, as a shader's compile error is, draws its en _ = try p.setTestFile("text\n"); var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); defer arena.deinit(); - const long = "Shader /home/someone/shaders/test_shadertoy_invalid.glsl: error: Linking fragment stage: No function definition (body) found: " ** 3; + const long = std.mem.asBytes(&@as([3][126]u8, @splat("Shader /home/someone/shaders/test_shadertoy_invalid.glsl: error: Linking fragment stage: No function definition (body) found: ".*))); for ([_][]const u8{ "Msg " ++ long, "" }) |line| { // The Msg builtin, and the path a failed compile takes (Post.zig). if (line.len > 0) try std.testing.expect(p.executeBuiltinLine(p.active, line)) else p.setMessage(p.active, long); @@ -1952,7 +1952,7 @@ test "the focused cursor glides a jump, lands a step at once, and is exact at re if (!builtins.capabilities.lift) return error.SkipZigTest; const p = try Pardes.init(std.testing.allocator, .{ .cols = 80, .rows = 30 }); defer p.deinit(); - _ = try p.setTestFile("some text on a line\n" ** 20); + _ = try p.setTestFile(std.mem.asBytes(&@as([20][20]u8, @splat("some text on a line\n".*)))); p.settings.cursor_blink = false; var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); defer arena.deinit(); @@ -2078,7 +2078,7 @@ test "a terminal's cursor lands with scrolling output, never gliding against it" defer arena.deinit(); const ms = std.time.ns_per_ms; var now: u64 = std.time.ns_per_s; - p.update(.{ .output = .{ .pane = @intCast(term), .bytes = "line\r\n" ** 20 ++ "$ some command typed" } }); + p.update(.{ .output = .{ .pane = @intCast(term), .bytes = std.mem.asBytes(&@as([20][6]u8, @splat("line\r\n".*))) ++ "$ some command typed" } }); p.advance(now); _ = try p.render(arena.allocator()); // Enter: three lines of output scroll up, the cursor to a new prompt. @@ -2101,10 +2101,10 @@ test "a monkey over notices, prompts, tags and tiny panes at a gui's metrics nev const random = prng.random(); const p = try Pardes.init(std.testing.allocator, .{ .cols = 80, .rows = 24 }); defer p.deinit(); - _ = try p.setTestFile("fuzz\n\u{754c}\u{754c} wide\n" ** 20); + _ = try p.setTestFile(std.mem.asBytes(&@as([20][17]u8, @splat("fuzz\n\u{754c}\u{754c} wide\n".*)))); var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); defer arena.deinit(); - const words = [_][]const u8{ "error:", "\u{754c}", "x", "Shader /tmp/a.glsl:", "e\u{301}", "\t", "long-" ** 20, " " }; + const words = [_][]const u8{ "error:", "\u{754c}", "x", "Shader /tmp/a.glsl:", "e\u{301}", "\t", std.mem.asBytes(&@as([20][5]u8, @splat("long-".*))), " " }; const commands = [_][]const u8{ "New", "Newcol", "Collapse", "Tagbottom", "TreeContext", "Wrap", "Find", "Del", "FocusTint", "Debug" }; var text: std.ArrayListUnmanaged(u8) = .empty; defer text.deinit(std.testing.allocator); @@ -2143,7 +2143,7 @@ test "a monkey over notices, prompts, tags and tiny panes at a gui's metrics nev // A tag of several rows. 5 => if (p.panes[p.active]) |pane| { text.clearRetainingCapacity(); - for (0..random.uintAtMost(usize, 5)) |_| try text.appendSlice(std.testing.allocator, if (random.boolean()) " Look\nmore \u{754c}" else "\n" ++ "x" ** 150); + for (0..random.uintAtMost(usize, 5)) |_| try text.appendSlice(std.testing.allocator, if (random.boolean()) " Look\nmore \u{754c}" else "\n" ++ &@as([150]u8, @splat('x'))); if (pane.tag.own) |own| std.testing.allocator.free(own); pane.tag.own = try std.testing.allocator.dupe(u8, text.items); }, @@ -2173,7 +2173,7 @@ test "a wide glyph cut by a tag's or a notice's edge is joined into the grid as defer arena.deinit(); const pane = p.panes[p.active].?; // Both alignments, so one of them puts a wide glyph across each edge. - for ([_][]const u8{ "\u{754c}" ** 30, "x" ++ "\u{754c}" ** 30 }) |wide| { + for ([_][]const u8{ std.mem.asBytes(&@as([30][3]u8, @splat("\u{754c}".*))), "x" ++ std.mem.asBytes(&@as([30][3]u8, @splat("\u{754c}".*))) }) |wide| { if (pane.tag.own) |own| std.testing.allocator.free(own); pane.tag.own = try std.testing.allocator.dupe(u8, wide); var message: [200]u8 = undefined; @@ -2201,7 +2201,7 @@ test "a body with context rows is painted once, and the grid's rows are what a p if (comptime !@import("syntax.zig").enabled) return error.SkipZigTest; const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 60, .rows = 16 }); defer p.deinit(); - const pane = try p.setTestFile("pub const Box = struct {\n pub fn run() void {\n" ++ (" // body line\n" ** 30) ++ " }\n};\n"); + const pane = try p.setTestFile("pub const Box = struct {\n pub fn run() void {\n" ++ (std.mem.asBytes(&@as([30][21]u8, @splat(" // body line\n".*)))) ++ " }\n};\n"); p.gpa.free(pane.file.?.path); pane.file.?.path = try p.gpa.dupe(u8, "/test.zig"); if (!panes.File.supportsContext(pane)) return error.SkipZigTest; @@ -2250,7 +2250,7 @@ test "a body with context rows is painted once, and the grid's rows are what a p /// Two columns, the file in the left one and a shell in the right, the /// right one focused with its cursor settled. fn twoColumns(p: *Pardes, arena: *std.heap.ArenaAllocator) !void { - _ = try p.setTestFile("some text on a line\n" ** 6); + _ = try p.setTestFile(std.mem.asBytes(&@as([6][20]u8, @splat("some text on a line\n".*)))); _ = try p.newShell(1, ""); try std.testing.expect(layout.splitColumn(p, 0, 1, false)); p.sync(); @@ -2386,7 +2386,7 @@ test "a pane focus reaches brightens on the same spring the one it leaves dims o if (!builtins.capabilities.lift) return error.SkipZigTest; const p = try Pardes.init(std.testing.allocator, .{ .cols = 80, .rows = 24 }); defer p.deinit(); - _ = try p.setTestFile("some text on a line\n" ** 4); + _ = try p.setTestFile(std.mem.asBytes(&@as([4][20]u8, @splat("some text on a line\n".*)))); p.newScratchBelow(0); p.settings.inactive_dim = 40; p.settings.motion = .smooth; diff --git a/src/dump.zig b/src/dump.zig index 402918c4..545d09ec 100644 --- a/src/dump.zig +++ b/src/dump.zig @@ -421,9 +421,9 @@ pub const Parsed = struct { pub fn check(gpa: std.mem.Allocator, bytes: []const u8, why: []u8) !void { var arena: std.heap.ArenaAllocator = .init(gpa); defer arena.deinit(); - const source = try arena.allocator().dupeZ(u8, bytes); - var diag: std.zon.parse.Diagnostics = .{}; - const state = std.zon.parse.fromSliceAlloc(State, arena.allocator(), source, &diag, .{ .free_on_error = false }) catch |err| { + const source = try arena.allocator().dupeSentinel(u8, bytes, 0); + var diag: std.zon.parse.Diagnostics = undefined; + const state = std.zon.parse.fromSlice(State, .{ .gpa = gpa, .arena = arena.allocator(), .source = source, .diagnostics = &diag }) catch |err| { const said = pardes.Messages.zonWhy(&diag, why[0 .. why.len - 1]); if (said.ptr != why.ptr) @memcpy(why[0..said.len], said); why[said.len] = 0; @@ -436,21 +436,13 @@ pub fn readZon(gpa: std.mem.Allocator, bytes: []const u8, label: []const u8) !Pa var parsed: Parsed = .{ .value = undefined, .arena = .init(gpa) }; errdefer parsed.deinit(); const arena = parsed.arena.allocator(); - const source = try gpa.dupeZ(u8, bytes); + const source = try gpa.dupeSentinel(u8, bytes, 0); defer gpa.free(source); - parsed.value = if (builtin.os.tag == .emscripten or builtin.os.tag == .freestanding) - std.zon.parse.fromSliceAlloc(State, arena, source, null, .{ .free_on_error = false }) catch |err| { - if (err == error.ParseZon) log.err("parse dump {s}: {s}", .{ label, @errorName(err) }); - return err; - } - else blk: { - var diag: std.zon.parse.Diagnostics = .{}; - defer diag.deinit(arena); - break :blk std.zon.parse.fromSliceAlloc(State, arena, source, &diag, .{ .free_on_error = false }) catch |err| { - if (err == error.ParseZon) log.err("parse dump {s}: {f}", .{ label, diag }); - return err; - }; + var diag: std.zon.parse.Diagnostics = undefined; + parsed.value = std.zon.parse.fromSlice(State, .{ .gpa = gpa, .arena = arena, .source = source, .diagnostics = &diag }) catch |err| { + if (err == error.ParseZon) log.err("{f}", .{diag.fmt(label)}); + return err; }; try validate(parsed.value); return parsed; diff --git a/src/esp32p4.zig b/src/esp32p4.zig index 6772e75d..ed18efd9 100644 --- a/src/esp32p4.zig +++ b/src/esp32p4.zig @@ -506,7 +506,7 @@ fn apply(c: *pardes.Pardes, ev: vaxis.Event) void { c.update(.pointer_leave); dirty = true; }, - .focus_in, .mouse_leave => {}, + .focus_in, .mouse_leave, .cursor_position => {}, // Capability replies. vaxis's own Loop sets these fields directly (`Loop.zig:377-403`); // with no Loop, this is where they land. DA1 is the terminator: every terminal answers it // last, so it is the signal that the whole handshake is in and the detected features can be diff --git a/src/esp32p4/input_rescue.zig b/src/esp32p4/input_rescue.zig index ba6974d2..d7556d46 100644 --- a/src/esp32p4/input_rescue.zig +++ b/src/esp32p4/input_rescue.zig @@ -245,7 +245,7 @@ test "a long transmit does not lose the input that arrives during it" { defer port.sent.deinit(std.testing.allocator); var ring: Ring = .{}; - const frame = "\x1b[1;1H" ++ "x" ** 400; + const frame = "\x1b[1;1H" ++ &@as([400]u8, @splat('x')); try std.testing.expectEqual(@as(u32, 0), pump(&port, &ring, frame, 1_000_000)); // Every output byte went out, in order. diff --git a/src/esp32p4/selftest.zig b/src/esp32p4/selftest.zig index 97b43059..19b71e90 100644 --- a/src/esp32p4/selftest.zig +++ b/src/esp32p4/selftest.zig @@ -270,7 +270,7 @@ export fn zig_main() noreturn { const typed = "the quick brown fox jumps over the lazy dog, and then some more besides"; var port: FakePort = .{ .tx_cap = 2, .incoming = typed }; var ring: input_rescue.Ring = .{}; - const frame = "\x1b[1;1H" ++ "x" ** 300; + const frame = "\x1b[1;1H" ++ &@as([300]u8, @splat('x')); const abandoned = input_rescue.pump(&port, &ring, frame, 1_000_000); check("the frame went out whole", abandoned == 0 and port.sent == frame.len); diff --git a/src/fs.zig b/src/fs.zig index fb76cee3..061d4225 100644 --- a/src/fs.zig +++ b/src/fs.zig @@ -677,7 +677,7 @@ pub fn statPath(io: std.Io, path: []const u8, options: std.Io.Dir.StatFileOption } test "a path with a part over 255 bytes is NameTooLong, never a panic" { - const long = "/tmp/" ++ "x" ** 300 ++ "/f"; + const long = "/tmp/" ++ &@as([300]u8, @splat('x')) ++ "/f"; try std.testing.expectError(error.NameTooLong, statPath(std.testing.io, long, .{})); } @@ -1152,7 +1152,7 @@ pub fn find(arena: std.mem.Allocator, dir: []const u8, pat: []const u8, out: []u notes.skipped += 1; continue; }) orelse break; - if (std.ascii.indexOfIgnoreCase(e.basename, pat) != null) { + if (std.ascii.findIgnoreCase(e.basename, pat) != null) { hits[hits_len] = try arena.dupe(u8, e.path); hits_len += 1; } @@ -1167,7 +1167,7 @@ pub fn find(arena: std.mem.Allocator, dir: []const u8, pat: []const u8, out: []u } else { for (sources) |s| { if (hits_len >= hits.len) break; - if (std.ascii.indexOfIgnoreCase(std.fs.path.basename(s.path), pat) != null) { + if (std.ascii.findIgnoreCase(std.fs.path.basename(s.path), pat) != null) { hits[hits_len] = s.path; hits_len += 1; } @@ -1201,7 +1201,7 @@ fn grepText(path: []const u8, text: []const u8, pat: []const u8, out: []u8, budg while (it.next()) |raw| { line += 1; if (result.hits >= budget) break; - const at = std.ascii.indexOfIgnoreCase(raw, pat) orelse continue; + const at = std.ascii.findIgnoreCase(raw, pat) orelse continue; const ln = std.mem.trimEnd(u8, raw, " \t\r"); var cut = @min(ln.len, 200); while (cut > 0 and cut < ln.len and ln[cut] & 0xc0 == 0x80) cut -= 1; diff --git a/src/gui/Post.zig b/src/gui/Post.zig index fc256135..8d0e14d9 100644 --- a/src/gui/Post.zig +++ b/src/gui/Post.zig @@ -610,13 +610,13 @@ const GhosttyUniforms = extern struct { }; test "the uniform block is ghostty's, offset for offset, and the prefix names it in that order" { - const ours = @typeInfo(Uniforms).@"struct".fields; - const theirs = @typeInfo(GhosttyUniforms).@"struct".fields; - try std.testing.expectEqual(theirs.len, ours.len); + const ours = @typeInfo(Uniforms).@"struct"; + const theirs = @typeInfo(GhosttyUniforms).@"struct"; + try std.testing.expectEqual(theirs.field_names.len, ours.field_names.len); try std.testing.expectEqual(@sizeOf(GhosttyUniforms), @sizeOf(Uniforms)); - inline for (ours, theirs) |a, b| { - try std.testing.expectEqual(@offsetOf(GhosttyUniforms, b.name), @offsetOf(Uniforms, a.name)); - try std.testing.expectEqual(b.type, a.type); + inline for (ours.field_names, ours.field_types, theirs.field_names, theirs.field_types) |a, a_type, b, b_type| { + try std.testing.expectEqual(@offsetOf(GhosttyUniforms, b), @offsetOf(Uniforms, a)); + try std.testing.expectEqual(b_type, a_type); } // By NAME: iSelectionForegroundColor sits where ghostty's Zig says // selection_background, which is where its GLSL puts the foreground. @@ -633,7 +633,7 @@ test "the uniform block is ghostty's, offset for offset, and the prefix names it .{ "vec3", "iBackgroundColor" }, .{ "vec3", "iForegroundColor" }, .{ "vec3", "iCursorColor" }, .{ "vec3", "iCursorText" }, .{ "vec3", "iSelectionForegroundColor" }, .{ "vec3", "iSelectionBackgroundColor" }, }; - try std.testing.expectEqual(ours.len, glsl.len); + try std.testing.expectEqual(ours.field_names.len, glsl.len); // Its three blocks (Globals, Palette, Colors) read as one, in order. const start = std.mem.indexOf(u8, prefix, "uniform Globals {").?; const end = std.mem.indexOf(u8, prefix, "uniform PardesPost {").?; diff --git a/src/gui/gui.zig b/src/gui/gui.zig index 5a026664..b8687fd3 100644 --- a/src/gui/gui.zig +++ b/src/gui/gui.zig @@ -25,11 +25,7 @@ const ninep_io = @import("../9p_io.zig"); const detached_client = @import("../detached/client.zig"); const tracy = @import("../tracy.zig"); -pub const c = @cImport({ - @cDefine("SDL_DISABLE_OLD_NAMES", "1"); - @cInclude("SDL3/SDL.h"); - @cInclude("font.h"); -}); +pub const c = @import("gui_c"); // SDL3 and font.h, translated by build.zig const host_io = @import("../host_io.zig"); extern "c" fn setenv(name: [*:0]const u8, value: [*:0]const u8, overwrite: c_int) c_int; @@ -4806,7 +4802,7 @@ fn dumpThemes(ctx: ?*anyopaque, pane: u8) void { } fn putClipboard(gpa: std.mem.Allocator, text: []const u8) void { - const z = gpa.dupeZ(u8, text) catch return; + const z = gpa.dupeSentinel(u8, text, 0) catch return; defer gpa.free(z); _ = c.SDL_SetClipboardText(z.ptr); } @@ -5131,7 +5127,7 @@ test "a wheel over codex in a terminal reaches its pty as the mouse reports it a wheelAt(&g, &in, .{ .y = 1, .integer_y = 1 }, mc); try std.testing.expectEqualStrings("\x1b[<64;6;4M", try Sent.take(core, &sent)); wheelAt(&g, &in, .{ .y = -3, .integer_y = -3 }, mc); - try std.testing.expectEqualStrings("\x1b[<65;6;4M" ** 3, try Sent.take(core, &sent)); + try std.testing.expectEqualStrings(std.mem.asBytes(&@as([3][10]u8, @splat("\x1b[<65;6;4M".*))), try Sent.take(core, &sent)); try std.testing.expectEqual(@as(i32, 0), g.scroll_notch); try std.testing.expect(g.scroll_pane == null); // A touchpad's fractions add up to a turn. @@ -7157,7 +7153,7 @@ test "every pixel of a grip column is band, button or ring, and the button sits const gpa = std.testing.allocator; const core = try pardes.Pardes.init(gpa, .{ .cols = 60, .rows = 20 }); defer core.deinit(); - const pane = try core.setTestFile("text\n" ** 60); + const pane = try core.setTestFile(std.mem.asBytes(&@as([60][5]u8, @splat("text\n".*)))); pane.tag.own = try gpa.dupe(u8, "second\nthird"); core.newScratchBelow(0); for ([_]struct { w: u32, h: u32, tag: u32 }{ .{ .w = 10, .h = 20, .tag = 12 }, .{ .w = 17, .h = 35, .tag = 30 }, .{ .w = 9, .h = 19, .tag = 15 }, .{ .w = 12, .h = 24, .tag = 24 } }) |m| for ([_]bool{ false, true }) |bottom| for ([_]usize{ 0, 1 }) |focus| for ([_]bool{ false, true }) |dirty| { @@ -10156,7 +10152,7 @@ test "the selection glows round its block, on the body only, fading in over 100 const gpa = std.testing.allocator; const core = try pardes.Pardes.init(gpa, .{ .cols = 80, .rows = 24 }); defer core.deinit(); - _ = try core.setTestFile("some text on a line\n" ** 30); + _ = try core.setTestFile(std.mem.asBytes(&@as([30][20]u8, @splat("some text on a line\n".*)))); core.settings.selection_glow = true; pardes.test_api.sync(core); const s = try core.render(core.scratch.allocator()); @@ -10206,7 +10202,7 @@ test "a hovered word glows along its foot, never over the cursor, fading in over const gpa = std.testing.allocator; const core = try pardes.Pardes.init(gpa, .{ .cols = 80, .rows = 24 }); defer core.deinit(); - _ = try core.setTestFile("some text on a line\n" ** 30); + _ = try core.setTestFile(std.mem.asBytes(&@as([30][20]u8, @splat("some text on a line\n".*)))); core.settings.hover_glow = true; pardes.test_api.sync(core); const s = try core.render(core.scratch.allocator()); @@ -10256,7 +10252,7 @@ test "occlusion shades each body's edges, inside it, never a tag, a grip or the const gpa = std.testing.allocator; const core = try pardes.Pardes.init(gpa, .{ .cols = 80, .rows = 24 }); defer core.deinit(); - _ = try core.setTestFile("some text on a line\n" ** 30); + _ = try core.setTestFile(std.mem.asBytes(&@as([30][20]u8, @splat("some text on a line\n".*)))); core.settings.occlusion = true; pardes.test_api.sync(core); const s = try core.render(core.scratch.allocator()); @@ -10295,7 +10291,7 @@ test "a body tells its first line, and lapis's dots under it move a quarter as f const gpa = std.testing.allocator; const core = try pardes.Pardes.init(gpa, .{ .cols = 80, .rows = 24 }); defer core.deinit(); - const pane = try core.setTestFile("line\n" ** 80); + const pane = try core.setTestFile(std.mem.asBytes(&@as([80][5]u8, @splat("line\n".*)))); pane.scrollBy(8); try std.testing.expect(core.executeBuiltinLine(0, "Theme lapis")); core.settings.parallax = true; diff --git a/src/host_io.zig b/src/host_io.zig index a90c903d..d789a77d 100644 --- a/src/host_io.zig +++ b/src/host_io.zig @@ -172,7 +172,7 @@ pub const Lsp = struct { const declared_path = if (file) |f| f.path else ""; const path = try gpa.dupe(u8, filesystem.localPath(declared_path) orelse declared_path); errdefer gpa.free(path); - const source = try gpa.dupeZ(u8, if (file) |f| f.content else ""); + const source = try gpa.dupeSentinel(u8, if (file) |f| f.content else "", 0); errdefer gpa.free(source); const arg = try gpa.dupe(u8, req.arg); errdefer gpa.free(arg); @@ -210,7 +210,7 @@ pub const Lsp = struct { if (f.output != null) continue; const local = filesystem.localPath(f.path) orelse continue; const other_path = try gpa.dupe(u8, local); - const other_source = gpa.dupeZ(u8, f.content) catch |err| { + const other_source = gpa.dupeSentinel(u8, f.content, 0) catch |err| { gpa.free(other_path); return err; }; @@ -785,7 +785,7 @@ pub const Shell = struct { var dir_buf: [4096]u8 = undefined; const dir = dir_buf[0..try tmp.dir.realPath(std.testing.io, &dir_buf)]; var path: [4200:0]u8 = undefined; - const p = try std.fmt.bufPrintZ(&path, "{s}/mysh", .{dir}); + const p = try std.fmt.bufPrintSentinel(&path, "{s}/mysh", .{dir}, 0); try std.testing.expectEqual(Family.bash, familyOf(p.ptr)); try std.testing.expectEqual(Family.none, familyOf("/bin/sh")); } @@ -1662,7 +1662,7 @@ pub fn forkShell( test "shell spawn rejects invalid directories before creating a child" { const rcs: Shell.PromptFiles = .{}; try std.testing.expectError(error.InvalidPath, forkShell(null, 0, &rcs, "/bin/sh", "/tmp\x00/ignored", 24, 80, null)); - const too_long = [_]u8{'x'} ** 4096; + const too_long = @as([4096]u8, @splat('x')); try std.testing.expectError(error.NameTooLong, forkShell(null, 0, &rcs, "/bin/sh", &too_long, 24, 80, null)); var tmp = std.testing.tmpDir(.{}); @@ -1675,7 +1675,7 @@ test "shell spawn rejects invalid directories before creating a child" { try std.testing.expectError(error.NotDir, forkShell(null, 0, &rcs, "/bin/sh", file, 24, 80, null)); const explicit_file = try std.fmt.bufPrint(&path_buf, "/n/os{s}/file", .{directory}); try std.testing.expectError(error.NotDir, forkShell(null, 0, &rcs, "/bin/sh", explicit_file, 24, 80, null)); - const missing = try std.fmt.bufPrint(&path_buf, "{s}/missing/" ++ ("child/" ** 50), .{directory}); + const missing = try std.fmt.bufPrint(&path_buf, "{s}/missing/" ++ (std.mem.asBytes(&@as([50][6]u8, @splat("child/".*)))), .{directory}); try std.testing.expect(missing.len > 256); try std.testing.expectError(error.FileNotFound, forkShell(null, 0, &rcs, "/bin/sh", missing, 24, 80, null)); } @@ -1720,7 +1720,7 @@ test "shell spawn uses an explicit OS directory longer than 256 bytes" { if (!haveFile("/bin/sh")) return error.SkipZigTest; var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); - const sub_path = "nested-directory-with-more-than-forty-characters/" ** 7; + const sub_path = std.mem.asBytes(&@as([7][49]u8, @splat("nested-directory-with-more-than-forty-characters/".*))); try tmp.dir.createDirPath(std.testing.io, sub_path); var directory_buf: [4096]u8 = undefined; const directory = directory_buf[0..try tmp.dir.realPathFile(std.testing.io, sub_path, &directory_buf)]; @@ -1801,7 +1801,7 @@ test "shell cwd rejects truncation and preserves an owned child path longer than const io = std.testing.io; var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); - const nested = "nested-directory-with-more-than-forty-characters/" ** 24; + const nested = std.mem.asBytes(&@as([24][49]u8, @splat("nested-directory-with-more-than-forty-characters/".*))); try tmp.dir.createDirPath(io, nested); var path_buf: [pardes.memory.limits.host_path_cap + 1]u8 = undefined; const directory = path_buf[0..try tmp.dir.realPathFile(io, nested, &path_buf)]; diff --git a/src/image.zig b/src/image.zig index 72520ad6..8bf9de08 100644 --- a/src/image.zig +++ b/src/image.zig @@ -242,11 +242,11 @@ pub const GlyphArt = struct { const glyphs_ascii = glyphs ++ ascii_glyphs; fn matchCell(cell: *const [64][3]u8, pal: Palette, gset: []const Glyph) Cell { - var counts = [_]u16{0} ** 16; + var counts = @as([16]u16, @splat(0)); for (cell) |px| counts[nearest(px, pal)] += 1; var cand: [4]u4 = undefined; var ncand: usize = 0; - var used = [_]bool{false} ** 16; + var used = @as([16]bool, @splat(false)); while (ncand < 4) : (ncand += 1) { var best: ?usize = null; for (counts, 0..) |c, i| { @@ -432,7 +432,7 @@ pub const GlyphArt = struct { test "render: tiny image produces a grid within bounds" { const a = std.testing.allocator; // 2x2 checker, RGBA - var img = [_]u8{0} ** (2 * 2 * 4); + var img = @as([2 * 2 * 4]u8, @splat(0)); img[0] = 255; img[1] = 255; img[2] = 255; diff --git a/src/linux/v9fs.zig b/src/linux/v9fs.zig index 5e031bfe..15945e7b 100644 --- a/src/linux/v9fs.zig +++ b/src/linux/v9fs.zig @@ -64,11 +64,11 @@ pub fn helperPath(buf: []u8) ![:0]u8 { const path = if (std.c.getenv("PARDES_V9FS_HELPER")) |env| blk: { const override = std.mem.span(env); if (!std.fs.path.isAbsolute(override)) return error.AbsoluteHelperPathRequired; - break :blk try std.fmt.bufPrintZ(buf, "{s}", .{override}); + break :blk try std.fmt.bufPrintSentinel(buf, "{s}", .{override}, 0); } else blk: { var own: [4096]u8 = undefined; const parent = std.fs.path.dirname(try selfPath(&own)) orelse return error.ExecutablePathUnavailable; - break :blk try std.fmt.bufPrintZ(buf, "{s}/{s}", .{ parent, executable }); + break :blk try std.fmt.bufPrintSentinel(buf, "{s}/{s}", .{ parent, executable }, 0); }; if (std.c.access(path.ptr, 1) != 0) return error.V9fsHelperNotFound; return path; diff --git a/src/locations.zig b/src/locations.zig index 745393e5..2828566d 100644 --- a/src/locations.zig +++ b/src/locations.zig @@ -587,12 +587,13 @@ pub const Config = struct { const key = token[0..colon]; const value = token[colon + 1 ..]; var found = false; - inline for (@typeInfo(Config).@"struct".fields) |field| { - if (std.mem.eql(u8, key, field.name)) { - @field(result, field.name) = switch (@typeInfo(field.type)) { + const info = @typeInfo(Config).@"struct"; + inline for (info.field_names, info.field_types) |name, T| { + if (std.mem.eql(u8, key, name)) { + @field(result, name) = switch (@typeInfo(T)) { .bool => if (std.mem.eql(u8, value, "on")) true else if (std.mem.eql(u8, value, "off")) false else return error.ExpectedOnOrOff, - .int => std.fmt.parseInt(field.type, value, 10) catch return error.InvalidContext, - .@"enum" => std.meta.stringToEnum(field.type, value) orelse return error.InvalidLayout, + .int => std.fmt.parseInt(T, value, 10) catch return error.InvalidContext, + .@"enum" => std.meta.stringToEnum(T, value) orelse return error.InvalidLayout, else => @compileError("unsupported location setting type"), }; found = true; @@ -604,11 +605,12 @@ pub const Config = struct { } pub fn write(config: Config, writer: *std.Io.Writer) !void { - inline for (@typeInfo(Config).@"struct".fields, 0..) |field, index| { + const info = @typeInfo(Config).@"struct"; + inline for (info.field_names, info.field_types, 0..) |name, T, index| { if (index > 0) try writer.writeByte(' '); - try writer.writeAll(field.name ++ ":"); - const value = @field(config, field.name); - switch (@typeInfo(field.type)) { + try writer.writeAll(name ++ ":"); + const value = @field(config, name); + switch (@typeInfo(T)) { .bool => try writer.writeAll(if (value) "on" else "off"), .int => try writer.print("{d}", .{value}), .@"enum" => try writer.writeAll(@tagName(value)), @@ -809,11 +811,11 @@ test "locations cache bounds memory and entries and evicts least recently used" try std.testing.expectEqual(@as(usize, 2), cache.len); try std.testing.expect(cache.bytes <= 40); try std.testing.expectEqualStrings("b.unknown", cache.entries[0].path); - try std.testing.expectError(error.SourceTooLarge, cache.getBounded(gpa, "large.unknown", "x" ** 41, false, false, 40)); + try std.testing.expectError(error.SourceTooLarge, cache.getBounded(gpa, "large.unknown", &@as([41]u8, @splat('x')), false, false, 40)); try std.testing.expectEqual(@as(usize, 2), cache.len); if (syntax.supportsPath("large.zig")) { const before = cache.analyses; - try std.testing.expectError(error.SourceTooLarge, cache.getBounded(gpa, "large.zig", "x" ** 25, true, true, 40)); + try std.testing.expectError(error.SourceTooLarge, cache.getBounded(gpa, "large.zig", &@as([25]u8, @splat('x')), true, true, 40)); try std.testing.expectEqual(before, cache.analyses); } cache.deinit(gpa); diff --git a/src/look.zig b/src/look.zig index 1065cb02..f9c470cf 100644 --- a/src/look.zig +++ b/src/look.zig @@ -671,7 +671,7 @@ pub fn runSearch(p: *Pardes, id: usize, pat_raw: []const u8, kind: Search, start const cl: usize = @intCast(@max(0, pane.body.cur_row)); const cc: usize = @intCast(@max(0, pane.body.cur_col)); for (lines, 0..) |ln, i| { - const at = std.ascii.indexOfIgnoreCase(ln, pat) orelse continue; + const at = std.ascii.findIgnoreCase(ln, pat) orelse continue; const row = try std.fmt.allocPrint(arena, "{s}:{d}:{d}{c}{d} {s}\n", .{ loc, i + 1, at + 1, config.range_sep, at + pat.len, std.mem.trimEnd(u8, ln, " \t"), }); @@ -1273,7 +1273,7 @@ fn missText(text: []const u8, buf: *[miss_path_cap + "…".len]u8) []const u8 { test "a miss names a long path by its start and its end, its middle given up to …" { var cut: [miss_path_cap + "…".len]u8 = undefined; - const long = "/home/someone/" ++ "deep/" ** 80 ++ "the-file.zig"; + const long = "/home/someone/" ++ std.mem.asBytes(&@as([80][5]u8, @splat("deep/".*))) ++ "the-file.zig"; const said = missText(long, &cut); try std.testing.expect(said.len <= miss_path_cap); try std.testing.expect(std.mem.startsWith(u8, said, "/home/someone/")); @@ -2185,7 +2185,7 @@ test "Look ignores missing and out of bounds pane addresses" { test "a pointer resting where a look-hover found nothing does not wake the core every frame" { const p = try Pardes.init(std.testing.allocator, .{ .cols = 80, .rows = 24 }); defer p.deinit(); - _ = try p.setTestFile(" \n" ** 30); + _ = try p.setTestFile(std.mem.asBytes(&@as([30][6]u8, @splat(" \n".*)))); p.sync(); const r = p.rects[p.active]; // Resting on blanks in the body: a wait, then nothing to open. diff --git a/src/lsp/lsp.zig b/src/lsp/lsp.zig index 96d42bbd..4a70efe5 100644 --- a/src/lsp/lsp.zig +++ b/src/lsp/lsp.zig @@ -92,7 +92,7 @@ else pub const backend_name = "lsp-client"; pub const supports: std.EnumSet(Kind) = blk: { - var s: std.EnumSet(Kind) = .initEmpty(); + var s: std.EnumSet(Kind) = .empty; for (0..backends.len) |i| s.setUnion(backends[i].supports); break :blk s; }; diff --git a/src/lsp/lsp_client.zig b/src/lsp/lsp_client.zig index 54bbaa79..b396879b 100644 --- a/src/lsp/lsp_client.zig +++ b/src/lsp/lsp_client.zig @@ -159,7 +159,7 @@ pub const specs = [_]Spec{ /// answered per connection; a kind its server never advertised simply returns /// no rows, which the harness reports as CLAIMED-EMPTY per language — honest, /// since the claim here is about the protocol, not about every server. -pub const supports: std.EnumSet(lsp.Kind) = .initFull(); +pub const supports: std.EnumSet(lsp.Kind) = .full; /// Routing: an extension in the table whose spec is not disabled by its env /// var. Deliberately does NOT probe for the binary — this runs on the Tab diff --git a/src/macos.zig b/src/macos.zig index 20463481..37db0abd 100644 --- a/src/macos.zig +++ b/src/macos.zig @@ -724,7 +724,7 @@ fn initCore(runtime: ?*const Runtime, cols_arg: u16, rows_arg: u16) !void { // in Debug, libc's malloc otherwise. libc's measured at least as fast as // std.heap.smp_allocator everywhere and faster on MuPDF's page-sized // rasters, so this shell no longer differs. - const gpa = if (builtin.mode == .Debug) debug_gpa.allocator() else std.heap.c_allocator; + const gpa = if (builtin.mode == .debug) debug_gpa.allocator() else std.heap.c_allocator; const allocs = pardes.memory.init(gpa); errdefer pardes.memory.deinit(); @@ -858,7 +858,7 @@ export fn pardes_deinit() void { st.gpa.destroy(st.threaded); pardes.memory.deinit(); // Leaks are logged and do not fail, as std.start treats the others'. - if (builtin.mode == .Debug) { + if (builtin.mode == .debug) { _ = debug_gpa.deinit(); debug_gpa = .init; } @@ -2871,22 +2871,22 @@ test "pardes.h matches the Zig boundary" { try expectEqual(@offsetOf(c.pardes_cell_s, "len"), @offsetOf(Cell, "len")); try expectEqual(@offsetOf(c.pardes_cell_s, "flags"), @offsetOf(Cell, "flags")); try expectEqual(@sizeOf(c.pardes_scene_s), @sizeOf(Scene)); - inline for (@typeInfo(Scene).@"struct".fields) |field| - try expectEqual(@offsetOf(c.pardes_scene_s, field.name), @offsetOf(Scene, field.name)); + inline for (@typeInfo(Scene).@"struct".field_names) |name| + try expectEqual(@offsetOf(c.pardes_scene_s, name), @offsetOf(Scene, name)); try expectEqual(@sizeOf(c.pardes_panel_box_s), @sizeOf(PanelBox)); - inline for (@typeInfo(PanelBox).@"struct".fields) |field| - try expectEqual(@offsetOf(c.pardes_panel_box_s, field.name), @offsetOf(PanelBox, field.name)); + inline for (@typeInfo(PanelBox).@"struct".field_names) |name| + try expectEqual(@offsetOf(c.pardes_panel_box_s, name), @offsetOf(PanelBox, name)); try expectEqual(@sizeOf(c.pardes_panel_track_s), @sizeOf(PanelTrack)); - inline for (@typeInfo(PanelTrack).@"struct".fields) |field| { - const c_name = comptime if (std.mem.eql(u8, field.name, "motion")) + inline for (@typeInfo(PanelTrack).@"struct".field_names) |name| { + const c_name = comptime if (std.mem.eql(u8, name, "motion")) "reserved0" else - field.name; - try expectEqual(@offsetOf(c.pardes_panel_track_s, c_name), @offsetOf(PanelTrack, field.name)); + name; + try expectEqual(@offsetOf(c.pardes_panel_track_s, c_name), @offsetOf(PanelTrack, name)); } try expectEqual(@sizeOf(c.pardes_image_s), @sizeOf(Image)); - inline for (@typeInfo(Image).@"struct".fields) |field| - try expectEqual(@offsetOf(c.pardes_image_s, field.name), @offsetOf(Image, field.name)); + inline for (@typeInfo(Image).@"struct".field_names) |name| + try expectEqual(@offsetOf(c.pardes_image_s, name), @offsetOf(Image, name)); try expectEqual(@sizeOf(c.pardes_runtime_s), @sizeOf(Runtime)); try expectEqual(@as(u32, c.PARDES_COLOR_DEFAULT), color_default); @@ -3177,7 +3177,7 @@ test "mac tag layer ABI preserves logical capacity and physical grip" { }); try std.testing.expectEqual(@as(u32, 11), pardes_tag_layer_value(0, 8)); try std.testing.expectEqual(@as(u8, 'Z'), pardes_tag_layer_cells(0).?[11].text[0]); - var canonical: [24]Cell = @splat(encodeCell(.{ .text = .{'G'} ++ .{0} ** 6, .len = 1, .default = false })); + var canonical: [24]Cell = @splat(encodeCell(.{ .text = .{ 'G', 0, 0, 0, 0, 0, 0 }, .len = 1, .default = false })); var source: [24]pardes.Cell = @splat(.{}); blankTagCells(&canonical, 8, 3, &source, &core.surface.tag_layers); try std.testing.expectEqual(@as(u8, 'G'), canonical[9].text[0]); diff --git a/src/main.zig b/src/main.zig index 26259b43..e3bae75f 100644 --- a/src/main.zig +++ b/src/main.zig @@ -464,6 +464,12 @@ fn nativeMain(init: std.process.Init) !void { } opts.tty_only = explicit_tty or session_only; opts.mounts = mounts[0..mounts_len]; + // `zig build run-isolated` with nothing named: something to look at on + // arrival, read out of the binary itself. + if (pardes.isolated and positional == null) { + session_only = false; + positional = "src/pardes.zig"; + } if (detach != null and attach != null) badArgs(init.io, "--detach and --attach are opposites: one runs the session, the other joins one", .{}); // --wait waits on the pane a FILE opens: with none there is nothing to diff --git a/src/memory.zig b/src/memory.zig index abfd40f6..48403c55 100644 --- a/src/memory.zig +++ b/src/memory.zig @@ -38,7 +38,7 @@ pub const limits = struct { }; const Allocator = std.mem.Allocator; -const debug_enabled = builtin.mode == .Debug; +const debug_enabled = builtin.mode == .debug; pub const Allocators = struct { pardes: Allocator, diff --git a/src/modal.zig b/src/modal.zig index 50e0ddf4..82f1a3a0 100644 --- a/src/modal.zig +++ b/src/modal.zig @@ -163,7 +163,7 @@ pub const Normal = struct { }; pub const Input = struct { - roles: std.EnumSet(Role) = .initEmpty(), + roles: std.EnumSet(Role) = .empty, cp: u21, ctrl: bool = false, alt: bool = false, diff --git a/src/ninep/addr.zig b/src/ninep/addr.zig index b78c46e7..3feda5a2 100644 --- a/src/ninep/addr.zig +++ b/src/ninep/addr.zig @@ -646,7 +646,7 @@ test "the address language, form by form" { try testing.expectEqualStrings(c[1], th.wr(p, addr, c[0]).reply.ename); } - const nested = "," ** 4096; + const nested = &@as([4096]u8, @splat(',')); _ = th.wr(p, addr, "#0"); try testing.expectEqual(E.INVAL, th.wr(p, addr, nested).errno()); } diff --git a/src/ninep/cols.zig b/src/ninep/cols.zig index e3b456ba..59f6ae42 100644 --- a/src/ninep/cols.zig +++ b/src/ninep/cols.zig @@ -288,18 +288,18 @@ test "exactly 4096 bytes written with echo's newline after a truncation fit ever const p = try th.withFile(testing.allocator, "x\n"); defer p.deinit(); const serial = th.serialOf(p); - const text = "w" ** 4096 ++ "\n"; + const text = &@as([4096]u8, @splat('w')) ++ "\n"; for ([_]u64{ tree.Node.of(serial, .tag), tree.Node.ofCol(layout.columnSerial(p, 0), .tag), @intFromEnum(tree.TopFile.tag) }) |node| { _ = th.call(p, .{ .tag = 1, .op = .setattr, .node = node, .truncate = true }); const h = th.call(p, .{ .tag = 2, .op = .open, .node = node, .omode = 1 }).reply.handle; const r = th.call(p, .{ .tag = 3, .op = .write, .node = node, .handle = h, .data = text }); try testing.expectEqual(tree.Status.ok, r.reply.status); _ = th.call(p, .{ .tag = 4, .op = .release, .node = node, .handle = h, .opened = true }); - try testing.expect(std.mem.endsWith(u8, th.rd(p, node, 0, 1 << 16).bytes, "w" ** 4096)); + try testing.expect(std.mem.endsWith(u8, th.rd(p, node, 0, 1 << 16).bytes, &@as([4096]u8, @splat('w')))); // One more byte is over. _ = th.call(p, .{ .tag = 5, .op = .setattr, .node = node, .truncate = true }); const h2 = th.call(p, .{ .tag = 6, .op = .open, .node = node, .omode = 1 }).reply.handle; - try testing.expectEqual(E.NOSPC, th.call(p, .{ .tag = 7, .op = .write, .node = node, .handle = h2, .data = "w" ** 4097 ++ "\n" }).errno()); + try testing.expectEqual(E.NOSPC, th.call(p, .{ .tag = 7, .op = .write, .node = node, .handle = h2, .data = &@as([4097]u8, @splat('w')) ++ "\n" }).errno()); _ = th.call(p, .{ .tag = 8, .op = .release, .node = node, .handle = h2, .opened = true }); } } @@ -316,7 +316,7 @@ test "a Newcol refused because the tags would not fit logs its err alone and spe for (p.col_panes[col][0..p.col_n[col]]) |k| { const each = p.panes[k].?; if (each.tag.own) |old| p.gpa.free(old); - each.tag.own = try p.gpa.dupe(u8, "word " ** 60); + each.tag.own = try p.gpa.dupe(u8, std.mem.asBytes(&@as([60][5]u8, @splat("word ".*)))); } try testing.expect(p.col_n[col] >= 2); p.sync(); @@ -588,7 +588,7 @@ test "a refused write after a truncation leaves every kind of tag as it was, and defer p.deinit(); const serial = th.serialOf(p); const col = layout.columnSerial(p, 0); - const big = "w" ** (limits.max_tag_tail + 1); + const big = &@as([limits.max_tag_tail + 1]u8, @splat('w')); // Each tag: a truncating open, then a write too long: nothing changes. for ([_]u64{ Node.of(serial, .tag), Node.ofCol(col, .tag), @intFromEnum(tree.TopFile.tag) }) |node| { _ = th.wr(p, node, " Mine"); diff --git a/src/ninep/ctl.zig b/src/ninep/ctl.zig index f6457b83..6b4bbafb 100644 --- a/src/ninep/ctl.zig +++ b/src/ninep/ctl.zig @@ -1682,9 +1682,9 @@ test "a look's miss repeats the path whole up to 256 bytes, then gives up its mi var line: [512]u8 = undefined; _ = wr(p, root, try std.fmt.bufPrint(&line, "{s}\n", .{long})); try testing.expect(th.logHas(p, try std.fmt.bufPrint(&line, "look: no match for \"{s}\"\n", .{long}))); - const huge = "é" ** 150; // 300 bytes: its middle cut to fit 256, between characters + const huge = std.mem.asBytes(&@as([150][2]u8, @splat("é".*))); // 300 bytes: its middle cut to fit 256, between characters _ = wr(p, root, huge ++ "\n"); - try testing.expect(th.logHas(p, "look: no match for \"" ++ "é" ** 63 ++ "…" ++ "é" ** 63 ++ "\"\n")); + try testing.expect(th.logHas(p, "look: no match for \"" ++ std.mem.asBytes(&@as([63][2]u8, @splat("é".*))) ++ "…" ++ std.mem.asBytes(&@as([63][2]u8, @splat("é".*))) ++ "\"\n")); } test "exec runs a builtin at the pane and records the pane it acted on" { @@ -2041,7 +2041,7 @@ test "Zerox twins dump their text once and come back on one buffer from a Restor defer p.deinit(); const first = serialOf(p); _ = wr(p, Node.of(first, .name), "/tmp/pardes-zerox-dump.txt\n"); - _ = wr(p, Node.of(first, .body), "unsaved " ** 64 ++ "\n"); + _ = wr(p, Node.of(first, .body), std.mem.asBytes(&@as([64][8]u8, @splat("unsaved ".*))) ++ "\n"); try testing.expect(p.executeBuiltinLine(0, "Zerox")); try testing.expect(p.executeBuiltinLine(0, "Zerox")); try pardes.dump.dumpState(p); @@ -2888,7 +2888,7 @@ test "a builtin that fails a ctl write logs only its err, so the same failure ag test "an exec line over the command limit fails the write and says the limit; a builtin's may be longer" { const p = try withFile(testing.allocator, "x\n"); defer p.deinit(); - const long = "echo " ++ "y" ** pardes.exec.command_max ++ "\n"; + const long = "echo " ++ &@as([pardes.exec.command_max]u8, @splat('y')) ++ "\n"; const refused = wr(p, root_exec, long); try testing.expectEqual(E.INVAL, refused.errno()); try testing.expectEqualStrings(e_too_long, refused.reply.ename); @@ -2896,7 +2896,7 @@ test "an exec line over the command limit fails the write and says the limit; a try testing.expect(th.logHas(p, try std.fmt.bufPrint(&rec, "err {d} exec: invalid command line: a command line is at most 1024 bytes", .{serialOf(p)}))); try testing.expectEqualStrings(e_control, wr(p, root_exec, "echo a\x01b\n").reply.ename); try testing.expect(th.logHas(p, try std.fmt.bufPrint(&rec, "err {d} exec: invalid command line: it holds", .{serialOf(p)}))); - try testing.expectEqual(Status.ok, wr(p, root_exec, "Msg " ++ "z" ** 1100 ++ "\n").reply.status); + try testing.expectEqual(Status.ok, wr(p, root_exec, "Msg " ++ &@as([1100]u8, @splat('z')) ++ "\n").reply.status); } test "Edit's p and = never fail for want of room for +Errors: the text is logged instead" { @@ -4012,8 +4012,8 @@ test "Back and Forward written to exec keep to the focused file, and JumpScope a defer p.deinit(); var tmp = testing.tmpDir(.{}); defer tmp.cleanup(); - try tmp.dir.writeFile(testing.io, .{ .sub_path = "a.txt", .data = "row\n" ** 100 }); - try tmp.dir.writeFile(testing.io, .{ .sub_path = "b.txt", .data = "row\n" ** 100 }); + try tmp.dir.writeFile(testing.io, .{ .sub_path = "a.txt", .data = std.mem.asBytes(&@as([100][4]u8, @splat("row\n".*))) }); + try tmp.dir.writeFile(testing.io, .{ .sub_path = "b.txt", .data = std.mem.asBytes(&@as([100][4]u8, @splat("row\n".*))) }); var dir_buf: [4096]u8 = undefined; const dir = dir_buf[0..try tmp.dir.realPath(testing.io, &dir_buf)]; var line: [4200]u8 = undefined; diff --git a/src/ninep/events.zig b/src/ninep/events.zig index 3910ac05..7b73dc0e 100644 --- a/src/ninep/events.zig +++ b/src/ninep/events.zig @@ -938,7 +938,7 @@ test "event records are acme's bytes, one per read, and .again when empty" { try testing.expectEqualStrings("ML0 ", rd(p, event, 0, 4).bytes); try testing.expectEqualStrings("3 4 3 one\n", rd(p, event, 0, 4096).bytes); - const big = "z" ** max_record_text; + const big = &@as([max_record_text]u8, @splat('z')); _ = noteAction(p, 0, .body_exec, 0, max_record_text, 0, big); try testing.expectEqualStrings("MX0 256 0 0 \n", rd(p, event, 0, 4096).bytes); @@ -1388,7 +1388,7 @@ test "opens of the log share the open records, and a closed one frees its record test "a click in the body reports the offsets of the word it takes, so the record can be written back" { const config = @import("../config.zig"); const gpa = testing.allocator; - const text = "alpha qty beta\n qty\n\tqty\ndef f(qty): return qty.x\n" ++ "w" ** 100 ++ " qty\n"; + const text = "alpha qty beta\n qty\n\tqty\ndef f(qty): return qty.x\n" ++ &@as([100]u8, @splat('w')) ++ " qty\n"; const p = try withFile(gpa, text); defer p.deinit(); // A scratch made over 9P, clicked while another pane has the keyboard. @@ -1459,7 +1459,7 @@ test "follow new skips what the log held and waits for what comes after" { test "a long msg record is cut between words at its cap, with an ellipsis" { const p = try withFile(testing.allocator, "x\n"); defer p.deinit(); - const long = "word " ** 60; // 300 bytes + const long = std.mem.asBytes(&@as([60][5]u8, @splat("word ".*))); // 300 bytes _ = wr(p, Node.of(serialOf(p), .ctl), "Msg " ++ long ++ "\n"); const log = @intFromEnum(tree.TopFile.log); const h = call(p, .{ .tag = 1, .op = .open, .node = log }).reply.handle; @@ -1485,7 +1485,7 @@ test "a record is one line of UTF-8: DEL and C1 are spaces, bytes not UTF-8 are test "a long err record keeps its end, its middle given up to an ellipsis" { const p = try withFile(testing.allocator, "x\n"); defer p.deinit(); - _ = wr(p, @intFromEnum(tree.TopFile.ctl), "Bogus" ++ "abcdefgh" ** 40 ++ "\n"); + _ = wr(p, @intFromEnum(tree.TopFile.ctl), "Bogus" ++ std.mem.asBytes(&@as([40][8]u8, @splat("abcdefgh".*))) ++ "\n"); const log = @intFromEnum(tree.TopFile.log); const h = call(p, .{ .tag = 1, .op = .open, .node = log }).reply.handle; const text = call(p, .{ .tag = 2, .op = .read, .node = log, .handle = h, .size = 1 << 16 }).bytes; @@ -1500,7 +1500,7 @@ test "a long err record keeps its end, its middle given up to an ellipsis" { test "two failures that agree only in what their records cut are two records, not one counted" { const p = try th.withFile(testing.allocator, "x\n"); defer p.deinit(); - const long = "why " ** 80; + const long = std.mem.asBytes(&@as([80][4]u8, @splat("why ".*))); p.setMessage(0, long ++ "first"); p.setMessage(0, long ++ "second"); try testing.expect(!th.logHas(p, "(x2)")); diff --git a/src/ninep/pane.zig b/src/ninep/pane.zig index 3b70d62f..8605cab8 100644 --- a/src/ninep/pane.zig +++ b/src/ninep/pane.zig @@ -1427,7 +1427,7 @@ test "a tag write past the limit is refused whole, naming the limit" { const tag = Node.of(serialOf(p), .tag); const before = try testing.allocator.dupe(u8, rd(p, tag, 0, 1 << 16).bytes); defer testing.allocator.free(before); - const big = "w" ** (limits.max_tag_tail + 10); + const big = &@as([limits.max_tag_tail + 10]u8, @splat('w')); const r = wr(p, tag, big); try testing.expectEqual(E.NOSPC, r.errno()); // `no space` is what 9ns maps to ENOSPC, so a shell through a mount @@ -1549,20 +1549,21 @@ test "a name with a component over 255 bytes is refused, and a long path's faile const p = try withFile(testing.allocator, "x\n"); defer p.deinit(); const serial = serialOf(p); - const refused = wr(p, Node.of(serial, .name), "/tmp/" ++ "c" ** 256 ++ "/f.txt\n"); + const refused = wr(p, Node.of(serial, .name), "/tmp/" ++ &@as([256]u8, @splat('c')) ++ "/f.txt\n"); try testing.expectEqual(E.INVAL, refused.errno()); try testing.expectEqualStrings("invalid file name: a component over 255 bytes", refused.reply.ename); - try testing.expectEqual(Status.ok, wr(p, Node.of(serial, .name), "/tmp/" ++ "c" ** 255 ++ "\n").reply.status); + try testing.expectEqual(Status.ok, wr(p, Node.of(serial, .name), "/tmp/" ++ &@as([255]u8, @splat('c')) ++ "\n").reply.status); // Held with no newline, it is refused by that write, not at the close. const held = call(p, .{ .tag = 1, .op = .open, .node = Node.of(serial, .name), .omode = 1 }).reply.handle; - try testing.expectEqual(E.INVAL, call(p, .{ .tag = 2, .op = .write, .node = Node.of(serial, .name), .handle = held, .data = "/tmp/" ++ "e" ** 256 }).errno()); + try testing.expectEqual(E.INVAL, call(p, .{ .tag = 2, .op = .write, .node = Node.of(serial, .name), .handle = held, .data = "/tmp/" ++ &@as([256]u8, @splat('e')) }).errno()); _ = call(p, .{ .tag = 3, .op = .release, .node = Node.of(serial, .name), .handle = held, .opened = true }); try testing.expectEqual(@as(usize, 0), p.fs.closed_lines.items.len); // A Save of a 3000-byte path the host refuses: the waiting write's // reason is at the end, the path giving up its middle. // (Under /tmp: under / a user's Save is refused permission, not // missing.) - const long = "/tmp/nonexistent-pardes-root/" ++ ("d" ** 200 ++ "/") ** 15 ++ "f.txt"; + const segment = &@as([200]u8, @splat('d')) ++ "/"; + const long = "/tmp/nonexistent-pardes-root/" ++ std.mem.asBytes(&@as([15][201]u8, @splat(segment.*))) ++ "f.txt"; const id = p.paneBySerial(serial).?; try nameBuffer(p, id, long, false); p.fs.late_failure_len = 0; diff --git a/src/ninep/pty.zig b/src/ninep/pty.zig index c58cf676..aeb57a00 100644 --- a/src/ninep/pty.zig +++ b/src/ninep/pty.zig @@ -1044,12 +1044,12 @@ test "a run's answer says cut when its output's start is gone, and reads a bound const q = try withTerm(gpa); defer q.deinit(); const kept = q.panes[0].?; - kept.terminal.?.vt.screens.get(.primary).?.pages.explicit_max_size = 1; + kept.terminal.?.vt.screens.get(.primary).?.pages.limits.set(.bytes, 1); const run = Node.of(serialOf(q), .pty_run); sh.put(q, prompt); h = sh.send(q, run); sh.put(q, c); - const lines = "pruned\r\n" ** 64; + const lines = std.mem.asBytes(&@as([64][8]u8, @splat("pruned\r\n".*))); var fed: usize = 0; while (!kept.terminal.?.stream.handler.out_start.?.garbage) : (fed += 1) { if (fed == 1000) return error.TestUnexpectedResult; @@ -1146,7 +1146,7 @@ test "a run's answer longer than its room is cut, its newline kept" { var slot: Run = .{}; const p = try th.withTerm(testing.allocator); defer p.deinit(); - answer(p, &slot, "busy: {s} is running", .{"x" ** 200}); + answer(p, &slot, "busy: {s} is running", .{&@as([200]u8, @splat('x'))}); try testing.expectEqual(slot.answer.len, slot.len); try testing.expectEqual(@as(u8, '\n'), slot.answer[slot.len - 1]); } diff --git a/src/ninep/screen.zig b/src/ninep/screen.zig index b991c3e4..8d4707e0 100644 --- a/src/ninep/screen.zig +++ b/src/ninep/screen.zig @@ -333,7 +333,7 @@ test "a terminal's body is its logical lines: a row the terminal wrapped is join const p = try th.withTerm(testing.allocator); defer p.deinit(); const pane = p.panes[0].?; - const long = "w" ** 50 ++ "x" ** 150; // wider than the pane: it wraps + const long = &@as([50]u8, @splat('w')) ++ &@as([150]u8, @splat('x')); // wider than the pane: it wraps try testing.expect(long.len > pane.cols); p.update(.{ .output = .{ .pane = 0, .bytes = long ++ "\r\nnext" } }); while (p.nextEffect()) |_| {} diff --git a/src/ninep/tree.zig b/src/ninep/tree.zig index eedab43b..5678832b 100644 --- a/src/ninep/tree.zig +++ b/src/ninep/tree.zig @@ -509,7 +509,7 @@ pub fn fitErr(text: []const u8, out: []u8) []const u8 { test "a reason past 128 bytes keeps its end: the path in it gives up its middle" { var out: [128]u8 = undefined; - const long = "Save /home/someone/projects/" ++ "deep/" ** 30 ++ "file.txt: no such directory"; + const long = "Save /home/someone/projects/" ++ std.mem.asBytes(&@as([30][5]u8, @splat("deep/".*))) ++ "file.txt: no such directory"; const fit = fitErr(long, &out); try testing.expect(fit.len <= 128); try testing.expect(std.mem.startsWith(u8, fit, "Save /home/someone/")); @@ -517,7 +517,7 @@ test "a reason past 128 bytes keeps its end: the path in it gives up its middle" try testing.expect(std.mem.indexOf(u8, fit, "…") != null); try testing.expect(std.unicode.utf8ValidateSlice(fit)); // No path: the whole text's middle goes, the end stays. - const words = "why " ** 40 ++ "the reason"; + const words = std.mem.asBytes(&@as([40][4]u8, @splat("why ".*))) ++ "the reason"; try testing.expect(std.mem.endsWith(u8, fitErr(words, &out), "the reason")); try testing.expectEqualStrings("short", fitErr("short", &out)); // Through the tree: a look at a long ./ name not there, a miss, says @@ -525,7 +525,7 @@ test "a reason past 128 bytes keeps its end: the path in it gives up its middle" const p = try th.withFile(testing.allocator, "x\n"); defer p.deinit(); var line: [512]u8 = undefined; - const r = th.wr(p, Node.of(serialOf(p), .look), try std.fmt.bufPrint(&line, "./{s}x.txt\n", .{"no-such-dir/" ** 20})); + const r = th.wr(p, Node.of(serialOf(p), .look), try std.fmt.bufPrint(&line, "./{s}x.txt\n", .{std.mem.asBytes(&@as([20][12]u8, @splat("no-such-dir/".*)))})); try testing.expectEqual(Status.ok, r.reply.status); try testing.expect(th.logHas(p, "x.txt: no such file")); } @@ -1492,17 +1492,17 @@ test "README names every file the tree serves" { return false; } }; - inline for (@typeInfo(TopFile).@"enum".fields) |f| { - const t: TopFile = @enumFromInt(f.value); + inline for (@typeInfo(TopFile).@"enum".field_values) |value| { + const t: TopFile = @enumFromInt(value); if (t != .root and !words.has(t.fileName())) { std.debug.print("README does not mention /{s}\n", .{t.fileName()}); return error.Undocumented; } } - inline for (@typeInfo(PaneFile).@"enum".fields) |f| { - const t: PaneFile = @enumFromInt(f.value); + inline for (@typeInfo(PaneFile).@"enum".field_values) |value| { + const t: PaneFile = @enumFromInt(value); const ok = if (t == .dir) true else if (t.inPty() and t != .pty) - std.mem.indexOf(u8, fs.help, "pty/" ++ comptime @as(PaneFile, @enumFromInt(f.value)).fileName()) != null + std.mem.indexOf(u8, fs.help, "pty/" ++ comptime @as(PaneFile, @enumFromInt(value)).fileName()) != null else words.has(t.fileName()); if (!ok) { diff --git a/src/normal.zig b/src/normal.zig index 77feb7cf..8de23d1c 100644 --- a/src/normal.zig +++ b/src/normal.zig @@ -1015,7 +1015,7 @@ test "gj/gk step the wrapped rows a body draws while j/k keep the file's lines" const p = try Pardes.init(gpa, .{ .tty_only = true }); defer p.deinit(); while (p.nextEffect()) |_| {} - const long = "a" ** 400; + const long = &@as([400]u8, @splat('a')); const pane = try p.setTestFile(long ++ "\nsecond\n"); p.settings.wrap = true; const width = panes.File.wrapWidth(pane, true); diff --git a/src/pager.zig b/src/pager.zig index 30418623..feabd194 100644 --- a/src/pager.zig +++ b/src/pager.zig @@ -38,7 +38,7 @@ pub fn parse(gpa: std.mem.Allocator, raw: []const u8, colour: bool) !Page { errdefer h.text.deinit(gpa); errdefer h.spans.deinit(gpa); try h.text.ensureTotalCapacity(gpa, raw.len); - var stream: ghostty_vt.Stream(*Handler) = .init(&h); + var stream: ghostty_vt.Stream(*Handler) = .init(.{ .handler = &h }); defer stream.deinit(); stream.nextSlice(raw); if (h.failed) return error.OutOfMemory; diff --git a/src/panes.zig b/src/panes.zig index ba1dedb5..07d5ccb1 100644 --- a/src/panes.zig +++ b/src/panes.zig @@ -318,7 +318,7 @@ pub const Pane = struct { /// `older` is an earlier message line still on screen; `index` says /// which (`Pane.msg_older`). pub const Kind = enum { older, message, leader, prompt }; - pub const max = @typeInfo(Kind).@"enum".fields.len - 1 + message_stack; + pub const max = @typeInfo(Kind).@"enum".field_names.len - 1 + message_stack; kinds: [max]Kind = undefined, index: [max]u8 = @splat(0), diff --git a/src/pardes.zig b/src/pardes.zig index 5f330712..8da0922d 100644 --- a/src/pardes.zig +++ b/src/pardes.zig @@ -807,7 +807,7 @@ test "TreeContext tag style preserves message rows and its opt-out survives rest if (comptime !syntax.enabled) return error.SkipZigTest; const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 60, .rows = 16 }); defer p.deinit(); - const pane = try p.setTestFile("pub const Box = struct {\n pub fn run() void {\n" ++ (" // body\n" ** 30) ++ " }\n};\n"); + const pane = try p.setTestFile("pub const Box = struct {\n pub fn run() void {\n" ++ (std.mem.asBytes(&@as([30][16]u8, @splat(" // body\n".*)))) ++ " }\n};\n"); p.gpa.free(pane.file.?.path); pane.file.?.path = try p.gpa.dupe(u8, "/test.zig"); if (!panes.File.supportsContext(pane)) return error.SkipZigTest; @@ -1247,7 +1247,9 @@ test "Def and Refs are a speaking file's tag words; gd, gr and a 2-1 chord all r const r = p.rects[0]; const x0 = r.x + config.GUTTER + panes.File.gutterWidth(pane); const use_y = p.bodyTop(pane, r) + 1; - const tag = try tagline.tagText(p, p.scratch.allocator(), pane); + // Copied out of the scratch arena, which each p.update resets. + const tag = try std.testing.allocator.dupe(u8, try tagline.tagText(p, p.scratch.allocator(), pane)); + defer std.testing.allocator.free(tag); for ([_]struct { word: []const u8, kind: lsp.Kind }{ .{ .word = " Def ", .kind = .definition }, .{ .word = " Refs", .kind = .references } }) |w| { // B1 sweeps the use of `alpha` on the second line (bytes 30..35), // leaving the cursor at its far end. @@ -1348,7 +1350,7 @@ test "acme placement: under a pane's text when it has many blank rows, else halv try std.testing.expectEqual(text_end, p.rects[second].y); // Fill both with text: no blank space is big, so the biggest pane is // halved. - const full = "x\n" ** 80; + const full = std.mem.asBytes(&@as([80][2]u8, @splat("x\n".*))); for ([_]usize{ top, second }) |id| panes.File.setContent(p, &p.panes[id].?.file.?, try p.gpa.dupe(u8, full)); p.sync(); const big = if (p.rects[second].h >= p.rects[top].h) second else top; @@ -2006,7 +2008,7 @@ test "a command pane shows how its command ended, and the next command there run try std.testing.expectEqual(@as(usize, 0), Count.signals); p.host = host_before; // A command line longer than a command pane takes is refused. - const long = "x" ** (exec.command_max + 1); + const long = &@as([exec.command_max + 1]u8, @splat('x')); try std.testing.expectEqual(@as(?usize, null), exec.execute(p, 1, long)); } @@ -2970,9 +2972,9 @@ test "restored terminals keep monotonic nonzero pane identities" { fn chordName(comptime c: config.Chord) []const u8 { comptime { const mods = (if (c.ctrl) "C-" else "") ++ (if (c.alt) "A-" else "") ++ (if (c.shift) "S-" else ""); - for (@typeInfo(Key).@"struct".decls) |d| { - if (@TypeOf(@field(Key, d.name)) != u21) continue; - if (@field(Key, d.name) == c.cp) return mods ++ d.name; + for (@typeInfo(Key).@"struct".decl_names) |d| { + if (@TypeOf(@field(Key, d)) != u21) continue; + if (@field(Key, d) == c.cp) return mods ++ d; } if (c.cp < 0x20 or c.cp > 0x7e) @compileError("chord has no name for the index"); return mods ++ &[_]u8{@as(u8, @intCast(c.cp))}; @@ -3088,11 +3090,11 @@ pub const builtin_rows: [std.enums.values(Builtin).len]Row = blk: { for (std.enums.values(Builtin), 0..) |b, i| { const keys = if (config.leader_path.get(b)) |path| leaderKeys(path) else ""; const rest = shortcuts(b); - const named = @tagName(b) ++ (if (rest.len == 0) "" else (" " ** (namew - @tagName(b).len)) ++ " " ++ rest); + const named = @tagName(b) ++ (if (rest.len == 0) "" else (&@as([namew - @tagName(b).len]u8, @splat(' '))) ++ " " ++ rest); rows[i] = .{ .path = config.leader_path.get(b), .cmd = b, - .line = keys ++ (" " ** (4 + keyw - keys.len)) ++ " " ++ named, + .line = keys ++ (&@as([4 + keyw - keys.len]u8, @splat(' '))) ++ " " ++ named, }; } const last = "\x7f"; @@ -3111,8 +3113,8 @@ comptime { @setEvalBranchQuota(20000); // one branch per string byte, behind the decl walk that folds Builtin var it = std.mem.tokenizeScalar(u8, config.topbar_str, ' '); words: while (it.next()) |w| { - for (@typeInfo(Builtin).@"enum".fields) |f| - if (std.mem.eql(u8, f.name, w)) continue :words; + for (@typeInfo(Builtin).@"enum".field_names) |name| + if (std.mem.eql(u8, name, w)) continue :words; @compileError("topbar word is not a builtin: " ++ w); } } @@ -4499,7 +4501,7 @@ pub const Pardes = struct { /// Panes made this step that found no room in their column /// (exec.placeNew): closed at the step's end, once whatever made them /// is done with them. - unplaced: std.StaticBitSet(MAX_PANES) = .initEmpty(), + unplaced: std.StaticBitSet(MAX_PANES) = .empty, /// A look's word search is running (look.lookUnresolved): from a /// terminal its rows refill the directory's one +Search (Output). word_look: bool = false, @@ -5018,7 +5020,7 @@ pub const Pardes = struct { if (p.dump_out) |d| gpa.free(d); p.fallback.deinit(); if (p.last_dump) |d| gpa.free(d); - if (p.custom_theme) |theme_value| std.zon.parse.free(gpa, theme_value); + if (p.custom_theme) |theme_value| gpa.free(theme_value.name); if (p.chord_arg) |a| gpa.free(a); for (p.spawn_dirs) |d| if (d) |dir| gpa.free(dir); p.pipe.deinit(gpa); @@ -8508,7 +8510,7 @@ test "raw tty Ctrl-B switches to editor mode without sending child input" { test "the jump list never holds two entries in a row the same, when the one between them goes" { const p = try Pardes.init(std.testing.allocator, .{ .cols = 60, .rows = 40 }); defer p.deinit(); - const pane = try p.setTestFile("a\n" ** 200); + const pane = try p.setTestFile(std.mem.asBytes(&@as([200][2]u8, @splat("a\n".*)))); const at: Loc = .{ .pane = 0, .serial = pane.serial, .line = 1, .col = 1 }; // A, a pane long closed with no file to keep it, A again, then far on. p.jumps[0] = at; @@ -9054,7 +9056,7 @@ const JumpsTest = struct { fn init(order: []const u8) !JumpsTest { const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 100, .rows = 80 }); errdefer p.deinit(); - const text = "row\n" ** 100; + const text = std.mem.asBytes(&@as([100][4]u8, @splat("row\n".*))); _ = try p.setTestFile(text); var t: JumpsTest = .{ .p = p }; for ([_][]const u8{ "/b.txt", "/test.txt", "" }, 1..) |path, n| { diff --git a/src/pdf.zig b/src/pdf.zig index d98d5ff2..5adc62d1 100644 --- a/src/pdf.zig +++ b/src/pdf.zig @@ -4,9 +4,7 @@ const std = @import("std"); const c_heap = @import("c_heap"); -const c = @cImport({ - @cInclude("pdf_bridge.h"); -}); +const c = @import("pdf_c"); // src/pdf_bridge.h, translated by build.zig /// What MuPDF allocates from, itself and the libraries it bundles (they all /// allocate through its context): `start`'s allocator, through the shared C @@ -1130,7 +1128,7 @@ pub const Document = struct { const page_number = try document.checkedPage(page); if (std.mem.indexOfScalar(u8, needle, 0) != null) return error.InvalidNeedle; - const needle_z = try gpa.dupeZ(u8, needle); + const needle_z = try gpa.dupeSentinel(u8, needle, 0); defer gpa.free(needle_z); var found: c.pardes_pdf_search_result = @@ -2067,7 +2065,7 @@ test "MuPDF search returns normalized oriented quads and word selection text" { const projected = try document.pageText(std.testing.allocator, 0); defer std.testing.allocator.free(projected); - try std.testing.expect(std.ascii.indexOfIgnoreCase(projected, "Pardes") != null); + try std.testing.expect(std.ascii.findIgnoreCase(projected, "Pardes") != null); // Exercise transactional cache replacement before searching page zero // again; a failed ownership handoff here tends to surface as a double drop. if (document.pages > 1) { @@ -2093,7 +2091,7 @@ test "MuPDF search returns normalized oriented quads and word selection text" { const text = try document.copySelection(std.testing.allocator, 0, selected.start, selected.end); defer std.testing.allocator.free(text); - try std.testing.expect(std.ascii.indexOfIgnoreCase(text, "Pardes") != null); + try std.testing.expect(std.ascii.findIgnoreCase(text, "Pardes") != null); } test "highlighted render changes pixels while plain render stays stable" { diff --git a/src/regexp.zig b/src/regexp.zig index 86132f60..4cbca57e 100644 --- a/src/regexp.zig +++ b/src/regexp.zig @@ -58,7 +58,7 @@ pub const Regex = struct { /// Timed on this machine's ReleaseSafe build: 10M steps of the worst /// patterns take 45-80 ms, and a Debug build is ten times slower. - pub const budget: u64 = if (builtin.mode == .Debug) 4_000_000 else 32_000_000; + pub const budget: u64 = if (builtin.mode == .debug) 4_000_000 else 32_000_000; pub const e_long = std.fmt.comptimePrint("bad regular expression: longer than mvzr's {d} operations (about {d} pattern characters)", .{ max_ops, max_ops }); pub const e_anchor = "bad regular expression: in a pattern with \\n, ^ can only come first and $ only just before a \\n"; @@ -503,10 +503,10 @@ test "a class with non-ASCII runes matches those runes: [éa-z], a range of them } test "a pattern past 64 characters compiles, and one past the limit says so" { - var long = try Regex.compile("a" ** 200); - const text = "x" ++ "a" ** 200 ++ "\n"; + var long = try Regex.compile(&@as([200]u8, @splat('a'))); + const text = "x" ++ &@as([200]u8, @splat('a')) ++ "\n"; try std.testing.expectEqual(@as(usize, 1), (try long.find(text, 0, text.len, text.len)).?.start); - try std.testing.expectError(error.TooLong, Regex.compile("a" ** (max_ops + 8))); + try std.testing.expectError(error.TooLong, Regex.compile(&@as([max_ops + 8]u8, @splat('a')))); try std.testing.expectError(error.Bad, Regex.compile("a[b")); } @@ -546,13 +546,13 @@ test "a search that would backtrack without end runs out of budget, promptly" { // As long a chain as mvzr compiles, over runs one `a` short of it: 2^20 // steps from every start. for (0..line.len / 20) |i| line[i * 20 + 19] = 'b'; - var chain = try Regex.compile("a?" ** 20 ++ "a" ** 20); + var chain = try Regex.compile(std.mem.asBytes(&@as([20][2]u8, @splat("a?".*))) ++ &@as([20]u8, @splat('a'))); try std.testing.expectError(error.TooSlow, chain.find(&line, 0, line.len, line.len)); } test "the match is the leftmost, however long the line" { // A window cut into the identifier would find `x... =` from its middle. - const text = "let " ++ "x" ** 100 ++ " = 1"; + const text = "let " ++ &@as([100]u8, @splat('x')) ++ " = 1"; var assign = try Regex.compile("\\s*(\\w+)\\s*="); const m = (try assign.find(text, 0, text.len, text.len)).?; try std.testing.expectEqual(@as(usize, 3), m.start); diff --git a/src/sam_edit.zig b/src/sam_edit.zig index d0c51bdb..f6253c89 100644 --- a/src/sam_edit.zig +++ b/src/sam_edit.zig @@ -1102,7 +1102,7 @@ fn expectEdit(text: []const u8, command: []const u8, want: []const u8) !void { test "an x over 100k lines is 100k searches, each with its own step budget" { const th = @import("ninep/testing.zig"); - const line = "x" ** 80 ++ "\n"; + const line = &@as([80]u8, @splat('x')) ++ "\n"; const text = try std.testing.allocator.alloc(u8, line.len * 100_000); defer std.testing.allocator.free(text); for (0..100_000) |k| @memcpy(text[line.len * k ..][0..line.len], line); diff --git a/src/syntax.zig b/src/syntax.zig index b2f5ea99..fa212ca7 100644 --- a/src/syntax.zig +++ b/src/syntax.zig @@ -1859,7 +1859,7 @@ test "syntax declaration locations clear snapshots without muting ordinary conte defer stop(); const header = "pub fn run() void {"; const content = "| \t" ++ header ++ "\n| \t const value = 42;\nfile.zig:3\t}\n"; - const snapshots = [_]u8{0xff} ** header.len; + const snapshots = @as([header.len]u8, @splat(0xff)); const Row = struct { path: []const u8 = "file.zig", code_start: usize, diff --git a/src/terminal.zig b/src/terminal.zig index 3190c6e3..a8e7931c 100644 --- a/src/terminal.zig +++ b/src/terminal.zig @@ -207,7 +207,7 @@ const LivePalette = struct { var seed = GColor.default; for (base, 0..) |rgb, i| seed[i] = rgb; - self.colors = GColor.generate256Color(seed, .initEmpty(), bg, fg, false); + self.colors = GColor.generate256Color(seed, .empty, bg, fg, false); self.key = key; return &self.colors; } @@ -609,10 +609,10 @@ pub fn create(gpa: std.mem.Allocator, cols: u16, rows: u16) !*Pane { state.vt = try ghostty_vt.Terminal.init(terminalIo(), gpa, .{ .cols = cols, .rows = rows, - .max_scrollback = 16 * 1024 * 1024, + .max_scrollback_bytes = 16 * 1024 * 1024, .kitty_image_storage_limit = if (images_enabled) TerminalImages.storage_limit else 0, }); - state.stream = .initAlloc(gpa, .{ .inner = state.vt.vtHandler() }); + state.stream = .init(.{ .handler = .{ .inner = state.vt.vtHandler() }, .allocator = gpa }); state.replay.head = 0; state.replay.len = 0; state.reply_len = 0; @@ -1055,7 +1055,11 @@ fn ingestWithPositions(pane: *Pane, bytes: []const u8) void { } }; } else failed = true; + // Whether the program cleared the screen (ED 2, a switch of screens); + // pardes reads the flag nowhere else. + pane.terminal.?.vt.flags.dirty.clear = false; ingest(pane, bytes); + const cleared = pane.terminal.?.vt.flags.dirty.clear; // RIS can destroy the alternate screen and every pin it owned. const alive = if (screens.generation(key) == generation) pages else null; var moved = false; @@ -1065,7 +1069,15 @@ fn ingestWithPositions(pane: *Pane, bytes: []const u8) void { if (pin.garbage) pointer_rows_lost = true; }; }; + // The program cleared the screen, or the rows the live copy stood on are + // gone (pruned, a reset): the copy goes with them, as what the program + // drew next. Kept, ghostty would move its rows to the top of what is + // left, over the program's new text. + var copy_lost = cleared or alive == null; for (spans[0..nspans]) |span| { + if (span.overlay == overlay) if (span.start.pin) |pin| if (alive != null and pin.garbage) { + copy_lost = true; + }; const start = pinnedRow(alive, span.start); const rows = @max(1, pinnedRow(alive, span.end) -| start +| 1); moved = moved or start != span.overlay.row or rows != span.overlay.rows; @@ -1096,6 +1108,11 @@ fn ingestWithPositions(pane: *Pane, bytes: []const u8) void { pane.clearPointerSelection(button); pane.sel[button].state = .none; }; + if (copy_lost) if (pane.ovl) |copy| { + pane.gpa.free(copy.text); + pane.ovl = null; + moved = true; + }; if (moved) pane.nsel_snap = 0; // Saved regex-preview offsets name the old flat text. if (failed) { const message = "terminal edit position reset: out of memory"; @@ -1211,7 +1228,7 @@ pub fn commandOutput(pane: *Pane, gpa: std.mem.Allocator, max_rows: usize) !Comm .whole = whole, }; } else true; - return .{ .text = try gpa.dupeZ(u8, ""), .whole = whole }; + return .{ .text = try gpa.dupeSentinel(u8, "", 0), .whole = whole }; } /// At a prompt with nothing typed on its line: no input left of the @@ -2813,7 +2830,7 @@ pub fn redo(p: *Pardes, pane: *Pane) void { pane.ensureCursorVisible(); } -pub fn ptyReport(handler: *ghostty_vt.TerminalStream.Handler, data: [:0]const u8) void { +pub fn ptyReport(handler: *ghostty_vt.TerminalStream.Handler, data: []const u8) void { const state: *State = @alignCast(@fieldParentPtr("vt", handler.terminal)); const room = state.reply.len - state.reply_len; const n = @min(room, data.len); @@ -2968,7 +2985,8 @@ test "a program that asked for focus reports hears CSI I and CSI O as its pane t /// over two cells). inline fn kittyTransmit(comptime extra: []const u8) []const u8 { return comptime blk: { - const pixels = [_]u8{ 255, 0, 0, 255, 0, 0, 0, 0, 255, 0, 0, 255 } ** 2; + const row = [_]u8{ 255, 0, 0, 255, 0, 0, 0, 0, 255, 0, 0, 255 }; + const pixels = row ++ row; var buf: [std.base64.standard.Encoder.calcSize(pixels.len)]u8 = undefined; const b64 = std.base64.standard.Encoder.encode(&buf, &pixels)[0..buf.len].*; break :blk "\x1b_Ga=T,f=24,s=4,v=2,i=7," ++ extra ++ ";" ++ b64 ++ "\x1b\\"; diff --git a/src/tty/tty.zig b/src/tty/tty.zig index ca2cb939..82cb40bd 100644 --- a/src/tty/tty.zig +++ b/src/tty/tty.zig @@ -129,7 +129,7 @@ fn readInput(loop: *Loop, tty: anytype, cache: *vaxis.GraphemeCache) !void { var parser: vaxis.Parser = .{}; var buf: [1024]u8 = undefined; var carried: usize = 0; - while (!loop.should_quit) { + while (true) { // stopInput cancels the task; the read then fails with Canceled if (carried == buf.len) return error.InputSequenceTooLong; const received = try tty.read(buf[carried..]); if (received == 0) return; @@ -295,7 +295,7 @@ test "terminal input preserves fragmented keys queries paste and text after EOF" fn getWinsize(_: *@This()) !vaxis.Winsize { return .{ .rows = 24, .cols = 80, .x_pixel = 0, .y_pixel = 0 }; } - fn inputFollows(self: *@This(), _: u32) bool { + pub fn inputFollows(self: *@This(), _: u32) bool { return self.next < self.parts.len; } fn read(self: *@This(), buf: []u8) !usize { @@ -380,7 +380,7 @@ test "terminal replies and malformed sequences never become typed text" { fn getWinsize(_: *@This()) !vaxis.Winsize { return .{ .rows = 24, .cols = 80, .x_pixel = 0, .y_pixel = 0 }; } - fn inputFollows(self: *@This(), _: u32) bool { + pub fn inputFollows(self: *@This(), _: u32) bool { return self.next < self.parts.len; } fn read(self: *@This(), buf: []u8) !usize { @@ -465,7 +465,7 @@ test "terminal input split at every byte with a gap reads as it does whole" { fn getWinsize(_: *@This()) !vaxis.Winsize { return .{ .rows = 24, .cols = 80, .x_pixel = 0, .y_pixel = 0 }; } - fn inputFollows(self: *@This(), ms: u32) bool { + pub fn inputFollows(self: *@This(), ms: u32) bool { return self.next < self.parts.len and self.gap_ms <= ms; } fn read(self: *@This(), buf: []u8) !usize { @@ -561,7 +561,7 @@ test "an ESC read by itself is the Escape key at once" { fn getWinsize(_: *@This()) !vaxis.Winsize { return .{ .rows = 24, .cols = 80, .x_pixel = 0, .y_pixel = 0 }; } - fn inputFollows(self: *@This(), _: u32) bool { + pub fn inputFollows(self: *@This(), _: u32) bool { self.asked = true; return self.next < self.parts.len; } @@ -609,7 +609,7 @@ test "a frame's answer is taken wherever the reads cut it, and never typed" { fn getWinsize(_: *@This()) !vaxis.Winsize { return .{ .rows = 24, .cols = 80, .x_pixel = 0, .y_pixel = 0 }; } - fn inputFollows(self: *@This(), _: u32) bool { + pub fn inputFollows(self: *@This(), _: u32) bool { return self.next < self.parts.len; } fn read(self: *@This(), buf: []u8) !usize { @@ -701,7 +701,7 @@ test "terminal input cancellation joins blocked reads and queued EOF" { fn getWinsize(_: *@This()) !vaxis.Winsize { return .{ .rows = 24, .cols = 80, .x_pixel = 0, .y_pixel = 0 }; } - fn inputFollows(_: *@This(), _: u32) bool { + pub fn inputFollows(_: *@This(), _: u32) bool { return false; } fn read(self: *@This(), buf: []u8) !usize { @@ -2332,7 +2332,7 @@ test "a terminal pane gets function keys as their sequences and lone modifiers n fn getWinsize(_: *@This()) !vaxis.Winsize { return .{ .rows = 24, .cols = 80, .x_pixel = 0, .y_pixel = 0 }; } - fn inputFollows(self: *@This(), _: u32) bool { + pub fn inputFollows(self: *@This(), _: u32) bool { return self.next < self.parts.len; } fn read(self: *@This(), buf: []u8) !usize { @@ -3033,7 +3033,7 @@ test "a jump leaves a trail of a few cells behind the cursor that fades in 120 m const gpa = std.testing.allocator; const core = try pardes.Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24 }); defer core.deinit(); - _ = try core.setTestFile("some text on a line\n" ** 20); + _ = try core.setTestFile(std.mem.asBytes(&@as([20][20]u8, @splat("some text on a line\n".*)))); try std.testing.expect(core.executeBuiltinLine(0, "Theme forge")); core.settings.jump_trail = true; for (0..40) |_| core.update(.tick); @@ -3078,7 +3078,7 @@ test "a notice chip casts a cell's shadow right and down, inside its body, off t const gpa = std.testing.allocator; const core = try pardes.Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24 }); defer core.deinit(); - _ = try core.setTestFile("some text on a line\n" ** 20); + _ = try core.setTestFile(std.mem.asBytes(&@as([20][20]u8, @splat("some text on a line\n".*)))); try std.testing.expect(core.executeBuiltinLine(0, "Theme forge")); core.settings.chip_shadow = true; try std.testing.expect(core.executeBuiltinLine(0, "Msg a notice")); @@ -3114,7 +3114,7 @@ test "a scrolled pane's thumb brightens and fades back in 250 ms" { const gpa = std.testing.allocator; const core = try pardes.Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24 }); defer core.deinit(); - const pane = try core.setTestFile("some text on a line\n" ** 200); + const pane = try core.setTestFile(std.mem.asBytes(&@as([200][20]u8, @splat("some text on a line\n".*)))); try std.testing.expect(core.executeBuiltinLine(0, "Theme forge")); core.settings.thumb_flash = true; for (0..40) |_| core.update(.tick); diff --git a/test/deck/replay.zig b/test/deck/replay.zig index 475f7476..49614b46 100644 --- a/test/deck/replay.zig +++ b/test/deck/replay.zig @@ -20,8 +20,9 @@ const Tally = struct { fn replay(src: [:0]const u8) !Tally { const gpa = std.testing.allocator; - const rec = try schema.parse(gpa, src); - defer schema.free(gpa, rec); + var arena: std.heap.ArenaAllocator = .init(gpa); + defer arena.deinit(); + const rec = try schema.parse(gpa, arena.allocator(), src); var d: deck.Deck = .{}; var tally: Tally = .{}; for (rec.events) |ev| { diff --git a/test/deck/schema.zig b/test/deck/schema.zig index 782c829a..401e15e8 100644 --- a/test/deck/schema.zig +++ b/test/deck/schema.zig @@ -61,10 +61,8 @@ pub const Event = struct { }; }; -pub fn parse(gpa: std.mem.Allocator, src: [:0]const u8) error{ OutOfMemory, ParseZon }!Recording { - return std.zon.parse.fromSliceAlloc(Recording, gpa, src, null, .{}); -} - -pub fn free(gpa: std.mem.Allocator, rec: Recording) void { - std.zon.parse.free(gpa, rec); +/// The recording's slices live in `arena`. +pub fn parse(gpa: std.mem.Allocator, arena: std.mem.Allocator, src: [:0]const u8) error{ OutOfMemory, ParseZon }!Recording { + var diagnostics: std.zon.parse.Diagnostics = undefined; + return std.zon.parse.fromSlice(Recording, .{ .gpa = gpa, .arena = arena, .source = src, .diagnostics = &diagnostics }); } diff --git a/test/e2e_harness.zig b/test/e2e_harness.zig index 9e67c49f..a2010c19 100644 --- a/test/e2e_harness.zig +++ b/test/e2e_harness.zig @@ -104,7 +104,7 @@ pub const Harness = struct { term.* = try ghostty_vt.Terminal.init(std.Io.Threaded.global_single_threaded.io(), gpa, .{ .cols = cols, .rows = rows, - .max_scrollback = 1024 * 1024, + .max_scrollback_bytes = 1024 * 1024, }); errdefer term.deinit(gpa); // vtStream() captures a pointer to `term`; term is heap-allocated so the diff --git a/test/fs_bench.zig b/test/fs_bench.zig index 746fe737..4764049f 100644 --- a/test/fs_bench.zig +++ b/test/fs_bench.zig @@ -272,7 +272,7 @@ pub fn main(init: std.process.Init) !void { .tag = 9, .op = .write, .node = s.node(.body), - .data = "x" ** 1024, + .data = &@as([1024]u8, @splat('x')), .size = 1024, }, "append: whole-body swap + undo snapshot"); @@ -327,7 +327,7 @@ pub fn main(init: std.process.Init) !void { try w.writeAll("]}\n"); } else { try w.print("{s:<26} {s:>9} {s:>8} {s}\n", .{ "request", "ns/op", "allocs", "note" }); - try w.print("{s:<26} {s:>9} {s:>8} {s}\n", .{ "-" ** 26, "-" ** 9, "-" ** 8, "-" ** 20 }); + try w.print("{s:<26} {s:>9} {s:>8} {s}\n", .{ &@as([26]u8, @splat('-')), &@as([9]u8, @splat('-')), &@as([8]u8, @splat('-')), &@as([20]u8, @splat('-')) }); for (rows.items) |r| try w.print("{s:<26} {d:>9} {d:>8} {s}\n", .{ r.name, r.ns, r.allocs, r.note }); } diff --git a/test/history.zig b/test/history.zig index 5ce45239..d399f7aa 100644 --- a/test/history.zig +++ b/test/history.zig @@ -432,24 +432,24 @@ test "history benchmark cases are nonempty unique and matched by name" { try std.testing.expectError(error.MissingField, readBenchmarks(arena, "{\"case\":\"first\"}")); const before = try readBenchmarks(arena, benchmark_fixture); const missing = try readBenchmarks(arena, "{\"case\":\"first\",\"bytes\":10,\"median_ns\":100,\"cold_ns\":100,\"allocations\":10,\"allocated_bytes\":1000}"); - try std.testing.expectError(error.DifferentBenchmarks, compareBenchmarks(.{before} ** 4, .{missing} ** 4, null, &report.writer)); + try std.testing.expectError(error.DifferentBenchmarks, compareBenchmarks(@splat(before), @splat(missing), null, &report.writer)); const renamed = \\{"case":"first","bytes":10,"median_ns":100,"cold_ns":100,"allocations":10,"allocated_bytes":1000} \\{"case":"renamed","bytes":20,"median_ns":100,"cold_ns":100,"allocations":10,"allocated_bytes":1000} ; const different = try readBenchmarks(arena, renamed); - try std.testing.expectError(error.DifferentBenchmarks, compareBenchmarks(.{before} ** 4, .{different} ** 4, null, &report.writer)); + try std.testing.expectError(error.DifferentBenchmarks, compareBenchmarks(@splat(before), @splat(different), null, &report.writer)); const reordered = \\{"case":"last","bytes":20,"median_ns":100,"cold_ns":100,"allocations":10,"allocated_bytes":1000} \\{"case":"first","bytes":10,"median_ns":100,"cold_ns":100,"allocations":10,"allocated_bytes":1000} ; const same = try readBenchmarks(arena, reordered); - try std.testing.expect(!try compareBenchmarks(.{before} ** 4, .{same} ** 4, 1, &report.writer)); + try std.testing.expect(!try compareBenchmarks(@splat(before), @splat(same), 1, &report.writer)); var samples = [4][]Benchmark{ before, before, before, different }; - try std.testing.expectError(error.DifferentBenchmarks, compareBenchmarks(.{before} ** 4, samples, null, &report.writer)); + try std.testing.expectError(error.DifferentBenchmarks, compareBenchmarks(@splat(before), samples, null, &report.writer)); samples[3] = try arena.dupe(Benchmark, before); samples[3][0].bytes += 1; - try std.testing.expectError(error.DifferentBenchmarkInputs, compareBenchmarks(.{before} ** 4, samples, null, &report.writer)); + try std.testing.expectError(error.DifferentBenchmarkInputs, compareBenchmarks(@splat(before), samples, null, &report.writer)); } test "history benchmark gate uses repeated process captures rather than the first process alone" { diff --git a/test/hxdiff.zig b/test/hxdiff.zig index 48c7ab93..b12bcd8e 100644 --- a/test/hxdiff.zig +++ b/test/hxdiff.zig @@ -39,7 +39,7 @@ pub fn main(init: std.process.Init) !void { var pane_override: ?[]const u8 = null; var goldens_path: ?[]const u8 = null; var waivers_path: ?[]const u8 = null; - const paths = try arena.alloc([]const u8, args.len - 1); + const paths = try arena.alloc([]const u8, @max(args.len - 1, 3)); // room for the defaults below var n_paths: usize = 0; var want_waivers = false; for (args[1..]) |a| { @@ -67,6 +67,18 @@ pub fn main(init: std.process.Init) !void { n_paths += 1; } } + // Named nothing (`zig build hxdiff` or `hxparity` bare): the checked-in + // suite, run from the repository root. + if (n_paths == 0 and !want_waivers) { + strict = true; + const defaults: []const []const u8 = if (parity) + &.{ "test/hxcases/cases.jsonl", "test/hxcases/parity.jsonl" } + else + &.{ "test/hxcases/cases.jsonl", "test/hxcases/goldens.jsonl", "test/hxcases/waivers.jsonl" }; + if (parity) waivers_path = waivers_path orelse "test/hxcases/parity-waivers.jsonl"; + @memcpy(paths[0..defaults.len], defaults); + n_paths = defaults.len; + } if (n_paths == 0 or want_waivers) fatal("usage: pardes-hxdiff [--parity] ... [goldens.jsonl [waivers.jsonl]]", .{}); const case_paths = paths[0..if (parity) n_paths else 1]; diff --git a/test/image_harness.zig b/test/image_harness.zig index 474ec48b..b45851cc 100644 --- a/test/image_harness.zig +++ b/test/image_harness.zig @@ -38,7 +38,7 @@ pub fn main(init: std.process.Init) !void { const args = try init.minimal.args.toSlice(arena); if (args.len != 3 and args.len != 4) return error.BadArgs; - const exe = try arena.dupeZ(u8, args[1]); + const exe = try arena.dupeSentinel(u8, args[1], 0); const backend = args[2]; const pdf_mode = args.len == 4 and std.mem.eql(u8, args[3], "pdf"); if (args.len == 4 and !pdf_mode) return error.BadArgs; diff --git a/test/lspbench.zig b/test/lspbench.zig index 02138d24..d0e25aee 100644 --- a/test/lspbench.zig +++ b/test/lspbench.zig @@ -216,7 +216,7 @@ fn reportText(rs: []const Result, rss: u64) void { const o = std.debug.print; o("backend: {s}\n\n", .{lsp.backend_name}); o("{s:<24} {s:>9} {s:>7} {s:>10} {s:>10} {s}\n", .{ "kind", "supports", "rows", "cold(us)", "warm(us)", "verdict" }); - o("{s}\n", .{"-" ** 78}); + o("{s}\n", .{&@as([78]u8, @splat('-'))}); var claimed: usize = 0; var working: usize = 0; var lies: usize = 0; diff --git a/test/monkey.zig b/test/monkey.zig index 83869ce4..dcea0b43 100644 --- a/test/monkey.zig +++ b/test/monkey.zig @@ -44,7 +44,7 @@ fn generate(gpa: std.mem.Allocator, seed: u64, steps: usize) ![]u8 { var s: Script = .{ .gpa = gpa }; try s.line("# pardes-monkey seed {d}, {d} steps", .{ seed, steps }); try s.line("file bad.txt hello \\xff\\xfe world\\nlatin-1 caf\\xe9 tail\\ntruncated \\xe6\\x97 here\\nend\\n", .{}); - try s.line("file wide.txt {s}tail\\nsecond line\\n", .{"\\xe6\\x97\\xa5\\xe6\\x9c\\xac\\xe8\\xaa\\x9e " ** 8}); + try s.line("file wide.txt {s}tail\\nsecond line\\n", .{std.mem.asBytes(&@as([8][37]u8, @splat("\\xe6\\x97\\xa5\\xe6\\x9c\\xac\\xe8\\xaa\\x9e ".*)))}); try s.line("lines long.txt 400 some words after the number, long enough to wrap in a narrow pane", .{}); try s.line("start 24 80 bad.txt", .{}); try s.line("wait 8000 Newcol Joincol", .{}); diff --git a/test/panes.zig b/test/panes.zig index 86e52838..54100f91 100644 --- a/test/panes.zig +++ b/test/panes.zig @@ -42,7 +42,7 @@ const TagLayerTests = struct { p.row_metrics = .{ .body_w = 10, .body_h = 20, .tagline_w = 5, .tagline_h = 10 }; p.gpa.free(pane.file.?.path); pane.file.?.path = try p.gpa.dupe(u8, "/x"); - try setTag(pane, " " ++ "a" ** 38 ++ "\t界 END"); + try setTag(pane, " " ++ &@as([38]u8, @splat('a')) ++ "\t界 END"); var frame = std.heap.ArenaAllocator.init(p.gpa); defer frame.deinit(); _ = try p.render(frame.allocator()); @@ -135,7 +135,7 @@ const TagLayerTests = struct { try std.testing.expectEqual(@as(i32, 0), p.panes[second].?.input.cur_col); p.update(.{ .key = .{ .cp = Key.escape } }); const left = p.panes[0].?; - try setTag(left, " " ++ "a" ** 110); + try setTag(left, " " ++ &@as([110]u8, @splat('a'))); _ = try p.render(frame.allocator()); const left_layer = try findLayer(p, .pane, 0); const left_text = try pardes.tagline.tagText(p, frame.allocator(), left); @@ -149,7 +149,7 @@ const TagLayerTests = struct { try std.testing.expectEqual(panes.File.rawAtDisplay(left_text, end_col), @as(usize, @intCast(left.tag.cur_col))); try std.testing.expect(left.sel[0].state == .done and left.sel[0].r0 == 0); p.update(.{ .key = .{ .cp = Key.escape } }); - const long = "a" ** 60 ++ "界END"; + const long = &@as([60]u8, @splat('a')) ++ "界END"; p.global_tag.own = try p.gpa.dupe(u8, long); for (p.col_tags[0..p.ncol]) |*tag| tag.own = try p.gpa.dupe(u8, long); _ = try p.render(frame.allocator()); @@ -581,7 +581,7 @@ const BodyHitTests = struct { const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 64, .rows = 18 }); defer p.deinit(); p.row_metrics = .{ .body_w = 10, .body_h = 20, .tagline_w = 8, .tagline_h = 10 }; - const pane = try TreeContextTests.setZigFile(p, "const Box = struct {\n pub fn work(\n value: usize,\n ) void {\n" ++ " // body\n" ** 60 ++ " }\n};\n"); + const pane = try TreeContextTests.setZigFile(p, "const Box = struct {\n pub fn work(\n value: usize,\n ) void {\n" ++ std.mem.asBytes(&@as([60][16]u8, @splat(" // body\n".*))) ++ " }\n};\n"); try std.testing.expect(p.executeBuiltinLine(0, "TreeContext")); pane.scrollBy(10); var frame = std.heap.ArenaAllocator.init(p.gpa); @@ -629,7 +629,7 @@ const LineNumberLookTests = struct { const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 64, .rows = 18 }); defer p.deinit(); p.row_metrics = .{ .body_w = 10, .body_h = 20, .tagline_w = 8, .tagline_h = 10 }; - const pane = try TreeContextTests.setZigFile(p, "const Box = struct {\n pub fn work(\n value: usize,\n ) void {\n" ++ " // body\n" ** 60 ++ " }\n};\n"); + const pane = try TreeContextTests.setZigFile(p, "const Box = struct {\n pub fn work(\n value: usize,\n ) void {\n" ++ std.mem.asBytes(&@as([60][16]u8, @splat(" // body\n".*))) ++ " }\n};\n"); try std.testing.expect(p.executeBuiltinLine(0, "TreeContext")); pane.scrollBy(30); var frame = std.heap.ArenaAllocator.init(p.gpa); @@ -686,7 +686,7 @@ const TreeContextTests = struct { if (!syntax.enabled) return error.SkipZigTest; const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 64, .rows = 18 }); defer p.deinit(); - const pane = try setZigFile(p, "const Box = struct {\n\n // omitted member comment\n\n pub fn work(\n value: usize,\n ) void {\n" ++ " // body\n" ** 30 ++ " }\n};\n"); + const pane = try setZigFile(p, "const Box = struct {\n\n // omitted member comment\n\n pub fn work(\n value: usize,\n ) void {\n" ++ std.mem.asBytes(&@as([30][16]u8, @splat(" // body\n".*))) ++ " }\n};\n"); p.row_metrics = .{ .body_w = 10, .body_h = 20, .tagline_w = 8, .tagline_h = 10 }; try std.testing.expect(p.executeBuiltinLine(0, "TreeContext")); pane.scrollBy(10); @@ -717,7 +717,7 @@ const TreeContextTests = struct { if (context and !syntax.enabled) continue; const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 64, .rows = 18 }); defer p.deinit(); - const pane = try setZigFile(p, "pub fn work() void {\n" ++ " // body\n" ** 100 ++ "}\n"); + const pane = try setZigFile(p, "pub fn work() void {\n" ++ std.mem.asBytes(&@as([100][12]u8, @splat(" // body\n".*))) ++ "}\n"); if (context) try std.testing.expect(p.executeBuiltinLine(0, "TreeContext")); var frame = std.heap.ArenaAllocator.init(p.gpa); defer frame.deinit(); @@ -792,7 +792,7 @@ const TreeContextTests = struct { if (!syntax.enabled) return error.SkipZigTest; const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 48, .rows = 14 }); defer p.deinit(); - const pane = try setZigFile(p, "pub fn @\"界name\"(\n\tvalue: usize,\n) void {\n" ++ " _ = value;\n" ** 12 ++ "}\n"); + const pane = try setZigFile(p, "pub fn @\"界name\"(\n\tvalue: usize,\n) void {\n" ++ std.mem.asBytes(&@as([12][15]u8, @splat(" _ = value;\n".*))) ++ "}\n"); pane.tag_expanded = false; // a one-row tag keeps this small screen's rows p.sync(); p.settings.wrap = false; @@ -820,7 +820,7 @@ const TreeContextTests = struct { // Read the body top again: the click cleared the announcement band the // builtin above put up, so the body moved with it. try std.testing.expectEqual(p.bodyTop(pane, p.rects[0]), cursor.y); - panes.File.setContent(p, &pane.file.?, try p.gpa.dupe(u8, "// no enclosing declaration\n" ** 18)); + panes.File.setContent(p, &pane.file.?, try p.gpa.dupe(u8, std.mem.asBytes(&@as([18][28]u8, @splat("// no enclosing declaration\n".*))))); _ = try p.render(frame.allocator()); try std.testing.expectEqual(@as(u16, 0), pane.context_rows); try std.testing.expectEqual(pane.scroll(), pane.wrapAt(0).line); @@ -942,7 +942,7 @@ const TtySelectionTests = struct { try noChildInput(p); _ = try p.render(frame.allocator()); try std.testing.expectEqualStrings(expected, pardes.test_api.heldSelection(p, 0).?); - p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b]133;C\x07" ++ "\r\nnew output" ** 30 } }); + p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b]133;C\x07" ++ std.mem.asBytes(&@as([30][12]u8, @splat("\r\nnew output".*))) } }); _ = try p.render(frame.allocator()); try std.testing.expectEqual(panes.Text.Mode.tty, pane.body.mode); try std.testing.expectEqualStrings(expected, pardes.test_api.heldSelection(p, 0).?); @@ -1266,7 +1266,7 @@ const ClickCursorTests = struct { test "click operands and hover follow the scrolled source selection" { const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 40, .rows = 14 }); defer p.deinit(); - const pane = try p.setTestFile("zero\none\ntwo\nthree\nalpha beta\nfive\ngamma delta\nseven\n" ++ "tail\n" ** 20); + const pane = try p.setTestFile("zero\none\ntwo\nthree\nalpha beta\nfive\ngamma delta\nseven\n" ++ std.mem.asBytes(&@as([20][5]u8, @splat("tail\n".*)))); p.presentation.enabled = false; p.settings.wrap = false; var frame = std.heap.ArenaAllocator.init(p.gpa); @@ -1323,7 +1323,7 @@ const JumpSelectionTests = struct { const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 34, .rows = 10 }); defer p.deinit(); p.settings.wrap = wrap; - const text = try std.fmt.allocPrint(p.gpa, "{s}{s}", .{ prefix, "unrelated destination text\n" ** 80 }); + const text = try std.fmt.allocPrint(p.gpa, "{s}{s}", .{ prefix, std.mem.asBytes(&@as([80][27]u8, @splat("unrelated destination text\n".*))) }); defer p.gpa.free(text); const pane = try p.setTestFile(text); var frame = std.heap.ArenaAllocator.init(p.gpa); @@ -1813,7 +1813,7 @@ test "a word the tag's wrapping breaks across rows is still one word to a click" var pad: usize = 1; const shown = while (pad < 80) : (pad += 1) { p.gpa.free(pane.file.?.path); - const path = try std.fmt.allocPrint(arena.allocator(), "/{s}/f.zig", .{("a" ** 80)[0..pad]}); + const path = try std.fmt.allocPrint(arena.allocator(), "/{s}/f.zig", .{(&@as([80]u8, @splat('a')))[0..pad]}); pane.file.?.path = try p.gpa.dupe(u8, path); p.sync(); const s = try pardes.tagline.shownTag(p, arena.allocator(), pane); @@ -1866,7 +1866,7 @@ test "terminal output keeps following new rows after scrollback eviction" { pane.body.mode = .tty; pane.tty_filter = false; const pages = &pane.terminal.?.vt.screens.active.pages; - pages.explicit_max_size = 64 * 1024; + pages.limits.set(.bytes, 64 * 1024); var frame = std.heap.ArenaAllocator.init(gpa); defer frame.deinit(); var evictions: usize = 0; @@ -1885,7 +1885,7 @@ test "terminal output keeps following new rows after scrollback eviction" { if (pages.scrollbar().total < previous) evictions += 1; } try std.testing.expect(evictions > phase); - try std.testing.expect(pages.page_size <= pages.maxSize()); + try std.testing.expect(pages.page_size <= pages.limits.max(.bytes)); const sb = pages.scrollbar(); try std.testing.expectEqual(sb.total - pane.rows, sb.offset); const full = try panes.terminal.screenTextAlloc(pane, gpa); @@ -1926,7 +1926,7 @@ test "terminal edit stays on its surviving row when old scrollback is evicted" { const pane = p.panes[0].?; pane.body.mode = .tty; const pages = &pane.terminal.?.vt.screens.active.pages; - pages.explicit_max_size = 64 * 1024; + pages.limits.set(.bytes, 64 * 1024); var next: usize = 0; while (next < 3000) { var buf: [32]u8 = undefined; @@ -1977,9 +1977,9 @@ test "terminal edits and undo survive partial history clearing and whole-screen pane.body.mode = .tty; if (action == .reset_alternate) p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[?1049h" } }); - p.update(.{ .output = .{ .pane = 0, .bytes = "old row\r\n" ** 40 } }); + p.update(.{ .output = .{ .pane = 0, .bytes = std.mem.asBytes(&@as([40][9]u8, @splat("old row\r\n".*))) } }); const pages = &pane.terminal.?.vt.screens.active.pages; - pages.explicit_max_size = 64 * 1024; + pages.limits.set(.bytes, 64 * 1024); const row: i32 = @as(i32, @intCast(pages.total_rows - pane.rows)) + @as(i32, if (action == .partial_clear_history) -1 else 2); pane.body.mode = .normal; @@ -2005,7 +2005,7 @@ test "terminal edits and undo survive partial history clearing and whole-screen const bytes = switch (action) { .clear_history, .partial_clear_history => "\x1b[3J", .reset_primary, .reset_alternate => "\x1bc", - .evict_all, .hidden_undo => "new row\r\n" ** 4000, + .evict_all, .hidden_undo => std.mem.asBytes(&@as([4000][9]u8, @splat("new row\r\n".*))), }; p.update(.{ .output = .{ .pane = 0, .bytes = bytes } }); const expected: i32 = if (action == .clear_history) 2 else 0; @@ -2045,7 +2045,7 @@ test "terminal lower scroll regions do not move edits above them" { var setup: [64]u8 = undefined; const bytes = try std.fmt.bufPrint(&setup, "\x1b[4;{d}r\x1b[{d};1H", .{ pane.rows, pane.rows }); p.update(.{ .output = .{ .pane = 0, .bytes = bytes } }); - p.update(.{ .output = .{ .pane = 0, .bytes = "tail\r\n" ** 50 } }); + p.update(.{ .output = .{ .pane = 0, .bytes = std.mem.asBytes(&@as([50][6]u8, @splat("tail\r\n".*))) } }); try std.testing.expectEqual(total, panes.terminal.scrollbar(pane).total); try std.testing.expectEqual(@as(i32, 1), pane.ovl.?.row); try std.testing.expectEqual(@as(i32, 1), pane.body.cur_row); @@ -2064,7 +2064,7 @@ test "terminal eviction and lower-region scrolling in one read preserve a surviv const pane = p.panes[0].?; pane.body.mode = .tty; const pages = &pane.terminal.?.vt.screens.active.pages; - pages.explicit_max_size = 64 * 1024; + pages.limits.set(.bytes, 64 * 1024); var next: usize = 0; while (next < 3000) { var buf: [32]u8 = undefined; @@ -2229,7 +2229,7 @@ test "prompt cancellation restores the selection before regex previews" { } test "a prompt that cannot be opened leaves the open one as it was" { - const Request = @typeInfo(@TypeOf(Pardes.startPrompt)).@"fn".params[3].type.?; + const Request = @typeInfo(@TypeOf(Pardes.startPrompt)).@"fn".param_types[3].?; for ([_]Request{ .{ .search = config.search_marker }, .save, .{ .pipe = .replace }, .{ .pipe = .ignore }, .{ .pipe = .insert }, .{ .pipe = .append } }) |request| { var failing = std.testing.FailingAllocator.init(std.testing.allocator, .{}); const p = try Pardes.init(failing.allocator(), .{ .tty_only = true }); @@ -2268,7 +2268,7 @@ test "Save's prompt starts from the pane's directory" { } test "a prompt opens with one allocation" { - const Request = @typeInfo(@TypeOf(Pardes.startPrompt)).@"fn".params[3].type.?; + const Request = @typeInfo(@TypeOf(Pardes.startPrompt)).@"fn".param_types[3].?; for ([_]Request{ .{ .search = config.search_marker }, .save, .{ .pipe = .replace }, .{ .pipe = .ignore }, .{ .pipe = .insert }, .{ .pipe = .append } }) |request| { var failing = std.testing.FailingAllocator.init(std.testing.allocator, .{}); const p = try Pardes.init(failing.allocator(), .{ .tty_only = true }); @@ -3441,7 +3441,7 @@ const PdfTests = struct { defer probe.deinit(std.testing.allocator); try std.testing.expectEqual(@as(usize, 0), probe.page); try std.testing.expect(probe.quads.len > 0); - try std.testing.expect(std.ascii.indexOfIgnoreCase(probe.text, "Pardes") != null); + try std.testing.expect(std.ascii.findIgnoreCase(probe.text, "Pardes") != null); } test "PDF point mapping restores band origin and fractional placement" { @@ -4812,7 +4812,7 @@ test "growing a file pane colors every newly visible Zig keyword" { const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 8 }); defer p.deinit(); - const pane = try p.setTestFile("pub fn f() void { if (true) {} }\n" ** 100); + const pane = try p.setTestFile(std.mem.asBytes(&@as([100][33]u8, @splat("pub fn f() void { if (true) {} }\n".*)))); const file = &pane.file.?; gpa.free(file.path); file.path = try gpa.dupe(u8, "/resize.zig"); diff --git a/test/pdf.zig b/test/pdf.zig index a0eb8154..a51fd1a9 100644 --- a/test/pdf.zig +++ b/test/pdf.zig @@ -2080,14 +2080,14 @@ test "PDF native mouse selection, Look, and highlights share page geometry" { @as(i32, r.y + r.h - 1), )); if (!panes.Pdf.beginSelection(p, pane, col, row)) continue; - if (std.ascii.indexOfIgnoreCase(pv.selection_text, "Pardes") != null) { + if (std.ascii.findIgnoreCase(pv.selection_text, "Pardes") != null) { selected_col = col; selected_row = row; break :find_word; } }; const word_col = selected_col orelse return error.PdfMouseMappingMissedWord; - try std.testing.expect(std.ascii.indexOfIgnoreCase( + try std.testing.expect(std.ascii.findIgnoreCase( pardes.test_api.heldSelection(p, 0).?, "Pardes", ) != null); @@ -2142,7 +2142,7 @@ test "PDF native mouse selection, Look, and highlights share page geometry" { const hover = p.pdf_hover_preview orelse return error.MissingPdfHoverPreview; try std.testing.expectEqual(@as(usize, 0), hover.probe.page); try std.testing.expect(hover.probe.quads.len > 0); - try std.testing.expect(std.ascii.indexOfIgnoreCase(hover.probe.text, "Pardes") != null); + try std.testing.expect(std.ascii.findIgnoreCase(hover.probe.text, "Pardes") != null); try std.testing.expect(p.look_hover_preview == null); try std.testing.expect(p.look_hover_wait == null); @@ -2188,7 +2188,7 @@ test "PDF native mouse selection, Look, and highlights share page geometry" { // search highlights without carrying an old selection into the result. p.update(.{ .mouse = .{ .button = config.look_button, .kind = .press, .col = word_col, .row = selected_row } }); p.update(.{ .mouse = .{ .button = config.look_button, .kind = .release, .col = word_col, .row = selected_row } }); - try std.testing.expect(std.ascii.indexOfIgnoreCase(pv.search_query, "Pardes") != null); + try std.testing.expect(std.ascii.findIgnoreCase(pv.search_query, "Pardes") != null); pv.resolveSearch(p.pdf_gpa); const highlights = (try panes.Pdf.buildHighlights( pv, diff --git a/test/pdf_scroll_bench.zig b/test/pdf_scroll_bench.zig index 166fa809..fdc42660 100644 --- a/test/pdf_scroll_bench.zig +++ b/test/pdf_scroll_bench.zig @@ -597,7 +597,7 @@ fn reportText(config: Config, travel: Travel, results: []const Result) void { "total_us", "rasters", "kept", "peak_kib", "visual", "transport", }); - std.debug.print("{s}\n", .{"-" ** 160}); + std.debug.print("{s}\n", .{&@as([160]u8, @splat('-'))}); for (results) |result| std.debug.print( "{s:<16} {d:>6} {d:>7} {d:>10} {d:>10} {d:>10} {d:>10} {d:>10} {d:>11} {d:>7} {d:>5} {d:>9} {x:0>16} {x:0>16}\n", .{ diff --git a/test/pdf_sections_bench.zig b/test/pdf_sections_bench.zig index 92c9ef7c..ee26e83d 100644 --- a/test/pdf_sections_bench.zig +++ b/test/pdf_sections_bench.zig @@ -454,7 +454,7 @@ fn reportText(config: Config, results: []const Result) void { std.debug.print("{s:<42} {s:>10} {s:>10} {s:>10} {s:>10} {s:>8} {s:>8} {s}\n", .{ "scenario", "min", "median", "p90", "max", "items", "bytes", "checksum", }); - std.debug.print("{s}\n", .{"-" ** 124}); + std.debug.print("{s}\n", .{&@as([124]u8, @splat('-'))}); for (results) |result| std.debug.print( "{s:<42} {d:>10} {d:>10} {d:>10} {d:>10} {d:>8} {d:>8} {x:0>16}\n", .{ diff --git a/test/perf-baseline-gui-Debug.json b/test/perf-baseline-gui-Debug.json deleted file mode 100644 index 39f5913c..00000000 --- a/test/perf-baseline-gui-Debug.json +++ /dev/null @@ -1 +0,0 @@ -{"harness":"303736f83a625e87","build":{"compiler":"0.16.0","target":"x86_64-linux.5.10...6.19-gnu.2.38","cpu":"x86_64","driver_optimize":"ReleaseFast","core_optimize":"Debug","c_optimize":"ReleaseFast","terminal_optimize":"ReleaseSafe","platform":"gui","grammars":"full","mupdf":true,"jpx":true,"tracy":false,"quic":false,"theme_animation":true,"terminal_simd":true,"prebuilt_shaders":false},"cols":120,"rows":40,"reps":10,"only":"medium","fixtures":[{"name":"small","lines":1000,"cols":60,"bytes":62694},{"name":"medium","lines":50000,"cols":60,"bytes":3201944},{"name":"large","lines":300000,"cols":60,"bytes":19464444},{"name":"longline","lines":400,"cols":8000,"bytes":3200400},{"name":"esp32p4","lines":12,"cols":240,"bytes":2892}],"cells":[{"op":"open","fixture":"medium","min_us":1818,"med_us":2104,"p90_us":2287,"max_us":2293},{"op":"render","fixture":"medium","min_us":78,"med_us":82,"p90_us":87,"max_us":87},{"op":"key-down","fixture":"medium","min_us":79,"med_us":81,"p90_us":89,"max_us":109},{"op":"key-right","fixture":"medium","min_us":79,"med_us":84,"p90_us":85,"max_us":89},{"op":"page-down","fixture":"medium","min_us":79,"med_us":81,"p90_us":84,"max_us":87},{"op":"wheel","fixture":"medium","min_us":77,"med_us":78,"p90_us":82,"max_us":82},{"op":"edit-char","fixture":"medium","min_us":1019,"med_us":1349,"p90_us":1597,"max_us":1632},{"op":"edit-twin","fixture":"medium","min_us":2029,"med_us":2353,"p90_us":2455,"max_us":2676},{"op":"body-2m","fixture":"medium","min_us":5978,"med_us":9708,"p90_us":11361,"max_us":11666},{"op":"body-appends","fixture":"medium","min_us":117933,"med_us":211247,"p90_us":268014,"max_us":275006},{"op":"deep-sel","fixture":"medium","min_us":73,"med_us":75,"p90_us":80,"max_us":84}]} diff --git a/test/perf-baseline-gui-debug.json b/test/perf-baseline-gui-debug.json new file mode 100644 index 00000000..4b60520b --- /dev/null +++ b/test/perf-baseline-gui-debug.json @@ -0,0 +1 @@ +{"harness":"6cf9f4b8943e7e29","build":{"compiler":"0.17.0","target":"x86_64-linux.5.10...7.2-gnu.2.38","cpu":"x86_64","driver_optimize":"fast","core_optimize":"debug","c_optimize":"fast","terminal_optimize":"safe","platform":"gui","grammars":"full","mupdf":true,"jpx":true,"tracy":false,"quic":false,"theme_animation":true,"terminal_simd":true,"prebuilt_shaders":false},"cols":120,"rows":40,"reps":10,"only":"medium","fixtures":[{"name":"small","lines":1000,"cols":60,"bytes":62694},{"name":"medium","lines":50000,"cols":60,"bytes":3201944},{"name":"large","lines":300000,"cols":60,"bytes":19464444},{"name":"longline","lines":400,"cols":8000,"bytes":3200400},{"name":"esp32p4","lines":12,"cols":240,"bytes":2892}],"cells":[{"op":"open","fixture":"medium","min_us":1732,"med_us":1881,"p90_us":2035,"max_us":2072},{"op":"render","fixture":"medium","min_us":89,"med_us":92,"p90_us":101,"max_us":102},{"op":"key-down","fixture":"medium","min_us":92,"med_us":94,"p90_us":100,"max_us":100},{"op":"key-right","fixture":"medium","min_us":91,"med_us":93,"p90_us":105,"max_us":109},{"op":"page-down","fixture":"medium","min_us":91,"med_us":95,"p90_us":99,"max_us":106},{"op":"wheel","fixture":"medium","min_us":90,"med_us":95,"p90_us":101,"max_us":101},{"op":"edit-char","fixture":"medium","min_us":1226,"med_us":1678,"p90_us":2093,"max_us":2323},{"op":"edit-twin","fixture":"medium","min_us":2275,"med_us":2697,"p90_us":2868,"max_us":2920},{"op":"body-2m","fixture":"medium","min_us":5213,"med_us":11333,"p90_us":18974,"max_us":18999},{"op":"body-appends","fixture":"medium","min_us":175012,"med_us":260087,"p90_us":317184,"max_us":317469},{"op":"deep-sel","fixture":"medium","min_us":83,"med_us":85,"p90_us":86,"max_us":98}]} diff --git a/test/perf-baseline-tty-Debug.json b/test/perf-baseline-tty-Debug.json deleted file mode 100644 index 9110398c..00000000 --- a/test/perf-baseline-tty-Debug.json +++ /dev/null @@ -1 +0,0 @@ -{"harness":"303736f83a625e87","build":{"compiler":"0.16.0","target":"x86_64-linux.5.10...6.19-gnu.2.38","cpu":"x86_64","driver_optimize":"ReleaseFast","core_optimize":"Debug","c_optimize":"ReleaseFast","terminal_optimize":"ReleaseSafe","platform":"tty","grammars":"full","mupdf":true,"jpx":true,"tracy":false,"quic":false,"theme_animation":true,"terminal_simd":true,"prebuilt_shaders":false},"cols":120,"rows":40,"reps":10,"only":"medium","fixtures":[{"name":"small","lines":1000,"cols":60,"bytes":62694},{"name":"medium","lines":50000,"cols":60,"bytes":3201944},{"name":"large","lines":300000,"cols":60,"bytes":19464444},{"name":"longline","lines":400,"cols":8000,"bytes":3200400},{"name":"esp32p4","lines":12,"cols":240,"bytes":2892}],"cells":[{"op":"open","fixture":"medium","min_us":1881,"med_us":2148,"p90_us":2324,"max_us":2644},{"op":"render","fixture":"medium","min_us":79,"med_us":87,"p90_us":90,"max_us":93},{"op":"key-down","fixture":"medium","min_us":81,"med_us":84,"p90_us":86,"max_us":90},{"op":"key-right","fixture":"medium","min_us":80,"med_us":85,"p90_us":89,"max_us":102},{"op":"page-down","fixture":"medium","min_us":85,"med_us":86,"p90_us":88,"max_us":88},{"op":"wheel","fixture":"medium","min_us":79,"med_us":85,"p90_us":90,"max_us":91},{"op":"edit-char","fixture":"medium","min_us":1037,"med_us":1300,"p90_us":1639,"max_us":1647},{"op":"edit-twin","fixture":"medium","min_us":2046,"med_us":2378,"p90_us":2529,"max_us":2585},{"op":"body-2m","fixture":"medium","min_us":5790,"med_us":9510,"p90_us":12226,"max_us":12462},{"op":"body-appends","fixture":"medium","min_us":132421,"med_us":224849,"p90_us":257368,"max_us":274890},{"op":"deep-sel","fixture":"medium","min_us":75,"med_us":80,"p90_us":84,"max_us":86}]} diff --git a/test/perf-baseline-tty-ReleaseFast.json b/test/perf-baseline-tty-ReleaseFast.json deleted file mode 100644 index 4cbc8b95..00000000 --- a/test/perf-baseline-tty-ReleaseFast.json +++ /dev/null @@ -1 +0,0 @@ -{"harness":"303736f83a625e87","build":{"compiler":"0.16.0","target":"x86_64-linux.5.10...6.19-gnu.2.38","cpu":"x86_64","driver_optimize":"ReleaseFast","core_optimize":"ReleaseFast","c_optimize":"ReleaseFast","terminal_optimize":"ReleaseFast","platform":"tty","grammars":"full","mupdf":true,"jpx":true,"tracy":false,"quic":false,"theme_animation":true,"terminal_simd":true,"prebuilt_shaders":false},"cols":120,"rows":40,"reps":10,"only":"medium","fixtures":[{"name":"small","lines":1000,"cols":60,"bytes":62694},{"name":"medium","lines":50000,"cols":60,"bytes":3201944},{"name":"large","lines":300000,"cols":60,"bytes":19464444},{"name":"longline","lines":400,"cols":8000,"bytes":3200400},{"name":"esp32p4","lines":12,"cols":240,"bytes":2892}],"cells":[{"op":"open","fixture":"medium","min_us":1775,"med_us":1995,"p90_us":2092,"max_us":2094},{"op":"render","fixture":"medium","min_us":80,"med_us":86,"p90_us":89,"max_us":95},{"op":"key-down","fixture":"medium","min_us":81,"med_us":83,"p90_us":95,"max_us":101},{"op":"key-right","fixture":"medium","min_us":79,"med_us":84,"p90_us":85,"max_us":98},{"op":"page-down","fixture":"medium","min_us":80,"med_us":82,"p90_us":96,"max_us":97},{"op":"wheel","fixture":"medium","min_us":78,"med_us":80,"p90_us":87,"max_us":88},{"op":"edit-char","fixture":"medium","min_us":1036,"med_us":1377,"p90_us":1602,"max_us":1621},{"op":"edit-twin","fixture":"medium","min_us":2266,"med_us":2715,"p90_us":3695,"max_us":3927},{"op":"body-2m","fixture":"medium","min_us":4739,"med_us":8675,"p90_us":11518,"max_us":13657},{"op":"body-appends","fixture":"medium","min_us":111613,"med_us":214959,"p90_us":264859,"max_us":283506},{"op":"deep-sel","fixture":"medium","min_us":74,"med_us":76,"p90_us":89,"max_us":96}]} diff --git a/test/perf-baseline-tty-debug.json b/test/perf-baseline-tty-debug.json new file mode 100644 index 00000000..a01335bd --- /dev/null +++ b/test/perf-baseline-tty-debug.json @@ -0,0 +1 @@ +{"harness":"6cf9f4b8943e7e29","build":{"compiler":"0.17.0","target":"x86_64-linux.5.10...7.2-gnu.2.38","cpu":"x86_64","driver_optimize":"fast","core_optimize":"debug","c_optimize":"fast","terminal_optimize":"safe","platform":"tty","grammars":"full","mupdf":true,"jpx":true,"tracy":false,"quic":false,"theme_animation":true,"terminal_simd":true,"prebuilt_shaders":false},"cols":120,"rows":40,"reps":10,"only":"medium","fixtures":[{"name":"small","lines":1000,"cols":60,"bytes":62694},{"name":"medium","lines":50000,"cols":60,"bytes":3201944},{"name":"large","lines":300000,"cols":60,"bytes":19464444},{"name":"longline","lines":400,"cols":8000,"bytes":3200400},{"name":"esp32p4","lines":12,"cols":240,"bytes":2892}],"cells":[{"op":"open","fixture":"medium","min_us":2169,"med_us":2697,"p90_us":3126,"max_us":3207},{"op":"render","fixture":"medium","min_us":89,"med_us":96,"p90_us":101,"max_us":115},{"op":"key-down","fixture":"medium","min_us":93,"med_us":98,"p90_us":104,"max_us":115},{"op":"key-right","fixture":"medium","min_us":96,"med_us":97,"p90_us":102,"max_us":108},{"op":"page-down","fixture":"medium","min_us":96,"med_us":98,"p90_us":102,"max_us":103},{"op":"wheel","fixture":"medium","min_us":89,"med_us":100,"p90_us":128,"max_us":168},{"op":"edit-char","fixture":"medium","min_us":1821,"med_us":2274,"p90_us":2404,"max_us":2610},{"op":"edit-twin","fixture":"medium","min_us":2710,"med_us":3180,"p90_us":3413,"max_us":3636},{"op":"body-2m","fixture":"medium","min_us":9090,"med_us":14438,"p90_us":18158,"max_us":22063},{"op":"body-appends","fixture":"medium","min_us":241367,"med_us":375874,"p90_us":470623,"max_us":528094},{"op":"deep-sel","fixture":"medium","min_us":88,"med_us":89,"p90_us":90,"max_us":90}]} diff --git a/test/perf-baseline-tty-fast.json b/test/perf-baseline-tty-fast.json new file mode 100644 index 00000000..04fc88d3 --- /dev/null +++ b/test/perf-baseline-tty-fast.json @@ -0,0 +1 @@ +{"harness":"6cf9f4b8943e7e29","build":{"compiler":"0.17.0","target":"x86_64-linux.5.10...7.2-gnu.2.38","cpu":"x86_64","driver_optimize":"fast","core_optimize":"fast","c_optimize":"fast","terminal_optimize":"fast","platform":"tty","grammars":"full","mupdf":true,"jpx":true,"tracy":false,"quic":false,"theme_animation":true,"terminal_simd":true,"prebuilt_shaders":false},"cols":120,"rows":40,"reps":10,"only":"medium","fixtures":[{"name":"small","lines":1000,"cols":60,"bytes":62694},{"name":"medium","lines":50000,"cols":60,"bytes":3201944},{"name":"large","lines":300000,"cols":60,"bytes":19464444},{"name":"longline","lines":400,"cols":8000,"bytes":3200400},{"name":"esp32p4","lines":12,"cols":240,"bytes":2892}],"cells":[{"op":"open","fixture":"medium","min_us":1695,"med_us":2024,"p90_us":2180,"max_us":2292},{"op":"render","fixture":"medium","min_us":79,"med_us":82,"p90_us":92,"max_us":94},{"op":"key-down","fixture":"medium","min_us":81,"med_us":82,"p90_us":83,"max_us":84},{"op":"key-right","fixture":"medium","min_us":80,"med_us":82,"p90_us":91,"max_us":91},{"op":"page-down","fixture":"medium","min_us":81,"med_us":84,"p90_us":90,"max_us":171},{"op":"wheel","fixture":"medium","min_us":79,"med_us":80,"p90_us":90,"max_us":101},{"op":"edit-char","fixture":"medium","min_us":1332,"med_us":1691,"p90_us":1967,"max_us":1987},{"op":"edit-twin","fixture":"medium","min_us":2160,"med_us":2457,"p90_us":2718,"max_us":2757},{"op":"body-2m","fixture":"medium","min_us":5047,"med_us":13525,"p90_us":16257,"max_us":20323},{"op":"body-appends","fixture":"medium","min_us":155834,"med_us":261597,"p90_us":329936,"max_us":333538},{"op":"deep-sel","fixture":"medium","min_us":75,"med_us":76,"p90_us":84,"max_us":96}]} diff --git a/test/perf.zig b/test/perf.zig index c9235954..d01d1bb5 100644 --- a/test/perf.zig +++ b/test/perf.zig @@ -1054,7 +1054,7 @@ fn measureTerminalSession(io: std.Io, mib: usize, reps: usize, json: bool) !void .undo_output = undo_output, .history_rows = state.vt.screens.active.pages.scrollbar().total, .history_bytes = state.vt.screens.active.pages.page_size, - .history_limit_bytes = state.vt.screens.active.pages.maxSize(), + .history_limit_bytes = state.vt.screens.active.pages.limits.max(.bytes), .row_count_decreases = row_count_decreases, .allocator_calls = counter.calls, .allocator_live_after_output = live_after_output, @@ -1385,7 +1385,7 @@ fn reportText( for (fixtures) |fx| { if (base != null) o(" {s:>19}", .{fx.name}) else o(" {s:>12}", .{fx.name}); } - o("\n{s}\n", .{if (base != null) "-" ** (12 + fixtures.len * 20) else "-" ** (12 + fixtures.len * 13)}); + o("\n{s}\n", .{if (base != null) &@as([12 + fixtures.len * 20]u8, @splat('-')) else &@as([12 + fixtures.len * 13]u8, @splat('-'))}); var worst_jitter: f64 = 0; for (std.enums.values(Op), 0..) |op, oi| { o("{s:<12}", .{op.label()}); @@ -1412,7 +1412,7 @@ fn reportText( for (term_fixtures) |fx| { if (base != null) o(" {s:>19}", .{fx.name}) else o(" {s:>12}", .{fx.name}); } - o("\n{s}\n", .{if (base != null) "-" ** (12 + term_fixtures.len * 20) else "-" ** (12 + term_fixtures.len * 13)}); + o("\n{s}\n", .{if (base != null) &@as([12 + term_fixtures.len * 20]u8, @splat('-')) else &@as([12 + term_fixtures.len * 13]u8, @splat('-'))}); for (std.enums.values(TermOp), 0..) |op, oi| { o("{s:<12}", .{op.label()}); for (0..term_fixtures.len) |fi| { @@ -1524,10 +1524,11 @@ fn parseBase(src: []const u8, opts: Options, bytes: *const [fixtures.len]usize) defer parsed.deinit(); const report = parsed.value; if (!std.mem.eql(u8, report.harness, harness_id)) return error.BaselineHarnessMismatch; - inline for (std.meta.fields(BuildIdentity)) |field| { - const before = @field(report.build, field.name); - const after = @field(build_identity, field.name); - const same = if (field.type == []const u8) std.mem.eql(u8, before, after) else before == after; + const info = @typeInfo(BuildIdentity).@"struct"; + inline for (info.field_names, info.field_types) |name, T| { + const before = @field(report.build, name); + const after = @field(build_identity, name); + const same = if (T == []const u8) std.mem.eql(u8, before, after) else before == after; if (!same) return error.BaselineBuildMismatch; } if (report.cols != opts.cols or report.rows != opts.rows or report.reps != opts.reps or diff --git a/test/snapshot.zig b/test/snapshot.zig index 5522fbb9..2d8a8664 100644 --- a/test/snapshot.zig +++ b/test/snapshot.zig @@ -157,8 +157,8 @@ pub fn main(init: std.process.Init) !void { script_i += 1; } if (exe == null) fatal("usage: pardes-snap [scripts...] [--update] [--jobs=N]", .{}); - const exe_z = try arena.dupeZ(u8, exe.?); - lspmock_bin = if (lspmock) |p| try arena.dupeZ(u8, p) else null; + const exe_z = try arena.dupeSentinel(u8, exe.?, 0); + lspmock_bin = if (lspmock) |p| try arena.dupeSentinel(u8, p, 0) else null; if (scripts.len == 0) { scripts = try listSnaps(arena, try absPath(arena, orig_cwd, "test/snapshots")); @@ -443,7 +443,7 @@ fn runBatch( fn runOne(arena: std.mem.Allocator, exe_z: [:0]const u8, script_path: []const u8, update: bool) u8 { if (careful) beCareful(); const stem = std.fs.path.stem(script_path); - const report_z = arena.dupeZ(u8, reportPath(arena, script_path) catch return 1) catch return 1; + const report_z = arena.dupeSentinel(u8, reportPath(arena, script_path) catch return 1, 0) catch return 1; const fd = libc.open(report_z, .{ .ACCMODE = .WRONLY, .CREAT = true, .TRUNC = true }, @as(libc.mode_t, 0o644)); if (fd >= 0) { _ = libc.dup2(fd, 1); @@ -457,7 +457,7 @@ fn runOne(arena: std.mem.Allocator, exe_z: [:0]const u8, script_path: []const u8 // dirty to every manual `cmp` audit. Unlink only this script's exact path // before it starts; a new mismatch below writes it back. const actual_path = std.fmt.allocPrint(arena, "{s}.actual", .{base_path}) catch return 1; - const actual_path_z = arena.dupeZ(u8, actual_path) catch return 1; + const actual_path_z = arena.dupeSentinel(u8, actual_path, 0) catch return 1; if (record_dir == null) _ = libc.unlink(actual_path_z); const golden: ?[]u8 = if (record_dir == null) readFileAlloc(arena, golden_path) catch null else null; const started = eh.nowMs(); @@ -473,7 +473,7 @@ fn runOne(arena: std.mem.Allocator, exe_z: [:0]const u8, script_path: []const u8 return 0; } if (update) { - eh.writeFile(arena.dupeZ(u8, golden_path) catch return 1, out) catch return 1; + eh.writeFile(arena.dupeSentinel(u8, golden_path, 0) catch return 1, out) catch return 1; std.debug.print("UPDATED {s} ({d} bytes)\n", .{ stem, out.len }); return 0; } @@ -485,7 +485,7 @@ fn runOne(arena: std.mem.Allocator, exe_z: [:0]const u8, script_path: []const u8 std.debug.print("PASS {s} ({d}ms)\n", .{ stem, took }); return 0; } - eh.writeFile(arena.dupeZ(u8, actual_path) catch return 1, out) catch |err| { + eh.writeFile(arena.dupeSentinel(u8, actual_path, 0) catch return 1, out) catch |err| { std.debug.print("FAIL {s}: differs from golden; cannot write {s}: {s} ({d}ms)\n", .{ stem, actual_path, @errorName(err), took }); printFirstDiff(golden.?, out); return 1; @@ -557,7 +557,7 @@ fn runScript(arena: std.mem.Allocator, exe_z: [:0]const u8, script_path: []const try mkdir(arena, work, false); // deterministic shell: fixed prompt, no history, no user rc leakage try eh.writeFile(try std.fmt.allocPrintSentinel(arena, "{s}/.bashrc", .{home}, 0), "PS1='$ '\nHISTFILE=\n"); - _ = setenv("HOME", try arena.dupeZ(u8, home), 1); + _ = setenv("HOME", try arena.dupeSentinel(u8, home, 0), 1); // Keep startup configuration hermetic even when the developer exports an // XDG directory that points outside this per-snapshot fake home. const config_home = try std.fmt.allocPrintSentinel(arena, "{s}/.config", .{home}, 0); @@ -602,8 +602,8 @@ fn runScript(arena: std.mem.Allocator, exe_z: [:0]const u8, script_path: []const // take turns — which cost more wall clock than the other 51 scripts put // together. Scripts name it `$DUMP`. const dump_path = try std.fmt.allocPrint(arena, "{s}/dump.zon", .{base}); - _ = setenv("PARDES_DUMP", try arena.dupeZ(u8, dump_path), 1); - if (chdirRc(try arena.dupeZ(u8, work)) < 0) return error.ChdirFailed; + _ = setenv("PARDES_DUMP", try arena.dupeSentinel(u8, dump_path, 0), 1); + if (chdirRc(try arena.dupeSentinel(u8, work, 0)) < 0) return error.ChdirFailed; const chunks = try arena.alloc([]const u8, countCaptures(src)); var chunk_len: usize = 0; @@ -636,7 +636,7 @@ fn runScript(arena: std.mem.Allocator, exe_z: [:0]const u8, script_path: []const try eh.appendFile(try std.fmt.allocPrintSentinel(arena, "{s}/pardes/init", .{config_home}, 0), setting); } else if (std.mem.eql(u8, cmd, "file")) { const name = tok.next() orelse return error.BadScript; - try eh.writeFile(try arena.dupeZ(u8, name), try unescape(arena, tok.rest())); + try eh.writeFile(try arena.dupeSentinel(u8, name, 0), try unescape(arena, tok.rest())); } else if (std.mem.eql(u8, cmd, "lines")) { const name = tok.next() orelse return error.BadScript; const n = try std.fmt.parseInt(usize, tok.next() orelse return error.BadScript, 10); @@ -646,7 +646,7 @@ fn runScript(arena: std.mem.Allocator, exe_z: [:0]const u8, script_path: []const // scroll test needs and `file` can only give as one huge script line const tail = tok.rest(); const buf = try numberedLines(arena, n, tail); - try eh.writeFile(try arena.dupeZ(u8, name), buf); + try eh.writeFile(try arena.dupeSentinel(u8, name, 0), buf); } else if (std.mem.eql(u8, cmd, "ppmdiag")) { // The diagonal-split test PPM from the old e2e (white over blue), // grown to 512x512 with the white half filled by a fixed LCG @@ -658,7 +658,7 @@ fn runScript(arena: std.mem.Allocator, exe_z: [:0]const u8, script_path: []const // down to flat color and a block always wins). const name = tok.next() orelse return error.BadScript; const ppm = try ppmDiag(arena); - try eh.writeFile(try arena.dupeZ(u8, name), ppm); + try eh.writeFile(try arena.dupeSentinel(u8, name, 0), ppm); } else if (std.mem.eql(u8, cmd, "dirmk")) { try mkdir(arena, tok.next() orelse return error.BadScript, false); } else if (std.mem.eql(u8, cmd, "run")) { @@ -668,7 +668,7 @@ fn runScript(arena: std.mem.Allocator, exe_z: [:0]const u8, script_path: []const // different inotify event. This runs in the script's cwd, as a // child of the RUNNER, so nothing it does reaches the app's ptys: // whatever the app then shows, it woke up for by itself. - if (system(try arena.dupeZ(u8, tok.rest())) != 0) return error.RunFailed; + if (system(try arena.dupeSentinel(u8, tok.rest(), 0)) != 0) return error.RunFailed; } else if (std.mem.eql(u8, cmd, "start")) { const rows = try std.fmt.parseInt(u16, tok.next() orelse return error.BadScript, 10); const cols = try std.fmt.parseInt(u16, tok.next() orelse return error.BadScript, 10); @@ -676,7 +676,7 @@ fn runScript(arena: std.mem.Allocator, exe_z: [:0]const u8, script_path: []const var nextra: usize = 0; while (tok.next()) |a| : (nextra += 1) { if (nextra >= extra.len) return error.BadScript; - extra[nextra] = (try arena.dupeZ(u8, a)).ptr; + extra[nextra] = (try arena.dupeSentinel(u8, a, 0)).ptr; } if (h) |*hp| hp.deinit(); // scripts may restart (e.g. dump then -l) // a new process is a new screen: capture it whole, or its first @@ -963,13 +963,13 @@ fn treeAsleep(root: libc.pid_t) bool { while (n > 0) { n -= 1; const pid = stack[n]; - const dir_path = std.fmt.bufPrintZ(&path_buf, "/proc/{d}/task", .{pid}) catch continue; + const dir_path = std.fmt.bufPrintSentinel(&path_buf, "/proc/{d}/task", .{pid}, 0) catch continue; const dir = libc.opendir(dir_path) orelse continue; // exited between steps defer _ = libc.closedir(dir); while (libc.readdir(dir)) |d| { const tid = std.mem.sliceTo(@as([*:0]const u8, @ptrCast(&d.name)), 0); if (tid[0] == '.') continue; - const stat = readProc(&buf, std.fmt.bufPrintZ(&path_buf, "/proc/{d}/task/{s}/stat", .{ pid, tid }) catch continue) orelse continue; + const stat = readProc(&buf, std.fmt.bufPrintSentinel(&path_buf, "/proc/{d}/task/{s}/stat", .{ pid, tid }, 0) catch continue) orelse continue; // "pid (comm) S ..." — comm can hold spaces and parens, so the // state is the char two past the LAST ')' const close = std.mem.lastIndexOfScalar(u8, stat, ')') orelse continue; @@ -983,7 +983,7 @@ fn treeAsleep(root: libc.pid_t) bool { 'R', 'D', 'Z' => return false, else => {}, } - const kids = readProc(&buf, std.fmt.bufPrintZ(&path_buf, "/proc/{d}/task/{s}/children", .{ pid, tid }) catch continue) orelse continue; + const kids = readProc(&buf, std.fmt.bufPrintSentinel(&path_buf, "/proc/{d}/task/{s}/children", .{ pid, tid }, 0) catch continue) orelse continue; var it = std.mem.tokenizeAny(u8, kids, " \n"); while (it.next()) |k| { if (n >= stack.len) return false; // deeper than we can walk: assume busy @@ -1554,7 +1554,7 @@ fn absPath(arena: std.mem.Allocator, cwd: []const u8, p: []const u8) ![]const u8 } fn listSnaps(arena: std.mem.Allocator, dir_path: []const u8) ![][]const u8 { - const dir_z = try arena.dupeZ(u8, dir_path); + const dir_z = try arena.dupeSentinel(u8, dir_path, 0); const count = countSnapEntries(dir_z, dir_path); const scripts = try arena.alloc([]const u8, count); const dir = libc.opendir(dir_z) orelse fatal("no snapshots/ dir at {s}", .{dir_path}); @@ -1583,7 +1583,7 @@ fn countSnapEntries(dir_z: [:0]const u8, dir_path: []const u8) usize { } fn readFileAlloc(arena: std.mem.Allocator, path: []const u8) ![]u8 { - const path_z = try arena.dupeZ(u8, path); + const path_z = try arena.dupeSentinel(u8, path, 0); const fd = libc.open(path_z, .{ .ACCMODE = .RDONLY }); if (fd < 0) return error.OpenFailed; defer _ = libc.close(fd); @@ -1611,7 +1611,7 @@ fn readFileAlloc(arena: std.mem.Allocator, path: []const u8) ![]u8 { } fn mkdir(arena: std.mem.Allocator, path: []const u8, exist_ok: bool) !void { - const path_z = try arena.dupeZ(u8, path); + const path_z = try arena.dupeSentinel(u8, path, 0); const rc = libc.mkdir(path_z, 0o755); if (rc != 0) { if (exist_ok and libc.errno(rc) == .EXIST) return; diff --git a/test/snapshots/exec.golden b/test/snapshots/exec.golden index df49336c..30473c9e 100644 --- a/test/snapshots/exec.golden +++ b/test/snapshots/exec.golden @@ -22,15 +22,17 @@ == snap kept grid=140x31 cursor=6,3 |3: ZZARG ls |4: ./c.sh e.txt +|8: |9: == snap chord grid=140x31 cursor=6,3 |3: ZZARG Exec ls -|9: CHORDARG:ZZARG +|5: ./c.sh ZZARG +|6: CHORDARG:ZZARG == snap deleted grid=140x31 cursor=4,5 |3: ls ls |4: e.txt e.txt -|8: -|9: +|5: +|6: |17: |18: |19: diff --git a/test/snapshots/tinywin.golden b/test/snapshots/tinywin.golden deleted file mode 100644 index 787a9d8f..00000000 --- a/test/snapshots/tinywin.golden +++ /dev/null @@ -1,83 +0,0 @@ -== snap stacked grid=100x31 cursor=14,3 -| Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit -| New Tty Find Grep Joincol Delcol -|$ /tmp/pardes-snap/tinywin/cwd Tty+bash Save Mode Filter Collapse Del -| $ :^[n^[n^[n -| -| -| -| -| -| -| -| -| -| -| -| -| -| -| -| -| -| /tmp/pardes-snap/tinywin/cwd/+New Save Tty Collapse Del -| 1 -== snap shrunk grid=60x4 cursor=59,3 -| Newcol Joincol Find Grep Help Changelog Tutor Dump Themes -| New Tty Find Grep Joincol Delcol -|$ /tmp/pardes-snap/tinywin/cwd Tty+bash Save Mode Filter Col -| /tmp/pardes-snap/tinywin/cwd/+New Save Tty Collapse Del -== snap columns grid=100x31 cursor=23,3 -| Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit -| New Tty Find Grep Joincol Delcol -|$ /tmp/pardes-snap/tinywin/cwd Tty+bash Save Mode Filter Collapse Del -| $ :^[n^[n^[n cn cn cn -| -| -| -| -| -| -| -| -| -| -| -| -| -| -| -| -| -| /tmp/pardes-snap/tinywin/cwd/+New Save Tty Collapse Del -| 1 -== snap narrow grid=4x31 cursor=2,20 -| Ne -| Ne -|$ /t -| mp -| /p -| ar -| de -| s- -| sn -| ap -| $ -| ^[ -| n^ -| [n -| ^[ -| n -| cn -| c -| n -| cn -| -| /t -| mp -| /p -| ar -| de -| s- -| sn -| ap diff --git a/test/snapshots/tinywin.snap b/test/snapshots/tinywin.snap deleted file mode 100644 index 3d22d583..00000000 --- a/test/snapshots/tinywin.snap +++ /dev/null @@ -1,31 +0,0 @@ -# Shrinking the window past "one row per pane" used to panic: computeGeom gave -# every pane in a column at least one row, so `y` walked off the bottom and -# renderPane got a rect outside the surface (assert). Panes that no longer fit -# now get h = 0 and simply do not render until the window grows back. -start 31 100 -wait 8000 $ -key a-n -stable 400 8000 -key a-n -stable 400 8000 -key a-n -stable 400 8000 -key a-n -stable 700 15000 -snap stacked -resize 4 60 -stable 700 10000 -snap shrunk -# ...and the same sideways: more columns than the window is wide -resize 31 100 -stable 700 10000 -key space c n -stable 600 8000 -key space c n -stable 600 8000 -key space c n -stable 700 15000 -snap columns -resize 31 4 -stable 700 10000 -snap narrow diff --git a/test/unit_profile_test.zig b/test/unit_profile_test.zig index 721f1212..a4cdd09e 100644 --- a/test/unit_profile_test.zig +++ b/test/unit_profile_test.zig @@ -149,11 +149,8 @@ fn fixture(init: std.process.Init) !void { var write_buffer: [1024]u8 = undefined; var reader = std.Io.File.stdin().readerStreaming(io, &read_buffer); var writer = std.Io.File.stdout().writerStreaming(io, &write_buffer); - var server = try std.zig.Server.init(.{ - .in = &reader.interface, - .out = &writer.interface, - .zig_version = if (std.mem.eql(u8, mode, "version")) "wrong-version" else builtin.zig_version_string, - }); + var server: std.zig.Server = .{ .in = &reader.interface, .out = &writer.interface }; + try server.serveStringMessage(.zig_version, if (std.mem.eql(u8, mode, "version")) "wrong-version" else builtin.zig_version_string); while (true) { const request = try server.receiveMessage(); switch (request.tag) { diff --git a/tools/gen_themes.zig b/tools/gen_themes.zig index 65e85d1c..be5fde2f 100644 --- a/tools/gen_themes.zig +++ b/tools/gen_themes.zig @@ -152,13 +152,14 @@ fn byName(_: void, a: Theme, b: Theme) bool { fn emit(w: *std.Io.Writer, t: Theme) !void { try w.writeAll("// Generated by tools/gen_themes.zig. Do not edit.\npub const theme = .{\n"); try w.print(" .name = \"{s}\",\n", .{t.name}); - inline for (@typeInfo(Theme).@"struct".fields) |f| { - if (comptime std.mem.eql(u8, f.name, "name")) continue; - if (comptime std.mem.eql(u8, f.name, "palette")) continue; - try w.print(" .{s} = ", .{f.name}); - if (comptime @typeInfo(f.type) == .optional) { - if (@field(t, f.name)) |c| try rgb(w, c) else try w.writeAll("null"); - } else try rgb(w, @field(t, f.name)); + const info = @typeInfo(Theme).@"struct"; + inline for (info.field_names, info.field_types) |name, T| { + if (comptime std.mem.eql(u8, name, "name")) continue; + if (comptime std.mem.eql(u8, name, "palette")) continue; + try w.print(" .{s} = ", .{name}); + if (comptime @typeInfo(T) == .optional) { + if (@field(t, name)) |c| try rgb(w, c) else try w.writeAll("null"); + } else try rgb(w, @field(t, name)); try w.writeAll(",\n"); } if (t.palette) |p| { -- cgit v1.3 From 23518c9d7c061f8a06f6632da8b64b37801b514f Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Wed, 21 Oct 2026 17:25:52 -0300 Subject: zig fmt for Zig 0.17 --- build.zig | 15 +- src/9p_io.zig | 2 +- src/Dir.zig | 4 +- src/File.zig | 12 +- src/Messages.zig | 2 +- src/Presentation.zig | 6 +- src/animation.zig | 11 +- src/builtins.zig | 22 +- src/detached/client.zig | 2 +- src/detached/server.zig | 4 +- src/detached/wire.zig | 82 +-- src/diff.zig | 4 +- src/draw.zig | 4 +- src/dump.zig | 4 +- src/edit_cmd.zig | 2 +- src/esp32p4.zig | 34 +- src/esp32p4/app.zig | 6 +- src/esp32p4_9p.zig | 2 +- src/fonts.zig | 2 +- src/gui/Post.zig | 19 +- src/gui/gui.zig | 32 +- src/host_io.zig | 20 +- src/linux/v9fs.zig | 6 +- src/look.zig | 2 +- src/macos.zig | 98 ++-- src/main.zig | 2 +- src/mini.zig | 10 +- src/mouse.zig | 18 +- src/ninep/addr.zig | 6 +- src/ninep/cols.zig | 54 +- src/ninep/ctl.zig | 168 +++--- src/ninep/events.zig | 30 +- src/ninep/pane.zig | 8 +- src/ninep/pty.zig | 5 +- src/ninep/screen.zig | 4 +- src/ninep/testing.zig | 4 +- src/ninep/tree.zig | 120 ++-- src/pager.zig | 4 +- src/pardes.zig | 10 +- src/pdf_view.zig | 2 +- src/syntax.zig | 82 +-- src/terminal.zig | 2 +- src/web.zig | 32 +- test/deck/buttons.zon | 158 ++--- test/deck/lpad-swipe.zon | 322 +++++------ test/deck/replay.zig | 36 +- test/deck/rpad-drag.zon | 442 +++++++------- test/deck/triggers.zon | 1148 ++++++++++++++++++------------------- test/fs_bench.zig | 6 +- test/lspfixture/broken.zig | 4 +- test/output.zig | 10 +- test/panes.zig | 2 +- test/pdf.zig | 6 +- test/pdf_scroll_bench.zig | 2 +- test/perf-baseline-gui-debug.json | 2 +- test/perf-baseline-tty-debug.json | 2 +- test/perf-baseline-tty-fast.json | 2 +- test/perf.zig | 6 +- test/unit_profile.zig | 4 +- 59 files changed, 1556 insertions(+), 1554 deletions(-) (limited to 'src/main.zig') diff --git a/build.zig b/build.zig index ddd41a03..ca7b26af 100644 --- a/build.zig +++ b/build.zig @@ -39,10 +39,13 @@ pub const macos_min_version: std.SemanticVersion = .{ .major = 13, .minor = 0, . pub const TreeSitterGrammars = enum { disabled, zig, minimal, full }; const gui_shaders = [_][]const u8{ - "ui.vert", "ui.frag", + "ui.vert", + "ui.frag", "decor.frag", - "overlay.vert", "overlay.frag", - "image.vert", "image.frag", + "overlay.vert", + "overlay.frag", + "image.vert", + "image.frag", "post.vert", // The bundled post passes: shaders/post/.glsl behind the // Shadertoy prefix (shaderSource). @@ -843,7 +846,7 @@ pub fn build(b: *std.Build) void { const render_anchor = \\ if ((!self.refresh and \\ last.eql(cell) and - ; + ; if (std.mem.count(u8, render_src, render_anchor) != 1) std.debug.panic("vaxis's Vaxis.zig changed at `{s}`: redo its patch in build.zig", .{render_anchor}); render_src = std.mem.replaceOwned(u8, b.allocator, render_src, render_anchor, \\ if ((!self.refresh and @@ -924,7 +927,6 @@ pub fn build(b: *std.Build) void { .uucode = uucode_mod, }); - const iso_off = b.addOptions(); iso_off.addOption(bool, "isolated", false); const iso_on = b.addOptions(); @@ -1401,7 +1403,6 @@ pub fn build(b: *std.Build) void { const lspbench_check_step = b.step("lspbench-check", "require every configured language probe to complete correctly"); lspbench_check_step.dependOn(&run_lspbench_check.step); - const locations_bench_step = b.step("locations-bench", "measure cold/warm result formatting (-Doptimize=ReleaseFast; CSV on stderr)"); if (optimize != .fast) { locations_bench_step.dependOn(&b.addFail("locations-bench requires -Doptimize=ReleaseFast").step); @@ -2016,6 +2017,6 @@ fn wireCore(m: *std.Build.Module, d: struct { /// helper because `cpu_features_add` wants a set and there is no literal syntax for one. fn riscvFeatures(comptime features: []const std.Target.riscv.Feature) std.Target.Cpu.Feature.Set { var set = std.Target.Cpu.Feature.Set.empty; - for (features) |f| set.addFeature(@intFromEnum(f)); + for (features) |f| set.addFeature(@backingInt(f)); return set; } diff --git a/src/9p_io.zig b/src/9p_io.zig index 27d79b93..446c24de 100644 --- a/src/9p_io.zig +++ b/src/9p_io.zig @@ -1015,7 +1015,7 @@ pub fn sweepDeadSockets(io: std.Io, dir: [:0]const u8) void { i += 1 + name.len; const pid = deadSocketPid(name).?; if (pid == libc.getpid()) continue; - if (std.posix.errno(std.c.kill(pid, @enumFromInt(0))) != .SRCH) continue; + if (std.posix.errno(std.c.kill(pid, @fromBackingInt(@intCast(0)))) != .SRCH) continue; var path_buf: [sun_path_len:0]u8 = undefined; const path = std.fmt.bufPrintSentinel(&path_buf, "{s}/{s}", .{ dir, name }, 0) catch continue; const facts = statNoFollow(path) orelse continue; diff --git a/src/Dir.zig b/src/Dir.zig index 36895bda..b994bc06 100644 --- a/src/Dir.zig +++ b/src/Dir.zig @@ -463,10 +463,10 @@ test "over 9P a directory pane is a text pane whose name ends in /, its body the defer s.p.deinit(); const p = s.p; var line_buf: [4200]u8 = undefined; - _ = th.wr(p, @intFromEnum(tree.TopFile.look), try std.fmt.bufPrint(&line_buf, "{s}\n", .{s.dir})); + _ = th.wr(p, @backingInt(tree.TopFile.look), try std.fmt.bufPrint(&line_buf, "{s}\n", .{s.dir})); p.sync(); const pane = p.panes[p.active].?; - const index = th.rd(p, @intFromEnum(tree.TopFile.index), 0, 8192).bytes; + const index = th.rd(p, @backingInt(tree.TopFile.index), 0, 8192).bytes; try testing.expect(std.mem.indexOf(u8, index, try std.fmt.bufPrint(&line_buf, "{d} text 0 {s}/ ", .{ pane.serial, s.dir })) != null); try testing.expectEqualStrings(".dot sub/ top.txt\n", th.rd(p, tree.Node.of(pane.serial, .body), 0, 4096).bytes); var fields = std.mem.tokenizeScalar(u8, th.rd(p, tree.Node.of(pane.serial, .ctl), 0, 4096).bytes, ' '); diff --git a/src/File.zig b/src/File.zig index c42e39ec..59b04e3f 100644 --- a/src/File.zig +++ b/src/File.zig @@ -251,7 +251,7 @@ pub fn dumpPane( fn dumpLocationRows(arena: std.mem.Allocator, rows: []const locations.Row) ![]const dump.LocationRow { const saved = try arena.alloc(dump.LocationRow, rows.len); for (rows, saved) |row, *out| out.* = .{ - .kind = @enumFromInt(@intFromEnum(row.kind)), + .kind = @fromBackingInt(@intCast(@backingInt(row.kind))), .declaration = row.declaration, .mark_occurrence = row.mark_occurrence, .source_column = row.source_column, @@ -336,10 +336,10 @@ fn restoreOutputLocationRows(gpa: std.mem.Allocator, content: []const u8, saved: const colors = try dump.decodeBytes(gpa, row.colors_b64); errdefer gpa.free(colors); if (colors.len != 0 and colors.len != code_len) return error.InvalidLocationRows; - for (colors) |color| if (color > @intFromEnum(syntax.Syn.comment)) return error.InvalidLocationRows; + for (colors) |color| if (color > @backingInt(syntax.Syn.comment)) return error.InvalidLocationRows; const path = try gpa.dupe(u8, row.path); out.* = .{ - .kind = @enumFromInt(@intFromEnum(row.kind)), + .kind = @fromBackingInt(@intCast(@backingInt(row.kind))), .declaration = row.declaration, .mark_occurrence = row.mark_occurrence, .source_column = row.source_column, @@ -1028,7 +1028,7 @@ pub fn restore(p: *Pardes, id: usize, src: dump.Pane) !*Pane { const colors = try dump.decodeBytes(p.gpa, saved.mini_colors_b64); errdefer p.gpa.free(colors); if (colors.len != content.len or colors.len > Mini.max_output_bytes) return error.InvalidMini; - for (colors) |color| if (color > @intFromEnum(syntax.Syn.comment)) return error.InvalidMini; + for (colors) |color| if (color > @backingInt(syntax.Syn.comment)) return error.InvalidMini; mini = .{ .source = source, .colors = colors }; } else if (saved.mini_colors_b64.len > 0) return error.InvalidMini; @@ -1984,7 +1984,7 @@ pub fn recolorSyntax(p: *Pardes, s: *Surface, pane: *Pane, f: *State, r: pardes. if (if (tint != null and hs + c == 0) SynStyle{ .fg = tint.?.fg, .bold = true } else - synStyle(p, @enumFromInt(highlights[hidx] & syntax.syn_bits))) |ss| + synStyle(p, @fromBackingInt(@intCast(highlights[hidx] & syntax.syn_bits)))) |ss| { var fill: usize = 0; while (fill < cells and prefix_width + screen_c + fill < tw) : (fill += 1) { @@ -2189,7 +2189,7 @@ pub fn recolorDiffOutput(p: *Pardes, s: *Surface, pane: *Pane, r: pardes.Rect, t // green is the tint's to say now: its code takes the page's ink. const paint: ?SynStyle = if (tint != null and prefix) .{ .fg = tint.?.fg, .bold = true } - else if (synStyle(p, @enumFromInt(style & syntax.syn_bits))) |ss| + else if (synStyle(p, @fromBackingInt(@intCast(style & syntax.syn_bits)))) |ss| ss else if (tint != null) .{ .fg = ink, .bold = false } diff --git a/src/Messages.zig b/src/Messages.zig index b67a8402..6d064c93 100644 --- a/src/Messages.zig +++ b/src/Messages.zig @@ -721,7 +721,7 @@ test "with no frontend attached a message goes once it has lingered, on the cloc // line above it with it. p.unattended = true; // A read served meanwhile changes nothing; the session's loop expires. - _ = p.serveFs(.{ .tag = 1, .op = .read, .node = @intFromEnum(ctlfs.TopFile.index), .size = 64 }); + _ = p.serveFs(.{ .tag = 1, .op = .read, .node = @backingInt(ctlfs.TopFile.index), .size = 64 }); try std.testing.expect(pane.msg_len > 0); expireUnattended(p); try std.testing.expectEqual(@as(u16, 0), pane.msg_len); diff --git a/src/Presentation.zig b/src/Presentation.zig index 5cec73e0..2a75b66d 100644 --- a/src/Presentation.zig +++ b/src/Presentation.zig @@ -226,7 +226,7 @@ fn stamp(p: *const Pardes, track: Track) Track { switch (track.effect) { .slide, .zoom, .vertical => { const motion = animation.Motion.of(p.settings.motion); - stamped.motion = @intFromEnum(p.settings.motion) + 1; + stamped.motion = @backingInt(p.settings.motion) + 1; stamped.frame_count = @intFromFloat(@max(2, @round(@as(f32, @floatFromInt(track.effect.frames())) * motion.span))); }, else => {}, @@ -741,7 +741,7 @@ test "a pane past its mark never takes a neighbour's click" { // Bouncy, at its peak: pane 0 slides right to 0..40 and swings past it, // over the neighbour at 40..80. var presentation: Presentation = .{}; - var track: Track = .{ .serial = 7, .effect = .slide, .motion = @intFromEnum(animation.Motion.Flavour.bouncy) + 1, .frame_count = 20, .from = .{ .x = -40, .y = 0, .w = 40, .h = 20 }, .to = .{ .x = 0, .y = 0, .w = 40, .h = 20 } }; + var track: Track = .{ .serial = 7, .effect = .slide, .motion = @backingInt(animation.Motion.Flavour.bouncy) + 1, .frame_count = 20, .from = .{ .x = -40, .y = 0, .w = 40, .h = 20 }, .to = .{ .x = 0, .y = 0, .w = 40, .h = 20 } }; var peak: u16 = 0; var furthest: f32 = -1e9; while (track.frame < track.frames()) : (track.frame += 1) { @@ -807,7 +807,7 @@ test "presentation snapshots own compact body and tag rows across later edits" { } test "a move retargeted mid-way carries its speed into the new one" { - const smooth = @intFromEnum(animation.Motion.Flavour.smooth) + 1; + const smooth = @backingInt(animation.Motion.Flavour.smooth) + 1; const first: Track = .{ .serial = 1, .phase = .moving, .effect = .slide, .motion = smooth, .frame = 4, .frame_count = 14, .from = .{ .x = 0, .y = 1, .w = 40, .h = 20 }, .to = .{ .x = 40, .y = 1, .w = 40, .h = 20 } }; const was = first.velocity(); try std.testing.expect(was.x > 0.5); diff --git a/src/animation.zig b/src/animation.zig index 19f7ce0b..547b9201 100644 --- a/src/animation.zig +++ b/src/animation.zig @@ -897,7 +897,7 @@ test "each flavour is its own motion: off lands at once, bouncy overshoots, play last = now; } try std.testing.expect(t < 1600 * ms); - settle[@intFromEnum(flavour)] = t; + settle[@backingInt(flavour)] = t; switch (flavour) { .crisp, .smooth => try std.testing.expect(peak <= 1.0005 and low >= 0), // Clearly past the mark, not a hint of it. @@ -909,8 +909,8 @@ test "each flavour is its own motion: off lands at once, bouncy overshoots, play // Smooth takes twice crisp's time and more: a character, not a tuning. // Yet as the default a pane's arrival (a slide's 12 frames, scaled) is // inside §8.1's 220 ms, and a lift is still before 300 ms. - try std.testing.expect(settle[@intFromEnum(Motion.Flavour.smooth)] > 2 * settle[@intFromEnum(Motion.Flavour.crisp)]); - try std.testing.expect(settle[@intFromEnum(Motion.Flavour.smooth)] <= 300 * ms); + try std.testing.expect(settle[@backingInt(Motion.Flavour.smooth)] > 2 * settle[@backingInt(Motion.Flavour.crisp)]); + try std.testing.expect(settle[@backingInt(Motion.Flavour.smooth)] <= 300 * ms); try std.testing.expect(@round(@as(f32, 12) * Motion.of(.smooth).span) * frame_ms <= 220); // A fixed-length move lands exactly on its mark, whatever the flavour. for (std.enums.values(Motion.Flavour)) |flavour| try std.testing.expectEqual(@as(f32, 1), Motion.of(flavour).ease(1)); @@ -920,7 +920,7 @@ test "a flavour's stretched pane lands exactly on its box, and a click finds the const from: Box = .{ .x = 0, .y = 2, .w = 30, .h = 10 }; const to: Box = .{ .x = 37.3, .y = 2, .w = 30, .h = 10 }; for (std.enums.values(Motion.Flavour)) |flavour| { - var track: Track = .{ .effect = .slide, .motion = @intFromEnum(flavour) + 1, .frame_count = 20, .from = from, .to = to }; + var track: Track = .{ .effect = .slide, .motion = @backingInt(flavour) + 1, .frame_count = 20, .from = from, .to = to }; track.frame = track.frames() - 1; const landed = track.presented(); // Bit for bit: no stretch or float residue once it lands. @@ -929,7 +929,7 @@ test "a flavour's stretched pane lands exactly on its box, and a click finds the // Playful at its most stretched: the pane is drawn wider than its box, // and the drawn place of a cell maps back to that cell (the pointer // inverts the same box: target + (x - shown.x) / shown.w * target.w). - var track: Track = .{ .effect = .slide, .motion = @intFromEnum(Motion.Flavour.playful) + 1, .frame_count = 20, .from = from, .to = to }; + var track: Track = .{ .effect = .slide, .motion = @backingInt(Motion.Flavour.playful) + 1, .frame_count = 20, .from = from, .to = to }; var most: u16 = 0; var widest: f32 = 0; while (track.frame < track.frames()) : (track.frame += 1) { @@ -1309,4 +1309,3 @@ test "retarget starts at the currently displayed value" { for (0..transition_steps) |_| tween.advance(); try std.testing.expectEqual(third, tween.displayed); } - diff --git a/src/builtins.zig b/src/builtins.zig index d9cef8c9..83966228 100644 --- a/src/builtins.zig +++ b/src/builtins.zig @@ -199,7 +199,7 @@ pub const registry = struct { pub fn takesArg(b: Builtin()) bool { inline for (manualBuiltinList(), 0..) |T, i| - if (@intFromEnum(b) == i) return @hasDecl(T, "takes_arg") and T.takes_arg; + if (@backingInt(b) == i) return @hasDecl(T, "takes_arg") and T.takes_arg; // Every setting takes its value, and a switch flips when bare. return true; } @@ -210,7 +210,7 @@ pub const registry = struct { /// may be in (`Dump+2024.zon` is a name, not Dump's argument). pub fn plusArg(b: Builtin()) bool { inline for (manualBuiltinList(), 0..) |T, i| - if (@intFromEnum(b) == i) return @hasDecl(T, "plus_arg") and T.plus_arg; + if (@backingInt(b) == i) return @hasDecl(T, "plus_arg") and T.plus_arg; return false; } @@ -223,15 +223,15 @@ pub const registry = struct { /// pane it is refused (exec.runBuiltinFrom), as Repl and Edit are. pub fn needs(b: Builtin()) ?PaneKind { inline for (manualBuiltinList(), 0..) |T, i| - if (@intFromEnum(b) == i) return if (@hasDecl(T, "needs")) T.needs else null; + if (@backingInt(b) == i) return if (@hasDecl(T, "needs")) T.needs else null; return null; } pub fn requiresArg(b: Builtin()) bool { inline for (manualBuiltinList(), 0..) |T, i| - if (@intFromEnum(b) == i) return @hasDecl(T, "requires_arg") and T.requires_arg; + if (@backingInt(b) == i) return @hasDecl(T, "requires_arg") and T.requires_arg; inline for (comptime settingList(), manualBuiltinCount()..) |setting, i| - if (@intFromEnum(b) == i) return switch (setting.action) { + if (@backingInt(b) == i) return switch (setting.action) { // a switch flips bare, a choice steps, and DumpDir and Shell bare // are the default .toggle, .transition, .scene, .dump_dir, .choice, .lift, .shader_animation, .motion, .shell => false, @@ -244,15 +244,15 @@ pub const registry = struct { pub fn scope(b: Builtin()) Scope { inline for (manualBuiltinList(), 0..) |T, i| - if (@intFromEnum(b) == i) return if (@hasDecl(T, "scope")) T.scope else .pane; + if (@backingInt(b) == i) return if (@hasDecl(T, "scope")) T.scope else .pane; return .session; // a setting } pub fn outputTraits(b: Builtin()) ?OutputTraits { inline for (manualBuiltinList(), 0..) |T, i| - if (@intFromEnum(b) == i) return if (@hasDecl(T, "output")) T.output else null; + if (@backingInt(b) == i) return if (@hasDecl(T, "output")) T.output else null; inline for (comptime settingList(), manualBuiltinCount()..) |_, i| - if (@intFromEnum(b) == i) return null; + if (@backingInt(b) == i) return null; unreachable; } @@ -260,15 +260,15 @@ pub const registry = struct { /// The ones that own that row themselves declare `quiet` and do not. pub fn announces(b: Builtin()) bool { inline for (manualBuiltinList(), 0..) |T, i| - if (@intFromEnum(b) == i) return !(@hasDecl(T, "quiet") and T.quiet); + if (@backingInt(b) == i) return !(@hasDecl(T, "quiet") and T.quiet); return true; // a setting builtin changes something invisible; say so } pub fn dispatch(b: Builtin(), c: Ctx) void { inline for (manualBuiltinList(), 0..) |T, i| - if (@intFromEnum(b) == i) return T.run(c); + if (@backingInt(b) == i) return T.run(c); inline for (comptime settingList(), manualBuiltinCount()..) |setting, i| - if (@intFromEnum(b) == i) return exec.applySettingBuiltin(c.p, setting, c.arg); + if (@backingInt(b) == i) return exec.applySettingBuiltin(c.p, setting, c.arg); unreachable; } }; diff --git a/src/detached/client.zig b/src/detached/client.zig index cf1842d9..60950208 100644 --- a/src/detached/client.zig +++ b/src/detached/client.zig @@ -1209,7 +1209,7 @@ test "detached session: a frontend is never asked to fork, write, or watch" { } const named = for (allowed) |ok| { const want = std.meta.stringToEnum(wire.ServerTag, ok).?; - if (@intFromEnum(want) == tag) break true; + if (@backingInt(want) == tag) break true; } else false; if (!named) { std.debug.print("tag 0x{x:0>2} is decodable by a frontend and is not one of the nine\n", .{tag}); diff --git a/src/detached/server.zig b/src/detached/server.zig index 79d1189a..41bc054f 100644 --- a/src/detached/server.zig +++ b/src/detached/server.zig @@ -1049,7 +1049,7 @@ pub const Session = struct { } fn apply(s: *Session, c: *Client, slot: u8, tag: u8, payload: []const u8) wire.Error!void { - if (tag == @intFromEnum(wire.ClientTag.hello)) { + if (tag == @backingInt(wire.ClientTag.hello)) { if (c.attached) return error.BadValue; const claimed = try wire.helloVersion(payload); if (claimed != wire.version) { @@ -1124,7 +1124,7 @@ pub const Session = struct { if (entry.scene == null) break true; } else false; const compiled = s.shaders.sync(s.gpa, s.io, s.core, if (files) s.inotify() else s.inotify_fd, &s.watches, .{ .ctx = &s.mailbox, .call = wakeForExit }); - const key = @as(u64, s.shaders.revision) << 8 | @intFromEnum(s.core.settings.shader_animation); + const key = @as(u64, s.shaders.revision) << 8 | @backingInt(s.core.settings.shader_animation); var chain: wire.Post = .{ .animation = s.core.settings.shader_animation, .len = s.core.settings.post.len }; _ = s.shaders.view(&s.core.settings.post, &chain.passes); for (&s.clients) |*c| { diff --git a/src/detached/wire.zig b/src/detached/wire.zig index f1b7a1b3..d57a28be 100644 --- a/src/detached/wire.zig +++ b/src/detached/wire.zig @@ -569,13 +569,13 @@ pub fn framed(buf: []const u8) Error!?Framed { fn putColor(w: *Writer, c: pardes.Color) Error!void { switch (c) { - .default => try w.putByte(@intFromEnum(ColorTag.default)), + .default => try w.putByte(@backingInt(ColorTag.default)), .index => |i| { - try w.putByte(@intFromEnum(ColorTag.index)); + try w.putByte(@backingInt(ColorTag.index)); try w.putByte(i); }, .rgb => |v| { - try w.putByte(@intFromEnum(ColorTag.rgb)); + try w.putByte(@backingInt(ColorTag.rgb)); try w.putBytes(&v); }, } @@ -606,7 +606,7 @@ const Ul = @FieldType(pardes.CellStyle, "ul"); /// the `inline else`, exactly as `clientTag` keeps the machine-local reports. fn putUl(w: *Writer, u: Ul) Error!void { try w.putByte(switch (u) { - inline else => |t| @intFromEnum(@field(UlTag, @tagName(t))), + inline else => |t| @backingInt(@field(UlTag, @tagName(t))), }); } @@ -618,7 +618,7 @@ fn getUl(r: *Reader) Error!Ul { fn putFont(w: *Writer, f: pardes.FontRole) Error!void { try w.putByte(switch (f) { - inline else => |t| @intFromEnum(@field(FontTag, @tagName(t))), + inline else => |t| @backingInt(@field(FontTag, @tagName(t))), }); } @@ -795,12 +795,12 @@ pub fn encodeFrameLayers(out: []u8, cols: u16, rows: u16, cursor: ?Cursor, point std.debug.assert(cells.len == @as(usize, cols) * @as(usize, rows)); const full = prev.len != cells.len; var w: Writer = .init(out); - const at = try beginMessage(&w, @intFromEnum(ServerTag.frame)); + const at = try beginMessage(&w, @backingInt(ServerTag.frame)); const header: FrameHeader = if (pointer_shape == .link) (if (full) .full_link else .diff_link) else (if (full) .full else .diff); - try w.putByte(@intFromEnum(header)); + try w.putByte(@backingInt(header)); try w.putU16(cols); try w.putU16(rows); try putCursor(&w, cursor, cols, rows); @@ -837,7 +837,7 @@ pub fn encodeFrameLayers(out: []u8, cols: u16, rows: u16, cursor: ?Cursor, point for (tags) |layer| { if (layer.rows == 0) continue; if (layer.cells.len != @as(usize, layer.cols) * layer.rows) return error.BadValue; - try w.putByte(@intFromEnum(layer.kind)); + try w.putByte(@backingInt(layer.kind)); try w.putU16(layer.id); try w.putU32(layer.serial); try w.putU16(layer.viewport.x); @@ -852,7 +852,7 @@ pub fn encodeFrameLayers(out: []u8, cols: u16, rows: u16, cursor: ?Cursor, point } try w.putU16(@intCast(regions.len)); for (regions) |region| { - try w.putByte(@intFromEnum(region.kind)); + try w.putByte(@backingInt(region.kind)); try w.putByte(region.owner); try w.putU32(region.serial); try w.putU16(region.rect.x); @@ -1003,7 +1003,7 @@ fn getBodyHit(r: *Reader) Error!?pardes.Mouse.BodyHit { fn putTagHit(w: *Writer, hit: ?pardes.TagHit) Error!void { try w.putBool(hit != null); if (hit) |h| { - try w.putByte(@intFromEnum(h.kind)); + try w.putByte(@backingInt(h.kind)); try w.putU16(h.id); try w.putU32(h.serial); try w.putU16(h.col); @@ -1030,7 +1030,7 @@ fn getTagHit(r: *Reader) Error!?pardes.TagHit { pub fn encodeClient(out: []u8, msg: ClientMsg) Error![]const u8 { var w: Writer = .init(out); - const at = try beginMessage(&w, @intFromEnum(clientTag(msg))); + const at = try beginMessage(&w, @backingInt(clientTag(msg))); switch (msg) { .hello => |h| { try w.putU16(h.version); @@ -1048,10 +1048,10 @@ pub fn encodeClient(out: []u8, msg: ClientMsg) Error![]const u8 { }, .mouse => |m| { try w.putByte(switch (m.button) { - inline else => |t| @intFromEnum(@field(ButtonTag, @tagName(t))), + inline else => |t| @backingInt(@field(ButtonTag, @tagName(t))), }); try w.putByte(switch (m.kind) { - inline else => |t| @intFromEnum(@field(KindTag, @tagName(t))), + inline else => |t| @backingInt(@field(KindTag, @tagName(t))), }); try w.putU16(m.col); try w.putU16(m.row); @@ -1164,7 +1164,7 @@ fn serverTag(msg: ServerMsg) ServerTag { /// payload is a walk of two grids rather than a value (see `encodeFrame`). pub fn encodeServer(out: []u8, msg: ServerMsg) Error![]const u8 { var w: Writer = .init(out); - const at = try beginMessage(&w, @intFromEnum(serverTag(msg))); + const at = try beginMessage(&w, @backingInt(serverTag(msg))); switch (msg) { .welcome => |v| { try w.putU16(v.version); @@ -1172,7 +1172,7 @@ pub fn encodeServer(out: []u8, msg: ServerMsg) Error![]const u8 { try w.putU16(v.cols); try w.putU16(v.rows); }, - .refuse => |why| try w.putByte(@intFromEnum(why)), + .refuse => |why| try w.putByte(@backingInt(why)), // A frame's runs are not a value this union can hold; the server calls // encodeFrame directly and this arm exists so the switch stays // exhaustive over ServerMsg. @@ -1182,11 +1182,11 @@ pub fn encodeServer(out: []u8, msg: ServerMsg) Error![]const u8 { .read_clipboard => {}, .open_link => |u| try w.putSlice16(u), .post => |p| { - try w.putByte(@intFromEnum(p.animation)); + try w.putByte(@backingInt(p.animation)); try w.putByte(p.len); for (p.list()) |pass| { // 0 a file, else a bundled scene and one. - try w.putByte(if (pass.scene) |scene| @as(u8, @intFromEnum(scene)) + 1 else 0); + try w.putByte(if (pass.scene) |scene| @as(u8, @backingInt(scene)) + 1 else 0); try w.putByte(pass.level); try w.putByte(@intFromBool(pass.animated)); try w.putU32(pass.revision); @@ -1341,9 +1341,9 @@ test "detached wire: every Event variant round-trips" { // The tag space is the protocol's own, so assert the numbers themselves: // a renumbering here breaks every deployed frontend and must be a diff // somebody reads, not a silent change. - try testing.expectEqual(@as(u8, 0x01), @intFromEnum(ClientTag.hello)); - try testing.expectEqual(@as(u8, 0x10), @intFromEnum(ClientTag.key)); - try testing.expectEqual(@as(u8, 0x1d), @intFromEnum(ClientTag.pointer_leave)); + try testing.expectEqual(@as(u8, 0x01), @backingInt(ClientTag.hello)); + try testing.expectEqual(@as(u8, 0x10), @backingInt(ClientTag.key)); + try testing.expectEqual(@as(u8, 0x1d), @backingInt(ClientTag.pointer_leave)); { const got = try roundClient(&buf, .{ .hello = .{ .cols = 80, .rows = 24 } }); @@ -1506,7 +1506,7 @@ test "detached wire: a session is never told to do a frontend's remembering" { } const named = for (allowed) |ok| { const want = std.meta.stringToEnum(ClientTag, ok).?; - if (@intFromEnum(want) == tag) break true; + if (@backingInt(want) == tag) break true; } else false; if (!named) { std.debug.print("tag 0x{x:0>2} is decodable by a session and is not something a human did\n", .{tag}); @@ -1752,8 +1752,8 @@ test "detached wire: a truncated frame is refused at every length" { for (0..header_len + 1) |cut| try testing.expectEqual(@as(?Framed, null), try framed(copy[0..cut])); // A payload with bytes LEFT OVER is refused too: it is not this message. - try testing.expectError(error.Trailing, decodeClient(@intFromEnum(ClientTag.pointer_leave), "x")); - try testing.expectError(error.Trailing, decodeServer(@intFromEnum(ServerTag.quit), "x")); + try testing.expectError(error.Trailing, decodeClient(@backingInt(ClientTag.pointer_leave), "x")); + try testing.expectError(error.Trailing, decodeServer(@backingInt(ServerTag.quit), "x")); } test "detached wire: an unknown tag is refused, never guessed" { @@ -1765,9 +1765,9 @@ test "detached wire: an unknown tag is refused, never guessed" { } // A tag NESTED in a payload gets the same treatment: a color, an // underline style, a mouse button, a refusal reason. - try testing.expectError(error.BadTag, decodeServer(@intFromEnum(ServerTag.refuse), &.{0x7f})); + try testing.expectError(error.BadTag, decodeServer(@backingInt(ServerTag.refuse), &.{0x7f})); try testing.expectError(error.BadTag, decodeClient( - @intFromEnum(ClientTag.mouse), + @backingInt(ClientTag.mouse), &.{ 0xff, 0x00, 0, 0, 0, 0, 0 }, )); } @@ -1775,7 +1775,7 @@ test "detached wire: an unknown tag is refused, never guessed" { test "detached wire: an over-long length prefix is refused before it is believed" { // The prefix a hostile or corrupt peer sends to make the receiver allocate // or index by it. `framed` must refuse rather than wait for 4 GiB. - var head: [header_len]u8 = .{ @intFromEnum(ClientTag.paste), 0, 0, 0, 0 }; + var head: [header_len]u8 = .{ @backingInt(ClientTag.paste), 0, 0, 0, 0 }; std.mem.writeInt(u32, head[1..5], max_payload + 1, .little); try testing.expectError(error.Overlong, framed(&head)); std.mem.writeInt(u32, head[1..5], std.math.maxInt(u32), .little); @@ -1789,10 +1789,10 @@ test "detached wire: an over-long length prefix is refused before it is believed var paste: [8]u8 = undefined; std.mem.writeInt(u32, paste[0..4], 4096, .little); @memcpy(paste[4..8], "abcd"); - try testing.expectError(error.Truncated, decodeClient(@intFromEnum(ClientTag.paste), &paste)); + try testing.expectError(error.Truncated, decodeClient(@backingInt(ClientTag.paste), &paste)); // ...and past the cap, which is refused rather than read. std.mem.writeInt(u32, paste[0..4], max_payload + 1, .little); - try testing.expectError(error.Overlong, decodeClient(@intFromEnum(ClientTag.paste), &paste)); + try testing.expectError(error.Overlong, decodeClient(@backingInt(ClientTag.paste), &paste)); } test "detached wire: a frame that lies about its runs cannot walk out of the grid" { @@ -1837,13 +1837,13 @@ test "detached wire: a frame that lies about its runs cannot walk out of the gri // it is used to bound the walk. var head: [frame_head]u8 = undefined; var w: Writer = .init(&head); - try w.putByte(@intFromEnum(FrameKind.diff)); + try w.putByte(@backingInt(FrameKind.diff)); try w.putU16(cols); try w.putU16(rows); try putCursor(&w, null, cols, rows); try w.putU32(0); // no body layers try w.putU32(9); - try testing.expectError(error.Overlong, decodeServer(@intFromEnum(ServerTag.frame), w.written())); + try testing.expectError(error.Overlong, decodeServer(@backingInt(ServerTag.frame), w.written())); // ...and a grid of the wrong size is the receiver's own bug, not a frame // it should paint half of. @@ -1885,7 +1885,7 @@ test "detached wire: a cursor outside the grid is refused, not painted" { var head: [frame_head]u8 = undefined; for ([_][2]u16{ .{ cols, 0 }, .{ 0, rows }, .{ 0xffff, 0xffff } }) |xy| { var w: Writer = .init(&head); - try w.putByte(@intFromEnum(FrameKind.diff)); + try w.putByte(@backingInt(FrameKind.diff)); try w.putU16(cols); try w.putU16(rows); // Written by hand: `putCursor` now refuses this too, which is the @@ -1897,19 +1897,19 @@ test "detached wire: a cursor outside the grid is refused, not painted" { try w.putU32(0); try testing.expectError( error.BadValue, - decodeServer(@intFromEnum(ServerTag.frame), w.written()), + decodeServer(@backingInt(ServerTag.frame), w.written()), ); } // The last cell IS in the grid, and a frame carrying it decodes. { var w: Writer = .init(&head); - try w.putByte(@intFromEnum(FrameKind.diff)); + try w.putByte(@backingInt(FrameKind.diff)); try w.putU16(cols); try w.putU16(rows); try putCursor(&w, .{ .x = cols - 1, .y = rows - 1, .bar = true }, cols, rows); try w.putU32(0); // no body layers try w.putU32(0); - const got = (try decodeServer(@intFromEnum(ServerTag.frame), w.written())).frame; + const got = (try decodeServer(@backingInt(ServerTag.frame), w.written())).frame; try testing.expectEqual(@as(u16, cols - 1), got.cursor.?.x); try testing.expectEqual(@as(u16, rows - 1), got.cursor.?.y); } @@ -1933,25 +1933,25 @@ test "detached wire: values a field cannot mean are refused" { // A bool is 0 or 1. `2` used to be "true" in every hand-written codec that // ever silently accepted a corrupt stream. try testing.expectError(error.BadValue, decodeClient( - @intFromEnum(ClientTag.key), + @backingInt(ClientTag.key), &.{ 'a', 0, 0, 0, 0, 0, 2, 0, 0 }, )); // A codepoint past Unicode's last: @intCast into Key.cp's u21 would panic. try testing.expectError(error.BadValue, decodeClient( - @intFromEnum(ClientTag.key), + @backingInt(ClientTag.key), &.{ 0x00, 0x00, 0x11, 0x00, 0, 0, 0, 0, 0 }, )); // A pane the core cannot index. `pdf_scroll` reads its pane byte before the // f32 that follows, so a one-byte payload reaches the check this is about // rather than tripping `Truncated` first. try testing.expectError(error.BadValue, decodeClient( - @intFromEnum(ClientTag.pdf_scroll), + @backingInt(ClientTag.pdf_scroll), &.{pardes.MAX_PANES}, )); // A zero-column grid would collapse a shared session; an over-wide one is // past what this protocol carries. try testing.expectError(error.BadValue, decodeClient( - @intFromEnum(ClientTag.hello), + @backingInt(ClientTag.hello), &.{ 1, 0, 0, 0, 24, 0 }, )); { @@ -1959,15 +1959,15 @@ test "detached wire: values a field cannot mean are refused" { std.mem.writeInt(u16, hello[0..2], version, .little); std.mem.writeInt(u16, hello[2..4], max_cols + 1, .little); std.mem.writeInt(u16, hello[4..6], 24, .little); - try testing.expectError(error.BadValue, decodeClient(@intFromEnum(ClientTag.hello), &hello)); + try testing.expectError(error.BadValue, decodeClient(@backingInt(ClientTag.hello), &hello)); } // A NaN scroll distance. `pinch` multiplies into a zoom the pane keeps. { var pinch: [4]u8 = undefined; std.mem.writeInt(u32, &pinch, @bitCast(std.math.nan(f32)), .little); - try testing.expectError(error.BadValue, decodeClient(@intFromEnum(ClientTag.pinch), &pinch)); + try testing.expectError(error.BadValue, decodeClient(@backingInt(ClientTag.pinch), &pinch)); std.mem.writeInt(u32, &pinch, @bitCast(std.math.inf(f32)), .little); - try testing.expectError(error.BadValue, decodeClient(@intFromEnum(ClientTag.touch_scroll), &pinch)); + try testing.expectError(error.BadValue, decodeClient(@backingInt(ClientTag.touch_scroll), &pinch)); } // A cell with the reserved attribute bit set, and one with an impossible // grapheme length. Both are bytes this protocol has no meaning for. diff --git a/src/diff.zig b/src/diff.zig index 362695d5..842a6b41 100644 --- a/src/diff.zig +++ b/src/diff.zig @@ -163,8 +163,8 @@ pub const Walk = struct { }; const meta_words = [_][]const u8{ - "index ", "new file mode ", "deleted file mode ", "old mode ", "new mode ", - "similarity index ", "rename from ", "rename to ", "copy from ", "copy to ", + "index ", "new file mode ", "deleted file mode ", "old mode ", "new mode ", + "similarity index ", "rename from ", "rename to ", "copy from ", "copy to ", "Binary files ", "dissimilarity ", }; diff --git a/src/draw.zig b/src/draw.zig index e6420ed4..22a8dc2a 100644 --- a/src/draw.zig +++ b/src/draw.zig @@ -564,7 +564,7 @@ pub fn render(p: *Pardes, arena: std.mem.Allocator) !*Surface { .accent = chrome.box, .sel_fg = p.theme().sel_fg, .sel_bg = p.theme().sel_bg, - .lift_style = @intFromEnum(liftStyle(p)), + .lift_style = @backingInt(liftStyle(p)), .rule_px = p.theme().rule_px orelse 2, .grip_border = boxBorder(p), .grip_focus_ring = chrome.box, @@ -1167,7 +1167,7 @@ fn renderHeaderLayer(p: *Pardes, arena: std.mem.Allocator, layer: *pardes.Layer, const start = modal.lineStartOffset(text, index + top); const end = start + shown.len; if (mine and swept.lo < swept.hi and swept.hi > start and swept.lo < end) { - const button = @intFromEnum(sweep.button); + const button = @backingInt(sweep.button); var col = panes.File.rawDisplayCol(shown, @max(swept.lo, start) - start) -| scroll; const stop = panes.File.rawDisplayCol(shown, @min(swept.hi, end) - start) -| scroll; while (col < stop and col < columns) : (col += 1) { diff --git a/src/dump.zig b/src/dump.zig index 545d09ec..76a6de85 100644 --- a/src/dump.zig +++ b/src/dump.zig @@ -1100,7 +1100,7 @@ test "a restored session's column and workspace tags take more than one selectio try std.testing.expect(restored.col_tags[0].reserveSels()); try std.testing.expect(restored.global_tag.reserveSels()); try std.testing.expect(restored.fs.started != 0); - const stat = th.call(restored, .{ .tag = 1, .op = .getattr, .node = @intFromEnum(pardes.ctlfs.TopFile.index) }); + const stat = th.call(restored, .{ .tag = 1, .op = .getattr, .node = @backingInt(pardes.ctlfs.TopFile.index) }); try std.testing.expect(stat.reply.attr.mtime != 0); } @@ -1146,7 +1146,7 @@ test "a pane restored with unsaved text is asked about by Exit, Restore, Del and const node = if (std.mem.eql(u8, word, "Del") or std.mem.eql(u8, word, "get")) ctlfs.Node.of(restored.panes[id].?.serial, .ctl) else - @intFromEnum(ctlfs.TopFile.ctl); + @backingInt(ctlfs.TopFile.ctl); const line = if (std.mem.eql(u8, word, "Restore")) try std.fmt.bufPrint(&restore_line, "Restore {s}/d.zon\n", .{dir}) else if (std.mem.eql(u8, word, "Exit")) "Exit\n" else if (std.mem.eql(u8, word, "Del")) "Del\n" else "get\n"; const answer = th.wr(restored, node, line); try std.testing.expectEqual(ctlfs.Status.err, answer.reply.status); diff --git a/src/edit_cmd.zig b/src/edit_cmd.zig index d3377e09..447ea66b 100644 --- a/src/edit_cmd.zig +++ b/src/edit_cmd.zig @@ -495,7 +495,7 @@ test "Edit , | sort runs off the loop, through the session's shell in the file's try testing.expectEqualStrings(@import("ninep/ctl.zig").e_after_edit, after.reply.ename); try testing.expect(p.pipe.edit_run == null and !th.logHas(p, "before")); } - try testing.expectEqual(tree.E.INVAL, th.wr(p, @intFromEnum(tree.TopFile.exec), "Msg before\nEdit , | sort\n").errno()); + try testing.expectEqual(tree.E.INVAL, th.wr(p, @backingInt(tree.TopFile.exec), "Msg before\nEdit , | sort\n").errno()); } test "the held write asked again is parked again, then answered once, and a flush stops the Edit" { diff --git a/src/esp32p4.zig b/src/esp32p4.zig index ed18efd9..683d19e1 100644 --- a/src/esp32p4.zig +++ b/src/esp32p4.zig @@ -134,19 +134,19 @@ pub const GpioFn = *const fn (ctx: ?*anyopaque, pin: u16, was: *u8, now: *u8) ca var host_alloc: Allocator = undefined; fn hostAlloc(_: *anyopaque, len: usize, alignment: std.mem.Alignment, _: usize) ?[*]u8 { - return host_alloc.alloc(host_alloc.ctx, len, @intFromEnum(alignment)); + return host_alloc.alloc(host_alloc.ctx, len, @backingInt(alignment)); } fn hostResize(_: *anyopaque, mem: []u8, alignment: std.mem.Alignment, new_len: usize, _: usize) bool { - return host_alloc.resize(host_alloc.ctx, mem.ptr, mem.len, @intFromEnum(alignment), new_len); + return host_alloc.resize(host_alloc.ctx, mem.ptr, mem.len, @backingInt(alignment), new_len); } fn hostRemap(_: *anyopaque, mem: []u8, alignment: std.mem.Alignment, new_len: usize, _: usize) ?[*]u8 { - return if (host_alloc.resize(host_alloc.ctx, mem.ptr, mem.len, @intFromEnum(alignment), new_len)) mem.ptr else null; + return if (host_alloc.resize(host_alloc.ctx, mem.ptr, mem.len, @backingInt(alignment), new_len)) mem.ptr else null; } fn hostFree(_: *anyopaque, mem: []u8, alignment: std.mem.Alignment, _: usize) void { - host_alloc.free(host_alloc.ctx, mem.ptr, mem.len, @intFromEnum(alignment)); + host_alloc.free(host_alloc.ctx, mem.ptr, mem.len, @backingInt(alignment)); } const host_vtable: std.mem.Allocator.VTable = .{ @@ -447,19 +447,21 @@ fn apply(c: *pardes.Pardes, ev: vaxis.Event) void { else => null, }; if (button) |b| { - c.update(.{ .mouse = .{ - .button = b, - .kind = switch (m.type) { - .press => .press, - .release => .release, - .motion => .motion, - .drag => .drag, + c.update(.{ + .mouse = .{ + .button = b, + .kind = switch (m.type) { + .press => .press, + .release => .release, + .motion => .motion, + .drag => .drag, + }, + // Before the first cell (a drag past the edge): the edge. + .col = @intCast(@max(0, m.col)), + .row = @intCast(@max(0, m.row)), + .ctrl = m.mods.ctrl, }, - // Before the first cell (a drag past the edge): the edge. - .col = @intCast(@max(0, m.col)), - .row = @intCast(@max(0, m.row)), - .ctrl = m.mods.ctrl, - } }); + }); dirty = true; } }, diff --git a/src/esp32p4/app.zig b/src/esp32p4/app.zig index 4ee131ec..800e7597 100644 --- a/src/esp32p4/app.zig +++ b/src/esp32p4/app.zig @@ -235,17 +235,17 @@ var gpa_heap: heapmod.Heap = undefined; fn cAlloc(_: ?*anyopaque, len: usize, log2_align: u8) callconv(.c) ?[*]u8 { const a = gpa_heap.allocator(); - return a.vtable.alloc(a.ptr, len, @enumFromInt(log2_align), @returnAddress()); + return a.vtable.alloc(a.ptr, len, @fromBackingInt(@intCast(log2_align)), @returnAddress()); } fn cResize(_: ?*anyopaque, ptr: [*]u8, len: usize, log2_align: u8, new_len: usize) callconv(.c) bool { const a = gpa_heap.allocator(); - return a.vtable.resize(a.ptr, ptr[0..len], @enumFromInt(log2_align), new_len, @returnAddress()); + return a.vtable.resize(a.ptr, ptr[0..len], @fromBackingInt(@intCast(log2_align)), new_len, @returnAddress()); } fn cFree(_: ?*anyopaque, ptr: [*]u8, len: usize, log2_align: u8) callconv(.c) void { const a = gpa_heap.allocator(); - a.vtable.free(a.ptr, ptr[0..len], @enumFromInt(log2_align), @returnAddress()); + a.vtable.free(a.ptr, ptr[0..len], @fromBackingInt(@intCast(log2_align)), @returnAddress()); } const editor_allocator: Allocator = .{ diff --git a/src/esp32p4_9p.zig b/src/esp32p4_9p.zig index cd59b9df..5fcab85b 100644 --- a/src/esp32p4_9p.zig +++ b/src/esp32p4_9p.zig @@ -103,7 +103,7 @@ fn die(msg: []const u8) noreturn { .{ .rerror = .{ .ename = msg[0..@min(msg.len, ninep.errmax)] } }, ninep.notag, &buf, - // unreachable: the message is cut to errmax and buf is sized to it + // unreachable: the message is cut to errmax and buf is sized to it ) catch unreachable; uart.write(bytes); while (true) {} diff --git a/src/fonts.zig b/src/fonts.zig index 098bf36f..88cde63a 100644 --- a/src/fonts.zig +++ b/src/fonts.zig @@ -324,7 +324,7 @@ fn sfntBase(head: []const u8) ?usize { fn scratchFont(buf: *[64:0]u8, ext: []const u8) [:0]const u8 { return std.fmt.bufPrintSentinel(buf, "/tmp/pardes-fonts-test-{d}{s}", .{ @as(u32, @intCast(libc.getpid())), ext, - // unreachable: 23 bytes, a u32 pid (10) and a short extension fit 64 + // unreachable: 23 bytes, a u32 pid (10) and a short extension fit 64 }, 0) catch unreachable; } diff --git a/src/gui/Post.zig b/src/gui/Post.zig index 8d0e14d9..17e8d7e9 100644 --- a/src/gui/Post.zig +++ b/src/gui/Post.zig @@ -623,15 +623,15 @@ test "the uniform block is ghostty's, offset for offset, and the prefix names it try std.testing.expectEqual(@offsetOf(GhosttyUniforms, "selection_background_color"), @offsetOf(Uniforms, "selection_foreground_color")); // The prefix's block, member by member, in ghostty's GLSL names and types. const glsl = [_]struct { []const u8, []const u8 }{ - .{ "vec3", "iResolution" }, .{ "float", "iTime" }, .{ "float", "iTimeDelta" }, - .{ "float", "iFrameRate" }, .{ "int", "iFrame" }, .{ "float", "iChannelTime[4]" }, - .{ "vec3", "iChannelResolution[4]" }, .{ "vec4", "iMouse" }, .{ "vec4", "iDate" }, - .{ "float", "iSampleRate" }, .{ "vec4", "iCurrentCursor" }, .{ "vec4", "iPreviousCursor" }, - .{ "vec4", "iCurrentCursorColor" }, .{ "vec4", "iPreviousCursorColor" }, .{ "int", "iCurrentCursorStyle" }, - .{ "int", "iPreviousCursorStyle" }, .{ "int", "iCursorVisible" }, .{ "float", "iTimeCursorChange" }, - .{ "float", "iTimeFocus" }, .{ "int", "iFocus" }, .{ "vec3", "iPalette[256]" }, - .{ "vec3", "iBackgroundColor" }, .{ "vec3", "iForegroundColor" }, .{ "vec3", "iCursorColor" }, - .{ "vec3", "iCursorText" }, .{ "vec3", "iSelectionForegroundColor" }, .{ "vec3", "iSelectionBackgroundColor" }, + .{ "vec3", "iResolution" }, .{ "float", "iTime" }, .{ "float", "iTimeDelta" }, + .{ "float", "iFrameRate" }, .{ "int", "iFrame" }, .{ "float", "iChannelTime[4]" }, + .{ "vec3", "iChannelResolution[4]" }, .{ "vec4", "iMouse" }, .{ "vec4", "iDate" }, + .{ "float", "iSampleRate" }, .{ "vec4", "iCurrentCursor" }, .{ "vec4", "iPreviousCursor" }, + .{ "vec4", "iCurrentCursorColor" }, .{ "vec4", "iPreviousCursorColor" }, .{ "int", "iCurrentCursorStyle" }, + .{ "int", "iPreviousCursorStyle" }, .{ "int", "iCursorVisible" }, .{ "float", "iTimeCursorChange" }, + .{ "float", "iTimeFocus" }, .{ "int", "iFocus" }, .{ "vec3", "iPalette[256]" }, + .{ "vec3", "iBackgroundColor" }, .{ "vec3", "iForegroundColor" }, .{ "vec3", "iCursorColor" }, + .{ "vec3", "iCursorText" }, .{ "vec3", "iSelectionForegroundColor" }, .{ "vec3", "iSelectionBackgroundColor" }, }; try std.testing.expectEqual(ours.field_names.len, glsl.len); // Its three blocks (Globals, Palette, Colors) read as one, in order. @@ -673,7 +673,6 @@ test "a moved cursor becomes the previous one, stamped with the time of the move try std.testing.expectEqual([4]f32{ 1.0 / 255.0, 2.0 / 255.0, 3.0 / 255.0, 1 }, post.uniforms.selection_foreground_color); } - test "a still pass asks for no idle frames; one that reads the clock does" { var post: Post = .{}; const fake: *Pipeline = @ptrFromInt(0x1000); diff --git a/src/gui/gui.zig b/src/gui/gui.zig index b8687fd3..f0dd0682 100644 --- a/src/gui/gui.zig +++ b/src/gui/gui.zig @@ -1888,7 +1888,6 @@ const Gui = struct { sel_glow: SelGlow = .{}, hover_glow: SelGlow = .{}, /// G14: the cells last drawn and when each last changed. - /// The cursor's blink (blinkNow): when the frame drawn last arrived, /// a redraw owed for an edge, and this frame's cursor mode and alpha. frame_arrival_ns: u64 = 0, @@ -2291,7 +2290,7 @@ fn setTransitionFields( instance.present_y0 = presented[1]; instance.present_x1 = presented[2]; instance.present_y1 = presented[3]; - instance.effect = @intFromEnum(active.effect); + instance.effect = @backingInt(active.effect); instance.progress_bits = @bitCast(active.amount()); instance.serial = active.serial; instance.cell_coord = cell_coord; @@ -3356,8 +3355,8 @@ fn setStdinRaw() !void { term.lflag.ICANON = false; term.lflag.IEXTEN = false; term.lflag.ISIG = false; - term.cc[@intFromEnum(posix.V.MIN)] = 1; - term.cc[@intFromEnum(posix.V.TIME)] = 0; + term.cc[@backingInt(posix.V.MIN)] = 1; + term.cc[@backingInt(posix.V.TIME)] = 0; try posix.tcsetattr(0, .NOW, term); } @@ -5484,7 +5483,6 @@ test "a notch scrolls the core at once and the picture glides after it, a wrappe try std.testing.expect(!g.glide.pending and !g.glide.moving()); } - fn resetScroll(g: *Gui) void { g.scroll_pane = null; g.scroll_delta = 0; @@ -5519,13 +5517,15 @@ fn stepScroll(g: *Gui, core: *pardes.Pardes, gpa: std.mem.Allocator) void { const down = left > 0; left += if (down) -1 else 1; const was = pane.scroll(); - core.update(.{ .mouse = .{ - .button = if (down) .wheel_down else .wheel_up, - .kind = .press, - .col = g.scroll_col, - .row = g.scroll_row, - .shift = true, // pardes's own scroll, never a program's wheel - } }); + core.update(.{ + .mouse = .{ + .button = if (down) .wheel_down else .wheel_up, + .kind = .press, + .col = g.scroll_col, + .row = g.scroll_row, + .shift = true, // pardes's own scroll, never a program's wheel + }, + }); if (pane.scroll() == was) { resetScroll(g); return; @@ -7251,7 +7251,7 @@ test "a rising pane past its mark stays inside its box" { var g: Gui = undefined; g.cell_w = 10; g.cell_h = 20; - var track: pardes.animation.Track = .{ .serial = 3, .phase = .opening, .effect = .vertical, .motion = @intFromEnum(pardes.animation.Motion.Flavour.bouncy) + 1, .frame_count = 20, .from = .{ .x = 0, .y = 10, .w = 40, .h = 10 }, .to = .{ .x = 0, .y = 0, .w = 40, .h = 10 } }; + var track: pardes.animation.Track = .{ .serial = 3, .phase = .opening, .effect = .vertical, .motion = @backingInt(pardes.animation.Motion.Flavour.bouncy) + 1, .frame_count = 20, .from = .{ .x = 0, .y = 10, .w = 40, .h = 10 }, .to = .{ .x = 0, .y = 0, .w = 40, .h = 10 } }; var peak: u16 = 0; var highest: f32 = 1e9; while (track.frame < track.frames()) : (track.frame += 1) { @@ -8788,7 +8788,6 @@ fn addPattern(g: *Gui, gpa: std.mem.Allocator, x0: f32, y0: f32, x1: f32, y1: f3 instance.effect |= checker_bit; } - /// How a lift of 0 to 1 stands off the page: the shadow's blur and offset /// in cell heights, and its darkest, where it leaves the caster's edge. /// Within §8.2's budget: sigma 0.4-0.8 cell, at most 30% darker at the edge. @@ -8926,7 +8925,6 @@ fn clipToBodies(g: *Gui, gpa: std.mem.Allocator, first: usize, bodies: []const [ }; } - /// Like shadowCeiling for a light colour laid over at `a` (sRGB blend, as /// the decor pipeline blends a colour that is not black): the largest `a` /// that keeps text and page apart by min(their contrast, 4.5). @@ -10099,7 +10097,7 @@ test "decor is read from the regions, each pane's in its own group" { try std.testing.expect(tracked.decor_count >= 4); try std.testing.expectEqual(still, groups.items[0].decor_count + tracked.decor_count); for (g.decor.items[tracked.decor_start..][0..tracked.decor_count]) |item| - try std.testing.expectEqual(@as(u32, @intFromEnum(pardes.animation.Transition.slide)), item.effect); + try std.testing.expectEqual(@as(u32, @backingInt(pardes.animation.Transition.slide)), item.effect); // Cursors stand still while panes move. try std.testing.expectEqual(@as(u32, 0), groups.items[groups.ink].decor_count); } @@ -10468,7 +10466,7 @@ fn appendCursorGlide(g: *Gui, surface: *const pardes.Surface, builder: *OverlayB fn appendWorkspacePet(g: *Gui, core: ?*const pardes.Pardes, surface: *const pardes.Surface, builder: *OverlayBuilder) void { const p = core orelse return; - const kind: pet.Kind = @enumFromInt(@intFromEnum(p.settings.pet)); + const kind: pet.Kind = @fromBackingInt(@intCast(@backingInt(p.settings.pet))); if (kind == .off or surface.rows == 0 or surface.cols == 0) { g.pet_state = .{}; return; diff --git a/src/host_io.zig b/src/host_io.zig index d789a77d..bef88172 100644 --- a/src/host_io.zig +++ b/src/host_io.zig @@ -572,7 +572,7 @@ pub const Shell = struct { const name = std.mem.sliceTo(@as([*:0]const u8, @ptrCast(&ent.name)), 0); const pid = rcPid(name) orelse continue; if (pid == std.c.getpid()) continue; - if (std.posix.errno(std.c.kill(pid, @enumFromInt(0))) != .SRCH) continue; + if (std.posix.errno(std.c.kill(pid, @fromBackingInt(@intCast(0)))) != .SRCH) continue; if (name.len >= 64 or n == dead.len) continue; @memcpy(dead[n][0..name.len], name); dead_len[n] = name.len; @@ -1236,8 +1236,8 @@ pub fn resetChildSignals() void { const default: posix.Sigaction = .{ .handler = .{ .handler = posix.SIG.DFL }, .mask = posix.sigemptyset(), .flags = 0 }; var sig: u8 = 1; while (sig < 65) : (sig += 1) { - if (sig == @intFromEnum(posix.SIG.KILL) or sig == @intFromEnum(posix.SIG.STOP)) continue; - _ = std.c.sigaction(@enumFromInt(sig), &default, null); + if (sig == @backingInt(posix.SIG.KILL) or sig == @backingInt(posix.SIG.STOP)) continue; + _ = std.c.sigaction(@fromBackingInt(@intCast(sig)), &default, null); } const none = posix.sigemptyset(); posix.sigprocmask(posix.SIG.SETMASK, &none, null); @@ -1620,13 +1620,13 @@ pub fn forkShell( if (pid == 0) { resetChildSignals(); if (cwd_z) |path| if (chdir(path.ptr) != 0) { - const why = [_]u8{ 'c', @truncate(@intFromEnum(libc.errno(@as(c_int, -1)))) }; + const why = [_]u8{ 'c', @truncate(@backingInt(libc.errno(@as(c_int, -1)))) }; _ = libc.write(told[1], &why, why.len); _exit(126); }; if (envp) |env| _ = execve(spawn.path, &spawn.argv, env); _ = execv(spawn.path, &spawn.argv); - const why = [_]u8{ 'x', @truncate(@intFromEnum(libc.errno(@as(c_int, -1)))) }; + const why = [_]u8{ 'x', @truncate(@backingInt(libc.errno(@as(c_int, -1)))) }; _ = libc.write(told[1], &why, why.len); _exit(127); } @@ -1643,7 +1643,7 @@ pub fn forkShell( if (failed) |why| { _ = libc.close(master); _ = libc.waitpid(pid, null, 0); - const e: libc.E = @enumFromInt(why[1]); + const e: libc.E = @fromBackingInt(@intCast(why[1])); if (why[0] == 'c') return if (e == .NOENT or e == .NOTDIR) error.FileNotFound else error.AccessDenied; return switch (e) { // Itself, or its script's interpreter: told apart by whether it @@ -2167,7 +2167,7 @@ pub fn reapExited(pid: libc.pid_t) ?struct { status: ?u8 } { if (got != pid) return .{ .status = null }; const s: u32 = @bitCast(status); if (libc.W.IFEXITED(s)) return .{ .status = @truncate(libc.W.EXITSTATUS(s)) }; - if (libc.W.IFSIGNALED(s)) return .{ .status = @truncate(128 + @as(u32, @intFromEnum(libc.W.TERMSIG(s)))) }; + if (libc.W.IFSIGNALED(s)) return .{ .status = @truncate(128 + @as(u32, @backingInt(libc.W.TERMSIG(s)))) }; return .{ .status = null }; } @@ -2194,7 +2194,7 @@ pub fn exitStatus(pid: libc.pid_t, wait_ms: u32) ?u8 { if (got == pid) { const s: u32 = @bitCast(status); if (libc.W.IFEXITED(s)) return @truncate(libc.W.EXITSTATUS(s)); - if (libc.W.IFSIGNALED(s)) return @truncate(128 + @as(u32, @intFromEnum(libc.W.TERMSIG(s)))); + if (libc.W.IFSIGNALED(s)) return @truncate(128 + @as(u32, @backingInt(libc.W.TERMSIG(s)))); return null; } if (got < 0 or waited >= wait_ms) return null; @@ -2722,8 +2722,8 @@ test "a retired shell that ignores the hangup is killed and reaped, not left a z retireShell(pid); // A zombie still answers kill(pid, 0); only a reaped pid is gone. var waited: i64 = 0; - while (libc.kill(pid, @enumFromInt(0)) == 0 and waited < 2000) : (waited += 10) sleepMs(10); - try std.testing.expect(libc.kill(pid, @enumFromInt(0)) != 0); + while (libc.kill(pid, @fromBackingInt(@intCast(0))) == 0 and waited < 2000) : (waited += 10) sleepMs(10); + try std.testing.expect(libc.kill(pid, @fromBackingInt(@intCast(0))) != 0); try std.testing.expect(waited >= 90); // it did ignore the hangup } diff --git a/src/linux/v9fs.zig b/src/linux/v9fs.zig index 15945e7b..0d1e2e33 100644 --- a/src/linux/v9fs.zig +++ b/src/linux/v9fs.zig @@ -89,7 +89,7 @@ var sudo_pid: std.atomic.Value(c_int) = .init(-1); fn forwardSignal(sig: std.posix.SIG) callconv(.c) void { const pid = sudo_pid.load(.monotonic); - if (pid > 0) _ = kill(pid, @intCast(@intFromEnum(sig))); + if (pid > 0) _ = kill(pid, @intCast(@backingInt(sig))); } fn launch(arena: std.mem.Allocator, args: []const [:0]const u8) !u8 { @@ -123,8 +123,8 @@ fn launch(arena: std.mem.Allocator, args: []const [:0]const u8) !u8 { const default: std.posix.Sigaction = .{ .handler = .{ .handler = std.posix.SIG.DFL }, .mask = std.posix.sigemptyset(), .flags = 0 }; var sig: u8 = 1; while (sig < 65) : (sig += 1) { - if (sig == @intFromEnum(std.posix.SIG.KILL) or sig == @intFromEnum(std.posix.SIG.STOP)) continue; - _ = std.c.sigaction(@enumFromInt(sig), &default, null); + if (sig == @backingInt(std.posix.SIG.KILL) or sig == @backingInt(std.posix.SIG.STOP)) continue; + _ = std.c.sigaction(@fromBackingInt(@intCast(sig)), &default, null); } const none = std.posix.sigemptyset(); std.posix.sigprocmask(std.posix.SIG.SETMASK, &none, null); diff --git a/src/look.zig b/src/look.zig index f9c470cf..f4fbe52e 100644 --- a/src/look.zig +++ b/src/look.zig @@ -2555,7 +2555,7 @@ test "every entry point to Look takes one expansion: a diff line and a file:12:5 const line = modal.lineSlice(case.text, case.row); // A diff line written whole; a place, as a script writes it. const written = if (std.mem.eql(u8, case.name, "change.diff")) line else line[case.sweep[0] .. case.sweep[1] + 1]; - _ = th.wr(p, @intFromEnum(pardes.ctlfs.TopFile.look), written); + _ = th.wr(p, @backingInt(pardes.ctlfs.TopFile.look), written); }, .event_write_back => { const body = pane.file.?.content; diff --git a/src/macos.zig b/src/macos.zig index 37db0abd..21af41ae 100644 --- a/src/macos.zig +++ b/src/macos.zig @@ -1717,18 +1717,20 @@ fn mouseWithHit(button_arg: c_int, kind_arg: c_int, col: u16, row: u16, mods: u3 3 => .drag, else => return, }; - st.core.update(.{ .mouse = .{ - .body_hit = hit, - .tag_hit = tag_hit, - .button = button, - .kind = kind, - .col = col, - .row = row, - .ctrl = mods & 1 != 0, - // Option-click is B2 and Cmd-click B3 (mouse.emulateButton). - .alt = mods & 2 != 0, - .super = mods & 8 != 0, - } }); + st.core.update(.{ + .mouse = .{ + .body_hit = hit, + .tag_hit = tag_hit, + .button = button, + .kind = kind, + .col = col, + .row = row, + .ctrl = mods & 1 != 0, + // Option-click is B2 and Cmd-click B3 (mouse.emulateButton). + .alt = mods & 2 != 0, + .super = mods & 8 != 0, + }, + }); } export fn pardes_pointer_leave() void { @@ -2156,7 +2158,7 @@ export fn pardes_tag_layer_value(index: u32, field: u32) u32 { const layer = &st.core.surface.tag_layers[index]; return switch (field) { 0 => layer.cols, - 1 => @intFromEnum(layer.kind), + 1 => @backingInt(layer.kind), 2 => layer.id, 3 => layer.serial, 4 => layer.viewport.x, @@ -2238,7 +2240,7 @@ export fn pardes_pointer_shape() u32 { pardes.turn.wake(); defer pardes.turn.rest(); const st = &(state orelse return 0); - return @intFromEnum(st.core.surface.pointer_shape); + return @backingInt(st.core.surface.pointer_shape); } export fn pardes_cursor_y() i32 { @@ -2646,7 +2648,7 @@ fn encodeAttrs(style: pardes.CellStyle) u16 { attrs |= @as(u16, @intFromBool(style.reverse)) << 4; attrs |= @as(u16, @intFromBool(style.invisible)) << 5; attrs |= @as(u16, @intFromBool(style.strikethrough)) << 6; - attrs |= @as(u16, @intFromEnum(style.ul)) << 8; + attrs |= @as(u16, @backingInt(style.ul)) << 8; return attrs; } @@ -2896,21 +2898,21 @@ test "pardes.h matches the Zig boundary" { try expectEqual(@as(u8, c.PARDES_CELL_HOVER), cell_flag_hover); try expectEqual(@as(u16, c.PARDES_TOPBAR_H), pardes.TOPBAR_H); try expectEqual(@as(u32, c.PARDES_SCENE_CRT), scene_flag_crt); - try expectEqual(@as(u8, c.PARDES_PANEL_OPENING), @intFromEnum(animation.Phase.opening)); - try expectEqual(@as(u8, c.PARDES_PANEL_MOVING), @intFromEnum(animation.Phase.moving)); - try expectEqual(@as(u8, c.PARDES_PANEL_CLOSING), @intFromEnum(animation.Phase.closing)); - try expectEqual(@as(u8, c.PARDES_PANEL_OFF), @intFromEnum(animation.Transition.off)); - try expectEqual(@as(u8, c.PARDES_PANEL_SLIDE), @intFromEnum(animation.Transition.slide)); - try expectEqual(@as(u8, c.PARDES_PANEL_ZOOM), @intFromEnum(animation.Transition.zoom)); - try expectEqual(@as(u8, c.PARDES_PANEL_DISSOLVE), @intFromEnum(animation.Transition.dissolve)); - try expectEqual(@as(u8, c.PARDES_PANEL_ASCII), @intFromEnum(animation.Transition.ascii)); - try expectEqual(@as(u8, c.PARDES_PANEL_VERTICAL), @intFromEnum(animation.Transition.vertical)); - try expectEqual(@as(u8, c.PARDES_PANEL_EDGES), @intFromEnum(animation.Transition.edges)); - try expectEqual(@as(u8, c.PARDES_PANEL_FALL), @intFromEnum(animation.Transition.fall)); - try expectEqual(@as(u8, c.PARDES_PANEL_WAVE), @intFromEnum(animation.Transition.wave)); - try expectEqual(@as(u8, c.PARDES_PANEL_CURTAIN), @intFromEnum(animation.Transition.curtain)); - try expectEqual(@as(u8, c.PARDES_PANEL_SCRAMBLE), @intFromEnum(animation.Transition.scramble)); - try expectEqual(@as(u8, c.PARDES_PANEL_TYPEWRITER), @intFromEnum(animation.Transition.typewriter)); + try expectEqual(@as(u8, c.PARDES_PANEL_OPENING), @backingInt(animation.Phase.opening)); + try expectEqual(@as(u8, c.PARDES_PANEL_MOVING), @backingInt(animation.Phase.moving)); + try expectEqual(@as(u8, c.PARDES_PANEL_CLOSING), @backingInt(animation.Phase.closing)); + try expectEqual(@as(u8, c.PARDES_PANEL_OFF), @backingInt(animation.Transition.off)); + try expectEqual(@as(u8, c.PARDES_PANEL_SLIDE), @backingInt(animation.Transition.slide)); + try expectEqual(@as(u8, c.PARDES_PANEL_ZOOM), @backingInt(animation.Transition.zoom)); + try expectEqual(@as(u8, c.PARDES_PANEL_DISSOLVE), @backingInt(animation.Transition.dissolve)); + try expectEqual(@as(u8, c.PARDES_PANEL_ASCII), @backingInt(animation.Transition.ascii)); + try expectEqual(@as(u8, c.PARDES_PANEL_VERTICAL), @backingInt(animation.Transition.vertical)); + try expectEqual(@as(u8, c.PARDES_PANEL_EDGES), @backingInt(animation.Transition.edges)); + try expectEqual(@as(u8, c.PARDES_PANEL_FALL), @backingInt(animation.Transition.fall)); + try expectEqual(@as(u8, c.PARDES_PANEL_WAVE), @backingInt(animation.Transition.wave)); + try expectEqual(@as(u8, c.PARDES_PANEL_CURTAIN), @backingInt(animation.Transition.curtain)); + try expectEqual(@as(u8, c.PARDES_PANEL_SCRAMBLE), @backingInt(animation.Transition.scramble)); + try expectEqual(@as(u8, c.PARDES_PANEL_TYPEWRITER), @backingInt(animation.Transition.typewriter)); try expectEqual(@as(u21, c.PARDES_KEY_ENTER), pardes.Key.enter); try expectEqual(@as(u21, c.PARDES_KEY_ESCAPE), pardes.Key.escape); @@ -2926,24 +2928,24 @@ test "pardes.h matches the Zig boundary" { try expectEqual(@as(u21, c.PARDES_KEY_PAGE_DOWN), pardes.Key.page_down); try expectEqual(@as(u21, c.PARDES_KEY_DELETE), pardes.Key.delete); - try expectEqual(c.PARDES_MOUSE_LEFT, @intFromEnum(pardes.Mouse.Button.left)); - try expectEqual(c.PARDES_MOUSE_MIDDLE, @intFromEnum(pardes.Mouse.Button.middle)); - try expectEqual(c.PARDES_MOUSE_RIGHT, @intFromEnum(pardes.Mouse.Button.right)); - try expectEqual(c.PARDES_MOUSE_WHEEL_UP, @intFromEnum(pardes.Mouse.Button.wheel_up)); - try expectEqual(c.PARDES_MOUSE_WHEEL_DOWN, @intFromEnum(pardes.Mouse.Button.wheel_down)); - try expectEqual(c.PARDES_MOUSE_WHEEL_LEFT, @intFromEnum(pardes.Mouse.Button.wheel_left)); - try expectEqual(c.PARDES_MOUSE_WHEEL_RIGHT, @intFromEnum(pardes.Mouse.Button.wheel_right)); - try expectEqual(c.PARDES_MOUSE_NONE, @intFromEnum(pardes.Mouse.Button.none)); - try expectEqual(c.PARDES_MOUSE_BACK, @intFromEnum(pardes.Mouse.Button.back)); - try expectEqual(c.PARDES_MOUSE_FORWARD, @intFromEnum(pardes.Mouse.Button.forward)); - try expectEqual(c.PARDES_MOUSE_PRESS, @intFromEnum(pardes.Mouse.Kind.press)); - try expectEqual(c.PARDES_MOUSE_RELEASE, @intFromEnum(pardes.Mouse.Kind.release)); - try expectEqual(c.PARDES_MOUSE_MOTION, @intFromEnum(pardes.Mouse.Kind.motion)); - try expectEqual(c.PARDES_MOUSE_DRAG, @intFromEnum(pardes.Mouse.Kind.drag)); - - try expectEqual(c.PARDES_HAPTIC_NONE, @intFromEnum(pardes.Haptic.none)); - try expectEqual(c.PARDES_HAPTIC_EXEC, @intFromEnum(pardes.Haptic.exec)); - try expectEqual(c.PARDES_HAPTIC_LOOK, @intFromEnum(pardes.Haptic.look)); + try expectEqual(c.PARDES_MOUSE_LEFT, @backingInt(pardes.Mouse.Button.left)); + try expectEqual(c.PARDES_MOUSE_MIDDLE, @backingInt(pardes.Mouse.Button.middle)); + try expectEqual(c.PARDES_MOUSE_RIGHT, @backingInt(pardes.Mouse.Button.right)); + try expectEqual(c.PARDES_MOUSE_WHEEL_UP, @backingInt(pardes.Mouse.Button.wheel_up)); + try expectEqual(c.PARDES_MOUSE_WHEEL_DOWN, @backingInt(pardes.Mouse.Button.wheel_down)); + try expectEqual(c.PARDES_MOUSE_WHEEL_LEFT, @backingInt(pardes.Mouse.Button.wheel_left)); + try expectEqual(c.PARDES_MOUSE_WHEEL_RIGHT, @backingInt(pardes.Mouse.Button.wheel_right)); + try expectEqual(c.PARDES_MOUSE_NONE, @backingInt(pardes.Mouse.Button.none)); + try expectEqual(c.PARDES_MOUSE_BACK, @backingInt(pardes.Mouse.Button.back)); + try expectEqual(c.PARDES_MOUSE_FORWARD, @backingInt(pardes.Mouse.Button.forward)); + try expectEqual(c.PARDES_MOUSE_PRESS, @backingInt(pardes.Mouse.Kind.press)); + try expectEqual(c.PARDES_MOUSE_RELEASE, @backingInt(pardes.Mouse.Kind.release)); + try expectEqual(c.PARDES_MOUSE_MOTION, @backingInt(pardes.Mouse.Kind.motion)); + try expectEqual(c.PARDES_MOUSE_DRAG, @backingInt(pardes.Mouse.Kind.drag)); + + try expectEqual(c.PARDES_HAPTIC_NONE, @backingInt(pardes.Haptic.none)); + try expectEqual(c.PARDES_HAPTIC_EXEC, @backingInt(pardes.Haptic.exec)); + try expectEqual(c.PARDES_HAPTIC_LOOK, @backingInt(pardes.Haptic.look)); try expectEqual(@as(u16, c.PARDES_ATTR_BOLD), encodeAttrs(.{ .bold = true })); try expectEqual(@as(u16, c.PARDES_ATTR_DIM), encodeAttrs(.{ .dim = true })); diff --git a/src/main.zig b/src/main.zig index e3bae75f..64614daa 100644 --- a/src/main.zig +++ b/src/main.zig @@ -499,7 +499,7 @@ fn nativeMain(init: std.process.Init) !void { if (!outside) { const owner = std.mem.span(std.c.getenv("PARDES_PID") orelse break :forwarding); const pid = std.fmt.parseInt(std.c.pid_t, owner, 10) catch break :forwarding; - if (pid <= 0 or std.c.kill(pid, @enumFromInt(0)) != 0) break :forwarding; + if (pid <= 0 or std.c.kill(pid, @fromBackingInt(@intCast(0))) != 0) break :forwarding; } // Can I reach it? That is the other two, and it is a separate answer. diff --git a/src/mini.zig b/src/mini.zig index 8af64201..ce291c99 100644 --- a/src/mini.zig +++ b/src/mini.zig @@ -130,7 +130,7 @@ pub fn generate(gpa: std.mem.Allocator, source: []const u8, styles: []const u8) if (source.len > max_input_bytes) return error.MiniTooLarge; if (!std.unicode.utf8ValidateSlice(source)) return error.InvalidUtf8; if (styles.len != 0 and styles.len != source.len) return error.InvalidMiniColors; - for (styles) |color| if (color > @intFromEnum(syntax.Syn.comment)) return error.InvalidMiniColors; + for (styles) |color| if (color > @backingInt(syntax.Syn.comment)) return error.InvalidMiniColors; const len = try render(null, source, styles); const content = try gpa.alloc(u8, len); errdefer gpa.free(content); @@ -248,17 +248,17 @@ test "Mini chooses highlighted dots over plain ink with stable color ties" { const gpa = std.testing.allocator; const source = "xx\nxx\nxx\nxx\n"; var styles: [source.len]u8 = @splat(0); - styles[0] = @intFromEnum(syntax.Syn.keyword); + styles[0] = @backingInt(syntax.Syn.keyword); const rare = try generate(gpa, source, &styles); defer rare.deinit(gpa); try std.testing.expectEqualStrings("⣿\n", rare.content); try std.testing.expectEqualSlices(u8, &.{ 1, 1, 1, 0 }, rare.colors); - styles[0] = @intFromEnum(syntax.Syn.string); - styles[1] = @intFromEnum(syntax.Syn.number); + styles[0] = @backingInt(syntax.Syn.string); + styles[1] = @backingInt(syntax.Syn.number); const tied = try generate(gpa, source, &styles); defer tied.deinit(gpa); try std.testing.expectEqualSlices(u8, &.{ 2, 2, 2, 0 }, tied.colors); - styles[3] = @intFromEnum(syntax.Syn.number); + styles[3] = @backingInt(syntax.Syn.number); const majority = try generate(gpa, source, &styles); defer majority.deinit(gpa); try std.testing.expectEqualSlices(u8, &.{ 3, 3, 3, 0 }, majority.colors); diff --git a/src/mouse.zig b/src/mouse.zig index 536a4fdb..43323f9a 100644 --- a/src/mouse.zig +++ b/src/mouse.zig @@ -379,7 +379,7 @@ fn programMouse(p: *Pardes, m: Mouse) bool { .none => null, else => return false, }; - const bit: u3 = if (button) |b| @as(u3, 1) << @intCast(@intFromEnum(b)) else 0; + const bit: u3 = if (button) |b| @as(u3, 1) << @intCast(@backingInt(b)) else 0; const at = p.presentation.pointer(p.screen_w, p.screen_h, @min(m.col, p.screen_w -| 1), @min(m.row, p.screen_h -| 1)); var mods: panes.terminal.MouseMods = .{ .shift = m.shift, .alt = m.alt, .ctrl = m.ctrl }; var buf: [64]u8 = undefined; @@ -701,7 +701,7 @@ pub fn handleMouse(p: *Pardes, event: Mouse) void { // look; the rest of the gesture is inert if (p.drag == .select and p.drag.select.button == config.look_button) { if (p.panes[p.drag.select.id]) |t| { - t.sel[@intFromEnum(config.look_button)].state = .none; + t.sel[@backingInt(config.look_button)].state = .none; if (comptime pdf_enabled) panes.Pdf.pointerCancel(t, p.drag.select.pdf); } @@ -812,7 +812,7 @@ pub fn handleMouse(p: *Pardes, event: Mouse) void { // an execute or look drag cancels it (textselect23's mask) if (p.drag == .select) { if (p.panes[p.drag.select.id]) |t| { - t.sel[@intFromEnum(p.drag.select.button)].state = .none; + t.sel[@backingInt(p.drag.select.button)].state = .none; if (comptime pdf_enabled) panes.Pdf.pointerCancel(t, p.drag.select.pdf); } @@ -833,8 +833,8 @@ pub fn handleMouse(p: *Pardes, event: Mouse) void { pane.scrollBy(if (m.button == config.look_button) local else -local); } else if (edit.pointerTextSelection(p, id, mcol, mrow, m.body_hit, p.pointer_tag_hit)) |pointed| { if (m.button == config.look_button) p.active = id; - pane.clearPointerSelection(@intFromEnum(m.button)); - pane.sel[@intFromEnum(m.button)] = pointed.sel; + pane.clearPointerSelection(@backingInt(m.button)); + pane.sel[@backingInt(m.button)] = pointed.sel; p.drag = .{ .select = .{ .id = id, @@ -906,7 +906,7 @@ pub fn dragUpdate(p: *Pardes, mcol: u16, mrow: u16, body_hit: ?Mouse.BodyHit) vo .select => |*s| { if (p.panes[s.id]) |pane| { const r = p.rects[s.id]; - const b = @intFromEnum(s.button); + const b = @backingInt(s.button); const tag_rows: i32 = pane.tag_rows; if (pane.body_rows > 0 and pane.sel[b].r0 >= tag_rows) if (body_hit) |supplied| { const mapped_hit = bodyHitForPane(p, s.id, supplied, true) orelse return; @@ -1235,10 +1235,10 @@ fn dragRelease(p: *Pardes, button: Mouse.Button) void { } if (s.chorded) { // a cut/paste chord consumed this drag; the release is inert - pane.sel[@intFromEnum(s.button)].state = .none; + pane.sel[@backingInt(s.button)].state = .none; return; } - const b = @intFromEnum(s.button); + const b = @backingInt(s.button); pane.sel[b].state = .done; if (s.button == config.select_button) { const sl = pane.sel[sel_slot]; @@ -1501,7 +1501,7 @@ test "plain left click clears explicit modal selection" { try std.testing.expectEqual(@as(i32, 3), pane.body.cur_col); try std.testing.expect(!pane.body.vsel.active); try std.testing.expect(!pane.body.msel.active); - try std.testing.expectEqual(.none, pane.sel[@intFromEnum(config.select_button)].state); + try std.testing.expectEqual(.none, pane.sel[@backingInt(config.select_button)].state); } test "selection drag and queued release do not enter panel pending state" { diff --git a/src/ninep/addr.zig b/src/ninep/addr.zig index 3feda5a2..86d2d49e 100644 --- a/src/ninep/addr.zig +++ b/src/ninep/addr.zig @@ -638,9 +638,9 @@ test "the address language, form by form" { } // Each failure says which it is. for ([_][2][]const u8{ - .{ "zzz", e_syntax }, .{ "/nomatch/", e_no_match }, .{ "99", e_range }, - .{ "#999", e_range }, .{ "/a[/", e_regexp }, .{ "/(a/", e_regexp }, - .{ "/*a/", e_regexp }, .{ "99:1", e_range }, .{ "2:0", e_col_zero }, + .{ "zzz", e_syntax }, .{ "/nomatch/", e_no_match }, .{ "99", e_range }, + .{ "#999", e_range }, .{ "/a[/", e_regexp }, .{ "/(a/", e_regexp }, + .{ "/*a/", e_regexp }, .{ "99:1", e_range }, .{ "2:0", e_col_zero }, }) |c| { _ = th.wr(p, addr, "#0"); try testing.expectEqualStrings(c[1], th.wr(p, addr, c[0]).reply.ename); diff --git a/src/ninep/cols.zig b/src/ninep/cols.zig index 59f6ae42..6f5bee23 100644 --- a/src/ninep/cols.zig +++ b/src/ninep/cols.zig @@ -34,7 +34,7 @@ pub fn writeLayout(p: *Pardes, w: *std.Io.Writer) !void { const active = activeColumn(p); for (0..p.ncol) |c| { try w.print("{d} {d} {d} {d} {s} {s}", .{ - layout.columnSerial(p, c), c, p.col_x[c], p.col_w[c], + layout.columnSerial(p, c), c, p.col_x[c], p.col_w[c], if (active == c) "current" else "notcurrent", if (p.col_n[c] == 0) "empty" else "full", }); for (p.col_panes[c][0..p.col_n[c]]) |id| if (p.panes[id]) |pane| try w.print(" {d}", .{pane.serial}); @@ -229,8 +229,8 @@ test "Joincol is refused when the joined column cannot give each pane its tag an const p = try pardes.Pardes.init(testing.allocator, .{ .tty_only = true, .cols = 160, .rows = 12 }); defer p.deinit(); while (p.nextEffect()) |_| {} - const ctl = @intFromEnum(tree.TopFile.ctl); - const focus = @intFromEnum(tree.TopFile.focus); + const ctl = @backingInt(tree.TopFile.ctl); + const focus = @backingInt(tree.TopFile.focus); // Two panes in the first column, then a second column of two. const a = try th.newPane(p); _ = a; @@ -257,10 +257,10 @@ test "pane/new takes rows from a pane in another column before refusing ENOSPC" while (p.nextEffect()) |_| {} const first = p.panes[p.active].?.serial; // A second column holding one tall pane. - try testing.expectEqual(tree.Status.ok, th.wr(p, @intFromEnum(tree.TopFile.ctl), "Newcol\n").reply.status); + try testing.expectEqual(tree.Status.ok, th.wr(p, @backingInt(tree.TopFile.ctl), "Newcol\n").reply.status); const tall = try th.newPane(p); const tall_col = layout.findPane(p, p.paneBySerial(tall).?).?.col; - const focus = @intFromEnum(tree.TopFile.focus); + const focus = @backingInt(tree.TopFile.focus); var digits: [16]u8 = undefined; // From the first column, until pane/new is refused. var moved = false; @@ -289,7 +289,7 @@ test "exactly 4096 bytes written with echo's newline after a truncation fit ever defer p.deinit(); const serial = th.serialOf(p); const text = &@as([4096]u8, @splat('w')) ++ "\n"; - for ([_]u64{ tree.Node.of(serial, .tag), tree.Node.ofCol(layout.columnSerial(p, 0), .tag), @intFromEnum(tree.TopFile.tag) }) |node| { + for ([_]u64{ tree.Node.of(serial, .tag), tree.Node.ofCol(layout.columnSerial(p, 0), .tag), @backingInt(tree.TopFile.tag) }) |node| { _ = th.call(p, .{ .tag = 1, .op = .setattr, .node = node, .truncate = true }); const h = th.call(p, .{ .tag = 2, .op = .open, .node = node, .omode = 1 }).reply.handle; const r = th.call(p, .{ .tag = 3, .op = .write, .node = node, .handle = h, .data = text }); @@ -320,8 +320,8 @@ test "a Newcol refused because the tags would not fit logs its err alone and spe } try testing.expect(p.col_n[col] >= 2); p.sync(); - const ctl = @intFromEnum(tree.TopFile.ctl); - const focus = @intFromEnum(tree.TopFile.focus); + const ctl = @backingInt(tree.TopFile.ctl); + const focus = @backingInt(tree.TopFile.focus); var digits: [16]u8 = undefined; const own = try std.fmt.bufPrint(&digits, "{d}\n", .{pane.serial}); var refused = false; @@ -349,7 +349,7 @@ test "a Newcol refused because the tags would not fit logs its err alone and spe test "a tagexec word that makes, acts on and focuses no pane reads back nothing" { const p = try th.withFile(testing.allocator, "x\n"); defer p.deinit(); - const tagexec = @intFromEnum(tree.TopFile.tagexec); + const tagexec = @backingInt(tree.TopFile.tagexec); try testing.expectEqual(tree.Status.ok, th.wr(p, tagexec, "Newcol\n").reply.status); try testing.expectEqualStrings("", th.rd(p, tagexec, 0, 64).bytes); // A column's New makes one, and answers it. @@ -362,7 +362,7 @@ test "a tagexec word that makes, acts on and focuses no pane reads back nothing" test "New written to a column's ctl reads back the new pane alone, as its exec does" { const p = try th.withFile(testing.allocator, "x\n"); defer p.deinit(); - const root_exec = @intFromEnum(tree.TopFile.exec); + const root_exec = @backingInt(tree.TopFile.exec); _ = th.wr(p, root_exec, "Msg before\n"); const ctl_node = tree.Node.ofCol(layout.columnSerial(p, 0), .ctl); try testing.expectEqual(tree.Status.ok, th.wr(p, ctl_node, "New\n").reply.status); @@ -390,7 +390,7 @@ test "a pane's word written to /tagexec or a column's exec is refused, and acts const p = try th.withFile(testing.allocator, "x\n"); defer p.deinit(); const col_exec = tree.Node.ofCol(layout.columnSerial(p, 0), .exec); - for ([_]u64{ @intFromEnum(tree.TopFile.tagexec), col_exec }) |node| { + for ([_]u64{ @backingInt(tree.TopFile.tagexec), col_exec }) |node| { for ([_][]const u8{ "Undo\n", "Msg hi\n", "Redo\n" }) |line| { const refused = th.wr(p, node, line); try testing.expectEqual(E.INVAL, refused.errno()); @@ -411,7 +411,7 @@ test "Help and Find at /tagexec act in the session's directory, not the keyboard const session = buf[0..try tmp.dir.realPath(testing.io, &buf)]; @memcpy(p.session_dir[0..session.len], session); p.session_dir_len = @intCast(session.len); - const tagexec = @intFromEnum(tree.TopFile.tagexec); + const tagexec = @backingInt(tree.TopFile.tagexec); for ([_][]const u8{ "Help\n", "Find needle\n" }) |line| { try testing.expectEqual(tree.Status.ok, th.wr(p, tagexec, line).reply.status); const made = p.panes[p.active].?.file.?.path; @@ -427,7 +427,7 @@ test "a shell command at /tagexec or a column's exec is a command pane in the se const term = p.panes[p.active].?; try testing.expect(pardes.exec.takesCommandLine(p, p.active)); const col_exec = tree.Node.ofCol(layout.columnSerial(p, 0), .exec); - for ([_]u64{ @intFromEnum(tree.TopFile.tagexec), col_exec }) |node| { + for ([_]u64{ @backingInt(tree.TopFile.tagexec), col_exec }) |node| { p.active = p.paneBySerial(term.serial).?; const before = p.next_serial; const r = th.wr(p, node, "echo from-the-tag\n"); @@ -443,7 +443,7 @@ test "a shell command at /tagexec or a column's exec is a command pane in the se test "New and Tty run at /tagexec and a column's exec, with no pane at all too" { const p = try th.withFile(testing.allocator, "x\n"); defer p.deinit(); - const tagexec = @intFromEnum(tree.TopFile.tagexec); + const tagexec = @backingInt(tree.TopFile.tagexec); const col_exec = tree.Node.ofCol(layout.columnSerial(p, 0), .exec); for ([_]u64{ tagexec, col_exec }) |node| for ([_][]const u8{ "New\n", "Tty\n" }) |line| { const before = p.next_serial; @@ -469,7 +469,7 @@ test "every pane word a tag no pane owns does not hold is refused there, Edit in const Builtin = pardes.builtins.registry.Builtin(); const col_exec = tree.Node.ofCol(layout.columnSerial(p, 0), .exec); for ([_]struct { node: u64, own: []const u8 }{ - .{ .node = @intFromEnum(tree.TopFile.tagexec), .own = pardes.config.topbar_str }, + .{ .node = @backingInt(tree.TopFile.tagexec), .own = pardes.config.topbar_str }, .{ .node = col_exec, .own = tagline.column_tag_default }, }) |tag_file| { var checked: usize = 0; @@ -517,7 +517,7 @@ test "layout lists each column's place, panes and state, and the active one" { const first_serial = layout.columnSerial(p, 0); const new_serial = layout.columnSerial(p, 1); try testing.expect(first_serial != new_serial); - const layout_node = @intFromEnum(tree.TopFile.layout); + const layout_node = @backingInt(tree.TopFile.layout); const text = th.rd(p, layout_node, 0, 4096).bytes; var want: [256]u8 = undefined; const first = try std.fmt.bufPrint(&want, "{d} 0 {d} {d} notcurrent full {d}\n", .{ first_serial, p.col_x[0], p.col_w[0], p.panes[0].?.serial }); @@ -528,19 +528,19 @@ test "layout lists each column's place, panes and state, and the active one" { try testing.expect(text.len > 0); try testing.expectEqual(@as(u64, 0), th.call(p, .{ .tag = 1, .op = .getattr, .node = layout_node }).reply.attr.size); // generated by each read // /index says which column each pane is in, by its serial, last. - try testing.expect(std.mem.endsWith(u8, th.rd(p, @intFromEnum(tree.TopFile.index), 0, 4096).bytes, try std.fmt.bufPrint(&want, " {d}\n", .{first_serial}))); + try testing.expect(std.mem.endsWith(u8, th.rd(p, @backingInt(tree.TopFile.index), 0, 4096).bytes, try std.fmt.bufPrint(&want, " {d}\n", .{first_serial}))); try testing.expect(th.logHas(p, try std.fmt.bufPrint(&want, "newcol {d}\n", .{new_serial}))); // A column that closes takes its name with it; the others keep theirs. try p.removeColumn(1); try testing.expect(th.logHas(p, try std.fmt.bufPrint(&want, "delcol {d}\n", .{new_serial}))); - try testing.expectEqual(E.NOENT, th.look_up(p, @intFromEnum(tree.TopFile.col), try std.fmt.bufPrint(&want, "{d}", .{new_serial})).errno()); + try testing.expectEqual(E.NOENT, th.look_up(p, @backingInt(tree.TopFile.col), try std.fmt.bufPrint(&want, "{d}", .{new_serial})).errno()); try testing.expectEqual(first_serial, layout.columnSerial(p, 0)); } test "a column's tag and the workspace's read, replace and append as a pane tag does, on one line" { const p = try th.withFile(testing.allocator, "x\n"); defer p.deinit(); - const col_dir = @intFromEnum(tree.TopFile.col); + const col_dir = @backingInt(tree.TopFile.col); const serial = layout.columnSerial(p, 0); var name: [16]u8 = undefined; try testing.expectEqual(tree.Status.ok, th.look_up(p, col_dir, try std.fmt.bufPrint(&name, "{d}", .{serial})).reply.status); @@ -557,7 +557,7 @@ test "a column's tag and the workspace's read, replace and append as a pane tag // `>>` appends; a newline in a one-line tag is a space. _ = th.wr(p, tag, " Lint\nNow"); try testing.expectEqualStrings("Make Lint Now", th.rd(p, tag, 0, 4096).bytes); - const top = @intFromEnum(tree.TopFile.tag); + const top = @backingInt(tree.TopFile.tag); _ = th.call(p, .{ .tag = 3, .op = .setattr, .node = top, .truncate = true }); _ = th.wr(p, top, "Newcol Exit\n"); try testing.expectEqualStrings("Newcol Exit", tagline.topbar(p)); @@ -574,11 +574,11 @@ test "a focus write makes its pane's column the active one: layout says so and p p.sync(); try testing.expectEqual(@as(usize, 1), layout.findPane(p, p.active).?.col); var digits: [16]u8 = undefined; - _ = th.wr(p, @intFromEnum(tree.TopFile.focus), try std.fmt.bufPrint(&digits, "{d}\n", .{left})); + _ = th.wr(p, @backingInt(tree.TopFile.focus), try std.fmt.bufPrint(&digits, "{d}\n", .{left})); var want: [32]u8 = undefined; - const text = th.rd(p, @intFromEnum(tree.TopFile.layout), 0, 4096).bytes; + const text = th.rd(p, @backingInt(tree.TopFile.layout), 0, 4096).bytes; try testing.expect(std.mem.endsWith(u8, text, try std.fmt.bufPrint(&want, "active {d}\n", .{layout.columnSerial(p, 0)}))); - const made = th.call(p, .{ .tag = 1, .op = .open, .node = @intFromEnum(tree.TopFile.new) }).reply.handle; + const made = th.call(p, .{ .tag = 1, .op = .open, .node = @backingInt(tree.TopFile.new) }).reply.handle; try testing.expectEqual(@as(usize, 0), layout.findPane(p, p.paneBySerial(made).?).?.col); } } @@ -590,7 +590,7 @@ test "a refused write after a truncation leaves every kind of tag as it was, and const col = layout.columnSerial(p, 0); const big = &@as([limits.max_tag_tail + 1]u8, @splat('w')); // Each tag: a truncating open, then a write too long: nothing changes. - for ([_]u64{ Node.of(serial, .tag), Node.ofCol(col, .tag), @intFromEnum(tree.TopFile.tag) }) |node| { + for ([_]u64{ Node.of(serial, .tag), Node.ofCol(col, .tag), @backingInt(tree.TopFile.tag) }) |node| { _ = th.wr(p, node, " Mine"); const before = try testing.allocator.dupe(u8, th.rd(p, node, 0, 1 << 16).bytes); defer testing.allocator.free(before); @@ -651,13 +651,13 @@ test "a column's ctl and exec act on it as its tag would, and rmdir closes it on try testing.expectEqual(@as(?usize, 0), layout.columnBySerial(p, right)); try testing.expect(std.mem.endsWith(u8, headerText(p, right).?, " Mine")); // The root's ctl points a column word at the column's own. - try testing.expect(std.mem.endsWith(u8, th.wr(p, @intFromEnum(tree.TopFile.ctl), "Delcol\n").reply.ename, "write it to col//ctl")); + try testing.expect(std.mem.endsWith(u8, th.wr(p, @backingInt(tree.TopFile.ctl), "Delcol\n").reply.ename, "write it to col//ctl")); } test "tagexec runs a word as a click in the workspace tag; exec files read back what they touched; their messages are the session's" { const p = try th.withFile(testing.allocator, "x\n"); defer p.deinit(); - const tagexec = @intFromEnum(tree.TopFile.tagexec); + const tagexec = @backingInt(tree.TopFile.tagexec); try testing.expectEqual(tree.Status.ok, th.look_up(p, tree.root, "tagexec").reply.status); try testing.expectEqual(tree.Status.ok, th.wr(p, tagexec, "Newcol\n").reply.status); try testing.expectEqual(@as(usize, 2), p.ncol); @@ -680,7 +680,7 @@ test "a word run from the workspace's or a column's tag runs in the session's di defer p.deinit(); const session = p.sessionDir(); try testing.expect(!std.mem.eql(u8, session, pardes.Pardes.paneDir(p.panes[0].?))); // the file is elsewhere - const dirs = [_]u64{ @intFromEnum(tree.TopFile.tagexec), Node.ofCol(layout.columnSerial(p, 0), .exec) }; + const dirs = [_]u64{ @backingInt(tree.TopFile.tagexec), Node.ofCol(layout.columnSerial(p, 0), .exec) }; for (dirs) |node| { try testing.expectEqual(tree.Status.ok, th.wr(p, node, "true\n").reply.status); const made = p.paneBySerial(p.fs.results[0]).?; diff --git a/src/ninep/ctl.zig b/src/ninep/ctl.zig index 6b4bbafb..3e7c367b 100644 --- a/src/ninep/ctl.zig +++ b/src/ninep/ctl.zig @@ -1277,15 +1277,15 @@ const withFile = th.withFile; const serialOf = th.serialOf; const Node = tree.Node; const Status = tree.Status; -const root_status = @intFromEnum(tree.TopFile.status); -const root_look = @intFromEnum(tree.TopFile.look); -const root_exec = @intFromEnum(tree.TopFile.exec); +const root_status = @backingInt(tree.TopFile.status); +const root_look = @backingInt(tree.TopFile.look); +const root_exec = @backingInt(tree.TopFile.exec); test "a control character in a write to any ctl refuses the whole write, and a quoted line shows a tab as a blank" { const p = try withFile(testing.allocator, "x\n"); defer p.deinit(); const col = layout.columnSerial(p, 0); - for ([_]u64{ @intFromEnum(tree.TopFile.ctl), Node.of(serialOf(p), .ctl), Node.ofCol(col, .ctl) }) |node| { + for ([_]u64{ @backingInt(tree.TopFile.ctl), Node.of(serialOf(p), .ctl), Node.ofCol(col, .ctl) }) |node| { const r = wr(p, node, "Wrap off\nbo\x01gus\n"); try testing.expectEqual(E.INVAL, r.errno()); try testing.expectEqualStrings(e_control, r.reply.ename); @@ -1325,7 +1325,7 @@ test "pane ctl read is acme's fields -- index's five, width in cells, font, tab test "commands lists every builtin with its argument and the ctl that takes it" { const p = try withFile(testing.allocator, "x\n"); defer p.deinit(); - const node = @intFromEnum(tree.TopFile.commands); + const node = @backingInt(tree.TopFile.commands); const listed = rd(p, node, 0, 1 << 16); try testing.expectEqual(@as(u64, listed.bytes.len), call(p, .{ .tag = 1, .op = .getattr, .node = node }).reply.attr.size); try testing.expectEqual(E.PERM, wr(p, node, "Del\n").errno()); @@ -1372,7 +1372,7 @@ test "focus reads the pane with the keyboard, and a serial written to it moves t defer p.deinit(); const first = serialOf(p); const second = try th.newPane(p); - const focus = @intFromEnum(tree.TopFile.focus); + const focus = @backingInt(tree.TopFile.focus); var line: [16]u8 = undefined; try testing.expectEqualStrings(try std.fmt.bufPrint(&line, "{d}\n", .{second}), rd(p, focus, 0, 64).bytes); try testing.expectEqual(@as(u64, rd(p, focus, 0, 64).bytes.len), call(p, .{ .tag = 1, .op = .getattr, .node = focus }).reply.attr.size); @@ -1447,7 +1447,7 @@ test "the root ctl reads the settings as a write takes them, and takes the sessi const gpa = testing.allocator; const p = try withFile(gpa, "x\n"); defer p.deinit(); - const root_ctl = @intFromEnum(tree.TopFile.ctl); + const root_ctl = @backingInt(tree.TopFile.ctl); const first = rd(p, root_ctl, 0, 1 << 16); try testing.expectEqual(Status.ok, first.reply.status); const settings = try gpa.dupe(u8, first.bytes); @@ -1575,7 +1575,7 @@ test "a write of an Edit block carries it whole, to a pane's ctl, the root's ctl try testing.expectEqual(Status.ok, wr(p, Node.of(serial, .ctl), "Edit ,x/foo/{\ni/[/\na/]/\n}\n").reply.status); try testing.expectEqualStrings("[foo] x\n[foo] y\n", rd(p, body, 0, 64).bytes); p.active = p.paneBySerial(serial).?; - try testing.expectEqual(Status.ok, wr(p, @intFromEnum(tree.TopFile.ctl), "Edit ,x/\\[/{\nc/ 0); - try testing.expectEqual(@as(u64, 0), call(p, .{ .tag = 1, .op = .getattr, .node = @intFromEnum(tree.TopFile.index) }).reply.attr.size); + try testing.expectEqual(@as(u64, 0), call(p, .{ .tag = 1, .op = .getattr, .node = @backingInt(tree.TopFile.index) }).reply.attr.size); // Its tag never carries the raw newline either. const tag = rd(p, Node.of(serialOf(p), .tag), 0, 4096).bytes; try testing.expect(std.mem.indexOf(u8, tag, "/tmp/two\\nlines") != null); // A backslash of the name's own is doubled: `\n` written in a name // reads back unlike a newline. p.setCwd(term, "/tmp/back\\nslash"); - try testing.expect(std.mem.indexOf(u8, rd(p, @intFromEnum(tree.TopFile.index), 0, 4096).bytes, "/tmp/back\\\\nslash") != null); + try testing.expect(std.mem.indexOf(u8, rd(p, @backingInt(tree.TopFile.index), 0, 4096).bytes, "/tmp/back\\\\nslash") != null); } test "a look at a ./ or ../ name that is not there is a miss naming the file; a plain one is looked for as text" { @@ -3766,7 +3766,7 @@ test "a served-tree pane spoils no Grep, and Look . from a gone directory is ENO test "a tag write refuses NUL and the other control characters" { const p = try withFile(testing.allocator, "x\n"); defer p.deinit(); - for ([_]u64{ @intFromEnum(tree.TopFile.tag), tree.Node.ofCol(pardes.layout.columnSerial(p, 0), .tag), Node.of(serialOf(p), .tag) }) |node| { + for ([_]u64{ @backingInt(tree.TopFile.tag), tree.Node.ofCol(pardes.layout.columnSerial(p, 0), .tag), Node.of(serialOf(p), .tag) }) |node| { const refused = wr(p, node, " a\x00b"); try testing.expectEqual(E.INVAL, refused.errno()); try testing.expectStringStartsWith(refused.reply.ename, "invalid tag text"); @@ -3815,7 +3815,7 @@ test "a column takes panes until their documented minimums fill it, not until no const p = try Pardes.init(testing.allocator, .{ .tty_only = true, .cols = 160, .rows = 50 }); defer p.deinit(); while (p.nextEffect()) |_| {} - const new = @intFromEnum(tree.TopFile.new); + const new = @backingInt(tree.TopFile.new); while (call(p, .{ .tag = 1, .op = .open, .node = new }).reply.status == .ok) p.sync(); p.sync(); const avail = p.screen_h - (p.topBarHeight() + p.columnBarHeight()); @@ -3913,13 +3913,13 @@ test "a closed file is found again: Recent and /recent list it closed, a look at const opened = p.active; try testing.expectEqualStrings(a, p.panes[opened].?.file.?.path); var want: [4300]u8 = undefined; - try testing.expect(std.mem.indexOf(u8, rd(p, @intFromEnum(tree.TopFile.recent), 0, 8192).bytes, try std.fmt.bufPrint(&want, "open {s}\n", .{a})) != null); + try testing.expect(std.mem.indexOf(u8, rd(p, @backingInt(tree.TopFile.recent), 0, 8192).bytes, try std.fmt.bufPrint(&want, "open {s}\n", .{a})) != null); // Another file, so the jumplist has somewhere to come back from. try testing.expectEqual(Status.ok, wr(p, root_look, try std.fmt.bufPrint(&line, "{s}/b.txt\n", .{dir})).reply.status); p.sync(); try testing.expectEqual(Status.ok, wr(p, Node.of(p.panes[opened].?.serial, .ctl), "Del\n").reply.status); p.sync(); - try testing.expect(std.mem.indexOf(u8, rd(p, @intFromEnum(tree.TopFile.recent), 0, 8192).bytes, try std.fmt.bufPrint(&want, "closed {s}\n", .{a})) != null); + try testing.expect(std.mem.indexOf(u8, rd(p, @backingInt(tree.TopFile.recent), 0, 8192).bytes, try std.fmt.bufPrint(&want, "closed {s}\n", .{a})) != null); // Recent lists it, closed, at its dot; a look at the row opens it there. try testing.expectEqual(Status.ok, wr(p, root_exec, "Recent\n").reply.status); const rows = p.panes[p.paneBySerial(try std.fmt.parseInt(u32, std.mem.trimEnd(u8, rd(p, root_exec, 0, 64).bytes, "\n"), 10)).?].?; @@ -4045,8 +4045,8 @@ test "Back and Forward written to exec keep to the focused file, and JumpScope a .{ .word = "Forward", .file = "/b.txt", .line = 80 }, .{ .word = "Forward", .file = "/a.txt", .line = 80 }, }); - try testing.expectEqual(Status.ok, wr(p, @intFromEnum(tree.TopFile.ctl), "JumpScope all\n").reply.status); - try testing.expect(std.mem.indexOf(u8, rd(p, @intFromEnum(tree.TopFile.ctl), 0, 8192).bytes, "JumpScope all\n") != null); + try testing.expectEqual(Status.ok, wr(p, @backingInt(tree.TopFile.ctl), "JumpScope all\n").reply.status); + try testing.expect(std.mem.indexOf(u8, rd(p, @backingInt(tree.TopFile.ctl), 0, 8192).bytes, "JumpScope all\n") != null); try walk(p, &.{ .{ .word = "Back", .file = "/b.txt", .line = 80 }, .{ .word = "Back", .file = "/a.txt", .line = 40 }, @@ -4102,14 +4102,14 @@ test "a new file saved shows in /recent, open, while it is" { try testing.expectEqual(Status.ok, wr(p, Node.of(made, .ctl), "Save\n").reply.status); p.perform(.{ .save_file = .{ .pane = @intCast(p.paneBySerial(made).?) } }); var want: [4300]u8 = undefined; - try testing.expect(std.mem.indexOf(u8, rd(p, @intFromEnum(tree.TopFile.recent), 0, 8192).bytes, try std.fmt.bufPrint(&want, "open {s}\n", .{path})) != null); + try testing.expect(std.mem.indexOf(u8, rd(p, @backingInt(tree.TopFile.recent), 0, 8192).bytes, try std.fmt.bufPrint(&want, "open {s}\n", .{path})) != null); } test "/recent shows a name as /index does, a newline in it escaped" { const p = try withFile(testing.allocator, "x\n"); defer p.deinit(); p.recent.opened(p.recentGpa(), "/tmp/a\nb\\c"); - const text = rd(p, @intFromEnum(tree.TopFile.recent), 0, 8192).bytes; + const text = rd(p, @backingInt(tree.TopFile.recent), 0, 8192).bytes; try testing.expect(std.mem.indexOf(u8, text, "closed /tmp/a\\nb\\\\c\n") != null); } @@ -4191,8 +4191,8 @@ test "size is monotonic: growing is never refused, and a size once taken is take defer p.deinit(); while (p.nextEffect()) |_| {} p.unattended = true; - const root_ctl = @intFromEnum(tree.TopFile.ctl); - const new = @intFromEnum(tree.TopFile.new); + const root_ctl = @backingInt(tree.TopFile.ctl); + const new = @backingInt(tree.TopFile.new); // The dogfood's repro: Newcol, three pane/new, a Tty, then pane/new // until a column has no room (ENOSPC). try testing.expectEqual(Status.ok, wr(p, root_ctl, "Newcol\n").reply.status); @@ -4283,7 +4283,7 @@ test "a file changed on disk under unsaved edits is not reloaded: it says so, ge var want: [32]u8 = undefined; try testing.expect(th.logHas(p, try std.fmt.bufPrint(&want, "changed {d}\n", .{serial}))); // Exit and get still ask about the edits. - try testing.expectEqual(Status.err, wr(p, @intFromEnum(tree.TopFile.ctl), "Exit\n").reply.status); + try testing.expectEqual(Status.err, wr(p, @backingInt(tree.TopFile.ctl), "Exit\n").reply.status); try testing.expect(std.mem.indexOf(u8, wr(p, Node.of(serial, .ctl), "get\n").reply.ename, "Modified") != null); // Save warns once before overwriting the newer file, then writes. const first = wr(p, Node.of(serial, .ctl), "Save\n"); @@ -4328,7 +4328,7 @@ test "a looked word is found in its own pane, next place after the dot, wrapping test "every word's /commands description is its own doc comment's first sentence, no citation" { const p = try withFile(testing.allocator, "x\n"); defer p.deinit(); - const listed = rd(p, @intFromEnum(tree.TopFile.commands), 0, 1 << 16).bytes; + const listed = rd(p, @backingInt(tree.TopFile.commands), 0, 1 << 16).bytes; for ([_][]const u8{ "\nRepl arg pane -- Binds this terminal as a language's REPL, so an exec on that language's files is typed into it instead of run.\n", "\nJoincol root -- Fold the active pane's column into the one on its right, keeping its panes.\n", @@ -4374,7 +4374,7 @@ test "Newcol at the column cap fails the write and says the cap" { const p = try withFile(testing.allocator, "x\n"); defer p.deinit(); p.update(.{ .resize = .{ .cols = 4000, .rows = 30 } }); - const root_ctl = @intFromEnum(tree.TopFile.ctl); + const root_ctl = @backingInt(tree.TopFile.ctl); while (p.ncol < pardes.MAX_COLS) { // From the widest column's tag, so no column gets too narrow first. p.sync(); @@ -4403,7 +4403,7 @@ test "Save on a terminal asked over 9P is an ask in the log, answered with a pat try testing.expect(p.panes[id].?.prompt == .save); // Again: the one open stands, one ask in the log. _ = wr(p, Node.of(serial, .tagexec), "Save\n"); - const log = @intFromEnum(tree.TopFile.log); + const log = @backingInt(tree.TopFile.log); const h = call(p, .{ .tag = 1, .op = .open, .node = log }).reply.handle; try testing.expectEqual(@as(usize, 1), std.mem.count(u8, call(p, .{ .tag = 2, .op = .read, .node = log, .handle = h, .size = 1 << 16 }).bytes, "save path\n")); _ = call(p, .{ .tag = 3, .op = .release, .node = log, .handle = h }); @@ -4429,7 +4429,7 @@ test "get names the path it could not read, logs the edits it threw away, and a pardes.panes.File.deleted(p, 0); pardes.panes.File.deleted(p, 0); var rec: [32]u8 = undefined; - const log = @intFromEnum(tree.TopFile.log); + const log = @backingInt(tree.TopFile.log); const h = call(p, .{ .tag = 1, .op = .open, .node = log }).reply.handle; try testing.expectEqual(@as(usize, 1), std.mem.count(u8, call(p, .{ .tag = 2, .op = .read, .node = log, .handle = h, .size = 1 << 16 }).bytes, try std.fmt.bufPrint(&rec, "changed {d} deleted\n", .{serial}))); _ = call(p, .{ .tag = 3, .op = .release, .node = log, .handle = h }); @@ -4441,12 +4441,12 @@ test "a builtin that fails through exec, tagexec or a column's exec fails the wr p.update(.tick); // the pane's `new` is logged first while (p.nextEffect()) |_| {} const serial = serialOf(p); - for ([_]u64{ root_exec, Node.of(serial, .exec), @intFromEnum(tree.TopFile.tagexec), Node.ofCol(pardes.layout.columnSerial(p, 0), .exec) }) |node| { + for ([_]u64{ root_exec, Node.of(serial, .exec), @backingInt(tree.TopFile.tagexec), Node.ofCol(pardes.layout.columnSerial(p, 0), .exec) }) |node| { const failed = wr(p, node, "Unmount zzz\n"); try testing.expectEqual(Status.err, failed.reply.status); try testing.expect(std.mem.indexOf(u8, failed.reply.ename, "Unmount: no such mount zzz") != null); } - const log = @intFromEnum(tree.TopFile.log); + const log = @backingInt(tree.TopFile.log); const h = call(p, .{ .tag = 1, .op = .open, .node = log }).reply.handle; const text = call(p, .{ .tag = 2, .op = .read, .node = log, .handle = h, .size = 1 << 16 }).bytes; try testing.expect(std.mem.indexOf(u8, text, "msg ") == null); @@ -4458,11 +4458,11 @@ test "a builtin that fails through exec, tagexec or a column's exec fails the wr // A control character is refused with its reason. try testing.expectEqualStrings(e_control, wr(p, root_exec, "Msg a\x01b\n").reply.ename); // A look miss: one err, no msg. - _ = wr(p, @intFromEnum(tree.TopFile.look), "zzqqnotthere\n"); + _ = wr(p, @backingInt(tree.TopFile.look), "zzqqnotthere\n"); try testing.expect(th.logHas(p, "look: no match for \"zzqqnotthere\"")); try testing.expect(!th.logHas(p, "msg 1 Look: no match")); // The same miss again is that record counted, as any repeated err is. - _ = wr(p, @intFromEnum(tree.TopFile.look), "zzqqnotthere\n"); + _ = wr(p, @backingInt(tree.TopFile.look), "zzqqnotthere\n"); try testing.expect(th.logHas(p, "look: no match for \"zzqqnotthere\" (x2)\n")); } @@ -4483,7 +4483,7 @@ test "@p:
takes any sam address; a miss and an unknown serial a const p = try withFile(testing.allocator, "foo x foo y\nbar\n"); defer p.deinit(); const serial = serialOf(p); - const root = @intFromEnum(tree.TopFile.look); + const root = @backingInt(tree.TopFile.look); const dot = Node.of(serial, .dot); const Case = struct { addr: []const u8, want: []const u8 }; for ([_]Case{ @@ -4544,7 +4544,7 @@ test "@p:
takes any address over the terminal's lines, select const id = p.paneBySerial(serial).?; p.update(.{ .output = .{ .pane = @intCast(id), .bytes = "one\r\ntwo MARK three\r\n" } }); const pane = p.panes[id].?; - const root = @intFromEnum(tree.TopFile.look); + const root = @backingInt(tree.TopFile.look); var line: [64]u8 = undefined; try testing.expectEqual(Status.ok, wr(p, root, try std.fmt.bufPrint(&line, "@p{d}:0/MARK/\n", .{serial})).reply.status); try testing.expectEqual(@as(i32, 1), pane.body.cur_row); @@ -4576,7 +4576,7 @@ test "a bad command inside an Edit block written whole is named, not the } after test "a refused Delcol changes nothing: no pane, no focus" { const p = try withFile(testing.allocator, "x\n"); defer p.deinit(); - _ = wr(p, @intFromEnum(tree.TopFile.ctl), "Newcol\n"); + _ = wr(p, @backingInt(tree.TopFile.ctl), "Newcol\n"); const made = try th.newPane(p); _ = wr(p, Node.of(made, .name), "/tmp/pardes-delcol-refused.txt\n"); _ = wr(p, Node.of(made, .body), "edit\n"); @@ -4599,8 +4599,8 @@ test "a refused Delcol changes nothing: no pane, no focus" { test "pager answers its +Pager on the open that asked, whatever another client exec'd meanwhile" { const p = try withFile(testing.allocator, "x\n"); defer p.deinit(); - const pager = @intFromEnum(tree.TopFile.pager); - const exec = @intFromEnum(tree.TopFile.exec); + const pager = @backingInt(tree.TopFile.pager); + const exec = @backingInt(tree.TopFile.exec); const asked = call(p, .{ .tag = 1, .op = .open, .node = pager, .omode = 2 }).reply.handle; try testing.expectEqual(Status.ok, call(p, .{ .tag = 2, .op = .write, .node = pager, .handle = asked, .data = "/tmp\n" }).reply.status); const paged = for (p.panes) |slot| { @@ -4653,7 +4653,7 @@ test "pager answers its +Pager on the open that asked, whatever another client e test "what a /pager open writes after its directory is the text: plain in the body, its colours the pane's, clean, in by the read" { const p = try withFile(testing.allocator, "x\n"); defer p.deinit(); - const pager = @intFromEnum(tree.TopFile.pager); + const pager = @backingInt(tree.TopFile.pager); const asked = call(p, .{ .tag = 1, .op = .open, .node = pager, .omode = 2 }).reply.handle; // The directory and the text's start in one write, escapes and all, a // second line no directory; the rest in writes after it. @@ -4812,7 +4812,7 @@ test "a second LookWord list look in a directory refills its +Search rather than const path = try std.fmt.bufPrint(&path_buf, "{s}/words.txt", .{dir}); const p = try Pardes.init(gpa, .{ .file = path, .tty_only = true, .cols = 80, .rows = 30 }); defer p.deinit(); - _ = wr(p, @intFromEnum(tree.TopFile.ctl), "LookWord list\n"); + _ = wr(p, @backingInt(tree.TopFile.ctl), "LookWord list\n"); pardes.look.lookAt(p, 0, "alpha"); pardes.look.lookAt(p, 0, "beta"); var searches: usize = 0; @@ -4986,7 +4986,7 @@ test "DumpDir refuses a relative directory and one that may not be written, up f if (comptime !pardes.hosted) return; const p = try withFile(testing.allocator, "x\n"); defer p.deinit(); - const root_ctl = @intFromEnum(tree.TopFile.ctl); + const root_ctl = @backingInt(tree.TopFile.ctl); try testing.expectEqual(E.INVAL, wr(p, root_ctl, "DumpDir dumps\n").errno()); try testing.expectEqual(E.INVAL, wr(p, root_ctl, "DumpDir /proc/1/root/dumps\n").errno()); try testing.expectEqual(Status.ok, wr(p, root_ctl, "DumpDir /tmp/pardes-dumps-test\n").reply.status); @@ -4998,7 +4998,7 @@ test "DumpDir refuses a relative directory and one that may not be written, up f test "a Mount dial with a network it does not know is a bad dial address, EINVAL" { const p = try withFile(testing.allocator, "x\n"); defer p.deinit(); - const r = wr(p, @intFromEnum(tree.TopFile.ctl), "Mount peer nowhere!x\n"); + const r = wr(p, @backingInt(tree.TopFile.ctl), "Mount peer nowhere!x\n"); try testing.expectEqual(E.INVAL, r.errno()); try testing.expectStringStartsWith(r.reply.ename, "Mount: bad dial address: nowhere!x"); } @@ -5056,11 +5056,11 @@ test "a Mount of a socket path that is not there says no such socket, ENOENT" { if (comptime !pardes.hosted) return; const p = try withFile(testing.allocator, "x\n"); defer p.deinit(); - const r = wr(p, @intFromEnum(tree.TopFile.ctl), "Mount peer unix!/tmp/pardes-surely-no-socket\n"); + const r = wr(p, @backingInt(tree.TopFile.ctl), "Mount peer unix!/tmp/pardes-surely-no-socket\n"); try testing.expectEqual(E.NOENT, r.errno()); try testing.expect(std.mem.indexOf(u8, r.reply.ename, "no such socket") != null); try testing.expectEqual(@as(usize, 0), p.fs.mounts.items.len); - try testing.expectEqual(E.INVAL, wr(p, @intFromEnum(tree.TopFile.ctl), "Mount peer rel/x.sock\n").errno()); + try testing.expectEqual(E.INVAL, wr(p, @backingInt(tree.TopFile.ctl), "Mount peer rel/x.sock\n").errno()); } test "the init file reads past a BOM, and every line it fails is a notice and an err, never silent" { diff --git a/src/ninep/events.zig b/src/ninep/events.zig index 7b73dc0e..78788c3c 100644 --- a/src/ninep/events.zig +++ b/src/ninep/events.zig @@ -542,7 +542,7 @@ pub const Action = enum(u8) { tag_exec = 'x', pub fn char(a: Action) u8 { - return @intFromEnum(a); + return @backingInt(a); } pub fn fromChar(c: u8) ?Action { @@ -550,7 +550,7 @@ pub const Action = enum(u8) { } pub fn onTag(a: Action) bool { - return @intFromEnum(a) >= 'a'; + return @backingInt(a) >= 'a'; } }; @@ -889,7 +889,7 @@ test "a stream read at an offset inside its last answer gets the rest of it agai defer p.deinit(); p.update(.tick); while (p.nextEffect()) |_| {} - const log = @intFromEnum(tree.TopFile.log); + const log = @backingInt(tree.TopFile.log); const f = call(p, .{ .tag = 1, .op = .open, .node = log }).reply.handle; const frozen: u64 = call(p, .{ .tag = 2, .op = .read, .node = log, .handle = f, .size = 8192 }).bytes.len; _ = call(p, .{ .tag = 3, .op = .write, .node = log, .handle = f, .data = "follow" }); @@ -897,7 +897,7 @@ test "a stream read at an offset inside its last answer gets the rest of it agai notePath(p, "dump", "/b"); const Read = struct { fn at(pp: *Pardes, h: u32, off: u64) []const u8 { - return call(pp, .{ .tag = 4, .op = .read, .node = @intFromEnum(tree.TopFile.log), .handle = h, .off = off, .size = 128 }).bytes; + return call(pp, .{ .tag = 4, .op = .read, .node = @backingInt(tree.TopFile.log), .handle = h, .off = off, .size = 128 }).bytes; } }; try testing.expectEqualStrings("dump /a\n", Read.at(p, f, frozen)); @@ -1130,7 +1130,7 @@ test "writing an event record back performs the action it names" { // A look written back sets what look reads back. _ = wr(p, event, "FL0 3\n"); var want_serial: [16]u8 = undefined; - try testing.expectEqualStrings(try std.fmt.bufPrint(&want_serial, "{d}\n", .{serial}), rd(p, @intFromEnum(tree.TopFile.look), 0, 64).bytes); + try testing.expectEqualStrings(try std.fmt.bufPrint(&want_serial, "{d}\n", .{serial}), rd(p, @backingInt(tree.TopFile.look), 0, 64).bytes); // Well formed but past the text: said so, not "bad event syntax". try testing.expectEqualStrings("range past end of body", wr(p, event, "MX0 999\n").reply.ename); @@ -1144,7 +1144,7 @@ test "the log records whether or not anyone reads, and an open that follows wait const gpa = testing.allocator; const p = try withFile(gpa, "logged\n"); defer p.deinit(); - const log = @intFromEnum(tree.TopFile.log); + const log = @backingInt(tree.TopFile.log); var expected: [4200]u8 = undefined; // Nobody holds /log open, and the pane is recorded anyway. @@ -1256,21 +1256,21 @@ test "a refused or failed write is an err record in the log, saying which file a p.update(.tick); // the pane's `new` is logged before the log is opened while (p.nextEffect()) |_| {} const serial = serialOf(p); - const log = @intFromEnum(tree.TopFile.log); + const log = @backingInt(tree.TopFile.log); const f = call(p, .{ .tag = 1, .op = .open, .node = log }).reply.handle; const frozen = call(p, .{ .tag = 2, .op = .read, .node = log, .handle = f, .size = 1 << 16 }).bytes.len; _ = call(p, .{ .tag = 3, .op = .write, .node = log, .handle = f, .data = "follow" }); var want: [128]u8 = undefined; const next = struct { fn record(pp: *Pardes, h: u32, off: usize) []const u8 { - return call(pp, .{ .tag = 4, .op = .read, .node = @intFromEnum(tree.TopFile.log), .handle = h, .off = off, .size = 4096 }).bytes; + return call(pp, .{ .tag = 4, .op = .read, .node = @backingInt(tree.TopFile.log), .handle = h, .off = off, .size = 4096 }).bytes; } }; _ = wr(p, Node.of(serial, .addr), "/nowhere/"); try testing.expectEqualStrings(try std.fmt.bufPrint(&want, "err {d} addr: no match for regexp\n", .{serial}), next.record(p, f, frozen)); - _ = wr(p, @intFromEnum(tree.TopFile.ctl), "Bogus"); + _ = wr(p, @backingInt(tree.TopFile.ctl), "Bogus"); try testing.expectEqualStrings("err - ctl: unknown control message \"Bogus\"\n", next.record(p, f, frozen)); - _ = wr(p, @intFromEnum(tree.TopFile.focus), "99999"); + _ = wr(p, @backingInt(tree.TopFile.focus), "99999"); try testing.expectEqualStrings("err - focus: no such pane\n", next.record(p, f, frozen)); // A write that succeeds says nothing. _ = wr(p, Node.of(serial, .addr), "#0"); @@ -1373,7 +1373,7 @@ test "opens of the log share the open records, and a closed one frees its record const gpa = testing.allocator; const p = try withFile(gpa, "x\n"); defer p.deinit(); - const log = @intFromEnum(tree.TopFile.log); + const log = @backingInt(tree.TopFile.log); var handles: [tree.open_slots]u32 = undefined; for (&handles) |*h| h.* = call(p, .{ .tag = 1, .op = .open, .node = log }).reply.handle; try testing.expectEqual(E.NFILE, call(p, .{ .tag = 2, .op = .open, .node = log }).errno()); @@ -1447,7 +1447,7 @@ test "follow new skips what the log held and waits for what comes after" { p.update(.tick); // the pane's `new` is logged first while (p.nextEffect()) |_| {} p.setMessage(0, "before the open"); - const log = @intFromEnum(tree.TopFile.log); + const log = @backingInt(tree.TopFile.log); const h = call(p, .{ .tag = 1, .op = .open, .node = log }).reply.handle; try testing.expectEqual(Status.ok, call(p, .{ .tag = 2, .op = .write, .node = log, .handle = h, .data = "follow new\n" }).reply.status); try testing.expectEqual(Status.again, call(p, .{ .tag = 3, .op = .read, .node = log, .handle = h, .size = 4096 }).reply.status); @@ -1461,7 +1461,7 @@ test "a long msg record is cut between words at its cap, with an ellipsis" { defer p.deinit(); const long = std.mem.asBytes(&@as([60][5]u8, @splat("word ".*))); // 300 bytes _ = wr(p, Node.of(serialOf(p), .ctl), "Msg " ++ long ++ "\n"); - const log = @intFromEnum(tree.TopFile.log); + const log = @backingInt(tree.TopFile.log); const h = call(p, .{ .tag = 1, .op = .open, .node = log }).reply.handle; const text = call(p, .{ .tag = 2, .op = .read, .node = log, .handle = h, .size = 1 << 16 }).bytes; const at = std.mem.lastIndexOf(u8, text, "msg ").?; @@ -1485,8 +1485,8 @@ test "a record is one line of UTF-8: DEL and C1 are spaces, bytes not UTF-8 are test "a long err record keeps its end, its middle given up to an ellipsis" { const p = try withFile(testing.allocator, "x\n"); defer p.deinit(); - _ = wr(p, @intFromEnum(tree.TopFile.ctl), "Bogus" ++ std.mem.asBytes(&@as([40][8]u8, @splat("abcdefgh".*))) ++ "\n"); - const log = @intFromEnum(tree.TopFile.log); + _ = wr(p, @backingInt(tree.TopFile.ctl), "Bogus" ++ std.mem.asBytes(&@as([40][8]u8, @splat("abcdefgh".*))) ++ "\n"); + const log = @backingInt(tree.TopFile.log); const h = call(p, .{ .tag = 1, .op = .open, .node = log }).reply.handle; const text = call(p, .{ .tag = 2, .op = .read, .node = log, .handle = h, .size = 1 << 16 }).bytes; const at = std.mem.lastIndexOf(u8, text, "err - ctl: ").?; diff --git a/src/ninep/pane.zig b/src/ninep/pane.zig index 8605cab8..dc104e4b 100644 --- a/src/ninep/pane.zig +++ b/src/ninep/pane.zig @@ -1104,7 +1104,7 @@ test "index lists serial kind dirty flag and name, and stats 0, a view generated const p = try withFile(gpa, "hello\nthere\n"); defer p.deinit(); const pane = p.panes[0].?; - const index = @intFromEnum(tree.TopFile.index); + const index = @backingInt(tree.TopFile.index); const a = rd(p, index, 0, 4096); try testing.expectEqual(Status.ok, a.reply.status); @@ -1138,7 +1138,7 @@ test "a terminal is listed as term with its directory as name" { var want: [64]u8 = undefined; try testing.expect(std.mem.indexOf( u8, - rd(p, @intFromEnum(tree.TopFile.index), 0, 4096).bytes, + rd(p, @backingInt(tree.TopFile.index), 0, 4096).bytes, try std.fmt.bufPrint(&want, "{d} term 0 /work/dir {d}\n", .{ pane.serial, columnOf(p, 0) }), ) != null); try testing.expectEqualStrings("/work/dir\n", rd(p, Node.of(pane.serial, .name), 0, 4096).bytes); @@ -1751,8 +1751,8 @@ test "name refreshes cached syntax for unchanged contents" { try testing.expectEqual(Status.ok, wr(p, Node.of(pane.serial, .name), "renamed.zig\n").reply.status); panes.File.refreshHighlights(p); try testing.expect(pane.file.?.highlights.len >= 2); - try testing.expectEqual(@intFromEnum(pardes.syntax.Syn.keyword), pane.file.?.highlights[0]); - try testing.expectEqual(@intFromEnum(pardes.syntax.Syn.keyword), pane.file.?.highlights[1]); + try testing.expectEqual(@backingInt(pardes.syntax.Syn.keyword), pane.file.?.highlights[0]); + try testing.expectEqual(@backingInt(pardes.syntax.Syn.keyword), pane.file.?.highlights[1]); try testing.expectEqualStrings("fn check() void {}\n", pane.file.?.content); } diff --git a/src/ninep/pty.zig b/src/ninep/pty.zig index aeb57a00..d80f7175 100644 --- a/src/ninep/pty.zig +++ b/src/ninep/pty.zig @@ -893,7 +893,7 @@ test "a shell that exits under a run answers its status, and the log says exit b const prompt = "\x1b]133;A;cl=line;aid=pardes\x07$ \x1b]133;B;aid=pardes\x07"; p.update(.{ .output = .{ .pane = 0, .bytes = prompt } }); while (p.nextEffect()) |_| {} - const log = @intFromEnum(tree.TopFile.log); + const log = @backingInt(tree.TopFile.log); const f = call(p, .{ .tag = 1, .op = .open, .node = log }).reply.handle; const frozen = call(p, .{ .tag = 2, .op = .read, .node = log, .handle = f, .size = 1 << 16 }).bytes.len; _ = call(p, .{ .tag = 3, .op = .write, .node = log, .handle = f, .data = "follow" }); @@ -984,7 +984,6 @@ test "a run's answer says cut when its output's start is gone, and reads a bound var got = sh.answered(p, node, h, into); try testing.expectEqualStrings("exit 0\nafter\n", got); - // A resize between its start and end reflows the pins with the text. h = sh.send(p, node); sh.put(p, c ++ "one\r\ntwo\r\n"); @@ -1092,7 +1091,7 @@ test "a terminal's ctl counts its body, and a new directory is a rename in the l _ = fields.next(); try testing.expectEqual(body_len, try std.fmt.parseInt(usize, fields.next().?, 10)); - const log = @intFromEnum(tree.TopFile.log); + const log = @backingInt(tree.TopFile.log); const f = call(p, .{ .tag = 4, .op = .open, .node = log }).reply.handle; const frozen = call(p, .{ .tag = 5, .op = .read, .node = log, .handle = f, .size = 1 << 16 }).bytes.len; _ = call(p, .{ .tag = 6, .op = .write, .node = log, .handle = f, .data = "follow" }); diff --git a/src/ninep/screen.zig b/src/ninep/screen.zig index 8d4707e0..ba676ded 100644 --- a/src/ninep/screen.zig +++ b/src/ninep/screen.zig @@ -95,7 +95,7 @@ const withTerm = th.withTerm; const serialOf = th.serialOf; const Node = tree.Node; const Status = tree.Status; -const screen_node = @intFromEnum(tree.TopFile.screen); +const screen_node = @backingInt(tree.TopFile.screen); test "listener addresses are readable canonical dials with bounded partial reads" { const gpa = testing.allocator; @@ -111,7 +111,7 @@ test "listener addresses are readable canonical dials with bounded partial reads try testing.expectEqualStrings(expected, bytes); try testing.expectError(error.ReadOnlyFilesystem, fs.write(p, path, "")); } - const node = @intFromEnum(tree.TopFile.listeners); + const node = @backingInt(tree.TopFile.listeners); var off: usize = 0; while (off < expected.len) { const part = rd(p, node, off, 3); diff --git a/src/ninep/testing.zig b/src/ninep/testing.zig index a35a9cf0..ec665130 100644 --- a/src/ninep/testing.zig +++ b/src/ninep/testing.zig @@ -71,7 +71,7 @@ pub fn logHas(p: *Pardes, needle: []const u8) bool { /// How many times the log, read whole from a fresh open, holds `needle`. pub fn logCount(p: *Pardes, needle: []const u8) usize { - const log = @intFromEnum(tree.TopFile.log); + const log = @backingInt(tree.TopFile.log); const h = call(p, .{ .tag = 1, .op = .open, .node = log }).reply.handle; defer _ = call(p, .{ .tag = 3, .op = .release, .node = log, .handle = h }); const text = call(p, .{ .tag = 2, .op = .read, .node = log, .handle = h, .size = 1 << 16 }).bytes; @@ -95,7 +95,7 @@ pub fn look_up(p: *Pardes, dir: u64, name: []const u8) Answer { /// The open is what makes the pane; the handle it answers is the serial, which /// is also what a read of that fid reports. pub fn newPane(p: *Pardes) !u32 { - const made = call(p, .{ .tag = 8, .op = .open, .node = @intFromEnum(tree.TopFile.new) }); + const made = call(p, .{ .tag = 8, .op = .open, .node = @backingInt(tree.TopFile.new) }); if (made.reply.status != .ok or made.reply.handle == 0) return error.NoPane; return made.reply.handle; } diff --git a/src/ninep/tree.zig b/src/ninep/tree.zig index 5678832b..9aa0225a 100644 --- a/src/ninep/tree.zig +++ b/src/ninep/tree.zig @@ -115,7 +115,7 @@ pub fn changesPane(p: *Pardes, req: Req) bool { return switch (req.op) { .write => true, .setattr => truncates(req), - .open => req.node == @intFromEnum(TopFile.new), + .open => req.node == @backingInt(TopFile.new), .release => req.remove or holdsLines(p, req) or holdsPage(p, req), .read => holdsPage(p, req), .lookup, .getattr, .readdir => false, @@ -279,7 +279,7 @@ pub const TopFile = enum(u5) { } }; -pub const root: u64 = @intFromEnum(TopFile.root); +pub const root: u64 = @backingInt(TopFile.root); /// Declaration order is readdir order. pub const PaneFile = enum(u5) { @@ -363,11 +363,11 @@ pub const Node = packed struct(u64) { pub fn of(serial: u32, file: PaneFile) u64 { std.debug.assert(serial != 0); - return @bitCast(Node{ .file = @intFromEnum(file), .serial = serial }); + return @bitCast(Node{ .file = @backingInt(file), .serial = serial }); } pub fn ofCol(serial: u32, file: ColFile) u64 { - return @bitCast(Node{ .file = @intFromEnum(file), .serial = col_bit | @as(u59, serial) }); + return @bitCast(Node{ .file = @backingInt(file), .serial = col_bit | @as(u59, serial) }); } pub fn target(node: u64) ?Target { @@ -424,9 +424,9 @@ pub fn resolveSelf(p: *Pardes, path: []const u8) ?u64 { // `new` is reached in /pane, where the panes it makes are. const top = std.meta.stringToEnum(TopFile, first) orelse return sources.node(normalized); if (top == .root or top == .new or top == .pane or parts.next() != null) return null; - return @intFromEnum(top); + return @backingInt(top); } - const next = parts.next() orelse return @intFromEnum(TopFile.pane); + const next = parts.next() orelse return @backingInt(TopFile.pane); // `new` is served on the wire but deliberately unreachable from an editor // path: this resolves Look targets and hover previews, and a preview that // opened `new` to see what was there would make a pane per hover. @@ -606,7 +606,7 @@ fn attrOf(p: *Pardes, target: Target) ?Reply.Attr { switch (target) { .top => |f| return .{ .name = f.fileName(), - .node = @intFromEnum(f), + .node = @backingInt(f), .dir = f.dir(), .mode = f.mode(), .size = topSize(p, f), @@ -695,11 +695,11 @@ fn lookup(p: *Pardes, req: Req, target: Target) Reply { const parent: u64 = switch (target) { .top => |top| if (top.dir()) root else return Reply.fail(req.tag, E.NOTDIR), .pane => |t| switch (t.file) { - .dir => @intFromEnum(TopFile.pane), + .dir => @backingInt(TopFile.pane), .pty => Node.of(t.serial, .dir), else => return Reply.fail(req.tag, E.NOTDIR), }, - .col => |c| if (c.file == .dir) @intFromEnum(TopFile.col) else return Reply.fail(req.tag, E.NOTDIR), + .col => |c| if (c.file == .dir) @backingInt(TopFile.col) else return Reply.fail(req.tag, E.NOTDIR), }; return handle(p, .{ .tag = req.tag, .op = .getattr, .node = parent }); } @@ -709,12 +709,12 @@ fn lookup(p: *Pardes, req: Req, target: Target) Reply { .root => root: { if (std.mem.eql(u8, name, "os")) return fs.osHandle(p, .{ .tag = req.tag, .op = .getattr, .node = fs.os_root }); // `new` is reached in /pane, where the panes it makes are. - if (std.meta.stringToEnum(TopFile, name)) |t| if (t != .root and t != .new) break :root @intFromEnum(t); + if (std.meta.stringToEnum(TopFile, name)) |t| if (t != .root and t != .new) break :root @backingInt(t); if (sources.node(name)) |n| return sources.handle(p, .{ .tag = req.tag, .op = .getattr, .node = n }); return Reply.fail(req.tag, E.NOENT); }, .pane => pane: { - if (std.mem.eql(u8, name, new_pane)) break :pane @intFromEnum(TopFile.new); + if (std.mem.eql(u8, name, new_pane)) break :pane @backingInt(TopFile.new); // A pane directory is its serial, in decimal digits and never 0. if (name.len > 10) return Reply.fail(req.tag, E.NOENT); for (name) |c| if (c < '0' or c > '9') return Reply.fail(req.tag, E.NOENT); @@ -778,13 +778,13 @@ fn readdir(p: *Pardes, req: Req, target: Target) Reply { // The guide, then what describes the session, then the // files that act, then the directories. inline for (.{ TopFile.README, TopFile.index, TopFile.status, TopFile.focus, TopFile.ctl, TopFile.commands, TopFile.recent, TopFile.look, TopFile.exec, TopFile.pager, TopFile.log, TopFile.screen, TopFile.listeners, TopFile.layout, TopFile.tag, TopFile.tagexec, TopFile.pane, TopFile.col }) |t| { - if (skip > 0) skip -= 1 else stageDirent(out, p.gpa, @intFromEnum(t), t.dir(), t.fileName()); + if (skip > 0) skip -= 1 else stageDirent(out, p.gpa, @backingInt(t), t.dir(), t.fileName()); } if (skip > 0) skip -= 1 else stageDirent(out, p.gpa, fs.os_root, true, "os"); sources.stage(p, out, "", &skip); }, .pane => { - if (skip > 0) skip -= 1 else stageDirent(out, p.gpa, @intFromEnum(TopFile.new), false, TopFile.new.fileName()); + if (skip > 0) skip -= 1 else stageDirent(out, p.gpa, @backingInt(TopFile.new), false, TopFile.new.fileName()); var last: u32 = 0; while (nextSerialAfter(p, last)) |serial| { last = serial; @@ -1378,7 +1378,7 @@ test "a listing read in chunks is what it was at the open, however the panes cha const p = try th.withFile(testing.allocator, "x\n"); defer p.deinit(); for ([_]TopFile{ .index, .layout, .recent, .ctl }) |file| { - const node = @intFromEnum(file); + const node = @backingInt(file); const whole = try testing.allocator.dupe(u8, th.rd(p, node, 0, 1 << 16).bytes); defer testing.allocator.free(whole); const h = th.call(p, .{ .tag = 1, .op = .open, .node = node }).reply.handle; @@ -1389,7 +1389,7 @@ test "a listing read in chunks is what it was at the open, however the panes cha // Something changes between the chunks. const made = try th.newPane(p); _ = th.wr(p, Node.of(made, .name), "/tmp/pardes-frozen-listing.txt\n"); - _ = th.wr(p, @intFromEnum(TopFile.ctl), "Verbose off\n"); + _ = th.wr(p, @backingInt(TopFile.ctl), "Verbose off\n"); while (true) { const more = th.call(p, .{ .tag = 2, .op = .read, .node = node, .handle = h, .off = got.items.len, .size = 7 }).bytes; if (more.len == 0) break; @@ -1397,7 +1397,7 @@ test "a listing read in chunks is what it was at the open, however the panes cha } _ = th.call(p, .{ .tag = 3, .op = .release, .node = node, .handle = h, .opened = true }); try testing.expectEqualStrings(whole, got.items); - _ = th.wr(p, @intFromEnum(TopFile.ctl), "Verbose on\n"); + _ = th.wr(p, @backingInt(TopFile.ctl), "Verbose on\n"); } } @@ -1418,7 +1418,7 @@ test "filesystem inspection preserves pending and displayed Look hover" { } }); try testing.expect(p.look_hover_wait != null); const body = Node.of(serialOf(p), .body); - const screen_node = @intFromEnum(TopFile.screen); + const screen_node = @backingInt(TopFile.screen); for (0..2) |phase| { if (phase == 1) { for (0..delay) |_| p.update(.tick); @@ -1429,7 +1429,7 @@ test "filesystem inspection preserves pending and displayed Look hover" { const requests = [_]Req{ .{ .tag = 1, .op = .lookup, .node = root, .data = "screen" }, .{ .tag = 1, .op = .lookup, .node = root, .data = "status" }, - .{ .tag = 1, .op = .getattr, .node = @intFromEnum(TopFile.pane) }, + .{ .tag = 1, .op = .getattr, .node = @backingInt(TopFile.pane) }, .{ .tag = 2, .op = .getattr, .node = body }, .{ .tag = 3, .op = .open, .node = body }, .{ .tag = 4, .op = .read, .node = body, .size = 5 }, @@ -1458,14 +1458,14 @@ test "log stats 0 however much it holds, a stream as acme's generated files are" defer p.deinit(); _ = th.wr(p, Node.of(th.serialOf(p), .exec), "Msg a record for the log\n"); try testing.expect(th.logHas(p, "a record for the log")); - try testing.expectEqual(@as(u64, 0), call(p, .{ .tag = 1, .op = .getattr, .node = @intFromEnum(TopFile.log) }).reply.attr.size); + try testing.expectEqual(@as(u64, 0), call(p, .{ .tag = 1, .op = .getattr, .node = @backingInt(TopFile.log) }).reply.attr.size); } test "filesystem pane creation and truncation cancel Look hover" { const requests = [_]Req{ // Opening `new` is what makes a pane now; walking to it makes none, // and so must leave a pending hover alone. - .{ .tag = 2, .op = .open, .node = @intFromEnum(TopFile.new) }, + .{ .tag = 2, .op = .open, .node = @backingInt(TopFile.new) }, .{ .tag = 3, .op = .setattr, .node = 0, .truncate = true }, }; for (requests) |request| { @@ -1493,16 +1493,16 @@ test "README names every file the tree serves" { } }; inline for (@typeInfo(TopFile).@"enum".field_values) |value| { - const t: TopFile = @enumFromInt(value); + const t: TopFile = @fromBackingInt(@intCast(value)); if (t != .root and !words.has(t.fileName())) { std.debug.print("README does not mention /{s}\n", .{t.fileName()}); return error.Undocumented; } } inline for (@typeInfo(PaneFile).@"enum".field_values) |value| { - const t: PaneFile = @enumFromInt(value); + const t: PaneFile = @fromBackingInt(@intCast(value)); const ok = if (t == .dir) true else if (t.inPty() and t != .pty) - std.mem.indexOf(u8, fs.help, "pty/" ++ comptime @as(PaneFile, @enumFromInt(value)).fileName()) != null + std.mem.indexOf(u8, fs.help, "pty/" ++ comptime @as(PaneFile, @fromBackingInt(@intCast(value))).fileName()) != null else words.has(t.fileName()); if (!ok) { @@ -1530,8 +1530,8 @@ test "readdir lists the root and a pane directory without creating anything" { try testing.expectEqualStrings(name, top[i].name); try testing.expectEqual(i >= 16, top[i].dir); } - try testing.expectEqual(@intFromEnum(TopFile.pane), top[16].node); - try testing.expectEqual(@intFromEnum(TopFile.col), top[17].node); + try testing.expectEqual(@backingInt(TopFile.pane), top[16].node); + try testing.expectEqual(@backingInt(TopFile.col), top[17].node); try testing.expectEqual(fs.os_root, top[18].node); var idbuf: [16]u8 = undefined; try testing.expect(th.nameAt(top, try std.fmt.bufPrint(&idbuf, "{d}", .{serial})) == null); @@ -1554,7 +1554,7 @@ test "readdir lists the root and a pane directory without creating anything" { try testing.expectEqual(Status.ok, call(p, .{ .tag = 1, .op = .getattr, .node = entry.node }).reply.status); try testing.expectEqual(before, p.next_serial); } - const panes_dir = rdir(p, @intFromEnum(TopFile.pane), 0); + const panes_dir = rdir(p, @backingInt(TopFile.pane), 0); const listed = th.dirents(panes_dir.bytes, &buf); var idname: [16]u8 = undefined; const own = th.nameAt(listed, try std.fmt.bufPrint(&idname, "{d}", .{serial})).?; @@ -1565,16 +1565,16 @@ test "readdir lists the root and a pane directory without creating anything" { // client that stats every name a listing gave it inert. const shown = th.nameAt(listed, new_pane).?; try testing.expect(!shown.dir); - try testing.expectEqual(Status.ok, look_up(p, @intFromEnum(TopFile.pane), new_pane).reply.status); - try testing.expectEqual(Status.ok, call(p, .{ .tag = 1, .op = .getattr, .node = @intFromEnum(TopFile.new) }).reply.status); + try testing.expectEqual(Status.ok, look_up(p, @backingInt(TopFile.pane), new_pane).reply.status); + try testing.expectEqual(Status.ok, call(p, .{ .tag = 1, .op = .getattr, .node = @backingInt(TopFile.new) }).reply.status); try testing.expectEqual(before, p.next_serial); const dir = rdir(p, Node.of(serial, .dir), 0); const files = th.dirents(dir.bytes, &buf); try testing.expectEqual(@as(usize, 18), files.len); for ([_][]const u8{ - "name", "body", "tag", "ctl", "addr", "dot", "limit", "data", "xdata", - "sel", "dirty", "mark", "scroll", "errors", "event", "look", "exec", "tagexec", + "name", "body", "tag", "ctl", "addr", "dot", "limit", "data", "xdata", + "sel", "dirty", "mark", "scroll", "errors", "event", "look", "exec", "tagexec", }, 0..) |name, i| try testing.expectEqualStrings(name, files[i].name); try testing.expect(th.nameAt(files, ".") == null); @@ -1588,7 +1588,7 @@ test "readdir lists the root and a pane directory without creating anything" { try testing.expectEqual(before, p.next_serial); try testing.expectEqual(E.NOTDIR, rdir(p, Node.of(serial, .body), 0).errno()); - try testing.expectEqual(E.NOTDIR, rdir(p, @intFromEnum(TopFile.index), 0).errno()); + try testing.expectEqual(E.NOTDIR, rdir(p, @backingInt(TopFile.index), 0).errno()); } test "lookup resolves top files, pane serials and pane files" { @@ -1597,7 +1597,7 @@ test "lookup resolves top files, pane serials and pane files" { defer p.deinit(); const serial = serialOf(p); - try testing.expectEqual(@as(u64, @intFromEnum(TopFile.index)), look_up(p, root, "index").reply.attr.node); + try testing.expectEqual(@as(u64, @backingInt(TopFile.index)), look_up(p, root, "index").reply.attr.node); try testing.expect(!look_up(p, root, "status").reply.attr.dir); try testing.expectEqual(@as(u16, 0o444), look_up(p, root, "status").reply.attr.mode); try testing.expectEqual(@as(u16, 0o666), look_up(p, root, "look").reply.attr.mode); @@ -1607,17 +1607,17 @@ test "lookup resolves top files, pane serials and pane files" { try testing.expectEqual(E.NOENT, look_up(p, root, "nosuchthing").errno()); try testing.expectEqual(E.NOENT, look_up(p, root, "self").errno()); try testing.expectEqual(E.NOENT, look_up(p, root, "cons").errno()); - try testing.expectEqual(E.NOTDIR, look_up(p, @intFromEnum(TopFile.index), "x").errno()); + try testing.expectEqual(E.NOTDIR, look_up(p, @backingInt(TopFile.index), "x").errno()); var idbuf: [16]u8 = undefined; const serial_name = try std.fmt.bufPrint(&idbuf, "{d}", .{serial}); try testing.expectEqual(E.NOENT, look_up(p, root, serial_name).errno()); - const dir = look_up(p, @intFromEnum(TopFile.pane), serial_name); + const dir = look_up(p, @backingInt(TopFile.pane), serial_name); try testing.expectEqual(Node.of(serial, .dir), dir.reply.attr.node); try testing.expect(dir.reply.attr.dir); try testing.expectEqualStrings(serial_name, dir.reply.attr.name); - try testing.expectEqual(E.NOENT, look_up(p, @intFromEnum(TopFile.pane), "99999").errno()); - try testing.expectEqual(E.NOENT, look_up(p, @intFromEnum(TopFile.pane), "0").errno()); + try testing.expectEqual(E.NOENT, look_up(p, @backingInt(TopFile.pane), "99999").errno()); + try testing.expectEqual(E.NOENT, look_up(p, @backingInt(TopFile.pane), "0").errno()); const body = look_up(p, Node.of(serial, .dir), "body"); try testing.expectEqual(Node.of(serial, .body), body.reply.attr.node); @@ -1634,19 +1634,19 @@ test "opening /pane/new makes a pane and removing one closes it" { const p = try withFile(gpa, "first\n"); defer p.deinit(); const before = p.next_serial; - const panes_dir = @intFromEnum(TopFile.pane); + const panes_dir = @backingInt(TopFile.pane); // Browsing /pane creates nothing, and neither does walking or stat-ing // `new` itself: only an open does. That is what lets `new` be listed at // all, since `ls -l` stats every name a listing handed it. try testing.expectEqual(Status.ok, rdir(p, panes_dir, 0).reply.status); try testing.expectEqual(Status.ok, look_up(p, panes_dir, new_pane).reply.status); - try testing.expectEqual(Status.ok, call(p, .{ .tag = 1, .op = .getattr, .node = @intFromEnum(TopFile.new) }).reply.status); + try testing.expectEqual(Status.ok, call(p, .{ .tag = 1, .op = .getattr, .node = @backingInt(TopFile.new) }).reply.status); try testing.expectEqual(before, p.next_serial); // The open makes the pane and hands back its serial; the read only // observes, so two reads of one fid answer the same pane. - const made = call(p, .{ .tag = 2, .op = .open, .node = @intFromEnum(TopFile.new) }); + const made = call(p, .{ .tag = 2, .op = .open, .node = @backingInt(TopFile.new) }); try testing.expectEqual(Status.ok, made.reply.status); try testing.expectEqual(before + 1, p.next_serial); const serial = before + 1; @@ -1654,7 +1654,7 @@ test "opening /pane/new makes a pane and removing one closes it" { var expected: [16]u8 = undefined; const want = try std.fmt.bufPrint(&expected, "{d}\n", .{serial}); for (0..2) |_| { - const answer = call(p, .{ .tag = 3, .op = .read, .node = @intFromEnum(TopFile.new), .handle = made.reply.handle, .size = 64 }); + const answer = call(p, .{ .tag = 3, .op = .read, .node = @backingInt(TopFile.new), .handle = made.reply.handle, .size = 64 }); try testing.expectEqualStrings(want, answer.bytes); } @@ -1668,10 +1668,10 @@ test "opening /pane/new makes a pane and removing one closes it" { // A second open is a second pane, and releasing a clone fid leaves the // pane it made standing. - const second = call(p, .{ .tag = 4, .op = .open, .node = @intFromEnum(TopFile.new) }); + const second = call(p, .{ .tag = 4, .op = .open, .node = @backingInt(TopFile.new) }); try testing.expectEqual(Status.ok, second.reply.status); try testing.expect(second.reply.handle != made.reply.handle); - _ = call(p, .{ .tag = 5, .op = .release, .node = @intFromEnum(TopFile.new), .handle = made.reply.handle, .opened = true }); + _ = call(p, .{ .tag = 5, .op = .release, .node = @backingInt(TopFile.new), .handle = made.reply.handle, .opened = true }); try testing.expect(p.paneBySerial(serial) != null); try testing.expectEqualStrings("hi", p.panes[id].?.file.?.content); @@ -1689,7 +1689,7 @@ test "opening /pane/new makes a pane and removing one closes it" { // Tremove closes the pane it names, and nothing else in the tree. try testing.expectEqual(E.PERM, th.rmdir(p, Node.of(serial, .body)).errno()); - try testing.expectEqual(E.PERM, th.rmdir(p, @intFromEnum(TopFile.index)).errno()); + try testing.expectEqual(E.PERM, th.rmdir(p, @backingInt(TopFile.index)).errno()); try testing.expect(p.paneBySerial(serial) != null); try testing.expectEqual(Status.ok, th.rmdir(p, Node.of(serial, .dir)).reply.status); try testing.expect(p.paneBySerial(serial) == null); @@ -1700,7 +1700,7 @@ test "every open that holds something is one record, named by its handle only on const p = try th.withTerm(testing.allocator); defer p.deinit(); const serial = serialOf(p); - const log = @intFromEnum(TopFile.log); + const log = @backingInt(TopFile.log); const event = Node.of(serial, .event); const run = Node.of(serial, .pty_run); const logged = call(p, .{ .tag = 1, .op = .open, .node = log }).reply.handle; @@ -1729,15 +1729,15 @@ test "directories walk to their parents" { defer p.deinit(); for ([_]struct { node: u64, parent: u64 }{ .{ .node = root, .parent = root }, - .{ .node = @intFromEnum(TopFile.pane), .parent = root }, - .{ .node = Node.of(serialOf(p), .dir), .parent = @intFromEnum(TopFile.pane) }, + .{ .node = @backingInt(TopFile.pane), .parent = root }, + .{ .node = Node.of(serialOf(p), .dir), .parent = @backingInt(TopFile.pane) }, .{ .node = fs.os_root, .parent = root }, }) |case| { const result = look_up(p, case.node, ".."); try testing.expectEqual(Status.ok, result.reply.status); try testing.expectEqual(case.parent, result.reply.attr.node); } - try testing.expectEqual(E.NOTDIR, look_up(p, @intFromEnum(TopFile.index), "..").errno()); + try testing.expectEqual(E.NOTDIR, look_up(p, @backingInt(TopFile.index), "..").errno()); try testing.expectEqual(E.NOTDIR, look_up(p, Node.of(serialOf(p), .body), "..").errno()); } @@ -1748,10 +1748,10 @@ test "editor paths resolve to the same nodes the wire serves" { var path: [64]u8 = undefined; try testing.expectEqual(root, resolveSelf(p, "").?); try testing.expectEqual(root, resolveSelf(p, "/./pane/../").?); - try testing.expectEqual(@intFromEnum(TopFile.index), resolveSelf(p, "index").?); - try testing.expectEqual(@intFromEnum(TopFile.status), resolveSelf(p, "status").?); + try testing.expectEqual(@backingInt(TopFile.index), resolveSelf(p, "index").?); + try testing.expectEqual(@backingInt(TopFile.status), resolveSelf(p, "status").?); try testing.expect(resolveSelf(p, "new") == null); - try testing.expectEqual(@intFromEnum(TopFile.pane), resolveSelf(p, "pane").?); + try testing.expectEqual(@backingInt(TopFile.pane), resolveSelf(p, "pane").?); try testing.expectEqual(Node.of(serial, .dir), resolveSelf(p, try std.fmt.bufPrint(&path, "pane/{d}", .{serial})).?); try testing.expectEqual(Node.of(serial, .sel), resolveSelf(p, try std.fmt.bufPrint(&path, "pane/{d}/sel", .{serial})).?); try testing.expect(resolveSelf(p, try std.fmt.bufPrint(&path, "pane/{d}/pty/ctl", .{serial})) == null); @@ -1800,7 +1800,7 @@ test "random placements, refused or not, leave no pane under its tag and two row const action = r.uintLessThan(u8, 8); switch (action) { 0 => _ = th.wr(p, Node.of(at, .exec), "New\n"), - 1 => _ = call(p, .{ .tag = 1, .op = .open, .node = @intFromEnum(TopFile.new) }), + 1 => _ = call(p, .{ .tag = 1, .op = .open, .node = @backingInt(TopFile.new) }), 2 => _ = th.wr(p, Node.of(at, .exec), "Newcol\n"), 3 => _ = th.wr(p, Node.of(at, .exec), "Edit =\n"), 4 => _ = th.wr(p, Node.of(at, .exec), "Tty\n"), @@ -1823,7 +1823,7 @@ test "at the pane cap, pane/new, look and New each say so, and look reads back e // Tall enough that the column holds every pane at its tag and two rows, // and wide enough that each tag, the session directory's +New, is one. p.update(.{ .resize = .{ .cols = 400, .rows = pardes.MAX_PANES * 4 } }); - const new = @intFromEnum(TopFile.new); + const new = @backingInt(TopFile.new); while (p.freeSlot() != null) try testing.expectEqual(Status.ok, call(p, .{ .tag = 1, .op = .open, .node = new }).reply.status); var want: [64]u8 = undefined; const said = try std.fmt.bufPrint(&want, "no space for a pane: {d} max", .{pardes.MAX_PANES}); @@ -1840,7 +1840,7 @@ test "at the pane cap, pane/new, look and New each say so, and look reads back e var dir_buf: [4096]u8 = undefined; const dir = dir_buf[0..try tmp.dir.realPath(testing.io, &dir_buf)]; var line: [4200]u8 = undefined; - const look_node = @intFromEnum(TopFile.look); + const look_node = @backingInt(TopFile.look); const looked = th.wr(p, look_node, try std.fmt.bufPrint(&line, "{s}/f.txt\n", .{dir})); try testing.expect(looked.errno() != 0); try testing.expect(std.mem.indexOf(u8, looked.reply.ename, said) != null); @@ -1857,7 +1857,7 @@ test "at the pane cap, pane/new, look and New each say so, and look reads back e test "nothing a mount's close or a no-op truncate sends waits on the editor: a held line runs at its next step" { const p = try withFile(testing.allocator, "x\n"); defer p.deinit(); - const exec = @intFromEnum(TopFile.exec); + const exec = @backingInt(TopFile.exec); // `> exec` truncates nothing; `> body` does. try testing.expect(!needsQuiet(p, .{ .tag = 1, .op = .setattr, .node = exec, .truncate = true })); try testing.expect(!changesPane(p, .{ .tag = 1, .op = .setattr, .node = exec, .truncate = true })); @@ -1875,7 +1875,7 @@ test "nothing a mount's close or a no-op truncate sends waits on the editor: a h test "a command line cut across writes runs once whole, and the last runs at release; an Edit block waits for its end" { const p = try th.withFile(testing.allocator, "x\n"); defer p.deinit(); - const exec = @intFromEnum(TopFile.exec); + const exec = @backingInt(TopFile.exec); const h = call(p, .{ .tag = 1, .op = .open, .node = exec, .omode = 1 }).reply.handle; try testing.expect(h != 0); // Each piece fills its Twrite (a client's one write cut at msize). @@ -1906,12 +1906,12 @@ test "a refused open, create or remove says why in words and logs no err; a refu const serial = serialOf(p); // pane/new is read, never written: a write is refused, and is no // failure the log tells of. - const new = th.wr(p, @intFromEnum(TopFile.new), "x\n"); + const new = th.wr(p, @backingInt(TopFile.new), "x\n"); try testing.expectEqual(Status.err, new.reply.status); try testing.expectEqualStrings("permission denied", new.reply.ename); const made = call(p, .{ .tag = 2, .op = .open, .node = Node.of(serial, .body), .create = true }); try testing.expectEqualStrings("permission denied", made.reply.ename); - const gone = th.rmdir(p, @intFromEnum(TopFile.index)); + const gone = th.rmdir(p, @backingInt(TopFile.index)); try testing.expectEqual(Status.err, gone.reply.status); try testing.expect(gone.reply.ename.len > 0 and !std.ascii.isUpper(gone.reply.ename[0])); // An OTRUNC open's truncation of data after a failed addr: refused, no err. @@ -1961,7 +1961,7 @@ test "a write with no newline waits for its newline or the close, whatever its s test "look and exec read back what their own open's write touched; a fresh open reads the session's last" { const p = try th.withFile(testing.allocator, "x\n"); defer p.deinit(); - const exec = @intFromEnum(TopFile.exec); + const exec = @backingInt(TopFile.exec); const first = p.panes[0].?.serial; const mine = call(p, .{ .tag = 1, .op = .open, .node = exec, .omode = 2 }).reply.handle; const theirs = call(p, .{ .tag = 2, .op = .open, .node = exec, .omode = 2 }).reply.handle; @@ -2013,7 +2013,7 @@ test "a rename of a pane's directory or file is refused as not permitted" { test "no placement leaves a pane shorter than its tag and two rows; a full column refuses the next" { const p = try th.withFile(testing.allocator, "x\n"); defer p.deinit(); - const new = @intFromEnum(TopFile.new); + const new = @backingInt(TopFile.new); var made: usize = 1; const refused = while (made < pardes.MAX_PANES) : (made += 1) { const a = call(p, .{ .tag = 1, .op = .open, .node = new }); @@ -2078,7 +2078,7 @@ test "a pane made from pane/new goes last in its column, even when the last pane const p = try th.withFile(testing.allocator, "x\n"); defer p.deinit(); for (0..3) |_| { - const made = call(p, .{ .tag = 1, .op = .open, .node = @intFromEnum(TopFile.new) }).reply.handle; + const made = call(p, .{ .tag = 1, .op = .open, .node = @backingInt(TopFile.new) }).reply.handle; p.sync(); try testing.expectEqual(made, p.panes[p.col_panes[0][p.col_n[0] - 1]].?.serial); } diff --git a/src/pager.zig b/src/pager.zig index feabd194..aba73d43 100644 --- a/src/pager.zig +++ b/src/pager.zig @@ -240,8 +240,8 @@ const Handler = struct { .reset_strikethrough => s.strikethrough = false, .direct_color_fg => |c| s.fg = .{ .rgb = .{ c.r, c.g, c.b } }, .direct_color_bg => |c| s.bg = .{ .rgb = .{ c.r, c.g, c.b } }, - .@"8_fg", .@"8_bright_fg" => |name| s.fg = .{ .index = @intFromEnum(name) }, - .@"8_bg", .@"8_bright_bg" => |name| s.bg = .{ .index = @intFromEnum(name) }, + .@"8_fg", .@"8_bright_fg" => |name| s.fg = .{ .index = @backingInt(name) }, + .@"8_bg", .@"8_bright_bg" => |name| s.bg = .{ .index = @backingInt(name) }, .@"256_fg" => |i| s.fg = .{ .index = i }, .@"256_bg" => |i| s.bg = .{ .index = i }, .reset_fg => s.fg = .default, diff --git a/src/pardes.zig b/src/pardes.zig index 8da0922d..7e166847 100644 --- a/src/pardes.zig +++ b/src/pardes.zig @@ -924,7 +924,7 @@ test "Filter is ordered after Del and toggles only its terminal or +Pager pane" const testing = std.testing; const del = std.meta.stringToEnum(Builtin, "Del") orelse return error.MissingDelBuiltin; const filter = std.meta.stringToEnum(Builtin, "Filter") orelse return error.MissingFilterBuiltin; - try testing.expectEqual(@intFromEnum(del) + 1, @intFromEnum(filter)); + try testing.expectEqual(@backingInt(del) + 1, @backingInt(filter)); const p = try Pardes.init(testing.allocator, .{ .tty_only = true }); defer p.deinit(); @@ -3308,8 +3308,8 @@ test "tabbed file aligns syntax cursor and mouse at the nearest insertion gap" { const pane = try p.setTestFile("\treturn x\n"); const f = &pane.file.?; f.highlights = try p.tree_sitter_gpa.alloc(u8, f.content.len); - @memset(f.highlights, @intFromEnum(syntax.Syn.none)); - @memset(f.highlights[1..7], @intFromEnum(syntax.Syn.keyword)); + @memset(f.highlights, @backingInt(syntax.Syn.none)); + @memset(f.highlights[1..7], @backingInt(syntax.Syn.keyword)); f.syntax_dirty = false; pane.body.cur_row = 0; pane.body.cur_col = 1; @@ -3721,7 +3721,7 @@ pub fn hit(key: Key, binding: []const config.Chord) bool { return false; } -pub const sel_slot = @intFromEnum(config.select_button); +pub const sel_slot = @backingInt(config.select_button); /// Pixel dimensions are meaningful only to the native PDF placement path. /// Keep resize events layout-only when that path is not part of the build. @@ -6040,7 +6040,7 @@ pub const Pardes = struct { // The one-failure rule is a write's: a refused open (its OTRUNC's // truncation, a setattr, too), create or remove is its Rerror alone, // no err, as is a write to pane/new, which is only ever read. - const ruled = req.op == .write and req.node != @intFromEnum(ctlfs.TopFile.new); + const ruled = req.op == .write and req.node != @backingInt(ctlfs.TopFile.new); if (reply.status == .err and ruled) ctlfs.events.noteError(p, req, reply); // The request was a whole step of its own, so it settles the way a // step does: the cursor and scroll reconciled, the scripted panes diff --git a/src/pdf_view.zig b/src/pdf_view.zig index 567117bb..500f05f3 100644 --- a/src/pdf_view.zig +++ b/src/pdf_view.zig @@ -2604,7 +2604,7 @@ pub fn pointerRelease( ) PointerRelease { if (comptime !enabled) return .{}; const state = &(pane.pdf orelse return .{}); - const slot = @intFromEnum(button); + const slot = @backingInt(button); const grid_selection = pane.sel[slot]; pane.sel[slot].state = .none; // native quads, not projected text cells diff --git a/src/syntax.zig b/src/syntax.zig index fa212ca7..1c09c9f3 100644 --- a/src/syntax.zig +++ b/src/syntax.zig @@ -214,7 +214,7 @@ fn ensure(spec: *Spec) !Selected { const capture_styles = spec.capture_styles[0..query.captureCount()]; for (capture_styles, 0..) |*style, id| { const name = query.captureNameForId(@intCast(id)) orelse ""; - style.* = @intFromEnum(synFor(name)); + style.* = @backingInt(synFor(name)); if (style.* == 0) query.disableCapture(name); } const parser = ts.Parser.create(); @@ -965,11 +965,11 @@ test "syntax formatted locations color hidden context and preserve multiline sou const styles = try highlightLocationRows(gpa, content, &rows); defer gpa.free(styles); const body = std.mem.indexOf(u8, content, "comment body").?; - try std.testing.expectEqual(@intFromEnum(Syn.comment), styles[body]); - try std.testing.expectEqual(@intFromEnum(Syn.none), styles[body - 1]); + try std.testing.expectEqual(@backingInt(Syn.comment), styles[body]); + try std.testing.expectEqual(@backingInt(Syn.none), styles[body - 1]); const number = std.mem.indexOf(u8, content, "42").?; - try std.testing.expectEqual(@intFromEnum(Syn.number), styles[number]); - try std.testing.expectEqual(@intFromEnum(Syn.none), styles[0]); + try std.testing.expectEqual(@backingInt(Syn.number), styles[number]); + try std.testing.expectEqual(@backingInt(Syn.none), styles[0]); } test "syntax formatted locations separate alignment from Markdown indentation" { @@ -985,8 +985,8 @@ test "syntax formatted locations separate alignment from Markdown indentation" { }; const styles = try highlightLocationRows(gpa, content, &rows); defer gpa.free(styles); - try std.testing.expectEqual(@intFromEnum(Syn.keyword), styles[std.mem.indexOf(u8, content, "Heading").?]); - try std.testing.expectEqual(@intFromEnum(Syn.string), styles[std.mem.indexOf(u8, content, "Code").?]); + try std.testing.expectEqual(@backingInt(Syn.keyword), styles[std.mem.indexOf(u8, content, "Heading").?]); + try std.testing.expectEqual(@backingInt(Syn.string), styles[std.mem.indexOf(u8, content, "Code").?]); } fn inject(styles: []u8, source: []const u8, node: ts.Node, markdown: bool) void { const kind = node.kind(); @@ -1149,7 +1149,7 @@ pub fn highlightDiffRows(gpa: std.mem.Allocator, content: []const u8, start_raw: .meta, .old_path, .new_path => .comment, else => .none, }; - if (style != .none) window.fill(at, nl - at, @intFromEnum(style)); + if (style != .none) window.fill(at, nl - at, @backingInt(style)); } if (nl >= content.len) break; at = nl + 1; @@ -1192,10 +1192,10 @@ fn paintDiffPiece(gpa: std.mem.Allocator, window: anytype, bytes: []const u8, at for (kinds) |kind| { const line = lines.next() orelse break; const style: u8 = switch (kind) { - .added => @intFromEnum(Syn.string) | diff_added, - .removed => @intFromEnum(Syn.number) | diff_removed, - .no_newline => @intFromEnum(Syn.comment), - .hunk => @intFromEnum(Syn.keyword), + .added => @backingInt(Syn.string) | diff_added, + .removed => @backingInt(Syn.number) | diff_removed, + .no_newline => @backingInt(Syn.comment), + .hunk => @backingInt(Syn.keyword), else => 0, }; if (style != 0) window.fill(at + offset, line.len, style); @@ -1273,8 +1273,8 @@ fn paintHunk(gpa: std.mem.Allocator, out: []u8, bytes: []const u8, kinds: []cons .removed => @memcpy(dst, old_colors[old_at..][0..code_len]), .added => @memcpy(dst, new_colors[new_at..][0..code_len]), .context => @memcpy(dst, if (context_new) new_colors[new_at..][0..code_len] else old_colors[old_at..][0..code_len]), - .no_newline => @memset(out[offset..][0..line.len], @intFromEnum(Syn.comment)), - .hunk => @memset(out[offset..][0..line.len], @intFromEnum(Syn.keyword)), + .no_newline => @memset(out[offset..][0..line.len], @backingInt(Syn.comment)), + .hunk => @memset(out[offset..][0..line.len], @backingInt(Syn.keyword)), else => {}, } if (kind == .context or kind == .removed) old_at += code_len + 1; @@ -1322,8 +1322,8 @@ test "syntax a results row is coloured by the file its location names" { try std.testing.expectEqual(content.len, styles.len); for (styles[0.."src/a.zig:1:1".len]) |b| try std.testing.expectEqual(@as(u8, 0), b); const zig_kw = std.mem.indexOf(u8, content, "struct").?; - try std.testing.expectEqual(@intFromEnum(Syn.keyword), styles[zig_kw]); - try std.testing.expectEqual(@intFromEnum(Syn.keyword), styles[zig_kw + 5]); + try std.testing.expectEqual(@backingInt(Syn.keyword), styles[zig_kw]); + try std.testing.expectEqual(@backingInt(Syn.keyword), styles[zig_kw + 5]); const prose = std.mem.indexOf(u8, content, "just some prose").?; for (styles[prose .. prose + 14]) |b| try std.testing.expectEqual(@as(u8, 0), b); const bare = std.mem.indexOf(u8, content, "src/c.zig").?; @@ -1371,14 +1371,14 @@ test "syntax default full grammar set highlights Typst source" { const keyword_at = std.mem.indexOf(u8, source, "let").?; const number_at = std.mem.indexOf(u8, source, "42").?; const string_at = std.mem.indexOf(u8, source, "\"hello\"").?; - try std.testing.expectEqual(Syn.comment, @as(Syn, @enumFromInt(styles[comment_at]))); - try std.testing.expectEqual(Syn.keyword, @as(Syn, @enumFromInt(styles[keyword_at]))); - try std.testing.expectEqual(Syn.number, @as(Syn, @enumFromInt(styles[number_at]))); - try std.testing.expectEqual(Syn.string, @as(Syn, @enumFromInt(styles[string_at]))); + try std.testing.expectEqual(Syn.comment, @as(Syn, @fromBackingInt(@intCast(styles[comment_at])))); + try std.testing.expectEqual(Syn.keyword, @as(Syn, @fromBackingInt(@intCast(styles[keyword_at])))); + try std.testing.expectEqual(Syn.number, @as(Syn, @fromBackingInt(@intCast(styles[number_at])))); + try std.testing.expectEqual(Syn.string, @as(Syn, @fromBackingInt(@intCast(styles[string_at])))); const short_ext = try highlightFileRange(std.testing.allocator, "paper.typ", source, 0, source.len); defer std.testing.allocator.free(short_ext); - try std.testing.expectEqual(Syn.keyword, @as(Syn, @enumFromInt(short_ext[keyword_at]))); + try std.testing.expectEqual(Syn.keyword, @as(Syn, @fromBackingInt(@intCast(short_ext[keyword_at])))); } test "syntax Typst markup constructs paint and raw blocks inject their language" { @@ -1403,7 +1403,7 @@ test "syntax Typst markup constructs paint and raw blocks inject their language" const synAt = struct { fn f(s: []const u8, src: []const u8, needle: []const u8, offset: usize) Syn { - return @enumFromInt(s[std.mem.indexOf(u8, src, needle).? + offset]); + return @fromBackingInt(@intCast(s[std.mem.indexOf(u8, src, needle).? + offset])); } }.f; try std.testing.expectEqual(Syn.keyword, synAt(styles, source, "= Heading", 0)); @@ -1443,7 +1443,7 @@ test "syntax markdown highlights markup, injects inline spans and fenced code bl const synAt = struct { fn f(s: []const u8, src: []const u8, needle: []const u8, offset: usize) Syn { - return @enumFromInt(s[std.mem.indexOf(u8, src, needle).? + offset]); + return @fromBackingInt(@intCast(s[std.mem.indexOf(u8, src, needle).? + offset])); } }.f; try std.testing.expectEqual(Syn.keyword, synAt(styles, source, "Title", 0)); @@ -1471,8 +1471,8 @@ test "syntax inline fast path agrees with full Markdown query" { const actual = try std.testing.allocator.alloc(u8, source.len); defer std.testing.allocator.free(actual); for ([_]Syn{ .none, .keyword }) |background| { - @memset(expected, @intFromEnum(background)); - @memset(actual, @intFromEnum(background)); + @memset(expected, @backingInt(background)); + @memset(actual, @backingInt(background)); runQuery(expected, sel, tree, 0); inject(actual, source, tree.rootNode(), true); if (!std.mem.eql(u8, expected, actual)) std.debug.print("inline mismatch: {s}\n", .{source}); @@ -1511,9 +1511,9 @@ test "syntax plain Markdown keeps block styles without starting the inline parse const source = "# Heading\n\nPlain prose.\n\n indented code\n"; const styles = try highlightFileRange(std.testing.allocator, "a.md", source, 0, source.len); defer std.testing.allocator.free(styles); - try std.testing.expectEqual(@intFromEnum(Syn.keyword), styles[2]); - try std.testing.expectEqual(@intFromEnum(Syn.none), styles[std.mem.indexOf(u8, source, "Plain").?]); - try std.testing.expectEqual(@intFromEnum(Syn.string), styles[std.mem.indexOf(u8, source, "indented").?]); + try std.testing.expectEqual(@backingInt(Syn.keyword), styles[2]); + try std.testing.expectEqual(@backingInt(Syn.none), styles[std.mem.indexOf(u8, source, "Plain").?]); + try std.testing.expectEqual(@backingInt(Syn.string), styles[std.mem.indexOf(u8, source, "indented").?]); for (specs) |spec| { if (std.mem.eql(u8, spec.name, "markdown_inline")) try std.testing.expect(spec.selected == null); } @@ -1544,7 +1544,7 @@ test "syntax highlightDiff colors unified diff lines by prefix" { } fn diffSynAt(styles: []const u8, text: []const u8, needle: []const u8, offset: usize) Syn { - return @enumFromInt(styles[std.mem.indexOf(u8, text, needle).? + offset] & syn_bits); + return @fromBackingInt(@intCast(styles[std.mem.indexOf(u8, text, needle).? + offset] & syn_bits)); } test "syntax a Zig hunk is coloured as Zig, each side parsed whole" { @@ -1715,7 +1715,7 @@ test "syntax a hunk painted once is kept, and a long one is parsed in pieces" { const at = std.mem.indexOf(u8, content, "+const v1000 ").?; const window = try highlightDiff(gpa, content, at, at + 200); defer gpa.free(window); - try std.testing.expectEqual(Syn.number, @as(Syn, @enumFromInt(window["+const v1000 = ".len] & syn_bits))); + try std.testing.expectEqual(Syn.number, @as(Syn, @fromBackingInt(@intCast(window["+const v1000 = ".len] & syn_bits)))); var cached: usize = 0; for (diff_pieces) |slot| if (slot) |piece| { cached += 1; @@ -1780,7 +1780,7 @@ test "syntax query filtering preserves upstream colors" { reference.query = raw_query; reference.capture_styles = try std.testing.allocator.alloc(u8, raw_query.captureCount()); defer std.testing.allocator.free(reference.capture_styles); - for (reference.capture_styles, 0..) |*style, id| style.* = @intFromEnum(synFor(raw_query.captureNameForId(@intCast(id)) orelse "")); + for (reference.capture_styles, 0..) |*style, id| style.* = @backingInt(synFor(raw_query.captureNameForId(@intCast(id)) orelse "")); const tree = selected.parser.parseString(source, null) orelse return error.ParseFailed; defer tree.destroy(); var expected: [source.len]u8 = @splat(0); @@ -1806,8 +1806,8 @@ test "syntax Zig keyword captures cover both bytes beyond line ten thousand" { defer std.testing.allocator.free(styles); for ([_][]const u8{ "fn", "if" }) |keyword| { const at = std.mem.indexOf(u8, code, keyword).?; - try std.testing.expectEqual(@intFromEnum(Syn.keyword), styles[at]); - try std.testing.expectEqual(@intFromEnum(Syn.keyword), styles[at + 1]); + try std.testing.expectEqual(@backingInt(Syn.keyword), styles[at]); + try std.testing.expectEqual(@backingInt(Syn.keyword), styles[at + 1]); } } @@ -1823,8 +1823,8 @@ test "syntax allocator switching clears default-runtime caches" { const restored = try highlightFileRange(std.testing.allocator, "a.zig", source, 0, source.len); defer std.testing.allocator.free(restored); defer stop(); - try std.testing.expectEqual(@intFromEnum(Syn.keyword), restored[0]); - try std.testing.expectEqual(@intFromEnum(Syn.keyword), restored[1]); + try std.testing.expectEqual(@backingInt(Syn.keyword), restored[0]); + try std.testing.expectEqual(@backingInt(Syn.keyword), restored[1]); } test "syntax location context snapshots retain omitted multiline comment scope" { @@ -1848,8 +1848,8 @@ test "syntax location context snapshots retain omitted multiline comment scope" const styles = try highlightLocationRows(gpa, content, &rows); defer gpa.free(styles); for (styles[rows[0].code_start..][0..code.len]) |style| - try std.testing.expectEqual(@intFromEnum(Syn.comment), style); - try std.testing.expectEqual(@intFromEnum(Syn.none), styles[0]); + try std.testing.expectEqual(@backingInt(Syn.comment), style); + try std.testing.expectEqual(@backingInt(Syn.none), styles[0]); } test "syntax declaration locations clear snapshots without muting ordinary context" { @@ -1875,7 +1875,7 @@ test "syntax declaration locations clear snapshots without muting ordinary conte const styles = try highlightLocationRows(gpa, content, &rows); defer gpa.free(styles); for (styles[3..][0..header.len]) |style| try std.testing.expectEqual(@as(u8, 0), style); - try std.testing.expectEqual(@intFromEnum(Syn.number), styles[std.mem.indexOf(u8, content, "42").?]); + try std.testing.expectEqual(@backingInt(Syn.number), styles[std.mem.indexOf(u8, content, "42").?]); } test "syntax stacked addresses do not split multiline source groups" { @@ -1895,11 +1895,11 @@ test "syntax stacked addresses do not split multiline source groups" { }; const styles = try highlightLocationRows(gpa, content, &rows); defer gpa.free(styles); - try std.testing.expectEqual(@intFromEnum(Syn.comment), styles[std.mem.indexOf(u8, content, "42").?]); - try std.testing.expectEqual(@intFromEnum(Syn.number), styles[std.mem.indexOf(u8, content, "7;").?]); + try std.testing.expectEqual(@backingInt(Syn.comment), styles[std.mem.indexOf(u8, content, "42").?]); + try std.testing.expectEqual(@backingInt(Syn.number), styles[std.mem.indexOf(u8, content, "7;").?]); for ([_][]const u8{ "a.c:1:1", "a.c:2:1", "a.c:3:1" }) |label| { const at = std.mem.indexOf(u8, content, label).?; - for (styles[at..][0..label.len]) |style| try std.testing.expectEqual(@intFromEnum(Syn.none), style); + for (styles[at..][0..label.len]) |style| try std.testing.expectEqual(@backingInt(Syn.none), style); } } diff --git a/src/terminal.zig b/src/terminal.zig index a8e7931c..33ad22e6 100644 --- a/src/terminal.zig +++ b/src/terminal.zig @@ -1347,7 +1347,7 @@ pub fn forwardKey(p: *Pardes, id: usize, key: Key) void { pub fn enterTty(p: *Pardes, id: usize) void { const pane = p.panes[id] orelse return; - const selected = pane.rawPointerText(pane.sel[@intFromEnum(config.select_button)]) != null; + const selected = pane.rawPointerText(pane.sel[@backingInt(config.select_button)]) != null; if (comptime enabled) if (!selected and pane.terminal != null and pane.body.cur_pinned and pane.terminal.?.vt.cursorIsAtPrompt()) handoff: { const screen = pane.terminal.?.vt.screens.active; const goff: i32 = @intCast(screen.pages.scrollbar().offset); diff --git a/src/web.zig b/src/web.zig index fed2ba5a..f89aa7e9 100644 --- a/src/web.zig +++ b/src/web.zig @@ -258,18 +258,20 @@ fn mouseWithHit(button_arg: u32, kind_arg: u32, col_arg: u32, row_arg: u32, mods 3 => .drag, else => return, }; - s.core.update(.{ .mouse = .{ - .body_hit = hit, - .tag_hit = tag_hit, - .button = button, - .kind = kind, - .col = @intCast(@min(col_arg, std.math.maxInt(u16))), - .row = @intCast(@min(row_arg, std.math.maxInt(u16))), - .ctrl = mods & 1 != 0, - // Alt-click is B2 and Cmd/Super-click B3 (mouse.emulateButton). - .alt = mods & 2 != 0, - .super = mods & 8 != 0, - } }); + s.core.update(.{ + .mouse = .{ + .body_hit = hit, + .tag_hit = tag_hit, + .button = button, + .kind = kind, + .col = @intCast(@min(col_arg, std.math.maxInt(u16))), + .row = @intCast(@min(row_arg, std.math.maxInt(u16))), + .ctrl = mods & 1 != 0, + // Alt-click is B2 and Cmd/Super-click B3 (mouse.emulateButton). + .alt = mods & 2 != 0, + .super = mods & 8 != 0, + }, + }); } export fn pardes_touch_scroll(delta: f32) void { @@ -347,7 +349,7 @@ export fn pardes_tag_layer_value(index: u32, field: u32) u32 { if (layer.rows == 0) return 0; return switch (field) { 0 => layer.cols, - 1 => @intFromEnum(layer.kind), + 1 => @backingInt(layer.kind), 2 => layer.id, 3 => layer.serial, 4 => layer.viewport.x, @@ -421,7 +423,7 @@ export fn pardes_row_metrics(body_w: u16, body_h: u16, tagline_w: u16, tagline_h export fn pardes_pointer_shape() u32 { const s = &(state orelse return 0); - return @intFromEnum(s.core.surface.pointer_shape); + return @backingInt(s.core.surface.pointer_shape); } export fn pardes_cursor_y() i32 { @@ -557,6 +559,6 @@ fn encodeAttrs(style: pardes.CellStyle) u16 { attrs |= @as(u16, @intFromBool(style.invisible)) << 5; attrs |= @as(u16, @intFromBool(style.strikethrough)) << 6; attrs |= @as(u16, @intFromBool(style.font_role == .tagline)) * attr_tagline; - attrs |= @as(u16, @intFromEnum(style.ul)) << 8; + attrs |= @as(u16, @backingInt(style.ul)) << 8; return attrs; } diff --git a/test/deck/buttons.zon b/test/deck/buttons.zon index 8b3ae7f8..50d9c70c 100644 --- a/test/deck/buttons.zon +++ b/test/deck/buttons.zon @@ -1,81 +1,81 @@ .{ .version = 1, .events = .{ -.{.t=3700753450,.pad=2,.ev=.{.button=.{.idx=10,.down=true}}}, -.{.t=3900818994,.pad=2,.ev=.{.button=.{.idx=10,.down=false}}}, -.{.t=3956546622,.pad=2,.ev=.{.button=.{.idx=9,.down=true}}}, -.{.t=4123264775,.pad=2,.ev=.{.button=.{.idx=9,.down=false}}}, -.{.t=4930702402,.pad=2,.ev=.{.button=.{.idx=8,.down=true}}}, -.{.t=5145495294,.pad=2,.ev=.{.button=.{.idx=8,.down=false}}}, -.{.t=5256748340,.pad=2,.ev=.{.button=.{.idx=7,.down=true}}}, -.{.t=5467530268,.pad=2,.ev=.{.button=.{.idx=7,.down=false}}}, -.{.t=6756403713,.pad=2,.ev=.{.button=.{.idx=2,.down=true}}}, -.{.t=6911854483,.pad=2,.ev=.{.button=.{.idx=2,.down=false}}}, -.{.t=7211860980,.pad=2,.ev=.{.button=.{.idx=3,.down=true}}}, -.{.t=7389532087,.pad=2,.ev=.{.button=.{.idx=3,.down=false}}}, -.{.t=8133944867,.pad=2,.ev=.{.button=.{.idx=3,.down=true}}}, -.{.t=8289426557,.pad=2,.ev=.{.button=.{.idx=3,.down=false}}}, -.{.t=9089438184,.pad=2,.ev=.{.button=.{.idx=5,.down=true}}}, -.{.t=9234016011,.pad=2,.ev=.{.button=.{.idx=2,.down=true}}}, -.{.t=9356447170,.pad=2,.ev=.{.button=.{.idx=2,.down=false}}}, -.{.t=9500690066,.pad=2,.ev=.{.button=.{.idx=5,.down=false}}}, -.{.t=10234132592,.pad=2,.ev=.{.button=.{.idx=5,.down=true}}}, -.{.t=10389693142,.pad=2,.ev=.{.button=.{.idx=2,.down=true}}}, -.{.t=10500635738,.pad=2,.ev=.{.button=.{.idx=2,.down=false}}}, -.{.t=10600562571,.pad=2,.ev=.{.button=.{.idx=5,.down=false}}}, -.{.t=11211884827,.pad=2,.ev=.{.button=.{.idx=3,.down=true}}}, -.{.t=11333789807,.pad=2,.ev=.{.button=.{.idx=3,.down=false}}}, -.{.t=11622673840,.pad=2,.ev=.{.button=.{.idx=3,.down=true}}}, -.{.t=11778210450,.pad=2,.ev=.{.button=.{.idx=3,.down=false}}}, -.{.t=12056066449,.pad=2,.ev=.{.button=.{.idx=0,.down=true}}}, -.{.t=12200470216,.pad=2,.ev=.{.button=.{.idx=0,.down=false}}}, -.{.t=13122626673,.pad=2,.ev=.{.button=.{.idx=1,.down=true}}}, -.{.t=13256318175,.pad=2,.ev=.{.button=.{.idx=1,.down=false}}}, -.{.t=30877608417,.pad=2,.ev=.{.button=.{.idx=13,.down=true}}}, -.{.t=30932947265,.pad=2,.ev=.{.button=.{.idx=13,.down=false}}}, -.{.t=31188916557,.pad=2,.ev=.{.button=.{.idx=14,.down=true}}}, -.{.t=31344392047,.pad=2,.ev=.{.button=.{.idx=14,.down=false}}}, -.{.t=31355303161,.pad=2,.ev=.{.button=.{.idx=11,.down=true}}}, -.{.t=31377574308,.pad=2,.ev=.{.button=.{.idx=11,.down=false}}}, -.{.t=31377580618,.pad=2,.ev=.{.button=.{.idx=11,.down=true}}}, -.{.t=31533158438,.pad=2,.ev=.{.button=.{.idx=11,.down=false}}}, -.{.t=31599806330,.pad=2,.ev=.{.button=.{.idx=12,.down=true}}}, -.{.t=31699701622,.pad=2,.ev=.{.button=.{.idx=14,.down=true}}}, -.{.t=31699711442,.pad=2,.ev=.{.button=.{.idx=12,.down=false}}}, -.{.t=31833163995,.pad=2,.ev=.{.button=.{.idx=14,.down=false}}}, -.{.t=31844214668,.pad=2,.ev=.{.button=.{.idx=11,.down=true}}}, -.{.t=31933218167,.pad=2,.ev=.{.button=.{.idx=11,.down=false}}}, -.{.t=31944106321,.pad=2,.ev=.{.button=.{.idx=13,.down=true}}}, -.{.t=31944118861,.pad=2,.ev=.{.button=.{.idx=13,.down=false}}}, -.{.t=32577585424,.pad=2,.ev=.{.button=.{.idx=7,.down=true}}}, -.{.t=32777404849,.pad=2,.ev=.{.button=.{.idx=7,.down=false}}}, -.{.t=32932893939,.pad=2,.ev=.{.button=.{.idx=8,.down=true}}}, -.{.t=33122371409,.pad=2,.ev=.{.button=.{.idx=8,.down=false}}}, -.{.t=34899667922,.pad=2,.ev=.{.button=.{.idx=10,.down=true}}}, -.{.t=35143908581,.pad=2,.ev=.{.button=.{.idx=10,.down=false}}}, -.{.t=35143918751,.pad=2,.ev=.{.button=.{.idx=9,.down=true}}}, -.{.t=35299532711,.pad=2,.ev=.{.button=.{.idx=9,.down=false}}}, -.{.t=36188307687,.pad=2,.ev=.{.button=.{.idx=10,.down=true}}}, -.{.t=36351697335,.pad=2,.ev=.{.button=.{.idx=9,.down=true}}}, -.{.t=36399712574,.pad=2,.ev=.{.button=.{.idx=10,.down=false}}}, -.{.t=36521680424,.pad=2,.ev=.{.button=.{.idx=10,.down=true}}}, -.{.t=36543814231,.pad=2,.ev=.{.button=.{.idx=9,.down=false}}}, -.{.t=36688528867,.pad=2,.ev=.{.button=.{.idx=10,.down=false}}}, -.{.t=38810548641,.pad=2,.ev=.{.button=.{.idx=8,.down=true}}}, -.{.t=38988265258,.pad=2,.ev=.{.button=.{.idx=8,.down=false}}}, -.{.t=39421485428,.pad=2,.ev=.{.button=.{.idx=7,.down=true}}}, -.{.t=39521563760,.pad=2,.ev=.{.button=.{.idx=8,.down=true}}}, -.{.t=39543869347,.pad=2,.ev=.{.button=.{.idx=7,.down=false}}}, -.{.t=39654975672,.pad=2,.ev=.{.button=.{.idx=8,.down=false}}}, -.{.t=40199575307,.pad=2,.ev=.{.button=.{.idx=0,.down=true}}}, -.{.t=40388115109,.pad=2,.ev=.{.button=.{.idx=0,.down=false}}}, -.{.t=40810375225,.pad=2,.ev=.{.button=.{.idx=2,.down=true}}}, -.{.t=40976868838,.pad=2,.ev=.{.button=.{.idx=2,.down=false}}}, -.{.t=41032455046,.pad=2,.ev=.{.button=.{.idx=3,.down=true}}}, -.{.t=41243668724,.pad=2,.ev=.{.button=.{.idx=3,.down=false}}}, -.{.t=42565700760,.pad=2,.ev=.{.button=.{.idx=2,.down=true}}}, -.{.t=42743538487,.pad=2,.ev=.{.button=.{.idx=2,.down=false}}}, -.{.t=43676697498,.pad=2,.ev=.{.button=.{.idx=5,.down=true}}}, -.{.t=43932510879,.pad=2,.ev=.{.button=.{.idx=5,.down=false}}}, -.{.t=43943745523,.pad=2,.ev=.{.button=.{.idx=1,.down=true}}}, -.{.t=44021582808,.pad=2,.ev=.{.button=.{.idx=1,.down=false}}}, -.{.t=44599100514,.pad=2,.ev=.{.button=.{.idx=1,.down=true}}}, + .{ .t = 3700753450, .pad = 2, .ev = .{ .button = .{ .idx = 10, .down = true } } }, + .{ .t = 3900818994, .pad = 2, .ev = .{ .button = .{ .idx = 10, .down = false } } }, + .{ .t = 3956546622, .pad = 2, .ev = .{ .button = .{ .idx = 9, .down = true } } }, + .{ .t = 4123264775, .pad = 2, .ev = .{ .button = .{ .idx = 9, .down = false } } }, + .{ .t = 4930702402, .pad = 2, .ev = .{ .button = .{ .idx = 8, .down = true } } }, + .{ .t = 5145495294, .pad = 2, .ev = .{ .button = .{ .idx = 8, .down = false } } }, + .{ .t = 5256748340, .pad = 2, .ev = .{ .button = .{ .idx = 7, .down = true } } }, + .{ .t = 5467530268, .pad = 2, .ev = .{ .button = .{ .idx = 7, .down = false } } }, + .{ .t = 6756403713, .pad = 2, .ev = .{ .button = .{ .idx = 2, .down = true } } }, + .{ .t = 6911854483, .pad = 2, .ev = .{ .button = .{ .idx = 2, .down = false } } }, + .{ .t = 7211860980, .pad = 2, .ev = .{ .button = .{ .idx = 3, .down = true } } }, + .{ .t = 7389532087, .pad = 2, .ev = .{ .button = .{ .idx = 3, .down = false } } }, + .{ .t = 8133944867, .pad = 2, .ev = .{ .button = .{ .idx = 3, .down = true } } }, + .{ .t = 8289426557, .pad = 2, .ev = .{ .button = .{ .idx = 3, .down = false } } }, + .{ .t = 9089438184, .pad = 2, .ev = .{ .button = .{ .idx = 5, .down = true } } }, + .{ .t = 9234016011, .pad = 2, .ev = .{ .button = .{ .idx = 2, .down = true } } }, + .{ .t = 9356447170, .pad = 2, .ev = .{ .button = .{ .idx = 2, .down = false } } }, + .{ .t = 9500690066, .pad = 2, .ev = .{ .button = .{ .idx = 5, .down = false } } }, + .{ .t = 10234132592, .pad = 2, .ev = .{ .button = .{ .idx = 5, .down = true } } }, + .{ .t = 10389693142, .pad = 2, .ev = .{ .button = .{ .idx = 2, .down = true } } }, + .{ .t = 10500635738, .pad = 2, .ev = .{ .button = .{ .idx = 2, .down = false } } }, + .{ .t = 10600562571, .pad = 2, .ev = .{ .button = .{ .idx = 5, .down = false } } }, + .{ .t = 11211884827, .pad = 2, .ev = .{ .button = .{ .idx = 3, .down = true } } }, + .{ .t = 11333789807, .pad = 2, .ev = .{ .button = .{ .idx = 3, .down = false } } }, + .{ .t = 11622673840, .pad = 2, .ev = .{ .button = .{ .idx = 3, .down = true } } }, + .{ .t = 11778210450, .pad = 2, .ev = .{ .button = .{ .idx = 3, .down = false } } }, + .{ .t = 12056066449, .pad = 2, .ev = .{ .button = .{ .idx = 0, .down = true } } }, + .{ .t = 12200470216, .pad = 2, .ev = .{ .button = .{ .idx = 0, .down = false } } }, + .{ .t = 13122626673, .pad = 2, .ev = .{ .button = .{ .idx = 1, .down = true } } }, + .{ .t = 13256318175, .pad = 2, .ev = .{ .button = .{ .idx = 1, .down = false } } }, + .{ .t = 30877608417, .pad = 2, .ev = .{ .button = .{ .idx = 13, .down = true } } }, + .{ .t = 30932947265, .pad = 2, .ev = .{ .button = .{ .idx = 13, .down = false } } }, + .{ .t = 31188916557, .pad = 2, .ev = .{ .button = .{ .idx = 14, .down = true } } }, + .{ .t = 31344392047, .pad = 2, .ev = .{ .button = .{ .idx = 14, .down = false } } }, + .{ .t = 31355303161, .pad = 2, .ev = .{ .button = .{ .idx = 11, .down = true } } }, + .{ .t = 31377574308, .pad = 2, .ev = .{ .button = .{ .idx = 11, .down = false } } }, + .{ .t = 31377580618, .pad = 2, .ev = .{ .button = .{ .idx = 11, .down = true } } }, + .{ .t = 31533158438, .pad = 2, .ev = .{ .button = .{ .idx = 11, .down = false } } }, + .{ .t = 31599806330, .pad = 2, .ev = .{ .button = .{ .idx = 12, .down = true } } }, + .{ .t = 31699701622, .pad = 2, .ev = .{ .button = .{ .idx = 14, .down = true } } }, + .{ .t = 31699711442, .pad = 2, .ev = .{ .button = .{ .idx = 12, .down = false } } }, + .{ .t = 31833163995, .pad = 2, .ev = .{ .button = .{ .idx = 14, .down = false } } }, + .{ .t = 31844214668, .pad = 2, .ev = .{ .button = .{ .idx = 11, .down = true } } }, + .{ .t = 31933218167, .pad = 2, .ev = .{ .button = .{ .idx = 11, .down = false } } }, + .{ .t = 31944106321, .pad = 2, .ev = .{ .button = .{ .idx = 13, .down = true } } }, + .{ .t = 31944118861, .pad = 2, .ev = .{ .button = .{ .idx = 13, .down = false } } }, + .{ .t = 32577585424, .pad = 2, .ev = .{ .button = .{ .idx = 7, .down = true } } }, + .{ .t = 32777404849, .pad = 2, .ev = .{ .button = .{ .idx = 7, .down = false } } }, + .{ .t = 32932893939, .pad = 2, .ev = .{ .button = .{ .idx = 8, .down = true } } }, + .{ .t = 33122371409, .pad = 2, .ev = .{ .button = .{ .idx = 8, .down = false } } }, + .{ .t = 34899667922, .pad = 2, .ev = .{ .button = .{ .idx = 10, .down = true } } }, + .{ .t = 35143908581, .pad = 2, .ev = .{ .button = .{ .idx = 10, .down = false } } }, + .{ .t = 35143918751, .pad = 2, .ev = .{ .button = .{ .idx = 9, .down = true } } }, + .{ .t = 35299532711, .pad = 2, .ev = .{ .button = .{ .idx = 9, .down = false } } }, + .{ .t = 36188307687, .pad = 2, .ev = .{ .button = .{ .idx = 10, .down = true } } }, + .{ .t = 36351697335, .pad = 2, .ev = .{ .button = .{ .idx = 9, .down = true } } }, + .{ .t = 36399712574, .pad = 2, .ev = .{ .button = .{ .idx = 10, .down = false } } }, + .{ .t = 36521680424, .pad = 2, .ev = .{ .button = .{ .idx = 10, .down = true } } }, + .{ .t = 36543814231, .pad = 2, .ev = .{ .button = .{ .idx = 9, .down = false } } }, + .{ .t = 36688528867, .pad = 2, .ev = .{ .button = .{ .idx = 10, .down = false } } }, + .{ .t = 38810548641, .pad = 2, .ev = .{ .button = .{ .idx = 8, .down = true } } }, + .{ .t = 38988265258, .pad = 2, .ev = .{ .button = .{ .idx = 8, .down = false } } }, + .{ .t = 39421485428, .pad = 2, .ev = .{ .button = .{ .idx = 7, .down = true } } }, + .{ .t = 39521563760, .pad = 2, .ev = .{ .button = .{ .idx = 8, .down = true } } }, + .{ .t = 39543869347, .pad = 2, .ev = .{ .button = .{ .idx = 7, .down = false } } }, + .{ .t = 39654975672, .pad = 2, .ev = .{ .button = .{ .idx = 8, .down = false } } }, + .{ .t = 40199575307, .pad = 2, .ev = .{ .button = .{ .idx = 0, .down = true } } }, + .{ .t = 40388115109, .pad = 2, .ev = .{ .button = .{ .idx = 0, .down = false } } }, + .{ .t = 40810375225, .pad = 2, .ev = .{ .button = .{ .idx = 2, .down = true } } }, + .{ .t = 40976868838, .pad = 2, .ev = .{ .button = .{ .idx = 2, .down = false } } }, + .{ .t = 41032455046, .pad = 2, .ev = .{ .button = .{ .idx = 3, .down = true } } }, + .{ .t = 41243668724, .pad = 2, .ev = .{ .button = .{ .idx = 3, .down = false } } }, + .{ .t = 42565700760, .pad = 2, .ev = .{ .button = .{ .idx = 2, .down = true } } }, + .{ .t = 42743538487, .pad = 2, .ev = .{ .button = .{ .idx = 2, .down = false } } }, + .{ .t = 43676697498, .pad = 2, .ev = .{ .button = .{ .idx = 5, .down = true } } }, + .{ .t = 43932510879, .pad = 2, .ev = .{ .button = .{ .idx = 5, .down = false } } }, + .{ .t = 43943745523, .pad = 2, .ev = .{ .button = .{ .idx = 1, .down = true } } }, + .{ .t = 44021582808, .pad = 2, .ev = .{ .button = .{ .idx = 1, .down = false } } }, + .{ .t = 44599100514, .pad = 2, .ev = .{ .button = .{ .idx = 1, .down = true } } }, } } diff --git a/test/deck/lpad-swipe.zon b/test/deck/lpad-swipe.zon index 33a17751..d5b5049a 100644 --- a/test/deck/lpad-swipe.zon +++ b/test/deck/lpad-swipe.zon @@ -1,163 +1,163 @@ .{ .version = 1, .events = .{ -.{.t=28555347100,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.29483032,.y=0.24435425,.pressure=0.0022583008}}}, -.{.t=28555355490,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.2937622,.y=0.24847412,.pressure=0.0015563965}}}, -.{.t=28566662333,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.2920227,.y=0.25350952,.pressure=0.00048828125}}}, -.{.t=28566669273,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.up,.x=0.28912354,.y=0.25863647,.pressure=0}}}, -.{.t=28633190705,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.down,.x=0.26437378,.y=0.44036865,.pressure=0.0008239746}}}, -.{.t=28644226129,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.2635193,.y=0.44857788,.pressure=0.0008239746}}}, -.{.t=28644235079,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.26348877,.y=0.4538269,.pressure=0.0015563965}}}, -.{.t=28644241049,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.26272583,.y=0.45950317,.pressure=0.003692627}}}, -.{.t=28655363472,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.26229858,.y=0.46218872,.pressure=0.0047912598}}}, -.{.t=28655373032,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.26153564,.y=0.46594238,.pressure=0.005493164}}}, -.{.t=28666533886,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.2607727,.y=0.46810913,.pressure=0.008026123}}}, -.{.t=28666541736,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.26037598,.y=0.46969604,.pressure=0.00982666}}}, -.{.t=28666544986,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.26004028,.y=0.47079468,.pressure=0.010894775}}}, -.{.t=28677510399,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.25985718,.y=0.47192383,.pressure=0.011962891}}}, -.{.t=28677516759,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.25924683,.y=0.47277832,.pressure=0.013061523}}}, -.{.t=28677520229,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.25894165,.y=0.47366333,.pressure=0.01449585}}}, -.{.t=28688736483,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.25906372,.y=0.47409058,.pressure=0.015197754}}}, -.{.t=28688747523,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.25872803,.y=0.47351074,.pressure=0.013061523}}}, -.{.t=28688752063,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.25827026,.y=0.4732666,.pressure=0.013397217}}}, -.{.t=28699780696,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.2581787,.y=0.47317505,.pressure=0.014129639}}}, -.{.t=28699788576,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.25759888,.y=0.47305298,.pressure=0.014831543}}}, -.{.t=28699792416,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.25787354,.y=0.47280884,.pressure=0.01449585}}}, -.{.t=28711058720,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.25784302,.y=0.47225952,.pressure=0.013763428}}}, -.{.t=28711073040,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.25738525,.y=0.472229,.pressure=0.014129639}}}, -.{.t=28722312593,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.25720215,.y=0.4717102,.pressure=0.013763428}}}, -.{.t=28722328533,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.2572937,.y=0.47213745,.pressure=0.012329102}}}, -.{.t=28722335123,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.2576294,.y=0.4721985,.pressure=0.01449585}}}, -.{.t=28733104547,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.25784302,.y=0.4718933,.pressure=0.013763428}}}, -.{.t=28733113157,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.2571411,.y=0.472229,.pressure=0.013763428}}}, -.{.t=28733116517,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.256958,.y=0.47235107,.pressure=0.010894775}}}, -.{.t=28744542840,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.25598145,.y=0.47323608,.pressure=0.011962891}}}, -.{.t=28744554360,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.25558472,.y=0.47372437,.pressure=0.012329102}}}, -.{.t=28744558310,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.25463867,.y=0.47329712,.pressure=0.013061523}}}, -.{.t=28755164615,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.2541809,.y=0.4736023,.pressure=0.013397217}}}, -.{.t=28755173055,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.2536316,.y=0.47485352,.pressure=0.013397217}}}, -.{.t=28766369408,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.2527771,.y=0.4749756,.pressure=0.011962891}}}, -.{.t=28766376998,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.2524109,.y=0.47543335,.pressure=0.011962891}}}, -.{.t=28766380848,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.2518921,.y=0.4761963,.pressure=0.011962891}}}, -.{.t=28777479342,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.25073242,.y=0.4764099,.pressure=0.013397217}}}, -.{.t=28777487702,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.24984741,.y=0.4772644,.pressure=0.015197754}}}, -.{.t=28777491542,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.24942017,.y=0.47872925,.pressure=0.015563965}}}, -.{.t=28788858885,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.24816895,.y=0.47982788,.pressure=0.016296387}}}, -.{.t=28788869705,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.247406,.y=0.48181152,.pressure=0.016998291}}}, -.{.t=28788873665,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.24645996,.y=0.48260498,.pressure=0.015563965}}}, -.{.t=28800073548,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.2456665,.y=0.48516846,.pressure=0.01663208}}}, -.{.t=28800082148,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.24414062,.y=0.48757935,.pressure=0.018432617}}}, -.{.t=28800086718,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.2437439,.y=0.48986816,.pressure=0.019165039}}}, -.{.t=28810881362,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.2432251,.y=0.49273682,.pressure=0.017730713}}}, -.{.t=28810890602,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.24337769,.y=0.4951172,.pressure=0.018432617}}}, -.{.t=28822223135,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.24224854,.y=0.49868774,.pressure=0.018066406}}}, -.{.t=28822236725,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.2409668,.y=0.5030823,.pressure=0.018432617}}}, -.{.t=28822243035,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.24002075,.y=0.5093689,.pressure=0.017364502}}}, -.{.t=28833221849,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.23800659,.y=0.52023315,.pressure=0.017364502}}}, -.{.t=28833234799,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.23648071,.y=0.5312195,.pressure=0.018066406}}}, -.{.t=28833241859,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.23449707,.y=0.54260254,.pressure=0.018432617}}}, -.{.t=28844533292,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.23208618,.y=0.5539551,.pressure=0.019165039}}}, -.{.t=28844544902,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.22930908,.y=0.5640869,.pressure=0.020599365}}}, -.{.t=28844549012,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.22769165,.y=0.5701294,.pressure=0.022399902}}}, -.{.t=28855315576,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.22613525,.y=0.57528687,.pressure=0.023468018}}}, -.{.t=28855325516,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.22503662,.y=0.5812073,.pressure=0.02420044}}}, -.{.t=28866614540,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.22335815,.y=0.5848694,.pressure=0.02420044}}}, -.{.t=28866626480,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.22390747,.y=0.5887146,.pressure=0.024536133}}}, -.{.t=28866629910,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.22283936,.y=0.59265137,.pressure=0.024536133}}}, -.{.t=28877415724,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.22262573,.y=0.59625244,.pressure=0.025268555}}}, -.{.t=28877428004,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.22128296,.y=0.6008606,.pressure=0.025268555}}}, -.{.t=28888551597,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.2204895,.y=0.60409546,.pressure=0.025268555}}}, -.{.t=28888564767,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.21896362,.y=0.61083984,.pressure=0.025634766}}}, -.{.t=28888571967,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.21774292,.y=0.6156006,.pressure=0.025970459}}}, -.{.t=28899744701,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.21542358,.y=0.62112427,.pressure=0.02633667}}}, -.{.t=28899757861,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.21438599,.y=0.62576294,.pressure=0.027435303}}}, -.{.t=28899764601,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.21298218,.y=0.63223267,.pressure=0.027069092}}}, -.{.t=28910731865,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.21209717,.y=0.63708496,.pressure=0.02633667}}}, -.{.t=28910746485,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.21133423,.y=0.6419983,.pressure=0.02670288}}}, -.{.t=28921990138,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.21032715,.y=0.64730835,.pressure=0.027435303}}}, -.{.t=28922004158,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.2090149,.y=0.65237427,.pressure=0.027069092}}}, -.{.t=28922010498,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.20770264,.y=0.6588135,.pressure=0.02670288}}}, -.{.t=28932967412,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.20559692,.y=0.6654968,.pressure=0.025970459}}}, -.{.t=28932979792,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.20404053,.y=0.67285156,.pressure=0.025634766}}}, -.{.t=28932983492,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.20187378,.y=0.6821594,.pressure=0.024536133}}}, -.{.t=28944345285,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.19940186,.y=0.6911926,.pressure=0.02420044}}}, -.{.t=28944363135,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.19662476,.y=0.703949,.pressure=0.022033691}}}, -.{.t=28944369185,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.19250488,.y=0.71707153,.pressure=0.02130127}}}, -.{.t=28955070939,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.18859863,.y=0.7327881,.pressure=0.020599365}}}, -.{.t=28955080209,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.18469238,.y=0.7469177,.pressure=0.018798828}}}, -.{.t=28966644072,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.1803894,.y=0.76065063,.pressure=0.018066406}}}, -.{.t=28966660132,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.17681885,.y=0.7729492,.pressure=0.019165039}}}, -.{.t=28966666102,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.17303467,.y=0.78430176,.pressure=0.01953125}}}, -.{.t=28977523276,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.17047119,.y=0.79385376,.pressure=0.019165039}}}, -.{.t=28977533506,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.16790771,.y=0.8000183,.pressure=0.019866943}}}, -.{.t=28977538756,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.16583252,.y=0.8055115,.pressure=0.018798828}}}, -.{.t=28988801809,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.16448975,.y=0.8109131,.pressure=0.01953125}}}, -.{.t=28988815059,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.16299438,.y=0.81552124,.pressure=0.02130127}}}, -.{.t=28988820159,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.16275024,.y=0.8183899,.pressure=0.02166748}}}, -.{.t=29000005933,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.16235352,.y=0.8191223,.pressure=0.022399902}}}, -.{.t=29000020133,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.16220093,.y=0.820343,.pressure=0.023468018}}}, -.{.t=29000023943,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.16268921,.y=0.8208618,.pressure=0.023834229}}}, -.{.t=29010879647,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.1618042,.y=0.82214355,.pressure=0.025634766}}}, -.{.t=29010893477,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.16238403,.y=0.82196045,.pressure=0.02633667}}}, -.{.t=29022239700,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.16329956,.y=0.82180786,.pressure=0.027069092}}}, -.{.t=29022255010,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.16305542,.y=0.8227539,.pressure=0.027069092}}}, -.{.t=29022260530,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.16360474,.y=0.8215027,.pressure=0.02670288}}}, -.{.t=29033423863,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.16390991,.y=0.8215637,.pressure=0.02670288}}}, -.{.t=29033439393,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.16513062,.y=0.820282,.pressure=0.02633667}}}, -.{.t=29033446553,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.16571045,.y=0.82003784,.pressure=0.027069092}}}, -.{.t=29044100787,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.16552734,.y=0.81985474,.pressure=0.024536133}}}, -.{.t=29044110747,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.16653442,.y=0.8192444,.pressure=0.023468018}}}, -.{.t=29044114927,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.16690063,.y=0.81710815,.pressure=0.023101807}}}, -.{.t=29055305531,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.16772461,.y=0.81536865,.pressure=0.022766113}}}, -.{.t=29055315751,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.16854858,.y=0.81365967,.pressure=0.022399902}}}, -.{.t=29066613054,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.16940308,.y=0.811615,.pressure=0.02166748}}}, -.{.t=29066629614,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.17041016,.y=0.80908203,.pressure=0.02130127}}}, -.{.t=29066636804,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.17147827,.y=0.8067322,.pressure=0.02130127}}}, -.{.t=29077513018,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.17288208,.y=0.8036804,.pressure=0.019165039}}}, -.{.t=29077525768,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.17391968,.y=0.8003235,.pressure=0.015197754}}}, -.{.t=29077531158,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.17553711,.y=0.7965088,.pressure=0.014831543}}}, -.{.t=29088910511,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.17697144,.y=0.7913208,.pressure=0.015563965}}}, -.{.t=29088924801,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.17819214,.y=0.78622437,.pressure=0.01449585}}}, -.{.t=29088930391,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.17999268,.y=0.7813721,.pressure=0.013397217}}}, -.{.t=29100047575,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.18148804,.y=0.7752991,.pressure=0.014129639}}}, -.{.t=29100061535,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.1831665,.y=0.76898193,.pressure=0.014129639}}}, -.{.t=29100068045,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.184906,.y=0.7624817,.pressure=0.013763428}}}, -.{.t=29111067488,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.18692017,.y=0.7561035,.pressure=0.013061523}}}, -.{.t=29111083948,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.18884277,.y=0.7487488,.pressure=0.01449585}}}, -.{.t=29122288972,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.19082642,.y=0.7409973,.pressure=0.01449585}}}, -.{.t=29122305542,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.19223022,.y=0.73428345,.pressure=0.014831543}}}, -.{.t=29122313342,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.19274902,.y=0.7257385,.pressure=0.014831543}}}, -.{.t=29133328146,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.19299316,.y=0.714447,.pressure=0.015197754}}}, -.{.t=29133345356,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.1928711,.y=0.7018738,.pressure=0.01449585}}}, -.{.t=29133350306,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.19335938,.y=0.6808777,.pressure=0.014831543}}}, -.{.t=29144200749,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.19464111,.y=0.65582275,.pressure=0.014831543}}}, -.{.t=29144216579,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.19668579,.y=0.63186646,.pressure=0.01449585}}}, -.{.t=29144223419,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.19927979,.y=0.6045227,.pressure=0.013763428}}}, -.{.t=29154998954,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.20211792,.y=0.57891846,.pressure=0.0126953125}}}, -.{.t=29155006203,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.20501709,.y=0.551239,.pressure=0.0126953125}}}, -.{.t=29166393667,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.20880127,.y=0.5248718,.pressure=0.012329102}}}, -.{.t=29166404147,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.21270752,.y=0.499115,.pressure=0.013397217}}}, -.{.t=29166409197,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.21655273,.y=0.47366333,.pressure=0.013763428}}}, -.{.t=29177500380,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.2204895,.y=0.45114136,.pressure=0.0101623535}}}, -.{.t=29177510970,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.22451782,.y=0.4290161,.pressure=0.0101623535}}}, -.{.t=29177516230,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.2286377,.y=0.40975952,.pressure=0.0101623535}}}, -.{.t=29188832983,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.23208618,.y=0.39212036,.pressure=0.010528564}}}, -.{.t=29188846483,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.23532104,.y=0.375885,.pressure=0.007293701}}}, -.{.t=29188851103,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.23809814,.y=0.35943604,.pressure=0.009460449}}}, -.{.t=29200021967,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.24072266,.y=0.34292603,.pressure=0.011260986}}}, -.{.t=29200037067,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.24298096,.y=0.32809448,.pressure=0.011962891}}}, -.{.t=29200042877,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.24493408,.y=0.3138733,.pressure=0.010528564}}}, -.{.t=29210884631,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.24728394,.y=0.29989624,.pressure=0.012329102}}}, -.{.t=29221881625,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.24908447,.y=0.2866516,.pressure=0.011962891}}}, -.{.t=29221891355,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.250885,.y=0.2755432,.pressure=0.010528564}}}, -.{.t=29221896615,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.252594,.y=0.26571655,.pressure=0.011962891}}}, -.{.t=29233293918,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.25378418,.y=0.2571106,.pressure=0.0126953125}}}, -.{.t=29233306418,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.25476074,.y=0.24942017,.pressure=0.0126953125}}}, -.{.t=29233312238,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.25534058,.y=0.24307251,.pressure=0.011260986}}}, -.{.t=29244359261,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.25610352,.y=0.23760986,.pressure=0.0101623535}}}, -.{.t=29244375081,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.25680542,.y=0.23291016,.pressure=0.0101623535}}}, -.{.t=29244383211,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.25750732,.y=0.22824097,.pressure=0.0101623535}}}, -.{.t=29255381715,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.25823975,.y=0.22570801,.pressure=0.007659912}}}, -.{.t=29255392615,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.25909424,.y=0.2234497,.pressure=0.007293701}}}, -.{.t=29266740458,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.2599182,.y=0.22180176,.pressure=0.006225586}}}, -.{.t=29266753748,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.26089478,.y=0.22140503,.pressure=0.0051574707}}}, -.{.t=29266758978,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.26275635,.y=0.22149658,.pressure=0.0033569336}}}, + .{ .t = 28555347100, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.29483032, .y = 0.24435425, .pressure = 0.0022583008 } } }, + .{ .t = 28555355490, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.2937622, .y = 0.24847412, .pressure = 0.0015563965 } } }, + .{ .t = 28566662333, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.2920227, .y = 0.25350952, .pressure = 0.00048828125 } } }, + .{ .t = 28566669273, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .up, .x = 0.28912354, .y = 0.25863647, .pressure = 0 } } }, + .{ .t = 28633190705, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .down, .x = 0.26437378, .y = 0.44036865, .pressure = 0.0008239746 } } }, + .{ .t = 28644226129, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.2635193, .y = 0.44857788, .pressure = 0.0008239746 } } }, + .{ .t = 28644235079, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.26348877, .y = 0.4538269, .pressure = 0.0015563965 } } }, + .{ .t = 28644241049, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.26272583, .y = 0.45950317, .pressure = 0.003692627 } } }, + .{ .t = 28655363472, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.26229858, .y = 0.46218872, .pressure = 0.0047912598 } } }, + .{ .t = 28655373032, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.26153564, .y = 0.46594238, .pressure = 0.005493164 } } }, + .{ .t = 28666533886, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.2607727, .y = 0.46810913, .pressure = 0.008026123 } } }, + .{ .t = 28666541736, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.26037598, .y = 0.46969604, .pressure = 0.00982666 } } }, + .{ .t = 28666544986, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.26004028, .y = 0.47079468, .pressure = 0.010894775 } } }, + .{ .t = 28677510399, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.25985718, .y = 0.47192383, .pressure = 0.011962891 } } }, + .{ .t = 28677516759, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.25924683, .y = 0.47277832, .pressure = 0.013061523 } } }, + .{ .t = 28677520229, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.25894165, .y = 0.47366333, .pressure = 0.01449585 } } }, + .{ .t = 28688736483, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.25906372, .y = 0.47409058, .pressure = 0.015197754 } } }, + .{ .t = 28688747523, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.25872803, .y = 0.47351074, .pressure = 0.013061523 } } }, + .{ .t = 28688752063, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.25827026, .y = 0.4732666, .pressure = 0.013397217 } } }, + .{ .t = 28699780696, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.2581787, .y = 0.47317505, .pressure = 0.014129639 } } }, + .{ .t = 28699788576, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.25759888, .y = 0.47305298, .pressure = 0.014831543 } } }, + .{ .t = 28699792416, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.25787354, .y = 0.47280884, .pressure = 0.01449585 } } }, + .{ .t = 28711058720, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.25784302, .y = 0.47225952, .pressure = 0.013763428 } } }, + .{ .t = 28711073040, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.25738525, .y = 0.472229, .pressure = 0.014129639 } } }, + .{ .t = 28722312593, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.25720215, .y = 0.4717102, .pressure = 0.013763428 } } }, + .{ .t = 28722328533, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.2572937, .y = 0.47213745, .pressure = 0.012329102 } } }, + .{ .t = 28722335123, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.2576294, .y = 0.4721985, .pressure = 0.01449585 } } }, + .{ .t = 28733104547, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.25784302, .y = 0.4718933, .pressure = 0.013763428 } } }, + .{ .t = 28733113157, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.2571411, .y = 0.472229, .pressure = 0.013763428 } } }, + .{ .t = 28733116517, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.256958, .y = 0.47235107, .pressure = 0.010894775 } } }, + .{ .t = 28744542840, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.25598145, .y = 0.47323608, .pressure = 0.011962891 } } }, + .{ .t = 28744554360, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.25558472, .y = 0.47372437, .pressure = 0.012329102 } } }, + .{ .t = 28744558310, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.25463867, .y = 0.47329712, .pressure = 0.013061523 } } }, + .{ .t = 28755164615, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.2541809, .y = 0.4736023, .pressure = 0.013397217 } } }, + .{ .t = 28755173055, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.2536316, .y = 0.47485352, .pressure = 0.013397217 } } }, + .{ .t = 28766369408, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.2527771, .y = 0.4749756, .pressure = 0.011962891 } } }, + .{ .t = 28766376998, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.2524109, .y = 0.47543335, .pressure = 0.011962891 } } }, + .{ .t = 28766380848, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.2518921, .y = 0.4761963, .pressure = 0.011962891 } } }, + .{ .t = 28777479342, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.25073242, .y = 0.4764099, .pressure = 0.013397217 } } }, + .{ .t = 28777487702, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.24984741, .y = 0.4772644, .pressure = 0.015197754 } } }, + .{ .t = 28777491542, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.24942017, .y = 0.47872925, .pressure = 0.015563965 } } }, + .{ .t = 28788858885, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.24816895, .y = 0.47982788, .pressure = 0.016296387 } } }, + .{ .t = 28788869705, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.247406, .y = 0.48181152, .pressure = 0.016998291 } } }, + .{ .t = 28788873665, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.24645996, .y = 0.48260498, .pressure = 0.015563965 } } }, + .{ .t = 28800073548, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.2456665, .y = 0.48516846, .pressure = 0.01663208 } } }, + .{ .t = 28800082148, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.24414062, .y = 0.48757935, .pressure = 0.018432617 } } }, + .{ .t = 28800086718, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.2437439, .y = 0.48986816, .pressure = 0.019165039 } } }, + .{ .t = 28810881362, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.2432251, .y = 0.49273682, .pressure = 0.017730713 } } }, + .{ .t = 28810890602, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.24337769, .y = 0.4951172, .pressure = 0.018432617 } } }, + .{ .t = 28822223135, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.24224854, .y = 0.49868774, .pressure = 0.018066406 } } }, + .{ .t = 28822236725, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.2409668, .y = 0.5030823, .pressure = 0.018432617 } } }, + .{ .t = 28822243035, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.24002075, .y = 0.5093689, .pressure = 0.017364502 } } }, + .{ .t = 28833221849, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.23800659, .y = 0.52023315, .pressure = 0.017364502 } } }, + .{ .t = 28833234799, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.23648071, .y = 0.5312195, .pressure = 0.018066406 } } }, + .{ .t = 28833241859, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.23449707, .y = 0.54260254, .pressure = 0.018432617 } } }, + .{ .t = 28844533292, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.23208618, .y = 0.5539551, .pressure = 0.019165039 } } }, + .{ .t = 28844544902, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.22930908, .y = 0.5640869, .pressure = 0.020599365 } } }, + .{ .t = 28844549012, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.22769165, .y = 0.5701294, .pressure = 0.022399902 } } }, + .{ .t = 28855315576, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.22613525, .y = 0.57528687, .pressure = 0.023468018 } } }, + .{ .t = 28855325516, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.22503662, .y = 0.5812073, .pressure = 0.02420044 } } }, + .{ .t = 28866614540, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.22335815, .y = 0.5848694, .pressure = 0.02420044 } } }, + .{ .t = 28866626480, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.22390747, .y = 0.5887146, .pressure = 0.024536133 } } }, + .{ .t = 28866629910, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.22283936, .y = 0.59265137, .pressure = 0.024536133 } } }, + .{ .t = 28877415724, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.22262573, .y = 0.59625244, .pressure = 0.025268555 } } }, + .{ .t = 28877428004, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.22128296, .y = 0.6008606, .pressure = 0.025268555 } } }, + .{ .t = 28888551597, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.2204895, .y = 0.60409546, .pressure = 0.025268555 } } }, + .{ .t = 28888564767, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.21896362, .y = 0.61083984, .pressure = 0.025634766 } } }, + .{ .t = 28888571967, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.21774292, .y = 0.6156006, .pressure = 0.025970459 } } }, + .{ .t = 28899744701, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.21542358, .y = 0.62112427, .pressure = 0.02633667 } } }, + .{ .t = 28899757861, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.21438599, .y = 0.62576294, .pressure = 0.027435303 } } }, + .{ .t = 28899764601, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.21298218, .y = 0.63223267, .pressure = 0.027069092 } } }, + .{ .t = 28910731865, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.21209717, .y = 0.63708496, .pressure = 0.02633667 } } }, + .{ .t = 28910746485, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.21133423, .y = 0.6419983, .pressure = 0.02670288 } } }, + .{ .t = 28921990138, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.21032715, .y = 0.64730835, .pressure = 0.027435303 } } }, + .{ .t = 28922004158, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.2090149, .y = 0.65237427, .pressure = 0.027069092 } } }, + .{ .t = 28922010498, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.20770264, .y = 0.6588135, .pressure = 0.02670288 } } }, + .{ .t = 28932967412, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.20559692, .y = 0.6654968, .pressure = 0.025970459 } } }, + .{ .t = 28932979792, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.20404053, .y = 0.67285156, .pressure = 0.025634766 } } }, + .{ .t = 28932983492, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.20187378, .y = 0.6821594, .pressure = 0.024536133 } } }, + .{ .t = 28944345285, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.19940186, .y = 0.6911926, .pressure = 0.02420044 } } }, + .{ .t = 28944363135, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.19662476, .y = 0.703949, .pressure = 0.022033691 } } }, + .{ .t = 28944369185, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.19250488, .y = 0.71707153, .pressure = 0.02130127 } } }, + .{ .t = 28955070939, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.18859863, .y = 0.7327881, .pressure = 0.020599365 } } }, + .{ .t = 28955080209, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.18469238, .y = 0.7469177, .pressure = 0.018798828 } } }, + .{ .t = 28966644072, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.1803894, .y = 0.76065063, .pressure = 0.018066406 } } }, + .{ .t = 28966660132, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.17681885, .y = 0.7729492, .pressure = 0.019165039 } } }, + .{ .t = 28966666102, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.17303467, .y = 0.78430176, .pressure = 0.01953125 } } }, + .{ .t = 28977523276, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.17047119, .y = 0.79385376, .pressure = 0.019165039 } } }, + .{ .t = 28977533506, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.16790771, .y = 0.8000183, .pressure = 0.019866943 } } }, + .{ .t = 28977538756, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.16583252, .y = 0.8055115, .pressure = 0.018798828 } } }, + .{ .t = 28988801809, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.16448975, .y = 0.8109131, .pressure = 0.01953125 } } }, + .{ .t = 28988815059, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.16299438, .y = 0.81552124, .pressure = 0.02130127 } } }, + .{ .t = 28988820159, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.16275024, .y = 0.8183899, .pressure = 0.02166748 } } }, + .{ .t = 29000005933, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.16235352, .y = 0.8191223, .pressure = 0.022399902 } } }, + .{ .t = 29000020133, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.16220093, .y = 0.820343, .pressure = 0.023468018 } } }, + .{ .t = 29000023943, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.16268921, .y = 0.8208618, .pressure = 0.023834229 } } }, + .{ .t = 29010879647, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.1618042, .y = 0.82214355, .pressure = 0.025634766 } } }, + .{ .t = 29010893477, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.16238403, .y = 0.82196045, .pressure = 0.02633667 } } }, + .{ .t = 29022239700, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.16329956, .y = 0.82180786, .pressure = 0.027069092 } } }, + .{ .t = 29022255010, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.16305542, .y = 0.8227539, .pressure = 0.027069092 } } }, + .{ .t = 29022260530, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.16360474, .y = 0.8215027, .pressure = 0.02670288 } } }, + .{ .t = 29033423863, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.16390991, .y = 0.8215637, .pressure = 0.02670288 } } }, + .{ .t = 29033439393, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.16513062, .y = 0.820282, .pressure = 0.02633667 } } }, + .{ .t = 29033446553, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.16571045, .y = 0.82003784, .pressure = 0.027069092 } } }, + .{ .t = 29044100787, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.16552734, .y = 0.81985474, .pressure = 0.024536133 } } }, + .{ .t = 29044110747, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.16653442, .y = 0.8192444, .pressure = 0.023468018 } } }, + .{ .t = 29044114927, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.16690063, .y = 0.81710815, .pressure = 0.023101807 } } }, + .{ .t = 29055305531, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.16772461, .y = 0.81536865, .pressure = 0.022766113 } } }, + .{ .t = 29055315751, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.16854858, .y = 0.81365967, .pressure = 0.022399902 } } }, + .{ .t = 29066613054, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.16940308, .y = 0.811615, .pressure = 0.02166748 } } }, + .{ .t = 29066629614, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.17041016, .y = 0.80908203, .pressure = 0.02130127 } } }, + .{ .t = 29066636804, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.17147827, .y = 0.8067322, .pressure = 0.02130127 } } }, + .{ .t = 29077513018, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.17288208, .y = 0.8036804, .pressure = 0.019165039 } } }, + .{ .t = 29077525768, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.17391968, .y = 0.8003235, .pressure = 0.015197754 } } }, + .{ .t = 29077531158, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.17553711, .y = 0.7965088, .pressure = 0.014831543 } } }, + .{ .t = 29088910511, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.17697144, .y = 0.7913208, .pressure = 0.015563965 } } }, + .{ .t = 29088924801, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.17819214, .y = 0.78622437, .pressure = 0.01449585 } } }, + .{ .t = 29088930391, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.17999268, .y = 0.7813721, .pressure = 0.013397217 } } }, + .{ .t = 29100047575, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.18148804, .y = 0.7752991, .pressure = 0.014129639 } } }, + .{ .t = 29100061535, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.1831665, .y = 0.76898193, .pressure = 0.014129639 } } }, + .{ .t = 29100068045, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.184906, .y = 0.7624817, .pressure = 0.013763428 } } }, + .{ .t = 29111067488, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.18692017, .y = 0.7561035, .pressure = 0.013061523 } } }, + .{ .t = 29111083948, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.18884277, .y = 0.7487488, .pressure = 0.01449585 } } }, + .{ .t = 29122288972, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.19082642, .y = 0.7409973, .pressure = 0.01449585 } } }, + .{ .t = 29122305542, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.19223022, .y = 0.73428345, .pressure = 0.014831543 } } }, + .{ .t = 29122313342, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.19274902, .y = 0.7257385, .pressure = 0.014831543 } } }, + .{ .t = 29133328146, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.19299316, .y = 0.714447, .pressure = 0.015197754 } } }, + .{ .t = 29133345356, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.1928711, .y = 0.7018738, .pressure = 0.01449585 } } }, + .{ .t = 29133350306, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.19335938, .y = 0.6808777, .pressure = 0.014831543 } } }, + .{ .t = 29144200749, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.19464111, .y = 0.65582275, .pressure = 0.014831543 } } }, + .{ .t = 29144216579, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.19668579, .y = 0.63186646, .pressure = 0.01449585 } } }, + .{ .t = 29144223419, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.19927979, .y = 0.6045227, .pressure = 0.013763428 } } }, + .{ .t = 29154998954, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.20211792, .y = 0.57891846, .pressure = 0.0126953125 } } }, + .{ .t = 29155006203, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.20501709, .y = 0.551239, .pressure = 0.0126953125 } } }, + .{ .t = 29166393667, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.20880127, .y = 0.5248718, .pressure = 0.012329102 } } }, + .{ .t = 29166404147, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.21270752, .y = 0.499115, .pressure = 0.013397217 } } }, + .{ .t = 29166409197, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.21655273, .y = 0.47366333, .pressure = 0.013763428 } } }, + .{ .t = 29177500380, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.2204895, .y = 0.45114136, .pressure = 0.0101623535 } } }, + .{ .t = 29177510970, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.22451782, .y = 0.4290161, .pressure = 0.0101623535 } } }, + .{ .t = 29177516230, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.2286377, .y = 0.40975952, .pressure = 0.0101623535 } } }, + .{ .t = 29188832983, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.23208618, .y = 0.39212036, .pressure = 0.010528564 } } }, + .{ .t = 29188846483, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.23532104, .y = 0.375885, .pressure = 0.007293701 } } }, + .{ .t = 29188851103, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.23809814, .y = 0.35943604, .pressure = 0.009460449 } } }, + .{ .t = 29200021967, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.24072266, .y = 0.34292603, .pressure = 0.011260986 } } }, + .{ .t = 29200037067, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.24298096, .y = 0.32809448, .pressure = 0.011962891 } } }, + .{ .t = 29200042877, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.24493408, .y = 0.3138733, .pressure = 0.010528564 } } }, + .{ .t = 29210884631, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.24728394, .y = 0.29989624, .pressure = 0.012329102 } } }, + .{ .t = 29221881625, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.24908447, .y = 0.2866516, .pressure = 0.011962891 } } }, + .{ .t = 29221891355, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.250885, .y = 0.2755432, .pressure = 0.010528564 } } }, + .{ .t = 29221896615, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.252594, .y = 0.26571655, .pressure = 0.011962891 } } }, + .{ .t = 29233293918, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.25378418, .y = 0.2571106, .pressure = 0.0126953125 } } }, + .{ .t = 29233306418, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.25476074, .y = 0.24942017, .pressure = 0.0126953125 } } }, + .{ .t = 29233312238, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.25534058, .y = 0.24307251, .pressure = 0.011260986 } } }, + .{ .t = 29244359261, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.25610352, .y = 0.23760986, .pressure = 0.0101623535 } } }, + .{ .t = 29244375081, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.25680542, .y = 0.23291016, .pressure = 0.0101623535 } } }, + .{ .t = 29244383211, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.25750732, .y = 0.22824097, .pressure = 0.0101623535 } } }, + .{ .t = 29255381715, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.25823975, .y = 0.22570801, .pressure = 0.007659912 } } }, + .{ .t = 29255392615, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.25909424, .y = 0.2234497, .pressure = 0.007293701 } } }, + .{ .t = 29266740458, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.2599182, .y = 0.22180176, .pressure = 0.006225586 } } }, + .{ .t = 29266753748, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.26089478, .y = 0.22140503, .pressure = 0.0051574707 } } }, + .{ .t = 29266758978, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.26275635, .y = 0.22149658, .pressure = 0.0033569336 } } }, } } diff --git a/test/deck/replay.zig b/test/deck/replay.zig index 49614b46..778f4191 100644 --- a/test/deck/replay.zig +++ b/test/deck/replay.zig @@ -45,12 +45,12 @@ fn replay(src: [:0]const u8) !Tally { tally.max_step = @max(tally.max_step, @max(@abs(mv.dx), @abs(mv.dy))); }, .click => |ck| if (ck.down) { - tally.click_down[@intFromEnum(ck.which)] += 1; + tally.click_down[@backingInt(ck.which)] += 1; } else { - tally.click_up[@intFromEnum(ck.which)] += 1; + tally.click_up[@backingInt(ck.which)] += 1; }, .wheel => |ticks| tally.wheel += ticks, - .key => |k| tally.keys[@intFromEnum(k)] += 1, + .key => |k| tally.keys[@backingInt(k)] += 1, .rumble => tally.rumbles += 1, }; } @@ -72,7 +72,7 @@ test "right-pad drag moves the pointer, fresh touches don't jump" { try std.testing.expectEqual(0, t.wheel); // a light-touch drag stays well under the click threshold — no phantom // select clicks (nor their rumble) - try std.testing.expectEqual(0, t.click_down[@intFromEnum(deck.Click.select)]); + try std.testing.expectEqual(0, t.click_down[@backingInt(deck.Click.select)]); try std.testing.expectEqual(0, t.rumbles); } @@ -82,11 +82,11 @@ test "trigger pull+release clicks exactly once each" { // through dozens of intermediate values, interleaved with ~500 stick // axis events: hysteresis must yield exactly one click apiece, only // the execute pull rumbles, and the sticks produce nothing - try std.testing.expectEqual(1, t.click_down[@intFromEnum(deck.Click.select)]); - try std.testing.expectEqual(1, t.click_up[@intFromEnum(deck.Click.select)]); - try std.testing.expectEqual(1, t.click_down[@intFromEnum(deck.Click.execute)]); - try std.testing.expectEqual(1, t.click_up[@intFromEnum(deck.Click.execute)]); - try std.testing.expectEqual(0, t.click_down[@intFromEnum(deck.Click.look)]); + try std.testing.expectEqual(1, t.click_down[@backingInt(deck.Click.select)]); + try std.testing.expectEqual(1, t.click_up[@backingInt(deck.Click.select)]); + try std.testing.expectEqual(1, t.click_down[@backingInt(deck.Click.execute)]); + try std.testing.expectEqual(1, t.click_up[@backingInt(deck.Click.execute)]); + try std.testing.expectEqual(0, t.click_down[@backingInt(deck.Click.look)]); try std.testing.expectEqual(1, t.rumbles); try std.testing.expectEqual(0, t.moves); } @@ -100,7 +100,7 @@ test "left-pad swipe scrolls" { try std.testing.expectEqual(5, t.wheel); try std.testing.expectEqual(0, t.moves); // the swipe presses lightly — no phantom look clicks - try std.testing.expectEqual(0, t.click_down[@intFromEnum(deck.Click.look)]); + try std.testing.expectEqual(0, t.click_down[@backingInt(deck.Click.look)]); try std.testing.expectEqual(0, t.rumbles); } @@ -166,15 +166,15 @@ test "buttons: dpad n/N, A Enter, Y Tab, L1 look + rumble" { const t = try replay(@embedFile("buttons.zon")); // every button press of a real all-buttons sweep: dpad-down x1, // dpad-up x3, A x2, Y x5, L1 x3; the other buttons map to nothing - try std.testing.expectEqual(1, t.keys[@intFromEnum(deck.Keytap.n)]); - try std.testing.expectEqual(3, t.keys[@intFromEnum(deck.Keytap.cap_n)]); - try std.testing.expectEqual(2, t.keys[@intFromEnum(deck.Keytap.enter)]); - try std.testing.expectEqual(5, t.keys[@intFromEnum(deck.Keytap.tab)]); - try std.testing.expectEqual(3, t.click_down[@intFromEnum(deck.Click.look)]); - try std.testing.expectEqual(3, t.click_up[@intFromEnum(deck.Click.look)]); + try std.testing.expectEqual(1, t.keys[@backingInt(deck.Keytap.n)]); + try std.testing.expectEqual(3, t.keys[@backingInt(deck.Keytap.cap_n)]); + try std.testing.expectEqual(2, t.keys[@backingInt(deck.Keytap.enter)]); + try std.testing.expectEqual(5, t.keys[@backingInt(deck.Keytap.tab)]); + try std.testing.expectEqual(3, t.click_down[@backingInt(deck.Click.look)]); + try std.testing.expectEqual(3, t.click_up[@backingInt(deck.Click.look)]); try std.testing.expectEqual(3, t.rumbles); - try std.testing.expectEqual(0, t.click_down[@intFromEnum(deck.Click.select)]); - try std.testing.expectEqual(0, t.click_down[@intFromEnum(deck.Click.execute)]); + try std.testing.expectEqual(0, t.click_down[@backingInt(deck.Click.select)]); + try std.testing.expectEqual(0, t.click_down[@backingInt(deck.Click.execute)]); try std.testing.expectEqual(0, t.moves); try std.testing.expectEqual(0, t.wheel); } diff --git a/test/deck/rpad-drag.zon b/test/deck/rpad-drag.zon index 20dea6ef..c7a82db9 100644 --- a/test/deck/rpad-drag.zon +++ b/test/deck/rpad-drag.zon @@ -1,223 +1,223 @@ .{ .version = 1, .events = .{ -.{.t=1557743788,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.down,.x=0.48794556,.y=0.3156128,.pressure=0.0004272461}}}, -.{.t=1557747308,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.49105835,.y=0.31570435,.pressure=0.0015563965}}}, -.{.t=1568667061,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.49325562,.y=0.31576538,.pressure=0.004638672}}}, -.{.t=1568677161,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.49591064,.y=0.31585693,.pressure=0.0035095215}}}, -.{.t=1568682171,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.4988098,.y=0.31588745,.pressure=0.0026855469}}}, -.{.t=1579851545,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.50076294,.y=0.31607056,.pressure=0.004638672}}}, -.{.t=1579859265,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.50289917,.y=0.31637573,.pressure=0.0063171387}}}, -.{.t=1579863375,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.5050354,.y=0.31655884,.pressure=0.008026123}}}, -.{.t=1590959349,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.50717163,.y=0.31655884,.pressure=0.0063171387}}}, -.{.t=1590970369,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.50927734,.y=0.31698608,.pressure=0.0040893555}}}, -.{.t=1590975739,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.5108948,.y=0.31750488,.pressure=0.0038146973}}}, -.{.t=1601902982,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.5126953,.y=0.31808472,.pressure=0.005218506}}}, -.{.t=1601911482,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.51400757,.y=0.318573,.pressure=0.0066223145}}}, -.{.t=1613345665,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.51571655,.y=0.31878662,.pressure=0.007171631}}}, -.{.t=1613352235,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.51660156,.y=0.31936646,.pressure=0.0068969727}}}, -.{.t=1613356725,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.5178528,.y=0.3199463,.pressure=0.0066223145}}}, -.{.t=1624412039,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.5187378,.y=0.3206787,.pressure=0.0057678223}}}, -.{.t=1624425589,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.52023315,.y=0.32138062,.pressure=0.0043640137}}}, -.{.t=1624432009,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.5215454,.y=0.3218689,.pressure=0.0040893555}}}, -.{.t=1635289123,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.5227356,.y=0.3222351,.pressure=0.0018310547}}}, -.{.t=1635297503,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.52371216,.y=0.3229065,.pressure=0.0026855469}}}, -.{.t=1635301553,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.5246887,.y=0.3234558,.pressure=0.002105713}}}, -.{.t=1646425097,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.52545166,.y=0.323761,.pressure=0.0007019043}}}, -.{.t=1646433957,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.up,.x=0.5263977,.y=0.3241577,.pressure=0}}}, -.{.t=1657611170,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.down,.x=0.52749634,.y=0.32489014,.pressure=0.0004272461}}}, -.{.t=1657620700,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.up,.x=0.52893066,.y=0.32543945,.pressure=0}}}, -.{.t=2568455904,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.down,.x=0.71746826,.y=0.4960022,.pressure=0.0026855469}}}, -.{.t=2568464274,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.72143555,.y=0.49996948,.pressure=0.0032348633}}}, -.{.t=2568468384,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.72436523,.y=0.5033264,.pressure=0.004638672}}}, -.{.t=2579442397,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.7271118,.y=0.5065918,.pressure=0.0066223145}}}, -.{.t=2579450697,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.73065186,.y=0.51031494,.pressure=0.008850098}}}, -.{.t=2579455357,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.7350464,.y=0.5145569,.pressure=0.010253906}}}, -.{.t=2590631621,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.74017334,.y=0.51916504,.pressure=0.012512207}}}, -.{.t=2590639051,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.7455139,.y=0.52420044,.pressure=0.014190674}}}, -.{.t=2601728264,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.7537842,.y=0.5307617,.pressure=0.01727295}}}, -.{.t=2601737594,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.76501465,.y=0.5390625,.pressure=0.017852783}}}, -.{.t=2601745184,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.7758789,.y=0.54782104,.pressure=0.017578125}}}, -.{.t=2612868798,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.78726196,.y=0.55740356,.pressure=0.018676758}}}, -.{.t=2612877548,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.79766846,.y=0.56655884,.pressure=0.016998291}}}, -.{.t=2612881858,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.8077698,.y=0.57421875,.pressure=0.016174316}}}, -.{.t=2624096121,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.81689453,.y=0.5804138,.pressure=0.0184021}}}, -.{.t=2624103861,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.8230896,.y=0.58462524,.pressure=0.017578125}}}, -.{.t=2624108371,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.8291321,.y=0.58810425,.pressure=0.016448975}}}, -.{.t=2635100225,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.8328247,.y=0.5901184,.pressure=0.015594482}}}, -.{.t=2635107345,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.835022,.y=0.59017944,.pressure=0.016174316}}}, -.{.t=2635111905,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.83724976,.y=0.5899353,.pressure=0.016174316}}}, -.{.t=2646151229,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.8390808,.y=0.5890198,.pressure=0.014770508}}}, -.{.t=2646160149,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.8404541,.y=0.58709717,.pressure=0.014190674}}}, -.{.t=2657358812,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.8408203,.y=0.58535767,.pressure=0.016448975}}}, -.{.t=2657364952,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.8411865,.y=0.5831604,.pressure=0.015045166}}}, -.{.t=2657368602,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.84106445,.y=0.5809021,.pressure=0.0184021}}}, -.{.t=2668497496,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.84155273,.y=0.5791321,.pressure=0.018676758}}}, -.{.t=2668503176,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.84198,.y=0.5767517,.pressure=0.0184021}}}, -.{.t=2679574619,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.8413696,.y=0.5749817,.pressure=0.01727295}}}, -.{.t=2679583429,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.8410034,.y=0.57302856,.pressure=0.015594482}}}, -.{.t=2679588959,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.8402405,.y=0.57077026,.pressure=0.016998291}}}, -.{.t=2690585493,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.83987427,.y=0.5680237,.pressure=0.017578125}}}, -.{.t=2690591573,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.8392639,.y=0.5658264,.pressure=0.016998291}}}, -.{.t=2701710277,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.8384094,.y=0.56329346,.pressure=0.015045166}}}, -.{.t=2701715427,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.8366089,.y=0.5602722,.pressure=0.012512207}}}, -.{.t=2701719287,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.8343506,.y=0.55578613,.pressure=0.013641357}}}, -.{.t=2712932260,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.8309326,.y=0.5510254,.pressure=0.012512207}}}, -.{.t=2712941600,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.8270569,.y=0.54504395,.pressure=0.013641357}}}, -.{.t=2712946870,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.82263184,.y=0.53845215,.pressure=0.012786865}}}, -.{.t=2724074464,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.8186035,.y=0.5309448,.pressure=0.012237549}}}, -.{.t=2724081034,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.8176575,.y=0.5210266,.pressure=0.011383057}}}, -.{.t=2724085114,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.8161926,.y=0.5109863,.pressure=0.010253906}}}, -.{.t=2735041467,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.81481934,.y=0.49887085,.pressure=0.008575439}}}, -.{.t=2735049697,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.8135681,.y=0.48706055,.pressure=0.0066223145}}}, -.{.t=2735053437,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.8110962,.y=0.47451782,.pressure=0.0066223145}}}, -.{.t=2746200461,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.8079529,.y=0.46011353,.pressure=0.008300781}}}, -.{.t=2746207531,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.8046875,.y=0.44818115,.pressure=0.008850098}}}, -.{.t=2757301144,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.8004761,.y=0.4363098,.pressure=0.010253906}}}, -.{.t=2757308574,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.796051,.y=0.4248352,.pressure=0.009979248}}}, -.{.t=2757312724,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.79104614,.y=0.4133911,.pressure=0.013366699}}}, -.{.t=2775948317,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.78637695,.y=0.4032898,.pressure=0.012237549}}}, -.{.t=2775958817,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.78131104,.y=0.39471436,.pressure=0.015045166}}}, -.{.t=2775962507,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.7763977,.y=0.38796997,.pressure=0.016723633}}}, -.{.t=2775966007,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.77178955,.y=0.38198853,.pressure=0.018127441}}}, -.{.t=2775969667,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.76724243,.y=0.37753296,.pressure=0.019805908}}}, -.{.t=2779448262,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.7628784,.y=0.37338257,.pressure=0.018127441}}}, -.{.t=2790559265,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.75909424,.y=0.36990356,.pressure=0.020935059}}}, -.{.t=2790566225,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.75512695,.y=0.36654663,.pressure=0.021484375}}}, -.{.t=2801688299,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.7513733,.y=0.36395264,.pressure=0.020385742}}}, -.{.t=2801695099,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.7475891,.y=0.36190796,.pressure=0.020385742}}}, -.{.t=2801697739,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.74487305,.y=0.35958862,.pressure=0.020385742}}}, -.{.t=2812906962,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.74191284,.y=0.3572998,.pressure=0.022888184}}}, -.{.t=2812918202,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.7388611,.y=0.35458374,.pressure=0.022338867}}}, -.{.t=2812924662,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.7357178,.y=0.35250854,.pressure=0.021209717}}}, -.{.t=2824054786,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.7324829,.y=0.3503418,.pressure=0.021484375}}}, -.{.t=2824059786,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.7289429,.y=0.3484497,.pressure=0.022888184}}}, -.{.t=2824063716,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.72506714,.y=0.34591675,.pressure=0.022613525}}}, -.{.t=2835063039,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.7218323,.y=0.34277344,.pressure=0.02319336}}}, -.{.t=2835070099,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.7174072,.y=0.34020996,.pressure=0.020080566}}}, -.{.t=2835075929,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.71273804,.y=0.33743286,.pressure=0.020080566}}}, -.{.t=2846116163,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.7079773,.y=0.3343506,.pressure=0.018676758}}}, -.{.t=2846123943,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.7023926,.y=0.33081055,.pressure=0.019805908}}}, -.{.t=2857453356,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.6963806,.y=0.32598877,.pressure=0.019805908}}}, -.{.t=2857460036,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.6892395,.y=0.32144165,.pressure=0.020935059}}}, -.{.t=2857466116,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.6821289,.y=0.31661987,.pressure=0.018127441}}}, -.{.t=2868624580,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.6739197,.y=0.31192017,.pressure=0.018676758}}}, -.{.t=2868632160,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.6664429,.y=0.3072815,.pressure=0.018981934}}}, -.{.t=2868637550,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.6587219,.y=0.30307007,.pressure=0.017578125}}}, -.{.t=2879637654,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.65133667,.y=0.29888916,.pressure=0.017852783}}}, -.{.t=2879646144,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.6444702,.y=0.29452515,.pressure=0.017852783}}}, -.{.t=2879653574,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.6372986,.y=0.29092407,.pressure=0.016174316}}}, -.{.t=2890493398,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.6305542,.y=0.28729248,.pressure=0.016448975}}}, -.{.t=2890500368,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.62493896,.y=0.28427124,.pressure=0.016448975}}}, -.{.t=2901904031,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.6192627,.y=0.28234863,.pressure=0.015594482}}}, -.{.t=2901913451,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.61428833,.y=0.27990723,.pressure=0.014190674}}}, -.{.t=2901920201,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.6097412,.y=0.277771,.pressure=0.013641357}}}, -.{.t=2913077524,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.6056824,.y=0.27627563,.pressure=0.013641357}}}, -.{.t=2913084054,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.6019287,.y=0.27560425,.pressure=0.012512207}}}, -.{.t=2913088274,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.5984192,.y=0.27441406,.pressure=0.011657715}}}, -.{.t=2924138128,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.59536743,.y=0.27404785,.pressure=0.011962891}}}, -.{.t=2924146018,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.5923767,.y=0.27398682,.pressure=0.013641357}}}, -.{.t=2924151648,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.5900574,.y=0.2736206,.pressure=0.013366699}}}, -.{.t=2935179332,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.5883484,.y=0.27407837,.pressure=0.014465332}}}, -.{.t=2935187861,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.5866394,.y=0.27478027,.pressure=0.01586914}}}, -.{.t=2935191171,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.58551025,.y=0.2756958,.pressure=0.015045166}}}, -.{.t=2946370475,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.5841675,.y=0.27648926,.pressure=0.01727295}}}, -.{.t=2946379375,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.5830078,.y=0.27764893,.pressure=0.0184021}}}, -.{.t=2957467849,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.5821533,.y=0.278656,.pressure=0.01953125}}}, -.{.t=2957477449,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.5817566,.y=0.28030396,.pressure=0.016998291}}}, -.{.t=2957483529,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.58148193,.y=0.28225708,.pressure=0.015319824}}}, -.{.t=2968627182,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.5809021,.y=0.2843933,.pressure=0.01586914}}}, -.{.t=2968643772,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.580719,.y=0.28659058,.pressure=0.014190674}}}, -.{.t=2979684996,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.5805969,.y=0.28967285,.pressure=0.013641357}}}, -.{.t=2979694336,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.58026123,.y=0.29241943,.pressure=0.010559082}}}, -.{.t=2979699086,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.57995605,.y=0.29571533,.pressure=0.008575439}}}, -.{.t=2990715289,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.57958984,.y=0.29934692,.pressure=0.010253906}}}, -.{.t=2990723719,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.5793457,.y=0.30322266,.pressure=0.008300781}}}, -.{.t=3002153093,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.5791931,.y=0.30700684,.pressure=0.0060424805}}}, -.{.t=3002161152,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.5791931,.y=0.3117981,.pressure=0.0060424805}}}, -.{.t=3002165632,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.57958984,.y=0.3164673,.pressure=0.00491333}}}, -.{.t=3012982186,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.5806885,.y=0.3215027,.pressure=0.0068969727}}}, -.{.t=3012991236,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.5819702,.y=0.32669067,.pressure=0.0057678223}}}, -.{.t=3012998166,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.5845032,.y=0.3322754,.pressure=0.007446289}}}, -.{.t=3024201460,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.5869446,.y=0.33740234,.pressure=0.008026123}}}, -.{.t=3024208990,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.59017944,.y=0.34225464,.pressure=0.009155273}}}, -.{.t=3024211980,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.5932617,.y=0.34698486,.pressure=0.012237549}}}, -.{.t=3035025244,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.59643555,.y=0.3517456,.pressure=0.013366699}}}, -.{.t=3035031374,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.6001282,.y=0.35601807,.pressure=0.016998291}}}, -.{.t=3035034874,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.60409546,.y=0.3600464,.pressure=0.019805908}}}, -.{.t=3046541367,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.60775757,.y=0.36398315,.pressure=0.022338867}}}, -.{.t=3046548887,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.61169434,.y=0.36740112,.pressure=0.022613525}}}, -.{.t=3057532891,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.6154785,.y=0.37051392,.pressure=0.025146484}}}, -.{.t=3057540471,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.6194763,.y=0.37329102,.pressure=0.025421143}}}, -.{.t=3057545781,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.6232605,.y=0.3761902,.pressure=0.026000977}}}, -.{.t=3068735374,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.62753296,.y=0.3789673,.pressure=0.025421143}}}, -.{.t=3068748304,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.6313782,.y=0.3816223,.pressure=0.024017334}}}, -.{.t=3068754594,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.63513184,.y=0.38391113,.pressure=0.023742676}}}, -.{.t=3079554878,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.6390991,.y=0.38616943,.pressure=0.023468018}}}, -.{.t=3079563518,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.6433716,.y=0.38833618,.pressure=0.02178955}}}, -.{.t=3079568338,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.64767456,.y=0.39031982,.pressure=0.02319336}}}, -.{.t=3090741042,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.65234375,.y=0.3919983,.pressure=0.02319336}}}, -.{.t=3090749882,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.65689087,.y=0.39379883,.pressure=0.021209717}}}, -.{.t=3101724975,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.6610718,.y=0.39520264,.pressure=0.022888184}}}, -.{.t=3101732005,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.66574097,.y=0.39642334,.pressure=0.021484375}}}, -.{.t=3101735255,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.6701355,.y=0.3973999,.pressure=0.019805908}}}, -.{.t=3113361458,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.6748352,.y=0.39767456,.pressure=0.0206604}}}, -.{.t=3113368498,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.67944336,.y=0.39797974,.pressure=0.022613525}}}, -.{.t=3113372028,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.6838379,.y=0.39785767,.pressure=0.022338867}}}, -.{.t=3123796833,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.6879883,.y=0.3970642,.pressure=0.01953125}}}, -.{.t=3123803053,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.69177246,.y=0.39624023,.pressure=0.018127441}}}, -.{.t=3123806563,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.69555664,.y=0.39569092,.pressure=0.016998291}}}, -.{.t=3134998596,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.69888306,.y=0.3942871,.pressure=0.016998291}}}, -.{.t=3135007066,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.7023926,.y=0.39257812,.pressure=0.017578125}}}, -.{.t=3135011336,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.7060852,.y=0.39056396,.pressure=0.017578125}}}, -.{.t=3146195970,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.7102051,.y=0.38861084,.pressure=0.015594482}}}, -.{.t=3146202620,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.715271,.y=0.386261,.pressure=0.014190674}}}, -.{.t=3157408853,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.7234802,.y=0.38327026,.pressure=0.01586914}}}, -.{.t=3157418073,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.730896,.y=0.38006592,.pressure=0.01586914}}}, -.{.t=3157423313,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.73880005,.y=0.37652588,.pressure=0.016448975}}}, -.{.t=3168334437,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.74557495,.y=0.37350464,.pressure=0.017578125}}}, -.{.t=3168341357,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.75097656,.y=0.37020874,.pressure=0.016723633}}}, -.{.t=3168344697,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.7561035,.y=0.36791992,.pressure=0.013916016}}}, -.{.t=3179518520,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.75982666,.y=0.36517334,.pressure=0.013061523}}}, -.{.t=3179524910,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.7633362,.y=0.3623352,.pressure=0.013061523}}}, -.{.t=3179530860,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.765625,.y=0.35949707,.pressure=0.013641357}}}, -.{.t=3190702424,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.7669678,.y=0.3564453,.pressure=0.012786865}}}, -.{.t=3190710904,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.76849365,.y=0.3536682,.pressure=0.011383057}}}, -.{.t=3201886237,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.7687378,.y=0.35095215,.pressure=0.010559082}}}, -.{.t=3201895897,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.7681885,.y=0.34838867,.pressure=0.009155273}}}, -.{.t=3201900097,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.7668457,.y=0.34570312,.pressure=0.009155273}}}, -.{.t=3212919591,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.7654724,.y=0.34277344,.pressure=0.008850098}}}, -.{.t=3212927311,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.7631836,.y=0.34002686,.pressure=0.0066223145}}}, -.{.t=3212932591,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.7612915,.y=0.3373413,.pressure=0.0040893555}}}, -.{.t=3224127654,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.7590027,.y=0.33529663,.pressure=0.0043640137}}}, -.{.t=3224134564,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.7567444,.y=0.33319092,.pressure=0.0024108887}}}, -.{.t=3224138834,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.7541809,.y=0.3307495,.pressure=0.00491333}}}, -.{.t=3234961798,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.75216675,.y=0.32843018,.pressure=0.0038146973}}}, -.{.t=3234967628,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.7489929,.y=0.32583618,.pressure=0.0038146973}}}, -.{.t=3234971398,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.7467346,.y=0.32296753,.pressure=0.005218506}}}, -.{.t=3246367272,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.7436218,.y=0.32019043,.pressure=0.0043640137}}}, -.{.t=3246376701,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.7402649,.y=0.3173523,.pressure=0.0038146973}}}, -.{.t=3257870675,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.73721313,.y=0.31466675,.pressure=0.0018310547}}}, -.{.t=3257881104,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.7336731,.y=0.31219482,.pressure=0.0024108887}}}, -.{.t=3257886264,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.73062134,.y=0.3100891,.pressure=0.0015563965}}}, -.{.t=3268291019,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.72720337,.y=0.30807495,.pressure=0.0007019043}}}, -.{.t=3268298969,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.7241516,.y=0.30593872,.pressure=0.0015563965}}}, -.{.t=3268303569,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.7213135,.y=0.30371094,.pressure=0.0035095215}}}, -.{.t=3279746522,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.71810913,.y=0.302063,.pressure=0.002960205}}}, -.{.t=3279757542,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.7147217,.y=0.30056763,.pressure=0.00491333}}}, -.{.t=3279762862,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.71087646,.y=0.29907227,.pressure=0.00491333}}}, -.{.t=3290574016,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.70751953,.y=0.29745483,.pressure=0.0040893555}}}, -.{.t=3290581596,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.70376587,.y=0.29592896,.pressure=0.0040893555}}}, -.{.t=3301750300,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.6994934,.y=0.2951355,.pressure=0.0038146973}}}, -.{.t=3301760370,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.6951904,.y=0.29397583,.pressure=0.005218506}}}, -.{.t=3301767410,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.6905823,.y=0.29284668,.pressure=0.00491333}}}, -.{.t=3312951293,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.685791,.y=0.29266357,.pressure=0.0068969727}}}, -.{.t=3312959893,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.68136597,.y=0.29257202,.pressure=0.005493164}}}, -.{.t=3312965373,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.6772461,.y=0.29229736,.pressure=0.0068969727}}}, -.{.t=3324079267,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.672699,.y=0.29318237,.pressure=0.004638672}}}, -.{.t=3324090337,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.66882324,.y=0.294281,.pressure=0.004638672}}}, -.{.t=3324095997,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.66537476,.y=0.29525757,.pressure=0.004638672}}}, -.{.t=3335061800,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.6620178,.y=0.2966919,.pressure=0.002960205}}}, -.{.t=3335068160,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.6590576,.y=0.29788208,.pressure=0.0007019043}}}, -.{.t=3335073750,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.up,.x=0.6562805,.y=0.29956055,.pressure=0}}}, -.{.t=3390587188,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.down,.x=0.6447449,.y=0.33596802,.pressure=0.0007019043}}}, -.{.t=3390593138,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.6447754,.y=0.3406067,.pressure=0.0035095215}}}, + .{ .t = 1557743788, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .down, .x = 0.48794556, .y = 0.3156128, .pressure = 0.0004272461 } } }, + .{ .t = 1557747308, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.49105835, .y = 0.31570435, .pressure = 0.0015563965 } } }, + .{ .t = 1568667061, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.49325562, .y = 0.31576538, .pressure = 0.004638672 } } }, + .{ .t = 1568677161, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.49591064, .y = 0.31585693, .pressure = 0.0035095215 } } }, + .{ .t = 1568682171, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.4988098, .y = 0.31588745, .pressure = 0.0026855469 } } }, + .{ .t = 1579851545, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.50076294, .y = 0.31607056, .pressure = 0.004638672 } } }, + .{ .t = 1579859265, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.50289917, .y = 0.31637573, .pressure = 0.0063171387 } } }, + .{ .t = 1579863375, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.5050354, .y = 0.31655884, .pressure = 0.008026123 } } }, + .{ .t = 1590959349, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.50717163, .y = 0.31655884, .pressure = 0.0063171387 } } }, + .{ .t = 1590970369, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.50927734, .y = 0.31698608, .pressure = 0.0040893555 } } }, + .{ .t = 1590975739, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.5108948, .y = 0.31750488, .pressure = 0.0038146973 } } }, + .{ .t = 1601902982, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.5126953, .y = 0.31808472, .pressure = 0.005218506 } } }, + .{ .t = 1601911482, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.51400757, .y = 0.318573, .pressure = 0.0066223145 } } }, + .{ .t = 1613345665, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.51571655, .y = 0.31878662, .pressure = 0.007171631 } } }, + .{ .t = 1613352235, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.51660156, .y = 0.31936646, .pressure = 0.0068969727 } } }, + .{ .t = 1613356725, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.5178528, .y = 0.3199463, .pressure = 0.0066223145 } } }, + .{ .t = 1624412039, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.5187378, .y = 0.3206787, .pressure = 0.0057678223 } } }, + .{ .t = 1624425589, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.52023315, .y = 0.32138062, .pressure = 0.0043640137 } } }, + .{ .t = 1624432009, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.5215454, .y = 0.3218689, .pressure = 0.0040893555 } } }, + .{ .t = 1635289123, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.5227356, .y = 0.3222351, .pressure = 0.0018310547 } } }, + .{ .t = 1635297503, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.52371216, .y = 0.3229065, .pressure = 0.0026855469 } } }, + .{ .t = 1635301553, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.5246887, .y = 0.3234558, .pressure = 0.002105713 } } }, + .{ .t = 1646425097, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.52545166, .y = 0.323761, .pressure = 0.0007019043 } } }, + .{ .t = 1646433957, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .up, .x = 0.5263977, .y = 0.3241577, .pressure = 0 } } }, + .{ .t = 1657611170, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .down, .x = 0.52749634, .y = 0.32489014, .pressure = 0.0004272461 } } }, + .{ .t = 1657620700, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .up, .x = 0.52893066, .y = 0.32543945, .pressure = 0 } } }, + .{ .t = 2568455904, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .down, .x = 0.71746826, .y = 0.4960022, .pressure = 0.0026855469 } } }, + .{ .t = 2568464274, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.72143555, .y = 0.49996948, .pressure = 0.0032348633 } } }, + .{ .t = 2568468384, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.72436523, .y = 0.5033264, .pressure = 0.004638672 } } }, + .{ .t = 2579442397, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.7271118, .y = 0.5065918, .pressure = 0.0066223145 } } }, + .{ .t = 2579450697, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.73065186, .y = 0.51031494, .pressure = 0.008850098 } } }, + .{ .t = 2579455357, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.7350464, .y = 0.5145569, .pressure = 0.010253906 } } }, + .{ .t = 2590631621, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.74017334, .y = 0.51916504, .pressure = 0.012512207 } } }, + .{ .t = 2590639051, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.7455139, .y = 0.52420044, .pressure = 0.014190674 } } }, + .{ .t = 2601728264, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.7537842, .y = 0.5307617, .pressure = 0.01727295 } } }, + .{ .t = 2601737594, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.76501465, .y = 0.5390625, .pressure = 0.017852783 } } }, + .{ .t = 2601745184, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.7758789, .y = 0.54782104, .pressure = 0.017578125 } } }, + .{ .t = 2612868798, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.78726196, .y = 0.55740356, .pressure = 0.018676758 } } }, + .{ .t = 2612877548, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.79766846, .y = 0.56655884, .pressure = 0.016998291 } } }, + .{ .t = 2612881858, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.8077698, .y = 0.57421875, .pressure = 0.016174316 } } }, + .{ .t = 2624096121, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.81689453, .y = 0.5804138, .pressure = 0.0184021 } } }, + .{ .t = 2624103861, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.8230896, .y = 0.58462524, .pressure = 0.017578125 } } }, + .{ .t = 2624108371, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.8291321, .y = 0.58810425, .pressure = 0.016448975 } } }, + .{ .t = 2635100225, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.8328247, .y = 0.5901184, .pressure = 0.015594482 } } }, + .{ .t = 2635107345, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.835022, .y = 0.59017944, .pressure = 0.016174316 } } }, + .{ .t = 2635111905, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.83724976, .y = 0.5899353, .pressure = 0.016174316 } } }, + .{ .t = 2646151229, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.8390808, .y = 0.5890198, .pressure = 0.014770508 } } }, + .{ .t = 2646160149, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.8404541, .y = 0.58709717, .pressure = 0.014190674 } } }, + .{ .t = 2657358812, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.8408203, .y = 0.58535767, .pressure = 0.016448975 } } }, + .{ .t = 2657364952, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.8411865, .y = 0.5831604, .pressure = 0.015045166 } } }, + .{ .t = 2657368602, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.84106445, .y = 0.5809021, .pressure = 0.0184021 } } }, + .{ .t = 2668497496, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.84155273, .y = 0.5791321, .pressure = 0.018676758 } } }, + .{ .t = 2668503176, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.84198, .y = 0.5767517, .pressure = 0.0184021 } } }, + .{ .t = 2679574619, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.8413696, .y = 0.5749817, .pressure = 0.01727295 } } }, + .{ .t = 2679583429, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.8410034, .y = 0.57302856, .pressure = 0.015594482 } } }, + .{ .t = 2679588959, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.8402405, .y = 0.57077026, .pressure = 0.016998291 } } }, + .{ .t = 2690585493, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.83987427, .y = 0.5680237, .pressure = 0.017578125 } } }, + .{ .t = 2690591573, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.8392639, .y = 0.5658264, .pressure = 0.016998291 } } }, + .{ .t = 2701710277, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.8384094, .y = 0.56329346, .pressure = 0.015045166 } } }, + .{ .t = 2701715427, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.8366089, .y = 0.5602722, .pressure = 0.012512207 } } }, + .{ .t = 2701719287, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.8343506, .y = 0.55578613, .pressure = 0.013641357 } } }, + .{ .t = 2712932260, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.8309326, .y = 0.5510254, .pressure = 0.012512207 } } }, + .{ .t = 2712941600, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.8270569, .y = 0.54504395, .pressure = 0.013641357 } } }, + .{ .t = 2712946870, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.82263184, .y = 0.53845215, .pressure = 0.012786865 } } }, + .{ .t = 2724074464, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.8186035, .y = 0.5309448, .pressure = 0.012237549 } } }, + .{ .t = 2724081034, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.8176575, .y = 0.5210266, .pressure = 0.011383057 } } }, + .{ .t = 2724085114, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.8161926, .y = 0.5109863, .pressure = 0.010253906 } } }, + .{ .t = 2735041467, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.81481934, .y = 0.49887085, .pressure = 0.008575439 } } }, + .{ .t = 2735049697, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.8135681, .y = 0.48706055, .pressure = 0.0066223145 } } }, + .{ .t = 2735053437, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.8110962, .y = 0.47451782, .pressure = 0.0066223145 } } }, + .{ .t = 2746200461, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.8079529, .y = 0.46011353, .pressure = 0.008300781 } } }, + .{ .t = 2746207531, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.8046875, .y = 0.44818115, .pressure = 0.008850098 } } }, + .{ .t = 2757301144, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.8004761, .y = 0.4363098, .pressure = 0.010253906 } } }, + .{ .t = 2757308574, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.796051, .y = 0.4248352, .pressure = 0.009979248 } } }, + .{ .t = 2757312724, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.79104614, .y = 0.4133911, .pressure = 0.013366699 } } }, + .{ .t = 2775948317, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.78637695, .y = 0.4032898, .pressure = 0.012237549 } } }, + .{ .t = 2775958817, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.78131104, .y = 0.39471436, .pressure = 0.015045166 } } }, + .{ .t = 2775962507, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.7763977, .y = 0.38796997, .pressure = 0.016723633 } } }, + .{ .t = 2775966007, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.77178955, .y = 0.38198853, .pressure = 0.018127441 } } }, + .{ .t = 2775969667, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.76724243, .y = 0.37753296, .pressure = 0.019805908 } } }, + .{ .t = 2779448262, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.7628784, .y = 0.37338257, .pressure = 0.018127441 } } }, + .{ .t = 2790559265, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.75909424, .y = 0.36990356, .pressure = 0.020935059 } } }, + .{ .t = 2790566225, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.75512695, .y = 0.36654663, .pressure = 0.021484375 } } }, + .{ .t = 2801688299, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.7513733, .y = 0.36395264, .pressure = 0.020385742 } } }, + .{ .t = 2801695099, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.7475891, .y = 0.36190796, .pressure = 0.020385742 } } }, + .{ .t = 2801697739, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.74487305, .y = 0.35958862, .pressure = 0.020385742 } } }, + .{ .t = 2812906962, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.74191284, .y = 0.3572998, .pressure = 0.022888184 } } }, + .{ .t = 2812918202, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.7388611, .y = 0.35458374, .pressure = 0.022338867 } } }, + .{ .t = 2812924662, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.7357178, .y = 0.35250854, .pressure = 0.021209717 } } }, + .{ .t = 2824054786, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.7324829, .y = 0.3503418, .pressure = 0.021484375 } } }, + .{ .t = 2824059786, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.7289429, .y = 0.3484497, .pressure = 0.022888184 } } }, + .{ .t = 2824063716, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.72506714, .y = 0.34591675, .pressure = 0.022613525 } } }, + .{ .t = 2835063039, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.7218323, .y = 0.34277344, .pressure = 0.02319336 } } }, + .{ .t = 2835070099, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.7174072, .y = 0.34020996, .pressure = 0.020080566 } } }, + .{ .t = 2835075929, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.71273804, .y = 0.33743286, .pressure = 0.020080566 } } }, + .{ .t = 2846116163, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.7079773, .y = 0.3343506, .pressure = 0.018676758 } } }, + .{ .t = 2846123943, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.7023926, .y = 0.33081055, .pressure = 0.019805908 } } }, + .{ .t = 2857453356, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.6963806, .y = 0.32598877, .pressure = 0.019805908 } } }, + .{ .t = 2857460036, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.6892395, .y = 0.32144165, .pressure = 0.020935059 } } }, + .{ .t = 2857466116, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.6821289, .y = 0.31661987, .pressure = 0.018127441 } } }, + .{ .t = 2868624580, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.6739197, .y = 0.31192017, .pressure = 0.018676758 } } }, + .{ .t = 2868632160, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.6664429, .y = 0.3072815, .pressure = 0.018981934 } } }, + .{ .t = 2868637550, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.6587219, .y = 0.30307007, .pressure = 0.017578125 } } }, + .{ .t = 2879637654, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.65133667, .y = 0.29888916, .pressure = 0.017852783 } } }, + .{ .t = 2879646144, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.6444702, .y = 0.29452515, .pressure = 0.017852783 } } }, + .{ .t = 2879653574, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.6372986, .y = 0.29092407, .pressure = 0.016174316 } } }, + .{ .t = 2890493398, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.6305542, .y = 0.28729248, .pressure = 0.016448975 } } }, + .{ .t = 2890500368, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.62493896, .y = 0.28427124, .pressure = 0.016448975 } } }, + .{ .t = 2901904031, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.6192627, .y = 0.28234863, .pressure = 0.015594482 } } }, + .{ .t = 2901913451, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.61428833, .y = 0.27990723, .pressure = 0.014190674 } } }, + .{ .t = 2901920201, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.6097412, .y = 0.277771, .pressure = 0.013641357 } } }, + .{ .t = 2913077524, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.6056824, .y = 0.27627563, .pressure = 0.013641357 } } }, + .{ .t = 2913084054, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.6019287, .y = 0.27560425, .pressure = 0.012512207 } } }, + .{ .t = 2913088274, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.5984192, .y = 0.27441406, .pressure = 0.011657715 } } }, + .{ .t = 2924138128, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.59536743, .y = 0.27404785, .pressure = 0.011962891 } } }, + .{ .t = 2924146018, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.5923767, .y = 0.27398682, .pressure = 0.013641357 } } }, + .{ .t = 2924151648, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.5900574, .y = 0.2736206, .pressure = 0.013366699 } } }, + .{ .t = 2935179332, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.5883484, .y = 0.27407837, .pressure = 0.014465332 } } }, + .{ .t = 2935187861, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.5866394, .y = 0.27478027, .pressure = 0.01586914 } } }, + .{ .t = 2935191171, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.58551025, .y = 0.2756958, .pressure = 0.015045166 } } }, + .{ .t = 2946370475, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.5841675, .y = 0.27648926, .pressure = 0.01727295 } } }, + .{ .t = 2946379375, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.5830078, .y = 0.27764893, .pressure = 0.0184021 } } }, + .{ .t = 2957467849, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.5821533, .y = 0.278656, .pressure = 0.01953125 } } }, + .{ .t = 2957477449, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.5817566, .y = 0.28030396, .pressure = 0.016998291 } } }, + .{ .t = 2957483529, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.58148193, .y = 0.28225708, .pressure = 0.015319824 } } }, + .{ .t = 2968627182, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.5809021, .y = 0.2843933, .pressure = 0.01586914 } } }, + .{ .t = 2968643772, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.580719, .y = 0.28659058, .pressure = 0.014190674 } } }, + .{ .t = 2979684996, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.5805969, .y = 0.28967285, .pressure = 0.013641357 } } }, + .{ .t = 2979694336, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.58026123, .y = 0.29241943, .pressure = 0.010559082 } } }, + .{ .t = 2979699086, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.57995605, .y = 0.29571533, .pressure = 0.008575439 } } }, + .{ .t = 2990715289, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.57958984, .y = 0.29934692, .pressure = 0.010253906 } } }, + .{ .t = 2990723719, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.5793457, .y = 0.30322266, .pressure = 0.008300781 } } }, + .{ .t = 3002153093, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.5791931, .y = 0.30700684, .pressure = 0.0060424805 } } }, + .{ .t = 3002161152, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.5791931, .y = 0.3117981, .pressure = 0.0060424805 } } }, + .{ .t = 3002165632, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.57958984, .y = 0.3164673, .pressure = 0.00491333 } } }, + .{ .t = 3012982186, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.5806885, .y = 0.3215027, .pressure = 0.0068969727 } } }, + .{ .t = 3012991236, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.5819702, .y = 0.32669067, .pressure = 0.0057678223 } } }, + .{ .t = 3012998166, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.5845032, .y = 0.3322754, .pressure = 0.007446289 } } }, + .{ .t = 3024201460, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.5869446, .y = 0.33740234, .pressure = 0.008026123 } } }, + .{ .t = 3024208990, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.59017944, .y = 0.34225464, .pressure = 0.009155273 } } }, + .{ .t = 3024211980, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.5932617, .y = 0.34698486, .pressure = 0.012237549 } } }, + .{ .t = 3035025244, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.59643555, .y = 0.3517456, .pressure = 0.013366699 } } }, + .{ .t = 3035031374, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.6001282, .y = 0.35601807, .pressure = 0.016998291 } } }, + .{ .t = 3035034874, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.60409546, .y = 0.3600464, .pressure = 0.019805908 } } }, + .{ .t = 3046541367, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.60775757, .y = 0.36398315, .pressure = 0.022338867 } } }, + .{ .t = 3046548887, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.61169434, .y = 0.36740112, .pressure = 0.022613525 } } }, + .{ .t = 3057532891, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.6154785, .y = 0.37051392, .pressure = 0.025146484 } } }, + .{ .t = 3057540471, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.6194763, .y = 0.37329102, .pressure = 0.025421143 } } }, + .{ .t = 3057545781, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.6232605, .y = 0.3761902, .pressure = 0.026000977 } } }, + .{ .t = 3068735374, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.62753296, .y = 0.3789673, .pressure = 0.025421143 } } }, + .{ .t = 3068748304, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.6313782, .y = 0.3816223, .pressure = 0.024017334 } } }, + .{ .t = 3068754594, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.63513184, .y = 0.38391113, .pressure = 0.023742676 } } }, + .{ .t = 3079554878, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.6390991, .y = 0.38616943, .pressure = 0.023468018 } } }, + .{ .t = 3079563518, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.6433716, .y = 0.38833618, .pressure = 0.02178955 } } }, + .{ .t = 3079568338, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.64767456, .y = 0.39031982, .pressure = 0.02319336 } } }, + .{ .t = 3090741042, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.65234375, .y = 0.3919983, .pressure = 0.02319336 } } }, + .{ .t = 3090749882, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.65689087, .y = 0.39379883, .pressure = 0.021209717 } } }, + .{ .t = 3101724975, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.6610718, .y = 0.39520264, .pressure = 0.022888184 } } }, + .{ .t = 3101732005, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.66574097, .y = 0.39642334, .pressure = 0.021484375 } } }, + .{ .t = 3101735255, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.6701355, .y = 0.3973999, .pressure = 0.019805908 } } }, + .{ .t = 3113361458, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.6748352, .y = 0.39767456, .pressure = 0.0206604 } } }, + .{ .t = 3113368498, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.67944336, .y = 0.39797974, .pressure = 0.022613525 } } }, + .{ .t = 3113372028, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.6838379, .y = 0.39785767, .pressure = 0.022338867 } } }, + .{ .t = 3123796833, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.6879883, .y = 0.3970642, .pressure = 0.01953125 } } }, + .{ .t = 3123803053, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.69177246, .y = 0.39624023, .pressure = 0.018127441 } } }, + .{ .t = 3123806563, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.69555664, .y = 0.39569092, .pressure = 0.016998291 } } }, + .{ .t = 3134998596, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.69888306, .y = 0.3942871, .pressure = 0.016998291 } } }, + .{ .t = 3135007066, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.7023926, .y = 0.39257812, .pressure = 0.017578125 } } }, + .{ .t = 3135011336, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.7060852, .y = 0.39056396, .pressure = 0.017578125 } } }, + .{ .t = 3146195970, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.7102051, .y = 0.38861084, .pressure = 0.015594482 } } }, + .{ .t = 3146202620, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.715271, .y = 0.386261, .pressure = 0.014190674 } } }, + .{ .t = 3157408853, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.7234802, .y = 0.38327026, .pressure = 0.01586914 } } }, + .{ .t = 3157418073, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.730896, .y = 0.38006592, .pressure = 0.01586914 } } }, + .{ .t = 3157423313, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.73880005, .y = 0.37652588, .pressure = 0.016448975 } } }, + .{ .t = 3168334437, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.74557495, .y = 0.37350464, .pressure = 0.017578125 } } }, + .{ .t = 3168341357, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.75097656, .y = 0.37020874, .pressure = 0.016723633 } } }, + .{ .t = 3168344697, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.7561035, .y = 0.36791992, .pressure = 0.013916016 } } }, + .{ .t = 3179518520, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.75982666, .y = 0.36517334, .pressure = 0.013061523 } } }, + .{ .t = 3179524910, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.7633362, .y = 0.3623352, .pressure = 0.013061523 } } }, + .{ .t = 3179530860, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.765625, .y = 0.35949707, .pressure = 0.013641357 } } }, + .{ .t = 3190702424, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.7669678, .y = 0.3564453, .pressure = 0.012786865 } } }, + .{ .t = 3190710904, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.76849365, .y = 0.3536682, .pressure = 0.011383057 } } }, + .{ .t = 3201886237, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.7687378, .y = 0.35095215, .pressure = 0.010559082 } } }, + .{ .t = 3201895897, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.7681885, .y = 0.34838867, .pressure = 0.009155273 } } }, + .{ .t = 3201900097, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.7668457, .y = 0.34570312, .pressure = 0.009155273 } } }, + .{ .t = 3212919591, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.7654724, .y = 0.34277344, .pressure = 0.008850098 } } }, + .{ .t = 3212927311, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.7631836, .y = 0.34002686, .pressure = 0.0066223145 } } }, + .{ .t = 3212932591, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.7612915, .y = 0.3373413, .pressure = 0.0040893555 } } }, + .{ .t = 3224127654, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.7590027, .y = 0.33529663, .pressure = 0.0043640137 } } }, + .{ .t = 3224134564, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.7567444, .y = 0.33319092, .pressure = 0.0024108887 } } }, + .{ .t = 3224138834, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.7541809, .y = 0.3307495, .pressure = 0.00491333 } } }, + .{ .t = 3234961798, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.75216675, .y = 0.32843018, .pressure = 0.0038146973 } } }, + .{ .t = 3234967628, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.7489929, .y = 0.32583618, .pressure = 0.0038146973 } } }, + .{ .t = 3234971398, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.7467346, .y = 0.32296753, .pressure = 0.005218506 } } }, + .{ .t = 3246367272, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.7436218, .y = 0.32019043, .pressure = 0.0043640137 } } }, + .{ .t = 3246376701, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.7402649, .y = 0.3173523, .pressure = 0.0038146973 } } }, + .{ .t = 3257870675, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.73721313, .y = 0.31466675, .pressure = 0.0018310547 } } }, + .{ .t = 3257881104, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.7336731, .y = 0.31219482, .pressure = 0.0024108887 } } }, + .{ .t = 3257886264, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.73062134, .y = 0.3100891, .pressure = 0.0015563965 } } }, + .{ .t = 3268291019, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.72720337, .y = 0.30807495, .pressure = 0.0007019043 } } }, + .{ .t = 3268298969, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.7241516, .y = 0.30593872, .pressure = 0.0015563965 } } }, + .{ .t = 3268303569, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.7213135, .y = 0.30371094, .pressure = 0.0035095215 } } }, + .{ .t = 3279746522, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.71810913, .y = 0.302063, .pressure = 0.002960205 } } }, + .{ .t = 3279757542, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.7147217, .y = 0.30056763, .pressure = 0.00491333 } } }, + .{ .t = 3279762862, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.71087646, .y = 0.29907227, .pressure = 0.00491333 } } }, + .{ .t = 3290574016, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.70751953, .y = 0.29745483, .pressure = 0.0040893555 } } }, + .{ .t = 3290581596, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.70376587, .y = 0.29592896, .pressure = 0.0040893555 } } }, + .{ .t = 3301750300, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.6994934, .y = 0.2951355, .pressure = 0.0038146973 } } }, + .{ .t = 3301760370, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.6951904, .y = 0.29397583, .pressure = 0.005218506 } } }, + .{ .t = 3301767410, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.6905823, .y = 0.29284668, .pressure = 0.00491333 } } }, + .{ .t = 3312951293, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.685791, .y = 0.29266357, .pressure = 0.0068969727 } } }, + .{ .t = 3312959893, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.68136597, .y = 0.29257202, .pressure = 0.005493164 } } }, + .{ .t = 3312965373, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.6772461, .y = 0.29229736, .pressure = 0.0068969727 } } }, + .{ .t = 3324079267, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.672699, .y = 0.29318237, .pressure = 0.004638672 } } }, + .{ .t = 3324090337, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.66882324, .y = 0.294281, .pressure = 0.004638672 } } }, + .{ .t = 3324095997, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.66537476, .y = 0.29525757, .pressure = 0.004638672 } } }, + .{ .t = 3335061800, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.6620178, .y = 0.2966919, .pressure = 0.002960205 } } }, + .{ .t = 3335068160, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.6590576, .y = 0.29788208, .pressure = 0.0007019043 } } }, + .{ .t = 3335073750, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .up, .x = 0.6562805, .y = 0.29956055, .pressure = 0 } } }, + .{ .t = 3390587188, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .down, .x = 0.6447449, .y = 0.33596802, .pressure = 0.0007019043 } } }, + .{ .t = 3390593138, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.6447754, .y = 0.3406067, .pressure = 0.0035095215 } } }, } } diff --git a/test/deck/triggers.zon b/test/deck/triggers.zon index ad5f7656..8cac4b66 100644 --- a/test/deck/triggers.zon +++ b/test/deck/triggers.zon @@ -1,576 +1,576 @@ .{ .version = 1, .events = .{ -.{.t=3100837937,.pad=2,.ev=.{.axis=.{.idx=3,.value=997}}}, -.{.t=3100845387,.pad=2,.ev=.{.axis=.{.idx=0,.value=-829}}}, -.{.t=3100845387,.pad=2,.ev=.{.axis=.{.idx=1,.value=-1441}}}, -.{.t=3100845387,.pad=2,.ev=.{.axis=.{.idx=3,.value=1027}}}, -.{.t=3100849157,.pad=2,.ev=.{.axis=.{.idx=0,.value=-802}}}, -.{.t=3100849157,.pad=2,.ev=.{.axis=.{.idx=1,.value=-1411}}}, -.{.t=3100849157,.pad=2,.ev=.{.axis=.{.idx=3,.value=1057}}}, -.{.t=3111923010,.pad=2,.ev=.{.axis=.{.idx=0,.value=-829}}}, -.{.t=3111923010,.pad=2,.ev=.{.axis=.{.idx=1,.value=-1529}}}, -.{.t=3111923010,.pad=2,.ev=.{.axis=.{.idx=3,.value=1027}}}, -.{.t=3111936310,.pad=2,.ev=.{.axis=.{.idx=0,.value=-802}}}, -.{.t=3111936310,.pad=2,.ev=.{.axis=.{.idx=1,.value=-1323}}}, -.{.t=3111941850,.pad=2,.ev=.{.axis=.{.idx=1,.value=-1558}}}, -.{.t=3111941850,.pad=2,.ev=.{.axis=.{.idx=3,.value=997}}}, -.{.t=3123013224,.pad=2,.ev=.{.axis=.{.idx=0,.value=-829}}}, -.{.t=3123013224,.pad=2,.ev=.{.axis=.{.idx=1,.value=-1294}}}, -.{.t=3123013224,.pad=2,.ev=.{.axis=.{.idx=3,.value=1027}}}, -.{.t=3123021794,.pad=2,.ev=.{.axis=.{.idx=0,.value=-802}}}, -.{.t=3123021794,.pad=2,.ev=.{.axis=.{.idx=1,.value=-941}}}, -.{.t=3123021794,.pad=2,.ev=.{.axis=.{.idx=3,.value=997}}}, -.{.t=3134267607,.pad=2,.ev=.{.axis=.{.idx=5,.value=0}}}, -.{.t=3134267607,.pad=2,.ev=.{.axis=.{.idx=5,.value=214}}}, -.{.t=3134267607,.pad=2,.ev=.{.axis=.{.idx=0,.value=-829}}}, -.{.t=3134267607,.pad=2,.ev=.{.axis=.{.idx=1,.value=-647}}}, -.{.t=3134277137,.pad=2,.ev=.{.axis=.{.idx=5,.value=2674}}}, -.{.t=3134277137,.pad=2,.ev=.{.axis=.{.idx=0,.value=-802}}}, -.{.t=3134277137,.pad=2,.ev=.{.axis=.{.idx=1,.value=-500}}}, -.{.t=3134280727,.pad=2,.ev=.{.axis=.{.idx=5,.value=5436}}}, -.{.t=3134280727,.pad=2,.ev=.{.axis=.{.idx=0,.value=-829}}}, -.{.t=3134280727,.pad=2,.ev=.{.axis=.{.idx=1,.value=-206}}}, -.{.t=3134280727,.pad=2,.ev=.{.axis=.{.idx=3,.value=1027}}}, -.{.t=3146260210,.pad=2,.ev=.{.axis=.{.idx=5,.value=8198}}}, -.{.t=3146260210,.pad=2,.ev=.{.axis=.{.idx=0,.value=-774}}}, -.{.t=3146260210,.pad=2,.ev=.{.axis=.{.idx=1,.value=-176}}}, -.{.t=3146260210,.pad=2,.ev=.{.axis=.{.idx=3,.value=997}}}, -.{.t=3146270520,.pad=2,.ev=.{.axis=.{.idx=5,.value=11211}}}, -.{.t=3146270520,.pad=2,.ev=.{.axis=.{.idx=0,.value=-802}}}, -.{.t=3146270520,.pad=2,.ev=.{.axis=.{.idx=1,.value=-29}}}, -.{.t=3146274870,.pad=2,.ev=.{.axis=.{.idx=5,.value=13671}}}, -.{.t=3146274870,.pad=2,.ev=.{.axis=.{.idx=1,.value=86}}}, -.{.t=3146274870,.pad=2,.ev=.{.axis=.{.idx=3,.value=1027}}}, -.{.t=3156416215,.pad=2,.ev=.{.axis=.{.idx=5,.value=16432}}}, -.{.t=3156416215,.pad=2,.ev=.{.axis=.{.idx=0,.value=-829}}}, -.{.t=3156416215,.pad=2,.ev=.{.axis=.{.idx=1,.value=288}}}, -.{.t=3156416215,.pad=2,.ev=.{.axis=.{.idx=3,.value=997}}}, -.{.t=3156435465,.pad=2,.ev=.{.axis=.{.idx=5,.value=18893}}}, -.{.t=3156435465,.pad=2,.ev=.{.axis=.{.idx=0,.value=-802}}}, -.{.t=3156435465,.pad=2,.ev=.{.axis=.{.idx=1,.value=462}}}, -.{.t=3156441825,.pad=2,.ev=.{.axis=.{.idx=5,.value=21504}}}, -.{.t=3156441825,.pad=2,.ev=.{.axis=.{.idx=1,.value=491}}}, -.{.t=3156441825,.pad=2,.ev=.{.axis=.{.idx=3,.value=1057}}}, -.{.t=3167440508,.pad=2,.ev=.{.axis=.{.idx=5,.value=23915}}}, -.{.t=3167440508,.pad=2,.ev=.{.axis=.{.idx=1,.value=664}}}, -.{.t=3167440508,.pad=2,.ev=.{.axis=.{.idx=3,.value=1027}}}, -.{.t=3167449678,.pad=2,.ev=.{.axis=.{.idx=5,.value=26224}}}, -.{.t=3167449678,.pad=2,.ev=.{.axis=.{.idx=0,.value=-829}}}, -.{.t=3167449678,.pad=2,.ev=.{.axis=.{.idx=1,.value=779}}}, -.{.t=3167449678,.pad=2,.ev=.{.axis=.{.idx=3,.value=997}}}, -.{.t=3178634312,.pad=2,.ev=.{.axis=.{.idx=5,.value=28384}}}, -.{.t=3178634312,.pad=2,.ev=.{.axis=.{.idx=0,.value=-802}}}, -.{.t=3178634312,.pad=2,.ev=.{.axis=.{.idx=1,.value=837}}}, -.{.t=3178634312,.pad=2,.ev=.{.axis=.{.idx=3,.value=1027}}}, -.{.t=3178646332,.pad=2,.ev=.{.axis=.{.idx=5,.value=30593}}}, -.{.t=3178646332,.pad=2,.ev=.{.axis=.{.idx=0,.value=-829}}}, -.{.t=3178646332,.pad=2,.ev=.{.axis=.{.idx=3,.value=997}}}, -.{.t=3178651472,.pad=2,.ev=.{.axis=.{.idx=5,.value=32702}}}, -.{.t=3178651472,.pad=2,.ev=.{.axis=.{.idx=0,.value=-802}}}, -.{.t=3189737565,.pad=2,.ev=.{.axis=.{.idx=5,.value=32766}}}, -.{.t=3189737565,.pad=2,.ev=.{.axis=.{.idx=1,.value=924}}}, -.{.t=3189737565,.pad=2,.ev=.{.axis=.{.idx=3,.value=1027}}}, -.{.t=3189748175,.pad=2,.ev=.{.axis=.{.idx=3,.value=1057}}}, -.{.t=3189751215,.pad=2,.ev=.{.axis=.{.idx=1,.value=953}}}, -.{.t=3189751215,.pad=2,.ev=.{.axis=.{.idx=3,.value=1027}}}, -.{.t=3200899959,.pad=2,.ev=.{.axis=.{.idx=3,.value=997}}}, -.{.t=3200909349,.pad=2,.ev=.{.axis=.{.idx=0,.value=-774}}}, -.{.t=3200909349,.pad=2,.ev=.{.axis=.{.idx=1,.value=924}}}, -.{.t=3200914229,.pad=2,.ev=.{.axis=.{.idx=0,.value=-802}}}, -.{.t=3200914229,.pad=2,.ev=.{.axis=.{.idx=1,.value=953}}}, -.{.t=3200914229,.pad=2,.ev=.{.axis=.{.idx=3,.value=1027}}}, -.{.t=3212027402,.pad=2,.ev=.{.axis=.{.idx=0,.value=-829}}}, -.{.t=3212027402,.pad=2,.ev=.{.axis=.{.idx=1,.value=1010}}}, -.{.t=3212027402,.pad=2,.ev=.{.axis=.{.idx=3,.value=997}}}, -.{.t=3212033902,.pad=2,.ev=.{.axis=.{.idx=3,.value=1027}}}, -.{.t=3222960156,.pad=2,.ev=.{.axis=.{.idx=1,.value=981}}}, -.{.t=3222960156,.pad=2,.ev=.{.axis=.{.idx=3,.value=997}}}, -.{.t=3222967916,.pad=2,.ev=.{.axis=.{.idx=0,.value=-802}}}, -.{.t=3222967916,.pad=2,.ev=.{.axis=.{.idx=1,.value=953}}}, -.{.t=3222967916,.pad=2,.ev=.{.axis=.{.idx=3,.value=1087}}}, -.{.t=3234186130,.pad=2,.ev=.{.axis=.{.idx=0,.value=-857}}}, -.{.t=3234186130,.pad=2,.ev=.{.axis=.{.idx=1,.value=981}}}, -.{.t=3234186130,.pad=2,.ev=.{.axis=.{.idx=3,.value=1027}}}, -.{.t=3234194710,.pad=2,.ev=.{.axis=.{.idx=0,.value=-802}}}, -.{.t=3234194710,.pad=2,.ev=.{.axis=.{.idx=1,.value=953}}}, -.{.t=3234194710,.pad=2,.ev=.{.axis=.{.idx=3,.value=997}}}, -.{.t=3234198480,.pad=2,.ev=.{.axis=.{.idx=0,.value=-829}}}, -.{.t=3234198480,.pad=2,.ev=.{.axis=.{.idx=1,.value=1097}}}, -.{.t=3245272663,.pad=2,.ev=.{.axis=.{.idx=1,.value=1126}}}, -.{.t=3245272663,.pad=2,.ev=.{.axis=.{.idx=3,.value=1057}}}, -.{.t=3245280873,.pad=2,.ev=.{.axis=.{.idx=0,.value=-802}}}, -.{.t=3245280873,.pad=2,.ev=.{.axis=.{.idx=3,.value=997}}}, -.{.t=3245284263,.pad=2,.ev=.{.axis=.{.idx=1,.value=1097}}}, -.{.t=3245284263,.pad=2,.ev=.{.axis=.{.idx=3,.value=1027}}}, -.{.t=3256351647,.pad=2,.ev=.{.axis=.{.idx=0,.value=-829}}}, -.{.t=3256351647,.pad=2,.ev=.{.axis=.{.idx=3,.value=997}}}, -.{.t=3256361897,.pad=2,.ev=.{.axis=.{.idx=1,.value=1126}}}, -.{.t=3256361897,.pad=2,.ev=.{.axis=.{.idx=3,.value=1027}}}, -.{.t=3256366557,.pad=2,.ev=.{.axis=.{.idx=0,.value=-857}}}, -.{.t=3267453910,.pad=2,.ev=.{.axis=.{.idx=0,.value=-829}}}, -.{.t=3267461450,.pad=2,.ev=.{.axis=.{.idx=0,.value=-802}}}, -.{.t=3267461450,.pad=2,.ev=.{.axis=.{.idx=1,.value=1097}}}, -.{.t=3267461450,.pad=2,.ev=.{.axis=.{.idx=3,.value=1057}}}, -.{.t=3278671394,.pad=2,.ev=.{.axis=.{.idx=3,.value=1027}}}, -.{.t=3278679494,.pad=2,.ev=.{.axis=.{.idx=0,.value=-829}}}, -.{.t=3278679494,.pad=2,.ev=.{.axis=.{.idx=1,.value=1126}}}, -.{.t=3278679494,.pad=2,.ev=.{.axis=.{.idx=3,.value=997}}}, -.{.t=3278684284,.pad=2,.ev=.{.axis=.{.idx=1,.value=1097}}}, -.{.t=3289747017,.pad=2,.ev=.{.axis=.{.idx=0,.value=-802}}}, -.{.t=3289757957,.pad=2,.ev=.{.axis=.{.idx=0,.value=-774}}}, -.{.t=3289757957,.pad=2,.ev=.{.axis=.{.idx=1,.value=1068}}}, -.{.t=3289757957,.pad=2,.ev=.{.axis=.{.idx=3,.value=1057}}}, -.{.t=3289764977,.pad=2,.ev=.{.axis=.{.idx=0,.value=-829}}}, -.{.t=3289764977,.pad=2,.ev=.{.axis=.{.idx=3,.value=1027}}}, -.{.t=3300894251,.pad=2,.ev=.{.axis=.{.idx=0,.value=-802}}}, -.{.t=3300894251,.pad=2,.ev=.{.axis=.{.idx=3,.value=1057}}}, -.{.t=3300904161,.pad=2,.ev=.{.axis=.{.idx=0,.value=-829}}}, -.{.t=3300904161,.pad=2,.ev=.{.axis=.{.idx=3,.value=1027}}}, -.{.t=3300908771,.pad=2,.ev=.{.axis=.{.idx=3,.value=1057}}}, -.{.t=3312130554,.pad=2,.ev=.{.axis=.{.idx=0,.value=-802}}}, -.{.t=3312130554,.pad=2,.ev=.{.axis=.{.idx=1,.value=1039}}}, -.{.t=3312130554,.pad=2,.ev=.{.axis=.{.idx=3,.value=1027}}}, -.{.t=3312142164,.pad=2,.ev=.{.axis=.{.idx=3,.value=1057}}}, -.{.t=3312145624,.pad=2,.ev=.{.axis=.{.idx=0,.value=-829}}}, -.{.t=3312145624,.pad=2,.ev=.{.axis=.{.idx=1,.value=1068}}}, -.{.t=3312145624,.pad=2,.ev=.{.axis=.{.idx=3,.value=1027}}}, -.{.t=3323185928,.pad=2,.ev=.{.axis=.{.idx=0,.value=-802}}}, -.{.t=3323185928,.pad=2,.ev=.{.axis=.{.idx=1,.value=1039}}}, -.{.t=3323197438,.pad=2,.ev=.{.axis=.{.idx=1,.value=1010}}}, -.{.t=3334415941,.pad=2,.ev=.{.axis=.{.idx=0,.value=-829}}}, -.{.t=3334415941,.pad=2,.ev=.{.axis=.{.idx=3,.value=1057}}}, -.{.t=3334428191,.pad=2,.ev=.{.axis=.{.idx=0,.value=-802}}}, -.{.t=3334428191,.pad=2,.ev=.{.axis=.{.idx=3,.value=1027}}}, -.{.t=3334433441,.pad=2,.ev=.{.axis=.{.idx=0,.value=-829}}}, -.{.t=3345319335,.pad=2,.ev=.{.axis=.{.idx=0,.value=-802}}}, -.{.t=3345319335,.pad=2,.ev=.{.axis=.{.idx=1,.value=1039}}}, -.{.t=3345329665,.pad=2,.ev=.{.axis=.{.idx=0,.value=-774}}}, -.{.t=3345329665,.pad=2,.ev=.{.axis=.{.idx=1,.value=1010}}}, -.{.t=3345329665,.pad=2,.ev=.{.axis=.{.idx=3,.value=997}}}, -.{.t=3345334835,.pad=2,.ev=.{.axis=.{.idx=0,.value=-802}}}, -.{.t=3356434069,.pad=2,.ev=.{.axis=.{.idx=0,.value=-829}}}, -.{.t=3356434069,.pad=2,.ev=.{.axis=.{.idx=1,.value=1039}}}, -.{.t=3356434069,.pad=2,.ev=.{.axis=.{.idx=3,.value=1027}}}, -.{.t=3356449919,.pad=2,.ev=.{.axis=.{.idx=0,.value=-802}}}, -.{.t=3356449919,.pad=2,.ev=.{.axis=.{.idx=1,.value=1010}}}, -.{.t=3356449919,.pad=2,.ev=.{.axis=.{.idx=3,.value=997}}}, -.{.t=3367716072,.pad=2,.ev=.{.axis=.{.idx=0,.value=-857}}}, -.{.t=3367716072,.pad=2,.ev=.{.axis=.{.idx=1,.value=1068}}}, -.{.t=3367728332,.pad=2,.ev=.{.axis=.{.idx=0,.value=-829}}}, -.{.t=3367728332,.pad=2,.ev=.{.axis=.{.idx=1,.value=1039}}}, -.{.t=3367728332,.pad=2,.ev=.{.axis=.{.idx=3,.value=1027}}}, -.{.t=3367733692,.pad=2,.ev=.{.axis=.{.idx=0,.value=-802}}}, -.{.t=3367733692,.pad=2,.ev=.{.axis=.{.idx=1,.value=1010}}}, -.{.t=3367733692,.pad=2,.ev=.{.axis=.{.idx=3,.value=1057}}}, -.{.t=3378615526,.pad=2,.ev=.{.axis=.{.idx=3,.value=997}}}, -.{.t=3389836929,.pad=2,.ev=.{.axis=.{.idx=0,.value=-774}}}, -.{.t=3389836929,.pad=2,.ev=.{.axis=.{.idx=1,.value=981}}}, -.{.t=3389836929,.pad=2,.ev=.{.axis=.{.idx=3,.value=1027}}}, -.{.t=3389847129,.pad=2,.ev=.{.axis=.{.idx=5,.value=31648}}}, -.{.t=3389847129,.pad=2,.ev=.{.axis=.{.idx=0,.value=-802}}}, -.{.t=3389847129,.pad=2,.ev=.{.axis=.{.idx=1,.value=1010}}}, -.{.t=3389852719,.pad=2,.ev=.{.axis=.{.idx=5,.value=29137}}}, -.{.t=3389852719,.pad=2,.ev=.{.axis=.{.idx=1,.value=1039}}}, -.{.t=3401186593,.pad=2,.ev=.{.axis=.{.idx=5,.value=26074}}}, -.{.t=3401186593,.pad=2,.ev=.{.axis=.{.idx=0,.value=-829}}}, -.{.t=3401194003,.pad=2,.ev=.{.axis=.{.idx=5,.value=23262}}}, -.{.t=3401194003,.pad=2,.ev=.{.axis=.{.idx=0,.value=-802}}}, -.{.t=3401194003,.pad=2,.ev=.{.axis=.{.idx=1,.value=1010}}}, -.{.t=3401194003,.pad=2,.ev=.{.axis=.{.idx=3,.value=1057}}}, -.{.t=3401198713,.pad=2,.ev=.{.axis=.{.idx=5,.value=20349}}}, -.{.t=3401198713,.pad=2,.ev=.{.axis=.{.idx=3,.value=997}}}, -.{.t=3411932407,.pad=2,.ev=.{.axis=.{.idx=5,.value=17587}}}, -.{.t=3411932407,.pad=2,.ev=.{.axis=.{.idx=0,.value=-829}}}, -.{.t=3411932407,.pad=2,.ev=.{.axis=.{.idx=1,.value=1039}}}, -.{.t=3411941077,.pad=2,.ev=.{.axis=.{.idx=5,.value=15127}}}, -.{.t=3411941077,.pad=2,.ev=.{.axis=.{.idx=0,.value=-802}}}, -.{.t=3411941077,.pad=2,.ev=.{.axis=.{.idx=3,.value=1027}}}, -.{.t=3411944947,.pad=2,.ev=.{.axis=.{.idx=5,.value=12617}}}, -.{.t=3411944947,.pad=2,.ev=.{.axis=.{.idx=0,.value=-829}}}, -.{.t=3411944947,.pad=2,.ev=.{.axis=.{.idx=1,.value=953}}}, -.{.t=3411944947,.pad=2,.ev=.{.axis=.{.idx=3,.value=997}}}, -.{.t=3423178470,.pad=2,.ev=.{.axis=.{.idx=5,.value=10307}}}, -.{.t=3423178470,.pad=2,.ev=.{.axis=.{.idx=0,.value=-802}}}, -.{.t=3423178470,.pad=2,.ev=.{.axis=.{.idx=1,.value=924}}}, -.{.t=3423187080,.pad=2,.ev=.{.axis=.{.idx=5,.value=8298}}}, -.{.t=3423187080,.pad=2,.ev=.{.axis=.{.idx=1,.value=981}}}, -.{.t=3423187080,.pad=2,.ev=.{.axis=.{.idx=3,.value=1027}}}, -.{.t=3434307174,.pad=2,.ev=.{.axis=.{.idx=5,.value=6340}}}, -.{.t=3434307174,.pad=2,.ev=.{.axis=.{.idx=1,.value=924}}}, -.{.t=3434315334,.pad=2,.ev=.{.axis=.{.idx=5,.value=4532}}}, -.{.t=3434315334,.pad=2,.ev=.{.axis=.{.idx=3,.value=997}}}, -.{.t=3434318744,.pad=2,.ev=.{.axis=.{.idx=5,.value=2975}}}, -.{.t=3434318744,.pad=2,.ev=.{.axis=.{.idx=1,.value=866}}}, -.{.t=3445336427,.pad=2,.ev=.{.axis=.{.idx=5,.value=1067}}}, -.{.t=3445336427,.pad=2,.ev=.{.axis=.{.idx=1,.value=635}}}, -.{.t=3445344507,.pad=2,.ev=.{.axis=.{.idx=4,.value=446}}}, -.{.t=3445344507,.pad=2,.ev=.{.axis=.{.idx=5,.value=0}}}, -.{.t=3445344507,.pad=2,.ev=.{.axis=.{.idx=1,.value=346}}}, -.{.t=3445344507,.pad=2,.ev=.{.axis=.{.idx=3,.value=1027}}}, -.{.t=3445348567,.pad=2,.ev=.{.axis=.{.idx=4,.value=1854}}}, -.{.t=3445348567,.pad=2,.ev=.{.axis=.{.idx=1,.value=-59}}}, -.{.t=3456475621,.pad=2,.ev=.{.axis=.{.idx=4,.value=3310}}}, -.{.t=3456475621,.pad=2,.ev=.{.axis=.{.idx=1,.value=-176}}}, -.{.t=3456475621,.pad=2,.ev=.{.axis=.{.idx=3,.value=997}}}, -.{.t=3456483971,.pad=2,.ev=.{.axis=.{.idx=4,.value=4436}}}, -.{.t=3456483971,.pad=2,.ev=.{.axis=.{.idx=1,.value=-441}}}, -.{.t=3456487161,.pad=2,.ev=.{.axis=.{.idx=4,.value=5891}}}, -.{.t=3456487161,.pad=2,.ev=.{.axis=.{.idx=1,.value=-558}}}, -.{.t=22900269279,.pad=2,.ev=.{.axis=.{.idx=0,.value=-1493}}}, -.{.t=22900269279,.pad=2,.ev=.{.axis=.{.idx=1,.value=981}}}, -.{.t=22900269279,.pad=2,.ev=.{.axis=.{.idx=3,.value=1087}}}, -.{.t=22900282319,.pad=2,.ev=.{.axis=.{.idx=0,.value=-1465}}}, -.{.t=22900282319,.pad=2,.ev=.{.axis=.{.idx=1,.value=953}}}, -.{.t=22900282319,.pad=2,.ev=.{.axis=.{.idx=2,.value=-469}}}, -.{.t=22900282319,.pad=2,.ev=.{.axis=.{.idx=3,.value=1118}}}, -.{.t=22900288339,.pad=2,.ev=.{.axis=.{.idx=1,.value=981}}}, -.{.t=22900288339,.pad=2,.ev=.{.axis=.{.idx=2,.value=-439}}}, -.{.t=22900288339,.pad=2,.ev=.{.axis=.{.idx=3,.value=1087}}}, -.{.t=22911078513,.pad=2,.ev=.{.axis=.{.idx=0,.value=-1438}}}, -.{.t=22911078513,.pad=2,.ev=.{.axis=.{.idx=1,.value=953}}}, -.{.t=22911078513,.pad=2,.ev=.{.axis=.{.idx=2,.value=-469}}}, -.{.t=22911090183,.pad=2,.ev=.{.axis=.{.idx=2,.value=-498}}}, -.{.t=22922174447,.pad=2,.ev=.{.axis=.{.idx=0,.value=-1465}}}, -.{.t=22922174447,.pad=2,.ev=.{.axis=.{.idx=2,.value=-527}}}, -.{.t=22922174447,.pad=2,.ev=.{.axis=.{.idx=3,.value=1148}}}, -.{.t=22922182927,.pad=2,.ev=.{.axis=.{.idx=0,.value=-1493}}}, -.{.t=22922182927,.pad=2,.ev=.{.axis=.{.idx=1,.value=981}}}, -.{.t=22922182927,.pad=2,.ev=.{.axis=.{.idx=2,.value=-498}}}, -.{.t=22922182927,.pad=2,.ev=.{.axis=.{.idx=3,.value=1118}}}, -.{.t=22922186907,.pad=2,.ev=.{.axis=.{.idx=0,.value=-1465}}}, -.{.t=22933453380,.pad=2,.ev=.{.axis=.{.idx=2,.value=-469}}}, -.{.t=22933463530,.pad=2,.ev=.{.axis=.{.idx=0,.value=-1438}}}, -.{.t=22933463530,.pad=2,.ev=.{.axis=.{.idx=1,.value=924}}}, -.{.t=22933463530,.pad=2,.ev=.{.axis=.{.idx=2,.value=-498}}}, -.{.t=22933463530,.pad=2,.ev=.{.axis=.{.idx=3,.value=1148}}}, -.{.t=22933469520,.pad=2,.ev=.{.axis=.{.idx=1,.value=953}}}, -.{.t=22933469520,.pad=2,.ev=.{.axis=.{.idx=2,.value=-469}}}, -.{.t=22933469520,.pad=2,.ev=.{.axis=.{.idx=3,.value=1118}}}, -.{.t=22944601464,.pad=2,.ev=.{.axis=.{.idx=2,.value=-439}}}, -.{.t=22944601464,.pad=2,.ev=.{.axis=.{.idx=3,.value=1087}}}, -.{.t=22944613874,.pad=2,.ev=.{.axis=.{.idx=0,.value=-1465}}}, -.{.t=22944613874,.pad=2,.ev=.{.axis=.{.idx=2,.value=-469}}}, -.{.t=22944613874,.pad=2,.ev=.{.axis=.{.idx=3,.value=1118}}}, -.{.t=22944619754,.pad=2,.ev=.{.axis=.{.idx=0,.value=-1438}}}, -.{.t=22955633677,.pad=2,.ev=.{.axis=.{.idx=0,.value=-1493}}}, -.{.t=22955633677,.pad=2,.ev=.{.axis=.{.idx=1,.value=981}}}, -.{.t=22955633677,.pad=2,.ev=.{.axis=.{.idx=2,.value=-439}}}, -.{.t=22955633677,.pad=2,.ev=.{.axis=.{.idx=3,.value=1087}}}, -.{.t=22955647207,.pad=2,.ev=.{.axis=.{.idx=0,.value=-1465}}}, -.{.t=22955647207,.pad=2,.ev=.{.axis=.{.idx=1,.value=953}}}, -.{.t=22955647207,.pad=2,.ev=.{.axis=.{.idx=2,.value=-498}}}, -.{.t=22955647207,.pad=2,.ev=.{.axis=.{.idx=3,.value=1148}}}, -.{.t=22955652047,.pad=2,.ev=.{.axis=.{.idx=0,.value=-1438}}}, -.{.t=22955652047,.pad=2,.ev=.{.axis=.{.idx=3,.value=1118}}}, -.{.t=22966619841,.pad=2,.ev=.{.axis=.{.idx=0,.value=-1465}}}, -.{.t=22966619841,.pad=2,.ev=.{.axis=.{.idx=2,.value=-469}}}, -.{.t=22966628121,.pad=2,.ev=.{.axis=.{.idx=1,.value=924}}}, -.{.t=22966628121,.pad=2,.ev=.{.axis=.{.idx=3,.value=1087}}}, -.{.t=22977745245,.pad=2,.ev=.{.axis=.{.idx=0,.value=-1438}}}, -.{.t=22977745245,.pad=2,.ev=.{.axis=.{.idx=1,.value=953}}}, -.{.t=22977745245,.pad=2,.ev=.{.axis=.{.idx=2,.value=-498}}}, -.{.t=22977745245,.pad=2,.ev=.{.axis=.{.idx=3,.value=1148}}}, -.{.t=22977753905,.pad=2,.ev=.{.axis=.{.idx=0,.value=-1465}}}, -.{.t=22977753905,.pad=2,.ev=.{.axis=.{.idx=2,.value=-469}}}, -.{.t=22977753905,.pad=2,.ev=.{.axis=.{.idx=3,.value=1118}}}, -.{.t=22977757525,.pad=2,.ev=.{.axis=.{.idx=2,.value=-439}}}, -.{.t=22988922908,.pad=2,.ev=.{.axis=.{.idx=0,.value=-1438}}}, -.{.t=22988922908,.pad=2,.ev=.{.axis=.{.idx=1,.value=981}}}, -.{.t=22988936008,.pad=2,.ev=.{.axis=.{.idx=0,.value=-1465}}}, -.{.t=22988936008,.pad=2,.ev=.{.axis=.{.idx=2,.value=-469}}}, -.{.t=22988940638,.pad=2,.ev=.{.axis=.{.idx=0,.value=-1438}}}, -.{.t=22988940638,.pad=2,.ev=.{.axis=.{.idx=1,.value=953}}}, -.{.t=23000140672,.pad=2,.ev=.{.axis=.{.idx=0,.value=-1465}}}, -.{.t=23000140672,.pad=2,.ev=.{.axis=.{.idx=2,.value=-498}}}, -.{.t=23000152872,.pad=2,.ev=.{.axis=.{.idx=0,.value=-1438}}}, -.{.t=23000152872,.pad=2,.ev=.{.axis=.{.idx=1,.value=924}}}, -.{.t=23000152872,.pad=2,.ev=.{.axis=.{.idx=2,.value=-439}}}, -.{.t=23000152872,.pad=2,.ev=.{.axis=.{.idx=3,.value=1087}}}, -.{.t=23000158442,.pad=2,.ev=.{.axis=.{.idx=0,.value=-1493}}}, -.{.t=23000158442,.pad=2,.ev=.{.axis=.{.idx=1,.value=953}}}, -.{.t=23000158442,.pad=2,.ev=.{.axis=.{.idx=2,.value=-410}}}, -.{.t=23011247285,.pad=2,.ev=.{.axis=.{.idx=0,.value=-1438}}}, -.{.t=23011247285,.pad=2,.ev=.{.axis=.{.idx=2,.value=-439}}}, -.{.t=23011247285,.pad=2,.ev=.{.axis=.{.idx=3,.value=1057}}}, -.{.t=23011260265,.pad=2,.ev=.{.axis=.{.idx=0,.value=-1465}}}, -.{.t=23011260265,.pad=2,.ev=.{.axis=.{.idx=2,.value=-469}}}, -.{.t=23011260265,.pad=2,.ev=.{.axis=.{.idx=3,.value=1118}}}, -.{.t=23022366569,.pad=2,.ev=.{.axis=.{.idx=0,.value=-1438}}}, -.{.t=23022366569,.pad=2,.ev=.{.axis=.{.idx=1,.value=924}}}, -.{.t=23022366569,.pad=2,.ev=.{.axis=.{.idx=2,.value=-498}}}, -.{.t=23022366569,.pad=2,.ev=.{.axis=.{.idx=3,.value=1148}}}, -.{.t=23022380099,.pad=2,.ev=.{.axis=.{.idx=2,.value=-439}}}, -.{.t=23022380099,.pad=2,.ev=.{.axis=.{.idx=3,.value=1087}}}, -.{.t=23022385329,.pad=2,.ev=.{.axis=.{.idx=2,.value=-469}}}, -.{.t=23022385329,.pad=2,.ev=.{.axis=.{.idx=3,.value=1118}}}, -.{.t=23033207513,.pad=2,.ev=.{.axis=.{.idx=0,.value=-1465}}}, -.{.t=23033207513,.pad=2,.ev=.{.axis=.{.idx=1,.value=953}}}, -.{.t=23033215483,.pad=2,.ev=.{.axis=.{.idx=0,.value=-1438}}}, -.{.t=23033215483,.pad=2,.ev=.{.axis=.{.idx=1,.value=924}}}, -.{.t=23033215483,.pad=2,.ev=.{.axis=.{.idx=2,.value=-439}}}, -.{.t=23033215483,.pad=2,.ev=.{.axis=.{.idx=3,.value=1087}}}, -.{.t=23033219653,.pad=2,.ev=.{.axis=.{.idx=1,.value=953}}}, -.{.t=23044563226,.pad=2,.ev=.{.axis=.{.idx=1,.value=924}}}, -.{.t=23044563226,.pad=2,.ev=.{.axis=.{.idx=2,.value=-469}}}, -.{.t=23044563226,.pad=2,.ev=.{.axis=.{.idx=3,.value=1118}}}, -.{.t=23044572856,.pad=2,.ev=.{.axis=.{.idx=2,.value=-410}}}, -.{.t=23044572856,.pad=2,.ev=.{.axis=.{.idx=3,.value=1087}}}, -.{.t=23044576806,.pad=2,.ev=.{.axis=.{.idx=1,.value=953}}}, -.{.t=23044576806,.pad=2,.ev=.{.axis=.{.idx=2,.value=-469}}}, -.{.t=23044576806,.pad=2,.ev=.{.axis=.{.idx=3,.value=1118}}}, -.{.t=23055818709,.pad=2,.ev=.{.axis=.{.idx=0,.value=-1465}}}, -.{.t=23055818709,.pad=2,.ev=.{.axis=.{.idx=3,.value=1087}}}, -.{.t=23055828779,.pad=2,.ev=.{.axis=.{.idx=0,.value=-1438}}}, -.{.t=23055828779,.pad=2,.ev=.{.axis=.{.idx=1,.value=924}}}, -.{.t=23055828779,.pad=2,.ev=.{.axis=.{.idx=3,.value=1118}}}, -.{.t=23055832789,.pad=2,.ev=.{.axis=.{.idx=0,.value=-1410}}}, -.{.t=23055832789,.pad=2,.ev=.{.axis=.{.idx=3,.value=1087}}}, -.{.t=23066680603,.pad=2,.ev=.{.axis=.{.idx=0,.value=-1465}}}, -.{.t=23066680603,.pad=2,.ev=.{.axis=.{.idx=1,.value=953}}}, -.{.t=23066680603,.pad=2,.ev=.{.axis=.{.idx=3,.value=1118}}}, -.{.t=23066690143,.pad=2,.ev=.{.axis=.{.idx=0,.value=-1493}}}, -.{.t=23066690143,.pad=2,.ev=.{.axis=.{.idx=1,.value=981}}}, -.{.t=23066690143,.pad=2,.ev=.{.axis=.{.idx=2,.value=-439}}}, -.{.t=23066690143,.pad=2,.ev=.{.axis=.{.idx=3,.value=1087}}}, -.{.t=23077703397,.pad=2,.ev=.{.axis=.{.idx=0,.value=-1438}}}, -.{.t=23077703397,.pad=2,.ev=.{.axis=.{.idx=1,.value=924}}}, -.{.t=23077703397,.pad=2,.ev=.{.axis=.{.idx=3,.value=1118}}}, -.{.t=23077711687,.pad=2,.ev=.{.axis=.{.idx=0,.value=-1465}}}, -.{.t=23077711687,.pad=2,.ev=.{.axis=.{.idx=1,.value=953}}}, -.{.t=23077711687,.pad=2,.ev=.{.axis=.{.idx=2,.value=-469}}}, -.{.t=23077715567,.pad=2,.ev=.{.axis=.{.idx=0,.value=-1493}}}, -.{.t=23077715567,.pad=2,.ev=.{.axis=.{.idx=1,.value=981}}}, -.{.t=23077715567,.pad=2,.ev=.{.axis=.{.idx=2,.value=-439}}}, -.{.t=23077715567,.pad=2,.ev=.{.axis=.{.idx=3,.value=1087}}}, -.{.t=23088844720,.pad=2,.ev=.{.axis=.{.idx=0,.value=-1438}}}, -.{.t=23088844720,.pad=2,.ev=.{.axis=.{.idx=1,.value=953}}}, -.{.t=23088844720,.pad=2,.ev=.{.axis=.{.idx=2,.value=-498}}}, -.{.t=23088844720,.pad=2,.ev=.{.axis=.{.idx=3,.value=1148}}}, -.{.t=23088853270,.pad=2,.ev=.{.axis=.{.idx=0,.value=-1465}}}, -.{.t=23088853270,.pad=2,.ev=.{.axis=.{.idx=2,.value=-469}}}, -.{.t=23088853270,.pad=2,.ev=.{.axis=.{.idx=3,.value=1118}}}, -.{.t=23088856830,.pad=2,.ev=.{.axis=.{.idx=0,.value=-1438}}}, -.{.t=23088856830,.pad=2,.ev=.{.axis=.{.idx=1,.value=924}}}, -.{.t=23088856830,.pad=2,.ev=.{.axis=.{.idx=2,.value=-439}}}, -.{.t=23100184994,.pad=2,.ev=.{.axis=.{.idx=1,.value=953}}}, -.{.t=23100184994,.pad=2,.ev=.{.axis=.{.idx=2,.value=-410}}}, -.{.t=23100184994,.pad=2,.ev=.{.axis=.{.idx=3,.value=1087}}}, -.{.t=23100197834,.pad=2,.ev=.{.axis=.{.idx=0,.value=-1465}}}, -.{.t=23100202044,.pad=2,.ev=.{.axis=.{.idx=0,.value=-1438}}}, -.{.t=23100202044,.pad=2,.ev=.{.axis=.{.idx=1,.value=924}}}, -.{.t=23100202044,.pad=2,.ev=.{.axis=.{.idx=2,.value=-439}}}, -.{.t=23111316337,.pad=2,.ev=.{.axis=.{.idx=2,.value=-410}}}, -.{.t=23111328087,.pad=2,.ev=.{.axis=.{.idx=0,.value=-1465}}}, -.{.t=23111328087,.pad=2,.ev=.{.axis=.{.idx=2,.value=-439}}}, -.{.t=23122579831,.pad=2,.ev=.{.axis=.{.idx=0,.value=-1438}}}, -.{.t=23122579831,.pad=2,.ev=.{.axis=.{.idx=2,.value=-498}}}, -.{.t=23122579831,.pad=2,.ev=.{.axis=.{.idx=3,.value=1118}}}, -.{.t=23122592031,.pad=2,.ev=.{.axis=.{.idx=1,.value=953}}}, -.{.t=23122592031,.pad=2,.ev=.{.axis=.{.idx=2,.value=-469}}}, -.{.t=23122595681,.pad=2,.ev=.{.axis=.{.idx=1,.value=924}}}, -.{.t=23122595681,.pad=2,.ev=.{.axis=.{.idx=2,.value=-439}}}, -.{.t=23122595681,.pad=2,.ev=.{.axis=.{.idx=3,.value=1087}}}, -.{.t=23133201565,.pad=2,.ev=.{.axis=.{.idx=1,.value=953}}}, -.{.t=23133205635,.pad=2,.ev=.{.axis=.{.idx=4,.value=728}}}, -.{.t=23133205635,.pad=2,.ev=.{.axis=.{.idx=1,.value=924}}}, -.{.t=23133205635,.pad=2,.ev=.{.axis=.{.idx=3,.value=1118}}}, -.{.t=23144628108,.pad=2,.ev=.{.axis=.{.idx=4,.value=3169}}}, -.{.t=23144628108,.pad=2,.ev=.{.axis=.{.idx=0,.value=-1493}}}, -.{.t=23144628108,.pad=2,.ev=.{.axis=.{.idx=1,.value=953}}}, -.{.t=23144628108,.pad=2,.ev=.{.axis=.{.idx=2,.value=-410}}}, -.{.t=23144628108,.pad=2,.ev=.{.axis=.{.idx=3,.value=1087}}}, -.{.t=23144640728,.pad=2,.ev=.{.axis=.{.idx=4,.value=6314}}}, -.{.t=23144640728,.pad=2,.ev=.{.axis=.{.idx=0,.value=-1465}}}, -.{.t=23144640728,.pad=2,.ev=.{.axis=.{.idx=2,.value=-469}}}, -.{.t=23144640728,.pad=2,.ev=.{.axis=.{.idx=3,.value=1118}}}, -.{.t=23144644338,.pad=2,.ev=.{.axis=.{.idx=4,.value=10679}}}, -.{.t=23144644338,.pad=2,.ev=.{.axis=.{.idx=1,.value=981}}}, -.{.t=23144644338,.pad=2,.ev=.{.axis=.{.idx=2,.value=-410}}}, -.{.t=23144644338,.pad=2,.ev=.{.axis=.{.idx=3,.value=1087}}}, -.{.t=23155757852,.pad=2,.ev=.{.axis=.{.idx=4,.value=16500}}}, -.{.t=23155757852,.pad=2,.ev=.{.axis=.{.idx=0,.value=-1493}}}, -.{.t=23155757852,.pad=2,.ev=.{.axis=.{.idx=1,.value=953}}}, -.{.t=23155767512,.pad=2,.ev=.{.axis=.{.idx=4,.value=23682}}}, -.{.t=23155767512,.pad=2,.ev=.{.axis=.{.idx=0,.value=-1438}}}, -.{.t=23155767512,.pad=2,.ev=.{.axis=.{.idx=1,.value=924}}}, -.{.t=23155773302,.pad=2,.ev=.{.axis=.{.idx=4,.value=32084}}}, -.{.t=23155773302,.pad=2,.ev=.{.axis=.{.idx=0,.value=-1465}}}, -.{.t=23166856095,.pad=2,.ev=.{.axis=.{.idx=4,.value=32766}}}, -.{.t=23166856095,.pad=2,.ev=.{.axis=.{.idx=0,.value=-1438}}}, -.{.t=23166856095,.pad=2,.ev=.{.axis=.{.idx=2,.value=-439}}}, -.{.t=23166869315,.pad=2,.ev=.{.axis=.{.idx=1,.value=953}}}, -.{.t=23166869315,.pad=2,.ev=.{.axis=.{.idx=3,.value=1118}}}, -.{.t=23177937079,.pad=2,.ev=.{.axis=.{.idx=1,.value=924}}}, -.{.t=23177937079,.pad=2,.ev=.{.axis=.{.idx=3,.value=1087}}}, -.{.t=23177947099,.pad=2,.ev=.{.axis=.{.idx=0,.value=-1465}}}, -.{.t=23177947099,.pad=2,.ev=.{.axis=.{.idx=2,.value=-410}}}, -.{.t=23177950979,.pad=2,.ev=.{.axis=.{.idx=0,.value=-1438}}}, -.{.t=23177950979,.pad=2,.ev=.{.axis=.{.idx=2,.value=-439}}}, -.{.t=23177950979,.pad=2,.ev=.{.axis=.{.idx=3,.value=1118}}}, -.{.t=23188909763,.pad=2,.ev=.{.axis=.{.idx=2,.value=-410}}}, -.{.t=23188909763,.pad=2,.ev=.{.axis=.{.idx=3,.value=1087}}}, -.{.t=23188919373,.pad=2,.ev=.{.axis=.{.idx=0,.value=-1493}}}, -.{.t=23188919373,.pad=2,.ev=.{.axis=.{.idx=1,.value=981}}}, -.{.t=23188923533,.pad=2,.ev=.{.axis=.{.idx=0,.value=-1465}}}, -.{.t=23188923533,.pad=2,.ev=.{.axis=.{.idx=1,.value=953}}}, -.{.t=23188923533,.pad=2,.ev=.{.axis=.{.idx=2,.value=-439}}}, -.{.t=23188923533,.pad=2,.ev=.{.axis=.{.idx=3,.value=1057}}}, -.{.t=23200341706,.pad=2,.ev=.{.axis=.{.idx=0,.value=-1438}}}, -.{.t=23200341706,.pad=2,.ev=.{.axis=.{.idx=1,.value=924}}}, -.{.t=23200341706,.pad=2,.ev=.{.axis=.{.idx=3,.value=1087}}}, -.{.t=23200357446,.pad=2,.ev=.{.axis=.{.idx=2,.value=-469}}}, -.{.t=23200360546,.pad=2,.ev=.{.axis=.{.idx=1,.value=866}}}, -.{.t=23200360546,.pad=2,.ev=.{.axis=.{.idx=2,.value=-439}}}, -.{.t=23211356329,.pad=2,.ev=.{.axis=.{.idx=0,.value=-1493}}}, -.{.t=23211356329,.pad=2,.ev=.{.axis=.{.idx=1,.value=895}}}, -.{.t=23211356329,.pad=2,.ev=.{.axis=.{.idx=3,.value=1057}}}, -.{.t=23211369469,.pad=2,.ev=.{.axis=.{.idx=0,.value=-1438}}}, -.{.t=23211369469,.pad=2,.ev=.{.axis=.{.idx=1,.value=808}}}, -.{.t=23211369469,.pad=2,.ev=.{.axis=.{.idx=2,.value=-469}}}, -.{.t=23211369469,.pad=2,.ev=.{.axis=.{.idx=3,.value=1118}}}, -.{.t=23222496653,.pad=2,.ev=.{.axis=.{.idx=1,.value=722}}}, -.{.t=23222496653,.pad=2,.ev=.{.axis=.{.idx=2,.value=-410}}}, -.{.t=23222496653,.pad=2,.ev=.{.axis=.{.idx=3,.value=1057}}}, -.{.t=23222508723,.pad=2,.ev=.{.axis=.{.idx=1,.value=664}}}, -.{.t=23222508723,.pad=2,.ev=.{.axis=.{.idx=2,.value=-439}}}, -.{.t=23222508723,.pad=2,.ev=.{.axis=.{.idx=3,.value=1087}}}, -.{.t=23222512923,.pad=2,.ev=.{.axis=.{.idx=0,.value=-1465}}}, -.{.t=23222512923,.pad=2,.ev=.{.axis=.{.idx=1,.value=693}}}, -.{.t=23222512923,.pad=2,.ev=.{.axis=.{.idx=3,.value=1118}}}, -.{.t=23233616896,.pad=2,.ev=.{.axis=.{.idx=1,.value=404}}}, -.{.t=23233616896,.pad=2,.ev=.{.axis=.{.idx=3,.value=1087}}}, -.{.t=23233628876,.pad=2,.ev=.{.axis=.{.idx=1,.value=462}}}, -.{.t=23233628876,.pad=2,.ev=.{.axis=.{.idx=2,.value=-469}}}, -.{.t=23233628876,.pad=2,.ev=.{.axis=.{.idx=3,.value=1118}}}, -.{.t=23233634716,.pad=2,.ev=.{.axis=.{.idx=1,.value=375}}}, -.{.t=23233634716,.pad=2,.ev=.{.axis=.{.idx=2,.value=-439}}}, -.{.t=23244703810,.pad=2,.ev=.{.axis=.{.idx=1,.value=404}}}, -.{.t=23244703810,.pad=2,.ev=.{.axis=.{.idx=2,.value=-469}}}, -.{.t=23244703810,.pad=2,.ev=.{.axis=.{.idx=3,.value=1087}}}, -.{.t=23244716710,.pad=2,.ev=.{.axis=.{.idx=0,.value=-1438}}}, -.{.t=23244716710,.pad=2,.ev=.{.axis=.{.idx=1,.value=288}}}, -.{.t=23244716710,.pad=2,.ev=.{.axis=.{.idx=2,.value=-439}}}, -.{.t=23244722470,.pad=2,.ev=.{.axis=.{.idx=1,.value=317}}}, -.{.t=23255891634,.pad=2,.ev=.{.axis=.{.idx=1,.value=260}}}, -.{.t=23255891634,.pad=2,.ev=.{.axis=.{.idx=2,.value=-469}}}, -.{.t=23255903964,.pad=2,.ev=.{.axis=.{.idx=0,.value=-1410}}}, -.{.t=23255903964,.pad=2,.ev=.{.axis=.{.idx=1,.value=144}}}, -.{.t=23255903964,.pad=2,.ev=.{.axis=.{.idx=3,.value=1057}}}, -.{.t=23255909564,.pad=2,.ev=.{.axis=.{.idx=0,.value=-1465}}}, -.{.t=23255909564,.pad=2,.ev=.{.axis=.{.idx=1,.value=115}}}, -.{.t=23266911057,.pad=2,.ev=.{.axis=.{.idx=4,.value=30723}}}, -.{.t=23266911057,.pad=2,.ev=.{.axis=.{.idx=0,.value=-1438}}}, -.{.t=23266911057,.pad=2,.ev=.{.axis=.{.idx=1,.value=86}}}, -.{.t=23266924047,.pad=2,.ev=.{.axis=.{.idx=4,.value=27437}}}, -.{.t=23266924047,.pad=2,.ev=.{.axis=.{.idx=0,.value=-1465}}}, -.{.t=23266924047,.pad=2,.ev=.{.axis=.{.idx=1,.value=115}}}, -.{.t=23266924047,.pad=2,.ev=.{.axis=.{.idx=3,.value=1087}}}, -.{.t=23278235081,.pad=2,.ev=.{.axis=.{.idx=4,.value=24292}}}, -.{.t=23278235081,.pad=2,.ev=.{.axis=.{.idx=0,.value=-1438}}}, -.{.t=23278235081,.pad=2,.ev=.{.axis=.{.idx=1,.value=29}}}, -.{.t=23278246901,.pad=2,.ev=.{.axis=.{.idx=4,.value=21053}}}, -.{.t=23278246901,.pad=2,.ev=.{.axis=.{.idx=1,.value=57}}}, -.{.t=23278246901,.pad=2,.ev=.{.axis=.{.idx=2,.value=-439}}}, -.{.t=23278246901,.pad=2,.ev=.{.axis=.{.idx=3,.value=1057}}}, -.{.t=23278254110,.pad=2,.ev=.{.axis=.{.idx=4,.value=17814}}}, -.{.t=23278254110,.pad=2,.ev=.{.axis=.{.idx=1,.value=86}}}, -.{.t=23278254110,.pad=2,.ev=.{.axis=.{.idx=2,.value=-498}}}, -.{.t=23278254110,.pad=2,.ev=.{.axis=.{.idx=3,.value=1087}}}, -.{.t=23289217094,.pad=2,.ev=.{.axis=.{.idx=4,.value=14341}}}, -.{.t=23289217094,.pad=2,.ev=.{.axis=.{.idx=0,.value=-1465}}}, -.{.t=23289217094,.pad=2,.ev=.{.axis=.{.idx=1,.value=144}}}, -.{.t=23289217094,.pad=2,.ev=.{.axis=.{.idx=2,.value=-469}}}, -.{.t=23289217094,.pad=2,.ev=.{.axis=.{.idx=3,.value=1057}}}, -.{.t=23289231434,.pad=2,.ev=.{.axis=.{.idx=4,.value=11384}}}, -.{.t=23289231434,.pad=2,.ev=.{.axis=.{.idx=1,.value=57}}}, -.{.t=23289236534,.pad=2,.ev=.{.axis=.{.idx=4,.value=8708}}}, -.{.t=23289236534,.pad=2,.ev=.{.axis=.{.idx=0,.value=-1438}}}, -.{.t=23289236534,.pad=2,.ev=.{.axis=.{.idx=1,.value=0}}}, -.{.t=23300340478,.pad=2,.ev=.{.axis=.{.idx=4,.value=6126}}}, -.{.t=23300340478,.pad=2,.ev=.{.axis=.{.idx=2,.value=-439}}}, -.{.t=23300350538,.pad=2,.ev=.{.axis=.{.idx=4,.value=4014}}}, -.{.t=23300350538,.pad=2,.ev=.{.axis=.{.idx=1,.value=86}}}, -.{.t=23300354158,.pad=2,.ev=.{.axis=.{.idx=4,.value=2465}}}, -.{.t=23300354158,.pad=2,.ev=.{.axis=.{.idx=0,.value=-1410}}}, -.{.t=23300354158,.pad=2,.ev=.{.axis=.{.idx=1,.value=288}}}, -.{.t=23311366832,.pad=2,.ev=.{.axis=.{.idx=4,.value=634}}}, -.{.t=23311366832,.pad=2,.ev=.{.axis=.{.idx=1,.value=462}}}, -.{.t=23311366832,.pad=2,.ev=.{.axis=.{.idx=3,.value=1027}}}, -.{.t=23311379542,.pad=2,.ev=.{.axis=.{.idx=4,.value=0}}}, -.{.t=23311379542,.pad=2,.ev=.{.axis=.{.idx=0,.value=-1355}}}, -.{.t=23311379542,.pad=2,.ev=.{.axis=.{.idx=1,.value=779}}}, -.{.t=23311379542,.pad=2,.ev=.{.axis=.{.idx=2,.value=-410}}}, -.{.t=23322638775,.pad=2,.ev=.{.axis=.{.idx=0,.value=-1272}}}, -.{.t=23322638775,.pad=2,.ev=.{.axis=.{.idx=1,.value=953}}}, -.{.t=23322638775,.pad=2,.ev=.{.axis=.{.idx=2,.value=-439}}}, -.{.t=23322649765,.pad=2,.ev=.{.axis=.{.idx=0,.value=-1051}}}, -.{.t=23322649765,.pad=2,.ev=.{.axis=.{.idx=1,.value=981}}}, -.{.t=23322649765,.pad=2,.ev=.{.axis=.{.idx=3,.value=1057}}}, -.{.t=23322654995,.pad=2,.ev=.{.axis=.{.idx=0,.value=-885}}}, -.{.t=23322654995,.pad=2,.ev=.{.axis=.{.idx=1,.value=1039}}}, -.{.t=23333351109,.pad=2,.ev=.{.axis=.{.idx=0,.value=-691}}}, -.{.t=23333351109,.pad=2,.ev=.{.axis=.{.idx=2,.value=-469}}}, -.{.t=23333359049,.pad=2,.ev=.{.axis=.{.idx=0,.value=-553}}}, -.{.t=23333359049,.pad=2,.ev=.{.axis=.{.idx=3,.value=1087}}}, -.{.t=23333362519,.pad=2,.ev=.{.axis=.{.idx=1,.value=1010}}}, -.{.t=23333362519,.pad=2,.ev=.{.axis=.{.idx=2,.value=-439}}}, -.{.t=23333362519,.pad=2,.ev=.{.axis=.{.idx=3,.value=1057}}}, -.{.t=23344695372,.pad=2,.ev=.{.axis=.{.idx=1,.value=981}}}, -.{.t=23344706662,.pad=2,.ev=.{.axis=.{.idx=0,.value=-525}}}, -.{.t=23344706662,.pad=2,.ev=.{.axis=.{.idx=1,.value=953}}}, -.{.t=23344711982,.pad=2,.ev=.{.axis=.{.idx=0,.value=-553}}}, -.{.t=23344711982,.pad=2,.ev=.{.axis=.{.idx=1,.value=981}}}, -.{.t=23355868326,.pad=2,.ev=.{.axis=.{.idx=0,.value=-498}}}, -.{.t=23355868326,.pad=2,.ev=.{.axis=.{.idx=1,.value=1010}}}, -.{.t=23355878956,.pad=2,.ev=.{.axis=.{.idx=0,.value=-525}}}, -.{.t=23355878956,.pad=2,.ev=.{.axis=.{.idx=1,.value=981}}}, -.{.t=23355878956,.pad=2,.ev=.{.axis=.{.idx=2,.value=-469}}}, -.{.t=23355878956,.pad=2,.ev=.{.axis=.{.idx=3,.value=1087}}}, -.{.t=23355884866,.pad=2,.ev=.{.axis=.{.idx=1,.value=1010}}}, -.{.t=23355884866,.pad=2,.ev=.{.axis=.{.idx=2,.value=-410}}}, -.{.t=23355884866,.pad=2,.ev=.{.axis=.{.idx=3,.value=1027}}}, -.{.t=23366942749,.pad=2,.ev=.{.axis=.{.idx=0,.value=-553}}}, -.{.t=23366952219,.pad=2,.ev=.{.axis=.{.idx=0,.value=-525}}}, -.{.t=23366952219,.pad=2,.ev=.{.axis=.{.idx=1,.value=981}}}, -.{.t=23366952219,.pad=2,.ev=.{.axis=.{.idx=2,.value=-439}}}, -.{.t=23366952219,.pad=2,.ev=.{.axis=.{.idx=3,.value=1057}}}, -.{.t=23378047613,.pad=2,.ev=.{.axis=.{.idx=0,.value=-553}}}, -.{.t=23378047613,.pad=2,.ev=.{.axis=.{.idx=1,.value=1010}}}, -.{.t=23378064723,.pad=2,.ev=.{.axis=.{.idx=0,.value=-525}}}, -.{.t=23378064723,.pad=2,.ev=.{.axis=.{.idx=1,.value=981}}}, -.{.t=23378064723,.pad=2,.ev=.{.axis=.{.idx=2,.value=-469}}}, -.{.t=23388957907,.pad=2,.ev=.{.axis=.{.idx=0,.value=-553}}}, -.{.t=23388957907,.pad=2,.ev=.{.axis=.{.idx=1,.value=1039}}}, -.{.t=23388957907,.pad=2,.ev=.{.axis=.{.idx=2,.value=-439}}}, -.{.t=23388957907,.pad=2,.ev=.{.axis=.{.idx=3,.value=1027}}}, -.{.t=23388967217,.pad=2,.ev=.{.axis=.{.idx=1,.value=1010}}}, -.{.t=23388967217,.pad=2,.ev=.{.axis=.{.idx=2,.value=-410}}}, -.{.t=23388970117,.pad=2,.ev=.{.axis=.{.idx=0,.value=-525}}}, -.{.t=23388970117,.pad=2,.ev=.{.axis=.{.idx=1,.value=981}}}, -.{.t=23388970117,.pad=2,.ev=.{.axis=.{.idx=2,.value=-439}}}, -.{.t=23388970117,.pad=2,.ev=.{.axis=.{.idx=3,.value=1057}}}, -.{.t=23400316180,.pad=2,.ev=.{.axis=.{.idx=2,.value=-469}}}, -.{.t=23400325960,.pad=2,.ev=.{.axis=.{.idx=0,.value=-580}}}, -.{.t=23400325960,.pad=2,.ev=.{.axis=.{.idx=1,.value=1039}}}, -.{.t=23400325960,.pad=2,.ev=.{.axis=.{.idx=2,.value=-410}}}, -.{.t=23400330510,.pad=2,.ev=.{.axis=.{.idx=0,.value=-525}}}, -.{.t=23400330510,.pad=2,.ev=.{.axis=.{.idx=1,.value=981}}}, -.{.t=23400330510,.pad=2,.ev=.{.axis=.{.idx=2,.value=-439}}}, -.{.t=23411327274,.pad=2,.ev=.{.axis=.{.idx=1,.value=1039}}}, -.{.t=23411337364,.pad=2,.ev=.{.axis=.{.idx=1,.value=1010}}}, -.{.t=23411337364,.pad=2,.ev=.{.axis=.{.idx=3,.value=1027}}}, -.{.t=23422593127,.pad=2,.ev=.{.axis=.{.idx=2,.value=-469}}}, -.{.t=23422593127,.pad=2,.ev=.{.axis=.{.idx=3,.value=1057}}}, -.{.t=23422603997,.pad=2,.ev=.{.axis=.{.idx=2,.value=-410}}}, -.{.t=23422603997,.pad=2,.ev=.{.axis=.{.idx=3,.value=1027}}}, -.{.t=23422607677,.pad=2,.ev=.{.axis=.{.idx=2,.value=-439}}}, -.{.t=23422607677,.pad=2,.ev=.{.axis=.{.idx=3,.value=1057}}}, -.{.t=23433465571,.pad=2,.ev=.{.axis=.{.idx=1,.value=1039}}}, -.{.t=23433465571,.pad=2,.ev=.{.axis=.{.idx=3,.value=1027}}}, -.{.t=23433473571,.pad=2,.ev=.{.axis=.{.idx=1,.value=1010}}}, -.{.t=23433473571,.pad=2,.ev=.{.axis=.{.idx=2,.value=-469}}}, -.{.t=23433473571,.pad=2,.ev=.{.axis=.{.idx=3,.value=1057}}}, -.{.t=23444613485,.pad=2,.ev=.{.axis=.{.idx=1,.value=1039}}}, -.{.t=23444623255,.pad=2,.ev=.{.axis=.{.idx=2,.value=-439}}}, -.{.t=23444626645,.pad=2,.ev=.{.axis=.{.idx=1,.value=1010}}}, -.{.t=23444626645,.pad=2,.ev=.{.axis=.{.idx=3,.value=1027}}}, + .{ .t = 3100837937, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 997 } } }, + .{ .t = 3100845387, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -829 } } }, + .{ .t = 3100845387, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = -1441 } } }, + .{ .t = 3100845387, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1027 } } }, + .{ .t = 3100849157, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -802 } } }, + .{ .t = 3100849157, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = -1411 } } }, + .{ .t = 3100849157, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1057 } } }, + .{ .t = 3111923010, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -829 } } }, + .{ .t = 3111923010, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = -1529 } } }, + .{ .t = 3111923010, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1027 } } }, + .{ .t = 3111936310, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -802 } } }, + .{ .t = 3111936310, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = -1323 } } }, + .{ .t = 3111941850, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = -1558 } } }, + .{ .t = 3111941850, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 997 } } }, + .{ .t = 3123013224, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -829 } } }, + .{ .t = 3123013224, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = -1294 } } }, + .{ .t = 3123013224, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1027 } } }, + .{ .t = 3123021794, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -802 } } }, + .{ .t = 3123021794, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = -941 } } }, + .{ .t = 3123021794, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 997 } } }, + .{ .t = 3134267607, .pad = 2, .ev = .{ .axis = .{ .idx = 5, .value = 0 } } }, + .{ .t = 3134267607, .pad = 2, .ev = .{ .axis = .{ .idx = 5, .value = 214 } } }, + .{ .t = 3134267607, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -829 } } }, + .{ .t = 3134267607, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = -647 } } }, + .{ .t = 3134277137, .pad = 2, .ev = .{ .axis = .{ .idx = 5, .value = 2674 } } }, + .{ .t = 3134277137, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -802 } } }, + .{ .t = 3134277137, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = -500 } } }, + .{ .t = 3134280727, .pad = 2, .ev = .{ .axis = .{ .idx = 5, .value = 5436 } } }, + .{ .t = 3134280727, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -829 } } }, + .{ .t = 3134280727, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = -206 } } }, + .{ .t = 3134280727, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1027 } } }, + .{ .t = 3146260210, .pad = 2, .ev = .{ .axis = .{ .idx = 5, .value = 8198 } } }, + .{ .t = 3146260210, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -774 } } }, + .{ .t = 3146260210, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = -176 } } }, + .{ .t = 3146260210, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 997 } } }, + .{ .t = 3146270520, .pad = 2, .ev = .{ .axis = .{ .idx = 5, .value = 11211 } } }, + .{ .t = 3146270520, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -802 } } }, + .{ .t = 3146270520, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = -29 } } }, + .{ .t = 3146274870, .pad = 2, .ev = .{ .axis = .{ .idx = 5, .value = 13671 } } }, + .{ .t = 3146274870, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 86 } } }, + .{ .t = 3146274870, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1027 } } }, + .{ .t = 3156416215, .pad = 2, .ev = .{ .axis = .{ .idx = 5, .value = 16432 } } }, + .{ .t = 3156416215, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -829 } } }, + .{ .t = 3156416215, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 288 } } }, + .{ .t = 3156416215, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 997 } } }, + .{ .t = 3156435465, .pad = 2, .ev = .{ .axis = .{ .idx = 5, .value = 18893 } } }, + .{ .t = 3156435465, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -802 } } }, + .{ .t = 3156435465, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 462 } } }, + .{ .t = 3156441825, .pad = 2, .ev = .{ .axis = .{ .idx = 5, .value = 21504 } } }, + .{ .t = 3156441825, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 491 } } }, + .{ .t = 3156441825, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1057 } } }, + .{ .t = 3167440508, .pad = 2, .ev = .{ .axis = .{ .idx = 5, .value = 23915 } } }, + .{ .t = 3167440508, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 664 } } }, + .{ .t = 3167440508, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1027 } } }, + .{ .t = 3167449678, .pad = 2, .ev = .{ .axis = .{ .idx = 5, .value = 26224 } } }, + .{ .t = 3167449678, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -829 } } }, + .{ .t = 3167449678, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 779 } } }, + .{ .t = 3167449678, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 997 } } }, + .{ .t = 3178634312, .pad = 2, .ev = .{ .axis = .{ .idx = 5, .value = 28384 } } }, + .{ .t = 3178634312, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -802 } } }, + .{ .t = 3178634312, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 837 } } }, + .{ .t = 3178634312, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1027 } } }, + .{ .t = 3178646332, .pad = 2, .ev = .{ .axis = .{ .idx = 5, .value = 30593 } } }, + .{ .t = 3178646332, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -829 } } }, + .{ .t = 3178646332, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 997 } } }, + .{ .t = 3178651472, .pad = 2, .ev = .{ .axis = .{ .idx = 5, .value = 32702 } } }, + .{ .t = 3178651472, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -802 } } }, + .{ .t = 3189737565, .pad = 2, .ev = .{ .axis = .{ .idx = 5, .value = 32766 } } }, + .{ .t = 3189737565, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 924 } } }, + .{ .t = 3189737565, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1027 } } }, + .{ .t = 3189748175, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1057 } } }, + .{ .t = 3189751215, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 953 } } }, + .{ .t = 3189751215, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1027 } } }, + .{ .t = 3200899959, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 997 } } }, + .{ .t = 3200909349, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -774 } } }, + .{ .t = 3200909349, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 924 } } }, + .{ .t = 3200914229, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -802 } } }, + .{ .t = 3200914229, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 953 } } }, + .{ .t = 3200914229, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1027 } } }, + .{ .t = 3212027402, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -829 } } }, + .{ .t = 3212027402, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 1010 } } }, + .{ .t = 3212027402, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 997 } } }, + .{ .t = 3212033902, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1027 } } }, + .{ .t = 3222960156, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 981 } } }, + .{ .t = 3222960156, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 997 } } }, + .{ .t = 3222967916, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -802 } } }, + .{ .t = 3222967916, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 953 } } }, + .{ .t = 3222967916, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1087 } } }, + .{ .t = 3234186130, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -857 } } }, + .{ .t = 3234186130, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 981 } } }, + .{ .t = 3234186130, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1027 } } }, + .{ .t = 3234194710, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -802 } } }, + .{ .t = 3234194710, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 953 } } }, + .{ .t = 3234194710, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 997 } } }, + .{ .t = 3234198480, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -829 } } }, + .{ .t = 3234198480, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 1097 } } }, + .{ .t = 3245272663, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 1126 } } }, + .{ .t = 3245272663, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1057 } } }, + .{ .t = 3245280873, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -802 } } }, + .{ .t = 3245280873, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 997 } } }, + .{ .t = 3245284263, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 1097 } } }, + .{ .t = 3245284263, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1027 } } }, + .{ .t = 3256351647, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -829 } } }, + .{ .t = 3256351647, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 997 } } }, + .{ .t = 3256361897, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 1126 } } }, + .{ .t = 3256361897, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1027 } } }, + .{ .t = 3256366557, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -857 } } }, + .{ .t = 3267453910, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -829 } } }, + .{ .t = 3267461450, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -802 } } }, + .{ .t = 3267461450, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 1097 } } }, + .{ .t = 3267461450, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1057 } } }, + .{ .t = 3278671394, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1027 } } }, + .{ .t = 3278679494, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -829 } } }, + .{ .t = 3278679494, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 1126 } } }, + .{ .t = 3278679494, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 997 } } }, + .{ .t = 3278684284, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 1097 } } }, + .{ .t = 3289747017, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -802 } } }, + .{ .t = 3289757957, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -774 } } }, + .{ .t = 3289757957, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 1068 } } }, + .{ .t = 3289757957, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1057 } } }, + .{ .t = 3289764977, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -829 } } }, + .{ .t = 3289764977, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1027 } } }, + .{ .t = 3300894251, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -802 } } }, + .{ .t = 3300894251, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1057 } } }, + .{ .t = 3300904161, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -829 } } }, + .{ .t = 3300904161, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1027 } } }, + .{ .t = 3300908771, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1057 } } }, + .{ .t = 3312130554, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -802 } } }, + .{ .t = 3312130554, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 1039 } } }, + .{ .t = 3312130554, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1027 } } }, + .{ .t = 3312142164, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1057 } } }, + .{ .t = 3312145624, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -829 } } }, + .{ .t = 3312145624, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 1068 } } }, + .{ .t = 3312145624, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1027 } } }, + .{ .t = 3323185928, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -802 } } }, + .{ .t = 3323185928, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 1039 } } }, + .{ .t = 3323197438, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 1010 } } }, + .{ .t = 3334415941, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -829 } } }, + .{ .t = 3334415941, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1057 } } }, + .{ .t = 3334428191, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -802 } } }, + .{ .t = 3334428191, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1027 } } }, + .{ .t = 3334433441, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -829 } } }, + .{ .t = 3345319335, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -802 } } }, + .{ .t = 3345319335, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 1039 } } }, + .{ .t = 3345329665, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -774 } } }, + .{ .t = 3345329665, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 1010 } } }, + .{ .t = 3345329665, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 997 } } }, + .{ .t = 3345334835, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -802 } } }, + .{ .t = 3356434069, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -829 } } }, + .{ .t = 3356434069, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 1039 } } }, + .{ .t = 3356434069, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1027 } } }, + .{ .t = 3356449919, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -802 } } }, + .{ .t = 3356449919, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 1010 } } }, + .{ .t = 3356449919, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 997 } } }, + .{ .t = 3367716072, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -857 } } }, + .{ .t = 3367716072, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 1068 } } }, + .{ .t = 3367728332, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -829 } } }, + .{ .t = 3367728332, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 1039 } } }, + .{ .t = 3367728332, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1027 } } }, + .{ .t = 3367733692, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -802 } } }, + .{ .t = 3367733692, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 1010 } } }, + .{ .t = 3367733692, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1057 } } }, + .{ .t = 3378615526, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 997 } } }, + .{ .t = 3389836929, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -774 } } }, + .{ .t = 3389836929, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 981 } } }, + .{ .t = 3389836929, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1027 } } }, + .{ .t = 3389847129, .pad = 2, .ev = .{ .axis = .{ .idx = 5, .value = 31648 } } }, + .{ .t = 3389847129, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -802 } } }, + .{ .t = 3389847129, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 1010 } } }, + .{ .t = 3389852719, .pad = 2, .ev = .{ .axis = .{ .idx = 5, .value = 29137 } } }, + .{ .t = 3389852719, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 1039 } } }, + .{ .t = 3401186593, .pad = 2, .ev = .{ .axis = .{ .idx = 5, .value = 26074 } } }, + .{ .t = 3401186593, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -829 } } }, + .{ .t = 3401194003, .pad = 2, .ev = .{ .axis = .{ .idx = 5, .value = 23262 } } }, + .{ .t = 3401194003, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -802 } } }, + .{ .t = 3401194003, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 1010 } } }, + .{ .t = 3401194003, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1057 } } }, + .{ .t = 3401198713, .pad = 2, .ev = .{ .axis = .{ .idx = 5, .value = 20349 } } }, + .{ .t = 3401198713, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 997 } } }, + .{ .t = 3411932407, .pad = 2, .ev = .{ .axis = .{ .idx = 5, .value = 17587 } } }, + .{ .t = 3411932407, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -829 } } }, + .{ .t = 3411932407, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 1039 } } }, + .{ .t = 3411941077, .pad = 2, .ev = .{ .axis = .{ .idx = 5, .value = 15127 } } }, + .{ .t = 3411941077, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -802 } } }, + .{ .t = 3411941077, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1027 } } }, + .{ .t = 3411944947, .pad = 2, .ev = .{ .axis = .{ .idx = 5, .value = 12617 } } }, + .{ .t = 3411944947, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -829 } } }, + .{ .t = 3411944947, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 953 } } }, + .{ .t = 3411944947, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 997 } } }, + .{ .t = 3423178470, .pad = 2, .ev = .{ .axis = .{ .idx = 5, .value = 10307 } } }, + .{ .t = 3423178470, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -802 } } }, + .{ .t = 3423178470, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 924 } } }, + .{ .t = 3423187080, .pad = 2, .ev = .{ .axis = .{ .idx = 5, .value = 8298 } } }, + .{ .t = 3423187080, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 981 } } }, + .{ .t = 3423187080, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1027 } } }, + .{ .t = 3434307174, .pad = 2, .ev = .{ .axis = .{ .idx = 5, .value = 6340 } } }, + .{ .t = 3434307174, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 924 } } }, + .{ .t = 3434315334, .pad = 2, .ev = .{ .axis = .{ .idx = 5, .value = 4532 } } }, + .{ .t = 3434315334, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 997 } } }, + .{ .t = 3434318744, .pad = 2, .ev = .{ .axis = .{ .idx = 5, .value = 2975 } } }, + .{ .t = 3434318744, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 866 } } }, + .{ .t = 3445336427, .pad = 2, .ev = .{ .axis = .{ .idx = 5, .value = 1067 } } }, + .{ .t = 3445336427, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 635 } } }, + .{ .t = 3445344507, .pad = 2, .ev = .{ .axis = .{ .idx = 4, .value = 446 } } }, + .{ .t = 3445344507, .pad = 2, .ev = .{ .axis = .{ .idx = 5, .value = 0 } } }, + .{ .t = 3445344507, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 346 } } }, + .{ .t = 3445344507, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1027 } } }, + .{ .t = 3445348567, .pad = 2, .ev = .{ .axis = .{ .idx = 4, .value = 1854 } } }, + .{ .t = 3445348567, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = -59 } } }, + .{ .t = 3456475621, .pad = 2, .ev = .{ .axis = .{ .idx = 4, .value = 3310 } } }, + .{ .t = 3456475621, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = -176 } } }, + .{ .t = 3456475621, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 997 } } }, + .{ .t = 3456483971, .pad = 2, .ev = .{ .axis = .{ .idx = 4, .value = 4436 } } }, + .{ .t = 3456483971, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = -441 } } }, + .{ .t = 3456487161, .pad = 2, .ev = .{ .axis = .{ .idx = 4, .value = 5891 } } }, + .{ .t = 3456487161, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = -558 } } }, + .{ .t = 22900269279, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -1493 } } }, + .{ .t = 22900269279, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 981 } } }, + .{ .t = 22900269279, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1087 } } }, + .{ .t = 22900282319, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -1465 } } }, + .{ .t = 22900282319, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 953 } } }, + .{ .t = 22900282319, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -469 } } }, + .{ .t = 22900282319, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1118 } } }, + .{ .t = 22900288339, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 981 } } }, + .{ .t = 22900288339, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -439 } } }, + .{ .t = 22900288339, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1087 } } }, + .{ .t = 22911078513, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -1438 } } }, + .{ .t = 22911078513, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 953 } } }, + .{ .t = 22911078513, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -469 } } }, + .{ .t = 22911090183, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -498 } } }, + .{ .t = 22922174447, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -1465 } } }, + .{ .t = 22922174447, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -527 } } }, + .{ .t = 22922174447, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1148 } } }, + .{ .t = 22922182927, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -1493 } } }, + .{ .t = 22922182927, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 981 } } }, + .{ .t = 22922182927, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -498 } } }, + .{ .t = 22922182927, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1118 } } }, + .{ .t = 22922186907, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -1465 } } }, + .{ .t = 22933453380, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -469 } } }, + .{ .t = 22933463530, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -1438 } } }, + .{ .t = 22933463530, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 924 } } }, + .{ .t = 22933463530, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -498 } } }, + .{ .t = 22933463530, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1148 } } }, + .{ .t = 22933469520, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 953 } } }, + .{ .t = 22933469520, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -469 } } }, + .{ .t = 22933469520, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1118 } } }, + .{ .t = 22944601464, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -439 } } }, + .{ .t = 22944601464, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1087 } } }, + .{ .t = 22944613874, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -1465 } } }, + .{ .t = 22944613874, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -469 } } }, + .{ .t = 22944613874, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1118 } } }, + .{ .t = 22944619754, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -1438 } } }, + .{ .t = 22955633677, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -1493 } } }, + .{ .t = 22955633677, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 981 } } }, + .{ .t = 22955633677, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -439 } } }, + .{ .t = 22955633677, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1087 } } }, + .{ .t = 22955647207, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -1465 } } }, + .{ .t = 22955647207, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 953 } } }, + .{ .t = 22955647207, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -498 } } }, + .{ .t = 22955647207, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1148 } } }, + .{ .t = 22955652047, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -1438 } } }, + .{ .t = 22955652047, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1118 } } }, + .{ .t = 22966619841, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -1465 } } }, + .{ .t = 22966619841, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -469 } } }, + .{ .t = 22966628121, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 924 } } }, + .{ .t = 22966628121, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1087 } } }, + .{ .t = 22977745245, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -1438 } } }, + .{ .t = 22977745245, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 953 } } }, + .{ .t = 22977745245, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -498 } } }, + .{ .t = 22977745245, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1148 } } }, + .{ .t = 22977753905, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -1465 } } }, + .{ .t = 22977753905, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -469 } } }, + .{ .t = 22977753905, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1118 } } }, + .{ .t = 22977757525, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -439 } } }, + .{ .t = 22988922908, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -1438 } } }, + .{ .t = 22988922908, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 981 } } }, + .{ .t = 22988936008, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -1465 } } }, + .{ .t = 22988936008, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -469 } } }, + .{ .t = 22988940638, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -1438 } } }, + .{ .t = 22988940638, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 953 } } }, + .{ .t = 23000140672, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -1465 } } }, + .{ .t = 23000140672, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -498 } } }, + .{ .t = 23000152872, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -1438 } } }, + .{ .t = 23000152872, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 924 } } }, + .{ .t = 23000152872, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -439 } } }, + .{ .t = 23000152872, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1087 } } }, + .{ .t = 23000158442, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -1493 } } }, + .{ .t = 23000158442, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 953 } } }, + .{ .t = 23000158442, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -410 } } }, + .{ .t = 23011247285, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -1438 } } }, + .{ .t = 23011247285, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -439 } } }, + .{ .t = 23011247285, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1057 } } }, + .{ .t = 23011260265, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -1465 } } }, + .{ .t = 23011260265, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -469 } } }, + .{ .t = 23011260265, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1118 } } }, + .{ .t = 23022366569, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -1438 } } }, + .{ .t = 23022366569, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 924 } } }, + .{ .t = 23022366569, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -498 } } }, + .{ .t = 23022366569, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1148 } } }, + .{ .t = 23022380099, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -439 } } }, + .{ .t = 23022380099, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1087 } } }, + .{ .t = 23022385329, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -469 } } }, + .{ .t = 23022385329, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1118 } } }, + .{ .t = 23033207513, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -1465 } } }, + .{ .t = 23033207513, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 953 } } }, + .{ .t = 23033215483, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -1438 } } }, + .{ .t = 23033215483, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 924 } } }, + .{ .t = 23033215483, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -439 } } }, + .{ .t = 23033215483, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1087 } } }, + .{ .t = 23033219653, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 953 } } }, + .{ .t = 23044563226, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 924 } } }, + .{ .t = 23044563226, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -469 } } }, + .{ .t = 23044563226, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1118 } } }, + .{ .t = 23044572856, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -410 } } }, + .{ .t = 23044572856, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1087 } } }, + .{ .t = 23044576806, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 953 } } }, + .{ .t = 23044576806, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -469 } } }, + .{ .t = 23044576806, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1118 } } }, + .{ .t = 23055818709, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -1465 } } }, + .{ .t = 23055818709, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1087 } } }, + .{ .t = 23055828779, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -1438 } } }, + .{ .t = 23055828779, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 924 } } }, + .{ .t = 23055828779, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1118 } } }, + .{ .t = 23055832789, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -1410 } } }, + .{ .t = 23055832789, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1087 } } }, + .{ .t = 23066680603, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -1465 } } }, + .{ .t = 23066680603, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 953 } } }, + .{ .t = 23066680603, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1118 } } }, + .{ .t = 23066690143, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -1493 } } }, + .{ .t = 23066690143, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 981 } } }, + .{ .t = 23066690143, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -439 } } }, + .{ .t = 23066690143, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1087 } } }, + .{ .t = 23077703397, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -1438 } } }, + .{ .t = 23077703397, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 924 } } }, + .{ .t = 23077703397, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1118 } } }, + .{ .t = 23077711687, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -1465 } } }, + .{ .t = 23077711687, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 953 } } }, + .{ .t = 23077711687, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -469 } } }, + .{ .t = 23077715567, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -1493 } } }, + .{ .t = 23077715567, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 981 } } }, + .{ .t = 23077715567, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -439 } } }, + .{ .t = 23077715567, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1087 } } }, + .{ .t = 23088844720, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -1438 } } }, + .{ .t = 23088844720, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 953 } } }, + .{ .t = 23088844720, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -498 } } }, + .{ .t = 23088844720, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1148 } } }, + .{ .t = 23088853270, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -1465 } } }, + .{ .t = 23088853270, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -469 } } }, + .{ .t = 23088853270, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1118 } } }, + .{ .t = 23088856830, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -1438 } } }, + .{ .t = 23088856830, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 924 } } }, + .{ .t = 23088856830, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -439 } } }, + .{ .t = 23100184994, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 953 } } }, + .{ .t = 23100184994, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -410 } } }, + .{ .t = 23100184994, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1087 } } }, + .{ .t = 23100197834, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -1465 } } }, + .{ .t = 23100202044, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -1438 } } }, + .{ .t = 23100202044, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 924 } } }, + .{ .t = 23100202044, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -439 } } }, + .{ .t = 23111316337, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -410 } } }, + .{ .t = 23111328087, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -1465 } } }, + .{ .t = 23111328087, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -439 } } }, + .{ .t = 23122579831, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -1438 } } }, + .{ .t = 23122579831, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -498 } } }, + .{ .t = 23122579831, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1118 } } }, + .{ .t = 23122592031, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 953 } } }, + .{ .t = 23122592031, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -469 } } }, + .{ .t = 23122595681, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 924 } } }, + .{ .t = 23122595681, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -439 } } }, + .{ .t = 23122595681, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1087 } } }, + .{ .t = 23133201565, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 953 } } }, + .{ .t = 23133205635, .pad = 2, .ev = .{ .axis = .{ .idx = 4, .value = 728 } } }, + .{ .t = 23133205635, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 924 } } }, + .{ .t = 23133205635, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1118 } } }, + .{ .t = 23144628108, .pad = 2, .ev = .{ .axis = .{ .idx = 4, .value = 3169 } } }, + .{ .t = 23144628108, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -1493 } } }, + .{ .t = 23144628108, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 953 } } }, + .{ .t = 23144628108, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -410 } } }, + .{ .t = 23144628108, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1087 } } }, + .{ .t = 23144640728, .pad = 2, .ev = .{ .axis = .{ .idx = 4, .value = 6314 } } }, + .{ .t = 23144640728, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -1465 } } }, + .{ .t = 23144640728, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -469 } } }, + .{ .t = 23144640728, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1118 } } }, + .{ .t = 23144644338, .pad = 2, .ev = .{ .axis = .{ .idx = 4, .value = 10679 } } }, + .{ .t = 23144644338, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 981 } } }, + .{ .t = 23144644338, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -410 } } }, + .{ .t = 23144644338, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1087 } } }, + .{ .t = 23155757852, .pad = 2, .ev = .{ .axis = .{ .idx = 4, .value = 16500 } } }, + .{ .t = 23155757852, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -1493 } } }, + .{ .t = 23155757852, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 953 } } }, + .{ .t = 23155767512, .pad = 2, .ev = .{ .axis = .{ .idx = 4, .value = 23682 } } }, + .{ .t = 23155767512, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -1438 } } }, + .{ .t = 23155767512, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 924 } } }, + .{ .t = 23155773302, .pad = 2, .ev = .{ .axis = .{ .idx = 4, .value = 32084 } } }, + .{ .t = 23155773302, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -1465 } } }, + .{ .t = 23166856095, .pad = 2, .ev = .{ .axis = .{ .idx = 4, .value = 32766 } } }, + .{ .t = 23166856095, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -1438 } } }, + .{ .t = 23166856095, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -439 } } }, + .{ .t = 23166869315, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 953 } } }, + .{ .t = 23166869315, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1118 } } }, + .{ .t = 23177937079, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 924 } } }, + .{ .t = 23177937079, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1087 } } }, + .{ .t = 23177947099, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -1465 } } }, + .{ .t = 23177947099, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -410 } } }, + .{ .t = 23177950979, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -1438 } } }, + .{ .t = 23177950979, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -439 } } }, + .{ .t = 23177950979, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1118 } } }, + .{ .t = 23188909763, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -410 } } }, + .{ .t = 23188909763, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1087 } } }, + .{ .t = 23188919373, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -1493 } } }, + .{ .t = 23188919373, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 981 } } }, + .{ .t = 23188923533, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -1465 } } }, + .{ .t = 23188923533, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 953 } } }, + .{ .t = 23188923533, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -439 } } }, + .{ .t = 23188923533, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1057 } } }, + .{ .t = 23200341706, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -1438 } } }, + .{ .t = 23200341706, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 924 } } }, + .{ .t = 23200341706, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1087 } } }, + .{ .t = 23200357446, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -469 } } }, + .{ .t = 23200360546, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 866 } } }, + .{ .t = 23200360546, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -439 } } }, + .{ .t = 23211356329, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -1493 } } }, + .{ .t = 23211356329, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 895 } } }, + .{ .t = 23211356329, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1057 } } }, + .{ .t = 23211369469, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -1438 } } }, + .{ .t = 23211369469, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 808 } } }, + .{ .t = 23211369469, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -469 } } }, + .{ .t = 23211369469, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1118 } } }, + .{ .t = 23222496653, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 722 } } }, + .{ .t = 23222496653, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -410 } } }, + .{ .t = 23222496653, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1057 } } }, + .{ .t = 23222508723, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 664 } } }, + .{ .t = 23222508723, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -439 } } }, + .{ .t = 23222508723, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1087 } } }, + .{ .t = 23222512923, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -1465 } } }, + .{ .t = 23222512923, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 693 } } }, + .{ .t = 23222512923, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1118 } } }, + .{ .t = 23233616896, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 404 } } }, + .{ .t = 23233616896, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1087 } } }, + .{ .t = 23233628876, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 462 } } }, + .{ .t = 23233628876, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -469 } } }, + .{ .t = 23233628876, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1118 } } }, + .{ .t = 23233634716, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 375 } } }, + .{ .t = 23233634716, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -439 } } }, + .{ .t = 23244703810, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 404 } } }, + .{ .t = 23244703810, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -469 } } }, + .{ .t = 23244703810, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1087 } } }, + .{ .t = 23244716710, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -1438 } } }, + .{ .t = 23244716710, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 288 } } }, + .{ .t = 23244716710, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -439 } } }, + .{ .t = 23244722470, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 317 } } }, + .{ .t = 23255891634, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 260 } } }, + .{ .t = 23255891634, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -469 } } }, + .{ .t = 23255903964, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -1410 } } }, + .{ .t = 23255903964, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 144 } } }, + .{ .t = 23255903964, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1057 } } }, + .{ .t = 23255909564, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -1465 } } }, + .{ .t = 23255909564, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 115 } } }, + .{ .t = 23266911057, .pad = 2, .ev = .{ .axis = .{ .idx = 4, .value = 30723 } } }, + .{ .t = 23266911057, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -1438 } } }, + .{ .t = 23266911057, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 86 } } }, + .{ .t = 23266924047, .pad = 2, .ev = .{ .axis = .{ .idx = 4, .value = 27437 } } }, + .{ .t = 23266924047, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -1465 } } }, + .{ .t = 23266924047, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 115 } } }, + .{ .t = 23266924047, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1087 } } }, + .{ .t = 23278235081, .pad = 2, .ev = .{ .axis = .{ .idx = 4, .value = 24292 } } }, + .{ .t = 23278235081, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -1438 } } }, + .{ .t = 23278235081, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 29 } } }, + .{ .t = 23278246901, .pad = 2, .ev = .{ .axis = .{ .idx = 4, .value = 21053 } } }, + .{ .t = 23278246901, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 57 } } }, + .{ .t = 23278246901, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -439 } } }, + .{ .t = 23278246901, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1057 } } }, + .{ .t = 23278254110, .pad = 2, .ev = .{ .axis = .{ .idx = 4, .value = 17814 } } }, + .{ .t = 23278254110, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 86 } } }, + .{ .t = 23278254110, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -498 } } }, + .{ .t = 23278254110, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1087 } } }, + .{ .t = 23289217094, .pad = 2, .ev = .{ .axis = .{ .idx = 4, .value = 14341 } } }, + .{ .t = 23289217094, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -1465 } } }, + .{ .t = 23289217094, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 144 } } }, + .{ .t = 23289217094, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -469 } } }, + .{ .t = 23289217094, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1057 } } }, + .{ .t = 23289231434, .pad = 2, .ev = .{ .axis = .{ .idx = 4, .value = 11384 } } }, + .{ .t = 23289231434, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 57 } } }, + .{ .t = 23289236534, .pad = 2, .ev = .{ .axis = .{ .idx = 4, .value = 8708 } } }, + .{ .t = 23289236534, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -1438 } } }, + .{ .t = 23289236534, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 0 } } }, + .{ .t = 23300340478, .pad = 2, .ev = .{ .axis = .{ .idx = 4, .value = 6126 } } }, + .{ .t = 23300340478, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -439 } } }, + .{ .t = 23300350538, .pad = 2, .ev = .{ .axis = .{ .idx = 4, .value = 4014 } } }, + .{ .t = 23300350538, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 86 } } }, + .{ .t = 23300354158, .pad = 2, .ev = .{ .axis = .{ .idx = 4, .value = 2465 } } }, + .{ .t = 23300354158, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -1410 } } }, + .{ .t = 23300354158, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 288 } } }, + .{ .t = 23311366832, .pad = 2, .ev = .{ .axis = .{ .idx = 4, .value = 634 } } }, + .{ .t = 23311366832, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 462 } } }, + .{ .t = 23311366832, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1027 } } }, + .{ .t = 23311379542, .pad = 2, .ev = .{ .axis = .{ .idx = 4, .value = 0 } } }, + .{ .t = 23311379542, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -1355 } } }, + .{ .t = 23311379542, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 779 } } }, + .{ .t = 23311379542, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -410 } } }, + .{ .t = 23322638775, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -1272 } } }, + .{ .t = 23322638775, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 953 } } }, + .{ .t = 23322638775, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -439 } } }, + .{ .t = 23322649765, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -1051 } } }, + .{ .t = 23322649765, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 981 } } }, + .{ .t = 23322649765, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1057 } } }, + .{ .t = 23322654995, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -885 } } }, + .{ .t = 23322654995, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 1039 } } }, + .{ .t = 23333351109, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -691 } } }, + .{ .t = 23333351109, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -469 } } }, + .{ .t = 23333359049, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -553 } } }, + .{ .t = 23333359049, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1087 } } }, + .{ .t = 23333362519, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 1010 } } }, + .{ .t = 23333362519, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -439 } } }, + .{ .t = 23333362519, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1057 } } }, + .{ .t = 23344695372, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 981 } } }, + .{ .t = 23344706662, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -525 } } }, + .{ .t = 23344706662, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 953 } } }, + .{ .t = 23344711982, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -553 } } }, + .{ .t = 23344711982, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 981 } } }, + .{ .t = 23355868326, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -498 } } }, + .{ .t = 23355868326, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 1010 } } }, + .{ .t = 23355878956, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -525 } } }, + .{ .t = 23355878956, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 981 } } }, + .{ .t = 23355878956, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -469 } } }, + .{ .t = 23355878956, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1087 } } }, + .{ .t = 23355884866, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 1010 } } }, + .{ .t = 23355884866, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -410 } } }, + .{ .t = 23355884866, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1027 } } }, + .{ .t = 23366942749, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -553 } } }, + .{ .t = 23366952219, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -525 } } }, + .{ .t = 23366952219, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 981 } } }, + .{ .t = 23366952219, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -439 } } }, + .{ .t = 23366952219, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1057 } } }, + .{ .t = 23378047613, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -553 } } }, + .{ .t = 23378047613, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 1010 } } }, + .{ .t = 23378064723, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -525 } } }, + .{ .t = 23378064723, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 981 } } }, + .{ .t = 23378064723, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -469 } } }, + .{ .t = 23388957907, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -553 } } }, + .{ .t = 23388957907, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 1039 } } }, + .{ .t = 23388957907, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -439 } } }, + .{ .t = 23388957907, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1027 } } }, + .{ .t = 23388967217, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 1010 } } }, + .{ .t = 23388967217, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -410 } } }, + .{ .t = 23388970117, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -525 } } }, + .{ .t = 23388970117, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 981 } } }, + .{ .t = 23388970117, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -439 } } }, + .{ .t = 23388970117, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1057 } } }, + .{ .t = 23400316180, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -469 } } }, + .{ .t = 23400325960, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -580 } } }, + .{ .t = 23400325960, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 1039 } } }, + .{ .t = 23400325960, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -410 } } }, + .{ .t = 23400330510, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -525 } } }, + .{ .t = 23400330510, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 981 } } }, + .{ .t = 23400330510, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -439 } } }, + .{ .t = 23411327274, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 1039 } } }, + .{ .t = 23411337364, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 1010 } } }, + .{ .t = 23411337364, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1027 } } }, + .{ .t = 23422593127, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -469 } } }, + .{ .t = 23422593127, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1057 } } }, + .{ .t = 23422603997, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -410 } } }, + .{ .t = 23422603997, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1027 } } }, + .{ .t = 23422607677, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -439 } } }, + .{ .t = 23422607677, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1057 } } }, + .{ .t = 23433465571, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 1039 } } }, + .{ .t = 23433465571, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1027 } } }, + .{ .t = 23433473571, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 1010 } } }, + .{ .t = 23433473571, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -469 } } }, + .{ .t = 23433473571, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1057 } } }, + .{ .t = 23444613485, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 1039 } } }, + .{ .t = 23444623255, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -439 } } }, + .{ .t = 23444626645, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 1010 } } }, + .{ .t = 23444626645, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1027 } } }, } } diff --git a/test/fs_bench.zig b/test/fs_bench.zig index 4764049f..a8a8fd8c 100644 --- a/test/fs_bench.zig +++ b/test/fs_bench.zig @@ -113,7 +113,7 @@ fn checkReply(s: *Session, req: ctlfs.Req, reply: ctlfs.Reply) !void { if (reply.payload != .staged or reply.payload.staged != bytes.len or bytes.len > req.size) return error.IncorrectReply; const pane = s.core.panes[s.file_id].?; - if (req.node == @intFromEnum(ctlfs.TopFile.index)) { + if (req.node == @backingInt(ctlfs.TopFile.index)) { var expected_buf: [4200]u8 = undefined; const expected = try std.fmt.bufPrint(&expected_buf, "{d} text {d} {s}\n", .{ s.file_serial, @intFromBool(pane.file.?.revision != pane.file.?.saved_revision), pane.file.?.path }); if (!std.mem.eql(u8, expected, bytes)) return error.IncorrectReply; @@ -134,7 +134,7 @@ fn checkReply(s: *Session, req: ctlfs.Req, reply: ctlfs.Reply) !void { if (reply.payload != .staged or reply.payload.staged != bytes.len or bytes.len > req.size) return error.IncorrectReply; const names = [_][]const u8{ "README", "index", "status", "focus", "ctl", "commands", "look", "exec", "log", "screen", "listeners", "pane", "os" }; - const nodes = [_]u64{ @intFromEnum(ctlfs.TopFile.README), @intFromEnum(ctlfs.TopFile.index), @intFromEnum(ctlfs.TopFile.status), @intFromEnum(ctlfs.TopFile.focus), @intFromEnum(ctlfs.TopFile.ctl), @intFromEnum(ctlfs.TopFile.commands), @intFromEnum(ctlfs.TopFile.look), @intFromEnum(ctlfs.TopFile.exec), @intFromEnum(ctlfs.TopFile.log), @intFromEnum(ctlfs.TopFile.screen), @intFromEnum(ctlfs.TopFile.listeners), @intFromEnum(ctlfs.TopFile.pane), filesystem.os_root }; + const nodes = [_]u64{ @backingInt(ctlfs.TopFile.README), @backingInt(ctlfs.TopFile.index), @backingInt(ctlfs.TopFile.status), @backingInt(ctlfs.TopFile.focus), @backingInt(ctlfs.TopFile.ctl), @backingInt(ctlfs.TopFile.commands), @backingInt(ctlfs.TopFile.look), @backingInt(ctlfs.TopFile.exec), @backingInt(ctlfs.TopFile.log), @backingInt(ctlfs.TopFile.screen), @backingInt(ctlfs.TopFile.listeners), @backingInt(ctlfs.TopFile.pane), filesystem.os_root }; var off: usize = 0; var entry: usize = 0; while (off < bytes.len) : (entry += 1) { @@ -253,7 +253,7 @@ pub fn main(init: std.process.Init) !void { try bench(&s, "read index", reps, .{ .tag = 6, .op = .read, - .node = @intFromEnum(ctlfs.TopFile.index), + .node = @backingInt(ctlfs.TopFile.index), .size = 4096, }, "one line per pane"); try bench(&s, "readdir root", reps, .{ diff --git a/test/lspfixture/broken.zig b/test/lspfixture/broken.zig index 22c86c9b..b27840cd 100644 --- a/test/lspfixture/broken.zig +++ b/test/lspfixture/broken.zig @@ -20,6 +20,6 @@ pub fn hasUnusedLocal() u32 { return 7; } -pub fn badly_spaced ( a : u32 , b : u32 ) u32 { - return a+b; +pub fn badly_spaced(a: u32, b: u32) u32 { + return a + b; } diff --git a/test/output.zig b/test/output.zig index 6ea6f6fa..8403effa 100644 --- a/test/output.zig +++ b/test/output.zig @@ -475,7 +475,7 @@ test "Mini syntax colors survive toggles themes and rendering without source acc try panes.mini.open(p, 0, "demo.zig"); const id = p.active; const mini = p.panes[id].?; - const keyword = std.mem.indexOfScalar(u8, mini.file.?.mini.?.colors, @intFromEnum(pardes.syntax.Syn.keyword)) orelse return error.MissingKeywordColor; + const keyword = std.mem.indexOfScalar(u8, mini.file.?.mini.?.colors, @backingInt(pardes.syntax.Syn.keyword)) orelse return error.MissingKeywordColor; // Direct pane construction bypasses the host update's layout sync. p.update(.{ .resize = .{ .cols = 80, .rows = 24 } }); const position = modal.positionAt(mini.file.?.content, keyword); @@ -1656,7 +1656,7 @@ test "stacked search and LSP results retain source tint navigation and dump owne } try std.testing.expectEqual(@as(usize, 6), marked); const number = std.mem.indexOf(u8, file.content, "42").?; - try std.testing.expectEqual(@intFromEnum(pardes.syntax.Syn.number), file.highlights[number]); + try std.testing.expectEqual(@backingInt(pardes.syntax.Syn.number), file.highlights[number]); p.active = id; pane.body.mode = .normal; pardes.look.armLookWalk(p, id); @@ -1815,7 +1815,7 @@ test "location cache eviction retains early colors and honors disk and unsaved r return error.MissingEarlyContext; } }; - try std.testing.expectEqual(@intFromEnum(pardes.syntax.Syn.comment), try Color.valueColor(file)); + try std.testing.expectEqual(@backingInt(pardes.syntax.Syn.comment), try Color.valueColor(file)); const single = "f00.c:4:1-6 needle();\n"; // Put the evicted file back before a same-size edit tests exact-byte keys. try panes.Output.fillResults(p, 0, dir, .search, "eviction", try p.gpa.dupe(u8, single), null); @@ -1823,14 +1823,14 @@ test "location cache eviction retains early colors and honors disk and unsaved r try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "f00.c", .data = code }); try panes.Output.fillResults(p, 0, dir, .search, "eviction", try p.gpa.dupe(u8, single), null); try std.testing.expect(p.locations_cache.analyses > analyses); - try std.testing.expectEqual(@intFromEnum(pardes.syntax.Syn.number), try Color.valueColor(file)); + try std.testing.expectEqual(@backingInt(pardes.syntax.Syn.number), try Color.valueColor(file)); // An open buffer has priority over that disk revision, even with equal size. p.gpa.free(source.file.?.path); source.file.?.path = try std.fs.path.join(p.gpa, &.{ dir, "f00.c" }); panes.File.setContent(p, &source.file.?, try p.gpa.dupe(u8, comment)); try panes.Output.fillResults(p, 0, dir, .search, "eviction", try p.gpa.dupe(u8, single), null); - try std.testing.expectEqual(@intFromEnum(pardes.syntax.Syn.comment), try Color.valueColor(file)); + try std.testing.expectEqual(@backingInt(pardes.syntax.Syn.comment), try Color.valueColor(file)); try std.testing.expectEqualStrings(comment, source.file.?.content); } diff --git a/test/panes.zig b/test/panes.zig index 54100f91..c8f4b7eb 100644 --- a/test/panes.zig +++ b/test/panes.zig @@ -3193,7 +3193,7 @@ const OutputTests = struct { p.update(.{ .mouse = .{ .button = config.select_button, .kind = .press, .col = x, .row = y } }); p.update(.{ .mouse = .{ .button = config.select_button, .kind = .drag, .col = x + 2, .row = y + 1 } }); try std.testing.expect(p.drag == .select); - try std.testing.expectEqual(.dragging, result.sel[@intFromEnum(config.select_button)].state); + try std.testing.expectEqual(.dragging, result.sel[@backingInt(config.select_button)].state); try fillResults(p, 0, "/", .{ .query = .hover }, "", try p.gpa.dupe(u8, "short\n"), null); try std.testing.expect(p.drag == .none); p.update(.{ .mouse = .{ .button = config.select_button, .kind = .release, .col = x + 2, .row = y + 1 } }); diff --git a/test/pdf.zig b/test/pdf.zig index a51fd1a9..6c9308d4 100644 --- a/test/pdf.zig +++ b/test/pdf.zig @@ -25,7 +25,7 @@ const themes = pardes.themes; const pdf_raster_policy = pardes.pdf_raster_policy; const PDF_PAGE_GAP_PX = pardes.PDF_PAGE_GAP_PX; const BOX_H = pardes.BOX_H; -const sel_slot = @intFromEnum(config.select_button); +const sel_slot = @backingInt(config.select_button); const pane_tail = " " ++ config.pdf_pane_builtins_str; fn hasPdf(pane: *const pardes.Pane) bool { @@ -483,10 +483,10 @@ test "`:N` on a PDF turns to page N, from the pane and from the root's look, and try std.testing.expectEqual(failures, p.fs.failures); // Over 9P too: the root's look at `@pN:2` answers ok and logs no err. const ctlfs = pardes.ctlfs; - const written = p.serveFs(.{ .tag = 1, .op = .write, .node = @intFromEnum(ctlfs.TopFile.look), .data = try std.fmt.bufPrint(&line, "@p{d}:2\n", .{doc.serial}) }); + const written = p.serveFs(.{ .tag = 1, .op = .write, .node = @backingInt(ctlfs.TopFile.look), .data = try std.fmt.bufPrint(&line, "@p{d}:2\n", .{doc.serial}) }); try std.testing.expectEqual(ctlfs.Status.ok, written.status); try std.testing.expectEqual(@as(usize, 1), doc.pdf.?.page); - const log = @intFromEnum(ctlfs.TopFile.log); + const log = @backingInt(ctlfs.TopFile.log); const h = p.serveFs(.{ .tag = 2, .op = .open, .node = log }).handle; const record = p.fsPayload(p.serveFs(.{ .tag = 3, .op = .read, .node = log, .handle = h, .size = 1 << 16 })); try std.testing.expect(std.mem.indexOf(u8, record, "\nerr ") == null); diff --git a/test/pdf_scroll_bench.zig b/test/pdf_scroll_bench.zig index fdc42660..0f93068d 100644 --- a/test/pdf_scroll_bench.zig +++ b/test/pdf_scroll_bench.zig @@ -475,7 +475,7 @@ const Recorder = struct { self.visual = mix(self.visual, place.w); self.visual = mix(self.visual, place.h); self.visual = mix(self.visual, place.native.page); - self.visual = mix(self.visual, @intFromEnum(place.native.fit)); + self.visual = mix(self.visual, @backingInt(place.native.fit)); self.visual = mix(self.visual, place.native.pan_x); self.visual = mix(self.visual, place.native.pan_y); self.visual = mix(self.visual, @as(u32, @bitCast(place.native.pixel_offset_y))); diff --git a/test/perf-baseline-gui-debug.json b/test/perf-baseline-gui-debug.json index 4b60520b..ffcd678f 100644 --- a/test/perf-baseline-gui-debug.json +++ b/test/perf-baseline-gui-debug.json @@ -1 +1 @@ -{"harness":"6cf9f4b8943e7e29","build":{"compiler":"0.17.0","target":"x86_64-linux.5.10...7.2-gnu.2.38","cpu":"x86_64","driver_optimize":"fast","core_optimize":"debug","c_optimize":"fast","terminal_optimize":"safe","platform":"gui","grammars":"full","mupdf":true,"jpx":true,"tracy":false,"quic":false,"theme_animation":true,"terminal_simd":true,"prebuilt_shaders":false},"cols":120,"rows":40,"reps":10,"only":"medium","fixtures":[{"name":"small","lines":1000,"cols":60,"bytes":62694},{"name":"medium","lines":50000,"cols":60,"bytes":3201944},{"name":"large","lines":300000,"cols":60,"bytes":19464444},{"name":"longline","lines":400,"cols":8000,"bytes":3200400},{"name":"esp32p4","lines":12,"cols":240,"bytes":2892}],"cells":[{"op":"open","fixture":"medium","min_us":1732,"med_us":1881,"p90_us":2035,"max_us":2072},{"op":"render","fixture":"medium","min_us":89,"med_us":92,"p90_us":101,"max_us":102},{"op":"key-down","fixture":"medium","min_us":92,"med_us":94,"p90_us":100,"max_us":100},{"op":"key-right","fixture":"medium","min_us":91,"med_us":93,"p90_us":105,"max_us":109},{"op":"page-down","fixture":"medium","min_us":91,"med_us":95,"p90_us":99,"max_us":106},{"op":"wheel","fixture":"medium","min_us":90,"med_us":95,"p90_us":101,"max_us":101},{"op":"edit-char","fixture":"medium","min_us":1226,"med_us":1678,"p90_us":2093,"max_us":2323},{"op":"edit-twin","fixture":"medium","min_us":2275,"med_us":2697,"p90_us":2868,"max_us":2920},{"op":"body-2m","fixture":"medium","min_us":5213,"med_us":11333,"p90_us":18974,"max_us":18999},{"op":"body-appends","fixture":"medium","min_us":175012,"med_us":260087,"p90_us":317184,"max_us":317469},{"op":"deep-sel","fixture":"medium","min_us":83,"med_us":85,"p90_us":86,"max_us":98}]} +{"harness":"15bee9f100e5ef64","build":{"compiler":"0.17.0","target":"x86_64-linux.5.10...7.2-gnu.2.38","cpu":"x86_64","driver_optimize":"fast","core_optimize":"debug","c_optimize":"fast","terminal_optimize":"safe","platform":"gui","grammars":"full","mupdf":true,"jpx":true,"tracy":false,"quic":false,"theme_animation":true,"terminal_simd":true,"prebuilt_shaders":false},"cols":120,"rows":40,"reps":10,"only":"medium","fixtures":[{"name":"small","lines":1000,"cols":60,"bytes":62694},{"name":"medium","lines":50000,"cols":60,"bytes":3201944},{"name":"large","lines":300000,"cols":60,"bytes":19464444},{"name":"longline","lines":400,"cols":8000,"bytes":3200400},{"name":"esp32p4","lines":12,"cols":240,"bytes":2892}],"cells":[{"op":"open","fixture":"medium","min_us":1744,"med_us":1832,"p90_us":2468,"max_us":2524},{"op":"render","fixture":"medium","min_us":88,"med_us":97,"p90_us":114,"max_us":115},{"op":"key-down","fixture":"medium","min_us":95,"med_us":98,"p90_us":104,"max_us":105},{"op":"key-right","fixture":"medium","min_us":92,"med_us":96,"p90_us":98,"max_us":105},{"op":"page-down","fixture":"medium","min_us":91,"med_us":95,"p90_us":97,"max_us":105},{"op":"wheel","fixture":"medium","min_us":87,"med_us":93,"p90_us":99,"max_us":100},{"op":"edit-char","fixture":"medium","min_us":1241,"med_us":1459,"p90_us":1691,"max_us":1724},{"op":"edit-twin","fixture":"medium","min_us":2592,"med_us":3003,"p90_us":3481,"max_us":3503},{"op":"body-2m","fixture":"medium","min_us":4576,"med_us":8262,"p90_us":15424,"max_us":17259},{"op":"body-appends","fixture":"medium","min_us":152003,"med_us":227268,"p90_us":272872,"max_us":326510},{"op":"deep-sel","fixture":"medium","min_us":82,"med_us":83,"p90_us":90,"max_us":93}]} diff --git a/test/perf-baseline-tty-debug.json b/test/perf-baseline-tty-debug.json index a01335bd..b8e534c4 100644 --- a/test/perf-baseline-tty-debug.json +++ b/test/perf-baseline-tty-debug.json @@ -1 +1 @@ -{"harness":"6cf9f4b8943e7e29","build":{"compiler":"0.17.0","target":"x86_64-linux.5.10...7.2-gnu.2.38","cpu":"x86_64","driver_optimize":"fast","core_optimize":"debug","c_optimize":"fast","terminal_optimize":"safe","platform":"tty","grammars":"full","mupdf":true,"jpx":true,"tracy":false,"quic":false,"theme_animation":true,"terminal_simd":true,"prebuilt_shaders":false},"cols":120,"rows":40,"reps":10,"only":"medium","fixtures":[{"name":"small","lines":1000,"cols":60,"bytes":62694},{"name":"medium","lines":50000,"cols":60,"bytes":3201944},{"name":"large","lines":300000,"cols":60,"bytes":19464444},{"name":"longline","lines":400,"cols":8000,"bytes":3200400},{"name":"esp32p4","lines":12,"cols":240,"bytes":2892}],"cells":[{"op":"open","fixture":"medium","min_us":2169,"med_us":2697,"p90_us":3126,"max_us":3207},{"op":"render","fixture":"medium","min_us":89,"med_us":96,"p90_us":101,"max_us":115},{"op":"key-down","fixture":"medium","min_us":93,"med_us":98,"p90_us":104,"max_us":115},{"op":"key-right","fixture":"medium","min_us":96,"med_us":97,"p90_us":102,"max_us":108},{"op":"page-down","fixture":"medium","min_us":96,"med_us":98,"p90_us":102,"max_us":103},{"op":"wheel","fixture":"medium","min_us":89,"med_us":100,"p90_us":128,"max_us":168},{"op":"edit-char","fixture":"medium","min_us":1821,"med_us":2274,"p90_us":2404,"max_us":2610},{"op":"edit-twin","fixture":"medium","min_us":2710,"med_us":3180,"p90_us":3413,"max_us":3636},{"op":"body-2m","fixture":"medium","min_us":9090,"med_us":14438,"p90_us":18158,"max_us":22063},{"op":"body-appends","fixture":"medium","min_us":241367,"med_us":375874,"p90_us":470623,"max_us":528094},{"op":"deep-sel","fixture":"medium","min_us":88,"med_us":89,"p90_us":90,"max_us":90}]} +{"harness":"15bee9f100e5ef64","build":{"compiler":"0.17.0","target":"x86_64-linux.5.10...7.2-gnu.2.38","cpu":"x86_64","driver_optimize":"fast","core_optimize":"debug","c_optimize":"fast","terminal_optimize":"safe","platform":"tty","grammars":"full","mupdf":true,"jpx":true,"tracy":false,"quic":false,"theme_animation":true,"terminal_simd":true,"prebuilt_shaders":false},"cols":120,"rows":40,"reps":10,"only":"medium","fixtures":[{"name":"small","lines":1000,"cols":60,"bytes":62694},{"name":"medium","lines":50000,"cols":60,"bytes":3201944},{"name":"large","lines":300000,"cols":60,"bytes":19464444},{"name":"longline","lines":400,"cols":8000,"bytes":3200400},{"name":"esp32p4","lines":12,"cols":240,"bytes":2892}],"cells":[{"op":"open","fixture":"medium","min_us":1747,"med_us":1912,"p90_us":2150,"max_us":2247},{"op":"render","fixture":"medium","min_us":89,"med_us":95,"p90_us":102,"max_us":104},{"op":"key-down","fixture":"medium","min_us":97,"med_us":101,"p90_us":107,"max_us":133},{"op":"key-right","fixture":"medium","min_us":93,"med_us":104,"p90_us":109,"max_us":112},{"op":"page-down","fixture":"medium","min_us":92,"med_us":96,"p90_us":106,"max_us":108},{"op":"wheel","fixture":"medium","min_us":90,"med_us":92,"p90_us":96,"max_us":96},{"op":"edit-char","fixture":"medium","min_us":1167,"med_us":1345,"p90_us":1483,"max_us":1627},{"op":"edit-twin","fixture":"medium","min_us":2319,"med_us":2921,"p90_us":3425,"max_us":3539},{"op":"body-2m","fixture":"medium","min_us":4333,"med_us":7752,"p90_us":15941,"max_us":17192},{"op":"body-appends","fixture":"medium","min_us":149149,"med_us":234177,"p90_us":285302,"max_us":295516},{"op":"deep-sel","fixture":"medium","min_us":83,"med_us":88,"p90_us":99,"max_us":119}]} diff --git a/test/perf-baseline-tty-fast.json b/test/perf-baseline-tty-fast.json index 04fc88d3..46125349 100644 --- a/test/perf-baseline-tty-fast.json +++ b/test/perf-baseline-tty-fast.json @@ -1 +1 @@ -{"harness":"6cf9f4b8943e7e29","build":{"compiler":"0.17.0","target":"x86_64-linux.5.10...7.2-gnu.2.38","cpu":"x86_64","driver_optimize":"fast","core_optimize":"fast","c_optimize":"fast","terminal_optimize":"fast","platform":"tty","grammars":"full","mupdf":true,"jpx":true,"tracy":false,"quic":false,"theme_animation":true,"terminal_simd":true,"prebuilt_shaders":false},"cols":120,"rows":40,"reps":10,"only":"medium","fixtures":[{"name":"small","lines":1000,"cols":60,"bytes":62694},{"name":"medium","lines":50000,"cols":60,"bytes":3201944},{"name":"large","lines":300000,"cols":60,"bytes":19464444},{"name":"longline","lines":400,"cols":8000,"bytes":3200400},{"name":"esp32p4","lines":12,"cols":240,"bytes":2892}],"cells":[{"op":"open","fixture":"medium","min_us":1695,"med_us":2024,"p90_us":2180,"max_us":2292},{"op":"render","fixture":"medium","min_us":79,"med_us":82,"p90_us":92,"max_us":94},{"op":"key-down","fixture":"medium","min_us":81,"med_us":82,"p90_us":83,"max_us":84},{"op":"key-right","fixture":"medium","min_us":80,"med_us":82,"p90_us":91,"max_us":91},{"op":"page-down","fixture":"medium","min_us":81,"med_us":84,"p90_us":90,"max_us":171},{"op":"wheel","fixture":"medium","min_us":79,"med_us":80,"p90_us":90,"max_us":101},{"op":"edit-char","fixture":"medium","min_us":1332,"med_us":1691,"p90_us":1967,"max_us":1987},{"op":"edit-twin","fixture":"medium","min_us":2160,"med_us":2457,"p90_us":2718,"max_us":2757},{"op":"body-2m","fixture":"medium","min_us":5047,"med_us":13525,"p90_us":16257,"max_us":20323},{"op":"body-appends","fixture":"medium","min_us":155834,"med_us":261597,"p90_us":329936,"max_us":333538},{"op":"deep-sel","fixture":"medium","min_us":75,"med_us":76,"p90_us":84,"max_us":96}]} +{"harness":"15bee9f100e5ef64","build":{"compiler":"0.17.0","target":"x86_64-linux.5.10...7.2-gnu.2.38","cpu":"x86_64","driver_optimize":"fast","core_optimize":"fast","c_optimize":"fast","terminal_optimize":"fast","platform":"tty","grammars":"full","mupdf":true,"jpx":true,"tracy":false,"quic":false,"theme_animation":true,"terminal_simd":true,"prebuilt_shaders":false},"cols":120,"rows":40,"reps":10,"only":"medium","fixtures":[{"name":"small","lines":1000,"cols":60,"bytes":62694},{"name":"medium","lines":50000,"cols":60,"bytes":3201944},{"name":"large","lines":300000,"cols":60,"bytes":19464444},{"name":"longline","lines":400,"cols":8000,"bytes":3200400},{"name":"esp32p4","lines":12,"cols":240,"bytes":2892}],"cells":[{"op":"open","fixture":"medium","min_us":1904,"med_us":2040,"p90_us":2290,"max_us":2600},{"op":"render","fixture":"medium","min_us":80,"med_us":83,"p90_us":88,"max_us":93},{"op":"key-down","fixture":"medium","min_us":81,"med_us":87,"p90_us":93,"max_us":109},{"op":"key-right","fixture":"medium","min_us":79,"med_us":82,"p90_us":86,"max_us":96},{"op":"page-down","fixture":"medium","min_us":79,"med_us":83,"p90_us":89,"max_us":93},{"op":"wheel","fixture":"medium","min_us":77,"med_us":79,"p90_us":82,"max_us":83},{"op":"edit-char","fixture":"medium","min_us":1139,"med_us":1338,"p90_us":1453,"max_us":1578},{"op":"edit-twin","fixture":"medium","min_us":2515,"med_us":2776,"p90_us":2879,"max_us":2907},{"op":"body-2m","fixture":"medium","min_us":4832,"med_us":7650,"p90_us":15076,"max_us":15371},{"op":"body-appends","fixture":"medium","min_us":165796,"med_us":240881,"p90_us":284919,"max_us":292573},{"op":"deep-sel","fixture":"medium","min_us":73,"med_us":75,"p90_us":83,"max_us":93}]} diff --git a/test/perf.zig b/test/perf.zig index d01d1bb5..7662d028 100644 --- a/test/perf.zig +++ b/test/perf.zig @@ -517,8 +517,8 @@ fn gate(cells: *const [std.enums.values(Op).len][fixtures.len]Cell, base: *const }; // Typing beside a twin costs about what typing alone does, whatever the // baseline: the twin takes the splice, never a copy of the text. - const twin_op = @intFromEnum(Op.edit_twin); - const alone_op = @intFromEnum(Op.edit_char); + const twin_op = @backingInt(Op.edit_twin); + const alone_op = @backingInt(Op.edit_char); for (fixtures, 0..) |fx, fi| { const twin = cells[twin_op][fi].min_us; const alone = cells[alone_op][fi].min_us; @@ -1220,7 +1220,7 @@ fn measureMini(io: std.Io, fallback: std.mem.Allocator, reps: usize, json: bool) break :blk try pardes.syntax.highlightFileRange(gpa, path, source, 0, source.len); }; defer gpa.free(styles); - if (styles.len != source.len or std.mem.indexOfScalar(u8, styles, @intFromEnum(pardes.syntax.Syn.comment)) == null) + if (styles.len != source.len or std.mem.indexOfScalar(u8, styles, @backingInt(pardes.syntax.Syn.comment)) == null) return error.MiniSyntaxUnavailable; const expected = try pardes.panes.mini.generate(gpa, source, styles); defer expected.deinit(gpa); diff --git a/test/unit_profile.zig b/test/unit_profile.zig index 59794df9..941efeb2 100644 --- a/test/unit_profile.zig +++ b/test/unit_profile.zig @@ -6,7 +6,7 @@ const Memory = struct { rss_after_bytes: ?usize = null, cumulative_peak_rss_byte fn send(io: std.Io, file: std.Io.File, tag: Client.Tag, body: []const u8, deadline: std.Io.Timeout) !void { var header: [8]u8 = undefined; - std.mem.writeInt(u32, header[0..4], @intFromEnum(tag), .little); + std.mem.writeInt(u32, header[0..4], @backingInt(tag), .little); std.mem.writeInt(u32, header[4..8], @intCast(body.len), .little); for ([_][]const u8{ &header, body }) |part| { var offset: usize = 0; @@ -36,7 +36,7 @@ fn readAll(io: std.Io, file: std.Io.File, bytes: []u8, deadline: std.Io.Timeout) fn receive(io: std.Io, file: std.Io.File, gpa: std.mem.Allocator, deadline: std.Io.Timeout) !struct { tag: Server.Tag, body: []u8 } { var header: [8]u8 = undefined; try readAll(io, file, &header, deadline); - const tag: Server.Tag = @enumFromInt(std.mem.readInt(u32, header[0..4], .little)); + const tag: Server.Tag = @fromBackingInt(@intCast(std.mem.readInt(u32, header[0..4], .little))); const len = std.mem.readInt(u32, header[4..8], .little); if (len > 16 * 1024 * 1024) return error.MessageTooLarge; const bytes = try gpa.alloc(u8, len); -- cgit v1.3 From 0073d05329335dbb0eb85f5c3044e42805d144e5 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Fri, 23 Oct 2026 17:10:58 -0300 Subject: Callstack lists every caller and pages a tree too big for one query; memory bounds and resident-size fixes Callstack walks while the server answers, counts on the message row past a second, puts test callers last at each level, and ends a tree past one query's memory (memory.limits.arena.lsp_query, a 256 MiB region taken and given back per query) in a row whose Callstack shows the next page. Grep reads whole files. New hard limits: undo text per file, image decode pixels, the LSP snapshot of other open files, one paste. Safe builds no longer fill worst-case buffers with 0xAA (memory.unfilled), big regions are kept off transparent huge pages, and malloc_trim runs after big results. Also: Look's git show pages into a +Diff, and dropped marks in File. Co-Authored-By: Claude Opus 5.5 --- build.zig.zon | 4 +- docs/typ/guide.typ | 14 +- docs/typ/reference.typ | 9 +- src/9p.zig | 24 -- src/9p_io.zig | 121 +++--- src/File.zig | 141 +++++-- src/Registers.zig | 13 + src/ShaderBuild.zig | 23 +- src/builtins.zig | 3 + src/colors.zig | 2 +- src/config.zig | 66 +--- src/crash.zig | 6 + src/detached/server.zig | 29 +- src/dump.zig | 11 - src/edit.zig | 190 ++++++++-- src/exec.zig | 6 + src/fs.zig | 82 ++-- src/gui/gui.zig | 329 ++++++---------- src/gui/pet.zig | 29 +- src/host_io.zig | 103 ++++-- src/hunks.zig | 19 +- src/image.zig | 8 +- src/locations.zig | 135 +++++-- src/look.zig | 61 ++- src/lsp/lsp.zig | 17 +- src/lsp/lsp_client.zig | 761 ++++++++++++++++++++++++++------------ src/macos.zig | 17 +- src/main.zig | 12 +- src/memory.zig | 98 +++++ src/mini.zig | 16 +- src/modal.zig | 139 +++++-- src/mouse.zig | 11 +- src/ninep/addr.zig | 42 ++- src/ninep/ctl.zig | 4 + src/panes.zig | 3 + src/pardes.zig | 42 ++- src/regexp.zig | 11 +- src/sam_edit.zig | 15 + src/selection_pipe.zig | 11 +- src/surface.zig | 5 - src/terminal.zig | 86 +---- src/tty/tty.zig | 51 ++- test/lspbench.zig | 22 +- test/panes.zig | 3 - test/perf-baseline-gui-debug.json | 2 +- test/perf-baseline-tty-debug.json | 2 +- test/perf-baseline-tty-fast.json | 2 +- test/perf.zig | 21 +- 48 files changed, 1843 insertions(+), 978 deletions(-) (limited to 'src/main.zig') diff --git a/build.zig.zon b/build.zig.zon index 292bd479..7885fd4e 100644 --- a/build.zig.zon +++ b/build.zig.zon @@ -9,8 +9,8 @@ // read-only HTTPS URL is what a manifest can carry. Re-pin with // `zig fetch --save=cloud9 git+https://git.sr.ht/~gbrls/cloud9#`. .cloud9 = .{ - .url = "git+https://git.sr.ht/~gbrls/cloud9#d5c37d9122240fe95d308fbe15874e14dd786c5a", - .hash = "cloud9-0.1.0-yt86qnAvHgB1dEWGakukcJ54GZ7J3mv_lm_kApzAuEOY", + .url = "git+https://git.sr.ht/~gbrls/cloud9#0702e33bcfadf0abd9ccbaa8b681a19a84c332fe", + .hash = "cloud9-0.1.0-yt86qkExHgCRI7_eJsztRECamioWguBj2mTFsJ5N-AOn", }, // Pinned to the exact libvaxis commit ghostty is built against, so it // is compatible with ghostty's uucode configuration (the one we share diff --git a/docs/typ/guide.typ b/docs/typ/guide.typ index a5327a44..e60b4231 100644 --- a/docs/typ/guide.typ +++ b/docs/typ/guide.typ @@ -240,11 +240,19 @@ wrapping. Cross-directory Look paths are shortened when possible. pane. #word("LookNext") / #word("LookPrev") (#keys("SPC j n", "SPC j p")) select locations without opening them. The view follows the language server's static call hierarchy; recursive paths are marked `↻`, and a -large hierarchy invites continuing from another function. +hierarchy deeper than the limit invites continuing from another function. +Every caller is listed: the walk runs as long as the server keeps answering, +says how many callers it has found on the message row once it takes more +than a second, and shows what it found if the server stops answering. +Asking anything else stops it. A tree too big for one page (about 100,000 +rows, the memory one query may use) ends in a row saying so: running +#word("Callstack") in `+Callstack` shows the next page, from where this +one stopped, with that caller's own callers above it again. +At each level, callers whose function or file name contains "test" come +after the rest. #word("CallstackDepth") reports the current caller depth; `CallstackDepth 16` changes it for subsequent queries. The default is 8 -levels, and the accepted range is 1–64. The view also caps collection at -64 callers. +levels, and the accepted range is 1–64. `CallstackLayout stacked` (the default) puts each signature and call snippet below its location, aligned with the location text; `CallstackLayout inline` puts it diff --git a/docs/typ/reference.typ b/docs/typ/reference.typ index bb13b011..c14ad659 100644 --- a/docs/typ/reference.typ +++ b/docs/typ/reference.typ @@ -264,7 +264,9 @@ A line written to #file("exec") is #word("Exec"): a declaration; from a use it reaches every file); #word("Callstack") (#key("g c") or #key("SPC l b")) opens and focuses `+Callstack`, with static caller ancestry, tree-sitter signatures and Look locations - for callers and call sites. #word("CallstackDepth") reports or sets the + for callers and call sites, test callers after the rest at each level; run + in `+Callstack` itself, it shows the next page of a tree too big for one. + #word("CallstackDepth") reports or sets the runtime depth (1–64, default 8) for subsequent queries. `CallstackLayout stacked` (the default) aligns snippets below their locations; `CallstackLayout inline` places the snippets beside them. @@ -971,12 +973,11 @@ one a #file("exec") open still holds is never reused. In a command pane, #key("n = Find and Grep #word("Find") matches file names, #word("Grep") the text of lines, both literally and -ignoring ASCII case. #word("Grep") reads at most 256 KiB of a file and stops at 512 +ignoring ASCII case. #word("Grep") reads whole files and stops at 512 hits, #word("Find") at 512 names. The walk stops at 20000 files or 100000 entries, 16 deep, and passes over `.git`, `.jj`, `target`, `node_modules`, `.venv`, `__pycache__`, `.zig-cache` and `zig-out`. A cap hit, or a -directory it could not open, is said at the end: `cut at 512 hits`, `N -files read only in part (first 256 KiB)`, `walk cut at N entries`, `N +directory it could not open, is said at the end: `cut at 512 hits`, `walk cut at N entries`, `N directories skipped: permission denied`. A search that finds nothing and skipped nothing fails, `Grep: text not found`, and leaves the `+Search` as it was. diff --git a/src/9p.zig b/src/9p.zig index 67b3b39a..0979b66a 100644 --- a/src/9p.zig +++ b/src/9p.zig @@ -5,16 +5,10 @@ const cloud9 = @import("cloud9"); pub const fs = cloud9.fs; pub const Server = cloud9.fs.Server; -pub const Error = cloud9.Error; -pub const Type = cloud9.Type; -pub const isT = cloud9.isT; pub const header_len = cloud9.header_len; -pub const qid_len = cloud9.qid_len; -pub const stat_fixed = cloud9.stat_fixed; pub const notag = cloud9.notag; pub const nofid = cloud9.nofid; pub const max_welem = cloud9.max_welem; -pub const iohdrsz = cloud9.iohdrsz; pub const Qid = cloud9.Qid; pub const Stat = cloud9.Stat; pub const Msg = cloud9.Msg; @@ -23,29 +17,11 @@ pub const frameLen = cloud9.frameLen; pub const encode = cloud9.encode; pub const decode = cloud9.decode; pub const qtdir = cloud9.qtdir; -pub const qtappend = cloud9.qtappend; -pub const qtexcl = cloud9.qtexcl; -pub const qtmount = cloud9.qtmount; -pub const qtauth = cloud9.qtauth; -pub const qttmp = cloud9.qttmp; -pub const qtfile = cloud9.qtfile; -pub const dmdir = cloud9.dmdir; -pub const dmappend = cloud9.dmappend; -pub const dmexcl = cloud9.dmexcl; -pub const dmmount = cloud9.dmmount; -pub const dmauth = cloud9.dmauth; -pub const dmtmp = cloud9.dmtmp; -pub const dmperm = cloud9.dmperm; pub const Client = cloud9.Client; -pub const ClientError = cloud9.ClientError; -pub const max_tags = cloud9.max_tags; pub const oread = cloud9.oread; pub const owrite = cloud9.owrite; pub const ordwr = cloud9.ordwr; -pub const oexec = cloud9.oexec; pub const otrunc = cloud9.otrunc; -pub const ocexec = cloud9.ocexec; -pub const orclose = cloud9.orclose; pub const errmax = cloud9.fs.errmax; pub const errString = cloud9.fs.errString; pub const msize_min = cloud9.fs.msize_min; diff --git a/src/9p_io.zig b/src/9p_io.zig index 446c24de..87972b43 100644 --- a/src/9p_io.zig +++ b/src/9p_io.zig @@ -174,8 +174,15 @@ pub const Listener = struct { io: std.Io, /// The core that answers; `reset` puts a replacement in. core: *pardes.Pardes, - runner: Runner = undefined, + /// cloud9's runner, sized for every connection's buffers and parks (some + /// 136 MiB): pages of its own (`allocRunner`), written only as clients + /// take slots, so an idle session does not hold them resident. + runner: *Runner = undefined, stopping: std.atomic.Value(bool) = .init(false), + /// The watchers of held Edit writes (watchEdit): canceled and awaited + /// by `deinit`, once the turn lets a waiting one through, so none wakes + /// into a freed Listener. + edit_watchers: std.Io.Group = .init, /// A connection wrote the Restore and has yet to answer it. restore_writer: std.atomic.Value(bool) = .init(false), /// Clients turned away with every slot taken, since the log last said so. @@ -354,8 +361,7 @@ pub const Listener = struct { const later: pardes.ctlfs.Reply = .{ .tag = req.tag, .status = .again }; const ticket = conn.hold(&later) orelse return; core.fs.edit_hold = .{ .asker = conn, .slot = ticket.slot, .seq = ticket.seq, .tag = req.tag, .node = req.node, .handle = req.handle, .written = reply.written }; - const watcher = std.Thread.spawn(.{}, watchEdit, .{ l, conn, ticket }) catch return; - watcher.detach(); + l.edit_watchers.concurrent(l.io, watchEdit, .{ l, conn, ticket }) catch {}; return; } const restoring = core.restore_req != null; @@ -457,13 +463,13 @@ pub const Listener = struct { /// flush, so it is looked for, every 100 ms; a park out for a retry is /// not waiting either, so only three looks in a row with no write being /// served count. - fn watchEdit(l: *Listener, conn: *Runner.Conn, ticket: cloud9.fs.Ticket) void { - const io = pardes.turn.io orelse return; + fn watchEdit(l: *Listener, conn: *Runner.Conn, ticket: cloud9.fs.Ticket) error{Canceled}!void { var misses: u8 = 0; while (!l.stopping.load(.acquire)) { - io.sleep(.fromMilliseconds(100), .awake) catch return; + try l.io.sleep(.fromMilliseconds(100), .awake); _ = pardes.turn.take(); defer pardes.turn.give(); + if (l.stopping.load(.acquire)) return; const core = l.core; const h = core.fs.edit_hold orelse return; if (h.slot != ticket.slot or h.seq != ticket.seq or h.asker != @as(*anyopaque, conn)) return; @@ -914,6 +920,7 @@ pub const Listener = struct { // A connection task may be waiting for the turn; it answers // nothing more once stopping, but the wait itself must end. pardes.turn.rest(); + l.edit_watchers.cancel(l.io); // An answer given as the editor quit (a Kill written to /ctl) // may still be on its way out: let it go before the cut. const deadline = nowMs() +| 200; @@ -942,10 +949,26 @@ pub const Listener = struct { z[l.path_len] = 0; _ = libc.unlink(z[0..l.path_len :0]); } + freeRunner(l.runner); gpa.destroy(l); } }; +/// The runner's memory, from the page allocator with no fill: an Allocator's +/// `create` writes `undefined` over all of it in a safe build, which would make +/// every page resident at startup. +fn allocRunner() ?*Runner { + if (comptime !supported) return @constCast(&@as(Runner, {})); + const bytes = std.heap.page_allocator.rawAlloc(@sizeOf(Runner), .of(Runner), @returnAddress()) orelse return null; + @import("memory.zig").sparse(bytes[0..@sizeOf(Runner)]); + return @ptrCast(@alignCast(bytes)); +} + +fn freeRunner(runner: *Runner) void { + if (comptime !supported) return; + std.heap.page_allocator.rawFree(@as([*]u8, @ptrCast(runner))[0..@sizeOf(Runner)], .of(Runner), @returnAddress()); +} + /// The socket this process listens on, kept where a fatal signal's handler /// can reach it without allocating (unlinkOwnSocket); empty when none. var own_socket: [sun_path_len:0]u8 = undefined; @@ -1065,6 +1088,10 @@ pub fn listen(io: std.Io, gpa: std.mem.Allocator, core: *pardes.Pardes, named: [ } const l = gpa.create(Listener) catch return null; l.* = .{ .io = io, .core = core }; + l.runner = allocRunner() orelse { + gpa.destroy(l); + return null; + }; pardes.turn.start(io); pardes.turn.wake_parked = Listener.wakeParked; pardes.turn.answer_held = Listener.answerHeld; @@ -1551,7 +1578,7 @@ test "a socket path too long for sun_path is no listener, and leaves the editor' defer if (old_copy) |o| { _ = setenv("XDG_RUNTIME_DIR", o, 1); } else { - _ = unsetenv("XDG_RUNTIME_DIR"); + _ = @import("host_io.zig").testUnsetenv("XDG_RUNTIME_DIR"); }; const long = &@as([120]u8, @splat('n')); try testing.expect(listen(testing.io, testing.allocator, p, long, "", null, null) == null); @@ -1572,7 +1599,7 @@ test "a listening editor posts itself into the 9P registry and unposts on stop" if (old_runtime) |v| { _ = setenv("XDG_RUNTIME_DIR", v, 1); gpa.free(v); - } else _ = unsetenv("XDG_RUNTIME_DIR"); + } else _ = @import("host_io.zig").testUnsetenv("XDG_RUNTIME_DIR"); } try testing.expectEqual(@as(c_int, 0), setenv("XDG_RUNTIME_DIR", &directory, 1)); @@ -1633,7 +1660,7 @@ test "Unix TCP and QUIC share one listener through reads writes reconnects and r if (old_runtime) |v| { _ = setenv("XDG_RUNTIME_DIR", v, 1); gpa.free(v); - } else _ = unsetenv("XDG_RUNTIME_DIR"); + } else _ = @import("host_io.zig").testUnsetenv("XDG_RUNTIME_DIR"); } try testing.expectEqual(@as(c_int, 0), setenv("XDG_RUNTIME_DIR", &directory, 1)); const replacement = try gpa.alloc(u8, 3 * msize + 27); @@ -1754,7 +1781,7 @@ test "a change waits while the editor is out mid-step, a read does not, and the if (old_runtime) |v| { _ = setenv("XDG_RUNTIME_DIR", v, 1); gpa.free(v); - } else _ = unsetenv("XDG_RUNTIME_DIR"); + } else _ = @import("host_io.zig").testUnsetenv("XDG_RUNTIME_DIR"); } try testing.expectEqual(@as(c_int, 0), setenv("XDG_RUNTIME_DIR", &directory, 1)); @@ -1829,7 +1856,7 @@ test "a held read is answered when the log has news, and a flushed one spends no if (old_runtime) |v| { _ = setenv("XDG_RUNTIME_DIR", v, 1); gpa.free(v); - } else _ = unsetenv("XDG_RUNTIME_DIR"); + } else _ = @import("host_io.zig").testUnsetenv("XDG_RUNTIME_DIR"); } try testing.expectEqual(@as(c_int, 0), setenv("XDG_RUNTIME_DIR", &directory, 1)); @@ -2001,28 +2028,22 @@ pub fn exportSessionEnv(serial: u32, adopts: bool) void { exportEnv(if (own_socket_len > 0) own_socket[0..own_socket_len] else null, serial, adopts); } +/// Told to children through host_io.ChildEnv, never set into this process's +/// own environment (see ChildEnv.exportVar for why). fn exportEnv(socket: ?[]const u8, serial: u32, adopts: bool) void { - var announced = false; - if (adopts) announcing: { - var buf: [16]u8 = undefined; - const text = std.fmt.bufPrintSentinel(&buf, "{d}", .{@as(u32, @intCast(libc.getpid()))}, 0) catch - break :announcing; - announced = setenv("PARDES_PID", text, 1) == 0; - } - if (!announced) _ = unsetenv("PARDES_PID"); - - if (socket) |own| exporting: { - var sock: [sun_path_len]u8 = undefined; - const path = std.fmt.bufPrintSentinel(&sock, "{s}", .{own}, 0) catch break :exporting; + const ChildEnv = @import("host_io.zig").ChildEnv; + var pid_buf: [16]u8 = undefined; + ChildEnv.exportVar("PARDES_PID", if (adopts) std.fmt.bufPrint(&pid_buf, "{d}", .{@as(u32, @intCast(libc.getpid()))}) catch null else null); + if (socket) |own| { var buf: [16]u8 = undefined; - const id = std.fmt.bufPrintSentinel(&buf, "{d}", .{serial}, 0) catch break :exporting; - if (setenv("PARDES_9P", path, 1) != 0) break :exporting; + ChildEnv.exportVar("PARDES_9P", own); exportMount(own); - if (setenv("PARDES_PANE", id, 1) == 0) return; + ChildEnv.exportVar("PARDES_PANE", std.fmt.bufPrint(&buf, "{d}", .{serial}) catch unreachable); + return; } - _ = unsetenv("PARDES_9P"); - _ = unsetenv("PARDES_PANE"); - _ = unsetenv("PARDES_MOUNT"); + ChildEnv.exportVar("PARDES_9P", null); + ChildEnv.exportVar("PARDES_PANE", null); + ChildEnv.exportVar("PARDES_MOUNT", null); } /// $PARDES_MOUNT, the session's own directory, when the environment says @@ -2040,11 +2061,11 @@ fn exportMount(sock_path: []const u8) void { const suffix = ".sock"; if (mntgen and root.len > 0 and std.mem.startsWith(u8, base, sock_prefix) and std.mem.endsWith(u8, base, suffix) and base.len > sock_prefix.len + suffix.len) { var buf: [4096]u8 = undefined; - if (std.fmt.bufPrintSentinel(&buf, "{s}/pardes/{s}", .{ std.mem.trimEnd(u8, root, "/"), base[sock_prefix.len .. base.len - suffix.len] }, 0)) |mount| { - if (setenv("PARDES_MOUNT", mount, 1) == 0) return; + if (std.fmt.bufPrint(&buf, "{s}/pardes/{s}", .{ std.mem.trimEnd(u8, root, "/"), base[sock_prefix.len .. base.len - suffix.len] })) |mount| { + return @import("host_io.zig").ChildEnv.exportVar("PARDES_MOUNT", mount); } else |_| {} } - _ = unsetenv("PARDES_MOUNT"); + @import("host_io.zig").ChildEnv.exportVar("PARDES_MOUNT", null); } test "a pane's PARDES_MOUNT is the session's directory under 9ns --mntgen, and unset when not known" { @@ -2057,16 +2078,16 @@ test "a pane's PARDES_MOUNT is the session's directory under 9ns --mntgen, and u if (value) |old| { _ = setenv(name, old, 1); testing.allocator.free(old); - } else _ = unsetenv(name); + } else _ = @import("host_io.zig").testUnsetenv(name); }; _ = setenv("NINE_MOUNT", "/mnt/9p", 1); _ = setenv("NINE_MNTGEN", "1", 1); exportMount("/run/user/1000/pardes-9p-work.sock"); - try testing.expectEqualStrings("/mnt/9p/pardes/work", std.mem.span(libc.getenv("PARDES_MOUNT").?)); + try testing.expectEqualStrings("/mnt/9p/pardes/work", @import("host_io.zig").ChildEnv.exported("PARDES_MOUNT").?); // A mount of another server (9ns --unix): not this session's. - _ = unsetenv("NINE_MNTGEN"); + _ = @import("host_io.zig").testUnsetenv("NINE_MNTGEN"); exportMount("/run/user/1000/pardes-9p-work.sock"); - try testing.expect(libc.getenv("PARDES_MOUNT") == null); + try testing.expect(@import("host_io.zig").ChildEnv.exported("PARDES_MOUNT") == null); } test "9P shell environment states being inside pardes apart from how to reach it" { @@ -2079,16 +2100,16 @@ test "9P shell environment states being inside pardes apart from how to reach it if (value) |old| { _ = setenv(name, old, 1); testing.allocator.free(old); - } else _ = unsetenv(name); + } else _ = @import("host_io.zig").testUnsetenv(name); }; var dir: [sun_path_len:0]u8 = undefined; _ = setenv("XDG_RUNTIME_DIR", "/run/user/1000", 1); try testing.expectEqualStrings("/run/user/1000", socketDir(&dir).?); - _ = unsetenv("XDG_RUNTIME_DIR"); + _ = @import("host_io.zig").testUnsetenv("XDG_RUNTIME_DIR"); _ = setenv("HOME", "/home/example", 1); try testing.expectEqualStrings("/home/example/.local/state/pardes", socketDir(&dir).?); - _ = unsetenv("HOME"); + _ = @import("host_io.zig").testUnsetenv("HOME"); try testing.expect(socketDir(&dir) == null); const listener = try testing.allocator.create(Listener); @@ -2104,25 +2125,25 @@ test "9P shell environment states being inside pardes apart from how to reach it // parent, so a pardes started in one of its shells runs a session of // its own instead of handing its argument over. exportPaneEnv(listener, 7, false); - try testing.expectEqualStrings(path, std.mem.span(libc.getenv("PARDES_9P").?)); - try testing.expectEqualStrings("7", std.mem.span(libc.getenv("PARDES_PANE").?)); - try testing.expect(libc.getenv("PARDES_PID") == null); + try testing.expectEqualStrings(path, @import("host_io.zig").ChildEnv.exported("PARDES_9P").?); + try testing.expectEqualStrings("7", @import("host_io.zig").ChildEnv.exported("PARDES_PANE").?); + try testing.expect(@import("host_io.zig").ChildEnv.exported("PARDES_PID") == null); exportPaneEnv(listener, 8, true); - try testing.expectEqualStrings("8", std.mem.span(libc.getenv("PARDES_PANE").?)); - try testing.expectEqualStrings(own_pid, std.mem.span(libc.getenv("PARDES_PID").?)); + try testing.expectEqualStrings("8", @import("host_io.zig").ChildEnv.exported("PARDES_PANE").?); + try testing.expectEqualStrings(own_pid, @import("host_io.zig").ChildEnv.exported("PARDES_PID").?); // A session whose listener never came up is still the session this shell // is inside: the pid stands on its own, and only the address is missing. exportPaneEnv(null, 0, true); - try testing.expect(libc.getenv("PARDES_9P") == null); - try testing.expect(libc.getenv("PARDES_PANE") == null); - try testing.expectEqualStrings(own_pid, std.mem.span(libc.getenv("PARDES_PID").?)); + try testing.expect(@import("host_io.zig").ChildEnv.exported("PARDES_9P") == null); + try testing.expect(@import("host_io.zig").ChildEnv.exported("PARDES_PANE") == null); + try testing.expectEqualStrings(own_pid, @import("host_io.zig").ChildEnv.exported("PARDES_PID").?); exportPaneEnv(null, 0, false); - try testing.expect(libc.getenv("PARDES_9P") == null); - try testing.expect(libc.getenv("PARDES_PANE") == null); - try testing.expect(libc.getenv("PARDES_PID") == null); + try testing.expect(@import("host_io.zig").ChildEnv.exported("PARDES_9P") == null); + try testing.expect(@import("host_io.zig").ChildEnv.exported("PARDES_PANE") == null); + try testing.expect(@import("host_io.zig").ChildEnv.exported("PARDES_PID") == null); } pub const Client = struct { diff --git a/src/File.zig b/src/File.zig index 59b04e3f..7e05ac9f 100644 --- a/src/File.zig +++ b/src/File.zig @@ -43,14 +43,14 @@ pub const Snapshot = struct { saved_len: ?usize = null, fn deinit(s: Snapshot, gpa: std.mem.Allocator) void { - gpa.free(s.content); + pardes.memory.freeUnfilled(gpa, s.content); } }; /// The pane's text, place and name now, for an undo or redo step. fn snapshotOf(gpa: std.mem.Allocator, pane: *const Pane, f: *const State) ?Snapshot { return .{ - .content = gpa.dupe(u8, f.content) catch return null, + .content = pardes.memory.dupeUnfilled(gpa, f.content) catch return null, .cur_row = pane.body.cur_row, .cur_col = pane.body.cur_col, .vsel = pane.body.vsel, @@ -105,6 +105,8 @@ pub const History = struct { undo_len: usize = 0, redo: [limits.undo_max]Snapshot = undefined, redo_len: usize = 0, + /// The text `undo` and `redo` hold, kept near limits.undo_bytes. + bytes: usize = 0, /// The names the file had, each with the rename generation it ended /// (Snapshot.gen), and the generation now. @@ -115,6 +117,7 @@ pub const History = struct { const history = try gpa.create(History); history.undo_len = 0; history.redo_len = 0; + history.bytes = 0; history.names = .empty; history.gen = 0; return history; @@ -165,6 +168,9 @@ pub const State = struct { /// edit drops them (setContentSpan); shifting them through the splice, /// as pane.zig's shiftOne moves dot, would keep them. pager_spans: []pardes.pager.Span = &.{}, + /// The rows and spans an edit dropped, with the text they were for: an + /// edit (an undo) back to that very text takes them again. + dropped_marks: ?DroppedMarks = null, /// Seconds of the last content change, for the filesystem's stat; zero until edited. mtime: u32 = 0, /// Non-null for a generated output buffer rather than an on-disk file. @@ -457,10 +463,6 @@ test "an invalid byte in a grapheme is one cell, and never reaches vaxis's width try std.testing.expectEqual(@as(usize, 4), fitEnd(text, 0, 10)); } -pub fn byteDisplayWidth(byte: u8) usize { - return if (byte == '\t') config.tab_now else 1; -} - pub fn displayWidth(text: []const u8) usize { var width: usize = 0; var at: usize = 0; @@ -787,18 +789,9 @@ pub fn lineIndex(gpa: std.mem.Allocator, f: *State) ![]const usize { pub const Span = struct { head: usize, tail: usize }; fn editedLineStarts(gpa: std.mem.Allocator, starts: []const usize, old: []const u8, new: []const u8, known: ?Span) ![]usize { - const n = @min(old.len, new.len); - var head: usize = 0; - var tail: usize = 0; - if (known) |span| { - head = span.head; - tail = span.tail; - } else { - while (head + 64 <= n and std.mem.eql(u8, old[head..][0..64], new[head..][0..64])) head += 64; - while (head < n and old[head] == new[head]) head += 1; - while (tail + 64 <= n - head and std.mem.eql(u8, old[old.len - tail - 64 ..][0..64], new[new.len - tail - 64 ..][0..64])) tail += 64; - while (tail < n - head and old[old.len - tail - 1] == new[new.len - tail - 1]) tail += 1; - } + const span = known orelse spanOf(old, new); + const head = span.head; + const tail = span.tail; // A start s follows the newline at s-1: kept while that newline is in // the common head, shifted while it is in the common tail. const kept = std.sort.upperBound(usize, starts, head, struct { @@ -1123,6 +1116,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.dropped_marks) |m| m.deinit(p.gpa); if (file.context_declarations.len > 0) p.tree_sitter_gpa.free(file.context_declarations); if (file.node_tree) |tree| syntax.freeTree(tree); for (file.node_history.items) |step| p.gpa.free(step.ranges); @@ -1140,6 +1134,18 @@ fn reportEdit(p: *Pardes, f: *State, new: []const u8) void { pardes.ctlfs.events.noteReplace(p, id, false, f.content, new); } +pub const DroppedMarks = struct { + len: usize, + hash: u64, + rows: []locations.Row, + spans: []pardes.pager.Span, + + fn deinit(m: DroppedMarks, gpa: std.mem.Allocator) void { + locations.freeRows(gpa, m.rows); + gpa.free(m.spans); + } +}; + pub fn setContent(p: *Pardes, f: *State, new: []u8) void { setContentSpan(p, f, new, null); } @@ -1160,10 +1166,16 @@ pub fn setContentSpan(p: *Pardes, f: *State, new: []u8, span_in: ?Span) void { moved[i] = .{ .cursor = spliced(@min(at, f.content.len), f.content.len, new.len, span.?), .scroll = spliced(lineStart(p.gpa, tf, tf.scroll), f.content.len, new.len, span.?) }; } const old_starts = f.line_starts.ptr; - locations.freeRows(p.gpa, f.location_rows); - f.location_rows = &.{}; - p.gpa.free(f.pager_spans); - f.pager_spans = &.{}; + if (f.location_rows.len > 0 or f.pager_spans.len > 0) { + if (f.dropped_marks) |m| m.deinit(p.gpa); + f.dropped_marks = .{ .len = f.content.len, .hash = std.hash.Wyhash.hash(0, f.content), .rows = f.location_rows, .spans = f.pager_spans }; + f.location_rows = &.{}; + f.pager_spans = &.{}; + } else if (f.dropped_marks) |m| if (m.len == new.len and m.hash == std.hash.Wyhash.hash(0, new)) { + f.location_rows = m.rows; + f.pager_spans = m.spans; + f.dropped_marks = null; + }; for (p.panes) |slot| if (slot) |pane| { if (pane.file) |*file| if (file == f) { for (0..pane.sel.len) |button| { @@ -1182,7 +1194,9 @@ pub fn setContentSpan(p: *Pardes, f: *State, new: []u8, span_in: ?Span) void { f.saved_hash = std.hash.Wyhash.hash(0, f.content); f.saved_len = f.content.len; } - p.gpa.free(f.content); + // Raw: `free` overwrites a safe build's freed memory, a whole file's + // worth per keystroke. + if (f.content.len > 0) p.gpa.rawFree(f.content, .of(u8), @returnAddress()); f.content = new; f.revision +%= 1; if (f.saved_hash) |h| if ((f.saved_len orelse new.len) == new.len and std.hash.Wyhash.hash(0, new) == h) { @@ -1241,14 +1255,43 @@ fn spliced(at: usize, old_len: usize, new_len: usize, span: Span) usize { } /// What `old` and `new` agree on at either end. -fn spanOf(old: []const u8, new: []const u8) Span { +/// What `new` kept of `old` at either end, compared 32 bytes at a time +/// (a byte at a time was most of a `d` in a 7 MB file). +pub fn spanOf(old: []const u8, new: []const u8) Span { + const block = 32; const n = @min(old.len, new.len); - const head = std.mem.indexOfDiff(u8, old[0..n], new[0..n]) orelse n; + var head: usize = 0; + while (head + block <= n and std.mem.eql(u8, old[head..][0..block], new[head..][0..block])) head += block; + while (head < n and old[head] == new[head]) head += 1; var tail: usize = 0; + while (tail + block <= n - head and std.mem.eql(u8, old[old.len - tail - block ..][0..block], new[new.len - tail - block ..][0..block])) tail += block; while (tail < n - head and old[old.len - 1 - tail] == new[new.len - 1 - tail]) tail += 1; return .{ .head = head, .tail = tail }; } +test "spanOf by blocks finds the byte loop's ends" { + var prng: std.Random.DefaultPrng = .init(5); + const random = prng.random(); + var a: [160]u8 = undefined; + var b: [160]u8 = undefined; + for (0..4000) |_| { + const la = random.uintLessThan(usize, a.len); + const lb = random.uintLessThan(usize, b.len); + for (a[0..la]) |*c| c.* = "ab"[random.uintLessThan(usize, 2)]; + const keep = @min(la, lb); + @memcpy(b[0..keep], a[0..keep]); + for (b[keep..lb]) |*c| c.* = "ab"[random.uintLessThan(usize, 2)]; + if (lb > 0 and random.boolean()) b[random.uintLessThan(usize, lb)] ^= 1; + const old = a[0..la]; + const new = b[0..lb]; + const n = @min(old.len, new.len); + const head = std.mem.indexOfDiff(u8, old[0..n], new[0..n]) orelse n; + var tail: usize = 0; + while (tail < n - head and old[old.len - 1 - tail] == new[new.len - 1 - tail]) tail += 1; + try std.testing.expectEqual(Span{ .head = head, .tail = tail }, spanOf(old, new)); + } +} + fn positionIn(gpa: std.mem.Allocator, f: *State, at: usize) struct { row: usize, col: usize } { const index = lineIndex(gpa, f) catch { const c = modal.positionAt(f.content, at); @@ -1492,14 +1535,18 @@ pub fn restoreSnap(pane: *Pane, f: *State, snap: Snapshot) void { pane.ensureCursorVisible(); } -fn pushHistory(gpa: std.mem.Allocator, slots: []Snapshot, len: *usize, snap: Snapshot) void { - if (len.* == slots.len) { +/// Bounded in steps and in bytes: the oldest go first, though the one +/// pushed always stays. +fn pushHistory(gpa: std.mem.Allocator, history: *History, slots: []Snapshot, len: *usize, snap: Snapshot) void { + while (len.* > 0 and (len.* == slots.len or history.bytes + snap.content.len > limits.undo_bytes)) { + history.bytes -= slots[0].content.len; slots[0].deinit(gpa); - std.mem.copyForwards(Snapshot, slots[0 .. slots.len - 1], slots[1..]); + std.mem.copyForwards(Snapshot, slots[0 .. len.* - 1], slots[1..len.*]); len.* -= 1; } slots[len.*] = snap; len.* += 1; + history.bytes += snap.content.len; } pub fn pushUndo(p: *Pardes, pane: *Pane) void { @@ -1510,9 +1557,12 @@ pub fn pushUndo(p: *Pardes, pane: *Pane) void { if (std.mem.eql(u8, last.content, f.content) and last.gen == history.gen) return; } const snap = snapshotOf(p.gpa, pane, f) orelse return; - pushHistory(p.gpa, &history.undo, &history.undo_len, snap); - for (history.redo[0..history.redo_len]) |item| item.deinit(p.gpa); + for (history.redo[0..history.redo_len]) |item| { + history.bytes -= item.content.len; + item.deinit(p.gpa); + } history.redo_len = 0; + pushHistory(p.gpa, history, &history.undo, &history.undo_len, snap); } pub fn undo(p: *Pardes, pane: *Pane) void { @@ -1520,9 +1570,10 @@ pub fn undo(p: *Pardes, pane: *Pane) void { const history = f.history; if (history.undo_len == 0) return; const current = snapshotOf(p.gpa, pane, f) orelse return; - pushHistory(p.gpa, &history.redo, &history.redo_len, current); + pushHistory(p.gpa, history, &history.redo, &history.redo_len, current); history.undo_len -= 1; const previous = history.undo[history.undo_len]; + history.bytes -= previous.content.len; // the file's text now setContent(p, f, previous.content); restoreName(p, pane, f, previous); restoreSnap(pane, f, previous); @@ -1533,9 +1584,10 @@ pub fn redo(p: *Pardes, pane: *Pane) void { const history = f.history; if (history.redo_len == 0) return; const current = snapshotOf(p.gpa, pane, f) orelse return; - pushHistory(p.gpa, &history.undo, &history.undo_len, current); + pushHistory(p.gpa, history, &history.undo, &history.undo_len, current); history.redo_len -= 1; const next = history.redo[history.redo_len]; + history.bytes -= next.content.len; // the file's text now setContent(p, f, next.content); restoreName(p, pane, f, next); restoreSnap(pane, f, next); @@ -2266,3 +2318,28 @@ pub fn paintWordSelection( } } } + +test "undo keeps its steps within a byte bound, the newest always" { + const gpa = std.testing.allocator; + const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24 }); + defer p.deinit(); + const pane = try p.setTestFile(""); + const f = &pane.file.?; + const step = limits.undo_bytes / 4 + 1; + const text = try gpa.alloc(u8, step); + defer gpa.free(text); + for (0..8) |i| { + @memset(text, 'a' + @as(u8, @intCast(i))); + pushUndo(p, pane); + setContent(p, f, try gpa.dupe(u8, text)); + } + pushUndo(p, pane); + const history = f.history; + try std.testing.expect(history.undo_len > 0 and history.undo_len < 8); + try std.testing.expect(history.bytes <= limits.undo_bytes + step); + var sum: usize = 0; + for (history.undo[0..history.undo_len]) |snap| sum += snap.content.len; + try std.testing.expectEqual(sum, history.bytes); + undo(p, pane); + try std.testing.expectEqualStrings(text[0..1], f.content[0..1]); +} diff --git a/src/Registers.zig b/src/Registers.zig index 3f2486cd..5e23da5b 100644 --- a/src/Registers.zig +++ b/src/Registers.zig @@ -81,6 +81,7 @@ pub fn text(r: *Registers, gpa: std.mem.Allocator, name: u21) ?[]const u8 { const reg = r.get(name) orelse return null; if (reg.joined) |j| return j; var out: std.ArrayList(u8) = .empty; + defer out.deinit(gpa); // what a failed append left; empty once owned for (reg.values, 0..) |v, i| { if (i > 0 and !std.mem.endsWith(u8, reg.values[i - 1], "\n")) out.append(gpa, '\n') catch return null; out.appendSlice(gpa, v) catch return null; @@ -105,3 +106,15 @@ test "a register holds a value per range and joins them for one-text readers" { try std.testing.expectEqualStrings("x", r.text(gpa, 'a').?); try std.testing.expectEqualStrings("one\ntwo", r.text(gpa, default).?); } + +test "joining a register that runs out of memory partway leaks nothing" { + var r: Registers = .{}; + defer r.deinit(std.testing.allocator); + r.put(std.testing.allocator, default, "one", 0, 2, true); + r.put(std.testing.allocator, default, "two", 1, 2, false); + r.put(std.testing.allocator, default, &(@as([4096]u8, @splat('x'))), 1, 2, false); + // The first append allocates; growing for the 4096 bytes fails. + var failing = std.testing.FailingAllocator.init(std.testing.allocator, .{ .fail_index = 1, .resize_fail_index = 0 }); + try std.testing.expect(r.text(failing.allocator(), default) == null); + try std.testing.expectEqual(failing.allocated_bytes, failing.freed_bytes); +} diff --git a/src/ShaderBuild.zig b/src/ShaderBuild.zig index b50999a5..e5b6680b 100644 --- a/src/ShaderBuild.zig +++ b/src/ShaderBuild.zig @@ -76,7 +76,8 @@ const Result = union(enum) { spirv: struct { bytes: []u8, source: u64, animated: bool }, }; -/// One compile of the stale files, on its own thread. +/// One compile of the stale files, a task of its own: `deinit` cancels it +/// (glslc's wait is a cancelation point) rather than waiting out a glslc. const Job = struct { io: std.Io, gpa: std.mem.Allocator, @@ -86,7 +87,10 @@ const Job = struct { results: [max]Result = @splat(.none), len: usize = 0, done: std.atomic.Value(bool) = .init(false), - thread: std.Thread = undefined, + /// Set before the cancel: the files after the one it stopped are not + /// compiled either (a cancel is said once, to the wait it lands in). + stop: std.atomic.Value(bool) = .init(false), + future: std.Io.Future(void) = undefined, }; files: [max]File = @splat(.{}), @@ -105,7 +109,7 @@ pub fn sync(b: *Build, gpa: std.mem.Allocator, io: std.Io, core: *pardes.Pardes, var collected = false; if (b.job) |job| { if (!job.done.load(.acquire)) return false; - job.thread.join(); + job.future.await(job.io); b.job = null; b.collect(gpa, core, job); collected = true; @@ -148,7 +152,7 @@ pub fn sync(b: *Build, gpa: std.mem.Allocator, io: std.Io, core: *pardes.Pardes, job.len += 1; file.stale = false; } - job.thread = std.Thread.spawn(.{}, compile, .{job}) catch { + job.future = io.concurrent(compile, .{job}) catch { for (job.paths[0..job.len]) |path| gpa.free(path); gpa.destroy(job); return collected; @@ -174,7 +178,8 @@ pub fn view(b: *const Build, chain: *const Chain, out: *[max]Pass) []const Pass pub fn deinit(b: *Build, gpa: std.mem.Allocator, fd: c_int, watches: *file_watch.Table) void { if (b.job) |job| { - job.thread.join(); + job.stop.store(true, .release); + job.future.cancel(job.io); freeJob(gpa, job); } for (b.files[0..b.len]) |file| free(gpa, file); @@ -245,7 +250,10 @@ fn expand(buf: *[4096]u8, path: []const u8) []const u8 { /// build's own flags (build.zig compileGlsl), source on stdin, SPIR-V on /// stdout. fn compile(job: *Job) void { - for (job.paths[0..job.len], 0..) |path, i| job.results[i] = compileOne(job.gpa, job.io, path, job.known[i]); + for (job.paths[0..job.len], 0..) |path, i| { + if (job.stop.load(.acquire)) break; + job.results[i] = compileOne(job.gpa, job.io, path, job.known[i]); + } job.done.store(true, .release); if (job.wake.call) |call| call(job.wake.ctx); } @@ -378,7 +386,8 @@ test "a save that changes a file compiles it again, a failed one keeps the last fn run(build: *Build, c: *pardes.Pardes, f: c_int, w: *file_watch.Table) void { _ = build.sync(std.testing.allocator, std.testing.io, c, f, w, .{}); while (build.job) |job| { - while (!job.done.load(.acquire)) std.Thread.yield() catch {}; + job.future.await(std.testing.io); + job.done.store(true, .release); _ = build.sync(std.testing.allocator, std.testing.io, c, f, w, .{}); } } diff --git a/src/builtins.zig b/src/builtins.zig index cc7d1d4a..fdce534b 100644 --- a/src/builtins.zig +++ b/src/builtins.zig @@ -1971,6 +1971,9 @@ pub const WsDiagnostics = struct { /// Show outermost callers first, with signatures and call sites (gc). pub const Callstack = struct { pub fn run(c: Ctx) void { + // In +Callstack itself: the next page of what it shows. + if (c.pane.file) |f| if (f.output) |o| if (std.meta.eql(o.from, panes.Output.Origin{ .query = .callstack })) + return c.p.callstackMore(c.id); c.p.lspRequest(c.id, .callstack, ""); } }; diff --git a/src/colors.zig b/src/colors.zig index dd0d8938..28136975 100644 --- a/src/colors.zig +++ b/src/colors.zig @@ -840,7 +840,7 @@ pub fn loadThemeFile(p: *Pardes, generation: u32, bytes: []const u8, animate: bo @memcpy(settled[0..request.path.len], request.path); _ = p.theme_file_loaded.set(settled[0..request.path.len]); invalidateThemeDependentRasters(p); - _ = p.scratch.reset(.retain_capacity); + _ = p.scratch.reset(.{ .retain_with_limit = pardes.memory.limits.scratch_kept }); p.sync(); return true; } diff --git a/src/config.zig b/src/config.zig index a92aabb6..5251b1e5 100644 --- a/src/config.zig +++ b/src/config.zig @@ -1230,27 +1230,12 @@ pub const Runtime = struct { if (!state.shell.requested.set(value)) return false; state.shell.pending = true; }, - .tagline_size => { - const text = std.mem.trim(u8, argument orelse return false, " \t\r\n"); - const percent = std.fmt.parseInt(u16, text, 10) catch return false; - if (percent < tagline_percent_min or percent > tagline_percent_max) return false; - state.font.tagline_percent = @intCast(percent); - }, + .tagline_size => state.font.tagline_percent = @intCast(number(u16, argument, " \t\r\n", tagline_percent_min, tagline_percent_max) orelse return false), .window_opacity => { - const text = std.mem.trim(u8, argument orelse return false, " \t\r\n"); - for (text) |byte| if (!std.ascii.isDigit(byte)) return false; - const percent = std.fmt.parseInt(u8, text, 10) catch return false; - if (percent > 100) return false; - state.window_opacity = percent; + state.window_opacity = number(u8, argument, " \t\r\n", 0, 100) orelse return false; state.window_opacity_pending = true; }, - .window_blur => { - const text = std.mem.trim(u8, argument orelse return false, " \t\r\n"); - for (text) |byte| if (!std.ascii.isDigit(byte)) return false; - const percent = std.fmt.parseInt(u8, text, 10) catch return false; - if (percent > 100) return false; - state.window_blur = percent; - }, + .window_blur => state.window_blur = number(u8, argument, " \t\r\n", 0, 100) orelse return false, // Bare, it returns to the default directory. Else an absolute or // `~` path, to a directory there or to be made, that may be // written: a Dump there could never be, refused now. @@ -1264,10 +1249,7 @@ pub const Runtime = struct { if (!state.dump_dir.set(text)) return false; }, .message_ms => |which| { - const text = std.mem.trim(u8, argument orelse return false, " \t\r\n"); - for (text) |byte| if (!std.ascii.isDigit(byte)) return false; - const ms = std.fmt.parseInt(u16, text, 10) catch return false; - if (ms > message_ms_max) return false; + const ms = number(u16, argument, " \t\r\n", 0, message_ms_max) orelse return false; switch (which) { inline else => |w| @field(state, "message_" ++ @tagName(w) ++ "_ms") = ms, } @@ -1330,30 +1312,10 @@ pub const Runtime = struct { std.meta.stringToEnum(LiftStyle, text) orelse return false; }, .motion => state.motion = stepped(animation.Motion.Flavour, state.motion, argument) orelse return false, - .inactive_dim => { - const text = std.mem.trim(u8, argument orelse return false, " \t\r\n%"); - const percent = std.fmt.parseInt(u8, text, 10) catch return false; - if (percent > 100) return false; - state.inactive_dim = percent; - }, - .grip_width => { - const text = std.mem.trim(u8, argument orelse return false, " \t\r\n%"); - const percent = std.fmt.parseInt(u16, text, 10) catch return false; - if (percent < 50 or percent > 300) return false; - state.grip_width = percent; - }, - .callstack_depth => { - const text = std.mem.trim(u8, argument orelse return false, " \t\r\n"); - const depth = std.fmt.parseInt(u8, text, 10) catch return false; - if (depth < 1 or depth > @import("lsp/lsp.zig").callstack_max_depth) return false; - state.callstack_depth = depth; - }, - .tab => { - const text = std.mem.trim(u8, argument orelse return false, " \t\r\n"); - const width = std.fmt.parseInt(u16, text, 10) catch return false; - if (width < 1 or width > 16) return false; - state.tab = width; - }, + .inactive_dim => state.inactive_dim = number(u8, argument, " \t\r\n%", 0, 100) orelse return false, + .grip_width => state.grip_width = number(u16, argument, " \t\r\n%", 50, 300) orelse return false, + .callstack_depth => state.callstack_depth = number(u8, argument, " \t\r\n", 1, @import("lsp/lsp.zig").callstack_max_depth) orelse return false, + .tab => state.tab = number(u16, argument, " \t\r\n", 1, 16) orelse return false, .theme, .font => return false, } return true; @@ -1411,6 +1373,16 @@ pub const Runtime = struct { return all[(at + 1) % all.len]; } + /// A setting's number: digits only (parseInt alone takes a sign and `_`), + /// trimmed of `trim`, within lo..hi. + fn number(comptime T: type, argument: ?[]const u8, trim: []const u8, lo: T, hi: T) ?T { + const text = std.mem.trim(u8, argument orelse return null, trim); + if (text.len == 0) return null; + for (text) |byte| if (!std.ascii.isDigit(byte)) return null; + const n = std.fmt.parseInt(T, text, 10) catch return null; + return if (n < lo or n > hi) null else n; + } + /// What `on`, `off` or nothing after a switch word asks for: null flips /// it, as a bare tagline word does. fn switchedTo(argument: ?[]const u8) error{NotOnOrOff}!?bool { @@ -2523,7 +2495,7 @@ test "CallstackDepth is bounded and keeps the last valid runtime limit" { try std.testing.expect(Runtime.apply(&state, Runtime.find("CallstackDepth").?, value)); try std.testing.expectEqual(try std.fmt.parseInt(u8, value, 10), state.callstack_depth); } - for ([_][]const u8{ "0", "65", "256", "-1", "eight", "" }) |value| { + for ([_][]const u8{ "0", "65", "256", "-1", "+8", "1_6", "eight", "" }) |value| { try std.testing.expect(!Runtime.apply(&state, Runtime.find("CallstackDepth").?, value)); try std.testing.expectEqual(@as(u8, 64), state.callstack_depth); } diff --git a/src/crash.zig b/src/crash.zig index 34dc1b3d..a432fb87 100644 --- a/src/crash.zig +++ b/src/crash.zig @@ -34,6 +34,9 @@ pub const name = "crashes"; /// A panic handler is the one caller that cannot check whether its input is /// still alive, so it does not borrow. var dir_buf: [1024]u8 = undefined; + +/// The crash file's bound (see `record`). +const max_log_bytes = 256 * 1024; var dir_len: usize = 0; /// Called where the launcher sets `Options.config_dir`. Ignores a path too long @@ -109,6 +112,9 @@ pub fn record(msg: []const u8) void { }, @as(std.c.mode_t, 0o600)); if (fd < 0) return; defer _ = std.c.close(fd); + // Bounded: a file past `max_log_bytes` starts over, so it keeps the + // newest records rather than every crash since it was first made. + if (std.c.lseek(fd, 0, std.c.SEEK.END) > max_log_bytes) _ = std.c.ftruncate(fd, 0); var w: std.Io.Writer = .fixed(&scratch); diff --git a/src/detached/server.zig b/src/detached/server.zig index d6a1f553..6c8d4352 100644 --- a/src/detached/server.zig +++ b/src/detached/server.zig @@ -107,17 +107,19 @@ const Mailbox = struct { status: ?[]u8 = null, }; - mutex: std.atomic.Mutex = .unlocked, + /// Taken by the workers and the loop; `io` is the session's (initAsync). + mutex: std.Io.Mutex = .init, + io: std.Io = undefined, batch: Batch = .{}, wake: [2]c_int = .{ -1, -1 }, fn post(box: *Mailbox, completion: Completion) void { - while (!box.mutex.tryLock()) std.atomic.spinLoopHint(); + box.mutex.lockUncancelable(box.io); // Tasks retain their slot until the owner consumes their one completion. std.debug.assert(box.batch.len < capacity); box.batch.items[box.batch.len] = completion; box.batch.len += 1; - box.mutex.unlock(); + box.mutex.unlock(box.io); box.signal(); } @@ -130,8 +132,8 @@ const Mailbox = struct { fn take(box: *Mailbox) Batch { var bytes: [128]u8 = undefined; while (libc.recv(box.wake[0], &bytes, bytes.len, 0) > 0) {} - while (!box.mutex.tryLock()) std.atomic.spinLoopHint(); - defer box.mutex.unlock(); + box.mutex.lockUncancelable(box.io); + defer box.mutex.unlock(box.io); const batch = box.batch; box.batch.len = 0; box.batch.status = null; @@ -184,6 +186,7 @@ pub const Session = struct { accept_paused_ms: i64 = 0, pub fn initAsync(s: *Session) !void { + s.mailbox.io = s.io; var pair: [2]c_int = undefined; if (libc.socketpair(libc.AF.UNIX, libc.SOCK.STREAM, 0, &pair) != 0) return error.SocketFailed; errdefer for (pair) |fd| { @@ -410,7 +413,7 @@ pub const Session = struct { s.core.update(.{ .lsp_resp = .{ .id = request.id, .rows = null } }); return s.core.reportError(request.pane, "lsp", err); }; - const future = s.io.concurrent(lspWorker, .{ s.worker_gpa, job, &s.mailbox }) catch |err| { + const future = s.io.concurrent(lspWorker, .{ s.io, s.worker_gpa, job, &s.mailbox }) catch |err| { job.free(s.worker_gpa); s.core.update(.{ .lsp_resp = .{ .id = request.id, .rows = null } }); return s.core.reportError(request.pane, "lsp", err); @@ -418,8 +421,8 @@ pub const Session = struct { s.lsp_task = .{ .id = request.id, .future = future }; } - fn lspWorker(gpa: std.mem.Allocator, job: *host_io.Lsp.Job, box: *Mailbox) anyerror!void { - host_io.Lsp.work(gpa, job, box, deliverLspRows); + fn lspWorker(io: std.Io, gpa: std.mem.Allocator, job: *host_io.Lsp.Job, box: *Mailbox) anyerror!void { + host_io.Lsp.work(io, gpa, job, box, deliverLspRows); } fn deliverLspRows(ctx: ?*anyopaque, id: u32, rows: ?[]u8) void { @@ -430,10 +433,10 @@ pub const Session = struct { fn lspStatus(ctx: ?*anyopaque, text: []const u8) void { const s = of(ctx); const copy = s.worker_gpa.dupe(u8, text) catch return; - while (!s.mailbox.mutex.tryLock()) std.atomic.spinLoopHint(); + s.mailbox.mutex.lockUncancelable(s.io); if (s.mailbox.batch.status) |old| s.worker_gpa.free(old); s.mailbox.batch.status = copy; - s.mailbox.mutex.unlock(); + s.mailbox.mutex.unlock(s.io); s.mailbox.signal(); } @@ -529,7 +532,8 @@ pub const Session = struct { if (pane >= s.ptys.len) return; const pt = &s.ptys[pane]; if (pt.fd < 0) return; - if (pt.out.items.len > pty_backlog) { + // The bound holds with this write in: queued and new together. + if (pt.out.items.len + bytes.len > pty_backlog) { var mbuf: [256]u8 = undefined; const text = std.fmt.bufPrint( &mbuf, @@ -1145,6 +1149,9 @@ pub const Session = struct { s.queue(c, bytes); } + /// A client's queued output is at most `out_backlog + wire.max_payload`: + /// past the backlog it is closed, and one frame lands on top of it first + /// (a frame bigger than the backlog must still go out whole). fn queue(s: *Session, c: *Client, bytes: []const u8) void { if (c.out.items.len > out_backlog) return s.close(c, .backlog); s.account(); diff --git a/src/dump.zig b/src/dump.zig index 76a6de85..67934e0a 100644 --- a/src/dump.zig +++ b/src/dump.zig @@ -394,17 +394,6 @@ test "oversized recognized output argument is rejected before restore" { ); } -pub fn writeFile(io: std.Io, gpa: std.mem.Allocator, path: []const u8, state: State) !void { - try validate(state); - var out: std.Io.Writer.Allocating = .init(gpa); - defer out.deinit(); - try std.zon.stringify.serialize(state, .{ .whitespace = true }, &out.writer); - - var file = try std.Io.Dir.createFileAbsolute(io, path, .{}); - defer file.close(io); - try file.writeStreamingAll(io, out.written()); -} - pub const Parsed = struct { value: State, arena: std.heap.ArenaAllocator, diff --git a/src/edit.zig b/src/edit.zig index 466b5cdb..55365692 100644 --- a/src/edit.zig +++ b/src/edit.zig @@ -119,7 +119,15 @@ pub fn typeToTty(p: *Pardes, id: usize, pane: *const Pane, text: []const u8) voi for (panes.terminal.encodePaste(pane, cp)) |part| if (part.len > 0) p.emitWrite(id, part); } -pub fn applyPaste(p: *Pardes, bytes: []const u8) void { +pub fn applyPaste(p: *Pardes, whole: []const u8) void { + // Every shell's paste comes through here, bounded: what is past the + // limit is left out, at a character's start, and said. + const limit = @import("memory.zig").limits.max_paste_bytes; + const bytes = if (whole.len > limit) whole[0..modal.graphemeStart(whole, limit)] else whole; + if (whole.len > limit) { + var said: [96]u8 = undefined; + p.setMessage(p.active, std.fmt.bufPrint(&said, "paste cut at its limit, {d} KiB: the rest left out", .{limit / 1024}) catch "paste cut at its limit"); + } // A prompt answering for a header takes the paste, as it takes keys. const asking = if (p.panes[p.active]) |active| active.prompt != .none else false; if (!asking) if (tagline.focusedHeader(p)) |t| { @@ -466,8 +474,10 @@ fn editText(p: *Pardes, t: *Text, lo: i32, hi: i32, col: i32) ?panes.EditText { fn editTextEol(p: *Pardes, t: *Text, b: Bounds) ?panes.EditText { const eb = editText(p, t, b.lo_row, b.hi_row, -1) orelse return null; const r: usize = @intCast(@max(0, b.hi_row - eb.row0)); - if (r + 1 < modal.lineCount(eb.text)) return eb; - if (b.hi_col < @as(i32, @intCast(modal.lineSlice(eb.text, r).len))) return eb; + // A file's own line count and line, from its index. + const lines = if (indexedLine(p, t, eb.text, 0) != null) panes.File.nlines(p.gpa, &t.pane().?.file.?) else modal.lineCount(eb.text); + if (r + 1 < lines) return eb; + if (b.hi_col < @as(i32, @intCast(lineAt(p, t, eb.text, r).line.len))) return eb; return editText(p, t, b.lo_row, b.hi_row + 1, -1); } @@ -476,6 +486,47 @@ pub fn setEditText(p: *Pardes, t: *Text, new: []u8) void { setEditTextEnd(p, t, new, null); } +const LineAt = struct { start: usize, line: []const u8 }; + +/// `text`'s line count: the file's index when `text` is the pane's file. +fn lineCountOf(p: *Pardes, t: *Text, text: []const u8) usize { + if (indexedLine(p, t, text, 0) != null) return panes.File.nlines(p.gpa, &t.pane().?.file.?); + return modal.cursorLineCount(text); +} + +/// The row offset `off` is on: a search of the file's index when `text` is +/// the pane's file, else the newlines before it counted (modal.lineAtOffset). +fn rowOf(p: *Pardes, t: *Text, text: []const u8, off: usize) usize { + if (indexedLine(p, t, text, 0) != null) { + const index = panes.File.lineIndex(p.gpa, &t.pane().?.file.?) catch return modal.lineAtOffset(text, off); + return std.sort.upperBound(usize, index, @min(off, text.len), struct { + fn order(key: usize, item: usize) std.math.Order { + return std.math.order(key, item); + } + }.order) -| 1; + } + return modal.lineAtOffset(text, off); +} + +/// Line `row` of `text` and where it starts: through the file's line index +/// when `text` is the pane's file (a lookup), else counted from the top. +/// Finding line 94000 by counting was most of a keystroke in a 7 MB file. +fn lineAt(p: *Pardes, t: *Text, text: []const u8, row: usize) LineAt { + return indexedLine(p, t, text, row) orelse .{ .start = modal.lineStartOffset(text, row), .line = modal.lineSlice(text, row) }; +} + +/// lineAt's lookup, null when `text` is not the pane's file or `row` is past its last line. +fn indexedLine(p: *Pardes, t: *Text, text: []const u8, row: usize) ?LineAt { + if (t.what != .body) return null; + const pane = t.pane() orelse return null; + const f = if (pane.file) |*f| f else return null; + if (f.content.ptr != text.ptr or f.content.len != text.len) return null; + if (row >= panes.File.nlines(p.gpa, f)) return null; + const start = @min(panes.File.lineStart(p.gpa, f, row), text.len); + const end = std.mem.indexOfScalarPos(u8, text, start, '\n') orelse text.len; + return .{ .start = start, .line = text[start..end] }; +} + /// Where text `s` put in at `c` ends: `g.`'s place after typing it. fn insertedEnd(c: modal.Cursor, s: []const u8) modal.Cursor { const nl = std.mem.lastIndexOfScalar(u8, s, '\n') orelse return .{ .row = c.row, .col = c.col + s.len }; @@ -486,6 +537,13 @@ fn insertedEnd(c: modal.Cursor, s: []const u8) modal.Cursor { /// rows) when the caller knows it, as typing does: then nothing scans the /// whole text to find it. Null, it is found by comparing the texts. pub fn setEditTextEnd(p: *Pardes, t: *Text, new: []u8, known_end: ?modal.Cursor) void { + setEditTextSpan(p, t, new, known_end, null); +} + +/// `setEditTextEnd` with what a file's splice left alone at either end, when +/// the caller knows it (typing): the line index is then not found again by +/// comparing the whole old and new texts, which a keystroke in a 7 MB file did. +fn setEditTextSpan(p: *Pardes, t: *Text, new: []u8, known_end: ?modal.Cursor, span: ?panes.File.Span) void { if (t.what == .tag) { // A tag is edited as it is shown, but only what follows its // prefix is its own: an edit that changed the prefix is refused. @@ -511,16 +569,13 @@ pub fn setEditTextEnd(p: *Pardes, t: *Text, new: []u8, known_end: ?modal.Cursor) const pane = t.pane() orelse return retireEditText(p, new); // what changed ended where the texts agree again from their ends const old: []const u8, const row0: i32 = if (pane.file) |f| .{ f.content, 0 } else if (pane.ovl) |o| .{ o.text, o.row } else .{ "", 0 }; - const end = known_end orelse found: { - // ponytail: O(file), for the edits that do not say where they ended - // (paste, a pipe, s): typing passes its end and never comes here. - const front = std.mem.indexOfDiff(u8, old, new) orelse @min(old.len, new.len); - var back: usize = 0; - while (back < @min(old.len, new.len) - front and old[old.len - 1 - back] == new[new.len - 1 - back]) back += 1; - break :found modal.positionAt(new, new.len - back); - }; + // ponytail: O(file), for the edits that do not say what they changed + // (paste, a pipe, d, s): compared once, block by block, here; the same + // span then spares the line index a second comparison. + const found = span orelse if (known_end == null or pane.file != null) panes.File.spanOf(old, new) else null; + const end = known_end orelse modal.positionAt(new, new.len - found.?.tail); t.last_edit = .{ .row = @as(i32, @intCast(end.row)) + row0, .col = @intCast(end.col) }; - if (pane.file) |*f| return panes.File.setContent(p, f, new); + if (pane.file) |*f| return panes.File.setContentSpan(p, f, new, found); panes.terminal.setEditText(p, pane, new); } @@ -815,8 +870,10 @@ fn insertEdit(p: *Pardes, t: *Text, key: Key) void { const text = eb.text; const c = modal.Cursor{ .row = @intCast(@max(0, t.cur_row - eb.row0)), .col = @intCast(@max(0, t.cur_col)) }; if (key.text.len > 0 and !key.ctrl and !key.alt) { - const new = modal.insertAt(p.gpa, text, c, key.text) catch return; - setEditTextEnd(p, t, new, insertedEnd(c, key.text)); + // insertAt's offset (col clamped to the line), the line found once. + const at = if (indexedLine(p, t, text, c.row)) |l| l.start + @min(c.col, l.line.len) else modal.insertOffset(text, c); + const new = modal.spliceAlloc(p.gpa, text, at, at, key.text) catch return; + setEditTextSpan(p, t, new, insertedEnd(c, key.text), .{ .head = at, .tail = text.len - at }); for (key.text) |ch| { if (ch == '\n') { t.cur_row += 1; @@ -918,7 +975,8 @@ fn insertEdit(p: *Pardes, t: *Text, key: Key) void { }, Key.backspace => { if (t.cur_col > 0) { - const line = modal.lineSlice(text, c.row); + const found = lineAt(p, t, text, c.row); + const line = found.line; var prev = modal.prevGrapheme(line, c.col); // in leading blanks, back to the previous indent stop (helix // dedent): a whole unit when on one, else the part past it @@ -931,8 +989,12 @@ fn insertEdit(p: *Pardes, t: *Text, key: Key) void { prev = c.col; while (drop > 0 and prev > 0 and line[prev - 1] == ' ') : (drop -= 1) prev -= 1; } - const new = modal.deleteSpan(p.gpa, text, .{ .row = c.row, .col = prev }, c) catch return; - setEditTextEnd(p, t, new, .{ .row = c.row, .col = prev }); + // deleteSpan's splice, the line found once. + const s = found.start + @min(prev, line.len); + const e = found.start + @min(c.col, line.len); + const new = if (e > s) modal.spliceAlloc(p.gpa, text, s, e, "") catch return else p.gpa.dupe(u8, text) catch return; + const span: panes.File.Span = if (e > s) .{ .head = s, .tail = text.len - e } else .{ .head = text.len, .tail = 0 }; + setEditTextSpan(p, t, new, .{ .row = c.row, .col = prev }, span); t.cur_col = @intCast(prev); t.cur_pinned = true; t.show(); @@ -1479,26 +1541,33 @@ pub fn normalJoin(p: *Pardes, t: *Text, select_space: bool) void { const text = eb.text; var rs: [Text.max_selections]modal.Selection = undefined; const got = t.ranges(text, eb.row0, &rs); - const nlines = modal.cursorLineCount(text); + // Lines, their count and rows from the file's index when it has one: + // counted from the top, a J in a 7 MB file was 8 ms. + const nlines = lineCountOf(p, t, text); const arena = p.scratch.allocator(); - const chs = arena.alloc(TextChange, nlines) catch return; - var chs_len: usize = 0; + var changes: std.ArrayList(TextChange) = .empty; var next: usize = 0; // lines below this one are joined already for (rs[0..got.n]) |r| { - const span = Text.rangeLineSpan(text, r); + // Text.rangeLineSpan, through rowOf + const lo = @min(r.anchor, r.head); + const hi = @max(r.anchor, r.head); + const span = .{ .start = rowOf(p, t, text, lo), .end = rowOf(p, t, text, if (lo == hi) hi else @max(modal.prevGrapheme(text, hi), lo)) }; var end = span.end; if (span.start == end) end = @min(end + 1, nlines - 1); var l = @max(span.start, next); while (l < end) : (l += 1) { - const from = modal.lineEndOffset(text, l); - var to = if (l + 1 >= nlines) text.len else modal.lineStartOffset(text, l + 1); + const here = lineAt(p, t, text, l); + const from = here.start + here.line.len; + var to = if (l + 1 >= nlines) text.len else lineAt(p, t, text, l + 1).start; while (to < text.len and (text[to] == ' ' or text[to] == '\t')) to += 1; - const sep: []const u8 = if (to == modal.lineEndOffset(text, @min(l + 1, nlines - 1))) "" else " "; - chs[chs_len] = .{ .from = from, .to = to, .ins = sep }; - chs_len += 1; + const last = lineAt(p, t, text, @min(l + 1, nlines - 1)); + const sep: []const u8 = if (to == last.start + last.line.len) "" else " "; + changes.append(arena, .{ .from = from, .to = to, .ins = sep }) catch return; } next = @max(next, end); } + const chs = changes.items; + const chs_len = chs.len; if (chs_len == 0) return; pushUndo(p, t); const new = applyChanges(p, text, chs[0..chs_len]) catch return; @@ -2459,3 +2528,72 @@ test "a paste into a terminal is xterm's: bracketed when the program asked, cont p.update(.{ .paste = "x\x1b[201~y\n" }); try std.testing.expectEqualStrings("\x1b[200~x [201~y\n\x1b[201~", try take(p, &out)); } + +test "a paste past the limit is cut at it, and says so" { + const gpa = std.testing.allocator; + const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24 }); + defer p.deinit(); + const pane = try p.setTestFile(""); + pane.body.mode = .insert; + const limit = @import("memory.zig").limits.max_paste_bytes; + const big = try gpa.alloc(u8, limit + 100); + defer gpa.free(big); + @memset(big, 'x'); + applyPaste(p, big); + try std.testing.expect(pane.file.?.content.len <= limit); + try std.testing.expect(pane.file.?.content.len > 0); + try std.testing.expect(std.mem.indexOf(u8, pane.msg[0..pane.msg_len], "paste cut") != null); +} + +test "typing and backspace through the line index keep the text and the index as a rebuild has them" { + const gpa = std.testing.allocator; + const p = try Pardes.init(gpa, .{ .tty_only = true }); + defer p.deinit(); + while (p.nextEffect()) |_| {} + const pane = try p.setTestFile("one\n two\n\nthree four\n"); + pane.body.mode = .insert; + var prng: std.Random.DefaultPrng = .init(11); + const random = prng.random(); + for (0..300) |_| { + _ = panes.File.lineIndex(gpa, &pane.file.?) catch unreachable; + const f = &pane.file.?; + const row = random.uintLessThan(usize, panes.File.nlines(gpa, f)); + const line = modal.lineSlice(f.content, row); + pane.body.cur_row = @intCast(row); + pane.body.cur_col = @intCast(random.uintLessThan(usize, line.len + 1)); + pane.body.cur_pinned = true; + if (random.boolean()) { + insertKey(p, &pane.body, .{ .cp = 'x', .text = "x" }); + } else { + insertKey(p, &pane.body, .{ .cp = Key.backspace }); + } + // the index the edits kept, against one built from the text + const kept = try gpa.dupe(usize, try panes.File.lineIndex(gpa, &pane.file.?)); + defer gpa.free(kept); + gpa.free(pane.file.?.line_starts); + pane.file.?.line_starts = &.{}; + try std.testing.expectEqualSlices(usize, try panes.File.lineIndex(gpa, &pane.file.?), kept); + } +} + +test "J joins a line with the next, its indent dropped, a space between unless the next is empty" { + const gpa = std.testing.allocator; + const cases = [_]struct { text: []const u8, row: i32, rows: i32 = 0, want: []const u8 }{ + .{ .text = "a\n b\nc\n", .row = 0, .want = "a b\nc\n" }, + .{ .text = "a\n\nc\n", .row = 0, .want = "a\nc\n" }, + .{ .text = "a\nb", .row = 1, .want = "a\nb" }, + .{ .text = "one\n\ttwo\nthree\nfour\n", .row = 0, .rows = 2, .want = "one two three\nfour\n" }, + }; + for (cases) |case| { + const p = try Pardes.init(gpa, .{ .tty_only = true }); + defer p.deinit(); + while (p.nextEffect()) |_| {} + const pane = try p.setTestFile(case.text); + pane.body.mode = .normal; + pane.body.cur_row = case.row; + pane.body.cur_col = 0; + if (case.rows > 0) pane.body.vsel = .{ .active = true, .row = case.row + case.rows, .col = 0, .explicit = true }; + normalJoin(p, &pane.body, false); + try std.testing.expectEqualStrings(case.want, pane.file.?.content); + } +} diff --git a/src/exec.zig b/src/exec.zig index d03a4a48..c9f304b0 100644 --- a/src/exec.zig +++ b/src/exec.zig @@ -913,6 +913,12 @@ pub fn commandDone(p: *Pardes, id: usize, status: ?u8) void { pane.repl = null; pane.command_status = status; pane.body.mode = .normal; + // Look's `git show`: its output went to a +Pager, the +Diff now; only a + // failure is worth the pane. + if (pane.command_pages) { + pane.command_pages = false; + if (status == 0) return p.removePane(id, null) catch {}; + } var buf: [16]u8 = undefined; const code = if (status) |n| std.fmt.bufPrint(&buf, "{d}", .{n}) catch "?" else "?"; var said: [32]u8 = undefined; diff --git a/src/fs.zig b/src/fs.zig index 061d4225..032ab9c0 100644 --- a/src/fs.zig +++ b/src/fs.zig @@ -1087,17 +1087,17 @@ pub const platform_has_fs = !pardes.isolated and switch (pardes.platform) { const find_max_hits = 512; /// What a Find or Grep walk passed over, said under its hits: directories -/// it might not open, files read only in part, and caps it stopped at. +/// it might not open, and caps it stopped at. pub const WalkNotes = struct { skipped: usize = 0, - /// Files longer than grep_max_bytes, searched in their first part only. - partial: usize = 0, hits_cut: bool = false, + /// A pane search's matching lines it stopped at, its rows filling + /// look.search_text_output_bytes; 0 if none. + rows_cut: usize = 0, /// The cap on entries walked it stopped at, 0 if none. walk_cut: usize = 0, pub const max_hits = find_max_hits; - pub const max_file_bytes = grep_max_bytes; pub const max_files = grep_max_files; pub const max_depth = find_max_depth; @@ -1105,7 +1105,7 @@ pub const WalkNotes = struct { pub fn write(n: WalkNotes, out: []u8) usize { var w = std.Io.Writer.fixed(out); if (n.hits_cut) w.print("cut at {d} hits\n", .{max_hits}) catch {}; - if (n.partial > 0) w.print("{d} file{s} read only in part (first {d} KiB)\n", .{ n.partial, if (n.partial == 1) "" else "s", max_file_bytes / 1024 }) catch {}; + if (n.rows_cut > 0) w.print("cut at {d} lines\n", .{n.rows_cut}) catch {}; if (n.walk_cut > 0) w.print("walk cut at {d} entries\n", .{n.walk_cut}) catch {}; if (n.skipped > 0) w.print("{d} director{s} skipped: permission denied\n", .{ n.skipped, if (n.skipped == 1) "y" else "ies" }) catch {}; return w.buffered().len; @@ -1124,7 +1124,8 @@ pub const WalkNotes = struct { }; const find_max_depth = 16; const find_max_steps = 100_000; -pub const search_max_output_bytes = pardes.MAX_PANES * find_max_hits * (4096 + 320); +/// One root's Find or Grep rows at most: its hits, each a path and a line. +pub const search_root_output_bytes = find_max_hits * (4096 + 320); const find_skip = [_][]const u8{ ".git", ".jj", "target", "node_modules", @@ -1194,9 +1195,10 @@ const grep_max_files = 20_000; const GrepResult = struct { bytes: usize, hits: usize }; -fn grepText(path: []const u8, text: []const u8, pat: []const u8, out: []u8, budget: usize) GrepResult { +/// `text` starts at line `first_line` + 1 of its file. +fn grepText(path: []const u8, text: []const u8, pat: []const u8, out: []u8, budget: usize, first_line: usize) GrepResult { var result: GrepResult = .{ .bytes = 0, .hits = 0 }; - var line: usize = 0; + var line: usize = first_line; var it = std.mem.splitScalar(u8, text, '\n'); while (it.next()) |raw| { line += 1; @@ -1220,7 +1222,7 @@ pub fn grep(arena: std.mem.Allocator, gpa: std.mem.Allocator, dir: []const u8, b if (!platform_has_fs) { for (sources) |s| { if (hits >= find_max_hits or written == out.len) break; - const result = grepText(s.path, s.contents, pat, out[written..], find_max_hits - hits); + const result = grepText(s.path, s.contents, pat, out[written..], find_max_hits - hits, 0); hits += result.hits; written += result.bytes; } @@ -1276,30 +1278,39 @@ pub fn grep(arena: std.mem.Allocator, gpa: std.mem.Allocator, dir: []const u8, b const path_z = std.fmt.bufPrintSentinel(&pathbuf, "{s}", .{path}, 0) catch return error.PathTooLong; const fd = libc.open(path_z, .{ .ACCMODE = .RDONLY, .CLOEXEC = true, .NONBLOCK = true }); if (fd < 0) continue; + defer _ = libc.close(fd); + // The whole file, a buffer at a time: each searched through its last + // whole line, the rest carried into the next. + const shown = lsp.rel(home, path); var len: usize = 0; - var readable = true; - while (len < buf.len) { - const n = libc.read(fd, buf[len..].ptr, buf.len - len); - if (n < 0) { - if (libc.errno(n) == .INTR) continue; - readable = false; - break; + var lines_before: usize = 0; + var first = true; + file: while (true) { + var eof = false; + while (len < buf.len) { + const n = libc.read(fd, buf[len..].ptr, buf.len - len); + if (n < 0) { + if (libc.errno(n) == .INTR) continue; + break :file; + } + if (n == 0) { + eof = true; + break; + } + len += @intCast(n); } - if (n == 0) break; - len += @intCast(n); + if (first and std.mem.indexOfScalar(u8, buf[0..@min(len, 1024)], 0) != null) break; + first = false; + // A line longer than the buffer is searched in buffer-sized parts. + const end = if (eof) len else if (std.mem.lastIndexOfScalar(u8, buf[0..len], '\n')) |nl| nl + 1 else len; + const result = grepText(shown, buf[0..end], pat, out[written..], find_max_hits - hits, lines_before); + hits += result.hits; + written += result.bytes; + if (eof or hits >= find_max_hits or written == out.len) break; + lines_before += std.mem.count(u8, buf[0..end], "\n"); + std.mem.copyForwards(u8, buf[0 .. len - end], buf[end..len]); + len -= end; } - // Read to its cap with more behind it: searched in part, and said. - var more: [1]u8 = undefined; - const longer = readable and len == buf.len and libc.read(fd, &more, 1) > 0; - _ = libc.close(fd); - if (!readable) continue; - const text = buf[0..len]; - if (std.mem.indexOfScalar(u8, text[0..@min(len, 1024)], 0) != null) continue; - if (longer) notes.partial += 1; - const shown = lsp.rel(home, path); - const result = grepText(shown, text, pat, out[written..], find_max_hits - hits); - hits += result.hits; - written += result.bytes; if (hits >= find_max_hits) notes.hits_cut = true; } return written; @@ -1366,14 +1377,14 @@ test "a directory the walk may not open is skipped and counted: Grep and Find ke try std.testing.expectEqual(@as(usize, 1), notes.skipped); } -test "Grep says when a cap hid what it might have found: a file read in part, the hits cut" { +test "Grep reads a long file to its end, and says when its hits were cut" { if (!platform_has_fs) return; const gpa = std.testing.allocator; var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); var base_buf: [std.fs.max_path_bytes]u8 = undefined; const dir = base_buf[0..try tmp.dir.realPath(std.testing.io, &base_buf)]; - // The match past the first 256 KiB of a long file. + // A match past the first buffer of a long file, on its own line number. const long = try gpa.alloc(u8, grep_max_bytes + 64); defer gpa.free(long); @memset(long, 'x'); @@ -1386,8 +1397,9 @@ test "Grep says when a cap hid what it might have found: a file read in part, th defer gpa.free(out); var notes: WalkNotes = .{}; var n = try grep(arena.allocator(), gpa, dir, dir, "needle", out, ¬es); - try std.testing.expectEqual(@as(usize, 0), n); - try std.testing.expectEqual(@as(usize, 1), notes.partial); + var want_buf: [64]u8 = undefined; + const want = try std.fmt.bufPrint(&want_buf, "long.txt:{d}:", .{std.mem.count(u8, long, "\n")}); + try std.testing.expect(std.mem.startsWith(u8, out[0..n], want)); // More hits than the cap. var many: std.ArrayList(u8) = .empty; defer many.deinit(gpa); @@ -1398,7 +1410,7 @@ test "Grep says when a cap hid what it might have found: a file read in part, th try std.testing.expect(notes.hits_cut); var said: [256]u8 = undefined; const lines = said[0..notes.write(&said)]; - try std.testing.expectEqualStrings("cut at 512 hits\n1 file read only in part (first 256 KiB)\n", lines); + try std.testing.expectEqualStrings("cut at 512 hits\n", lines); try std.testing.expect(WalkNotes.isNote("cut at 512 hits") and WalkNotes.isNote("2 directories skipped: permission denied") and !WalkNotes.isNote("src/2 directories.txt")); } diff --git a/src/gui/gui.zig b/src/gui/gui.zig index f9921111..9cd37b6b 100644 --- a/src/gui/gui.zig +++ b/src/gui/gui.zig @@ -828,18 +828,13 @@ fn emitTouchClick(t: *Touch, in: *Input, point: TouchNormPoint, button: pardes.M in.post(.{ .mouse = .{ .button = button, .kind = .release, .col = cell.col, .row = cell.row, .tag_hit = cell.tag_hit, .body_hit = cell.body_hit } }); } -fn normCell(norm: f32, win: f32, cell: f32) u16 { - const px = std.math.clamp(norm, 0.0, 1.0) * win; - return @intFromFloat(@max(0, @floor(px / cell))); -} - const Pty = struct { fd: c_int, pid: libc.pid_t, serial: u32, kill_at: i64 = 0, - reader: ?std.Thread = null, - stop: [2]c_int = .{ -1, -1 }, + /// Its reader, blocked in an Io read: `closePty` cancels it. + reader: ?std.Io.Future(void) = null, /// A command pane's child, watched to its exit (host_io.watchExit); /// the pty stays open until both its end of file and its exit. cmd: host_io.CommandWatch = .{}, @@ -876,31 +871,6 @@ const Msg = union(enum) { } }; -const LspWorkers = struct { - const capacity = 16; - active: std.atomic.Value(usize) = .init(0), - - fn start(workers: *LspWorkers) bool { - var count = workers.active.load(.monotonic); - while (count < capacity) - count = workers.active.cmpxchgWeak(count, count + 1, .monotonic, .monotonic) orelse return true; - return false; - } - - fn finish(workers: *LspWorkers) void { - const previous = workers.active.fetchSub(1, .release); - std.debug.assert(previous > 0); - } - - fn wait(workers: *LspWorkers) void { - var spins: u8 = 0; - while (workers.active.load(.acquire) != 0) { - spins +%= 1; - if (spins == 0) std.Thread.yield() catch {} else std.atomic.spinLoopHint(); - } - } -}; - const PipeTasks = selection_pipe.Tasks; const queue_capacity = 512; @@ -918,10 +888,13 @@ const MessageBatch = struct { const Queue = struct { gpa: std.mem.Allocator, lsp_allocator: std.mem.Allocator, - lsp_workers: *LspWorkers, + /// The query in flight; the UI thread's alone (spawnLsp, teardown). + lsp_task: ?host_io.Lsp.Task = null, sdl_wake: bool, // wake a blocking SDL_WaitEventTimeout on cross-thread push - mutex: libc.pthread_mutex_t = .{}, - space: libc.pthread_cond_t = .{}, + /// The process's Io: its terminal readers wait for space on `space`. + io: std.Io, + mutex: std.Io.Mutex = .init, + space: std.Io.Condition = .init, items: [queue_capacity]Msg = undefined, head: usize = 0, len: usize = 0, @@ -934,13 +907,11 @@ const Queue = struct { completion_len: usize = 0, fn lock(q: *Queue) void { - // unreachable failures: pthread calls on this queue's own initialised, non-recursive - // mutex and condition fail only on misuse (EINVAL, EDEADLK), never on input. - std.debug.assert(libc.pthread_mutex_lock(&q.mutex) == .SUCCESS); + q.mutex.lockUncancelable(q.io); } fn unlock(q: *Queue) void { - std.debug.assert(libc.pthread_mutex_unlock(&q.mutex) == .SUCCESS); + q.mutex.unlock(q.io); } fn wake(q: *Queue) void { @@ -973,14 +944,14 @@ const Queue = struct { }; if (matches) q.removeAt(i).deinit(q.gpa, q.lsp_allocator) else i += 1; } - std.debug.assert(libc.pthread_cond_broadcast(&q.space) == .SUCCESS); + q.space.broadcast(q.io); } fn pushOutput(q: *Queue, pane: u8, gen: u32, bytes: []u8) bool { q.lock(); while (!q.closed and q.readers[pane] == gen and q.len >= output_capacity) { q.waiting += 1; - std.debug.assert(libc.pthread_cond_wait(&q.space, &q.mutex) == .SUCCESS); + q.space.waitUncancelable(q.io, &q.mutex); q.waiting -= 1; } if (q.closed or q.readers[pane] != gen) { @@ -1088,7 +1059,7 @@ const Queue = struct { @memcpy(batch.items[batch.len..][0..q.completion_len], q.completions[0..q.completion_len]); batch.len += q.completion_len; q.completion_len = 0; - std.debug.assert(libc.pthread_cond_broadcast(&q.space) == .SUCCESS); + q.space.broadcast(q.io); } fn discardCompletions(q: *Queue) void { @@ -1104,7 +1075,7 @@ const Queue = struct { q.closed = true; q.files_changed = false; q.readers = @splat(null); - std.debug.assert(libc.pthread_cond_broadcast(&q.space) == .SUCCESS); + q.space.broadcast(q.io); q.unlock(); q.discardCompletions(); q.lock(); @@ -1121,15 +1092,12 @@ const Queue = struct { fn deinit(q: *Queue) void { q.close(); std.debug.assert(q.waiting == 0); - std.debug.assert(libc.pthread_cond_destroy(&q.space) == .SUCCESS); - std.debug.assert(libc.pthread_mutex_destroy(&q.mutex) == .SUCCESS); } }; test "GUI completion survives a full output queue" { const gpa = std.testing.allocator; - var workers: LspWorkers = .{}; - var queue: Queue = .{ .gpa = gpa, .lsp_allocator = gpa, .lsp_workers = &workers, .sdl_wake = false, .lsp_id = 7 }; + var queue: Queue = .{ .io = std.testing.io, .gpa = gpa, .lsp_allocator = gpa, .sdl_wake = false, .lsp_id = 7 }; defer queue.deinit(); queue.acceptReader(0, 1); for (0..output_capacity) |_| queue.push(.{ .output = .{ @@ -1185,8 +1153,7 @@ const PtyTests = struct { test "GUI PTY backpressure retains byte order and tail before EOF" { const gpa = std.testing.allocator; - var workers: LspWorkers = .{}; - var queue: Queue = .{ .gpa = gpa, .lsp_allocator = gpa, .lsp_workers = &workers, .sdl_wake = false }; + var queue: Queue = .{ .io = std.testing.io, .gpa = gpa, .lsp_allocator = gpa, .sdl_wake = false }; defer queue.deinit(); queue.acceptReader(0, 1); for (0..output_capacity) |_| queue.push(.{ .output = .{ .pane = 0, .gen = 1, .bytes = try gpa.dupe(u8, "before") } }); @@ -1220,8 +1187,7 @@ test "GUI PTY backpressure retains byte order and tail before EOF" { test "GUI PTY backpressure cancellation and close release owned producers" { const gpa = std.testing.allocator; for ([_]bool{ false, true }) |close| { - var workers: LspWorkers = .{}; - var queue: Queue = .{ .gpa = gpa, .lsp_allocator = gpa, .lsp_workers = &workers, .sdl_wake = false }; + var queue: Queue = .{ .io = std.testing.io, .gpa = gpa, .lsp_allocator = gpa, .sdl_wake = false }; defer queue.deinit(); queue.acceptReader(0, 1); for (0..output_capacity) |_| queue.push(.{ .output = .{ .pane = 0, .gen = 1, .bytes = try gpa.dupe(u8, "before") } }); @@ -1252,8 +1218,7 @@ test "GUI PTY backpressure cancellation and close release owned producers" { test "GUI PTY EOF reserve cannot evict terminal output" { const gpa = std.testing.allocator; - var workers: LspWorkers = .{}; - var queue: Queue = .{ .gpa = gpa, .lsp_allocator = gpa, .lsp_workers = &workers, .sdl_wake = false }; + var queue: Queue = .{ .io = std.testing.io, .gpa = gpa, .lsp_allocator = gpa, .sdl_wake = false }; defer queue.deinit(); for (0..pardes.MAX_PANES) |pane| queue.acceptReader(@intCast(pane), 1); for (0..output_capacity) |_| queue.push(.{ .output = .{ .pane = 0, .gen = 1, .bytes = try gpa.dupe(u8, "before") } }); @@ -1269,8 +1234,7 @@ test "GUI PTY reader delivers a real shell tail before EOF and joins on close" { const gpa = std.testing.allocator; const core = try pardes.Pardes.init(gpa, .{ .tty_only = true }); defer core.deinit(); - var workers: LspWorkers = .{}; - var queue: Queue = .{ .gpa = gpa, .lsp_allocator = gpa, .lsp_workers = &workers, .sdl_wake = false }; + var queue: Queue = .{ .io = std.testing.io, .gpa = gpa, .lsp_allocator = gpa, .sdl_wake = false }; defer queue.deinit(); var ptys: [pardes.MAX_PANES]?Pty = @splat(null); var gens: [pardes.MAX_PANES]u32 = @splat(1); @@ -1320,8 +1284,7 @@ test "GUI PTY Restore joins a real reader waiting for queue space" { var core = try pardes.Pardes.init(gpa, .{ .tty_only = true }); defer core.deinit(); try dump.dumpState(core); - var workers: LspWorkers = .{}; - var queue: Queue = .{ .gpa = gpa, .lsp_allocator = gpa, .lsp_workers = &workers, .sdl_wake = false }; + var queue: Queue = .{ .io = std.testing.io, .gpa = gpa, .lsp_allocator = gpa, .sdl_wake = false }; defer queue.deinit(); queue.acceptReader(1, 1); for (0..output_capacity) |_| queue.push(.{ .output = .{ .pane = 1, .gen = 1, .bytes = try gpa.dupe(u8, "other pane") } }); @@ -1365,8 +1328,7 @@ test "GUI PTY deletion joins an idle reader and retains only its owned child for const gpa = std.testing.allocator; const core = try pardes.Pardes.init(gpa, .{ .tty_only = true }); defer core.deinit(); - var workers: LspWorkers = .{}; - var queue: Queue = .{ .gpa = gpa, .lsp_allocator = gpa, .lsp_workers = &workers, .sdl_wake = false }; + var queue: Queue = .{ .io = std.testing.io, .gpa = gpa, .lsp_allocator = gpa, .sdl_wake = false }; defer queue.deinit(); var ptys: [pardes.MAX_PANES]?Pty = @splat(null); var gens: [pardes.MAX_PANES]u32 = @splat(1); @@ -1397,8 +1359,7 @@ test "GUI PTY deletion joins an idle reader and retains only its owned child for test "GUI PTY file watcher stops and joins without closing its watched descriptor" { if (!file_watch.supported) return error.SkipZigTest; const gpa = std.testing.allocator; - var workers: LspWorkers = .{}; - var queue: Queue = .{ .gpa = gpa, .lsp_allocator = gpa, .lsp_workers = &workers, .sdl_wake = false }; + var queue: Queue = .{ .io = std.testing.io, .gpa = gpa, .lsp_allocator = gpa, .sdl_wake = false }; defer queue.deinit(); const fd = file_watch.init(true); if (fd < 0) return error.WatchInitFailed; @@ -1422,8 +1383,7 @@ test "GUI completion failure survives backlog and leaves the document unchanged" pane.body.cur_col = 1; core.lspRequest(core.active, .completion, ""); const id = core.lsp_wait.?.id; - var workers: LspWorkers = .{}; - var queue: Queue = .{ .gpa = gpa, .lsp_allocator = gpa, .lsp_workers = &workers, .sdl_wake = false, .lsp_id = id }; + var queue: Queue = .{ .io = std.testing.io, .gpa = gpa, .lsp_allocator = gpa, .sdl_wake = false, .lsp_id = id }; defer queue.deinit(); queue.acceptReader(0, 1); for (0..output_capacity) |_| queue.push(.{ .output = .{ @@ -1452,8 +1412,7 @@ test "GUI completion failure survives backlog and leaves the document unchanged" test "GUI completions retain their arrival order across LSP and pipes" { const gpa = std.testing.allocator; - var workers: LspWorkers = .{}; - var queue: Queue = .{ .gpa = gpa, .lsp_allocator = gpa, .lsp_workers = &workers, .sdl_wake = false, .lsp_id = 2 }; + var queue: Queue = .{ .io = std.testing.io, .gpa = gpa, .lsp_allocator = gpa, .sdl_wake = false, .lsp_id = 2 }; defer queue.deinit(); queue.push(.{ .pipe = .{ .id = 1, .success = true, .outputs = &.{} } }); queue.push(.{ .lsp = .{ .id = 2, .rows = try gpa.dupe(u8, "second") } }); @@ -1469,8 +1428,7 @@ test "GUI completions retain their arrival order across LSP and pipes" { test "GUI completion reset frees queued payloads and rejects late LSP workers" { const gpa = std.testing.allocator; - var workers: LspWorkers = .{}; - var queue: Queue = .{ .gpa = gpa, .lsp_allocator = gpa, .lsp_workers = &workers, .sdl_wake = false, .lsp_id = 9 }; + var queue: Queue = .{ .io = std.testing.io, .gpa = gpa, .lsp_allocator = gpa, .sdl_wake = false, .lsp_id = 9 }; defer queue.deinit(); queue.acceptReader(0, 1); queue.push(.{ .output = .{ .pane = 0, .gen = 1, .bytes = try gpa.dupe(u8, "retained") } }); @@ -1523,29 +1481,22 @@ fn lspStatusSink(ctx: ?*anyopaque, text: []const u8) void { q.push(.{ .lsp_status = copy }); } -fn readPtyThread(gpa: std.mem.Allocator, fd: c_int, stop: c_int, pane: u8, gen: u32, q: *Queue) void { +fn readPty(io: std.Io, gpa: std.mem.Allocator, fd: c_int, pane: u8, gen: u32, q: *Queue) void { + const pty: std.Io.File = .{ .handle = fd, .flags = .{ .nonblocking = false } }; var buf: [0x10000]u8 = undefined; var failure: ?anyerror = null; while (true) { - var fds = [_]libc.pollfd{ - .{ .fd = stop, .events = libc.POLL.IN, .revents = 0 }, - .{ .fd = fd, .events = libc.POLL.IN, .revents = 0 }, + const n = pty.readStreaming(io, &.{&buf}) catch |err| switch (err) { + // A pty whose child has gone answers EIO: its end of file. + error.EndOfStream, error.InputOutput => break, + error.Canceled => return, + else => { + failure = err; + break; + }, }; - if (libc.poll(&fds, fds.len, -1) < 0) { - if (libc.errno(-1) == .INTR) continue; - failure = error.PollFailed; - break; - } - if (fds[0].revents != 0) return; - if (fds[1].revents == 0) continue; - const n = libc.read(fd, &buf, buf.len); - if (n < 0) { - if (libc.errno(n) == .INTR) continue; - if (libc.errno(n) != .IO) failure = error.ReadFailed; - break; - } - if (n == 0) break; - const bytes = gpa.dupe(u8, buf[0..@intCast(n)]) catch |err| { + if (n == 0) continue; + const bytes = gpa.dupe(u8, buf[0..n]) catch |err| { failure = err; break; }; @@ -1566,14 +1517,9 @@ fn stopPipe() ![2]c_int { fn spawnReader(gpa: std.mem.Allocator, pt: *Pty, pane: u8, gen: u32, q: *Queue) !void { std.debug.assert(pt.reader == null and pt.fd >= 0); - const stop = try stopPipe(); - errdefer for (stop) |fd| { - _ = libc.close(fd); - }; q.acceptReader(pane, gen); errdefer q.cancelReader(pane, gen); - pt.reader = try std.Thread.spawn(.{}, readPtyThread, .{ gpa, pt.fd, stop[0], pane, gen, q }); - pt.stop = stop; + pt.reader = try q.io.concurrent(readPty, .{ q.io, gpa, pt.fd, pane, gen, q }); } fn watchThread(fd: c_int, stop: c_int, q: *Queue) void { @@ -1592,9 +1538,8 @@ fn watchThread(fd: c_int, stop: c_int, q: *Queue) void { } } -fn lspThread(lsp_allocator: std.mem.Allocator, workers: *LspWorkers, job: *host_io.Lsp.Job, q: *Queue) void { - defer workers.finish(); - host_io.Lsp.work(lsp_allocator, job, q, pushLspRows); +fn lspThread(io: std.Io, lsp_allocator: std.mem.Allocator, job: *host_io.Lsp.Job, q: *Queue) anyerror!void { + host_io.Lsp.work(io, lsp_allocator, job, q, pushLspRows); } fn pushLspRows(ctx: ?*anyopaque, id: u32, rows: ?[]u8) void { @@ -1602,107 +1547,52 @@ fn pushLspRows(ctx: ?*anyopaque, id: u32, rows: ?[]u8) void { q.push(.{ .lsp = .{ .id = id, .rows = rows } }); } -fn spawnLsp(core: *pardes.Pardes, q: *Queue, e: host_io.Lsp.Request) void { +fn spawnLsp(core: *pardes.Pardes, io: std.Io, q: *Queue, e: host_io.Lsp.Request) void { const lsp_allocator = q.lsp_allocator; q.lock(); q.lsp_id = e.id; q.discardLsp(); q.unlock(); - if (!q.lsp_workers.start()) { - core.update(.{ .lsp_resp = .{ .id = e.id, .rows = null } }); - return core.reportError(e.pane, "lsp", error.WorkersBusy); + // Its waits are cancelation points: this join is short, and what it + // still delivers carries an id the queue now rejects. + if (q.lsp_task) |*old| { + old.future.cancel(io) catch {}; + q.lsp_task = null; } const job = host_io.Lsp.snapshot(lsp_allocator, core, e) catch |err| { - q.lsp_workers.finish(); core.update(.{ .lsp_resp = .{ .id = e.id, .rows = null } }); return core.reportError(e.pane, "lsp", err); }; - const th = std.Thread.spawn(.{}, lspThread, .{ lsp_allocator, q.lsp_workers, job, q }) catch |err| { - q.lsp_workers.finish(); + const future = io.concurrent(lspThread, .{ io, lsp_allocator, job, q }) catch |err| { job.free(lsp_allocator); core.update(.{ .lsp_resp = .{ .id = e.id, .rows = null } }); return core.reportError(e.pane, "lsp", err); }; - th.detach(); + q.lsp_task = .{ .id = e.id, .future = future }; } -test "GUI LSP worker limit rejects before allocation and recovers after owned workers exit" { +test "GUI LSP query answers, and a newer one cancels it" { const gpa = std.testing.allocator; + const io = std.testing.io; const core = try pardes.Pardes.init(gpa, .{ .tty_only = true }); defer core.deinit(); - const pane = try core.setTestFile("abc"); - pane.body.cur_col = 1; - var workers: LspWorkers = .{}; - var gate: std.Io.Event = .unset; - var threads: [LspWorkers.capacity]?std.Thread = @splat(null); - defer { - gate.set(std.testing.io); - for (threads) |thread| if (thread) |owned| owned.join(); - workers.wait(); - } - for (&threads) |*thread| { - try std.testing.expect(workers.start()); - thread.* = std.Thread.spawn(.{}, struct { - fn run(active: *LspWorkers, ready: *std.Io.Event) void { - defer active.finish(); - ready.waitUncancelable(std.testing.io); - } - }.run, .{ &workers, &gate }) catch |err| { - workers.finish(); - return err; - }; - } - try std.testing.expectEqual(@as(usize, LspWorkers.capacity), workers.active.load(.monotonic)); - try std.testing.expect(!workers.start()); - var failing = std.testing.FailingAllocator.init(gpa, .{ .fail_index = 0 }); - var queue: Queue = .{ .gpa = gpa, .lsp_allocator = failing.allocator(), .lsp_workers = &workers, .sdl_wake = false }; + _ = try core.setTestFile("abc"); + var queue: Queue = .{ .io = std.testing.io, .gpa = gpa, .lsp_allocator = gpa, .sdl_wake = false }; defer queue.deinit(); - core.lspRequest(core.active, .completion, ""); - const rejected = core.lsp_wait.?.id; - queue.lsp_id = rejected -% 1; - queue.push(.{ .lsp = .{ .id = queue.lsp_id.?, .rows = try gpa.dupe(u8, "obsolete queued result") } }); - spawnLsp(core, &queue, .{ - .id = rejected, - .kind = .completion, - .pane = @intCast(core.active), - .offset = 1, - .arg = "", - }); - try std.testing.expect(core.lsp_wait == null); - try std.testing.expectEqualStrings("abc", pane.file.?.content); - try std.testing.expectEqual(@as(i32, 1), pane.body.cur_col); - try std.testing.expect(std.mem.indexOf(u8, pane.msg[0..pane.msg_len], "workers busy") != null); - try std.testing.expectEqual(@as(usize, 0), failing.alloc_index); - try std.testing.expect(!failing.has_induced_failure); - try std.testing.expectEqual(rejected, queue.lsp_id.?); - try std.testing.expectEqual(@as(usize, 0), queue.completion_len); - queue.push(.{ .lsp = .{ .id = rejected -% 1, .rows = try gpa.dupe(u8, "obsolete late result") } }); - try std.testing.expectEqual(@as(usize, 0), queue.completion_len); - try std.testing.expectEqual(@as(usize, LspWorkers.capacity), workers.active.load(.monotonic)); - - gate.set(std.testing.io); - workers.wait(); - try std.testing.expectEqual(@as(usize, 0), workers.active.load(.monotonic)); - queue.lsp_allocator = gpa; - core.lspRequest(core.active, .status, ""); - const accepted = core.lsp_wait.?.id; - spawnLsp(core, &queue, .{ - .id = accepted, - .kind = .status, - .pane = @intCast(core.active), - .offset = 0, - .arg = "", - }); - workers.wait(); + for (0..2) |_| { + core.lspRequest(core.active, .status, ""); + spawnLsp(core, io, &queue, .{ .id = core.lsp_wait.?.id, .kind = .status, .pane = @intCast(core.active), .offset = 0, .arg = "" }); + } + const last = core.lsp_wait.?.id; + try queue.lsp_task.?.future.await(io); + queue.lsp_task = null; var batch = queue.take(); defer for (batch.slice()) |msg| msg.deinit(gpa, gpa); try std.testing.expectEqual(@as(usize, 1), batch.len); - try std.testing.expectEqual(accepted, batch.items[0].lsp.id); + try std.testing.expectEqual(last, batch.items[0].lsp.id); try std.testing.expect(batch.items[0].lsp.rows != null); - core.update(.{ .lsp_resp = .{ .id = accepted, .rows = batch.items[0].lsp.rows } }); + core.update(.{ .lsp_resp = .{ .id = last, .rows = batch.items[0].lsp.rows } }); try std.testing.expect(core.lsp_wait == null); - try std.testing.expectEqual(@as(usize, 0), workers.active.load(.monotonic)); - try std.testing.expectEqualStrings("abc", pane.file.?.content); } fn pipeThread(io: std.Io, gpa: std.mem.Allocator, job: *selection_pipe.Job, q: *Queue) anyerror!void { @@ -1748,11 +1638,10 @@ test "GUI worker setup failures finish matching LSP and pipe requests" { var failing = std.testing.FailingAllocator.init(gpa, .{ .fail_index = if (failure == 0) 0 else std.math.maxInt(usize), }); - var workers: LspWorkers = .{}; var queue: Queue = .{ + .io = std.testing.io, .gpa = gpa, .lsp_allocator = failing.allocator(), - .lsp_workers = &workers, .sdl_wake = false, }; defer queue.deinit(); @@ -1768,7 +1657,7 @@ test "GUI worker setup failures finish matching LSP and pipe requests" { if (failure == 0) { queue.lsp_id = req.id -% 1; queue.push(.{ .lsp = .{ .id = queue.lsp_id.?, .rows = try gpa.dupe(u8, "old queued result") } }); - spawnLsp(core, &queue, req); + spawnLsp(core, std.testing.io, &queue, req); try std.testing.expectEqual(req.id, queue.lsp_id.?); try std.testing.expectEqual(@as(usize, 0), queue.completion_len); queue.push(.{ .lsp = .{ .id = req.id -% 1, .rows = try gpa.dupe(u8, "late old result") } }); @@ -1791,7 +1680,7 @@ test "GUI worker setup failures finish matching LSP and pipe requests" { spawnPipe(core, failing_io, failing.allocator(), &queue, &tasks, pipe_id); try std.testing.expect(core.pipe.wait == null); try std.testing.expectEqualStrings("abc", pane.file.?.content); - try std.testing.expectEqual(@as(usize, 0), workers.active.load(.monotonic)); + try std.testing.expect(queue.lsp_task == null); try std.testing.expectEqual(@as(usize, 0), tasks.len); try std.testing.expectEqual(@as(usize, 0), queue.len); } @@ -2071,22 +1960,6 @@ fn fixedCellLayout(g: *const Gui) CellLayout { return .{ .w = @floatFromInt(g.cell_w), .h = @floatFromInt(g.cell_h), .x_off = 0, .y_off = 0 }; } -fn compactTaglineLayout(g: *const Gui, origin_col: f32) CellLayout { - const body_w: f32 = @floatFromInt(g.cell_w); - const tag_w: f32 = @floatFromInt(g.tagline_width); - return .{ - .w = tag_w, - .h = @floatFromInt(g.cell_h), - .x_off = origin_col * (body_w - tag_w), - .y_off = 0, - }; -} - -fn taglineLayoutForCell(g: *const Gui, col: u16) CellLayout { - // Canonical tag cells are physical grips; text is drawn by TagLayer. - return compactTaglineLayout(g, @floatFromInt(col)); -} - const boxContains = pardes.animation.Box.contains; /// What one tier draws, or one track in tiers 2 and 3 (docs/render-pipeline.md @@ -2663,15 +2536,14 @@ fn localSession( var ptys: [pardes.MAX_PANES]?Pty = @splat(null); var gens: [pardes.MAX_PANES]u32 = @splat(0); - var lsp_workers: LspWorkers = .{}; var queue: Queue = .{ + .io = io, .gpa = gpa, .lsp_allocator = allocs.lsp, - .lsp_workers = &lsp_workers, .sdl_wake = true, }; defer { - lsp_workers.wait(); + if (queue.lsp_task) |*task| task.future.cancel(io) catch {}; queue.deinit(); } var pipe_tasks: PipeTasks = .{}; @@ -3035,15 +2907,14 @@ fn runGrid(init: std.process.Init, opts_in: pardes.Options) !void { var ptys: [pardes.MAX_PANES]?Pty = @splat(null); var gens: [pardes.MAX_PANES]u32 = @splat(0); - var lsp_workers: LspWorkers = .{}; var queue: Queue = .{ + .io = io, .gpa = gpa, .lsp_allocator = allocs.lsp, - .lsp_workers = &lsp_workers, .sdl_wake = false, }; defer { - lsp_workers.wait(); + if (queue.lsp_task) |*task| task.future.cancel(io) catch {}; queue.deinit(); } var pipe_tasks: PipeTasks = .{}; @@ -4195,13 +4066,12 @@ const Shell = struct { fn closePty(s: *Shell, pane: u8) void { const pt = if (s.ptys[pane]) |*pt| pt else return; if (pt.fd < 0) return; + // Out of the queue first, which lets go a reader waiting for room + // in it; then its read is canceled (or, at its end, it is joined). s.queue.cancelReader(pane, s.gens[pane]); - if (pt.reader) |thread| { - _ = host_io.writeFd(pt.stop[1], "x"); - thread.join(); + if (pt.reader) |*reader| { + reader.cancel(s.queue.io); // the Io it was started on (spawnReader) pt.reader = null; - for (pt.stop) |fd| _ = libc.close(fd); - pt.stop = .{ -1, -1 }; } _ = libc.close(pt.fd); pt.fd = -1; @@ -4848,11 +4718,10 @@ test "the headless grid host round-trips a yank back as a paste" { var ptys: [pardes.MAX_PANES]?Pty = @splat(null); var gens: [pardes.MAX_PANES]u32 = @splat(0); - var lsp_workers: LspWorkers = .{}; var queue: Queue = .{ + .io = std.testing.io, .gpa = gpa, .lsp_allocator = gpa, - .lsp_workers = &lsp_workers, .sdl_wake = false, }; defer queue.deinit(); @@ -4933,7 +4802,7 @@ fn openLink(ctx: ?*anyopaque, url: []const u8) void { fn lsp(ctx: ?*anyopaque, req: host_io.Lsp.Request) void { const s = shellOf(ctx); - if (s.threads_ok) return spawnLsp(s.core, s.queue, req); + if (s.threads_ok) return spawnLsp(s.core, s.io, s.queue, req); s.core.update(.{ .lsp_resp = .{ .id = req.id, .rows = null } }); s.core.reportError(req.pane, "lsp", error.WorkersUnavailable); } @@ -5198,6 +5067,12 @@ const Glide = struct { below: []pardes.Cell = &.{}, nabove: u16 = 0, nbelow: u16 = 0, + /// The core's lines a scroll moved, not yet measured; and what the + /// glide in flight has moved, in lines and in the picture's rows. A + /// wrapped line is several rows, and the thumb counts lines. + pending_lines: f32 = 0, + lines_moved: f32 = 0, + rows_moved: f32 = 0, /// The Motion flavour the last loop step read. motion: pardes.animation.Motion = .{}, @@ -5211,6 +5086,16 @@ const Glide = struct { glide.pending = false; glide.nabove = 0; glide.nbelow = 0; + glide.pending_lines = 0; + glide.lines_moved = 0; + glide.rows_moved = 0; + } + + /// The glide's lag in the core's lines: its rows, scaled by the lines + /// they carried. + fn lagLines(glide: *const Glide) f32 { + if (glide.rows_moved == 0) return glide.offset; + return glide.offset * glide.lines_moved / glide.rows_moved; } fn deinit(glide: *Glide, gpa: std.mem.Allocator) void { @@ -5270,6 +5155,9 @@ const Glide = struct { break :found kk; } else 0; if (shift == 0) return glide.stop(); + glide.rows_moved += @floatFromInt(shift); + glide.lines_moved += glide.pending_lines; + glide.pending_lines = 0; // The rows that left: past the top going down, the bottom going up. if (!glide.ensure(gpa)) return glide.stop(); const keep = if (glide.dir > 0) &glide.above else &glide.below; @@ -5326,6 +5214,8 @@ fn stepGlide(g: *Gui, core: *pardes.Pardes, gpa: std.mem.Allocator) void { glide.offset = 0; glide.nabove = 0; glide.nbelow = 0; + glide.lines_moved = 0; + glide.rows_moved = 0; } } const notch = g.scroll_notch; @@ -5357,6 +5247,8 @@ fn stepGlide(g: *Gui, core: *pardes.Pardes, gpa: std.mem.Allocator) void { } var left = notch; var moved = false; + const first = pane.scroll(); + defer glide.pending_lines += @floatFromInt(@abs(pane.scroll() - first)); while (left != 0) { const down = left > 0; left += if (down) -1 else 1; @@ -9347,7 +9239,7 @@ fn paneDecor(g: *Gui, gpa: std.mem.Allocator, regions: []const pardes.Region, gr // In pixels, not rows, and with the picture while it glides // or lags behind the core's rows (both in rows of the body). const lag: f32 = if (g.glide.offset != 0 and g.glide.pane == rail.owner) - g.glide.offset + g.glide.lagLines() else if (g.scroll_pane != null and g.scroll_pane.? == rail.owner) g.scroll_lag else 0; const track_px = body_y1 - y0; const size = @min(track_px, @max(layout.h, rail.thumb_span * track_px)); @@ -9983,6 +9875,12 @@ test "the scrollbar thumb moves by the pixel and follows a glide" { g.glide.pane = core.active; g.glide.offset = -1; try std.testing.expectApproxEqAbs(at10, try thumb.top(&g, core), 1e-3); + // A wrapped line: the picture moved two rows for the one line, and the + // thumb lags the line, not two. + g.glide.lines_moved = 1; + g.glide.rows_moved = 2; + g.glide.offset = -2; + try std.testing.expectApproxEqAbs(at10, try thumb.top(&g, core), 1e-3); } test "the rule between stacked panes stays in the tag band's slack, at any tagline size" { @@ -10581,12 +10479,11 @@ fn appendWorkspacePet(g: *Gui, core: ?*const pardes.Pardes, surface: *const pard return; } // Read only the rendered global row. No pane/column tags, status text or - // mouse targets are changed, and editing the workspace parks the pet. + // mouse targets are changed; editing the workspace tag leaves it be. var occupied: usize = 0; for (surface.cells[0..surface.cols], 0..) |*cell, i| { if (cellCodepoint(cell) != ' ') occupied = i + 1; } - const editing = p.header_focus and p.header_column == null; const band_top: f32 = @floatFromInt(taglineBandOffset(0, builder.win_h, g.cell_h, g.tagline_height)); const region = if (occupied >= surface.cols) null else pet.lane( occupied, @@ -10594,7 +10491,6 @@ fn appendWorkspacePet(g: *Gui, core: ?*const pardes.Pardes, surface: *const pard builder.win_w, band_top, @floatFromInt(g.tagline_height), - editing, ); // SDL's regular pump already wakes at least every 16 ms. Quantization in // sample keeps this independent of input, render rate and scene effects, @@ -10602,16 +10498,24 @@ fn appendWorkspacePet(g: *Gui, core: ?*const pardes.Pardes, surface: *const pard const pose = g.pet_state.sample(kind, c.SDL_GetTicks(), region) orelse return; const ink = overlayRgb(p.chromeTheme().tag_fg); const eye = overlayRgb(p.chromeTheme().tag_bg); + // Behind the cursor: the overlay is over the cells, so the pixels a + // cursor covers are left out. + var boxes: [max_cursors]CursorBox = undefined; + const cursors = boxes[0..cursorBoxes(g, surface, fixedCellLayout(g), builder.win_h, &boxes)]; for (0..pet.height) |y| for (0..pet.width) |x| { const color = pet.pixel(kind, pose, x, y); if (color == 0) continue; const x0 = pose.x + @as(f32, @floatFromInt(x)) * pose.scale; const y0 = pose.y + @as(f32, @floatFromInt(y)) * pose.scale; + const covered = for (cursors) |box| { + if (x0 < box.x1 and x0 + pose.scale > box.x0 and y0 < box.y1 and y0 + pose.scale > box.y0) break true; + } else false; + if (covered) continue; builder.addRect(x0, y0, x0 + pose.scale, y0 + pose.scale, if (color == 2) eye else ink); }; } -test "pet overlay stays beyond workspace text and vanishes while its tag is edited" { +test "pet overlay stays beyond workspace text and keeps going while its tag is edited" { std.testing.refAllDecls(pet); const core = try pardes.Pardes.init(std.testing.allocator, .{ .cols = 80, .rows = 24 }); defer core.deinit(); @@ -10638,10 +10542,13 @@ test "pet overlay stays beyond workspace text and vanishes while its tag is edit try std.testing.expect(x >= 20 * 8 - 0.01); try std.testing.expect(y >= 0 and y < 20); } + const before = g.pet_state; pardes.tagline.enterHeader(core, null); builder.len = 0; appendWorkspacePet(&g, core, &surface, &builder); - try std.testing.expectEqual(@as(usize, 0), builder.len); + try std.testing.expect(builder.len > 0); + try std.testing.expectEqual(before.tick, g.pet_state.tick); + try std.testing.expectEqual(before.x, g.pet_state.x); } fn cursorColor(chrome: *const pardes.Chrome, cell: *const pardes.Cell, role: pardes.FontRole) [3]u8 { diff --git a/src/gui/pet.zig b/src/gui/pet.zig index a249d70f..7a13ca91 100644 --- a/src/gui/pet.zig +++ b/src/gui/pet.zig @@ -13,8 +13,8 @@ const hop_ticks = 8; /// Only the trailing blank part of the global tag is eligible. The caller /// supplies its last occupied cell, including any wide-grapheme continuation. -pub fn lane(occupied: usize, cell_w: f32, screen_w: f32, top: f32, band_h: f32, editing: bool) ?Lane { - if (editing or cell_w <= 0 or band_h < height + 2) return null; +pub fn lane(occupied: usize, cell_w: f32, screen_w: f32, top: f32, band_h: f32) ?Lane { + if (cell_w <= 0 or band_h < height + 2) return null; const scale = @min(3, @floor((band_h - 2) / height)); const left = @as(f32, @floatFromInt(occupied + 2)) * cell_w; const right = screen_w - 2 * cell_w - width * scale; @@ -32,11 +32,10 @@ pub const State = struct { frame: u8 = 0, rng: std.Random.DefaultPrng = undefined, + /// No lane (the tag's text has filled it) hides the pet but keeps + /// where it was and what it was doing. pub fn sample(s: *State, kind: Kind, now_ms: u64, area: ?Lane) ?Pose { - const region = area orelse { - s.* = .{}; - return null; - }; + const region = area orelse return null; if (kind == .off) { s.* = .{}; return null; @@ -142,11 +141,10 @@ pub fn pixel(kind: Kind, pose: Pose, x_in: usize, y: usize) u2 { }; } -test "pet stays in trailing workspace blanks and disappears during editing" { - try std.testing.expect(lane(20, 8, 200, 0, 16, false) == null); - try std.testing.expect(lane(3, 8, 200, 0, 16, true) == null); - try std.testing.expect(lane(3, 8, 200, 0, 10, false) == null); - const region = lane(3, 8, 200, 2, 20, false).?; +test "pet stays in trailing workspace blanks, and a lost lane hides it without a reset" { + try std.testing.expect(lane(20, 8, 200, 0, 16) == null); + try std.testing.expect(lane(3, 8, 200, 0, 10) == null); + const region = lane(3, 8, 200, 2, 20).?; try std.testing.expect(region.left >= 5 * 8); var state: State = .{}; var moved = false; @@ -159,12 +157,15 @@ test "pet stays in trailing workspace blanks and disappears during editing" { reversed = reversed or pose.left; } try std.testing.expect(moved and reversed); + const kept = state; try std.testing.expect(state.sample(.cat, 300000, null) == null); + try std.testing.expectEqual(kept.x, state.x); + try std.testing.expectEqual(kept.tick, state.tick); try std.testing.expect(state.sample(.off, 300100, region) == null); } test "pet clock is fixed rate and sprites bounded in both directions" { - const region = lane(1, 8, 400, 0, 16, false).?; + const region = lane(1, 8, 400, 0, 16).?; var state: State = .{}; const start = state.sample(.frog, 1000, region).?; try std.testing.expectEqualDeep(start, state.sample(.frog, 1099, region).?); @@ -180,7 +181,7 @@ test "pet clock is fixed rate and sprites bounded in both directions" { } test "pet rests at random spots and the frog travels only in the air" { - const region = lane(1, 8, 800, 0, 16, false).?; + const region = lane(1, 8, 800, 0, 16).?; var state: State = .{}; var last = state.sample(.frog, 0, region).?; var rested_midway = false; @@ -195,7 +196,7 @@ test "pet rests at random spots and the frog travels only in the air" { } test "pet initial idle visibly animates without walking or leaving its tile" { - const region = lane(1, 8, 400, 0, 16, false).?; + const region = lane(1, 8, 400, 0, 16).?; for ([_]Kind{ .cat, .frog }) |kind| { var state: State = .{}; const initial = state.sample(kind, 0, region).?; diff --git a/src/host_io.zig b/src/host_io.zig index c593551b..2c736e20 100644 --- a/src/host_io.zig +++ b/src/host_io.zig @@ -203,11 +203,14 @@ pub const Lsp = struct { } others.deinit(gpa); } + var copied: usize = 0; for (core.panes, 0..) |slot, i| { const other = slot orelse continue; if (i == req.pane) continue; const f = other.file orelse continue; if (f.output != null) continue; + if (copied + f.content.len > pardes.memory.limits.lsp_snapshot_bytes) continue; + copied += f.content.len; const local = filesystem.localPath(f.path) orelse continue; const other_path = try gpa.dupe(u8, local); const other_source = gpa.dupeSentinel(u8, f.content, 0) catch |err| { @@ -224,13 +227,19 @@ pub const Lsp = struct { // Null is failure; the receiver frees non-null rows with the job's allocator. pub const Deliver = *const fn (ctx: ?*anyopaque, id: u32, rows: ?[]u8) void; - pub fn work(gpa: std.mem.Allocator, job: *Job, ctx: ?*anyopaque, deliver: Deliver) void { + pub fn work(io: std.Io, gpa: std.mem.Allocator, job: *Job, ctx: ?*anyopaque, deliver: Deliver) void { defer job.free(gpa); - var arena: std.heap.ArenaAllocator = .init(gpa); - defer arena.deinit(); + // The query's memory is the fixed region memory.zig reserved at + // startup: a hard bound, reused by each query in turn. + const region = pardes.memory.takeLspQuery() orelse { + deliver(ctx, job.id, null); + return; + }; + var arena: std.heap.FixedBufferAllocator = .init(region); + defer pardes.memory.giveLspQuery(arena.end_index); var out: std.Io.Writer.Allocating = .init(gpa); defer out.deinit(); - pardes.lsp.query(gpa, arena.allocator(), .{ + pardes.lsp.query(io, gpa, arena.allocator(), .{ .kind = job.kind, .path = job.path, .source = job.source, @@ -240,6 +249,7 @@ pub const Lsp = struct { .others = job.others, .callstack_depth = job.callstack_depth, .callstack_corners = job.callstack_corners, + .budget = &arena, }, &out.writer) catch { deliver(ctx, job.id, null); return; @@ -367,7 +377,7 @@ pub const Lsp = struct { .offset = 0, .arg = "", }); - work(gpa, job, null, Sink.take); + work(std.testing.io, gpa, job, null, Sink.take); // `status` is the one kind that answers with no file and no cursor, which // is what makes it assertable here without a language server on the box. @@ -416,7 +426,7 @@ pub const Lsp = struct { .arg = "renamed", }); if (fail) failing.fail_index = failing.alloc_index; - work(failing.allocator(), job, &sink, Sink.take); + work(std.testing.io, failing.allocator(), job, &sink, Sink.take); try std.testing.expectEqual(fail, sink.failed); try std.testing.expect(core.lsp_wait == null); if (fail) { @@ -482,7 +492,7 @@ pub const Lsp = struct { defer core.deinit(); const job = try snapshot(gpa, core, .{ .id = 37, .kind = .status, .pane = @intCast(core.active), .offset = 0, .arg = "" }); var sink: Sink = .{}; - work(gpa, job, &sink, Sink.take); + work(std.testing.io, gpa, job, &sink, Sink.take); if (sink.rows) |rows| gpa.free(rows); try std.testing.expect(allocator.failed); try std.testing.expectEqual(@as(usize, 1), sink.calls); @@ -1179,7 +1189,7 @@ pub const Shell = struct { if (builtin.os.tag == .windows) return; var saved_buf: [std.fs.max_path_bytes:0]u8 = @splat(0); const saved: ?[:0]const u8 = if (std.c.getenv("XDG_RUNTIME_DIR")) |v| std.fmt.bufPrintSentinel(&saved_buf, "{s}", .{std.mem.span(v)}, 0) catch null else null; - defer _ = if (saved) |v| setenv("XDG_RUNTIME_DIR", v.ptr, 1) else unsetenv("XDG_RUNTIME_DIR"); + defer _ = if (saved) |v| setenv("XDG_RUNTIME_DIR", v.ptr, 1) else testUnsetenv("XDG_RUNTIME_DIR"); var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); @@ -1213,7 +1223,7 @@ pub const Shell = struct { try std.testing.expectEqualStrings(bash_rc, readSmall(c.bashPath().?, &buf) orelse return error.ReadFailed); // No runtime dir: private files, one per owner, gone at teardown. - _ = unsetenv("XDG_RUNTIME_DIR"); + _ = testUnsetenv("XDG_RUNTIME_DIR"); var d = PromptFiles.init(); var e = PromptFiles.init(); defer e.deinit(); @@ -1294,6 +1304,44 @@ pub const ChildEnv = struct { "TERM_PROGRAM=" ++ pardes.config.child_term_program, }; + /// What this editor tells its children of itself (exportPaneEnv, `$winid`), + /// kept here rather than set into this process's environment: std's Io read + /// that block at startup, and setenv/unsetenv rewrite it in place under it + /// (a spawn then scans a null inside it). `build` puts each exported one in + /// place of an inherited variable of its name; a cleared one hides it; one + /// never exported is inherited as it is. + pub const exported_names = [_][]const u8{ "PARDES_PID", "PARDES_9P", "PARDES_PANE", "PARDES_MOUNT", "winid" }; + var exported_state: [exported_names.len]enum { inherited, cleared, set } = @splat(.inherited); + var exported_line: [exported_names.len][pardes.memory.limits.host_path_cap + 64:0]u8 = undefined; + + /// Set (or, null, clear) what children are told for `var_name`. + pub fn exportVar(var_name: []const u8, value: ?[]const u8) void { + const i = exportedIndex(var_name).?; + const v = value orelse { + exported_state[i] = .cleared; + return; + }; + const line = std.fmt.bufPrintSentinel(&exported_line[i], "{s}={s}", .{ var_name, v }, 0) catch { + exported_state[i] = .cleared; + return; + }; + exported_state[i] = .set; + _ = line; + } + + /// What children are told for `var_name`, as `exportVar` left it; null + /// when cleared or never exported. + pub fn exported(var_name: []const u8) ?[]const u8 { + const i = exportedIndex(var_name) orelse return null; + if (exported_state[i] != .set) return null; + return std.mem.span(@as([*:0]const u8, &exported_line[i]))[var_name.len + 1 ..]; + } + + fn exportedIndex(var_name: []const u8) ?usize { + for (exported_names, 0..) |n, i| if (std.mem.eql(u8, n, var_name)) return i; + return null; + } + /// Wide enough for any real environment; `build` answers null rather than /// truncate, because a child missing half its variables is a worse bug /// than one missing TERM, and the caller then execs with `environ` intact. @@ -1318,7 +1366,8 @@ pub const ChildEnv = struct { if (std.mem.eql(u8, inherited, name(mine))) break true; } else false; if (shadowed) continue; - if (n + own.len + 1 > slots.len) return null; + if (exportedIndex(inherited)) |e| if (exported_state[e] != .inherited) continue; + if (n + own.len + exported_names.len + 1 > slots.len) return null; slots[n] = entry; n += 1; } @@ -1336,10 +1385,14 @@ pub const ChildEnv = struct { if (std.mem.eql(u8, name(entry.?), name(default))) break true; } else false; if (set) continue; - if (n + own.len + 4 > slots.len) return null; + if (n + own.len + exported_names.len + 4 > slots.len) return null; slots[n] = default; n += 1; } + for (&exported_line, exported_state) |*line, state| if (state == .set) { + slots[n] = line; + n += 1; + }; for (own) |mine| { slots[n] = mine; n += 1; @@ -1411,14 +1464,14 @@ test "the child environment replaces the launcher's terminal identity exactly on defer if (restore) |t| { _ = Shell.setenv("TERM", t.ptr, 1); } else { - _ = unsetenv("TERM"); + _ = testUnsetenv("TERM"); }; // A launcher TERM must be shadowed rather than duplicated, and the rest of // the environment must arrive untouched. try std.testing.expectEqual(@as(c_int, 0), Shell.setenv("TERM", "dumb", 1)); try std.testing.expectEqual(@as(c_int, 0), Shell.setenv("PARDES_CHILD_ENV_PROBE", "1", 1)); - defer _ = unsetenv("PARDES_CHILD_ENV_PROBE"); + defer _ = testUnsetenv("PARDES_CHILD_ENV_PROBE"); var slots: ChildEnv.Slots = undefined; // Where the user named no pager: a terminal's shell pages into a @@ -1481,6 +1534,16 @@ test "the child environment replaces the launcher's terminal identity exactly on extern "c" fn unsetenv(name: [*:0]const u8) c_int; +/// For tests: unset `name` without compacting the environment block std +/// captured at startup (std.testing.environ and Io's spawns read it later). A +/// new variable first moves glibc's `environ` to a heap copy, which unsetenv +/// then compacts instead. Runtime code never changes this process's +/// environment (ChildEnv.exportVar). +pub fn testUnsetenv(name: [*:0]const u8) c_int { + _ = Shell.setenv("PARDES_TEST_ENVIRON_COPIED", "1", 1); + return unsetenv(name); +} + /// The environment a pane's command is given (exportPaneEnv, `$winid`, /// ChildEnv), as `NAME=value` lines in `arena`, for a command that is not a /// pane's: an Edit's filters, run from pane `serial`. @@ -1497,10 +1560,7 @@ pub fn commandEnv(arena: std.mem.Allocator, serial: u32, adopts: bool) ![]const fn exportWinid(serial: u32) void { var buf: [16]u8 = undefined; - if (serial != 0) if (std.fmt.bufPrintSentinel(&buf, "{d}", .{serial}, 0)) |text| { - if (Shell.setenv("winid", text, 1) == 0) return; - } else |_| {}; - _ = unsetenv("winid"); + ChildEnv.exportVar("winid", if (serial == 0) null else std.fmt.bufPrint(&buf, "{d}", .{serial}) catch null); } /// The longest line a command pane runs (exec.zig refuses a longer one). @@ -1587,17 +1647,18 @@ pub fn forkShell( if (helper) |path| { const c = core.?; const pn = c.panes[pane].?; - const socket = libc.getenv("PARDES_9P") orelse return error.SessionSocketRequired; + const socket = ChildEnv.exported("PARDES_9P") orelse return error.SessionSocketRequired; var command: std.Io.Writer.Allocating = .init(c.gpa); defer command.deinit(); - try @import("linux/v9fs.zig").writeLaunchCommand(&command.writer, path, std.mem.span(socket), &spawn.argv); + try @import("linux/v9fs.zig").writeLaunchCommand(&command.writer, path, socket, &spawn.argv); if (!try pardes.panes.terminal.queuePendingCommand(pn, command.written())) return error.ShellAlreadyStarted; } // Built here and not after the fork: between fork and exec the child may // not call setenv, whose malloc can deadlock against a pty reader thread // that held the heap when the fork took its snapshot. var env_slots: ChildEnv.Slots = undefined; - const paging: ChildEnv.Paging = if (one_line != null) + const pages = if (core) |c| if (c.panes[pane]) |pn| pn.command_pages else false else false; + const paging: ChildEnv.Paging = if (one_line != null and !pages) .command else if (core) |c| (if (c.settings.pager == .off) .terminal_off else .terminal) else .terminal; const envp = ChildEnv.build(&env_slots, paging); @@ -1695,7 +1756,7 @@ test "a forked shell is told which terminal it is talking to" { defer if (restore) |t| { _ = Shell.setenv("TERM", t.ptr, 1); } else { - _ = unsetenv("TERM"); + _ = testUnsetenv("TERM"); }; _ = Shell.setenv("TERM", "dumb", 1); diff --git a/src/hunks.zig b/src/hunks.zig index 73c0654a..24aaf63d 100644 --- a/src/hunks.zig +++ b/src/hunks.zig @@ -368,21 +368,34 @@ const max_line_distance = 0.6; /// rather than aligned at a quadratic cost (delta aligns them all). const max_run = 256; const max_cells = 1 << 16; +/// Pairs one hunk compares (each a table of up to `max_cells`): past it, the +/// rest of its lines are shown unemphasised. And the scratch each pair is +/// aligned in, reused by the next: its table and the ranges it marks. +const max_pairs = 4096; +const pair_scratch_bytes = 8 << 20; /// Pair each removed line with the first added line after the last one /// paired that is near enough to it, in order, and emphasise in both the /// tokens one has and the other has not. fn inferEdits(arena: std.mem.Allocator, minus: []HunkLine, plus: []HunkLine) !void { if (minus.len == 0 or plus.len == 0 or minus.len > max_run or plus.len > max_run) return; + const plus_tokens = try arena.alloc([]const []const u8, plus.len); + for (plus, plus_tokens) |line, *tokens| tokens.* = try tokenize(arena, line.code); + var scratch: std.heap.FixedBufferAllocator = .init(try @import("memory.zig").unfilled(arena, pair_scratch_bytes)); + var pairs: usize = 0; var plus_index: usize = 0; for (minus) |*m| { const m_tokens = try tokenize(arena, m.code); var j = plus_index; while (j < plus.len) : (j += 1) { - const p_tokens = try tokenize(arena, plus[j].code); + const p_tokens = plus_tokens[j]; if ((m_tokens.len + 1) * (p_tokens.len + 1) > max_cells) continue; - var alignment = try Alignment.init(arena, m_tokens, p_tokens); - const marks = try annotate(arena, &alignment, m.code, plus[j].code); + if (pairs == max_pairs) return; + pairs += 1; + scratch.reset(); + const pair = scratch.allocator(); + var alignment = Alignment.init(pair, m_tokens, p_tokens) catch continue; + const marks = annotate(pair, &alignment, m.code, plus[j].code) catch continue; if (marks.distance > max_line_distance) continue; for (marks.minus) |r| for (m.styles[r[0]..r[1]]) |*b| { b.* |= syntax.diff_emph; diff --git a/src/image.zig b/src/image.zig index 8bf9de08..5797ce9e 100644 --- a/src/image.zig +++ b/src/image.zig @@ -768,7 +768,13 @@ pub fn readable(bytes: []const u8) bool { /// decode + downscale to RGBA, gpa-owned. Returns null on any failure — the /// pane then simply shows a blank body. pub fn decode(gpa: std.mem.Allocator, bytes: []const u8) ?struct { rgba: []u8, w: usize, h: usize } { - if (bytes.len == 0) return null; + if (bytes.len == 0 or bytes.len > std.math.maxInt(c_int)) return null; + // Bounded before decoding: a few KB of PNG can name gigapixels. + var iw: c_int = 0; + var ih: c_int = 0; + var ic: c_int = 0; + if (stbi_info_from_memory(bytes.ptr, @intCast(bytes.len), &iw, &ih, &ic) != 1) return null; + if (@as(usize, @intCast(@max(0, iw))) * @as(usize, @intCast(@max(0, ih))) > @import("memory.zig").limits.image_decode_pixels) return null; var img = zstbi.Image.loadFromMemory(bytes, 4) catch return null; // 4 = RGBA defer img.deinit(); var scaled: ?zstbi.Image = null; diff --git a/src/locations.zig b/src/locations.zig index 2828566d..1e4a20cf 100644 --- a/src/locations.zig +++ b/src/locations.zig @@ -217,6 +217,98 @@ pub fn treeContinuation(line: []const u8, buffer: []u8, max_cells: usize) []cons return out.buffered()[0..end]; } +const Resolved = struct { code: []const u8 = "", colors: []const u8 = &.{}, source_row: usize = 0 }; + +/// Each Callstack row's code (its call site's line, or a caller's header) and +/// colors, by input line. A page spans thousands of files, so they are taken +/// a file at a time: grouped by path, each file read, line-indexed and +/// analyzed once, its rows' code and colors copied out, and the file let go +/// before the next. Row by row, the cache compared the whole source each +/// time and past its 64 entries parsed it again, every lookup walked the +/// file from its top, and every source stayed in the arena to the end. +fn resolveCallstack(p: *pardes.Pardes, arena: std.mem.Allocator, dir: []const u8, input: []const u8) ![]Resolved { + const mark = @import("lsp/lsp.zig").callstack_match; + var all: std.ArrayList([]const u8) = .empty; + var by_path: std.StringArrayHashMapUnmanaged(std.ArrayList(u32)) = .empty; + var lines = std.mem.splitScalar(u8, std.mem.trimEnd(u8, input, "\n"), '\n'); + while (lines.next()) |raw| { + const line = if (std.mem.startsWith(u8, raw, mark)) raw[mark.len..] else raw; + const index: u32 = @intCast(all.items.len); + try all.append(arena, line); + const target = parseRaw(line[treePrefix(line).end..]); + if (target.at.line == 0) continue; + const entry = try by_path.getOrPut(arena, target.path); + if (!entry.found_existing) entry.value_ptr.* = .empty; + try entry.value_ptr.append(arena, index); + } + const resolved = try arena.alloc(Resolved, all.items.len); + @memset(resolved, .{}); + var file_arena: std.heap.ArenaAllocator = .init(p.gpa); + defer file_arena.deinit(); + for (by_path.keys(), by_path.values()) |path, indexes| { + _ = file_arena.reset(.retain_capacity); + const fa = file_arena.allocator(); + const source = sourceText(p, fa, dir, path); + var cached: Cache.Hit = .{ .analysis = .{} }; + defer cached.deinit(p.tree_sitter_gpa); + // Where each line starts, the file's length closing the last. + var starts: std.ArrayList(usize) = .empty; + if (source) |text| { + cached = p.locations_cache.get(p.tree_sitter_gpa, text.path, text.bytes, true, true) catch .{ .analysis = .{} }; + try starts.append(fa, 0); + var at: usize = 0; + while (std.mem.indexOfScalarPos(u8, text.bytes, at, '\n')) |nl| : (at = nl + 1) try starts.append(fa, nl + 1); + } + for (indexes.items) |index| { + const line = all.items[index]; + const prefix = treePrefix(line); + const target = parseRaw(line[prefix.end..]); + var code = line[prefix.end + target.code_start ..]; + var colors: []const u8 = &.{}; + var source_row = target.at.line - 1; + if (source) |text| { + const row = target.at.line - 1; + if (prefix.branch) { + // Choose the innermost header containing the server's name range. + var chosen: ?syntax.ContextDeclaration = null; + for (cached.analysis.declarations) |declaration| { + if (declaration.start_line <= row and row <= declaration.header_end_line) { + if (chosen == null or declaration.end_byte - declaration.start_byte < chosen.?.end_byte - chosen.?.start_byte) + chosen = declaration; + } + } + if (chosen) |header| { + code = text.bytes[header.start_byte..header.header_end_byte]; + source_row = header.start_line; + } else { + const fallback = indexedLine(text.bytes, starts.items, row); + if (fallback.len > 0) code = fallback; + } + } else if (code.len == 0) { + // A call site the language worker sent bare (it reads no + // sources for Callstack): its line, from the source here. + code = indexedLine(text.bytes, starts.items, row); + } + const offset = if (source_row < starts.items.len) starts.items[source_row] else text.bytes.len; + if (offset + code.len <= cached.analysis.colors.len and + std.mem.eql(u8, code, text.bytes[offset..][0..code.len])) + colors = cached.analysis.colors[offset..][0..code.len]; + code = try arena.dupe(u8, code); + colors = try arena.dupe(u8, colors); + } + resolved[index] = .{ .code = code, .colors = colors, .source_row = source_row }; + } + } + return resolved; +} + +/// modal.lineSlice through a line index (`starts`, as resolveCallstack builds it). +fn indexedLine(text: []const u8, starts: []const usize, row: usize) []const u8 { + if (row >= starts.len or starts[row] >= text.len) return ""; + const end = if (row + 1 < starts.len) starts[row + 1] - 1 else text.len; + return text[starts[row]..end]; +} + /// Enrich caller nodes on the UI thread, using the same source/declaration cache /// as LocationsContext. The LSP worker only supplies relationships and addresses. pub fn formatCallstack(p: *pardes.Pardes, dir: []const u8, input: []const u8) !Result { @@ -232,9 +324,10 @@ pub fn formatCallstack(p: *pardes.Pardes, dir: []const u8, input: []const u8) !R rows.deinit(p.gpa); } const stacked = p.settings.callstack_layout == .stacked; - var sources: std.StringHashMap(?Source) = .init(arena); + const resolved = try resolveCallstack(p, arena, dir, input); var lines = std.mem.splitScalar(u8, std.mem.trimEnd(u8, input, "\n"), '\n'); - while (lines.next()) |raw| { + var index: usize = 0; + while (lines.next()) |raw| : (index += 1) { const mark = @import("lsp/lsp.zig").callstack_match; const focus = std.mem.startsWith(u8, raw, mark); const line = if (focus) raw[mark.len..] else raw; @@ -245,41 +338,9 @@ pub fn formatCallstack(p: *pardes.Pardes, dir: []const u8, input: []const u8) !R try appendMetadata(p.gpa, &rows, .{ .path = "", .at = .{}, .label = "", .code = "", .original = null }, .context, 0, line.len, false); continue; } - const entry = try sources.getOrPut(target.path); - if (!entry.found_existing) entry.value_ptr.* = sourceText(p, arena, dir, target.path); - const source = entry.value_ptr.*; - var cached: Cache.Hit = .{ .analysis = .{} }; - defer cached.deinit(p.tree_sitter_gpa); - if (source) |text| cached = p.locations_cache.get(p.tree_sitter_gpa, text.path, text.bytes, true, true) catch .{ .analysis = .{} }; - var code = line[prefix.end + target.code_start ..]; - var colors: []const u8 = &.{}; - var source_row = target.at.line - 1; - if (source) |text| { - const row = target.at.line - 1; - if (prefix.branch) { - // Choose the innermost header containing the server's name range. - var chosen: ?syntax.ContextDeclaration = null; - for (cached.analysis.declarations) |declaration| { - if (declaration.start_line <= row and row <= declaration.header_end_line) { - if (chosen == null or declaration.end_byte - declaration.start_byte < chosen.?.end_byte - chosen.?.start_byte) - chosen = declaration; - } - } - if (chosen) |header| { - code = text.bytes[header.start_byte..header.header_end_byte]; - source_row = header.start_line; - } else { - const fallback = @import("modal.zig").lineSlice(text.bytes, row); - if (fallback.len > 0) code = fallback; - } - } - { - const offset = @import("modal.zig").lineStartOffset(text.bytes, source_row); - if (offset + code.len <= cached.analysis.colors.len and - std.mem.eql(u8, code, text.bytes[offset..][0..code.len])) - colors = cached.analysis.colors[offset..][0..code.len]; - } - } + const code = resolved[index].code; + const colors = resolved[index].colors; + var source_row = resolved[index].source_row; const recursion = prefix.branch and std.mem.endsWith(u8, line, " ↻ recursion"); const first_line = code[0 .. std.mem.indexOfScalar(u8, code, '\n') orelse code.len]; const source_indent = if (stacked) first_line.len - std.mem.trimStart(u8, first_line, " \t").len else 0; diff --git a/src/look.zig b/src/look.zig index f4fbe52e..02754fff 100644 --- a/src/look.zig +++ b/src/look.zig @@ -587,6 +587,10 @@ fn lookFirstHit(p: *Pardes, id: usize) void { /// Fills the results buffer, and answers how many rows a text or PDF /// search found (0 for Find and Grep, which do not count). With /// `open_empty` false a text search that found nothing opens no buffer. +/// A search of one pane's text (or its PDF) writes at most this many bytes +/// of rows: past it, the rows stop and say where. +pub const search_text_output_bytes = 16 << 20; + pub fn runSearch(p: *Pardes, id: usize, pat_raw: []const u8, kind: Search, start: SearchStart, open_empty: bool) !usize { const pane = p.panes[id] orelse return 0; // Blanks at either end are the pattern's (a look of an indented line); @@ -598,7 +602,9 @@ pub fn runSearch(p: *Pardes, id: usize, pat_raw: []const u8, kind: Search, start // root, and the directory the results buffer is named in. From a // column's or the workspace's tag, the session's. const dir = if (p.exec_header) p.sessionDir() else Pardes.paneDir(pane); - const out = try arena.alloc(u8, filesystem.search_max_output_bytes); + // As much as the search can write and no more: a root's hits for each + // root Grep walks, one for Find, `search_text_output_bytes` in a pane. + var out: []u8 = &.{}; var out_len: usize = 0; var nrows: usize = 0; var anchor: ?usize = null; @@ -631,6 +637,7 @@ pub fn runSearch(p: *Pardes, id: usize, pat_raw: []const u8, kind: Search, start roots[nroots] = d; nroots += 1; } + out = try @import("memory.zig").unfilled(arena, @max(1, nroots) * filesystem.search_root_output_bytes); // A pane's directory that is not there (a scratch named into one // not made yet, a peer's) has nothing to grep: passed over, not the // search's failure. @@ -641,9 +648,11 @@ pub fn runSearch(p: *Pardes, id: usize, pat_raw: []const u8, kind: Search, start }; nrows = std.mem.count(u8, out[0..out_len], "\n"); } else if (kind == .find) { + out = try @import("memory.zig").unfilled(arena, filesystem.search_root_output_bytes); out_len = try filesystem.find(arena, dir, pat, out, ¬es); nrows = std.mem.count(u8, out[0..out_len], "\n"); } else if (pane.hasPdf()) { + out = try @import("memory.zig").unfilled(arena, search_text_output_bytes); if (comptime pdf_enabled) { const found = try panes.Pdf.searchRows( &pane.pdf.?, @@ -658,6 +667,7 @@ pub fn runSearch(p: *Pardes, id: usize, pat_raw: []const u8, kind: Search, start anchor = found.anchor; } } else { + out = try @import("memory.zig").unfilled(arena, search_text_output_bytes); const lines = try edit.paneCursorLines(p, &pane.body); // a real file names itself; a terminal or an output buffer has no path const has_path = if (pane.file) |f| f.output == null else false; @@ -675,7 +685,10 @@ pub fn runSearch(p: *Pardes, id: usize, pat_raw: []const u8, kind: Search, start const row = try std.fmt.allocPrint(arena, "{s}:{d}:{d}{c}{d} {s}\n", .{ loc, i + 1, at + 1, config.range_sep, at + pat.len, std.mem.trimEnd(u8, ln, " \t"), }); - if (row.len > out.len - out_len) break; + if (row.len > out.len - out_len) { + notes.rows_cut = nrows; + break; + } if (start == .cursor and (i < cl or (i == cl and at <= cc))) anchor = nrows; @memcpy(out[out_len..][0..row.len], row); out_len += row.len; @@ -1451,6 +1464,7 @@ fn lookUnresolved(p: *Pardes, id: usize, pane: *Pane, trimmed: []const u8, text: // 9P is no keyboard input, and searches whatever the key mode. if (pane.image != null or (pane.body.mode == .tty and !p.fs.serving)) return; if (text.len == 0) return; + if (lookCommit(p, id, pane, trimmed)) return; if (p.settings.look_word == .search and pane.file != null) return lookWord(p, id, pane, text); p.word_look = true; defer p.word_look = false; @@ -1471,6 +1485,49 @@ fn lookUnresolved(p: *Pardes, id: usize, pane: *Pane, trimmed: []const u8, text: } } +/// A commit hash (7 to 40 hex digits, a letter and a digit among them) +/// looked at inside a git repository: `git show` it, paged into a +Pager, +/// which stacks its hunks in a +Diff (ctl.fillPager); the command pane +/// goes when it succeeds (exec.commandDone). +// ponytail: a hex word that names no commit leaves git's error in a command pane, not a search; check the object first if that bites. +fn lookCommit(p: *Pardes, id: usize, pane: *Pane, word: []const u8) bool { + if (comptime !pardes.hosted) return false; + if (!isCommitHash(word)) return false; + var dir = filesystem.localPath(Pardes.paneDir(pane)) orelse return false; + while (true) { + var buf: [4096]u8 = undefined; + const dot_git = std.fmt.bufPrint(&buf, "{s}/.git", .{dir}) catch return false; + if (exec.kindOf(dot_git) != null) break; + dir = std.fs.path.dirname(dir) orelse return false; + } + var line: [64]u8 = undefined; + const dst = exec.execute(p, id, std.fmt.bufPrint(&line, "git show {s}", .{word}) catch return false) orelse return true; + if (p.panes[dst]) |c| c.command_pages = true; + return true; +} + +fn isCommitHash(word: []const u8) bool { + if (word.len < 7 or word.len > 40) return false; + var digit = false; + var letter = false; + for (word) |c| switch (c) { + '0'...'9' => digit = true, + 'a'...'f' => letter = true, + else => return false, + }; + return digit and letter; +} + +test "a commit hash is 7 to 40 lowercase hex digits with a letter and a digit" { + try std.testing.expect(isCommitHash("9bffa7041c")); + try std.testing.expect(isCommitHash("9bffa7041cd2e8a0b6b1f7c3e4d5a6b7c8d9e0f1")); + try std.testing.expect(!isCommitHash("9bffa7")); + try std.testing.expect(!isCommitHash("defaced")); + try std.testing.expect(!isCommitHash("1234567")); + try std.testing.expect(!isCommitHash("0x9bffa7041c")); + try std.testing.expect(!isCommitHash("9BFFA7041C")); +} + /// Opens (or finds) `path` as Look would, `id`'s own pane when it is empty, /// and selects what `expr` addresses there from its dot. An address that /// does not evaluate moves nothing and says why (acme: no jump). diff --git a/src/lsp/lsp.zig b/src/lsp/lsp.zig index 4a70efe5..1c1b57a2 100644 --- a/src/lsp/lsp.zig +++ b/src/lsp/lsp.zig @@ -26,6 +26,10 @@ pub const Kind = enum { }; pub const callstack_match = "@callstack-match "; +/// The last row of a Callstack page that stopped full: ` `, +/// the entry indices from the top the next page starts at (`3.0.17`), and +/// how many callers this page holds. +pub const callstack_more = "@callstack-more "; pub const CallstackCorners = enum { rounded, square }; pub const callstack_default_depth: u8 = 8; pub const callstack_max_depth: u8 = 64; @@ -46,6 +50,9 @@ pub const Req = struct { /// For `explain`: the query it narrates, read from `arg` (` /// `) by `explaining`; a definition when none was asked before. explains: Kind = .definition, + /// The fixed region `arena` allocates from, when it is one: a walk that + /// can grow (Callstack) reads how much is left and stops in time. + budget: ?*const std.heap.FixedBufferAllocator = null, }; pub const Doc = struct { path: []const u8, source: [:0]const u8 }; @@ -102,18 +109,18 @@ pub fn speaks(path: []const u8) bool { return false; } -pub fn query(gpa: std.mem.Allocator, arena: std.mem.Allocator, req: Req, out: *std.Io.Writer) !void { +pub fn query(io: std.Io, gpa: std.mem.Allocator, arena: std.mem.Allocator, req: Req, out: *std.Io.Writer) !void { if (req.kind == .status) { try out.print("backend: {s}\n", .{backend_name}); - inline for (backends) |b| try b.query(gpa, arena, req, out); + inline for (backends) |b| try b.query(io, gpa, arena, req, out); return; } inline for (backends) |b| { if (b.speaks(req.path) and b.supports.contains(req.kind)) - return b.query(gpa, arena, req, out); + return b.query(io, gpa, arena, req, out); } if (req.kind == .explain and backends.len > 0) - return backends[0].query(gpa, arena, req, out); + return backends[0].query(io, gpa, arena, req, out); // Nothing asked: said why, where an empty answer would read as nothing // found. inline for (backends) |b| if (b.speaks(req.path)) @@ -217,6 +224,6 @@ test "a question no backend answers for a file says why rather than find nothing var buf: [256]u8 = undefined; var out: std.Io.Writer = .fixed(&buf); // A file no server speaks for is answered, not left empty. - try query(std.testing.allocator, arena.allocator(), .{ .kind = .incoming_calls, .path = "/x/notes.txt", .source = "", .offset = 0 }, &out); + try query(std.testing.io, std.testing.allocator, arena.allocator(), .{ .kind = .incoming_calls, .path = "/x/notes.txt", .source = "", .offset = 0 }, &out); try std.testing.expectStringStartsWith(out.buffered(), "@none "); } diff --git a/src/lsp/lsp_client.zig b/src/lsp/lsp_client.zig index b396879b..e356c979 100644 --- a/src/lsp/lsp_client.zig +++ b/src/lsp/lsp_client.zig @@ -8,9 +8,10 @@ //! worker thread, and a language server costs tens of milliseconds to start //! and MINUTES to index a large workspace. So a server is spawned lazily on //! the first query that needs it, kept for the life of the editor, and each -//! spec gets at most one — `conns[i]` guards itself with a pthread mutex -//! because the gui shell detaches its workers and a superseded query can still -//! be inside `run` when the next arrives. +//! spec gets at most one — `conns[i]` guards itself with an `Io.Mutex` +//! because a canceled query can still be inside `run` when the next arrives. +//! Every wait is an `Io` cancelation point: a shell cancels the worker of a +//! query it no longer wants, and the worker stops there. //! //! ONE READER THREAD PER SERVER, and it is not optional. The first design //! pumped the socket only while a query waited, which works for a server that @@ -28,7 +29,8 @@ //! under a thread still polling it. //! //! Nothing here may wedge the editor: -//! - every write and every mailbox wait is bounded by a deadline, +//! - every write is bounded by a deadline, and every mailbox wait by a +//! deadline or, while the server narrates progress, by cancelation, //! - a query the server does not answer in time returns no rows and sends //! `$/cancelRequest`; the server is NOT killed for being busy (an indexing //! server is busy for minutes and the status row says so) — but three @@ -58,20 +60,10 @@ extern "c" fn access(path: [*:0]const u8, mode: c_int) c_int; extern "c" fn getenv(name: [*:0]const u8) ?[*:0]const u8; extern "c" fn usleep(usec: c_uint) c_int; extern "c" fn atexit(f: *const fn () callconv(.c) void) c_int; -extern "c" fn realpath(path: [*:0]const u8, resolved: [*]u8) ?[*:0]u8; // test-only libc (the seam's own tests build a real directory tree) extern "c" fn mkdtemp(template: [*:0]u8) ?[*:0]u8; extern "c" fn mkdir(path: [*:0]const u8, mode: libc.mode_t) c_int; extern "c" fn system(cmd: [*:0]const u8) c_int; -// pthread condattr surface, absent from std.c: what makes the mailbox waits -// tick on CLOCK_MONOTONIC (linux) or a relative timeout (darwin). -const pthread_condattr_t = extern struct { data: [8]u8 align(@alignOf(usize)) = @splat(0) }; -extern "c" fn pthread_condattr_init(attr: *pthread_condattr_t) c_int; -extern "c" fn pthread_condattr_setclock(attr: *pthread_condattr_t, clock: c_int) c_int; -extern "c" fn pthread_condattr_destroy(attr: *pthread_condattr_t) c_int; -extern "c" fn pthread_cond_init(cond: *libc.pthread_cond_t, attr: ?*const pthread_condattr_t) c_int; -extern "c" fn pthread_cond_timedwait_relative_np(cond: *libc.pthread_cond_t, mutex: *libc.pthread_mutex_t, reltime: *const libc.timespec) c_int; -const CLOCK_MONOTONIC: c_int = 1; // linux ABI; the setclock call is linux-only const X_OK: c_int = 1; const POLLIN: i16 = 0x001; @@ -182,21 +174,35 @@ fn specFor(path: []const u8) ?usize { return null; } -// Deadlines. Requests are bounded because tty.zig cancels-and-joins the -// previous worker on a new keypress, so the worst UI stall a wedged wait can -// cause is one req_ms. Timeouts do NOT kill the server — an indexing -// rust-analyzer legitimately sits on a `gd` for longer than anyone will wait, -// and the message row is already narrating why. +// Deadlines. A shell cancels-and-joins the previous worker on a new query, +// and its waits are cancelation points: so a request needs no deadline to +// keep the editor responsive, and waits for its answer. Past req_ms the +// message row says the server is still at it; only a server silent and idle +// (no $/progress) for wedge_ms has failed to answer. Timeouts do NOT kill the +// server — an indexing rust-analyzer legitimately sits on a `gd` for minutes. +// The handshake runs protected from cancelation, so it keeps its deadline. const init_ms = 8_000; // spawn + initialize handshake -const req_ms = 4_000; // one request/response round trip +const req_ms = 4_000; // a request past this is said to be still working +const wedge_ms = 300_000; // silent and idle this long: not answering (rust-analyzer takes ~1 min on `default`'s callers in agave) const diag_ms = 1_200; // wait for a publishDiagnostics push after didChange const reply_ms = 2_000; // our answers to server-to-client requests +const reply_queue_bytes = 64 << 10; // replies waiting for the socket (Conn.replies) +const parse_kept = 1 << 20; // what the reader's parse arena keeps between messages +const max_diag_files = 256; // files a server's pushed diagnostics are kept for +const max_diag_bytes = 32 << 20; // and their bytes const wedged_strikes = 3; // consecutive timeouts before a restart -const max_rows = 2000; +/// Rows one answer may hold, and its writer's bytes: carved from the query's +/// fixed region (memory.limits.arena.lsp_query) with the rest of its memory. +const max_rows = 100_000; +/// What a Callstack walk leaves of its query's region for rendering the +/// tree it found: past this it stops and says so. +const callstack_reserve = 32 << 20; +/// What rendering leaves of the answer's writer for its closing line. +const row_room = 4096; const max_doc_bytes = 8 << 20; -const Err = error{ Dead, Timeout, Protocol, OutOfMemory, NoServer, Backoff, WriteFailed }; +const Err = error{ Dead, Timeout, Protocol, OutOfMemory, NoServer, Backoff, WriteFailed, Canceled }; /// Long-lived state outlives every query arena and cannot borrow the caller's /// gpa (a different one shows up in the harness than in the shell), so @@ -251,8 +257,22 @@ const State = enum(u8) { }; const Conn = struct { - mu: libc.pthread_mutex_t = .{}, - cond: libc.pthread_cond_t = .{}, + mu: std.Io.Mutex = .init, + cond: std.Io.Condition = .init, + /// Frames go out whole: a query's requests and the reader's replies + /// share the socket, and interleaved halves are a parse error that ends + /// the server. + write_mu: std.Io.Mutex = .init, + /// Replies the reader made while a query's write held the socket, sent + /// by that writer once its own message is out (releaseWrite): the reader + /// never waits to write, since a server blocked on its output reads + /// nothing more of ours. + /// Two halves: the reader appends to `replies[filling]`, and the writer + /// flips them and sends the other, with no copy and no wait. + replies: [2][reply_queue_bytes]u8 = undefined, + replies_len: [2]usize = .{ 0, 0 }, + filling: u1 = 0, + replies_mu: std.Io.Mutex = .init, state: State = .off, /// bumped per spawn. A reader thread that sees a different gen than its /// own is reading a corpse and exits; a waiter that sees one stops waiting. @@ -264,9 +284,6 @@ const Conn = struct { /// monotonic ms when the last handshake completed — a crash shortly /// after "ready" counts as a handshake failure for backoff purposes ready_at_ms: i64 = 0, - /// linux: the zeroed condvar defaults to REALTIME; re-initialized with a - /// monotonic condattr before its first wait (under the mutex) - cond_monotonic: bool = false, timeouts: u8 = 0, pid: libc.pid_t = -1, sock: c_int = -1, @@ -278,6 +295,8 @@ const Conn = struct { extra_roots: std.ArrayList([]u8) = .empty, docs: std.ArrayList(Doc) = .empty, diags: std.ArrayList(DiagSet) = .empty, + /// The bytes `diags` holds, kept under max_diag_bytes. + diag_bytes: usize = 0, /// the response mailbox: one request outstanding per connection want_id: u32 = 0, resp: ?[]u8 = null, @@ -285,13 +304,12 @@ const Conn = struct { progress: i32 = 0, title: [48]u8 = @splat(0), title_len: u8 = 0, + /// The server says it is still loading its workspace (rust-analyzer's + /// serverStatus, not quiescent): an empty answer now is not one. + loading: bool = false, + /// its index in `conns`, for what it posts + si: usize = 0, - fn lock(c: *Conn) void { - _ = libc.pthread_mutex_lock(&c.mu); - } - fn unlock(c: *Conn) void { - _ = libc.pthread_mutex_unlock(&c.mu); - } fn alive(c: *const Conn) bool { return c.state == .starting or c.state == .ready; } @@ -406,10 +424,10 @@ const Trace = struct { // ------------------------------------------------------------------- query -pub fn query(gpa: std.mem.Allocator, arena: std.mem.Allocator, asked: lsp.Req, out: *std.Io.Writer) !void { +pub fn query(io: std.Io, gpa: std.mem.Allocator, arena: std.mem.Allocator, asked: lsp.Req, out: *std.Io.Writer) !void { _ = gpa; const req = lsp.explaining(asked); - if (req.kind == .status) return status(req, out); + if (req.kind == .status) return status(io, req, out); var tr: Trace = .{ .on = req.kind == .explain }; const si = specFor(req.path) orelse { @@ -421,13 +439,14 @@ pub fn query(gpa: std.mem.Allocator, arena: std.mem.Allocator, asked: lsp.Req, o }; tr.note("file {s} -> {s} (languageId {s})", .{ std.fs.path.basename(req.path), specs[si].name, specs[si].lang }); - const scratch_buf = try arena.alloc(u8, max_rows * 512); + // Raw: `alloc` fills a safe build's new memory, all 51 MB of it, per query. + const scratch_buf = (arena.rawAlloc(max_rows * 512, .of(u8), @returnAddress()) orelse return error.OutOfMemory)[0 .. max_rows * 512]; var scratch: std.Io.Writer = .fixed(scratch_buf); const t0 = nowUs(); var err_name: []const u8 = ""; var failure: ?anyerror = null; - answer(arena, si, req, &scratch, &tr) catch |e| { + answer(io, arena, si, req, &scratch, &tr) catch |e| { failure = e; err_name = @errorName(e); tr.note("ERROR: {s}", .{err_name}); @@ -443,9 +462,9 @@ pub fn query(gpa: std.mem.Allocator, arena: std.mem.Allocator, asked: lsp.Req, o // again, not that it is not there. if (failure) |err| if (err == error.Backoff) { const c = &conns[si]; - c.lock(); + c.mu.lockUncancelable(io); const left_ms = c.retry_after_ms -| nowMs(); - c.unlock(); + c.mu.unlock(io); return lsp.none(out, "{s} failed recently; retry in {d}s", .{ specs[si].name, @divFloor(left_ms + 999, 1000) }); }; if (failure) |err| return err; @@ -464,17 +483,34 @@ fn traceOut(tr: *const Trace, req: lsp.Req, out: *std.Io.Writer, rows: usize, us try out.print("\n{d} row(s) in {d}us\n", .{ rows, us }); } -fn answer(arena: std.mem.Allocator, si: usize, req: lsp.Req, out: *std.Io.Writer, tr: *Trace) Err!void { +fn answer(io: std.Io, arena: std.mem.Allocator, si: usize, req: lsp.Req, out: *std.Io.Writer, tr: *Trace) Err!void { const c = &conns[si]; - c.lock(); - defer c.unlock(); - const g = try ensure(c, si, arena, req, tr); - run(c, si, arena, req, out, tr) catch |e| { + try c.mu.lock(io); + defer c.mu.unlock(io); + 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. + 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); + } +} + +/// One run of a query, and what its failure says of the server. +fn attempt(c: *Conn, io: std.Io, si: usize, arena: std.mem.Allocator, req: lsp.Req, out: *std.Io.Writer, tr: *Trace, g: u32) Err!void { + run(c, io, si, arena, req, out, tr) catch |e| { switch (e) { // transport-level: this server is gone; forget it, and the next // query respawns. Gen-checked so a respawn that happened while we // waited is not the one we kill. - error.Dead, error.Protocol => shutdownIf(c, g), + error.Dead, error.Protocol => shutdownIf(c, io, g), error.Timeout => { // Slow is only wedged when the server is IDLE. One with // active `$/progress` work (rust-analyzer running cargo @@ -487,18 +523,19 @@ fn answer(arena: std.mem.Allocator, si: usize, req: lsp.Req, out: *std.Io.Writer c.timeouts +|= 1; if (c.timeouts >= wedged_strikes and c.gen == g) { post(si, .always, "{s} not answering — restarting", .{specs[si].name}); - shutdownIf(c, g); + shutdownIf(c, io, g); } } }, - error.OutOfMemory, error.NoServer, error.Backoff, error.WriteFailed => {}, + // Canceled: the shell asked something newer, not a wedged server. + error.OutOfMemory, error.NoServer, error.Backoff, error.WriteFailed, error.Canceled => {}, } return e; }; c.timeouts = 0; } -fn run(c: *Conn, si: usize, arena: std.mem.Allocator, req: lsp.Req, out: *std.Io.Writer, tr: *Trace) Err!void { +fn run(c: *Conn, io: std.Io, si: usize, arena: std.mem.Allocator, req: lsp.Req, out: *std.Io.Writer, tr: *Trace) Err!void { // `explain` narrates the last query asked (a definition, `gd`, when // none was) — dispatch below on the effective kind so the trace // follows the code that query really runs. @@ -510,18 +547,18 @@ fn run(c: *Conn, si: usize, arena: std.mem.Allocator, req: lsp.Req, out: *std.Io var uri: std.ArrayList(u8) = .empty; try uriOf(&uri, arena, req.path); - try syncDoc(c, si, arena, uri.items, req.source); + try syncDoc(c, io, si, arena, uri.items, req.source); // Every other open file this server answers for, before a query whose // answer reaches them: zls renames only in the documents it has. if (lsp.reachesOtherFiles(kind)) for (req.others) |doc| if (specFor(doc.path) == si and !std.mem.eql(u8, doc.path, req.path)) { var other: std.ArrayList(u8) = .empty; try uriOf(&other, arena, doc.path); - try syncDoc(c, si, arena, other.items, doc.source); + try syncDoc(c, io, si, arena, other.items, doc.source); tr.note("synced {s} first", .{std.fs.path.basename(doc.path)}); }; const pos = posOf(req.source, req.offset, c.caps.enc); - var cx: Cx = .{ .arena = arena, .base = req.root, .cur_path = req.path, .cur_src = req.source, .out = out, .relative_parents = req.kind == .callstack, .callstack_corners = req.callstack_corners }; + var cx: Cx = .{ .arena = arena, .base = req.root, .cur_path = req.path, .cur_src = req.source, .out = out, .fixed_out = true, .relative_parents = req.kind == .callstack, .callstack_corners = req.callstack_corners }; for (req.others) |doc| try cx.files.append(arena, .{ .path = doc.path, .text = doc.source }); tr.note("server {s} (pid {d}), root {s}, {s} columns", .{ @tagName(c.state), c.pid, c.root, @tagName(c.caps.enc), @@ -540,7 +577,7 @@ fn run(c: *Conn, si: usize, arena: std.mem.Allocator, req: lsp.Req, out: *std.Io var b = try atPos(arena, uri.items, pos); if (kind == .references) try app(&b, arena, ",\"context\":{\"includeDeclaration\":true}"); tr.note("-> {s} @ {d}:{d}", .{ method, pos.line + 1, pos.ch + 1 }); - const result = (try call(c, arena, method, b.items, deadline)) orelse { + const result = (try call(c, io, arena, method, b.items, deadline)) orelse { tr.note("<- empty (no result, an error response, or null)", .{}); return; }; @@ -549,12 +586,12 @@ fn run(c: *Conn, si: usize, arena: std.mem.Allocator, req: lsp.Req, out: *std.Io }, .select_refs => { const b = try atPos(arena, uri.items, pos); - const result = (try call(c, arena, "textDocument/documentHighlight", b.items, deadline)) orelse return; + const result = (try call(c, io, arena, "textDocument/documentHighlight", b.items, deadline)) orelse return; for (items(result)) |h| try emitRange(&cx, c.caps.enc, uri.items, get(h, "range"), ""); }, .hover => { const b = try atPos(arena, uri.items, pos); - const result = (try call(c, arena, "textDocument/hover", b.items, deadline)) orelse return; + const result = (try call(c, io, arena, "textDocument/hover", b.items, deadline)) orelse return; const contents = get(result, "contents") orelse return; const text = str(contents) orelse str(get(contents, "value")) orelse blk: { for (items(contents)) |m| if (str(m) orelse str(get(m, "value"))) |t| break :blk t; @@ -569,26 +606,26 @@ fn run(c: *Conn, si: usize, arena: std.mem.Allocator, req: lsp.Req, out: *std.Io try app(&b, arena, "\"textDocument\":{\"uri\":"); try jstr(&b, arena, uri.items); try app(&b, arena, "}"); - const result = (try call(c, arena, "textDocument/documentSymbol", b.items, deadline)) orelse return; + const result = (try call(c, io, arena, "textDocument/documentSymbol", b.items, deadline)) orelse return; try walkSymbols(&cx, c.caps.enc, uri.items, result, 0); }, .workspace_symbols => { var b: std.ArrayList(u8) = .empty; try app(&b, arena, "\"query\":"); try jstr(&b, arena, req.arg); - const result = (try call(c, arena, "workspace/symbol", b.items, deadline)) orelse return; + const result = (try call(c, io, arena, "workspace/symbol", b.items, deadline)) orelse return; for (items(result)) |sym| { const loc = get(sym, "location") orelse continue; try emitRange(&cx, c.caps.enc, str(get(loc, "uri")) orelse continue, get(loc, "range"), str(get(sym, "name")) orelse ""); } }, - .diagnostics => try diagnostics(c, arena, &cx, uri.items, deadline), - .workspace_diagnostics => try workspaceDiagnostics(c, arena, &cx, deadline), + .diagnostics => try diagnostics(c, io, arena, &cx, uri.items, deadline), + .workspace_diagnostics => try workspaceDiagnostics(c, io, arena, &cx, deadline), .rename => { var b = try atPos(arena, uri.items, pos); try app(&b, arena, ",\"newName\":"); try jstr(&b, arena, req.arg); - const result = (try call(c, arena, "textDocument/rename", b.items, deadline)) orelse return; + const result = (try call(c, io, arena, "textDocument/rename", b.items, deadline)) orelse return; // Other open files that say the old name, should the server // answer for this file alone (zls renaming at a declaration does, // whatever it was told): applied here, they would no longer build. @@ -603,7 +640,7 @@ fn run(c: *Conn, si: usize, arena: std.mem.Allocator, req: lsp.Req, out: *std.Io try app(&b, arena, "\"textDocument\":{\"uri\":"); try jstr(&b, arena, uri.items); try app(&b, arena, "},\"options\":{\"tabSize\":4,\"insertSpaces\":true}"); - const result = (try call(c, arena, "textDocument/formatting", b.items, deadline)) orelse return; + const result = (try call(c, io, arena, "textDocument/formatting", b.items, deadline)) orelse return; try formatEdits(&cx, c.caps.enc, result, req.source); }, .code_action => { @@ -611,7 +648,7 @@ fn run(c: *Conn, si: usize, arena: std.mem.Allocator, req: lsp.Req, out: *std.Io try app(&b, arena, "\"textDocument\":{\"uri\":"); try jstr(&b, arena, uri.items); try b.print(arena, "}},\"range\":{{\"start\":{{\"line\":{d},\"character\":{d}}},\"end\":{{\"line\":{d},\"character\":{d}}}}},\"context\":{{\"diagnostics\":[]}}", .{ pos.line, pos.ch, pos.line, pos.ch }); - const result = (try call(c, arena, "textDocument/codeAction", b.items, deadline)) orelse return; + const result = (try call(c, io, arena, "textDocument/codeAction", b.items, deadline)) orelse return; for (items(result)) |ca| { const title = str(get(ca, "title")) orelse continue; try lsp.row(cx.out, lsp.rel(cx.base, cx.cur_path), pos.line, 0, flat(arena, title)); @@ -621,7 +658,7 @@ fn run(c: *Conn, si: usize, arena: std.mem.Allocator, req: lsp.Req, out: *std.Io .completion => { var b = try atPos(arena, uri.items, pos); try app(&b, arena, ",\"context\":{\"triggerKind\":1}"); - const result = (try call(c, arena, "textDocument/completion", b.items, deadline)) orelse return; + const result = (try call(c, io, arena, "textDocument/completion", b.items, deadline)) orelse return; const list = if (get(result, "items")) |it| items(it) else items(result); const here = lsp.rel(cx.base, cx.cur_path); var n: usize = 0; @@ -643,11 +680,11 @@ fn run(c: *Conn, si: usize, arena: std.mem.Allocator, req: lsp.Req, out: *std.Io n += 1; } }, - .callstack => try callstack(c, si, arena, &cx, uri.items, pos, deadline, tr, req.callstack_depth), - .incoming_calls => try hierarchy(c, si, arena, &cx, uri.items, pos, deadline, .incoming, tr), - .outgoing_calls => try hierarchy(c, si, arena, &cx, uri.items, pos, deadline, .outgoing, tr), - .supertypes => try hierarchy(c, si, arena, &cx, uri.items, pos, deadline, .supers, tr), - .subtypes => try hierarchy(c, si, arena, &cx, uri.items, pos, deadline, .subs, tr), + .callstack => try callstack(c, io, si, arena, &cx, uri.items, pos, deadline, tr, req.callstack_depth, req.budget, req.arg), + .incoming_calls => try hierarchy(c, io, si, arena, &cx, uri.items, pos, deadline, .incoming, tr), + .outgoing_calls => try hierarchy(c, io, si, arena, &cx, uri.items, pos, deadline, .outgoing, tr), + .supertypes => try hierarchy(c, io, si, arena, &cx, uri.items, pos, deadline, .supers, tr), + .subtypes => try hierarchy(c, io, si, arena, &cx, uri.items, pos, deadline, .subs, tr), .status, .explain => unreachable, } } @@ -687,13 +724,13 @@ fn walkSymbols(cx: *Cx, enc: Enc, uri: []const u8, node: std.json.Value, depth: /// Pull when the server does (LSP 3.17), the push store otherwise. The store /// path waits briefly for a publish that postdates the didChange we just /// sent, so `]d` right after an edit sees the new truth, not the old one. -fn diagnostics(c: *Conn, arena: std.mem.Allocator, cx: *Cx, uri: []const u8, deadline: i64) Err!void { +fn diagnostics(c: *Conn, io: std.Io, arena: std.mem.Allocator, cx: *Cx, uri: []const u8, deadline: i64) Err!void { if (c.caps.pull) { var b: std.ArrayList(u8) = .empty; try app(&b, arena, "\"textDocument\":{\"uri\":"); try jstr(&b, arena, uri); try app(&b, arena, "}"); - const result = (try call(c, arena, "textDocument/diagnostic", b.items, deadline)) orelse return; + const result = (try call(c, io, arena, "textDocument/diagnostic", b.items, deadline)) orelse return; for (items(get(result, "items"))) |dg| try emitDiag(cx, c.caps.enc, uri, dg, arena); return; } @@ -702,13 +739,13 @@ fn diagnostics(c: *Conn, arena: std.mem.Allocator, cx: *Cx, uri: []const u8, dea stale = d.stale; break; }; - if (stale) waitFresh(c, uri, nowMs() + diag_ms); + if (stale) try waitFresh(c, io, uri, nowMs() + diag_ms); try renderStore(c, arena, cx, uri); } -fn workspaceDiagnostics(c: *Conn, arena: std.mem.Allocator, cx: *Cx, deadline: i64) Err!void { +fn workspaceDiagnostics(c: *Conn, io: std.Io, arena: std.mem.Allocator, cx: *Cx, deadline: i64) Err!void { if (c.caps.pull_workspace) { - const result = (try call(c, arena, "workspace/diagnostic", "\"previousResultIds\":[]", deadline)) orelse return; + const result = (try call(c, io, arena, "workspace/diagnostic", "\"previousResultIds\":[]", deadline)) orelse return; for (items(get(result, "items"))) |per| { const uri = str(get(per, "uri")) orelse continue; for (items(get(per, "items"))) |dg| try emitDiag(cx, c.caps.enc, uri, dg, arena); @@ -741,7 +778,7 @@ fn renderStore(c: *Conn, arena: std.mem.Allocator, cx: *Cx, only_uri: ?[]const u /// Block (mutex released) until the reader marks `uri` fresh or the deadline /// passes. The reader broadcasts on every publishDiagnostics. -fn waitFresh(c: *Conn, uri: []const u8, deadline: i64) void { +fn waitFresh(c: *Conn, io: std.Io, uri: []const u8, deadline: i64) error{Canceled}!void { const g = c.gen; while (c.gen == g and c.alive()) { var fresh = false; @@ -750,7 +787,7 @@ fn waitFresh(c: *Conn, uri: []const u8, deadline: i64) void { break; }; if (fresh) return; - if (!timedWait(c, deadline)) return; + if (!try timedWait(c, io, deadline)) return; } } @@ -873,18 +910,21 @@ fn sortEdits(edits: []PutEdit) void { /// A bounded static hierarchy. Reuse the prepared item verbatim (including /// server data), and retain every call-site range rather than just a declaration. -fn hierarchyResult(c: *Conn, arena: std.mem.Allocator, item: std.json.Value, method: []const u8, deadline: i64) Err!?std.json.Value { +fn hierarchyResult(c: *Conn, io: std.Io, arena: std.mem.Allocator, item: std.json.Value, method: []const u8, deadline: i64) Err!?std.json.Value { if (jsonDepth(item, 0) > 96) return null; var body: std.ArrayList(u8) = .empty; try app(&body, arena, "\"item\":"); try app(&body, arena, std.json.Stringify.valueAlloc(arena, item, .{}) catch return error.OutOfMemory); - return call(c, arena, method, body.items, deadline); + return call(c, io, arena, method, body.items, deadline); } const CallTree = struct { - const Site = struct { range: std.json.Value, focus: bool }; + /// What a node keeps of the server's item: its own copies, so the + /// response it came in is freed once its subtree is walked. + const Call = struct { uri: []const u8, name: []const u8, at: Range }; + const Site = struct { range: Range, focus: bool }; const Node = struct { - item: std.json.Value, + call: Call, ranges: std.ArrayList(Site) = .empty, children: std.ArrayList(usize) = .empty, cycle: bool = false, @@ -893,10 +933,39 @@ const CallTree = struct { roots: std.ArrayList(usize) = .empty, path: [lsp.callstack_max_depth]std.json.Value = undefined, depth_limit: usize = lsp.callstack_default_depth, - visited: usize = 0, limited: bool = false, + out_of_time: bool = false, + out_of_memory: bool = false, + budget: ?*const std.heap.FixedBufferAllocator = null, + si: usize = 0, + collected: usize = 0, + started_ms: i64 = 0, + narrated: bool = false, siblings: [lsp.callstack_max_depth]bool = @splat(false), rendered: usize = 0, + /// Paging. A page starts at `start`, a path of entry indices from the + /// top (empty: the start), skipping what is before it at each level; + /// `rows` and `bytes` count what rendering takes, and the walk stops + /// before their caps at `cut`, which the next page starts at (`more`). + /// The ancestors on the path are shown again on it, as context. + start: [lsp.callstack_max_depth]u32 = undefined, + start_len: usize = 0, + at: [lsp.callstack_max_depth]u32 = undefined, + cut: [lsp.callstack_max_depth]u32 = undefined, + cut_len: usize = 0, + more: bool = false, + rows: usize = 0, + row_cap: usize = max_rows - 16, + /// The bytes those rows take, over-estimated (the uri for the path it + /// becomes), kept under the answer writer's room. + bytes: usize = 0, + byte_cap: usize = std.math.maxInt(usize), + + /// A row of a caller at `depth`: its tree columns, the uri the path is + /// made from, the name, and room for the address. + fn rowBytes(depth: usize, caller: Call) usize { + return 5 * (depth + 2) + caller.uri.len + caller.name.len + 40; + } /// Incoming paths arrive nearest-first. Insert them outermost-first, /// sharing common caller prefixes and retaining all their call sites. @@ -909,11 +978,14 @@ const CallTree = struct { const item = get(entry, "from").?; const children = if (parent) |id| tree.nodes.items[id].children.items else tree.roots.items; const found = for (children) |id| { - if (sameCall(tree.nodes.items[id].item, item)) break id; + if (sameCall(tree.nodes.items[id].call, item)) break id; } else null; + const depth = path.len - 1 - at; const id = found orelse blk: { const id = tree.nodes.items.len; - try tree.nodes.append(arena, .{ .item = item }); + try tree.nodes.append(arena, .{ .call = try callOf(arena, item) }); + tree.rows += 1; + tree.bytes += rowBytes(depth, tree.nodes.items[id].call); if (parent) |pid| { try tree.nodes.items[pid].children.append(arena, id); } else try tree.roots.append(arena, id); @@ -924,23 +996,39 @@ const CallTree = struct { for (items(get(entry, "fromRanges"))) |range| { const parsed = rangeOf(range) orelse continue; for (node.ranges.items) |*other| { - if (std.meta.eql(parsed, rangeOf(other.range).?)) { + if (std.meta.eql(parsed, other.range)) { other.focus = other.focus or at == 0; break; } - } else try node.ranges.append(arena, .{ .range = range, .focus = at == 0 }); + } else { + try node.ranges.append(arena, .{ .range = parsed, .focus = at == 0 }); + tree.rows += 1; + tree.bytes += rowBytes(depth + 1, .{ .uri = node.call.uri, .name = "", .at = parsed }); + } } parent = id; } } }; -fn sameCall(a: std.json.Value, b: std.json.Value) bool { - const au = str(get(a, "uri")) orelse return false; +fn callOf(arena: std.mem.Allocator, item: std.json.Value) Err!CallTree.Call { + return .{ + .uri = try arena.dupe(u8, str(get(item, "uri")).?), + .name = try arena.dupe(u8, str(get(item, "name")) orelse "(unnamed)"), + .at = rangeOf(get(item, "selectionRange") orelse get(item, "range")).?, + }; +} + +fn sameCall(a: CallTree.Call, b: std.json.Value) bool { const bu = str(get(b, "uri")) orelse return false; - const ar = rangeOf(get(a, "selectionRange") orelse get(a, "range")) orelse return false; const br = rangeOf(get(b, "selectionRange") orelse get(b, "range")) orelse return false; - return std.mem.eql(u8, au, bu) and std.meta.eql(ar, br); + return std.mem.eql(u8, a.uri, bu) and std.meta.eql(a.at, br); +} + +fn sameItem(a: std.json.Value, b: std.json.Value) bool { + const au = str(get(a, "uri")) orelse return false; + const ar = rangeOf(get(a, "selectionRange") orelse get(a, "range")) orelse return false; + return sameCall(.{ .uri = au, .name = "", .at = ar }, b); } fn callPrefix(out: *std.Io.Writer, tree: *const CallTree, depth: usize) Err!void { @@ -954,44 +1042,115 @@ fn validCaller(entry: std.json.Value) bool { rangeOf(get(from, "selectionRange") orelse get(from, "range")) != null; } -fn callstack(c: *Conn, si: usize, arena: std.mem.Allocator, cx: *Cx, uri: []const u8, pos: Pos, deadline: i64, tr: *Trace, max_depth: u8) Err!void { +fn callstack(c: *Conn, io: std.Io, si: usize, arena: std.mem.Allocator, cx: *Cx, uri: []const u8, pos: Pos, deadline: i64, tr: *Trace, max_depth: u8, budget: ?*const std.heap.FixedBufferAllocator, arg: []const u8) Err!void { if (!c.caps.call_hier) return lsp.none(cx.out, "{s} does not answer call hierarchy (no callHierarchyProvider)", .{specs[si].name}); const b = try atPos(arena, uri, pos); - const prepared = (try call(c, arena, "textDocument/prepareCallHierarchy", b.items, deadline)) orelse return; + const prepared = (try call(c, io, arena, "textDocument/prepareCallHierarchy", b.items, deadline)) orelse return; if (items(prepared).len == 0) return lsp.none(cx.out, "no function at this position", .{}); + // The rows come from the tree alone: the core reads the sources. + cx.no_text = true; + // Each response is parsed into its own part of the region, freed once + // its subtree is walked; only the path being walked is live JSON. + // Raw, as query()'s scratch: `alloc` would fill all ~100 MB of it. + const parse_len = if (budget) |fixed| (fixed.buffer.len - fixed.end_index) / 2 else 0; + var parse_fba: std.heap.FixedBufferAllocator = .init(if (budget != null) + (arena.rawAlloc(parse_len, .of(u8), @returnAddress()) orelse return error.OutOfMemory)[0..parse_len] + else + &.{}); + const parse = if (budget != null) parse_fba.allocator() else arena; for (items(prepared)) |item| { - var tree: CallTree = .{ .depth_limit = std.math.clamp(max_depth, 1, lsp.callstack_max_depth) }; - const incoming = try hierarchyResult(c, arena, item, "callHierarchy/incomingCalls", deadline); - const count = try collectCallers(c, arena, item, incoming, deadline, &tree, 0); - if (count == 0) try cx.out.writeAll("No callers reported\n"); + var tree: CallTree = .{ + .depth_limit = std.math.clamp(max_depth, 1, lsp.callstack_max_depth), + .si = si, + .started_ms = nowMs(), + .budget = budget, + // The page ends while the answer's writer has room for the rest. + .byte_cap = if (cx.fixed_out) (cx.out.buffer.len - cx.out.end) -| (1 << 20) else std.math.maxInt(usize), + }; + var steps = std.mem.tokenizeScalar(u8, std.mem.trim(u8, arg, " \n"), '.'); + while (steps.next()) |step| { + if (tree.start_len == tree.start.len) break; + tree.start[tree.start_len] = std.fmt.parseInt(u32, step, 10) catch break; + tree.start_len += 1; + } + const incoming = try hierarchyResult(c, io, parse, item, "callHierarchy/incomingCalls", deadline); + const count = try collectCallers(c, io, arena, if (budget != null) &parse_fba else null, item, incoming, &tree, 0, tree.start_len > 0); + if (tree.narrated) post(si, .always, "Callstack: {d} callers", .{tree.collected}); + if (count == 0 and tree.start_len == 0) try cx.out.writeAll("No callers reported\n"); try renderCallers(cx, c.caps.enc, &tree, tree.roots.items, 0); - if (tree.limited) try cx.out.writeAll("… continue from a function above with Callstack\n"); + if (tree.more) { + try cx.out.writeAll(lsp.callstack_more); + for (tree.cut[0..tree.cut_len], 0..) |index, level| try cx.out.print("{s}{d}", .{ if (level == 0) "" else ".", index }); + try cx.out.print(" {d}\n", .{tree.collected}); + } else if (tree.out_of_time) { + try cx.out.writeAll("… the language server ran out of time; continue from a function above with Callstack\n"); + } else if (tree.out_of_memory) { + try cx.out.writeAll("… stopped at the query's memory limit; continue from a function above with Callstack\n"); + } else if (tree.limited) try cx.out.writeAll("… continue from a function above with Callstack\n"); tr.note("callstack: {d} callers", .{tree.rendered}); } } -fn collectCallers(c: *Conn, arena: std.mem.Allocator, focus: std.json.Value, incoming: ?std.json.Value, deadline: i64, tree: *CallTree, depth: usize) Err!usize { +/// No caller count and no overall deadline: the walk narrates itself on the +/// message row after a second, and it stops when a request goes unanswered +/// (what was collected is shown), when the page is full (the rest is the +/// next page), or when the shell cancels it for a newer query. +fn collectCallers(c: *Conn, io: std.Io, arena: std.mem.Allocator, parse: ?*std.heap.FixedBufferAllocator, focus: std.json.Value, incoming: ?std.json.Value, tree: *CallTree, depth: usize, on_path: bool) Err!usize { var count: usize = 0; - for (items(incoming)) |entry| { - if (tree.visited >= 64) { - tree.limited = true; - break; + for (items(incoming), 0..) |entry, index| { + // A later page skips what the pages before it walked. + const resuming = on_path and depth < tree.start_len; + if (resuming and index < tree.start[depth]) continue; + tree.at[depth] = @intCast(index); + if (tree.budget) |b| if (b.buffer.len - b.end_index < callstack_reserve) { + tree.out_of_memory = true; + }; + if (!tree.more and (tree.rows >= tree.row_cap or tree.bytes >= tree.byte_cap or tree.out_of_memory)) { + // The page is full: the next goes on here. Never where this + // one began, which would page in place: past that entry. + tree.more = true; + tree.cut_len = depth + 1; + @memcpy(tree.cut[0..tree.cut_len], tree.at[0..tree.cut_len]); + if (tree.cut_len == tree.start_len and std.mem.eql(u32, tree.cut[0..tree.cut_len], tree.start[0..tree.start_len])) + tree.cut[depth] += 1; } + if (tree.out_of_time or tree.more) break; if (!validCaller(entry)) continue; const from = get(entry, "from").?; - const cycle = sameCall(focus, from) or for (tree.path[0..depth]) |ancestor| { - if (sameCall(get(ancestor, "from").?, from)) break true; + const cycle = sameItem(focus, from) or for (tree.path[0..depth]) |ancestor| { + if (sameItem(get(ancestor, "from").?, from)) break true; } else false; tree.path[depth] = entry; - tree.visited += 1; count += 1; + tree.collected += 1; + if (nowMs() - tree.started_ms >= 1000) { + tree.narrated = true; + post(tree.si, .chatty, "Callstack: {d} callers\u{2026}", .{tree.collected}); + } var children: usize = 0; if (!cycle) { - if (depth + 1 == tree.depth_limit or tree.visited >= 64) { + if (depth + 1 == tree.depth_limit) { tree.limited = true; } else { - const ancestors = try hierarchyResult(c, arena, from, "callHierarchy/incomingCalls", deadline); - children = try collectCallers(c, arena, focus, ancestors, deadline, tree, depth + 1); + const mark = if (parse) |fixed| fixed.end_index else 0; + defer if (parse) |fixed| { + fixed.end_index = mark; + }; + const ancestors = hierarchyResult(c, io, if (parse) |fixed| fixed.allocator() else arena, from, "callHierarchy/incomingCalls", nowMs() + req_ms) catch |e| switch (e) { + error.Timeout => blk: { + tree.out_of_time = true; + break :blk null; + }, + // A response bigger than the parse region: this caller + // stops here, the page with it. + error.OutOfMemory => blk: { + tree.out_of_memory = true; + break :blk null; + }, + else => return e, + }; + const deeper = resuming and index == tree.start[depth] and depth + 1 < tree.start_len; + if (!tree.out_of_time and !tree.out_of_memory) children = try collectCallers(c, io, arena, parse, focus, ancestors, tree, depth + 1, deeper); } } if (children == 0) try tree.addPath(arena, tree.path[0 .. depth + 1], cycle); @@ -999,51 +1158,61 @@ fn collectCallers(c: *Conn, arena: std.mem.Allocator, focus: std.json.Value, inc return count; } +/// Test callers sink below the rest; each group keeps the usual order. +// ponytail: substring heuristic, "latest.zig" or "contest" count as tests too +fn testCaller(caller: CallTree.Call) bool { + return std.ascii.findIgnoreCase(caller.name, "test") != null or + std.ascii.findIgnoreCase(std.fs.path.basenamePosix(caller.uri), "test") != null; +} + fn callerLess(tree: *const CallTree, a: usize, b: usize) bool { - const left = tree.nodes.items[a].item; - const right = tree.nodes.items[b].item; - const uri_order = std.mem.order(u8, str(get(left, "uri")).?, str(get(right, "uri")).?); + const left = tree.nodes.items[a].call; + const right = tree.nodes.items[b].call; + if (testCaller(left) != testCaller(right)) return testCaller(right); + const uri_order = std.mem.order(u8, left.uri, right.uri); if (uri_order != .eq) return uri_order == .lt; - return callRangeLess({}, get(left, "selectionRange") orelse get(left, "range").?, get(right, "selectionRange") orelse get(right, "range").?); + return rangeLess(left.at, right.at); } -fn callRangeLess(_: void, a: std.json.Value, b: std.json.Value) bool { - const left = rangeOf(a).?; - const right = rangeOf(b).?; +fn rangeLess(left: Range, right: Range) bool { return left.sl < right.sl or (left.sl == right.sl and left.sc < right.sc); } fn renderCallers(cx: *Cx, enc: Enc, tree: *CallTree, children: []usize, depth: usize) Err!void { std.mem.sort(usize, children, @as(*const CallTree, tree), callerLess); for (children, 0..) |id, index| { - if (tree.rendered >= 64) { + // emitRange's row ceiling and the writer's room, met here before a + // prefix is half written + if (cx.rows >= max_rows or (cx.fixed_out and cx.out.buffer.len - cx.out.end < row_room)) { tree.limited = true; return; } const node = &tree.nodes.items[id]; - const item = node.item; - const uri = str(get(item, "uri")).?; const more = index + 1 < children.len; try callPrefix(cx.out, tree, depth); const has_children = node.children.items.len > 0 or node.ranges.items.len > 0; const rounded = cx.callstack_corners == .rounded; try cx.out.writeAll(if (more) "├" else if (rounded) "╰" else "└"); try cx.out.writeAll(if (has_children) "──┬ " else "─── "); - const name = flat(cx.arena, str(get(item, "name")) orelse "(unnamed)"); + const name = flat(cx.arena, node.call.name); const label = if (node.cycle) try std.fmt.allocPrint(cx.arena, "{s} ↻ recursion", .{name}) else name; - try emitRange(cx, enc, uri, get(item, "selectionRange") orelse get(item, "range"), label); + try emitAt(cx, enc, node.call.uri, node.call.at, label); tree.rendered += 1; tree.siblings[depth] = more; std.mem.sort(CallTree.Site, node.ranges.items, {}, struct { fn less(_: void, a: CallTree.Site, b: CallTree.Site) bool { - return callRangeLess({}, a.range, b.range); + return rangeLess(a.range, b.range); } }.less); for (node.ranges.items, 0..) |site, site_index| { + if (cx.rows >= max_rows or (cx.fixed_out and cx.out.buffer.len - cx.out.end < row_room)) { + tree.limited = true; + return; + } if (site.focus) try cx.out.writeAll(lsp.callstack_match); try callPrefix(cx.out, tree, depth + 1); try cx.out.writeAll(if (node.children.items.len > 0 or site_index + 1 < node.ranges.items.len) "├─ " else if (rounded) "╰─ " else "└─ "); - try emitRange(cx, enc, uri, site.range, ""); + try emitAt(cx, enc, node.call.uri, site.range, ""); } try renderCallers(cx, enc, tree, node.children.items, depth + 1); } @@ -1054,7 +1223,7 @@ const Hier = enum { incoming, outgoing, supers, subs }; /// The two-step hierarchy kinds: prepare at the cursor, then follow every /// item the server returned (usually one). Gated on the server capability so /// an old server costs zero round trips. -fn hierarchy(c: *Conn, si: usize, arena: std.mem.Allocator, cx: *Cx, uri: []const u8, pos: Pos, deadline: i64, h: Hier, tr: *Trace) Err!void { +fn hierarchy(c: *Conn, io: std.Io, si: usize, arena: std.mem.Allocator, cx: *Cx, uri: []const u8, pos: Pos, deadline: i64, h: Hier, tr: *Trace) Err!void { const call_side = h == .incoming or h == .outgoing; if (call_side and !c.caps.call_hier) { tr.note("STOP: {s} does not advertise callHierarchyProvider", .{specs[si].name}); @@ -1072,9 +1241,9 @@ fn hierarchy(c: *Conn, si: usize, arena: std.mem.Allocator, cx: *Cx, uri: []cons .subs => "typeHierarchy/subtypes", }; const b = try atPos(arena, uri, pos); - const prepared = (try call(c, arena, prepare, b.items, deadline)) orelse return; + const prepared = (try call(c, io, arena, prepare, b.items, deadline)) orelse return; for (items(prepared)) |item| { - const result = (try hierarchyResult(c, arena, item, follow, deadline)) orelse return; + const result = (try hierarchyResult(c, io, arena, item, follow, deadline)) orelse return; for (items(result)) |entry| switch (h) { .incoming => { // one row per CALL SITE, under the caller's name — that is @@ -1134,6 +1303,10 @@ const Cx = struct { cur_path: []const u8, cur_src: []const u8, out: *std.Io.Writer, + /// `out` is the query's fixed answer buffer, whose room is checked. + fixed_out: bool = false, + /// Rows without their source text (Callstack: the core reads it). + no_text: bool = false, rows: usize = 0, relative_parents: bool = false, callstack_corners: lsp.CallstackCorners = .rounded, @@ -1169,11 +1342,16 @@ const Cx = struct { /// columns, and a single-line range becomes the `path:LINE:COL-ENDCOL` form a /// look SELECTS. `note` overrides the source line as the row's text. fn emitRange(cx: *Cx, enc: Enc, uri: []const u8, range: ?std.json.Value, note: []const u8) Err!void { + return emitAt(cx, enc, uri, rangeOf(range) orelse return, note); +} + +fn emitAt(cx: *Cx, enc: Enc, uri: []const u8, r: Range, note: []const u8) Err!void { if (cx.rows >= max_rows) return; const path = pathOf(cx.arena, uri) orelse return; if (path.len == 0 or path[0] != '/') return; // rows promise absolute-or-rel-from-base - const r = rangeOf(range) orelse return; - const src = cx.text(path); + // Without sources (Callstack) the asking file is still known: its rows' + // columns convert from utf-16 as ever. + const src = if (cx.no_text and !std.mem.eql(u8, path, cx.cur_path)) null else cx.text(path); var bol: usize = 0; var eol: usize = 0; @@ -1323,7 +1501,8 @@ fn transportPair(sv: *[2]libc.fd_t) bool { /// Spawn-or-return, and tell an existing server about a new project root. /// Returns the generation the caller's whole query is bound to. -fn ensure(c: *Conn, si: usize, arena: std.mem.Allocator, req: lsp.Req, tr: *Trace) Err!u32 { +fn ensure(c: *Conn, io: std.Io, si: usize, arena: std.mem.Allocator, req: lsp.Req, tr: *Trace) Err!u32 { + c.si = si; if (c.state == .disabled) { tr.note("STOP: {s} is disabled for this session (no binary; set {s})", .{ specs[si].name, specs[si].env }); return error.NoServer; @@ -1341,7 +1520,7 @@ fn ensure(c: *Conn, si: usize, arena: std.mem.Allocator, req: lsp.Req, tr: *Trac try app(&b, arena, "{\"jsonrpc\":\"2.0\",\"method\":\"workspace/didChangeWorkspaceFolders\",\"params\":{\"event\":{\"added\":[{\"name\":\"root\",\"uri\":\""); try uriOf(&b, arena, root); try app(&b, arena, "\"}],\"removed\":[]}}}"); - try frame(c.sock, b.items, nowMs() + reply_ms); + try send(c, io, b.items, nowMs() + wedge_ms); const owned = sa.dupe(u8, root) catch return error.OutOfMemory; c.extra_roots.append(sa, owned) catch sa.free(owned); } @@ -1430,12 +1609,13 @@ fn ensure(c: *Conn, si: usize, arena: std.mem.Allocator, req: lsp.Req, tr: *Trac if (c.resp) |r| sa.free(r); c.resp = null; c.progress = 0; + c.loading = false; c.timeouts = 0; forgetDocs(c); if (c.root.len > 0) sa.free(c.root); c.root = owned_root; - const th = std.Thread.spawn(.{}, reader, .{ si, g, sv[0] }) catch { + const th = std.Thread.spawn(.{}, reader, .{ io, si, g, sv[0] }) catch { // no reader means nobody would ever close the fd our way; do it here, // before anything else can see the conn _ = libc.close(sv[0]); @@ -1450,8 +1630,14 @@ fn ensure(c: *Conn, si: usize, arena: std.mem.Allocator, req: lsp.Req, tr: *Trac post(si, .always, "{s} starting — {s}", .{ specs[si].name, root }); tr.note("spawned {s} (pid {d}) at {s}", .{ specs[si].name, pid, root }); - handshake(c, arena, root) catch |e| { - shutdownIf(c, g); + // A start runs to the end however soon the query that began it is + // canceled: killing a half-started server would only make the next + // query start it again. The cancel lands at the next wait instead. + const protection = io.swapCancelProtection(.blocked); + const started = handshake(c, io, arena, root); + _ = io.swapCancelProtection(protection); + started catch |e| { + shutdownIf(c, io, g); // NOT a session disable. A handshake that misses the deadline is // routinely environmental — a rustup shim deciding to download the // project's pinned toolchain before launching the real server was @@ -1477,7 +1663,7 @@ fn ensure(c: *Conn, si: usize, arena: std.mem.Allocator, req: lsp.Req, tr: *Trac return g; } -fn handshake(c: *Conn, arena: std.mem.Allocator, root: []const u8) Err!void { +fn handshake(c: *Conn, io: std.Io, arena: std.mem.Allocator, root: []const u8) Err!void { var b: std.ArrayList(u8) = .empty; try b.print(arena, "\"processId\":{d},\"clientInfo\":{{\"name\":\"pardes\"}},\"rootUri\":\"", .{@as(u32, @bitCast(libc.getpid()))}); try uriOf(&b, arena, root); @@ -1509,7 +1695,7 @@ fn handshake(c: *Conn, arena: std.mem.Allocator, root: []const u8) Err!void { for (b.items) |ch| if (ch != '\n') try body.append(arena, ch); const deadline = nowMs() + init_ms; - const reply = (try call(c, arena, "initialize", body.items, deadline)) orelse return error.Protocol; + const reply = (try call(c, io, arena, "initialize", body.items, deadline)) orelse return error.Protocol; const caps = get(reply, "capabilities"); c.caps.enc = if (std.mem.eql(u8, str(get(caps, "positionEncoding")) orelse "utf-16", "utf-8")) .utf8 else .utf16; @@ -1521,7 +1707,7 @@ fn handshake(c: *Conn, arena: std.mem.Allocator, root: []const u8) Err!void { c.caps.type_hier = provider(get(caps, "typeHierarchyProvider")); c.caps.folders = if (get(get(get(caps, "workspace"), "workspaceFolders"), "supported")) |s| s == .bool and s.bool else false; - try frame(c.sock, "{\"jsonrpc\":\"2.0\",\"method\":\"initialized\",\"params\":{}}", deadline); + try send(c, io, "{\"jsonrpc\":\"2.0\",\"method\":\"initialized\",\"params\":{}}", deadline); } /// A server capability that may be `true`, an options object, or absent. @@ -1536,7 +1722,7 @@ fn provider(v: ?std.json.Value) bool { /// didOpen the first time a file is seen, didChange when its bytes moved, /// nothing when they did not — the common case between two presses of gd. -fn syncDoc(c: *Conn, si: usize, arena: std.mem.Allocator, uri: []const u8, src: []const u8) Err!void { +fn syncDoc(c: *Conn, io: std.Io, si: usize, arena: std.mem.Allocator, uri: []const u8, src: []const u8) Err!void { const hash = std.hash.Wyhash.hash(0, src); var doc: ?*Doc = null; for (c.docs.items) |*d| if (std.mem.eql(u8, d.uri, uri)) { @@ -1568,13 +1754,16 @@ fn syncDoc(c: *Conn, si: usize, arena: std.mem.Allocator, uri: []const u8, src: try jstr(&b, arena, src); try app(&b, arena, "}}}"); } - try frame(c.sock, b.items, nowMs() + req_ms); + // A server busy with what it was sent last reads no more meanwhile + // (clangd parses its compile database at a first open): this waits as + // an answer does, for a cancel or a server that has stopped. + try send(c, io, b.items, nowMs() + wedge_ms); } /// Send a request and wait on the mailbox. Returns the parsed `result`, or /// null for an error response / null result — both are legal "no answer". /// Runs with the conn mutex held; the mutex is released inside the wait. -fn call(c: *Conn, arena: std.mem.Allocator, method: []const u8, params: []const u8, deadline: i64) Err!?std.json.Value { +fn call(c: *Conn, io: std.Io, arena: std.mem.Allocator, method: []const u8, params: []const u8, deadline: i64) Err!?std.json.Value { const g = c.gen; const id = c.next_id; c.next_id +%= 1; @@ -1589,17 +1778,36 @@ fn call(c: *Conn, arena: std.mem.Allocator, method: []const u8, params: []const c.want_id = id; defer c.want_id = 0; - try frame(c.sock, b.items, deadline); + try send(c, io, b.items, if (c.state == .ready) nowMs() + wedge_ms else deadline); + // The handshake (still `.starting`) has its deadline. A ready server is + // waited for until it answers or the shell cancels this query for a + // newer one, so the first query after a start is answered, not lost: + // past `deadline` the message row says it is still working, and only + // silent and idle for wedge_ms is it not answering. + var said = false; + var busy_at = nowMs(); while (c.resp == null and c.gen == g and c.alive()) { - if (!timedWait(c, deadline)) break; + const ready = c.state == .ready; + const waiting = timedWait(c, io, if (ready) nowMs() + 500 else deadline) catch |e| { + cancelRequest(c, io, arena, id); + return e; + }; + if (!ready) { + if (waiting) continue; + break; + } + if (c.progress > 0) busy_at = nowMs(); + if (!said and nowMs() >= deadline) { + said = true; + post(c.si, .always, "{s} is still working on it\u{2026}", .{specs[c.si].name}); + } + if (nowMs() - busy_at >= wedge_ms) break; } + if (said and c.resp != null) post(c.si, .always, "{s} answered", .{specs[c.si].name}); if (c.gen != g or !c.alive()) return error.Dead; const raw = c.resp orelse { - // give the server leave to abandon the work we stopped waiting for - var cb: std.ArrayList(u8) = .empty; - cb.print(arena, "{{\"jsonrpc\":\"2.0\",\"method\":\"$/cancelRequest\",\"params\":{{\"id\":{d}}}}}", .{id}) catch return error.Timeout; - frame(c.sock, cb.items, nowMs() + reply_ms) catch {}; + cancelRequest(c, io, arena, id); return error.Timeout; }; c.resp = null; @@ -1609,49 +1817,23 @@ fn call(c: *Conn, arena: std.mem.Allocator, method: []const u8, params: []const if (result == .null) return null; return result; } -/// One bounded cond wait. False when the deadline has passed. -/// -/// The deadline arithmetic everywhere here is CLOCK_MONOTONIC, so the wait -/// must be too: a REALTIME abstime plus an NTP step backwards would park a -/// worker far past `req_ms`, violating the seam's bounded-wait promise. On -/// linux the condvar is lazily initialized with a monotonic condattr; darwin -/// has no setclock but has a RELATIVE wait, which never consults the wall -/// clock at all. -fn timedWait(c: *Conn, deadline: i64) bool { +/// Give the server leave to abandon the work we stopped waiting for. +fn cancelRequest(c: *Conn, io: std.Io, arena: std.mem.Allocator, id: u32) void { + var cb: std.ArrayList(u8) = .empty; + cb.print(arena, "{{\"jsonrpc\":\"2.0\",\"method\":\"$/cancelRequest\",\"params\":{{\"id\":{d}}}}}", .{id}) catch return; + send(c, io, cb.items, nowMs() + reply_ms) catch {}; +} + +/// One bounded cond wait, and a cancelation point: a worker the shell +/// cancels for a newer query stops here. False when the deadline has passed. +fn timedWait(c: *Conn, io: std.Io, deadline: i64) error{Canceled}!bool { const left = deadline - nowMs(); if (left <= 0) return false; const wait_ms = @min(left, 500); // tick so gen/state changes are noticed - if (comptime builtin.os.tag.isDarwin()) { - const rel: libc.timespec = .{ - .sec = @divTrunc(wait_ms, 1000), - .nsec = @rem(wait_ms, 1000) * 1_000_000, - }; - _ = pthread_cond_timedwait_relative_np(&c.cond, &c.mu, &rel); - return true; - } - if (!c.cond_monotonic) { - // lazily re-initialize the zeroed (REALTIME) condvar with a - // monotonic clock; under the mutex, and only before the first wait, - // so no thread can be parked on the old one - var attr: pthread_condattr_t = undefined; - if (pthread_condattr_init(&attr) == 0) { - _ = pthread_condattr_setclock(&attr, CLOCK_MONOTONIC); - _ = pthread_cond_init(&c.cond, &attr); - _ = pthread_condattr_destroy(&attr); - } - c.cond_monotonic = true; - } - var now: libc.timespec = undefined; - _ = libc.clock_gettime(.MONOTONIC, &now); - var abs: libc.timespec = .{ - .sec = now.sec + @divTrunc(wait_ms, 1000), - .nsec = now.nsec + @rem(wait_ms, 1000) * 1_000_000, + c.cond.waitTimeout(io, &c.mu, .{ .duration = .{ .raw = .fromMilliseconds(wait_ms), .clock = .awake } }) catch |e| switch (e) { + error.Timeout => {}, + error.Canceled => return error.Canceled, }; - if (abs.nsec >= 1_000_000_000) { - abs.sec += 1; - abs.nsec -= 1_000_000_000; - } - _ = libc.pthread_cond_timedwait(&c.cond, &c.mu, &abs); return true; } @@ -1659,7 +1841,7 @@ fn timedWait(c: *Conn, deadline: i64) bool { /// respawn that happened during the caller's wait must not be killed for its /// predecessor's crimes. Mutex held. The reader closes the fd; this only /// shuts the transport down and reaps the child. -fn shutdownIf(c: *Conn, g: u32) void { +fn shutdownIf(c: *Conn, io: std.Io, g: u32) void { if (c.gen != g or c.sock < 0) return; _ = libc.shutdown(c.sock, 2); // SHUT_RDWR: the reader sees EOF and closes reap(c.pid); @@ -1669,7 +1851,7 @@ fn shutdownIf(c: *Conn, g: u32) void { forgetDocs(c); if (c.resp) |r| sa.free(r); c.resp = null; - _ = libc.pthread_cond_broadcast(&c.cond); + c.cond.broadcast(io); } /// TERM, a bounded grace, then KILL, to the server's whole process group @@ -1715,6 +1897,7 @@ fn forgetDocs(c: *Conn) void { sa.free(d.body); } c.diags.clearRetainingCapacity(); + c.diag_bytes = 0; } // ------------------------------------------------------------ reader thread @@ -1722,20 +1905,22 @@ fn forgetDocs(c: *Conn) void { /// Owns the read side of one socket for one generation, and is the only /// closer of that fd. Routes responses to the mailbox, answers server /// requests, feeds the diagnostics store, narrates progress. -fn reader(si: usize, g: u32, sock: c_int) void { +fn reader(io: std.Io, si: usize, g: u32, sock: c_int) void { const c = &conns[si]; var buf = sa.alloc(u8, 256 * 1024) catch { - readerExit(c, si, g, sock); + readerExit(c, io, si, g, sock); return; }; defer sa.free(buf); var len: usize = 0; + var parse_arena: std.heap.ArenaAllocator = .init(sa); + defer parse_arena.deinit(); outer: while (true) { // drain every complete frame already buffered drain: while (true) switch (frameNext(buf[0..len])) { .frame => |m| { - dispatch(c, si, g, sock, buf[m.body_start..m.body_end]); + dispatch(c, io, si, g, sock, buf[m.body_start..m.body_end], &parse_arena); std.mem.copyForwards(u8, buf[0 .. len - m.consumed], buf[m.consumed..len]); len -= m.consumed; }, @@ -1761,9 +1946,9 @@ fn reader(si: usize, g: u32, sock: c_int) void { if (pr == 0) { // tick: a respawn while the server was silent leaves this thread // reading a corpse; notice and go - c.lock(); + c.mu.lockUncancelable(io); const stale = c.gen != g; - c.unlock(); + c.mu.unlock(io); if (stale) break :outer; continue; } @@ -1776,11 +1961,11 @@ fn reader(si: usize, g: u32, sock: c_int) void { if (got == 0) break :outer; // the server exited or shutdownIf spoke len += @intCast(got); } - readerExit(c, si, g, sock); + readerExit(c, io, si, g, sock); } -fn readerExit(c: *Conn, si: usize, g: u32, sock: c_int) void { - c.lock(); +fn readerExit(c: *Conn, io: std.Io, si: usize, g: u32, sock: c_int) void { + c.mu.lockUncancelable(io); if (c.gen == g and c.alive()) { // the server died on its own — shutdownIf never saw it, so the corpse // is ours to reap and the conn's transport fields are ours to clear @@ -1800,10 +1985,14 @@ fn readerExit(c: *Conn, si: usize, g: u32, sock: c_int) void { } else { post(si, .always, "{s} exited — restarts on the next query", .{specs[si].name}); } - _ = libc.pthread_cond_broadcast(&c.cond); + c.cond.broadcast(io); } - c.unlock(); + c.mu.unlock(io); + // A query writes with the mutex let go (send): the fd stays its until + // that write is done, and shutdown(2) has already made it fail fast. + c.write_mu.lockUncancelable(io); _ = libc.close(sock); + c.write_mu.unlock(io); } /// 10s doubling to 2min: the fork-per-keystroke guard's schedule. @@ -1845,32 +2034,33 @@ fn frameNext(data: []const u8) FrameStep { /// One message from the server. Parses into a throwaway arena; touches conn /// state only under the mutex; replies never hold it (bounded writes must not /// stall the mailbox). -fn dispatch(c: *Conn, si: usize, g: u32, sock: c_int, raw: []const u8) void { - var arena_state: std.heap.ArenaAllocator = .init(sa); - defer arena_state.deinit(); +fn dispatch(c: *Conn, io: std.Io, si: usize, g: u32, sock: c_int, raw: []const u8, arena_state: *std.heap.ArenaAllocator) void { + // The reader's one parse arena, reset per message: no mapping per + // `$/progress` report, and no more than parse_kept kept between them. + defer _ = arena_state.reset(.{ .retain_with_limit = parse_kept }); const arena = arena_state.allocator(); const v = std.json.parseFromSliceLeaky(std.json.Value, arena, raw, .{}) catch return; if (v != .object) return; if (str(get(v, "method"))) |method| { - if (get(v, "id")) |id| return serverRequest(arena, sock, method, id, get(v, "params")); - return notification(c, si, g, raw, method, get(v, "params")); + if (get(v, "id")) |id| return serverRequest(c, io, arena, sock, method, id, get(v, "params")); + return notification(c, io, si, g, raw, method, get(v, "params")); } // a response: deliver to the one waiting query, if it is still waiting const id = num(get(v, "id")) orelse return; - c.lock(); - defer c.unlock(); + c.mu.lockUncancelable(io); + defer c.mu.unlock(io); if (c.gen == g and c.want_id != 0 and id == c.want_id and c.resp == null) { c.resp = sa.dupe(u8, raw) catch null; - _ = libc.pthread_cond_broadcast(&c.cond); + c.cond.broadcast(io); } } /// The server asked US something. Everything optional was declined in the /// handshake, so a null-ish answer is always legal — but it must ARRIVE, or /// the server blocks forever on its own question. -fn serverRequest(arena: std.mem.Allocator, sock: c_int, method: []const u8, id: std.json.Value, params: ?std.json.Value) void { +fn serverRequest(c: *Conn, io: std.Io, arena: std.mem.Allocator, sock: c_int, method: []const u8, id: std.json.Value, params: ?std.json.Value) void { var b: std.ArrayList(u8) = .empty; app(&b, arena, "{\"jsonrpc\":\"2.0\",\"id\":") catch return; switch (id) { @@ -1890,17 +2080,17 @@ fn serverRequest(arena: std.mem.Allocator, sock: c_int, method: []const u8, id: } else { app(&b, arena, ",\"result\":null}") catch return; } - frame(sock, b.items, nowMs() + reply_ms) catch {}; + answerServer(c, io, sock, b.items); } -fn notification(c: *Conn, si: usize, g: u32, raw: []const u8, method: []const u8, params: ?std.json.Value) void { +fn notification(c: *Conn, io: std.Io, si: usize, g: u32, raw: []const u8, method: []const u8, params: ?std.json.Value) void { if (std.mem.eql(u8, method, "textDocument/publishDiagnostics")) { const uri = str(get(params, "uri")) orelse return; // keep the raw MESSAGE (params included); re-parsing it per query // beats owning a parsed tree past this arena's life const body = sa.dupe(u8, raw) catch return; - c.lock(); - defer c.unlock(); + c.mu.lockUncancelable(io); + defer c.mu.unlock(io); if (c.gen != g) { sa.free(body); return; @@ -1914,10 +2104,25 @@ fn notification(c: *Conn, si: usize, g: u32, raw: []const u8, method: []const u8 slot = d; break; }; + // Bounded in files and bytes: a new set that does not fit pushes + // out the oldest files' (the server sends a file's again when it + // changes); one bigger than the whole store is not kept. + if (body.len > max_diag_bytes) { + sa.free(body); + return; + } if (slot) |d| { + c.diag_bytes -= d.body.len; sa.free(d.body); d.body = body; - } else if (c.diags.items.len < 256) { + c.diag_bytes += body.len; + } else { + while (c.diags.items.len > 0 and (c.diags.items.len >= max_diag_files or c.diag_bytes + body.len > max_diag_bytes)) { + const old = c.diags.orderedRemove(0); + c.diag_bytes -= old.body.len; + sa.free(old.uri); + sa.free(old.body); + } const owned = sa.dupe(u8, uri) catch { sa.free(body); return; @@ -1927,17 +2132,18 @@ fn notification(c: *Conn, si: usize, g: u32, raw: []const u8, method: []const u8 sa.free(body); return; }; - } else sa.free(body); - _ = libc.pthread_cond_broadcast(&c.cond); // waitFresh watches this + c.diag_bytes += body.len; + } + c.cond.broadcast(io); // waitFresh watches this return; } if (std.mem.eql(u8, method, "$/progress")) { const value = get(params, "value") orelse return; const pkind = str(get(value, "kind")) orelse return; const msg = str(get(value, "message")) orelse ""; - c.lock(); + c.mu.lockUncancelable(io); if (c.gen != g) { - c.unlock(); + c.mu.unlock(io); return; } if (std.mem.eql(u8, pkind, "begin")) { @@ -1948,7 +2154,7 @@ fn notification(c: *Conn, si: usize, g: u32, raw: []const u8, method: []const u8 var tbuf: [48]u8 = undefined; const t = tbuf[0..c.title_len]; @memcpy(t, c.title[0..c.title_len]); - c.unlock(); + c.mu.unlock(io); post(si, .chatty, "{s}: {s}\u{2026} {s}", .{ specs[si].name, t, msg }); return; } @@ -1957,7 +2163,7 @@ fn notification(c: *Conn, si: usize, g: u32, raw: []const u8, method: []const u8 const t = tbuf[0..c.title_len]; @memcpy(t, c.title[0..c.title_len]); const pct = num(get(value, "percentage")); - c.unlock(); + c.mu.unlock(io); if (pct) |p| post(si, .chatty, "{s}: {s} {d}% {s}", .{ specs[si].name, t, p, msg }) else @@ -1968,7 +2174,7 @@ fn notification(c: *Conn, si: usize, g: u32, raw: []const u8, method: []const u8 c.progress -= 1; const idle = c.progress <= 0; if (idle) c.progress = 0; - c.unlock(); + 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 if (idle) post(si, .always, "{s}: ready", .{specs[si].name}); @@ -1985,6 +2191,12 @@ fn notification(c: *Conn, si: usize, g: u32, raw: []const u8, method: []const u8 if (std.mem.eql(u8, method, "experimental/serverStatus")) { const health = str(get(params, "health")) orelse "ok"; const quiescent = if (get(params, "quiescent")) |q| q == .bool and q.bool else false; + c.mu.lockUncancelable(io); + if (c.gen == g) { + c.loading = !quiescent; + c.cond.broadcast(io); + } + c.mu.unlock(io); if (!std.mem.eql(u8, health, "ok")) post(si, .always, "{s}: {s} — {s}", .{ specs[si].name, health, str(get(params, "message")) orelse "" }) else if (quiescent) @@ -1995,12 +2207,12 @@ fn notification(c: *Conn, si: usize, g: u32, raw: []const u8, method: []const u8 // ------------------------------------------------------------- introspection -fn status(req: lsp.Req, out: *std.Io.Writer) !void { +fn status(io: std.Io, req: lsp.Req, out: *std.Io.Writer) !void { _ = req; try out.print("\nprotocol servers (lsp-client):\n", .{}); for (&specs, 0..) |*s, i| { const c = &conns[i]; - c.lock(); + c.mu.lockUncancelable(io); const state = c.state; var rootbuf: [256]u8 = undefined; const rootlen = @min(c.root.len, rootbuf.len); @@ -2012,7 +2224,7 @@ fn status(req: lsp.Req, out: *std.Io.Writer) !void { const pull = c.caps.pull; const chier = c.caps.call_hier; const thier = c.caps.type_hier; - c.unlock(); + c.mu.unlock(io); const env_v = if (getenv(s.env)) |v| std.mem.span(v) else null; // Never spawned is not off: the first query of its files starts it. try out.print(" {s:<28} {s}", .{ s.name, if (state == .off) "not started yet (its first query starts it)" else @tagName(state) }); @@ -2069,21 +2281,80 @@ fn atPos(arena: std.mem.Allocator, uri: []const u8, pos: Pos) Err!std.ArrayList( return b; } -fn frame(sock: c_int, body: []const u8, deadline: i64) Err!void { +/// A message to the server from a query, the conn's mutex let go while it is +/// written: the reader goes on taking the server's output meanwhile, which a +/// server may be waiting to write before it reads more of ours. +fn send(c: *Conn, io: std.Io, body: []const u8, deadline: i64) Err!void { + const sock = c.sock; + c.mu.unlock(io); + defer c.mu.lockUncancelable(io); + return frame(c, io, sock, body, deadline); +} + +fn frame(c: *Conn, io: std.Io, sock: c_int, body: []const u8, deadline: i64) Err!void { if (sock < 0) return error.Dead; + c.write_mu.lockUncancelable(io); + defer releaseWrite(c, io, sock); var hdr: [64]u8 = undefined; const h = std.fmt.bufPrint(&hdr, "Content-Length: {d}\r\n\r\n", .{body.len}) catch return error.Protocol; - try sockWrite(sock, h, deadline); - try sockWrite(sock, body, deadline); + var started = false; + try sockWrite(io, sock, h, deadline, &started); + try sockWrite(io, sock, body, deadline, &started); +} + +/// The reader's answer to a server request: written now if the socket is +/// free, else queued for the query writing (bounded; one that does not fit is +/// dropped, and the server's request goes unanswered). +fn answerServer(c: *Conn, io: std.Io, sock: c_int, body: []const u8) void { + var hdr: [64]u8 = undefined; + const h = std.fmt.bufPrint(&hdr, "Content-Length: {d}\r\n\r\n", .{body.len}) catch return; + c.replies_mu.lockUncancelable(io); + const half = &c.replies[c.filling]; + const len = &c.replies_len[c.filling]; + if (len.* + h.len + body.len <= half.len) { + @memcpy(half[len.*..][0..h.len], h); + @memcpy(half[len.* + h.len ..][0..body.len], body); + len.* += h.len + body.len; + } + c.replies_mu.unlock(io); + if (c.write_mu.tryLock()) releaseWrite(c, io, sock); +} + +/// Lets the socket go, first sending what the reader queued meanwhile, and +/// again for what it queues while that goes out. +fn releaseWrite(c: *Conn, io: std.Io, sock: c_int) void { + while (true) { + c.replies_mu.lockUncancelable(io); + const sent = c.filling; + const n = c.replies_len[sent]; + if (n > 0) c.filling ^= 1; + c.replies_mu.unlock(io); + if (n > 0) { + var started = false; + sockWrite(null, sock, c.replies[sent][0..n], nowMs() + reply_ms, &started) catch {}; + c.replies_len[sent] = 0; + } + c.write_mu.unlock(io); + c.replies_mu.lockUncancelable(io); + const more = c.replies_len[c.filling] > 0; + c.replies_mu.unlock(io); + if (!more or !c.write_mu.tryLock()) return; + } } -fn sockWrite(sock: c_int, bytes: []const u8, deadline: i64) Err!void { +/// Writes `bytes`, `started` once any byte of their message is out. Before +/// then, the deadline and a cancel stop it; after, the message is finished +/// however long the server takes to read it (bounded by wedge_ms), since +/// half of one ends the server's reading of every message after it. +fn sockWrite(io: ?std.Io, sock: c_int, bytes: []const u8, deadline: i64, started: *bool) Err!void { var off: usize = 0; while (off < bytes.len) { - const left = deadline - nowMs(); - if (left <= 0) return error.Timeout; + if (!started.*) { + if (deadline - nowMs() <= 0) return error.Timeout; + if (io) |cancel_io| cancel_io.checkCancel() catch return error.Canceled; + } else if (nowMs() - deadline > wedge_ms) return error.Dead; var pfd = [_]libc.pollfd{.{ .fd = sock, .events = POLLOUT, .revents = 0 }}; - const pr = libc.poll(&pfd, 1, @intCast(@min(left, 1000))); + const pr = libc.poll(&pfd, 1, 500); if (pr < 0) { if (libc.errno(pr) == .INTR) continue; return error.Dead; @@ -2096,6 +2367,7 @@ fn sockWrite(sock: c_int, bytes: []const u8, deadline: i64) Err!void { return error.Dead; } if (n == 0) return error.Dead; + started.* = true; off += @intCast(n); } } @@ -2318,7 +2590,7 @@ test "caller trees reverse incoming paths and merge shared callers and sites" { try std.testing.expectEqual(@as(usize, 1), tree.roots.items.len); try std.testing.expectEqual(@as(usize, 4), tree.nodes.items.len); const root = tree.nodes.items[tree.roots.items[0]]; - try std.testing.expectEqualStrings("main", str(get(root.item, "name")).?); + try std.testing.expectEqualStrings("main", root.call.name); try std.testing.expectEqual(@as(usize, 1), root.ranges.items.len); const page = tree.nodes.items[root.children.items[0]]; try std.testing.expectEqual(@as(usize, 2), page.children.items.len); @@ -2355,6 +2627,32 @@ test "caller trees reverse incoming paths and merge shared callers and sites" { try std.testing.expect(recursive.nodes.items[1].cycle); } +test "test callers sort after the rest, each group by place" { + var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena_state.deinit(); + const arena = arena_state.allocator(); + const fixture = try std.json.parseFromSliceLeaky(std.json.Value, arena, "[{\"name\":\"test b\",\"uri\":\"file:///a.zig\",\"selectionRange\":{\"start\":{\"line\":0,\"character\":0},\"end\":{\"line\":0,\"character\":1}}},{\"name\":\"z\",\"uri\":\"file:///b.zig\",\"selectionRange\":{\"start\":{\"line\":0,\"character\":0},\"end\":{\"line\":0,\"character\":1}}},{\"name\":\"x\",\"uri\":\"file:///a_test.zig\",\"selectionRange\":{\"start\":{\"line\":0,\"character\":0},\"end\":{\"line\":0,\"character\":1}}},{\"name\":\"y\",\"uri\":\"file:///a.zig\",\"selectionRange\":{\"start\":{\"line\":5,\"character\":0},\"end\":{\"line\":5,\"character\":1}}}]", .{}); + var tree: CallTree = .{}; + for (items(fixture)) |item| try tree.nodes.append(arena, .{ .call = try callOf(arena, item) }); + var order = [_]usize{ 0, 1, 2, 3 }; + std.mem.sort(usize, &order, @as(*const CallTree, &tree), callerLess); + try std.testing.expectEqualSlices(usize, &.{ 3, 1, 0, 2 }, &order); +} + +test "a mailbox wait is a cancelation point: a canceled worker stops waiting" { + const io = std.testing.io; + var c: Conn = .{}; + const Waiter = struct { + fn run(conn: *Conn, wio: std.Io) error{Canceled}!void { + conn.mu.lockUncancelable(wio); + defer conn.mu.unlock(wio); + while (true) _ = try timedWait(conn, wio, nowMs() + 60_000); + } + }; + var future = try io.concurrent(Waiter.run, .{ &c, io }); + try std.testing.expectError(error.Canceled, future.cancel(io)); +} + test "callstack cross-crate paths remain resolvable without absolute path clutter" { var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena_state.deinit(); @@ -2584,37 +2882,38 @@ test "a language with no server to start says so, not that it did not answer" { defer arena.deinit(); var buf: [256]u8 = undefined; var out: std.Io.Writer = .fixed(&buf); - try query(std.testing.allocator, arena.allocator(), .{ .kind = .hover, .path = "/x/a.py", .source = "", .offset = 0 }, &out); + try query(std.testing.io, std.testing.allocator, arena.allocator(), .{ .kind = .hover, .path = "/x/a.py", .source = "", .offset = 0 }, &out); try std.testing.expectEqualStrings("@none language server for .py not found\n", out.buffered()); } test "Lspinfo before any query says a server is not started yet, not off" { var out: std.Io.Writer.Allocating = .init(std.testing.allocator); defer out.deinit(); - try status(.{ .kind = .status, .path = "", .source = "", .offset = 0 }, &out.writer); + try status(std.testing.io, .{ .kind = .status, .path = "", .source = "", .offset = 0 }, &out.writer); try std.testing.expect(std.mem.indexOf(u8, out.written(), "not started yet (its first query starts it)") != null); } test "a server that failed a moment ago is said to have failed, and when it is tried again, not to be missing" { if (getenv("PARDES_LSP_ZIG") != null) return error.SkipZigTest; + const io = std.testing.io; const si = specFor("/x/a.zig").?; const c = &conns[si]; - c.lock(); + c.mu.lockUncancelable(io); const was = .{ c.state, c.retry_after_ms }; c.state = .dead; c.retry_after_ms = nowMs() + 4500; - c.unlock(); + c.mu.unlock(io); defer { - c.lock(); + c.mu.lockUncancelable(io); c.state = was[0]; c.retry_after_ms = was[1]; - c.unlock(); + c.mu.unlock(io); } var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); defer arena.deinit(); var out: std.Io.Writer.Allocating = .init(std.testing.allocator); defer out.deinit(); - try query(std.testing.allocator, arena.allocator(), .{ .kind = .hover, .path = "/x/a.zig", .source = "", .offset = 0 }, &out.writer); + try query(std.testing.io, std.testing.allocator, arena.allocator(), .{ .kind = .hover, .path = "/x/a.zig", .source = "", .offset = 0 }, &out.writer); try std.testing.expect(std.mem.indexOf(u8, out.written(), "zls failed recently; retry in 5s") != null); } diff --git a/src/macos.zig b/src/macos.zig index 50fa04fa..5d3dfec4 100644 --- a/src/macos.zig +++ b/src/macos.zig @@ -44,7 +44,11 @@ fn hostWatchFile(pane: u8, generation: u32, path: ?[*]const u8, path_len: usize) const TIOCSWINSZ: c_int = @bitCast(@as(u32, if (@hasDecl(posix.T, "IOCSWINSZ")) posix.T.IOCSWINSZ else 0x80087467)); -pub const std_options: std.Options = .{ .logFn = logFn }; +// Every thread's alternate signal stack is a threadlocal that libc zeroes as +// the thread starts, so std's 256 KiB made each 9P connection's thread cost +// that much resident. A stack-overflow segfault on a thread still printed its +// whole symbolized trace from 32 KiB up (16 KiB double-faulted): 64 KiB. +pub const std_options: std.Options = .{ .logFn = logFn, .signal_stack_size = 64 * 1024 }; fn logFn( comptime level: std.log.Level, @@ -2419,7 +2423,7 @@ fn pipeWorker(st: *State, job: *selection_pipe.Job) anyerror!void { } fn lspWorker(st: *State, job: *host_io.Lsp.Job) anyerror!void { - host_io.Lsp.work(st.gpa, job, st, deliverLspRows); + host_io.Lsp.work(st.io, st.gpa, job, st, deliverLspRows); } fn deliverLspRows(ctx: ?*anyopaque, id: u32, rows: ?[]u8) void { @@ -2582,12 +2586,11 @@ fn reap(st: *State, pane: u8) void { } fn readPty(st: *State, io: std.Io, pty: std.Io.File, id: u8, gen: u32) anyerror!void { - var read_buf: [0x10000]u8 = undefined; - var reader = pty.readerStreaming(io, &read_buf); + // One buffer, read into directly: a Reader around it only added a second + // (and in a safe build, filled both as `undefined` on every start). + var buf: [0x10000]u8 = undefined; while (true) { - var buf: [0x10000]u8 = undefined; - var vec = [_][]u8{&buf}; - const n = reader.interface.readVec(&vec) catch break; + const n = pty.readStreaming(io, &.{&buf}) catch break; if (n == 0) break; const bytes = st.gpa.dupe(u8, buf[0..n]) catch break; st.inbox.pushOutput(st.gpa, io, .{ .pane = id, .gen = gen, .bytes = bytes }) catch break; diff --git a/src/main.zig b/src/main.zig index 64614daa..ea2db917 100644 --- a/src/main.zig +++ b/src/main.zig @@ -16,7 +16,11 @@ pub const std_options_debug_io: std.Io = if (is_emscripten) else std_options_debug_threaded_io.?.io(); -pub const std_options: std.Options = .{ .logFn = logFn }; +// Every thread's alternate signal stack is a threadlocal that libc zeroes as +// the thread starts, so std's 256 KiB made each 9P connection's thread cost +// that much resident. A stack-overflow segfault on a thread still printed its +// whole symbolized trace from 32 KiB up (16 KiB double-faulted): 64 KiB. +pub const std_options: std.Options = .{ .logFn = logFn, .signal_stack_size = 64 * 1024 }; fn logFn( comptime level: std.log.Level, @@ -328,7 +332,11 @@ fn webMain() !void { // malloc otherwise. Kept on purpose: glibc's malloc was measured at least as // fast as std.heap.smp_allocator on every scenario and faster on MuPDF's // page-sized rasters. macos.zig makes the same choice for itself. -fn nativeMain(init: std.process.Init) !void { +fn nativeMain(std_init: std.process.Init) !void { + var init = std_init; + // Zig 0.17's std.start gives a safe build a SafeAllocator over the page + // allocator, not libc's malloc: hand the shells malloc, as above. + if (builtin.mode != .debug) init.gpa = std.heap.c_allocator; var stderr_probe: [64]u8 = undefined; _ = std.debug.lockStderr(&stderr_probe); std.debug.unlockStderr(); diff --git a/src/memory.zig b/src/memory.zig index 48403c55..853d641a 100644 --- a/src/memory.zig +++ b/src/memory.zig @@ -16,6 +16,10 @@ pub const limits = struct { pub const pending_write_cap: usize = if (board) 0 else 4 * MiB; pub const wrap_rows = if (board) 128 else 256; pub const undo_max = if (board) 16 else 256; + /// The text a file's undo and redo steps hold together, kept by dropping + /// the oldest; the newest step always stays, so the bound per file is + /// this plus one snapshot (at most max_file_bytes). + pub const undo_bytes: usize = if (board) 64 * KiB else 64 * MiB; pub const message_log = if (board) 16 else 128; /// ranges one selection holds; helix has no limit, and a `%s` over a /// file's words wants hundreds @@ -23,6 +27,19 @@ pub const limits = struct { /// /log's ring, which records whether or not anyone reads it. pub const log_bytes: usize = if (board) 4 * KiB else 64 * KiB; pub const max_tag_tail: usize = if (board) 512 else 4096; + /// Pixels one image may decode to (RGBA, 4 bytes each): checked from its + /// header before stb_image allocates them. + pub const image_decode_pixels: usize = if (board) 0 else 64 * 1024 * 1024; + /// What the core's per-step scratch arena and the frame arena keep + /// between steps: a step that needed more (a huge Callstack's sources) + /// gives the rest back instead of holding its high-water mark. + pub const scratch_kept: usize = if (board) 4 * KiB else 16 * MiB; + pub const frame_kept: usize = if (board) 4 * KiB else 16 * MiB; + /// The other open files one language query copies for its server, in + /// bytes: past it the rest are left out (the asked file always goes). + pub const lsp_snapshot_bytes: usize = if (board) 0 else 64 * MiB; + /// One paste, from any shell: past it, the rest is left out and said. + pub const max_paste_bytes: usize = if (board) 16 * KiB else 4 * MiB; pub const host_path_cap: usize = if (board) 0 else 4095; /// -Dembed-sources: the editor serves its own sources under /src. pub const embedded_sources = config.embed_sources; @@ -34,6 +51,10 @@ pub const limits = struct { pub const tree_sitter = if (board) 0 else if (reduced_target) 4 * MiB else 16 * MiB; pub const image = if (board) 0 else if (reduced_target) 64 * KiB else 32 * MiB; pub const pdf = if (board) 0 else if (reduced_target or !config.mupdf) 64 * KiB else 64 * MiB; + /// One language query's working memory (its parsed answers, the rows + /// it writes): a hard bound, nothing spills. Callstack walks until it + /// would leave less than its rendering reserve. + pub const lsp_query = if (board or reduced_target) 0 else 256 * MiB; }; }; @@ -96,6 +117,82 @@ var frame_buffer: [limits.arena.frame]u8 = @splat(0); var tree_sitter_buffer: [limits.arena.tree_sitter]u8 = @splat(0); var image_buffer: [limits.arena.image]u8 = @splat(0); var pdf_buffer: [limits.arena.pdf]u8 = @splat(0); +var lsp_query_buffer: [limits.arena.lsp_query]u8 align(std.heap.page_size_max) = @splat(0); +var lsp_query_busy: std.atomic.Value(bool) = .init(false); +/// What a query may leave resident of the region (giveLspQuery). +const lsp_query_kept = 8 * MiB; + +/// The language query region, for the one query running; null while another +/// holds it (the shells cancel and join a query before starting the next). +pub fn takeLspQuery() ?[]u8 { + if (lsp_query_busy.swap(true, .acquire)) return null; + return &lsp_query_buffer; +} + +/// Gives the region back after a query. A big one's touched pages go back to +/// the system (zeroed again on their next touch, as .bss is), so one huge +/// answer does not stay resident; a small one's stay, for the next query to +/// reuse without faulting them in again. +pub fn giveLspQuery(used: usize) void { + if (comptime builtin.os.tag == .linux) if (used > lsp_query_kept) { + const page = std.heap.pageSize(); + const len = std.mem.alignForward(usize, @min(used, lsp_query_buffer.len), page); + std.posix.madvise(@as([*]align(std.heap.page_size_min) u8, @ptrCast(&lsp_query_buffer)), len, std.posix.MADV.DONTNEED) catch {}; + }; + lsp_query_busy.store(false, .release); +} + +/// `n` bytes as they come: `Allocator.alloc` fills a safe build's new memory +/// as `undefined` (0xAA), which writes, and makes resident, all of a buffer +/// sized for the worst case: every language query wrote its 51 MB answer +/// room, every search its 16 MiB. For buffers written before they are read. +pub fn unfilled(allocator: Allocator, n: usize) Allocator.Error![]u8 { + if (n == 0) return allocator.alloc(u8, 0); + const ptr = allocator.rawAlloc(n, .of(u8), @returnAddress()) orelse return error.OutOfMemory; + return ptr[0..n]; +} + +/// `bytes` copied into memory `unfilled` takes: a text-sized copy (an undo +/// snapshot) is written once, not filled first. +pub fn dupeUnfilled(allocator: Allocator, bytes: []const u8) Allocator.Error![]u8 { + const out = try unfilled(allocator, bytes.len); + @memcpy(out, bytes); + return out; +} + +/// Frees without the safe-build overwrite `free` does, for text-sized buffers +/// freed on every edit. +pub fn freeUnfilled(allocator: Allocator, bytes: []const u8) void { + if (bytes.len > 0) allocator.rawFree(@constCast(bytes), .of(u8), @returnAddress()); +} + +/// Gives libc's free memory back to the system, inside its heap too: after a +/// big result is formatted or a big pane torn down, glibc keeps what was freed +/// (a V8 Callstack page left 21 MiB free in the heap; this returned 20). +/// Walks the heap, so for rare, large events only. +pub fn trim() void { + if (comptime builtin.os.tag != .linux or builtin.abi.isMusl() or !builtin.link_libc) return; + const glibc = struct { + extern "c" fn malloc_trim(pad: usize) c_int; + }; + _ = glibc.malloc_trim(0); +} + +/// Marks a big region that is touched sparsely as not for huge pages. With +/// transparent huge pages on `always` (a common default), touching one byte +/// of a 2 MiB-aligned stretch makes all 2 MiB resident: the 9P runner's +/// slots and these arenas' first pages held 45 MiB of an idle session's +/// 71 MiB that way. Only the region given, never the whole process (a prctl +/// would reach every shell and server pardes starts). +pub fn sparse(region: []u8) void { + if (comptime builtin.os.tag != .linux) return; + const page = std.heap.pageSize(); + const start = std.mem.alignForward(usize, @intFromPtr(region.ptr), page); + const end = std.mem.alignBackward(usize, @intFromPtr(region.ptr) + region.len, page); + if (end <= start) return; + std.posix.madvise(@ptrFromInt(start), end - start, std.posix.MADV.NOHUGEPAGE) catch {}; +} + var pardes_fallback: SharedStackFallback = .{ .buffer = &pardes_buffer }; var frame_fallback: SharedStackFallback = .{ .buffer = &frame_buffer }; var tree_sitter_fallback: SharedStackFallback = .{ .buffer = &tree_sitter_buffer }; @@ -118,6 +215,7 @@ pub fn init(fallback: Allocator) Allocators { // a Debug build `fallback` is std.process.Init's gpa, a DebugAllocator // already, and a second one checked every block twice. const backing = if (debug_enabled) std.heap.page_allocator else fallback; + inline for (.{ &pardes_buffer, &frame_buffer, &tree_sitter_buffer, &image_buffer, &pdf_buffer, &lsp_query_buffer }) |buffer| sparse(buffer); pardes_fallback.fallback_allocator = backing; frame_fallback.fallback_allocator = backing; tree_sitter_fallback.fallback_allocator = backing; diff --git a/src/mini.zig b/src/mini.zig index ce291c99..8d8ea0b2 100644 --- a/src/mini.zig +++ b/src/mini.zig @@ -313,7 +313,21 @@ test "Mini publishes only complete snapshots and content replacement drops metad const dir = dir_buf[0..try tmp.dir.realPath(std.testing.io, &dir_buf)]; var path_buf: [4096]u8 = undefined; const path = try std.fmt.bufPrint(&path_buf, "{s}/mini.txt", .{dir}); - try std.testing.checkAllAllocationFailures(std.testing.allocator, Case.run, .{path}); + // Growth that never resizes in place: whether a resize fits where it is + // depends on the heap's layout, and with it how many allocations a run + // makes, which checkAllAllocationFailures needs to be the same each run. + const NoResize = struct { + fn resize(_: *anyopaque, _: []u8, _: std.mem.Alignment, _: usize, _: usize) bool { + return false; + } + fn remap(_: *anyopaque, _: []u8, _: std.mem.Alignment, _: usize, _: usize) ?[*]u8 { + return null; + } + }; + const testing_vtable = std.testing.allocator.vtable; + const no_resize_vtable: std.mem.Allocator.VTable = .{ .alloc = testing_vtable.alloc, .resize = NoResize.resize, .remap = NoResize.remap, .free = testing_vtable.free }; + const backing: std.mem.Allocator = .{ .ptr = std.testing.allocator.ptr, .vtable = &no_resize_vtable }; + try std.testing.checkAllAllocationFailures(backing, Case.run, .{path}); } test "Mini refuses a file that is no UTF-8, before its decoding could panic" { diff --git a/src/modal.zig b/src/modal.zig index 82f1a3a0..ad06833f 100644 --- a/src/modal.zig +++ b/src/modal.zig @@ -989,13 +989,77 @@ pub fn lineCount(content: []const u8) usize { // byte offset of the start of line `row` (0-based). row may == lineCount() // (== content.len, the end). pub fn lineStartOffset(content: []const u8, row: usize) usize { + // Newlines counted 32 bytes at a time, the last block byte by byte: one + // indexOfScalarPos per line was a call per line, 7000 of them to find + // line 7000 of a source, for every cursor move, selection and language + // request there. + const block = 32; + const Block = @Vector(block, u8); var off: usize = 0; - var r: usize = 0; - while (r < row) : (r += 1) { - const nl = std.mem.indexOfScalarPos(u8, content, off, '\n') orelse return content.len; - off = nl + 1; + var left = row; + if (left == 0) return 0; + while (off + block <= content.len) : (off += block) { + const chunk: Block = content[off..][0..block].*; + const found: usize = @popCount(@as(u32, @bitCast(chunk == @as(Block, @splat('\n'))))); + if (found >= left) break; + left -= found; + } + while (off < content.len) : (off += 1) if (content[off] == '\n') { + left -= 1; + if (left == 0) return off + 1; + }; + return content.len; +} + +test "lineStartOffset by blocks and offsetAt agree with a line at a time" { + var prng: std.Random.DefaultPrng = .init(0x9e3779b9); + const random = prng.random(); + var buf: [300]u8 = undefined; + for (0..2000) |_| { + const len = random.uintLessThan(usize, buf.len); + for (buf[0..len]) |*b| b.* = if (random.uintLessThan(u8, 4) == 0) '\n' else 'a'; + const text = buf[0..len]; + for (0..len + 3) |row| { + var off: usize = 0; + var r: usize = 0; + const want = while (r < row) : (r += 1) { + off = (std.mem.indexOfScalarPos(u8, text, off, '\n') orelse break text.len) + 1; + } else off; + try std.testing.expectEqual(want, lineStartOffset(text, row)); + const cursor: Cursor = .{ .row = row, .col = random.uintLessThan(usize, 6) }; + const clamped = lineStartOffset(text, @min(row, cursorLineCount(text) - 1)); + const end = std.mem.indexOfScalarPos(u8, text, clamped, '\n') orelse text.len; + try std.testing.expectEqual(clamped + graphemeStart(text[clamped..end], @min(cursor.col, end - clamped)), offsetAt(text, cursor)); + // lineSpan, as it was: a line at a time, null past the last. + const span: ?LineSpan = span: { + if (text.len == 0) break :span null; + var start: usize = 0; + for (0..row) |_| start = (std.mem.indexOfScalarPos(u8, text, start, '\n') orelse break :span null) + 1; + if (start == text.len and !(row == 0 or text[text.len - 1] == '\n')) break :span null; + break :span .{ .start = start, .end = std.mem.indexOfScalarPos(u8, text, start, '\n') orelse text.len }; + }; + try std.testing.expectEqual(span, lineSpan(text, row)); + // rangeBytes, as it was: each line looked for from the top, twice. + const other: Cursor = .{ .row = random.uintLessThan(usize, len + 3), .col = random.uintLessThan(usize, 6) }; + var lo = cursor; + var hi = other; + if (hi.row < lo.row or (hi.row == lo.row and hi.col < lo.col)) std.mem.swap(Cursor, &lo, &hi); + const lo_line = lineSlice(text, lo.row); + const hi_line = lineSlice(text, hi.row); + const s0 = lineStartOffset(text, lo.row) + graphemeStart(lo_line, @min(lo.col, lo_line.len)); + var e0 = lineStartOffset(text, hi.row) + graphemeStart(hi_line, @min(hi.col, hi_line.len)); + if (e0 < text.len) e0 = nextGrapheme(text, e0); + const got = rangeBytes(text, cursor, other); + try std.testing.expectEqual(s0, got.s); + try std.testing.expectEqual(@max(s0, e0), got.e); + } } - return off; +} + +/// The line that starts at `start` (lineSlice's, once its start is known). +fn lineFrom(content: []const u8, start: usize) []const u8 { + if (start >= content.len) return ""; + return content[start .. std.mem.indexOfScalarPos(u8, content, start, '\n') orelse content.len]; } // the text of line `row` (no terminator), a slice into `content`. @@ -1011,23 +1075,29 @@ pub fn lineSlice(content: []const u8, row: usize) []const u8 { /// A bounded scan of one line; null if the row does not exist. pub const LineSpan = struct { start: usize, end: usize }; +/// Just past the `row`-th newline; null if the text has fewer. +pub fn lineStartExact(content: []const u8, row: usize) ?usize { + const at = lineStartOffset(content, row); + // At the end: either the row-th newline was the last byte, or there were fewer. + if (at == content.len and std.mem.count(u8, content, "\n") < row) return null; + return at; +} + pub fn lineSpan(content: []const u8, row: usize) ?LineSpan { // Match lineCount: empty content has no lines; a trailing newline adds one. if (content.len == 0) return null; - var start: usize = 0; - var r: usize = 0; - while (r < row) : (r += 1) { - const nl = std.mem.indexOfScalarPos(u8, content, start, '\n') orelse return null; - start = nl + 1; - } - if (start > content.len) return null; + const start = lineStartExact(content, row) orelse return null; if (start == content.len and !(row == 0 or content.len == 0 or content[content.len - 1] == '\n')) return null; const end = std.mem.indexOfScalarPos(u8, content, start, '\n') orelse content.len; return .{ .start = start, .end = end }; } -fn spliceAlloc(alloc: std.mem.Allocator, content: []const u8, start: usize, end: usize, replacement: []const u8) ![]u8 { - const out = try alloc.alloc(u8, content.len - (end - start) + replacement.len); +pub fn spliceAlloc(alloc: std.mem.Allocator, content: []const u8, start: usize, end: usize, replacement: []const u8) ![]u8 { + // Raw: every byte is written below, where `alloc` fills a safe build's + // new memory first, a whole file's worth per keystroke. + const len = content.len - (end - start) + replacement.len; + if (len == 0) return alloc.alloc(u8, 0); + const out = (alloc.rawAlloc(len, .of(u8), @returnAddress()) orelse return error.OutOfMemory)[0..len]; @memcpy(out[0..start], content[0..start]); @memcpy(out[start..][0..replacement.len], replacement); @memcpy(out[start + replacement.len ..], content[end..]); @@ -1036,13 +1106,18 @@ fn spliceAlloc(alloc: std.mem.Allocator, content: []const u8, start: usize, end: /// insert `text` at (row, col). col is clamped to the line length. pub fn insertAt(alloc: std.mem.Allocator, content: []const u8, c: Cursor, text: []const u8) ![]u8 { + const off = insertOffset(content, c); + return spliceAlloc(alloc, content, off, off, text); +} + +/// Where insertAt puts its text: col clamped to the line, no further. +pub fn insertOffset(content: []const u8, c: Cursor) usize { // Only an out-of-range row requires counting the whole document. const span = lineSpan(content, c.row) orelse blk: { const last = lineCount(content) -| 1; break :blk lineSpan(content, last) orelse LineSpan{ .start = content.len, .end = content.len }; }; - const off = span.start + @min(c.col, span.end - span.start); - return spliceAlloc(alloc, content, off, off, text); + return span.start + @min(c.col, span.end - span.start); } // delete the character at (row, col). no-op if col is past the line end. @@ -1105,12 +1180,15 @@ fn rangeBytes(content: []const u8, a: Cursor, b: Cursor) struct { s: usize, e: u lo = b; hi = a; } - const lo_line = lineSlice(content, lo.row); - const hi_line = lineSlice(content, hi.row); + // Each line found once, the second from the first. + const lo_start = lineStartOffset(content, lo.row); + const hi_start = if (hi.row == lo.row) lo_start else lo_start + lineStartOffset(content[lo_start..], hi.row - lo.row); + const lo_line = lineFrom(content, lo_start); + const hi_line = lineFrom(content, hi_start); const lo_col = graphemeStart(lo_line, @min(lo.col, lo_line.len)); const hi_col = graphemeStart(hi_line, @min(hi.col, hi_line.len)); - const s = lineStartOffset(content, lo.row) + lo_col; - var e = lineStartOffset(content, hi.row) + hi_col; + const s = lo_start + lo_col; + var e = hi_start + hi_col; if (e < content.len) e = nextGrapheme(content, e); // include the grapheme under the head return .{ .s = s, .e = @max(s, e) }; } @@ -1138,12 +1216,12 @@ pub fn clearLine(alloc: std.mem.Allocator, content: []const u8, row: usize) ![]u // paste `text` as a new line BELOW `row`. Multiline `text` becomes several lines. pub fn pasteLineBelow(alloc: std.mem.Allocator, content: []const u8, row: usize, text: []const u8) ![]u8 { - const n = lineCount(content); - const off = if (row + 1 < n) lineStartOffset(content, row + 1) else content.len; + // The next line's start, or the end: no whole-text line count to know which. + const off = lineStartExact(content, row + 1) orelse content.len; const suffix_newline = off < content.len or (content.len > 0 and content[content.len - 1] == '\n'); const prefix_newline = !suffix_newline and off > 0; const extra: usize = @intFromBool(suffix_newline or prefix_newline); - const out = try alloc.alloc(u8, content.len + text.len + extra); + const out = try @import("memory.zig").unfilled(alloc, content.len + text.len + extra); var write: usize = 0; @memcpy(out[write..][0..off], content[0..off]); write += off; @@ -1393,8 +1471,10 @@ pub fn positionAt(text: []const u8, off: usize) Cursor { /// (row, col) -> clamped gap offset; col == line length lands ON the '\n' pub fn offsetAt(text: []const u8, c: Cursor) usize { - const row = @min(c.row, cursorLineCount(text) - 1); - const s = lineStartOffset(text, row); + // A row past the last is the last: found back from the end, where + // counting every line of the text to clamp it cost a pass over all of it. + var s = lineStartOffset(text, c.row); + if (s == text.len) s = if (std.mem.lastIndexOfScalar(u8, text, '\n')) |nl| nl + 1 else 0; // lineEndOffset(text, row) inlined: it starts by walking to `row` again, // and we are already standing there const e = std.mem.indexOfScalarPos(u8, text, s, '\n') orelse text.len; @@ -1783,15 +1863,6 @@ test "selection textobjects distinguish words and paragraph boundaries" { try std.testing.expectEqual(@as(usize, 7), r.head); } -/// leading-whitespace visual width (tab -> next multiple of INDENT_W) -pub fn indentWidth(line: []const u8) usize { - var w: usize = 0; - for (line) |ch| { - if (ch == ' ') w += 1 else if (ch == '\t') w = (w / INDENT_W + 1) * INDENT_W else break; - } - return w; -} - /// A line's indent as it is, tabs and spaces both, as acme's autoindent /// copies it: what o/O/insert-newline give the new line. pub fn indentText(line: []const u8) []const u8 { diff --git a/src/mouse.zig b/src/mouse.zig index 76c65a16..eeb987b2 100644 --- a/src/mouse.zig +++ b/src/mouse.zig @@ -1114,7 +1114,9 @@ fn mirrorTtySelection(p: *Pardes, pane: *Pane) void { /// second selects what edit.doubleClickRange says, from the caret the click /// left. A plain click still puts the caret on its cell. fn doubleClick(p: *Pardes, id: usize, t: *panes.Text, on_tag: bool, row: i32, col: i32) void { - const now = clockMs(); + // The host's clock, which every host keeps (a libc clock is no clock on + // the web or the board) and a test's virtual one replaces. + const now: i64 = @intCast(p.now_ns / std.time.ns_per_ms); const prev = p.last_click; p.last_click = .{ .id = id, .on_tag = on_tag, .row = row, .col = col, .ms = now }; const c = prev orelse return; @@ -1160,13 +1162,6 @@ fn sweepPoint(p: *Pardes, pane: *panes.Pane, r: i32, c: i32) ?modal.Cursor { return .{ .row = @intCast(w.line), .col = @intCast(@max(0, col)) }; } -fn clockMs() i64 { - if (comptime !pardes.hosted) return 0; - var ts: std.c.timespec = undefined; - if (std.c.clock_gettime(.MONOTONIC, &ts) != 0) return 0; - return @as(i64, ts.sec) * 1000 + @divTrunc(@as(i64, ts.nsec), 1_000_000); -} - fn dragRelease(p: *Pardes, button: Mouse.Button) void { // A different button's release belongs to a chord or another host // stream; only the button which began this gesture may end it. diff --git a/src/ninep/addr.zig b/src/ninep/addr.zig index 86d2d49e..7753c94d 100644 --- a/src/ninep/addr.zig +++ b/src/ninep/addr.zig @@ -239,21 +239,15 @@ pub const Addr = struct { k = @intFromBool(a.text[p] == '\n'); p += 1; } - while (k < n) { - if (p >= nc) { + if (k < n) { + p = nthLineAfter(a.text, p, n - k) orelse { a.err = e_range; return null; - } - if (a.text[p] == '\n') k += 1; - p += 1; + }; } p1 = p; } - while (p < nc) { - const ch = a.text[p]; - p += 1; - if (ch == '\n') break; - } + p = if (std.mem.indexOfScalarPos(u8, a.text, p, '\n')) |nl| nl + 1 else nc; return .{ .q0 = clip(p1), .q1 = clip(p) }; } @@ -678,3 +672,31 @@ test "a line just past the last newline is an empty one there, as sam's lineaddr try testing.expectEqual(Status.ok, th.wr(p, Node.of(th.serialOf(p), .ctl), "Edit 1i/header/\n").reply.status); try testing.expectEqualStrings("header", p.panes[0].?.file.?.content); } + +/// Just past the `count`-th newline at or after `from`; null if the text has +/// fewer. Counted a block at a time (modal.lineStartOffset), where a byte at +/// a time made `echo 7000 > addr` walk every byte above line 7000. +fn nthLineAfter(text: []const u8, from: usize, count: usize) ?usize { + return from + (modal.lineStartExact(text[from..], count) orelse return null); +} + +test "nthLineAfter finds what a byte at a time finds" { + var prng: std.Random.DefaultPrng = .init(0x51ab); + const random = prng.random(); + var buf: [200]u8 = undefined; + for (0..3000) |_| { + const len = random.uintLessThan(usize, buf.len); + for (buf[0..len]) |*b| b.* = if (random.uintLessThan(u8, 3) == 0) '\n' else 'x'; + const text = buf[0..len]; + const from = random.uintLessThan(usize, len + 1); + const count = 1 + random.uintLessThan(usize, 40); + var p = from; + var k: usize = 0; + const want: ?usize = while (k < count) { + if (p >= text.len) break null; + if (text[p] == '\n') k += 1; + p += 1; + } else p; + try std.testing.expectEqual(want, nthLineAfter(text, from, count)); + } +} diff --git a/src/ninep/ctl.zig b/src/ninep/ctl.zig index 733d9c8e..480c1dc7 100644 --- a/src/ninep/ctl.zig +++ b/src/ninep/ctl.zig @@ -4684,6 +4684,10 @@ test "what a /pager open writes after its directory is the text: plain in the bo // An edit drops the colours (pager.zig's ponytail). try testing.expectEqual(Status.ok, call(p, .{ .tag = 6, .op = .write, .node = Node.of(pn.serial, .body), .data = "more\n" }).reply.status); try testing.expectEqual(@as(usize, 0), f.pager_spans.len); + // Undone back to the paged text: its colours come back with it. + panes.File.undo(p, pn); + try testing.expectEqualStrings("red /a\nNext\n", f.content); + try testing.expectEqual(@as(usize, 2), f.pager_spans.len); // PagerColor off, and an open closed with no read: the same text, plain, // in at the editor's next step (a close through a mount never waits). diff --git a/src/panes.zig b/src/panes.zig index 7ce85419..b535993e 100644 --- a/src/panes.zig +++ b/src/panes.zig @@ -133,6 +133,9 @@ pub const Pane = struct { /// Its pty is still open: a job the command left in the background may /// be printing to it, and a reuse would hang it up. command_pty: bool = false, + /// Its child pages as a terminal's does (`pardes -`, a +Pager), not + /// through cat: Look's `git show` of a commit (look.lookCommit). + command_pages: bool = false, /// The shell a terminal runs when it is not the configured one (`Tty /// fish`), owned. shell: ?[]u8 = null, diff --git a/src/pardes.zig b/src/pardes.zig index aaa9d177..c2a3ba21 100644 --- a/src/pardes.zig +++ b/src/pardes.zig @@ -478,6 +478,7 @@ pub const Loc = struct { }; test { + _ = @import("modal.zig"); _ = @import("tagline.zig"); _ = @import("hunks.zig"); _ = @import("builtins_json.zig"); @@ -4645,6 +4646,10 @@ pub const Pardes = struct { /// The last query asked (Lspwhy explains it): its kind, argument, and /// the pane and place it was asked at. lsp_last: ?struct { kind: lsp.Kind, arg: Effect.Buf(128), serial: u32, offset: u32 } = null, + /// The Callstack page `+Callstack` shows stopped short: its file's pane, + /// the place it was asked at, and the direct caller the next page starts + /// at. Callstack run in `+Callstack` asks for it. + callstack_more: ?struct { serial: u32, offset: u32, next: Effect.Buf(128) } = null, lsp_wait: ?struct { id: u32, kind: lsp.Kind, @@ -5168,10 +5173,13 @@ pub const Pardes = struct { } fn reapPanes(p: *Pardes) void { + var reaped = false; for (&p.retired_panes.previous) |*slot| if (slot.*) |pane| { p.teardownPane(pane); slot.* = null; + reaped = true; }; + if (reaped) memory.trim(); p.retired_panes.previous = p.retired_panes.current; p.retired_panes.current = @splat(null); } @@ -5544,7 +5552,7 @@ pub const Pardes = struct { p.invalidate(); look.invalidateLookHover(p, id); const applied = p.applyWatchedFileChanged(id, bytes); - _ = p.scratch.reset(.retain_capacity); + _ = p.scratch.reset(.{ .retain_with_limit = memory.limits.scratch_kept }); p.sync(); return applied; } @@ -6000,7 +6008,7 @@ pub const Pardes = struct { // A pty streaming into an unwatched session spent most of its time // drawing what nobody looked at. if (v.watched) |f| if (!f(h.ctx)) return; - _ = p.frame_arena.reset(.retain_capacity); + _ = p.frame_arena.reset(.{ .retain_with_limit = memory.limits.frame_kept }); const surface = try p.render(p.frame_arena.allocator()); if (v.present) |f| f(h.ctx, surface); // Settled before post_present: a shell ticks there, and what that @@ -6202,7 +6210,7 @@ pub const Pardes = struct { look.advanceLookHover(p); }, } - _ = p.scratch.reset(.retain_capacity); + _ = p.scratch.reset(.{ .retain_with_limit = memory.limits.scratch_kept }); p.sync(); p.fsReport(); ctlfs.events.announce(p); @@ -6777,6 +6785,19 @@ pub const Pardes = struct { pub const SavePath = Effect.Buf(effect_path_cap); pub fn lspRequest(p: *Pardes, asked: usize, kind: lsp.Kind, arg_in: []const u8) void { + p.lspRequestAt(asked, kind, arg_in, null); + } + + /// The next page of the Callstack `+Callstack` shows, asked where the + /// first was. + pub fn callstackMore(p: *Pardes, from: usize) void { + const more = p.callstack_more orelse return p.reportFailure(from, "Callstack: this is the last page; run it in a file to start again"); + const id = p.paneBySerial(more.serial) orelse return p.reportFailure(from, "Callstack: the file it was asked in is closed"); + p.lspRequestAt(id, .callstack, more.next.slice(), more.offset); + } + + /// `lspRequest` at byte `at` of the pane's file rather than its cursor. + fn lspRequestAt(p: *Pardes, asked: usize, kind: lsp.Kind, arg_in: []const u8, at_byte: ?u32) void { var arg = arg_in; if (!normal.multiOnce(p)) return; // one question per keystroke, from the primary // Lspwhy narrates the last query where it was asked -- that pane's @@ -6800,7 +6821,7 @@ pub const Pardes = struct { (!zig_buf and std.mem.indexOfAny(u8, arg, " \t\r\n\"\\") != null)) return p.reportFailure(id, std.fmt.bufPrint(&said, "Rename: {s} is no name", .{arg}) catch "Rename: no name"); } - var off = if (pane.file) |f| modal.offsetAt(f.content, .{ + var off = if (at_byte) |at| @min(at, if (pane.file) |f| f.content.len else 0) else if (pane.file) |f| modal.offsetAt(f.content, .{ .row = @intCast(@max(0, pane.body.cur_row)), .col = @intCast(@max(0, pane.body.cur_col)), }) else 0; @@ -7089,13 +7110,24 @@ pub const Pardes = struct { } const dir = if (pane.file) |f| panes.Dir.ofName(f.path) else pane.cwdSlice(); - const content = p.gpa.dupe(u8, rows) catch return; + // A Callstack page that stops short ends in its marker: said as a + // row naming the word that shows the next page, and kept. + if (w.kind == .callstack) p.callstack_more = null; + const marker = if (w.kind == .callstack) std.mem.lastIndexOf(u8, rows, lsp.callstack_more) else null; + const content = if (marker) |at| more: { + var fields = std.mem.tokenizeAny(u8, rows[at + lsp.callstack_more.len ..], " \n"); + const next = fields.next() orelse ""; + const shown = fields.next() orelse "?"; + if (p.lsp_last) |last| p.callstack_more = .{ .serial = w.serial, .offset = last.offset, .next = .from(next) }; + break :more std.fmt.allocPrint(p.gpa, "{s}… {s} callers on this page, more after them: Callstack here shows the next page\n", .{ rows[0..at], shown }) catch return; + } else p.gpa.dupe(u8, rows) catch return; const serial_before = p.next_serial; p.fs.refilled = null; panes.Output.fillResults(p, w.pane, dir, from, w.arg.slice(), content, null) catch |err| { p.reportError(w.pane, "language response", err); return; }; + if (rows.len >= 1 << 20) memory.trim(); // What a 9P write that asked it answers: the pane the rows are in // (a multi-file Rename's preview, Lspinfo's +Lsp), made or filled // again, not the pane it was asked from. diff --git a/src/regexp.zig b/src/regexp.zig index 4cbca57e..6d281859 100644 --- a/src/regexp.zig +++ b/src/regexp.zig @@ -283,7 +283,10 @@ pub const Regex = struct { /// its top level and every branch starts with `^`; null when it is not /// one, or no branch does. fn anchoredAlternation(pat: []const u8, out: *[5 * max_ops + 2]u8) error{ Bad, Mixed }!?[]const u8 { - var bars: [16]usize = undefined; + // No rewrite is longer than `out`, so neither is any pattern it + // takes, nor its count of bars. + if (pat.len > out.len) return error.Bad; + var bars: [5 * max_ops + 2]u16 = undefined; var n: usize = 0; var depth: usize = 0; var in_class = false; @@ -301,8 +304,7 @@ pub const Regex = struct { } else if (c == ')') { depth -|= 1; } else if (c == '|' and depth == 0) { - if (n == bars.len) return error.Bad; - bars[n] = i; + bars[n] = @intCast(i); n += 1; } } @@ -518,6 +520,9 @@ test "a ^ after | anchors that branch: ^def|^ finds a line that starts either w try std.testing.expectError(error.Mixed, Regex.compile("^def|x")); var plain = try Regex.compile("a|b"); try std.testing.expectEqual(@as(usize, 7), (try plain.find(text, 0, text.len, text.len)).?.start); + // Seventeen branches and more are a pattern like any other. + var many = try Regex.compile("q|r|s|t|u|v|w|x|y|z|k|l|m|n|o|p|j|b"); + try std.testing.expectEqual(@as(usize, 0), (try many.find(text, 0, text.len, text.len)).?.start); } test "a quoted backslash before n is no newline, and a class ends where mvzr ends it" { diff --git a/src/sam_edit.zig b/src/sam_edit.zig index f6253c89..94b76816 100644 --- a/src/sam_edit.zig +++ b/src/sam_edit.zig @@ -259,6 +259,10 @@ fn fail(why: *Why, comptime fmt: []const u8, args: anytype) Failure { // ---- parsing: edit.c ---- +/// Commands one Edit may nest, loops (`x`, `y`, `g`, `v`, `X`, `Y`) and +/// braces together: each level is a stack frame holding a compiled regex. +pub const max_nest = 32; + const Parser = struct { arena: std.mem.Allocator, src: []const u8, @@ -271,6 +275,9 @@ const Parser = struct { open_text: bool = false, /// The address being read had a `,` after a `"re"`. file_comma: bool = false, + /// Commands open around the one being read, braces and loops alike: + /// each is a frame of `parse` and later of `execIn`, so it is bounded. + depth: u8 = 0, why: *Why, fn getch(ps: *Parser) ?u8 { @@ -460,6 +467,9 @@ const Parser = struct { /// edit.c:467, parsecmd. fn parse(ps: *Parser, nest: u32) Failure!?*Cmd { + if (ps.depth >= max_nest) return fail(ps.why, "commands nested more than {d} deep", .{max_nest}); + ps.depth += 1; + defer ps.depth -= 1; var file_re: ?[]const u8 = null; ps.file_comma = false; const a = try ps.address(&file_re); @@ -1163,6 +1173,11 @@ test "an Edit that fails halfway changes nothing, and says why in acme's words" .{ "e /tmp/x", "can't open /tmp/x: no files here" }, .{ "\"zz\" p", "no file matches \"zz\"" }, .{ ",s/(a)/\\1/", "no \\1: mvzr keeps no submatches" }, + .{ comptime deep: { + var loops: []const u8 = ""; + for (0..40) |_| loops = loops ++ ",x/a/"; + break :deep loops ++ "d"; + }, "commands nested more than 32 deep" }, .{ "1 m 1,2", "move overlaps itself" }, .{ ",x/(^|\\n)foo/d", "bad regular expression: in a pattern with \\n, ^ can only come first and $ only just before a \\n" }, }) |c| { diff --git a/src/selection_pipe.zig b/src/selection_pipe.zig index c3e5e3a6..229b3d67 100644 --- a/src/selection_pipe.zig +++ b/src/selection_pipe.zig @@ -401,7 +401,7 @@ pub fn runIn( }, }; child.stdin = null; // writer_context owns and closes this endpoint - var writer: ?std.Thread = std.Thread.spawn(.{}, writeInput, .{writer_context}) catch { + var writer: ?std.Io.Future(void) = io.concurrent(writeInput, .{writer_context}) catch { writer_context.file.close(io); gpa.free(writer_context.input); gpa.destroy(writer_context); @@ -410,8 +410,9 @@ pub fn runIn( }; // On every early return (a timeout, a ceiling) the answer goes at once: // the group is killed and the shell left to be reaped elsewhere - // (abandon), and the writer, which owns its input, let go. - defer if (writer) |thread| thread.detach(); + // (abandon), and the writer's write canceled (it closes and frees what + // it owns as it ends). + defer if (writer) |*w| w.cancel(io); defer if (child.id != null) abandonNow(io, &child, pid); defer if (token != 0) Running.remove(pid); if (token != 0 and !Running.add(token, pid)) return fail.k(.signal); @@ -443,7 +444,9 @@ pub fn runIn( multi_reader.checkAnyError() catch return fail.k(.io); if (token != 0) Running.remove(pid); const term = child.wait(io) catch return fail.k(.io); - writer.?.join(); + // A cancel of this job reaches the write too: a grandchild that keeps + // stdin open and never reads holds no worker. + writer.?.await(io); writer = null; const stdout = multi_reader.toOwnedSlice(0) catch return fail.k(.io); diff --git a/src/surface.zig b/src/surface.zig index e67cf21c..d6ec016d 100644 --- a/src/surface.zig +++ b/src/surface.zig @@ -533,11 +533,6 @@ pub const Surface = struct { return s.cell_diffs[@as(usize, y) * s.cols + x].changed(); } - pub fn panelCellDiff(s: *const Surface, x: u16, y: u16) PanelCellDiff { - if (!s.hasPanelDiff() or x >= s.cols or y >= s.rows) return .unchanged; - return s.cell_diffs[@as(usize, y) * s.cols + x]; - } - pub fn at(s: *Surface, x: u16, y: u16) *Cell { std.debug.assert(x < s.cols and y < s.rows); return &s.cells[@as(usize, y) * s.cols + x]; diff --git a/src/terminal.zig b/src/terminal.zig index 33ad22e6..05054521 100644 --- a/src/terminal.zig +++ b/src/terminal.zig @@ -1,4 +1,4 @@ -//! A terminal pane: its VT emulator and replay, prompt rows, the edit overlay +//! A terminal pane: its VT emulator, prompt rows, the edit overlay //! typed over shell rows, and the Filter that recolours output to the theme. const panes = @import("panes.zig"); const std = @import("std"); @@ -141,16 +141,9 @@ pub const MarkedHandler = if (enabled) struct { } } else void; -pub const Replay = struct { - bytes: [1024 * 1024]u8 = undefined, - head: usize = 0, - len: usize = 0, -}; - pub const State = struct { vt: VtSlot, stream: StreamSlot, - replay: Replay, reply: [256]u8 = undefined, reply_len: u16 = 0, /// The grid cell the program last heard the mouse at, so motion is @@ -613,8 +606,6 @@ pub fn create(gpa: std.mem.Allocator, cols: u16, rows: u16) !*Pane { .kitty_image_storage_limit = if (images_enabled) TerminalImages.storage_limit else 0, }); state.stream = .init(.{ .handler = .{ .inner = state.vt.vtHandler() }, .allocator = gpa }); - state.replay.head = 0; - state.replay.len = 0; state.reply_len = 0; state.mouse_cell = null; state.images = if (images_enabled) .{} else {}; @@ -678,43 +669,12 @@ pub fn restore(p: *Pardes, src: dump.Pane, live: bool) !*Pane { return pane; } -/// Feed the emulator and retain the bounded suffix a dump can replay. Live -/// output and restoration share this byte path, then apply different views. +/// Feed the emulator. Live output and restoration share this byte path, +/// then apply different views. fn ingest(pane: *Pane, bytes: []const u8) void { - const state = pane.terminal.?; - const replay = &state.replay; - if (bytes.len >= replay.bytes.len) { - const kept = bytes[bytes.len - replay.bytes.len ..]; - @memcpy(&replay.bytes, kept); - replay.head = 0; - replay.len = replay.bytes.len; - } else { - const overflow = bytes.len -| (replay.bytes.len - replay.len); - replay.head = (replay.head + overflow) % replay.bytes.len; - replay.len -= overflow; - const tail = (replay.head + replay.len) % replay.bytes.len; - const first = @min(bytes.len, replay.bytes.len - tail); - @memcpy(replay.bytes[tail..][0..first], bytes[0..first]); - @memcpy(replay.bytes[0 .. bytes.len - first], bytes[first..]); - replay.len += bytes.len; - } - state.stream.nextSlice(bytes); + pane.terminal.?.stream.nextSlice(bytes); } -/// Return the replay ring in chronological order. Wrapped records are copied -/// into `allocator`; contiguous records remain a borrowed slice of the pane. -fn replayBytes(pane: *const Pane, allocator: std.mem.Allocator) ![]const u8 { - const state = pane.terminal orelse return &.{}; - const replay = &state.replay; - if (replay.len == 0) return &.{}; - if (replay.head + replay.len <= replay.bytes.len) - return replay.bytes[replay.head..][0..replay.len]; - const out = try allocator.alloc(u8, replay.len); - const first = replay.bytes.len - replay.head; - @memcpy(out[0..first], replay.bytes[replay.head..]); - @memcpy(out[first..], replay.bytes[0 .. replay.len - first]); - return out; -} test "replay ownership is terminal-only and construction rolls back on allocation failure" { const Case = struct { @@ -753,7 +713,6 @@ test "document construction allocates only the pane and has inert terminal defau try std.testing.expectEqual(GridCursor{}, gridCursor(pane)); try std.testing.expectEqual(Scrollbar{}, scrollbar(pane)); try std.testing.expectEqualStrings("", try screenTextAlloc(pane, allocator)); - try std.testing.expectEqualStrings("", try replayBytes(pane, allocator)); try std.testing.expect(!failing.has_induced_failure); } @@ -779,46 +738,18 @@ test "terminal state keeps parser fragments and sends emulator replies through i } try std.testing.expectEqual(@as(usize, 1), replies); try std.testing.expectEqual(@as(u16, 0), state.reply_len); - try std.testing.expectEqualStrings("\x1b[6n", try replayBytes(pane, std.testing.allocator)); } -test "replay keeps a bounded chronological suffix across large writes and wrapping" { - if (comptime !enabled) return error.SkipZigTest; - const gpa = std.testing.allocator; - const pane = try create(gpa, 40, 12); - defer gpa.destroy(pane); - defer deinitEmulator(pane, gpa); - try std.testing.expectEqualStrings("", try replayBytes(pane, gpa)); - ingest(pane, "hello"); - const small = try replayBytes(pane, gpa); - try std.testing.expectEqualStrings("hello", small); - try std.testing.expectEqual(@intFromPtr(&pane.terminal.?.replay.bytes), @intFromPtr(small.ptr)); - - const capacity = pane.terminal.?.replay.bytes.len; - const input = try gpa.alloc(u8, capacity + 7); - defer gpa.free(input); - @memset(input, 0); - const ending = "\x1b[31mred\x1b[0m\r\n"; - @memcpy(input[input.len - ending.len ..], ending); - ingest(pane, input); - try std.testing.expectEqualSlices(u8, input[7..], try replayBytes(pane, gpa)); - ingest(pane, "next\r\n"); - const wrapped = try replayBytes(pane, gpa); - defer gpa.free(wrapped); - try std.testing.expectEqual(capacity, wrapped.len); - try std.testing.expectEqualSlices(u8, input[7 + "next\r\n".len ..], wrapped[0 .. capacity - "next\r\n".len]); - try std.testing.expectEqualStrings("next\r\n", wrapped[capacity - "next\r\n".len ..]); -} - -test "replay restores terminal cells from the retained stream" { +test "a terminal stream restores the cells it drew" { if (comptime !enabled) return error.SkipZigTest; const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 40, .rows = 12 }); defer p.deinit(); while (p.nextEffect()) |_| {} const pane = p.panes[0].?; - feedOutput(p, pane, "\x1b[31mred\x1b[0m\r\ncafé\r\n"); - const encoded = try dump.encodeBytes(gpa, try replayBytes(pane, gpa)); + const drawn = "\x1b[31mred\x1b[0m\r\ncafé\r\n"; + feedOutput(p, pane, drawn); + const encoded = try dump.encodeBytes(gpa, drawn); defer gpa.free(encoded); const restored = try restore(p, .{ .kind = .terminal, @@ -835,7 +766,6 @@ test "replay restores terminal cells from the retained stream" { const after = try screenTextAlloc(restored, gpa); defer gpa.free(after); try std.testing.expectEqualStrings(before, after); - try std.testing.expectEqualSlices(u8, try replayBytes(pane, gpa), try replayBytes(restored, gpa)); } test "a restored command pane comes back finished, its command not run again" { diff --git a/src/tty/tty.zig b/src/tty/tty.zig index 4cd1bc9a..afc0dbf0 100644 --- a/src/tty/tty.zig +++ b/src/tty/tty.zig @@ -34,6 +34,8 @@ var kitty_shm = std.atomic.Value(bool).init(false); var kitty_shm_probing = std.atomic.Value(bool).init(false); const kitty_shm_probe_id = 0x7fff_fff1; var kitty_shm_serial: u32 = 0; +/// Transmissions an unread shm segment outlives before it is removed. +const kitty_shm_window = 64; fn kittyShmName(buf: []u8, n: u32) ![:0]const u8 { return std.fmt.bufPrintSentinel(buf, "/pardes-{d}-{d}", .{ libc.getpid(), n }, 0); @@ -1787,6 +1789,13 @@ const Shell = struct { if (!s.kitty.contains(key) and vx.caps.kitty_graphics and kitty_shm.load(.acquire)) shm: { var buf: [64]u8 = undefined; kitty_shm_serial +%= 1; + // Bounded: a segment this many transmissions old was never + // read (a terminal reads one as its command arrives), and a + // tmpfs holds it in memory until it goes. + if (kitty_shm_serial > kitty_shm_window) { + var old_buf: [64]u8 = undefined; + if (kittyShmName(&old_buf, kitty_shm_serial - kitty_shm_window)) |old| _ = libc.shm_unlink(old) else |_| {} + } const name = kittyShmName(&buf, kitty_shm_serial) catch break :shm; if (!kittyShmWrite(name, place.rgba)) break :shm; if (vx.transmitLocalImagePath(s.gpa, s.tty.writer(), name, @intCast(place.iw), @intCast(place.ih), .shared_mem, .rgba) catch null) |handle| @@ -2010,7 +2019,7 @@ const Shell = struct { old.future.cancel(s.io) catch {}; s.lsp_task = null; } - const future = s.io.concurrent(lspWorker, .{ s.lsp_gpa, job, s.loop }) catch |err| { + const future = s.io.concurrent(lspWorker, .{ s.io, s.lsp_gpa, job, s.loop }) catch |err| { job.free(s.lsp_gpa); s.core.update(.{ .lsp_resp = .{ .id = req.id, .rows = null } }); return s.core.reportError(req.pane, "lsp", err); @@ -2144,9 +2153,9 @@ fn requestClipboard(vx: *vaxis.Vaxis, tty: *vaxis.Tty) void { vx.requestSystemClipboard(tty.writer()) catch {}; } -fn lspWorker(allocator: std.mem.Allocator, job: *host_io.Lsp.Job, loop: *Loop) anyerror!void { +fn lspWorker(io: std.Io, allocator: std.mem.Allocator, job: *host_io.Lsp.Job, loop: *Loop) anyerror!void { var sink: LspRowSink = .{ .allocator = allocator, .loop = loop }; - host_io.Lsp.work(allocator, job, &sink, LspRowSink.take); + host_io.Lsp.work(io, allocator, job, &sink, LspRowSink.take); } const LspRowSink = struct { @@ -2185,23 +2194,30 @@ fn watchFiles(io: std.Io, fd: c_int, loop: *Loop) anyerror!void { return; } const file: std.Io.File = .{ .handle = fd, .flags = .{ .nonblocking = false } }; - var read_buf: [4096]u8 = undefined; - var reader = file.readerStreaming(io, &read_buf); + // One buffer, read into directly: a Reader around it only added a second + // (and in a safe build, filled both as `undefined` on every start). + var buf: [4096]u8 = undefined; while (true) { - var buf: [4096]u8 = undefined; - var vec = [_][]u8{&buf}; - const n = reader.interface.readVec(&vec) catch break; + const n = file.readStreaming(io, &.{&buf}) catch break; if (n == 0) break; loop.postEvent(.files_changed) catch break; } } fn winchWatch(loop: *Loop, vx: *vaxis.Vaxis, tty: *vaxis.Tty) void { + winchWatchUntil(loop, vx, tty, null); +} + +/// A SIGWINCH watcher that ends: `stop` set, then a SIGWINCH sent to its +/// thread, wakes its sigwait and it returns, so whoever owns `loop` can join +/// it before the loop goes (attachSession's loop is on its stack). +fn winchWatchUntil(loop: *Loop, vx: *vaxis.Vaxis, tty: *vaxis.Tty, stop: ?*const std.atomic.Value(bool)) void { var set = posix.sigemptyset(); posix.sigaddset(&set, posix.SIG.WINCH); while (true) { var sig: c_int = 0; if (libc.sigwait(&set, &sig) != 0) continue; + if (stop) |flag| if (flag.load(.acquire)) return; if (vx.state.in_band_resize) continue; // terminal reports via CSI 48 const ws = tty.getWinsize() catch continue; loop.postEvent(.{ .winsize = ws }) catch {}; @@ -2285,12 +2301,11 @@ fn wakeFs(ctx: ?*anyopaque) void { } fn readPty(io: std.Io, gpa: std.mem.Allocator, pty: std.Io.File, id: usize, gen: u32, loop: *Loop) anyerror!void { - var read_buf: [0x10000]u8 = undefined; - var reader = pty.readerStreaming(io, &read_buf); + // One buffer, read into directly: a Reader around it only added a second + // (and in a safe build, filled both as `undefined` on every start). + var buf: [0x10000]u8 = undefined; while (true) { - var buf: [0x10000]u8 = undefined; - var vec = [_][]u8{&buf}; - const n = reader.interface.readVec(&vec) catch break; + const n = pty.readStreaming(io, &.{&buf}) catch break; if (n == 0) break; const bytes = try gpa.dupe(u8, buf[0..n]); loop.postEvent(.{ .pty_read = .{ .id = id, .gen = gen, .bytes = bytes } }) catch { @@ -2301,7 +2316,7 @@ fn readPty(io: std.Io, gpa: std.mem.Allocator, pty: std.Io.File, id: usize, gen: _ = loop.tryPostEvent(.{ .pty_eof = .{ .id = id, .gen = gen } }) catch {}; } -const max_paste_bytes: usize = 4 << 20; +const max_paste_bytes: usize = pardes.memory.limits.max_paste_bytes; fn pasteBytes(key: vaxis.Key) []const u8 { const text = key.text orelse ""; @@ -3023,7 +3038,13 @@ fn attachSession(init: std.process.Init, name: []const u8, tty: *vaxis.Tty, vx: startInput(&loop, &input_cache) catch |err| return .{ .lost = err }; defer stopInput(&loop); - (std.Thread.spawn(.{}, winchWatch, .{ &loop, vx, tty }) catch |err| return .{ .lost = err }).detach(); + var winch_stop: std.atomic.Value(bool) = .init(false); + const winch = std.Thread.spawn(.{}, winchWatchUntil, .{ &loop, vx, tty, &winch_stop }) catch |err| return .{ .lost = err }; + defer { + winch_stop.store(true, .release); + _ = libc.pthread_kill(winch.getHandle(), posix.SIG.WINCH); + winch.join(); + } vx.queryTerminalSend(tty.writer()) catch {}; return attachLoop(&a); diff --git a/test/lspbench.zig b/test/lspbench.zig index d0e25aee..08df9f4c 100644 --- a/test/lspbench.zig +++ b/test/lspbench.zig @@ -110,8 +110,13 @@ test "lspbench options reject unknown flags and multiple roots before probing" { try std.testing.expectError(error.MultipleRoots, Options.parse(&.{ "first", "--check", "second" })); } +/// The process's Io, for the queries: their waits are woken by the client's +/// reader threads, which a single-threaded Io cannot be. +var query_io: std.Io = undefined; + pub fn main(init: std.process.Init) !void { const gpa = std.heap.page_allocator; + query_io = init.io; const args = try init.minimal.args.toSlice(init.arena.allocator()); if (args.len > 1 and std.mem.eql(u8, args[1], "probe")) return probeCommand(init); @@ -171,13 +176,19 @@ fn checkResults(results: []const Result, required: usize) !void { for (results) |r| if (r.empty or !r.correct) return error.IncorrectProbe; } -fn runOnce(gpa: std.mem.Allocator, req: lsp.Req, expected: []const u8, r: *Result) !u64 { - var arena: std.heap.ArenaAllocator = .init(gpa); - defer arena.deinit(); +fn runOnce(gpa: std.mem.Allocator, req_in: lsp.Req, expected: []const u8, r: *Result) !u64 { + // The editor's own path (host_io.Lsp.work): the query in the fixed + // region reserved at startup, not a heap arena that maps its memory anew. + const memory = @import("pardes").memory; + const region = memory.takeLspQuery() orelse return error.QueryRegionBusy; + var arena: std.heap.FixedBufferAllocator = .init(region); + defer memory.giveLspQuery(arena.end_index); + var req = req_in; + req.budget = &arena; var out: std.Io.Writer.Allocating = .init(gpa); defer out.deinit(); const t0 = nowNs(); - try lsp.query(gpa, arena.allocator(), req, &out.writer); + try lsp.query(query_io, gpa, arena.allocator(), req, &out.writer); const ns = nowNs() -| t0; r.accept(out.written(), expected); return ns / 1000; @@ -341,6 +352,7 @@ extern "c" fn usleep(usec: c_uint) c_int; /// [--reps N] [--warm S]`, rows on stdout, the timing on stderr. fn probeCommand(init: std.process.Init) !void { const gpa = std.heap.page_allocator; + query_io = init.io; const arena = init.arena.allocator(); const io = std.Io.Threaded.global_single_threaded.io(); @@ -431,7 +443,7 @@ fn probeCommand(init: std.process.Init) !void { var scratch: std.heap.ArenaAllocator = .init(gpa); defer scratch.deinit(); const t0 = nowUs(); - try lsp.query(gpa, scratch.allocator(), .{ + try lsp.query(query_io, gpa, scratch.allocator(), .{ .kind = kind, .path = path, .source = source, diff --git a/test/panes.zig b/test/panes.zig index e98e3a54..1460b355 100644 --- a/test/panes.zig +++ b/test/panes.zig @@ -1913,9 +1913,6 @@ test "terminal output keeps following new rows after scrollback eviction" { try std.testing.expectEqualStrings("f", effect.write.bytes.slice()); try std.testing.expect(p.nextEffect() == null); } - const replay = &pane.terminal.?.replay; - try std.testing.expectEqual(replay.bytes.len, replay.len); - try std.testing.expect(replay.head > 0); } test "terminal edit stays on its surviving row when old scrollback is evicted" { diff --git a/test/perf-baseline-gui-debug.json b/test/perf-baseline-gui-debug.json index ffcd678f..a41c92b2 100644 --- a/test/perf-baseline-gui-debug.json +++ b/test/perf-baseline-gui-debug.json @@ -1 +1 @@ -{"harness":"15bee9f100e5ef64","build":{"compiler":"0.17.0","target":"x86_64-linux.5.10...7.2-gnu.2.38","cpu":"x86_64","driver_optimize":"fast","core_optimize":"debug","c_optimize":"fast","terminal_optimize":"safe","platform":"gui","grammars":"full","mupdf":true,"jpx":true,"tracy":false,"quic":false,"theme_animation":true,"terminal_simd":true,"prebuilt_shaders":false},"cols":120,"rows":40,"reps":10,"only":"medium","fixtures":[{"name":"small","lines":1000,"cols":60,"bytes":62694},{"name":"medium","lines":50000,"cols":60,"bytes":3201944},{"name":"large","lines":300000,"cols":60,"bytes":19464444},{"name":"longline","lines":400,"cols":8000,"bytes":3200400},{"name":"esp32p4","lines":12,"cols":240,"bytes":2892}],"cells":[{"op":"open","fixture":"medium","min_us":1744,"med_us":1832,"p90_us":2468,"max_us":2524},{"op":"render","fixture":"medium","min_us":88,"med_us":97,"p90_us":114,"max_us":115},{"op":"key-down","fixture":"medium","min_us":95,"med_us":98,"p90_us":104,"max_us":105},{"op":"key-right","fixture":"medium","min_us":92,"med_us":96,"p90_us":98,"max_us":105},{"op":"page-down","fixture":"medium","min_us":91,"med_us":95,"p90_us":97,"max_us":105},{"op":"wheel","fixture":"medium","min_us":87,"med_us":93,"p90_us":99,"max_us":100},{"op":"edit-char","fixture":"medium","min_us":1241,"med_us":1459,"p90_us":1691,"max_us":1724},{"op":"edit-twin","fixture":"medium","min_us":2592,"med_us":3003,"p90_us":3481,"max_us":3503},{"op":"body-2m","fixture":"medium","min_us":4576,"med_us":8262,"p90_us":15424,"max_us":17259},{"op":"body-appends","fixture":"medium","min_us":152003,"med_us":227268,"p90_us":272872,"max_us":326510},{"op":"deep-sel","fixture":"medium","min_us":82,"med_us":83,"p90_us":90,"max_us":93}]} +{"harness":"442f274a5da9136c","build":{"compiler":"0.17.0","target":"x86_64-linux.5.10...7.2-gnu.2.38","cpu":"x86_64","driver_optimize":"fast","core_optimize":"debug","c_optimize":"fast","terminal_optimize":"safe","platform":"gui","grammars":"full","mupdf":true,"jpx":true,"tracy":false,"quic":false,"theme_animation":true,"terminal_simd":true,"prebuilt_shaders":false},"cols":120,"rows":40,"reps":10,"only":"medium","fixtures":[{"name":"small","lines":1000,"cols":60,"bytes":62694},{"name":"medium","lines":50000,"cols":60,"bytes":3201944},{"name":"large","lines":300000,"cols":60,"bytes":19464444},{"name":"longline","lines":400,"cols":8000,"bytes":3200400},{"name":"esp32p4","lines":12,"cols":240,"bytes":2892}],"cells":[{"op":"open","fixture":"medium","min_us":2253,"med_us":2626,"p90_us":3065,"max_us":3090},{"op":"render","fixture":"medium","min_us":100,"med_us":103,"p90_us":103,"max_us":110},{"op":"key-down","fixture":"medium","min_us":102,"med_us":103,"p90_us":105,"max_us":113},{"op":"key-right","fixture":"medium","min_us":98,"med_us":104,"p90_us":108,"max_us":113},{"op":"page-down","fixture":"medium","min_us":103,"med_us":104,"p90_us":111,"max_us":114},{"op":"wheel","fixture":"medium","min_us":98,"med_us":100,"p90_us":102,"max_us":108},{"op":"edit-char","fixture":"medium","min_us":1251,"med_us":1940,"p90_us":2652,"max_us":3041},{"op":"edit-twin","fixture":"medium","min_us":2779,"med_us":3177,"p90_us":3366,"max_us":3657},{"op":"body-2m","fixture":"medium","min_us":5812,"med_us":11423,"p90_us":13681,"max_us":13758},{"op":"body-appends","fixture":"medium","min_us":153898,"med_us":241075,"p90_us":284518,"max_us":305761},{"op":"deep-sel","fixture":"medium","min_us":86,"med_us":91,"p90_us":94,"max_us":122}]} diff --git a/test/perf-baseline-tty-debug.json b/test/perf-baseline-tty-debug.json index b8e534c4..dc37e033 100644 --- a/test/perf-baseline-tty-debug.json +++ b/test/perf-baseline-tty-debug.json @@ -1 +1 @@ -{"harness":"15bee9f100e5ef64","build":{"compiler":"0.17.0","target":"x86_64-linux.5.10...7.2-gnu.2.38","cpu":"x86_64","driver_optimize":"fast","core_optimize":"debug","c_optimize":"fast","terminal_optimize":"safe","platform":"tty","grammars":"full","mupdf":true,"jpx":true,"tracy":false,"quic":false,"theme_animation":true,"terminal_simd":true,"prebuilt_shaders":false},"cols":120,"rows":40,"reps":10,"only":"medium","fixtures":[{"name":"small","lines":1000,"cols":60,"bytes":62694},{"name":"medium","lines":50000,"cols":60,"bytes":3201944},{"name":"large","lines":300000,"cols":60,"bytes":19464444},{"name":"longline","lines":400,"cols":8000,"bytes":3200400},{"name":"esp32p4","lines":12,"cols":240,"bytes":2892}],"cells":[{"op":"open","fixture":"medium","min_us":1747,"med_us":1912,"p90_us":2150,"max_us":2247},{"op":"render","fixture":"medium","min_us":89,"med_us":95,"p90_us":102,"max_us":104},{"op":"key-down","fixture":"medium","min_us":97,"med_us":101,"p90_us":107,"max_us":133},{"op":"key-right","fixture":"medium","min_us":93,"med_us":104,"p90_us":109,"max_us":112},{"op":"page-down","fixture":"medium","min_us":92,"med_us":96,"p90_us":106,"max_us":108},{"op":"wheel","fixture":"medium","min_us":90,"med_us":92,"p90_us":96,"max_us":96},{"op":"edit-char","fixture":"medium","min_us":1167,"med_us":1345,"p90_us":1483,"max_us":1627},{"op":"edit-twin","fixture":"medium","min_us":2319,"med_us":2921,"p90_us":3425,"max_us":3539},{"op":"body-2m","fixture":"medium","min_us":4333,"med_us":7752,"p90_us":15941,"max_us":17192},{"op":"body-appends","fixture":"medium","min_us":149149,"med_us":234177,"p90_us":285302,"max_us":295516},{"op":"deep-sel","fixture":"medium","min_us":83,"med_us":88,"p90_us":99,"max_us":119}]} +{"harness":"442f274a5da9136c","build":{"compiler":"0.17.0","target":"x86_64-linux.5.10...7.2-gnu.2.38","cpu":"x86_64","driver_optimize":"fast","core_optimize":"debug","c_optimize":"fast","terminal_optimize":"safe","platform":"tty","grammars":"full","mupdf":true,"jpx":true,"tracy":false,"quic":false,"theme_animation":true,"terminal_simd":true,"prebuilt_shaders":false},"cols":120,"rows":40,"reps":10,"only":"medium","fixtures":[{"name":"small","lines":1000,"cols":60,"bytes":62694},{"name":"medium","lines":50000,"cols":60,"bytes":3201944},{"name":"large","lines":300000,"cols":60,"bytes":19464444},{"name":"longline","lines":400,"cols":8000,"bytes":3200400},{"name":"esp32p4","lines":12,"cols":240,"bytes":2892}],"cells":[{"op":"open","fixture":"medium","min_us":2181,"med_us":2495,"p90_us":2621,"max_us":2660},{"op":"render","fixture":"medium","min_us":96,"med_us":98,"p90_us":102,"max_us":112},{"op":"key-down","fixture":"medium","min_us":101,"med_us":103,"p90_us":107,"max_us":108},{"op":"key-right","fixture":"medium","min_us":100,"med_us":112,"p90_us":118,"max_us":119},{"op":"page-down","fixture":"medium","min_us":97,"med_us":101,"p90_us":105,"max_us":107},{"op":"wheel","fixture":"medium","min_us":98,"med_us":100,"p90_us":108,"max_us":110},{"op":"edit-char","fixture":"medium","min_us":1377,"med_us":1842,"p90_us":2336,"max_us":2418},{"op":"edit-twin","fixture":"medium","min_us":2655,"med_us":3200,"p90_us":3321,"max_us":3660},{"op":"body-2m","fixture":"medium","min_us":5420,"med_us":10753,"p90_us":12826,"max_us":15385},{"op":"body-appends","fixture":"medium","min_us":153569,"med_us":232519,"p90_us":281625,"max_us":309036},{"op":"deep-sel","fixture":"medium","min_us":91,"med_us":98,"p90_us":111,"max_us":111}]} diff --git a/test/perf-baseline-tty-fast.json b/test/perf-baseline-tty-fast.json index 46125349..bd8f32dc 100644 --- a/test/perf-baseline-tty-fast.json +++ b/test/perf-baseline-tty-fast.json @@ -1 +1 @@ -{"harness":"15bee9f100e5ef64","build":{"compiler":"0.17.0","target":"x86_64-linux.5.10...7.2-gnu.2.38","cpu":"x86_64","driver_optimize":"fast","core_optimize":"fast","c_optimize":"fast","terminal_optimize":"fast","platform":"tty","grammars":"full","mupdf":true,"jpx":true,"tracy":false,"quic":false,"theme_animation":true,"terminal_simd":true,"prebuilt_shaders":false},"cols":120,"rows":40,"reps":10,"only":"medium","fixtures":[{"name":"small","lines":1000,"cols":60,"bytes":62694},{"name":"medium","lines":50000,"cols":60,"bytes":3201944},{"name":"large","lines":300000,"cols":60,"bytes":19464444},{"name":"longline","lines":400,"cols":8000,"bytes":3200400},{"name":"esp32p4","lines":12,"cols":240,"bytes":2892}],"cells":[{"op":"open","fixture":"medium","min_us":1904,"med_us":2040,"p90_us":2290,"max_us":2600},{"op":"render","fixture":"medium","min_us":80,"med_us":83,"p90_us":88,"max_us":93},{"op":"key-down","fixture":"medium","min_us":81,"med_us":87,"p90_us":93,"max_us":109},{"op":"key-right","fixture":"medium","min_us":79,"med_us":82,"p90_us":86,"max_us":96},{"op":"page-down","fixture":"medium","min_us":79,"med_us":83,"p90_us":89,"max_us":93},{"op":"wheel","fixture":"medium","min_us":77,"med_us":79,"p90_us":82,"max_us":83},{"op":"edit-char","fixture":"medium","min_us":1139,"med_us":1338,"p90_us":1453,"max_us":1578},{"op":"edit-twin","fixture":"medium","min_us":2515,"med_us":2776,"p90_us":2879,"max_us":2907},{"op":"body-2m","fixture":"medium","min_us":4832,"med_us":7650,"p90_us":15076,"max_us":15371},{"op":"body-appends","fixture":"medium","min_us":165796,"med_us":240881,"p90_us":284919,"max_us":292573},{"op":"deep-sel","fixture":"medium","min_us":73,"med_us":75,"p90_us":83,"max_us":93}]} +{"harness":"442f274a5da9136c","build":{"compiler":"0.17.0","target":"x86_64-linux.5.10...7.2-gnu.2.38","cpu":"x86_64","driver_optimize":"fast","core_optimize":"fast","c_optimize":"fast","terminal_optimize":"fast","platform":"tty","grammars":"full","mupdf":true,"jpx":true,"tracy":false,"quic":false,"theme_animation":true,"terminal_simd":true,"prebuilt_shaders":false},"cols":120,"rows":40,"reps":10,"only":"medium","fixtures":[{"name":"small","lines":1000,"cols":60,"bytes":62694},{"name":"medium","lines":50000,"cols":60,"bytes":3201944},{"name":"large","lines":300000,"cols":60,"bytes":19464444},{"name":"longline","lines":400,"cols":8000,"bytes":3200400},{"name":"esp32p4","lines":12,"cols":240,"bytes":2892}],"cells":[{"op":"open","fixture":"medium","min_us":2283,"med_us":2611,"p90_us":2812,"max_us":2917},{"op":"render","fixture":"medium","min_us":89,"med_us":97,"p90_us":105,"max_us":119},{"op":"key-down","fixture":"medium","min_us":88,"med_us":95,"p90_us":100,"max_us":116},{"op":"key-right","fixture":"medium","min_us":90,"med_us":99,"p90_us":103,"max_us":106},{"op":"page-down","fixture":"medium","min_us":86,"med_us":90,"p90_us":96,"max_us":97},{"op":"wheel","fixture":"medium","min_us":85,"med_us":91,"p90_us":94,"max_us":101},{"op":"edit-char","fixture":"medium","min_us":1229,"med_us":1823,"p90_us":1874,"max_us":2101},{"op":"edit-twin","fixture":"medium","min_us":2196,"med_us":2745,"p90_us":2928,"max_us":2972},{"op":"body-2m","fixture":"medium","min_us":5606,"med_us":10369,"p90_us":14063,"max_us":14406},{"op":"body-appends","fixture":"medium","min_us":155867,"med_us":237195,"p90_us":289128,"max_us":306283},{"op":"deep-sel","fixture":"medium","min_us":82,"med_us":84,"p90_us":86,"max_us":91}]} diff --git a/test/perf.zig b/test/perf.zig index 7662d028..ab284739 100644 --- a/test/perf.zig +++ b/test/perf.zig @@ -665,8 +665,6 @@ fn measureTerm(op: TermOp, fx: TermFixture, reps: usize) !Cell { .row = pane.body.cur_row, .col = pane.body.cur_col, .edit_len = if (pane.ovl) |overlay| overlay.text.len else 0, - .replay_head = state.replay.head, - .replay_len = state.replay.len, .cols = pane.cols, .rows = pane.rows, }; @@ -689,22 +687,11 @@ fn measureTerm(op: TermOp, fx: TermFixture, reps: usize) !Cell { _ = try frame(core); const dt = nowNs() -| t0; switch (op) { - .render => if (pane.body.cur_row != before.row or pane.body.cur_col != before.col or - state.replay.head != before.replay_head or state.replay.len != before.replay_len) + .render => if (pane.body.cur_row != before.row or pane.body.cur_col != before.col) return error.RenderChangedTerminal, - .output => { - const capacity = state.replay.bytes.len; - if (term_chunk.len == 0 or term_chunk.len >= capacity) return error.InvalidOutputFixture; - const overflow = term_chunk.len -| (capacity - before.replay_len); - if (state.replay.len != @min(capacity, before.replay_len + term_chunk.len) or - state.replay.head != (before.replay_head + overflow) % capacity) - return error.OutputWasNotRecorded; - const start = (state.replay.head + state.replay.len - term_chunk.len) % capacity; - const first = @min(term_chunk.len, capacity - start); - if (!std.mem.eql(u8, term_chunk[0..first], state.replay.bytes[start..][0..first]) or - !std.mem.eql(u8, term_chunk[first..], state.replay.bytes[0 .. term_chunk.len - first])) - return error.WrongTerminalOutput; - }, + // What the output did to the screen is the snapshot suite's to + // check; here it is timed. + .output => if (term_chunk.len == 0) return error.InvalidOutputFixture, .resize_rows => if (pane.rows == before.rows or pane.cols != before.cols or state.vt.screens.active.pages.rows != pane.rows) return error.TerminalDidNotResize, .resize_cols => if (pane.cols == before.cols or pane.rows != before.rows or -- cgit v1.3 From 80314064f6e81c8828340e010202b446f0e1f36d Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Fri, 23 Oct 2026 11:00:44 -0300 Subject: Audit (misc): std mkdir -p and JSON escaping, a 9P late failure's errno from ctl.failureErrno, dead switches and dumpHex out Co-Authored-By: Claude Opus 5.5 --- src/9p_io.zig | 112 +++++++++++++++++++++----------------------------- src/File.zig | 5 +-- src/Output.zig | 52 ++++++----------------- src/builtins.zig | 86 ++++++++++++-------------------------- src/builtins_json.zig | 22 +++------- src/config.zig | 75 ++++++--------------------------- src/dump.zig | 11 +---- src/esp32p4/uart.zig | 16 -------- src/fs.zig | 12 +----- src/gui/gui.zig | 13 ++---- src/hunks.zig | 6 +-- src/locations.zig | 25 +++++------ src/look.zig | 8 ++-- src/main.zig | 40 +++++++----------- src/syntax.zig | 5 +-- src/tagline.zig | 7 +--- src/terminal.zig | 4 +- src/web.zig | 59 +++++--------------------- 18 files changed, 156 insertions(+), 402 deletions(-) (limited to 'src/main.zig') diff --git a/src/9p_io.zig b/src/9p_io.zig index a825475f..a089a7cf 100644 --- a/src/9p_io.zig +++ b/src/9p_io.zig @@ -11,10 +11,7 @@ const quic = if (quic_enabled) @import("9p_quic.zig") else struct {}; const log = std.log.scoped(.ninep); -pub const darwin = switch (builtin.os.tag) { - .macos, .ios, .tvos, .watchos, .visionos => true, - else => false, -}; +pub const darwin = builtin.os.tag.isDarwin(); pub const supported = builtin.os.tag == .linux or darwin; pub const sun_path_len = @typeInfo(@FieldType(libc.sockaddr.un, "path")).array.len; @@ -47,15 +44,8 @@ pub fn statNoFollow(path: [:0]const u8) ?FileFacts { pub fn ensureSocketDir(dir: [:0]const u8) bool { if (dir.len == 0) return false; - var partial: [sun_path_len:0]u8 = undefined; - @memcpy(partial[0 .. dir.len + 1], dir[0 .. dir.len + 1]); - for (1..dir.len) |i| { - if (dir[i] != '/') continue; - partial[i] = 0; - _ = libc.mkdir(partial[0..i :0], 0o700); - partial[i] = '/'; - } - _ = libc.mkdir(dir, 0o700); + // A failure shows in the stat below. + _ = std.Io.Dir.cwd().createDirPathStatus(std.Io.Threaded.global_single_threaded.io(), dir, .fromMode(0o700)) catch {}; const stat = statNoFollow(dir) orelse return false; return stat.mode & 0o170000 == 0o040000 and stat.uid == libc.getuid() and stat.mode & 0o077 == 0; } @@ -394,11 +384,11 @@ pub const Listener = struct { // settle in the same wait is told to this write too. if (l.core == core and core.fs.late_failure_len != 0) { const late = core.fs.late_failure[0..core.fs.late_failure_len]; - // What is not there (`no such directory`) is ENOENT, as a - // builtin's failure saying so is (ctl.failureErrno). - const errno = if (std.mem.indexOf(u8, late, "no such") != null or std.mem.indexOf(u8, late, "not found") != null) - pardes.ctlfs.E.NOENT - else if (std.mem.indexOf(u8, late, "no space") != null) pardes.ctlfs.E.NOSPC else if (std.mem.indexOf(u8, late, "permission denied") != null) pardes.ctlfs.E.PERM else if (std.mem.indexOf(u8, late, "invalid") != null) pardes.ctlfs.E.INVAL else pardes.ctlfs.E.IO; + // The errno a builtin's failure in the same words has; what + // that leaves EIO and says `no space` (a full disk under a + // Save) is ENOSPC. + const said = @import("ninep/ctl.zig").failureErrno(late); + const errno = if (said == pardes.ctlfs.E.IO and std.mem.indexOf(u8, late, "no space") != null) pardes.ctlfs.E.NOSPC else said; const failed = pardes.ctlfs.failText(req.tag, errno, late); // Its err record says it (the path in it), the one record: it // was said with no msg while this waited (fs.write_waits). @@ -1017,21 +1007,11 @@ fn onFatalSignal(s: std.posix.SIG) callconv(.c) void { pub fn sweepDeadSockets(io: std.Io, dir: [:0]const u8) void { if (comptime !supported) return; var names: [8192]u8 = undefined; - var staged: usize = 0; - { - const d = std.Io.Dir.openDirAbsolute(io, dir, .{ .iterate = true }) catch return; - defer d.close(io); - var read_buf: [std.Io.Dir.Iterator.reader_buffer_len]u8 align(@alignOf(usize)) = undefined; - var reader: std.Io.Dir.Reader = .init(d, &read_buf); - while (true) { - const listed = (reader.next(io) catch break) orelse break; - if (deadSocketPid(listed.name) == null) continue; - if (staged + 1 + listed.name.len > names.len) break; - names[staged] = @intCast(listed.name.len); - @memcpy(names[staged + 1 ..][0..listed.name.len], listed.name); - staged += 1 + listed.name.len; + const staged = stageNames(io, dir, &names, struct { + fn keep(name: []const u8) bool { + return deadSocketPid(name) != null; } - } + }.keep); var i: usize = 0; while (i < staged) { const name = names[i + 1 ..][0..names[i]]; @@ -1048,6 +1028,28 @@ pub fn sweepDeadSockets(io: std.Io, dir: [:0]const u8) void { } } +/// The names in `dir` that `keep` takes (all with none), into `names` as a length byte and +/// the name each, until it is full; the bytes staged. They are staged +/// before anything is unlinked, so a sweep never asks a directory to keep +/// reading while it is being edited. +fn stageNames(io: std.Io, dir: [:0]const u8, names: []u8, comptime keep: ?fn ([]const u8) bool) usize { + const d = std.Io.Dir.openDirAbsolute(io, dir, .{ .iterate = true }) catch return 0; + defer d.close(io); + var read_buf: [std.Io.Dir.Iterator.reader_buffer_len]u8 align(@alignOf(usize)) = undefined; + var reader: std.Io.Dir.Reader = .init(d, &read_buf); + var staged: usize = 0; + while (true) { + const listed = (reader.next(io) catch break) orelse break; + if (listed.name.len == 0 or listed.name.len > 255) continue; + if (keep) |takes| if (!takes(listed.name)) continue; + if (staged + 1 + listed.name.len > names.len) break; + names[staged] = @intCast(listed.name.len); + @memcpy(names[staged + 1 ..][0..listed.name.len], listed.name); + staged += 1 + listed.name.len; + } + return staged; +} + /// The pid a `pardes-9p-.sock` name carries, or null for any other. fn deadSocketPid(name: []const u8) ?std.c.pid_t { if (!std.mem.startsWith(u8, name, prefix) or !std.mem.endsWith(u8, name, ".sock")) return null; @@ -1279,24 +1281,8 @@ fn ourSocket(target: []const u8, sockets: []const u8) bool { fn sweepRegistry(io: std.Io, svc: [:0]const u8, sockets: []const u8) void { if (comptime !supported) return; - // The names are staged before anything is unlinked, so the sweep - // never asks a directory to keep reading while it is being edited. var names: [4096]u8 = undefined; - var staged: usize = 0; - { - const dir = std.Io.Dir.openDirAbsolute(io, svc, .{ .iterate = true }) catch return; - defer dir.close(io); - var read_buf: [std.Io.Dir.Iterator.reader_buffer_len]u8 align(@alignOf(usize)) = undefined; - var reader: std.Io.Dir.Reader = .init(dir, &read_buf); - while (true) { - const listed = (reader.next(io) catch break) orelse break; - if (listed.name.len == 0 or listed.name.len > 255) continue; - if (staged + 1 + listed.name.len > names.len) break; - names[staged] = @intCast(listed.name.len); - @memcpy(names[staged + 1 ..][0..listed.name.len], listed.name); - staged += 1 + listed.name.len; - } - } + const staged = stageNames(io, svc, &names, null); var reaped: usize = 0; var i: usize = 0; @@ -2179,10 +2165,8 @@ pub const Client = struct { if (comptime !supported) return error.Unsupported; var names: [max_depth][]const u8 = undefined; const n = try elements(path, &names); - var sock_buf: [sun_path_len]u8 = undefined; - const sock = try resolve(&sock_buf, dial); var remote: RemoteError = .{}; - return fetchBytes(gpa, sock, names[0..n], &remote, null, display_path, @min(max_bytes, limits.max_file_bytes)) catch |err| { + return fetchBytes(gpa, dial, names[0..n], &remote, null, display_path, @min(max_bytes, limits.max_file_bytes)) catch |err| { if (err == error.Remote) said = remote; return err; }; @@ -2209,10 +2193,8 @@ pub const Client = struct { if (comptime !supported) return error.Unsupported; var names: [max_depth][]const u8 = undefined; const n = try elements(path, &names); - var sock_buf: [sun_path_len]u8 = undefined; - const sock = try resolve(&sock_buf, dial); var remote: RemoteError = .{}; - const result = fetchBytes(gpa, sock, names[0..n], &remote, bytes, path, limits.max_file_bytes) catch |err| { + const result = fetchBytes(gpa, dial, names[0..n], &remote, bytes, path, limits.max_file_bytes) catch |err| { if (err == error.Remote) said = remote; return err; }; @@ -2470,7 +2452,7 @@ pub const Client = struct { fn fetchBytes( gpa: std.mem.Allocator, - sock: Dial, + dial: []const u8, names: []const []const u8, remote: *RemoteError, write_bytes: ?[]const u8, @@ -2478,7 +2460,7 @@ pub const Client = struct { read_limit: usize, ) ![]u8 { if (comptime !supported) return Error.Dial; - const s = try startSession(gpa, sock, display_path); + const s = try startSession(gpa, dial, display_path); defer endSession(gpa, s); var out: std.Io.Writer.Allocating = .init(gpa); errdefer out.deinit(); @@ -2486,8 +2468,10 @@ pub const Client = struct { return out.toOwnedSlice(); } - /// A connected session whose requests have the usual deadline. - fn startSession(gpa: std.mem.Allocator, sock: Dial, display_path: []const u8) !*Session { + /// A connected session at `dial` whose requests have the usual deadline. + fn startSession(gpa: std.mem.Allocator, dial: []const u8, display_path: []const u8) !*Session { + var sock_buf: [sun_path_len]u8 = undefined; + const sock = try resolve(&sock_buf, dial); const deadline = nowMs() +| budget_ms; const s = try gpa.create(Session); s.* = .{ .fd = -1, .deadline = deadline, .display_path = display_path }; @@ -2518,11 +2502,9 @@ pub const Client = struct { if (comptime !supported) return error.Unsupported; var names: [max_depth][]const u8 = undefined; const n = try elements(path, &names); - var sock_buf: [sun_path_len]u8 = undefined; - const sock = try resolve(&sock_buf, dial); var remote: RemoteError = .{}; errdefer said = remote; - const s = try startSession(gpa, sock, path); + const s = try startSession(gpa, dial, path); defer endSession(gpa, s); const fid = (try walkTo(s, names[0..n], &remote)).fid; _ = try s.ask(.{ .open = .{ .fid = fid, .mode = ninep.ordwr } }, &remote); @@ -2562,10 +2544,8 @@ pub const Client = struct { if (comptime !supported) return error.Unsupported; var names: [max_depth][]const u8 = undefined; const n = try elements(path, &names); - var sock_buf: [sun_path_len]u8 = undefined; - const sock = try resolve(&sock_buf, dial); var remote: RemoteError = .{}; - const s = try startSession(gpa, sock, path); + const s = try startSession(gpa, dial, path); defer endSession(gpa, s); const fid = (try walkTo(s, names[0..n], &remote)).fid; _ = try s.ask(.{ .open = .{ .fid = fid, .mode = ninep.ordwr } }, &remote); @@ -2642,7 +2622,7 @@ pub const Client = struct { const before = nowMs(); try testing.expectError( Error.Dial, - fetchBytes(testing.allocator, .{ .unix = "/tmp/pardes-9p-no-such-socket.sock" }, names[0..n], &remote, null, "/pane/1/body", limits.max_file_bytes), + fetchBytes(testing.allocator, "/tmp/pardes-9p-no-such-socket.sock", names[0..n], &remote, null, "/pane/1/body", limits.max_file_bytes), ); try testing.expect(nowMs() - before < budget_ms); } diff --git a/src/File.zig b/src/File.zig index e92efaba..b1a4271f 100644 --- a/src/File.zig +++ b/src/File.zig @@ -2153,15 +2153,14 @@ pub const DiffOutput = struct { text[at] = '\n'; at += 1; } + // An empty slot, else the least recently used. var oldest: usize = 0; for (&o.slots, 0..) |*slot, i| { const e = slot.* orelse { oldest = i; break; }; - if (o.slots[oldest]) |old| if (e.used < old.used) { - oldest = i; - }; + if (e.used < o.slots[oldest].?.used) oldest = i; } if (o.slots[oldest]) |old| { p.gpa.free(old.text); diff --git a/src/Output.zig b/src/Output.zig index 3fc08d9a..9a11b2fc 100644 --- a/src/Output.zig +++ b/src/Output.zig @@ -949,51 +949,23 @@ fn helpContent(gpa: std.mem.Allocator, prefix: []const u8) ![]u8 { "C-left-click definition, by mouse\n" ++ "SPC l ... hover, rename, symbols,\n" ++ " calls, types: above\n"; - var len: usize = if (prefix.len == 0) - full_header.len + language_footer.len - else - group_header.len + prefix.len * 2 + 2; - if (show_calls_help) len += calls_help.len; + var out: std.Io.Writer.Allocating = .init(gpa); + errdefer out.deinit(); + const w = &out.writer; + if (prefix.len == 0) try w.writeAll(full_header) else { + try w.writeAll(group_header); + for (prefix) |c| try w.print(" {c}", .{c}); + try w.writeAll("\n\n"); + } for (pardes.builtin_rows) |row| { // a path-less builtin filters as the empty path: in the full listing // (which starts with nothing) and out of every group if (!std.mem.startsWith(u8, row.path orelse "", prefix)) continue; - len += row.line.len + 1; - } - const content = try gpa.alloc(u8, len); - var at: usize = 0; - if (prefix.len == 0) { - @memcpy(content[0..full_header.len], full_header); - at = full_header.len; - } else { - @memcpy(content[0..group_header.len], group_header); - at = group_header.len; - for (prefix) |c| { - content[at] = ' '; - content[at + 1] = c; - at += 2; - } - content[at] = '\n'; - content[at + 1] = '\n'; - at += 2; - } - for (pardes.builtin_rows) |row| { - if (!std.mem.startsWith(u8, row.path orelse "", prefix)) continue; - @memcpy(content[at..][0..row.line.len], row.line); - at += row.line.len; - content[at] = '\n'; - at += 1; - } - if (show_calls_help) { - @memcpy(content[at..][0..calls_help.len], calls_help); - at += calls_help.len; - } - if (prefix.len == 0) { - @memcpy(content[at..][0..language_footer.len], language_footer); - at += language_footer.len; + try w.print("{s}\n", .{row.line}); } - std.debug.assert(at == content.len); - return content; + if (show_calls_help) try w.writeAll(calls_help); + if (prefix.len == 0) try w.writeAll(language_footer); + return out.toOwnedSlice(); } pub fn openHelp(p: *Pardes, id: usize, prefix: []const u8) !void { diff --git a/src/builtins.zig b/src/builtins.zig index 7b1541ac..64710554 100644 --- a/src/builtins.zig +++ b/src/builtins.zig @@ -109,54 +109,27 @@ pub fn absentWhy(name: []const u8) ?[]const u8 { return null; } -fn manualBuiltinCount() comptime_int { +fn manualBuiltinList() []const type { comptime { - var count = 0; + @setEvalBranchQuota(4000); + var list: []const type = &.{}; for (@typeInfo(@This()).@"struct".decl_names) |d| { if (@TypeOf(@field(@This(), d)) != type) continue; const T = @field(@This(), d); if (@typeInfo(T) != .@"struct" or !@hasDecl(T, "run") or !isEnabled(T)) continue; if (@TypeOf(T.run) != fn (Ctx) void) @compileError(d ++ ".run must have signature fn (Ctx) void"); - count += 1; - } - return count; - } -} - -fn manualBuiltinList() [manualBuiltinCount()]type { - comptime { - @setEvalBranchQuota(4000); - var list: [manualBuiltinCount()]type = undefined; - var count = 0; - for (@typeInfo(@This()).@"struct".decl_names) |d| { - if (@TypeOf(@field(@This(), d)) != type) continue; - const T = @field(@This(), d); - if (@typeInfo(T) != .@"struct" or !@hasDecl(T, "run") or !isEnabled(T)) continue; - list[count] = T; - count += 1; + list = list ++ .{T}; } return list; } } -fn settingCount() comptime_int { +fn settingList() []const config.Runtime.Setting { comptime { - var count = 0; + var list: []const config.Runtime.Setting = &.{}; for (config.Runtime.settings) |setting| if (setting.enabled(capabilities)) { - count += 1; - }; - return count; - } -} - -fn settingList() [settingCount()]config.Runtime.Setting { - comptime { - var list: [settingCount()]config.Runtime.Setting = undefined; - var count = 0; - for (config.Runtime.settings) |setting| if (setting.enabled(capabilities)) { - list[count] = setting; - count += 1; + list = list ++ .{setting}; }; return list; } @@ -197,11 +170,17 @@ pub const registry = struct { return @Enum(Tag, .exhaustive, &names, &std.simd.iota(Tag, count)); } + /// What a hand-written builtin says as `name` (`pub const takes_arg = + /// true;`), `default` when it says nothing, and `setting` for a setting. + fn declOr(b: Builtin(), comptime name: []const u8, default: anytype, setting: @TypeOf(default)) @TypeOf(default) { + inline for (comptime manualBuiltinList(), 0..) |T, i| + if (@backingInt(b) == i) return if (@hasDecl(T, name)) @field(T, name) else default; + return setting; + } + pub fn takesArg(b: Builtin()) bool { - inline for (manualBuiltinList(), 0..) |T, i| - if (@backingInt(b) == i) return @hasDecl(T, "takes_arg") and T.takes_arg; // Every setting takes its value, and a switch flips when bare. - return true; + return declOr(b, "takes_arg", false, true); } /// Whether the word takes its argument joined by a `+` as one word a @@ -209,9 +188,7 @@ pub const registry = struct { /// that says `pub const plus_arg = true;`: others have arguments a `+` /// may be in (`Dump+2024.zon` is a name, not Dump's argument). pub fn plusArg(b: Builtin()) bool { - inline for (manualBuiltinList(), 0..) |T, i| - if (@backingInt(b) == i) return @hasDecl(T, "plus_arg") and T.plus_arg; - return false; + return declOr(b, "plus_arg", false, false); } /// Whether the word means nothing without its argument (`Mount`, @@ -222,15 +199,11 @@ pub const registry = struct { /// it says `pub const needs: PaneKind = .terminal;`, and on any other /// pane it is refused (exec.runBuiltinFrom), as Repl and Edit are. pub fn needs(b: Builtin()) ?PaneKind { - inline for (manualBuiltinList(), 0..) |T, i| - if (@backingInt(b) == i) return if (@hasDecl(T, "needs")) T.needs else null; - return null; + return declOr(b, "needs", @as(?PaneKind, null), null); } pub fn requiresArg(b: Builtin()) bool { - inline for (manualBuiltinList(), 0..) |T, i| - if (@backingInt(b) == i) return @hasDecl(T, "requires_arg") and T.requires_arg; - inline for (comptime settingList(), manualBuiltinCount()..) |setting, i| + inline for (comptime settingList(), comptime manualBuiltinList().len..) |setting, i| if (@backingInt(b) == i) return switch (setting.action) { // a switch flips bare, a choice steps, and DumpDir and Shell bare // are the default @@ -239,35 +212,28 @@ pub const registry = struct { // bare, it says the current value (exec.applySettingBuiltin) .tab, .callstack_depth => false, }; - unreachable; + return declOr(b, "requires_arg", false, false); } pub fn scope(b: Builtin()) Scope { - inline for (manualBuiltinList(), 0..) |T, i| - if (@backingInt(b) == i) return if (@hasDecl(T, "scope")) T.scope else .pane; - return .session; // a setting + return declOr(b, "scope", Scope.pane, .session); } pub fn outputTraits(b: Builtin()) ?OutputTraits { - inline for (manualBuiltinList(), 0..) |T, i| - if (@backingInt(b) == i) return if (@hasDecl(T, "output")) T.output else null; - inline for (comptime settingList(), manualBuiltinCount()..) |_, i| - if (@backingInt(b) == i) return null; - unreachable; + return declOr(b, "output", @as(?OutputTraits, null), null); } /// Does this builtin say its own name on the message row before it runs? /// The ones that own that row themselves declare `quiet` and do not. pub fn announces(b: Builtin()) bool { - inline for (manualBuiltinList(), 0..) |T, i| - if (@backingInt(b) == i) return !(@hasDecl(T, "quiet") and T.quiet); - return true; // a setting builtin changes something invisible; say so + // a setting builtin changes something invisible; say so + return !declOr(b, "quiet", false, false); } pub fn dispatch(b: Builtin(), c: Ctx) void { - inline for (manualBuiltinList(), 0..) |T, i| + inline for (comptime manualBuiltinList(), 0..) |T, i| if (@backingInt(b) == i) return T.run(c); - inline for (comptime settingList(), manualBuiltinCount()..) |setting, i| + inline for (comptime settingList(), comptime manualBuiltinList().len..) |setting, i| if (@backingInt(b) == i) return exec.applySettingBuiltin(c.p, setting, c.arg); unreachable; } diff --git a/src/builtins_json.zig b/src/builtins_json.zig index 7f998388..4440130d 100644 --- a/src/builtins_json.zig +++ b/src/builtins_json.zig @@ -11,17 +11,7 @@ const builtins = @import("builtins.zig"); const config = @import("config.zig"); const ctl = @import("ninep/ctl.zig"); -fn str(w: *std.Io.Writer, s: []const u8) !void { - try w.writeByte('"'); - for (s) |c| switch (c) { - '"' => try w.writeAll("\\\""), - '\\' => try w.writeAll("\\\\"), - '\n' => try w.writeAll("\\n"), - 0...9, 11...0x1f => try w.print("\\u{x:0>4}", .{c}), - else => try w.writeByte(c), - }; - try w.writeByte('"'); -} +const str = std.json.Stringify.encodeJsonString; const Entry = struct { name: []const u8, row: usize }; @@ -39,7 +29,7 @@ pub fn write(w: *std.Io.Writer) !void { const b = row.cmd; const name = @tagName(b); try w.writeAll(" {\"name\": "); - try str(w, name); + try str(name, .{}, w); try w.writeAll(", \"leader\": "); if (row.path) |p| { try w.writeAll("\"SPC"); @@ -55,21 +45,21 @@ pub fn write(w: *std.Io.Writer) !void { while (parts.next()) |part| if (part.len > 0) { if (!first) try w.writeAll(", "); first = false; - try str(w, part); + try str(part, .{}, w); }; try w.writeAll("], \"arg\": "); try w.writeAll(if (builtins.registry.takesArg(b)) "true" else "false"); try w.writeAll(", \"scope\": "); - try str(w, if (b == .Edit) "both" else if (builtins.registry.scope(b) == .session) "root" else "pane"); + try str(if (b == .Edit) "both" else if (builtins.registry.scope(b) == .session) "root" else "pane", .{}, w); const setting = config.Runtime.find(name); try w.writeAll(", \"setting\": "); try w.writeAll(if (setting != null) "true" else "false"); try w.writeAll(", \"choices\": "); - if (setting) |s| if (config.Runtime.choices(s.action)) |v| try str(w, v) else try w.writeAll("null") else try w.writeAll("null"); + if (setting) |s| if (config.Runtime.choices(s.action)) |v| try str(v, .{}, w) else try w.writeAll("null") else try w.writeAll("null"); var buf: [2048]u8 = undefined; const doc = if (setting) |s| s.doc else ctl.summaryOf(name, &buf); try w.writeAll(", \"doc\": "); - try str(w, doc); + try str(doc, .{}, w); try w.writeAll(if (n + 1 < order.len) "},\n" else "}\n"); } try w.writeAll("]\n"); diff --git a/src/config.zig b/src/config.zig index 5251b1e5..1fbf0d1b 100644 --- a/src/config.zig +++ b/src/config.zig @@ -293,9 +293,6 @@ pub const back_out: []const Chord = &.{.{ .cp = Key.escape, .shift = true }}; pub const tty_toggle_default: u21 = 'b'; -// OSC 133 prompt cells are hidden in normal mode; input columns stay intact. -pub const tty_blank: enum { prompt, prompt_and_input } = .prompt; - // Projected colors below this contrast use the theme's more legible anchor. pub const tty_filter_min_contrast: f64 = 1.5; @@ -386,9 +383,6 @@ pub const gui_topbar_pane_border_px: u8 = 1; // null follows the theme's scrollbar track. pub const gui_topbar_pane_border_rgb: ?[3]u8 = null; -// Transparency requires the SDL readback/blit path, even with an opaque theme. -pub const gui_transparent: bool = false; - // A vertical wheel tick suppresses this many subsequent horizontal ticks. pub const wheel_guard_ticks: u8 = 3; @@ -1428,12 +1422,12 @@ pub const Runtime = struct { /// effect but set by no word follows, after a blank line. pub fn writeReport(out: *std.Io.Writer, context: ReportContext) !void { const state = context.state; - for (settings) |setting| switch (setting.action) { + // TaglineSize is said wherever the shell sizes its tag, by its word + // or only at build time. + for (settings) |setting| if (!(if (setting.action == .tagline_size) context.capabilities.tagline_font_size else setting.enabled(context.capabilities))) + try out.print("# {s} unsupported\n", .{setting.word}) + else switch (setting.action) { .toggle => |field| { - if (!setting.enabled(context.capabilities)) { - try out.print("# {s} unsupported\n", .{setting.word}); - continue; - } const value = switch (field) { inline else => |f| @field(state, @tagName(f)), }; @@ -1443,18 +1437,8 @@ pub const Runtime = struct { try out.print("ThemeFile {s}\n", .{path}) else try out.print("{s} {s}\n", .{ setting.word, context.theme_name }), - .window_opacity => { - if (setting.enabled(context.capabilities)) - try out.print("{s} {d}\n", .{ setting.word, state.window_opacity }) - else - try out.print("# {s} unsupported\n", .{setting.word}); - }, - .window_blur => { - if (setting.enabled(context.capabilities)) - try out.print("{s} {d}\n", .{ setting.word, state.window_blur }) - else - try out.print("# {s} unsupported\n", .{setting.word}); - }, + .window_opacity => try out.print("{s} {d}\n", .{ setting.word, state.window_opacity }), + .window_blur => try out.print("{s} {d}\n", .{ setting.word, state.window_blur }), .dump_dir => { const dir = if (state.dump_dir.len > 0) state.dump_dir.get() else context.default_dump_dir; if (dir.len > 0) try out.print("{s} {s}\n", .{ setting.word, dir }) else try out.print("# {s} (none)\n", .{setting.word}); @@ -1466,9 +1450,7 @@ pub const Runtime = struct { const chosen = state.shell.requested.get(); try out.print("{s} {s}\n", .{ setting.word, if (chosen.len == 0) context.compiled_default_shell else chosen }); }, - .font => if (!setting.enabled(context.capabilities)) - try out.print("# {s} unsupported\n", .{setting.word}) - else { + .font => { // As `Font` takes it, `name:size`: the one asked for, else // the one in use. const f = &state.font; @@ -1483,28 +1465,14 @@ pub const Runtime = struct { if (f.requested_size_hundredths != 0) try out.print(":{d}.{d:0>2}", .{ f.requested_size_hundredths / 100, f.requested_size_hundredths % 100 }); try out.writeByte('\n'); }, - .tagline_size => if (!context.capabilities.tagline_font_size) - try out.print("# {s} unsupported\n", .{setting.word}) - else - try out.print("{s} {d}\n", .{ setting.word, state.font.tagline_percent }), + .tagline_size => try out.print("{s} {d}\n", .{ setting.word, state.font.tagline_percent }), // Each a switch of its own, the one in use on. - .transition => |transition| if (!setting.enabled(context.capabilities)) - try out.print("# {s} unsupported\n", .{setting.word}) - else - try out.print("{s} {s}\n", .{ setting.word, onOff(state.panel_transition == transition) }), + .transition => |transition| try out.print("{s} {s}\n", .{ setting.word, onOff(state.panel_transition == transition) }), .scene => |effect| { - if (!setting.enabled(context.capabilities)) { - try out.print("# {s} unsupported\n", .{setting.word}); - continue; - } const level = state.post.level(effect); if (level == 0) try out.print("{s} off\n", .{setting.word}) else try out.print("{s} {d}\n", .{ setting.word, level }); }, .shader => { - if (!setting.enabled(context.capabilities)) { - try out.print("# {s} unsupported\n", .{setting.word}); - continue; - } var files: usize = 0; for (state.post.list()) |entry| if (entry.scene == null) { try out.print("{s} {s}\n", .{ setting.word, entry.path.get() }); @@ -1512,25 +1480,16 @@ pub const Runtime = struct { }; if (files == 0) try out.print("{s} off\n", .{setting.word}); }, - .shader_animation => if (setting.enabled(context.capabilities)) - try out.print("{s} {s}\n", .{ setting.word, @tagName(state.shader_animation) }) - else - try out.print("# {s} unsupported\n", .{setting.word}), + .shader_animation => try out.print("{s} {s}\n", .{ setting.word, @tagName(state.shader_animation) }), .choice => |which| switch (which) { inline else => |field| try out.print("{s} {s}\n", .{ setting.word, @tagName(@field(state, @tagName(field))) }), }, - .lift => if (setting.enabled(context.capabilities)) - try out.print("{s} {s}\n", .{ setting.word, @tagName(state.lift) }) - else - try out.print("# {s} unsupported\n", .{setting.word}), + .lift => try out.print("{s} {s}\n", .{ setting.word, @tagName(state.lift) }), .motion => try out.print("{s} {s}\n", .{ setting.word, @tagName(state.motion) }), .inactive_dim => try out.print("{s} {d}\n", .{ setting.word, state.inactive_dim }), .callstack_depth => try out.print("{s} {d}\n", .{ setting.word, state.callstack_depth }), .tab => try out.print("{s} {d}\n", .{ setting.word, state.tab }), - .grip_width => if (setting.enabled(context.capabilities)) - try out.print("{s} {d}\n", .{ setting.word, state.grip_width }) - else - try out.print("# {s} unsupported\n", .{setting.word}), + .grip_width => try out.print("{s} {d}\n", .{ setting.word, state.grip_width }), }; if (context.locations.len > 0) try out.print("LocationsConfig {s}\n", .{context.locations}); @@ -1566,14 +1525,6 @@ pub const Runtime = struct { try out.print("# Pet: {s}\n", .{@tagName(state.pet)}); } - test "setting names are unique" { - for (settings, 0..) |setting, i| { - try std.testing.expect(setting.word.len > 0); - for (settings[i + 1 ..]) |later| - try std.testing.expect(!std.mem.eql(u8, setting.word, later.word)); - } - } - test "panel and scene effects flip bare and are set by on and off" { var state: Runtime = .{}; const slide = findAction(.{ .transition = .slide }).?; diff --git a/src/dump.zig b/src/dump.zig index 67934e0a..c8c302ab 100644 --- a/src/dump.zig +++ b/src/dump.zig @@ -38,16 +38,7 @@ pub fn outPath(buf: *[1024:0]u8, dir_setting: []const u8) ?[:0]const u8 { return std.fmt.bufPrintSentinel(buf, "{s}", .{std.mem.span(p)}, 0) catch null; var dir_buf: [900]u8 = undefined; const dir = directory(&dir_buf, dir_setting) orelse return null; - var dz: [901:0]u8 = undefined; - @memcpy(dz[0..dir.len], dir); - dz[dir.len] = 0; - // Each missing directory on the way, as `mkdir -p`: EEXIST is fine. - for (dz[1..dir.len], 1..) |c, i| if (c == '/') { - dz[i] = 0; - _ = std.c.mkdir(dz[0..i :0], 0o755); - dz[i] = '/'; - }; - _ = std.c.mkdir(dz[0..dir.len :0], 0o755); + _ = std.Io.Dir.cwd().createDirPathStatus(std.Io.Threaded.global_single_threaded.io(), dir, .fromMode(0o755)) catch {}; var ts: std.c.timespec = undefined; _ = std.c.clock_gettime(.REALTIME, &ts); const es: std.time.epoch.EpochSeconds = .{ .secs = @intCast(@max(0, ts.sec)) }; diff --git a/src/esp32p4/uart.zig b/src/esp32p4/uart.zig index 5690520c..a185737d 100644 --- a/src/esp32p4/uart.zig +++ b/src/esp32p4/uart.zig @@ -126,22 +126,6 @@ pub fn writeByte(b: u8) void { uart0.pushByte(b); } -/// Emit `n` bytes read from `addr` as two hex digits each, computing the digits arithmetically so -/// nothing here reads a lookup table. Used to answer "does a load from this address return what the -/// linker put there", which is not a question a string literal can be trusted to ask. -pub fn dumpHex(addr: u32, n: u32) void { - const p: [*]const volatile u8 = @ptrFromInt(addr); - var i: u32 = 0; - while (i < n) : (i += 1) { - const byte = p[i]; - for ([2]u8{ byte >> 4, byte & 0xf }) |nib| { - writeByte(if (nib < 10) '0' + nib else 'a' + (nib - 10)); - } - } - writeByte('\r'); - writeByte('\n'); -} - /// A u32 as eight hex digits, reading no memory at all. pub fn dumpWord(v: u32) void { var shift: u5 = 28; diff --git a/src/fs.zig b/src/fs.zig index 032ab9c0..e809eda5 100644 --- a/src/fs.zig +++ b/src/fs.zig @@ -686,18 +686,10 @@ test "a path with a part over 255 bytes is NameTooLong, never a panic" { /// that follows. pub fn makeDirs(dir: []const u8) void { if (comptime !platform_has_fs) return; - var z: [4096:0]u8 = undefined; - if (dir.len == 0 or dir.len >= z.len) return; - @memcpy(z[0..dir.len], dir); - z[dir.len] = 0; + if (dir.len == 0) return; pardes.turn.yield(); defer pardes.turn.back(); - for (z[1..dir.len], 1..) |c, i| if (c == '/') { - z[i] = 0; - _ = libc.mkdir(z[0..i :0], 0o755); - z[i] = '/'; - }; - _ = libc.mkdir(z[0..dir.len :0], 0o755); + _ = std.Io.Dir.cwd().createDirPathStatus(std.Io.Threaded.global_single_threaded.io(), dir, .fromMode(0o755)) catch {}; } /// Whether `dir` is not there to make because one above it refuses: its diff --git a/src/gui/gui.zig b/src/gui/gui.zig index 2d01db33..795ea743 100644 --- a/src/gui/gui.zig +++ b/src/gui/gui.zig @@ -54,11 +54,6 @@ const Ground = struct { } }; -fn ground(theme_bg: ?[3]u8, transparent: bool) Ground { - if (theme_bg) |rgb| return .opaqueRgb(rgb); - return .{ .rgb = bg_default, .clear = transparent }; -} - const p9_arrow_clr = [32]u8{ 0xFF, 0xFF, 0x80, 0x01, 0x80, 0x02, 0x80, 0x0C, 0x80, 0x10, 0x80, 0x10, 0x80, 0x08, 0x80, 0x04, @@ -1769,7 +1764,6 @@ const Gui = struct { capture_xfer_size: u32 = 0, soft_present: bool = false, - transparent: bool = false, surface_opacity: bool = false, applied_window_opacity: u8 = 100, soft_renderer: ?*c.SDL_Renderer = null, @@ -2187,7 +2181,7 @@ fn runNative(init: std.process.Init, opts_in: pardes.Options, attach: ?[]const u const native_wayland = !test_mode and std.mem.eql(u8, std.mem.span(c.SDL_GetCurrentVideoDriver()), "wayland"); // Background-only opacity needs per-pixel alpha; whole-window compositor // opacity would dim the text as well. SDL requires this flag at creation. - const surface_opacity = config.gui_transparent or native_wayland; + const surface_opacity = native_wayland; if (surface_opacity) win_flags |= c.SDL_WINDOW_TRANSPARENT; const window = c.SDL_CreateWindow("pardes", 1120, 720, win_flags) orelse { log.err("SDL_CreateWindow: {s}", .{c.SDL_GetError()}); @@ -2391,7 +2385,6 @@ fn runNative(init: std.process.Init, opts_in: pardes.Options, attach: ?[]const u .capture_series = test_mode and env.get("PARDES_TEST_SERIES") != null, .capture_dir = capture_dir orelse "", .soft_present = soft_present, - .transparent = config.gui_transparent, .surface_opacity = surface_opacity, .soft_renderer = soft_renderer, }; @@ -6092,7 +6085,7 @@ fn renderFrame( coverFrame(previous_covered, surface.cols, surface.rows, surface.previous_body_layers, surface.previous_tag_layers, surface.previous_regions); try buildDecor(g, gpa, surface, &groups, layout, win_w, win_h, cursors_shown); - const page = ground(chrome.page, g.transparent); + const page: Ground = .opaqueRgb(chrome.page orelse bg_default); const background_opacity = backgroundOpacity(g.applied_window_opacity); var color_target = std.mem.zeroes(c.SDL_GPUColorTargetInfo); color_target.texture = scene; @@ -8449,7 +8442,7 @@ fn softPresentFrame(g: *Gui, cmd: *c.SDL_GPUCommandBuffer, target: *c.SDL_GPUTex // The cell shader already produced premultiplied backgrounds with opaque // foreground ink. Copy that alpha unchanged; never modulate the full frame. _ = c.SDL_SetRenderDrawBlendMode(renderer, c.SDL_BLENDMODE_NONE); - _ = c.SDL_SetRenderDrawColor(renderer, 0, 0, 0, if (g.transparent or g.surface_opacity) 0 else 255); + _ = c.SDL_SetRenderDrawColor(renderer, 0, 0, 0, if (g.surface_opacity) 0 else 255); _ = c.SDL_RenderClear(renderer); _ = c.SDL_RenderTexture(renderer, texture, null, null); _ = c.SDL_RenderPresent(renderer); diff --git a/src/hunks.zig b/src/hunks.zig index 24aaf63d..8cd5c43a 100644 --- a/src/hunks.zig +++ b/src/hunks.zig @@ -111,11 +111,7 @@ const Out = struct { fn deinit(out: *Out) void { out.text.deinit(); - for (out.rows.items) |r| { - out.p.gpa.free(r.path); - out.p.gpa.free(r.colors); - } - out.rows.deinit(out.p.gpa); + locations.freeRowList(out.p.gpa, &out.rows); } const Meta = struct { diff --git a/src/locations.zig b/src/locations.zig index 1e4a20cf..6f086214 100644 --- a/src/locations.zig +++ b/src/locations.zig @@ -33,6 +33,15 @@ pub fn freeRows(gpa: std.mem.Allocator, rows: []Row) void { gpa.free(rows); } +/// A list of rows being built, given up: each row's own bytes, then the list. +pub fn freeRowList(gpa: std.mem.Allocator, rows: *std.ArrayList(Row)) void { + for (rows.items) |row| { + gpa.free(row.path); + gpa.free(row.colors); + } + rows.deinit(gpa); +} + pub fn equalRows(a: []const Row, b: []const Row) bool { if (a.len != b.len) return false; for (a, b) |left, right| { @@ -316,13 +325,7 @@ pub fn formatCallstack(p: *pardes.Pardes, dir: []const u8, input: []const u8) !R var out: std.Io.Writer.Allocating = .init(p.gpa); errdefer out.deinit(); var rows: std.ArrayList(Row) = .empty; - errdefer { - for (rows.items) |row| { - p.gpa.free(row.path); - p.gpa.free(row.colors); - } - rows.deinit(p.gpa); - } + errdefer freeRowList(p.gpa, &rows); const stacked = p.settings.callstack_layout == .stacked; const resolved = try resolveCallstack(p, arena, dir, input); var lines = std.mem.splitScalar(u8, std.mem.trimEnd(u8, input, "\n"), '\n'); @@ -496,13 +499,7 @@ pub fn format(p: *pardes.Pardes, dir: []const u8, input: []const u8, anchor: ?us var out: std.Io.Writer.Allocating = .init(p.gpa); errdefer out.deinit(); var rows: std.ArrayList(Row) = .empty; - errdefer { - for (rows.items) |row| { - p.gpa.free(row.path); - p.gpa.free(row.colors); - } - rows.deinit(p.gpa); - } + errdefer freeRowList(p.gpa, &rows); var mapped = anchor; if (p.locations_config.layout == .stacked) { for (pending.items, 0..) |row, index| { diff --git a/src/look.zig b/src/look.zig index 588574ed..2d97cb9f 100644 --- a/src/look.zig +++ b/src/look.zig @@ -32,9 +32,7 @@ const Key = pardes.Key; const Event = pardes.Event; const Pardes = pardes.Pardes; -extern "c" fn fork() c_int; extern "c" fn execv(path: [*:0]const u8, argv: [*:null]const ?[*:0]const u8) c_int; -extern "c" fn _exit(status: c_int) noreturn; const opener_path: ?[*:0]const u8 = switch (builtin.os.tag) { .linux => "/usr/bin/xdg-open", @@ -46,15 +44,15 @@ pub fn openLink(url: []const u8) void { const opener = opener_path orelse return; var buf: [1024]u8 = undefined; const url_z = std.fmt.bufPrintSentinel(&buf, "{s}", .{url}, 0) catch return; - const pid = fork(); + const pid = libc.fork(); if (pid < 0) return; if (pid == 0) { - if (fork() == 0) { + if (libc.fork() == 0) { @import("host_io.zig").resetChildSignals(); const argv: [3:null]?[*:0]const u8 = .{ opener, url_z.ptr, null }; _ = execv(opener, &argv); } - _exit(0); + libc._exit(0); } _ = libc.waitpid(pid, null, 0); } diff --git a/src/main.zig b/src/main.zig index ea2db917..52093b9a 100644 --- a/src/main.zig +++ b/src/main.zig @@ -144,32 +144,22 @@ fn pageInto(io: std.Io, gpa: std.mem.Allocator, dial: []const u8, text: []const /// Stdin to its end, as it came (its escapes are the session's to parse, /// pager.zig), at most a file's limit, a longer one cut there and said so /// at its end. -fn readStdinText(gpa: std.mem.Allocator) ![]u8 { +fn readStdinText(io: std.Io, gpa: std.mem.Allocator) ![]u8 { const limit = pardes.memory.limits.max_file_bytes; var raw: std.ArrayList(u8) = .empty; var chunk: [64 * 1024]u8 = undefined; - var cut = false; - while (true) { - const n = std.c.read(0, &chunk, chunk.len); - if (n < 0) { - if (std.posix.errno(n) == .INTR) continue; - return error.ReadFailed; - } - if (n == 0) break; - const got: usize = @intCast(n); - if (raw.items.len + got > limit) { - try raw.appendSlice(gpa, chunk[0 .. limit - raw.items.len]); - cut = true; - break; - } - try raw.appendSlice(gpa, chunk[0..got]); - } - if (cut) { - // CAN ends an escape the cut left half sent, and SGR 0 its colour, - // so the note is never swallowed or tinted. - const said = "\x18\x1b[m\n[pardes: the rest of stdin is cut: a pane holds at most a file's limit]\n"; - try raw.appendSlice(gpa, said); - } + var stdin = std.Io.File.stdin().readerStreaming(io, &chunk); + // One byte past the limit says there is more. + stdin.interface.appendRemaining(gpa, &raw, .limited(limit + 1)) catch |err| switch (err) { + error.StreamTooLong => { + raw.shrinkRetainingCapacity(limit); + // CAN ends an escape the cut left half sent, and SGR 0 its colour, + // so the note is never swallowed or tinted. + const said = "\x18\x1b[m\n[pardes: the rest of stdin is cut: a pane holds at most a file's limit]\n"; + try raw.appendSlice(gpa, said); + }, + else => |e| return e, + }; return raw.toOwnedSlice(gpa); } @@ -561,7 +551,7 @@ fn nativeMain(std_init: std.process.Init) !void { // made of it (as acme's `B` has no stdin, through pane/new, a name // and the body), and back at once: the PAGER a pane's shell gets. if (positional) |word| if (std.mem.eql(u8, word, "-")) { - const text = readStdinText(arena) catch |err| Refuse.with(init.io, "stdin", err); + const text = readStdinText(init.io, arena) catch |err| Refuse.with(init.io, "stdin", err); // Nothing paged: no pane, and done. if (text.len == 0) return; pageInto(init.io, arena, parent.dial, text); @@ -676,7 +666,7 @@ fn nativeMain(std_init: std.process.Init) !void { // `pardes -` outside a session: an editor whose first pane holds stdin, // as `vim -` does; the terminal is /dev/tty, never stdin. if (positional) |a| if (std.mem.eql(u8, a, "-")) { - opts.stdin_text = readStdinText(arena) catch |err| badArgs(init.io, "stdin: {s}", .{@errorName(err)}); + opts.stdin_text = readStdinText(init.io, arena) catch |err| badArgs(init.io, "stdin: {s}", .{@errorName(err)}); // Nothing paged: nothing to show. if (opts.stdin_text.?.len == 0) return; positional = null; diff --git a/src/syntax.zig b/src/syntax.zig index 1c09c9f3..803d815a 100644 --- a/src/syntax.zig +++ b/src/syntax.zig @@ -1172,15 +1172,14 @@ fn paintDiffPiece(gpa: std.mem.Allocator, window: anytype, bytes: []const u8, at errdefer syntax_allocator.free(colored); try paintHunk(gpa, colored, bytes, kinds, sel); window.put(at, colored); + // An empty slot, else the least recently used. var oldest: usize = 0; for (&diff_pieces, 0..) |*slot, i| { const piece = slot.* orelse { oldest = i; break; }; - if (diff_pieces[oldest]) |o| if (piece.used < o.used) { - oldest = i; - }; + if (piece.used < diff_pieces[oldest].?.used) oldest = i; } if (diff_pieces[oldest]) |old| syntax_allocator.free(old.styles); diff_pieces[oldest] = .{ .hash = hash, .styles = colored, .used = diff_clock }; diff --git a/src/tagline.zig b/src/tagline.zig index b6601d61..e668419d 100644 --- a/src/tagline.zig +++ b/src/tagline.zig @@ -192,12 +192,7 @@ pub fn defaultTail(pane: *const Pane) []const u8 { /// The tag as it is shown, read and pointed at: its computed prefix and /// its own text after it. pub fn tagText(p: *Pardes, arena: std.mem.Allocator, pane: *Pane) ![]u8 { - const prefix = try tagPrefix(p, pane); - const tail = curTail(pane); - const out = try arena.alloc(u8, prefix.len + tail.len); - @memcpy(out[0..prefix.len], prefix); - @memcpy(out[prefix.len..], tail); - return out; + return std.mem.concat(arena, u8, &.{ try tagPrefix(p, pane), curTail(pane) }); } /// Give the keyboard to the tag in normal mode (`:`), its cursor where diff --git a/src/terminal.zig b/src/terminal.zig index 05054521..755fde6c 100644 --- a/src/terminal.zig +++ b/src/terminal.zig @@ -1363,7 +1363,8 @@ const Rows = struct { const empty_grid = [1][]const u8{""}; /// What LEAVING raw tty mode does to one prompt row, decided from its cells -/// alone. See config.tty_blank for why any of this happens. +/// alone: OSC 133 prompt cells are hidden in normal mode, what was typed at +/// them stays. const PromptCut = union(enum) { /// show the row exactly as ghostty dumped it keep, @@ -1375,7 +1376,6 @@ const PromptCut = union(enum) { }; fn promptCut(pin: ghostty_vt.Pin) PromptCut { - if (config.tty_blank == .prompt_and_input) return .blank; const cells = pin.cells(.all); var cols: usize = 0; while (cols < cells.len and cells[cols].semantic_content == .prompt) cols += 1; diff --git a/src/web.zig b/src/web.zig index f89aa7e9..fd6371c0 100644 --- a/src/web.zig +++ b/src/web.zig @@ -15,58 +15,19 @@ const mouse = @import("mouse.zig"); const gpa = std.heap.wasm_allocator; const embedded_dump = @embedFile("embedded.dump.zon"); const input_capacity = 64 * 1024; -const c_alloc_header_size = 16; const attr_tagline: u16 = 1 << 7; +/// Tree-sitter's C runtime is linked into this module: its malloc, calloc, +/// realloc and free are the wasm allocator's, as the Zig core's are. A var, +/// as c_heap compares the allocator it is at run time (wasm_allocator's +/// `ptr` is undefined, which comptime refuses to compare). +var c_allocator: std.mem.Allocator = gpa; +const c_heap = @import("c_heap").Heap(&c_allocator); comptime { - if (c_alloc_header_size < @sizeOf(usize)) @compileError("C allocation header is too small"); -} - -/// Tree-sitter's C runtime is linked into this module. Its conventional -/// allocation symbols share the same wasm allocator as the Zig core and keep -/// the original allocation size in a 16-byte, max-aligned prefix. -export fn malloc(size_arg: usize) callconv(.c) ?*anyopaque { - const size = @max(size_arg, 1); - const total = std.math.add(usize, c_alloc_header_size, size) catch return null; - const bytes = gpa.alignedAlloc(u8, .@"16", total) catch return null; - const header: *align(16) usize = @ptrCast(bytes.ptr); - header.* = total; - return @ptrCast(bytes.ptr + c_alloc_header_size); -} - -export fn calloc(count: usize, size: usize) callconv(.c) ?*anyopaque { - const len = std.math.mul(usize, count, size) catch return null; - const ptr = malloc(len) orelse return null; - if (len != 0) { - const bytes: [*]u8 = @ptrCast(ptr); - @memset(bytes[0..len], 0); - } - return ptr; -} - -export fn free(ptr: ?*anyopaque) callconv(.c) void { - const data = ptr orelse return; - const data_bytes: [*]u8 = @ptrCast(data); - const base: [*]align(16) u8 = @ptrCast(@alignCast(data_bytes - c_alloc_header_size)); - const header: *align(16) usize = @ptrCast(base); - gpa.free(base[0..header.*]); -} - -export fn realloc(ptr: ?*anyopaque, size: usize) callconv(.c) ?*anyopaque { - if (ptr == null) return malloc(size); - if (size == 0) { - free(ptr); - return null; - } - const data_bytes: [*]u8 = @ptrCast(ptr.?); - const base: [*]align(16) u8 = @ptrCast(@alignCast(data_bytes - c_alloc_header_size)); - const header: *align(16) usize = @ptrCast(base); - const old_size = header.* - c_alloc_header_size; - const replacement = malloc(size) orelse return null; - const replacement_bytes: [*]u8 = @ptrCast(replacement); - @memcpy(replacement_bytes[0..@min(old_size, size)], data_bytes[0..@min(old_size, size)]); - free(ptr); - return replacement; + @export(&c_heap.malloc, .{ .name = "malloc" }); + @export(&c_heap.calloc, .{ .name = "calloc" }); + @export(&c_heap.realloc, .{ .name = "realloc" }); + @export(&c_heap.free, .{ .name = "free" }); } pub const std_options: std.Options = .{ .logFn = logFn }; -- cgit v1.3 From ef0de36bf473f22d37cc885054bf4eed98bf275f Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Fri, 23 Oct 2026 17:11:12 -0300 Subject: Arenas are regions mapped once with a page bitmap under a DebugAllocator; the shells allocate from one too Each arena (pardes, frame, lsp, tree_sitter, image, pdf and the new host) maps its region once and tracks 4 KiB pages in a bitmap; a full region spills to malloc and counts it. Freed runs of 64 KiB to 1 MiB go back at once, the rest at memory.trim. In a release build init.gpa is memory.host over libc's malloc. Measured against the old arenas: typing in a 7.4 MB file 1.95 ms a key (was 2.0), a V8 Callstack page 142 MiB (was 134) and 42 MiB after close (was 69). Co-Authored-By: Claude Opus 5.5 --- src/main.zig | 13 +- src/memory.zig | 425 +++++++++++++++++++++++++++++++++++++++++++++------------ 2 files changed, 344 insertions(+), 94 deletions(-) (limited to 'src/main.zig') diff --git a/src/main.zig b/src/main.zig index 52093b9a..9086fa90 100644 --- a/src/main.zig +++ b/src/main.zig @@ -317,16 +317,13 @@ fn webMain() !void { try @import("gui/gui.zig").run(.{}, .{}, null); } -// init.gpa, what the tty, gui and detached shells allocate from, is -// std.start's: a DebugAllocator in Debug and, since we link libc, libc's -// malloc otherwise. Kept on purpose: glibc's malloc was measured at least as -// fast as std.heap.smp_allocator on every scenario and faster on MuPDF's -// page-sized rasters. macos.zig makes the same choice for itself. +// init.gpa, what the tty, gui and detached shells allocate from, is their +// own fixed arena (memory.host) in a release build, spilling to libc's +// malloc, and std.start's DebugAllocator in Debug. Zig 0.17's std.start +// gives a safe build a SafeAllocator over the page allocator instead. fn nativeMain(std_init: std.process.Init) !void { var init = std_init; - // Zig 0.17's std.start gives a safe build a SafeAllocator over the page - // allocator, not libc's malloc: hand the shells malloc, as above. - if (builtin.mode != .debug) init.gpa = std.heap.c_allocator; + if (builtin.mode != .debug) init.gpa = pardes.memory.host(std.heap.c_allocator); var stderr_probe: [64]u8 = undefined; _ = std.debug.lockStderr(&stderr_probe); std.debug.unlockStderr(); diff --git a/src/memory.zig b/src/memory.zig index 853d641a..cb75ee0e 100644 --- a/src/memory.zig +++ b/src/memory.zig @@ -45,12 +45,20 @@ pub const limits = struct { pub const embedded_sources = config.embed_sources; pub const hexdump_row_bytes: u32 = if (board) 8 else 16; + /// Each arena's fixed region. On a native target these are address + /// space reserved at startup, resident only where used (`Pages`), so + /// they are sized for the worst case: the core holds a 256 MiB file, its + /// edit's copy and its undo. pub const arena = struct { - pub const pardes = if (board) 4 * KiB else if (reduced_target) 8 * MiB else 32 * MiB; - pub const frame = if (board) 4 * KiB else if (reduced_target) 4 * MiB else 16 * MiB; - pub const tree_sitter = if (board) 0 else if (reduced_target) 4 * MiB else 16 * MiB; - pub const image = if (board) 0 else if (reduced_target) 64 * KiB else 32 * MiB; - pub const pdf = if (board) 0 else if (reduced_target or !config.mupdf) 64 * KiB else 64 * MiB; + pub const pardes = if (board) 4 * KiB else if (reduced_target) 8 * MiB else 1024 * MiB; + pub const frame = if (board) 4 * KiB else if (reduced_target) 4 * MiB else 64 * MiB; + pub const lsp = if (board or reduced_target) 0 else 512 * MiB; + /// What a native shell allocates itself (`host`): its screen, the + /// bytes its ptys read, its 9P connections, its pipe jobs. + pub const host = if (board or reduced_target) 0 else 512 * MiB; + pub const tree_sitter = if (board) 0 else if (reduced_target) 4 * MiB else 256 * MiB; + pub const image = if (board) 0 else if (reduced_target) 64 * KiB else 256 * MiB; + pub const pdf = if (board) 0 else if (reduced_target or !config.mupdf) 64 * KiB else 512 * MiB; /// One language query's working memory (its parsed answers, the rows /// it writes): a hard bound, nothing spills. Callstack walks until it /// would leave less than its rendering reserve. @@ -70,8 +78,10 @@ pub const Allocators = struct { pdf: Allocator, }; -/// `std.heap.StackFallbackAllocator` with the buffer taken through its -/// lock-free interface. The core's allocator is used from two threads: a 9P +/// A freestanding target's arena (web, board): `std.heap.StackFallbackAllocator` +/// with the buffer taken through its lock-free interface. A +/// FixedBufferAllocator frees only its last block, so once a big operation +/// fills the buffer everything after spills; a native target uses `Pages`. The core's allocator is used from two threads: a 9P /// connection task answers a request while the editor's own thread is out /// in a syscall that allocates (`readFileLimit`, `grep`; see `pardes.turn`). /// The buffer is a separate zeroed global, not a field: an `undefined` one is @@ -112,11 +122,256 @@ const SharedStackFallback = struct { } }; -var pardes_buffer: [limits.arena.pardes]u8 = @splat(0); -var frame_buffer: [limits.arena.frame]u8 = @splat(0); -var tree_sitter_buffer: [limits.arena.tree_sitter]u8 = @splat(0); -var image_buffer: [limits.arena.image]u8 = @splat(0); -var pdf_buffer: [limits.arena.pdf]u8 = @splat(0); +/// One arena's fixed region on a native target, handed out in runs of 4 KiB +/// granules to the general allocator above it (`Region.general`). A freed run +/// is used again, and big ones go back to the system (`release`; `trim` +/// gives back the rest), so what is resident follows what is in use. When no +/// run fits, the block spills to the heap (`spill`) and is counted in +/// `spilled`. Called only under the general allocator's mutex. +const Pages = struct { + region: []u8 = @constCast(&[_]u8{}), + used: []u64 = &.{}, + spill: Allocator = undefined, + spilled: usize = 0, + /// Past the highest granule used yet: where `trim` stops. + top: usize = 0, + + const granule = 4 * KiB; + /// A freed run from `release_min` up to `keep_min` goes back at once: + /// kept until `trim`, a V8 Callstack page's emptied buckets and middling + /// blocks took its peak from 160 to 219 MiB. A bigger one stays resident + /// until `trim`: the next block of its size takes it without faulting it + /// in again, which each keystroke in a 7 MB file does (its edit's copy of + /// the text frees the one before; given back at once, 2.0 -> 3.2 ms a key). + const release_min = 64 * KiB; + const keep_min = 1 * MiB; + + fn allocator(self: *Pages) Allocator { + return .{ .ptr = self, .vtable = &.{ .alloc = alloc, .resize = resize, .remap = remap, .free = free } }; + } + + fn owns(self: *const Pages, ptr: [*]u8) bool { + const at = @intFromPtr(ptr) -% @intFromPtr(self.region.ptr); + return at < self.region.len; + } + + fn alloc(ctx: *anyopaque, len: usize, alignment: std.mem.Alignment, ra: usize) ?[*]u8 { + const self: *Pages = @ptrCast(@alignCast(ctx)); + const n = std.math.divCeil(usize, len, granule) catch unreachable; + const step = @max(1, alignment.toByteUnits() / granule); + if (find(self.used, n, step)) |start| { + mark(self.used, start, n, true); + self.top = @max(self.top, start + n); + return self.region.ptr + start * granule; + } + const ptr = self.spill.rawAlloc(len, alignment, ra) orelse return null; + self.spilled += len; + return ptr; + } + + fn resize(ctx: *anyopaque, buf: []u8, alignment: std.mem.Alignment, new_len: usize, ra: usize) bool { + const self: *Pages = @ptrCast(@alignCast(ctx)); + if (!self.owns(buf.ptr)) { + if (!self.spill.rawResize(buf, alignment, new_len, ra)) return false; + self.spilled = self.spilled - buf.len + new_len; + return true; + } + const start = (@intFromPtr(buf.ptr) - @intFromPtr(self.region.ptr)) / granule; + const n = std.math.divCeil(usize, buf.len, granule) catch unreachable; + const want = std.math.divCeil(usize, new_len, granule) catch unreachable; + if (want <= n) { + self.release(start + want, n - want); + return true; + } + if (start + want > self.used.len * 64 or freeRun(self.used, start + n, want - n) < want - n) return false; + mark(self.used, start + n, want - n, true); + self.top = @max(self.top, start + want); + return true; + } + + fn remap(ctx: *anyopaque, buf: []u8, alignment: std.mem.Alignment, new_len: usize, ra: usize) ?[*]u8 { + const self: *Pages = @ptrCast(@alignCast(ctx)); + if (!self.owns(buf.ptr)) { + const ptr = self.spill.rawRemap(buf, alignment, new_len, ra) orelse return null; + self.spilled = self.spilled - buf.len + new_len; + return ptr; + } + return if (resize(ctx, buf, alignment, new_len, ra)) buf.ptr else null; + } + + fn free(ctx: *anyopaque, buf: []u8, alignment: std.mem.Alignment, ra: usize) void { + const self: *Pages = @ptrCast(@alignCast(ctx)); + if (!self.owns(buf.ptr)) { + self.spilled -= buf.len; + return self.spill.rawFree(buf, alignment, ra); + } + const start = (@intFromPtr(buf.ptr) - @intFromPtr(self.region.ptr)) / granule; + self.release(start, std.math.divCeil(usize, buf.len, granule) catch unreachable); + } + + fn release(self: *Pages, start: usize, n: usize) void { + mark(self.used, start, n, false); + if (n * granule >= release_min and n * granule < keep_min) advise(self.region[start * granule ..][0 .. n * granule], std.posix.MADV.DONTNEED); + } + + /// Gives back the pages of every free run in `n` granules from `start`. + fn giveBack(self: *Pages, start: usize, n: usize) void { + var i = start; + while (i < start + n) { + if (i % 64 == 0 and self.used[i / 64] == ~@as(u64, 0)) { + i += 64; + continue; + } + const run = freeRun(self.used, i, start + n - i); + if (run > 0) advise(self.region[i * granule ..][0 .. run * granule], std.posix.MADV.DONTNEED); + i += run + 1; + } + } + + /// Gives back every free run below `top`: the small ones `release` + /// keeps resident, small and big. + fn trim(self: *Pages) void { + self.giveBack(0, self.top); + } + + /// The first free run of `n` granules starting at a multiple of `step`. + // ponytail: first fit, a scan of the region's bitmap (32 KiB for 1 GiB) + // per page-sized block; a free-run index if a profile ever shows it. + fn find(used: []const u64, n: usize, step: usize) ?usize { + const total = used.len * 64; + var start: usize = 0; + while (start + n <= total) { + if (start % 64 == 0 and used[start / 64] == ~@as(u64, 0)) { + start = std.mem.alignForward(usize, start + 64, step); + continue; + } + const got = freeRun(used, start, n); + if (got == n) return start; + start = std.mem.alignForward(usize, start + got + 1, step); + } + return null; + } + + /// How many of the `n` granules from `start` are free before a used one. + fn freeRun(used: []const u64, start: usize, n: usize) usize { + var i = start; + while (i < start + n) { + if (i % 64 == 0 and start + n - i >= 64 and used[i / 64] == 0) { + i += 64; + continue; + } + if (used[i / 64] >> @intCast(i % 64) & 1 != 0) break; + i += 1; + } + return i - start; + } + + fn mark(used: []u64, start: usize, n: usize, set: bool) void { + var i = start; + while (i < start + n) { + if (i % 64 == 0 and start + n - i >= 64) { + used[i / 64] = if (set) ~@as(u64, 0) else 0; + i += 64; + continue; + } + const bit = @as(u64, 1) << @intCast(i % 64); + if (set) used[i / 64] |= bit else used[i / 64] &= ~bit; + i += 1; + } + } +}; + +/// The general allocator over one arena's region: std's DebugAllocator for +/// its size classes, its checks and leak report only in a Debug build. +const General = std.heap.DebugAllocator(.{ + .safety = debug_enabled, + .thread_safe = true, + .backing_allocator_zeroes = false, + .page_size = 64 * KiB, +}); + +/// One arena: its region, the bitmap of its used granules, and the +/// allocator over them. A native region is address space mapped once, at the +/// first `init`, not .bss: gigabytes of .bss put static data out of reach of +/// x86-64's 32-bit offsets. A freestanding one is its .bss `buffer`. +const Region = struct { + size: usize, + bits: []u64, + buffer: []u8, + pages: Pages = .{}, + general: General = .init, + fallback: SharedStackFallback = undefined, + + fn init(r: *Region, spill: Allocator) Allocator { + if (reduced_target) { + r.fallback = .{ .buffer = r.buffer, .fallback_allocator = spill }; + return r.fallback.get(); + } + // Without the mapping (an address-space limit) every block spills. + const region = if (r.pages.region.len > 0) r.pages.region else if (std.heap.page_allocator.rawAlloc(r.size, .fromByteUnits(64 * KiB), @returnAddress())) |ptr| ptr[0..r.size] else @constCast(&[_]u8{}); + sparse(region); + @memset(r.bits, 0); + r.pages = .{ .region = region, .used = r.bits[0 .. region.len / Pages.granule / 64], .spill = spill }; + r.general = .{ .backing_allocator = r.pages.allocator() }; + return r.general.allocator(); + } + + fn trim(r: *Region) void { + if (reduced_target) return; + std.Io.Threaded.mutexLockUncancelable(&r.general.mutex); + defer std.Io.Threaded.mutexUnlock(&r.general.mutex); + r.pages.trim(); + } + + /// A fresh allocator in its place: a Debug deinit leaves 0xAA behind, + /// its mutex too, which a later `trim` would wait on for good. + fn deinit(r: *Region) bool { + if (reduced_target) return false; + const leaked = r.general.deinit() == .leak; + r.general = .{ .backing_allocator = r.pages.allocator() }; + return leaked; + } +}; + +/// Each arena's bitmap on a native target, its buffer on a freestanding one; +/// spelled out per arena: a generic returning the globals would share them +/// between two arenas of one size. +fn bitsFor(size: usize) usize { + return if (reduced_target) 0 else size / Pages.granule / 64; +} +fn bufferFor(size: usize) usize { + return if (reduced_target) size else 0; +} +var pardes_bits: [bitsFor(limits.arena.pardes)]u64 = @splat(0); +var pardes_buffer: [bufferFor(limits.arena.pardes)]u8 = @splat(0); +var pardes_region: Region = .{ .size = limits.arena.pardes, .bits = &pardes_bits, .buffer = &pardes_buffer }; +var frame_bits: [bitsFor(limits.arena.frame)]u64 = @splat(0); +var frame_buffer: [bufferFor(limits.arena.frame)]u8 = @splat(0); +var frame_region: Region = .{ .size = limits.arena.frame, .bits = &frame_bits, .buffer = &frame_buffer }; +var lsp_bits: [bitsFor(limits.arena.lsp)]u64 = @splat(0); +var lsp_buffer: [bufferFor(limits.arena.lsp)]u8 = @splat(0); +var lsp_region: Region = .{ .size = limits.arena.lsp, .bits = &lsp_bits, .buffer = &lsp_buffer }; +var tree_sitter_bits: [bitsFor(limits.arena.tree_sitter)]u64 = @splat(0); +var tree_sitter_buffer: [bufferFor(limits.arena.tree_sitter)]u8 = @splat(0); +var tree_sitter_region: Region = .{ .size = limits.arena.tree_sitter, .bits = &tree_sitter_bits, .buffer = &tree_sitter_buffer }; +var image_bits: [bitsFor(limits.arena.image)]u64 = @splat(0); +var image_buffer: [bufferFor(limits.arena.image)]u8 = @splat(0); +var image_region: Region = .{ .size = limits.arena.image, .bits = &image_bits, .buffer = &image_buffer }; +var pdf_bits: [bitsFor(limits.arena.pdf)]u64 = @splat(0); +var pdf_buffer: [bufferFor(limits.arena.pdf)]u8 = @splat(0); +var pdf_region: Region = .{ .size = limits.arena.pdf, .bits = &pdf_bits, .buffer = &pdf_buffer }; +var host_bits: [bitsFor(limits.arena.host)]u64 = @splat(0); +var host_buffer: [bufferFor(limits.arena.host)]u8 = @splat(0); +var host_region: Region = .{ .size = limits.arena.host, .bits = &host_bits, .buffer = &host_buffer }; + +/// The allocator a native shell allocates itself from, over its own arena, +/// for the life of the process (no `deinit`); what does not fit spills to +/// `spill`. A release build's: a Debug build keeps std.start's allocator +/// for its leak report. +pub fn host(spill: Allocator) Allocator { + return host_region.init(spill); +} + var lsp_query_buffer: [limits.arena.lsp_query]u8 align(std.heap.page_size_max) = @splat(0); var lsp_query_busy: std.atomic.Value(bool) = .init(false); /// What a query may leave resident of the region (giveLspQuery). @@ -166,11 +421,13 @@ pub fn freeUnfilled(allocator: Allocator, bytes: []const u8) void { if (bytes.len > 0) allocator.rawFree(@constCast(bytes), .of(u8), @returnAddress()); } -/// Gives libc's free memory back to the system, inside its heap too: after a -/// big result is formatted or a big pane torn down, glibc keeps what was freed -/// (a V8 Callstack page left 21 MiB free in the heap; this returned 20). -/// Walks the heap, so for rare, large events only. +/// Gives free memory back to the system, the arenas' and libc's, inside its +/// heap too: after a big result is formatted or a big pane torn down, the +/// tree-sitter arena kept 73 MiB of emptied buckets resident and glibc what +/// was freed (a V8 Callstack page left 21 MiB free in its heap; this returned +/// 20). Walks every arena and the heap, so for rare, large events only. pub fn trim() void { + inline for (.{ &pardes_region, &frame_region, &lsp_region, &tree_sitter_region, &image_region, &pdf_region, &host_region }) |r| r.trim(); if (comptime builtin.os.tag != .linux or builtin.abi.isMusl() or !builtin.link_libc) return; const glibc = struct { extern "c" fn malloc_trim(pad: usize) c_int; @@ -185,91 +442,72 @@ pub fn trim() void { /// 71 MiB that way. Only the region given, never the whole process (a prctl /// would reach every shell and server pardes starts). pub fn sparse(region: []u8) void { + advise(region, std.posix.MADV.NOHUGEPAGE); +} + +/// madvise over the whole pages inside `region`. +fn advise(region: []u8, advice: u32) void { if (comptime builtin.os.tag != .linux) return; const page = std.heap.pageSize(); const start = std.mem.alignForward(usize, @intFromPtr(region.ptr), page); const end = std.mem.alignBackward(usize, @intFromPtr(region.ptr) + region.len, page); if (end <= start) return; - std.posix.madvise(@ptrFromInt(start), end - start, std.posix.MADV.NOHUGEPAGE) catch {}; + std.posix.madvise(@ptrFromInt(start), end - start, advice) catch {}; } -var pardes_fallback: SharedStackFallback = .{ .buffer = &pardes_buffer }; -var frame_fallback: SharedStackFallback = .{ .buffer = &frame_buffer }; -var tree_sitter_fallback: SharedStackFallback = .{ .buffer = &tree_sitter_buffer }; -var image_fallback: SharedStackFallback = .{ .buffer = &image_buffer }; -var pdf_fallback: SharedStackFallback = .{ .buffer = &pdf_buffer }; - -const Debug = std.heap.DebugAllocator(.{}); -var pardes_debug: Debug = .init; -var frame_debug: Debug = .init; -var lsp_debug: Debug = .init; -var tree_sitter_debug: Debug = .init; -var image_debug: Debug = .init; -var pdf_debug: Debug = .init; - -// One session at a time; free its allocations before deinit. Concurrent LSP workers use the caller's allocator. +// One session at a time; free its allocations before deinit. The language +// workers allocate their answers from `lsp` on their own threads. pub fn init(fallback: Allocator) Allocators { - // A Debug build puts each allocator under a DebugAllocator of its own, - // which reports that subsystem's leaks and bad frees (deinit panics on a - // leak). Beneath that goes the page allocator rather than `fallback`: in - // a Debug build `fallback` is std.process.Init's gpa, a DebugAllocator - // already, and a second one checked every block twice. - const backing = if (debug_enabled) std.heap.page_allocator else fallback; - inline for (.{ &pardes_buffer, &frame_buffer, &tree_sitter_buffer, &image_buffer, &pdf_buffer, &lsp_query_buffer }) |buffer| sparse(buffer); - pardes_fallback.fallback_allocator = backing; - frame_fallback.fallback_allocator = backing; - tree_sitter_fallback.fallback_allocator = backing; - image_fallback.fallback_allocator = backing; - pdf_fallback.fallback_allocator = backing; - - const raw: Allocators = .{ - .pardes = pardes_fallback.get(), - .frame = frame_fallback.get(), - .lsp = backing, - .tree_sitter = tree_sitter_fallback.get(), - .image = image_fallback.get(), - .pdf = pdf_fallback.get(), - }; - if (!debug_enabled) return raw; - - pardes_debug = .{ .backing_allocator = raw.pardes }; - frame_debug = .{ .backing_allocator = raw.frame }; - lsp_debug = .{ .backing_allocator = raw.lsp }; - tree_sitter_debug = .{ .backing_allocator = raw.tree_sitter }; - image_debug = .{ .backing_allocator = raw.image }; - pdf_debug = .{ .backing_allocator = raw.pdf }; + // Beneath a Debug build's arenas goes the page allocator rather than + // `fallback`: in a Debug build `fallback` is std.process.Init's gpa, a + // DebugAllocator already, and the arenas' own check every block. + const spill = if (debug_enabled) std.heap.page_allocator else fallback; + sparse(&lsp_query_buffer); return .{ - .pardes = pardes_debug.allocator(), - .frame = frame_debug.allocator(), - .lsp = lsp_debug.allocator(), - .tree_sitter = tree_sitter_debug.allocator(), - .image = image_debug.allocator(), - .pdf = pdf_debug.allocator(), + .pardes = pardes_region.init(spill), + .frame = frame_region.init(spill), + .lsp = lsp_region.init(spill), + .tree_sitter = tree_sitter_region.init(spill), + .image = image_region.init(spill), + .pdf = pdf_region.init(spill), }; } +/// A Debug build's leak report, each arena's own (it panics on a leak). pub fn deinit() void { if (!debug_enabled) return; - var leaked = pardes_debug.deinit() == .leak; - leaked = (frame_debug.deinit() == .leak) or leaked; - leaked = (lsp_debug.deinit() == .leak) or leaked; - leaked = (tree_sitter_debug.deinit() == .leak) or leaked; - leaked = (image_debug.deinit() == .leak) or leaked; - leaked = (pdf_debug.deinit() == .leak) or leaked; + var leaked = pardes_region.deinit(); + leaked = frame_region.deinit() or leaked; + leaked = lsp_region.deinit() or leaked; + leaked = tree_sitter_region.deinit() or leaked; + leaked = image_region.deinit() or leaked; + leaked = pdf_region.deinit() or leaked; if (leaked) @panic("allocator leaks detected"); } -test "fixed allocators are separate, spill, and restart" { +test "arenas are separate, reuse what is freed, spill, and restart" { + if (reduced_target) return error.SkipZigTest; var allocs = init(std.testing.allocator); const core = try allocs.pardes.alloc(u8, 32); const frame = try allocs.frame.alloc(u8, 32); - try std.testing.expect(pardes_fallback.fixed.ownsPtr(core.ptr)); - try std.testing.expect(frame_fallback.fixed.ownsPtr(frame.ptr)); - try std.testing.expect(core.ptr != frame.ptr); + try std.testing.expect(pardes_region.pages.owns(core.ptr)); + try std.testing.expect(frame_region.pages.owns(frame.ptr)); - const spill = try allocs.pardes.alloc(u8, limits.arena.pardes + 1); - try std.testing.expect(!pardes_fallback.fixed.ownsPtr(spill.ptr)); - allocs.pardes.free(spill); + // A freed block is used again: a FixedBufferAllocator's was not, unless + // it was the last one, so an arena filled once and spilled after. + const big = try unfilled(allocs.pardes, 8 * MiB); + const after = try allocs.pardes.alloc(u8, 32); + freeUnfilled(allocs.pardes, big); + const again = try unfilled(allocs.pardes, 8 * MiB); + try std.testing.expectEqual(big.ptr, again.ptr); + + const spill = try unfilled(allocs.pardes, limits.arena.pardes + 1); + try std.testing.expect(!pardes_region.pages.owns(spill.ptr)); + try std.testing.expectEqual(limits.arena.pardes + 1, pardes_region.pages.spilled); + freeUnfilled(allocs.pardes, spill); + try std.testing.expectEqual(0, pardes_region.pages.spilled); + freeUnfilled(allocs.pardes, again); + allocs.pardes.free(after); allocs.frame.free(frame); allocs.pardes.free(core); deinit(); @@ -278,7 +516,21 @@ test "fixed allocators are separate, spill, and restart" { defer deinit(); const restarted = try allocs.pardes.alloc(u8, 32); defer allocs.pardes.free(restarted); - try std.testing.expect(pardes_fallback.fixed.ownsPtr(restarted.ptr)); + try std.testing.expect(pardes_region.pages.owns(restarted.ptr)); +} + +test "a region's runs: aligned first fit, growth in place, release" { + var used: [2]u64 = @splat(0); + Pages.mark(&used, 0, 3, true); + try std.testing.expectEqual(@as(?usize, 4), Pages.find(&used, 2, 4)); + try std.testing.expectEqual(@as(?usize, 3), Pages.find(&used, 70, 1)); + try std.testing.expectEqual(@as(?usize, null), Pages.find(&used, 126, 1)); + try std.testing.expectEqual(@as(?usize, 3), Pages.find(&used, 125, 1)); + Pages.mark(&used, 3, 125, true); + try std.testing.expectEqual(~@as(u64, 0), used[1]); + Pages.mark(&used, 10, 100, false); + try std.testing.expectEqual(@as(usize, 100), Pages.freeRun(&used, 10, 100)); + try std.testing.expectEqual(@as(usize, 100), Pages.freeRun(&used, 10, 101)); } test "memory limits preserve desktop capacities" { @@ -293,9 +545,10 @@ test "memory limits preserve desktop capacities" { try std.testing.expectEqual(@as(usize, 4095), limits.host_path_cap); try std.testing.expectEqual(config.embed_sources, limits.embedded_sources); try std.testing.expectEqual(@as(u32, 16), limits.hexdump_row_bytes); - try std.testing.expectEqual(32 * MiB, limits.arena.pardes); - try std.testing.expectEqual(16 * MiB, limits.arena.frame); - try std.testing.expectEqual(16 * MiB, limits.arena.tree_sitter); - try std.testing.expectEqual(32 * MiB, limits.arena.image); - try std.testing.expectEqual(if (config.mupdf) 64 * MiB else 64 * KiB, limits.arena.pdf); + try std.testing.expectEqual(1024 * MiB, limits.arena.pardes); + try std.testing.expectEqual(64 * MiB, limits.arena.frame); + try std.testing.expectEqual(512 * MiB, limits.arena.lsp); + try std.testing.expectEqual(256 * MiB, limits.arena.tree_sitter); + try std.testing.expectEqual(256 * MiB, limits.arena.image); + try std.testing.expectEqual(if (config.mupdf) 512 * MiB else 64 * KiB, limits.arena.pdf); } -- cgit v1.3 From f3405aaef8db79094b2741a9caaeaa5328ab6288 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Sat, 24 Oct 2026 13:47:11 -0300 Subject: Store 2/3: one bounded store every window shares (Store.zig): Recent as records read on use, the panes a session closes kept as one-pane dumps; Panes lists them (closed), Enter or a look at @pN brings one back beside the pane that took its rows An append-only log under $XDG_STATE_HOME/pardes/store, framed records with a CRC, flock on store.lock (never blocking a step), a stat on use, garbage passed over and compacted away by the next writer, compaction by rename, 100 MiB cap. dump.dumpPane/restorePane lifted out of dumpState/initDump; layout.giveBack; Options.recent_path is store_path. Host calls yield one at a time; /recent refreshes only when no step is out. Tests: two windows and a busy lock, the cap, garbage/torn/partial records, a closed pane's reopen with the layout invariant; fs.py: two live sessions over 9P. --- src/Query.zig | 57 ++- src/Store.zig | 1193 ++++++++++++++++++++++++++++++++++++++++++++++++++++ src/dump.zig | 216 +++++----- src/layout.zig | 26 ++ src/look.zig | 8 +- src/main.zig | 13 +- src/ninep/tree.zig | 4 + src/pardes.zig | 49 +-- src/recent.zig | 99 ++++- test/fs.py | 42 +- 10 files changed, 1541 insertions(+), 166 deletions(-) create mode 100644 src/Store.zig (limited to 'src/main.zig') diff --git a/src/Query.zig b/src/Query.zig index a871b71e..98419c7b 100644 --- a/src/Query.zig +++ b/src/Query.zig @@ -580,6 +580,8 @@ fn startSource(p: *Pardes, id: usize, q: *Query, source: Source, owner_id: ?usiz if (p.fs.serving) Stream.step(p); }, .recent => { + // Every window's files: what the others wrote since, read. + p.store.refresh(p); var out: std.Io.Writer.Allocating = .init(gpa); defer out.deinit(); Output.recentText(p, &out.writer, true) catch {}; @@ -591,15 +593,29 @@ fn startSource(p: *Pardes, id: usize, q: *Query, source: Source, owner_id: ?usiz q.names.add(gpa, rel, 0, path_end, Names.baseOf(rel[0..path_end]), 0) catch break; } }, - .panes => for (p.panes) |slot| { - const other = slot orelse continue; - if (other == rp or other.query != null) continue; - var buf: [4096 + 32]u8 = undefined; - const what: []const u8 = if (other.file) |f| f.path else if (other.command) |c| c else other.cwdSlice(); - const row = std.fmt.bufPrint(&buf, config.pane_addr ++ "{d} {s}", .{ other.serial, Names.relative(what, dir) }) catch continue; - const key_at = std.mem.indexOfScalar(u8, row, ' ').? + 1; - const ln = row[0 .. std.mem.indexOfAny(u8, row, "\r\n") orelse row.len]; - q.names.add(gpa, ln, key_at, ln.len -| key_at, Names.baseOf(ln[@min(key_at, ln.len)..]), other.serial) catch break; + .panes => { + for (p.panes) |slot| { + const other = slot orelse continue; + if (other == rp or other.query != null) continue; + var buf: [4096 + 32]u8 = undefined; + const what: []const u8 = if (other.file) |f| f.path else if (other.command) |c| c else other.cwdSlice(); + const row = std.fmt.bufPrint(&buf, config.pane_addr ++ "{d} {s}", .{ other.serial, Names.relative(what, dir) }) catch continue; + const key_at = std.mem.indexOfScalar(u8, row, ' ').? + 1; + const ln = row[0 .. std.mem.indexOfAny(u8, row, "\r\n") orelse row.len]; + q.names.add(gpa, ln, key_at, ln.len -| key_at, Names.baseOf(ln[@min(key_at, ln.len)..]), other.serial) catch break; + } + // Then the panes this session closed, the latest first, each + // `(closed)` and dimmer (makeNameRows): Enter brings one back + // where it was. Its name alone is matched, not the word. + var i = p.store.closed.items.len; + while (i > 0) : (i -= 1) { + const c = p.store.closed.items[i - 1]; + var buf: [4096 + 48]u8 = undefined; + const row = std.fmt.bufPrint(&buf, config.pane_addr ++ "{d} {s}" ++ closed_word, .{ c.serial, Names.relative(c.name, dir) }) catch continue; + const key_at = std.mem.indexOfScalar(u8, row, ' ').? + 1; + const key_len = row.len - closed_word.len - key_at; + q.names.add(gpa, row, key_at, key_len, Names.baseOf(row[key_at..][0..key_len]), c.serial) catch break; + } }, .symbols => { const oid = owner_id orelse return; @@ -622,6 +638,9 @@ fn startSource(p: *Pardes, id: usize, q: *Query, source: Source, owner_id: ?usiz } } +/// What a Panes row of a closed pane ends with. +const closed_word = " (closed)"; + /// The owner's declarations, from a parse that already exists: its sticky /// headers' (TreeContext) at this revision, or the locations cache's. None /// is made here, on the loop, unless `small` and the text is small: a @@ -1020,13 +1039,21 @@ fn makeNameRows(p: *Pardes, id: usize, pat: []const u8) !void { } try q.items.append(p.gpa, .{ .kind = .hit, .ref = cand.ref }); try writeRow(p, &out, &rows, row, meta); + // A closed pane's row is dimmer, the gutter's colour, between its + // marks (spans are walked in order, never overlapping). + const dim = q.source == .panes and p.paneBySerial(cand.ref) == null; + const dimmed: pardes.CellStyle = .{ .fg = .{ .rgb = chrome.lineno } }; + var gap: usize = 0; var k: usize = 0; while (k < nmarks) { var e = k + 1; while (e < nmarks and marks[e] == marks[e - 1] + 1) e += 1; + if (dim and marks[k] > gap) try spans.append(p.gpa, .{ .start = @intCast(at + gap), .end = @intCast(at + marks[k]), .style = dimmed }); try spans.append(p.gpa, .{ .start = @intCast(at + marks[k]), .end = @intCast(at + marks[e - 1] + 1), .style = tint }); + gap = marks[e - 1] + 1; k = e; } + if (dim and row.len > gap) try spans.append(p.gpa, .{ .start = @intCast(at + gap), .end = @intCast(at + row.len), .style = dimmed }); } if (q.names.hits.items.len > shown) try noteRow(p, q, &out, &rows, " ... and more: type more of the name"); if (q.source == .find) try skippedRow(p, q, rp, &out, &rows); @@ -1636,9 +1663,15 @@ pub fn land(p: *Pardes, id: usize, row: ?usize) void { look.focusPaneLine(p, oid, .{ .line = it.ref }, .center); return; }, - .panes => if (p.paneBySerial(it.ref)) |tid| { - p.active = tid; - if (layout.findPane(p, tid)) |at| p.setActiveColumn(at.col); + .panes => { + if (p.paneBySerial(it.ref)) |tid| { + p.active = tid; + if (layout.findPane(p, tid)) |at| p.setActiveColumn(at.col); + return; + } + // A pane this session closed: back where it was, from the + // pane that asked (the owner, not this one, which may go). + _ = p.store.reopen(p, it.ref, owner_id orelse id); return; }, else => {}, diff --git a/src/Store.zig b/src/Store.zig new file mode 100644 index 00000000..35033e04 --- /dev/null +++ b/src/Store.zig @@ -0,0 +1,1193 @@ +//! The store: the state every pardes window shares, one bounded file under +//! $XDG_STATE_HOME/pardes (Options.store_path), an append-only log of +//! framed records, `@ \n\n`: the files opened +//! lately (Recent, recent.zig) and the panes each session closed, each a +//! one-pane Dump, which Panes brings back where it was. docs/next-store.md +//! argues the format and the sharing; in short: +//! +//! - A writer takes `flock` on `store.lock` (never blocking a frame: busy, +//! its records wait for the next step), reads what others appended since +//! it last read, and appends its own with one write at the end. +//! - A reader takes no lock: on use, one stat of the path; longer, it reads +//! the tail; another inode (a compaction), all of it again. +//! - A record running past the end is being written: read next time. One +//! that is garbage is passed over to the next valid one, and the next +//! writer compacts. A missing, foreign or garbage file is an empty store: +//! pardes always starts. +//! - Compaction (under the lock): the live records, the closed panes of +//! sessions still running, into `store.new`, renamed over the store. The +//! file never passes `max_bytes`. +//! +//! With no path (no home, the web, a test that gives none) nothing is +//! kept past the session, and a closed pane's dump is held here instead. +const Store = @This(); + +const std = @import("std"); +const pardes = @import("pardes.zig"); +const dump = @import("dump.zig"); +const layout = @import("layout.zig"); +const exec = @import("exec.zig"); +const recent = @import("recent.zig"); +const Pardes = pardes.Pardes; +const Pane = pardes.Pane; + +/// The file is never longer: an append that would pass it compacts first, +/// and a compaction keeps the newest live records within half of it. +pub const max_bytes: u64 = 100 << 20; +/// A closed pane's record is never longer: a terminal's that would be is +/// kept without its history, any other pane's is not kept. +pub const max_record: usize = 8 << 20; +/// A session keeps this many closed panes, the newest. +pub const max_closed = 64; +/// The first record's body, its version; then a generation, new at each +/// compaction, so an inode number used again is no other file read on. +const magic = "pardes-store 1"; +/// A header line `@k \n` is never longer. +const max_head = 32; +/// A closed pane's first line, its place and name, is never longer. +const max_meta = 4096 + 128; + +/// A pane closed in this session, as Panes lists it and brings it back. +pub const Closed = struct { + serial: u32, + /// The column it was in, by serial. + column: u32, + /// The pane its rows went to, by serial, and whether it was below it: + /// brought back, it takes them from that pane alone. + gainer: u32, + below: bool, + /// The pane it was attached to, by serial (0 none). + owner: u32, + rows: u16, + /// What its Panes row shows: its file, command or directory (gpa). + name: []u8, + /// Its record's offset in the file read as `inode`. + at: u64 = 0, + /// Its record's body while it is in no file (not written yet, or no + /// file to write it to); empty once written. + body: []u8 = &.{}, + /// Where its record is in `pending`, until that is written. + pending_at: ?usize = null, +}; + +/// The store file; null, nothing is kept past the session. +path: ?[]const u8 = null, +/// Its bound: `max_bytes`, less in a test. +cap: u64 = max_bytes, +/// This session's, on its closed panes' records. +session: u64 = 0, +pid: i32 = 0, +/// The file as read so far: its inode, generation and how far. +inode: std.Io.File.INode = 0, +gen: u64 = 0, +end: u64 = 0, +/// Its length when first read whole: a file past twice that (and 1 MiB) +/// is compacted. +base: u64 = 0, +/// A record that is not one was passed over: the next writer compacts. +garbage: bool = false, +/// Read once at start (or there was none): only then is anything written, +/// so a session never writes over a store it did not read. +loaded: bool = false, +/// Framed records waiting for the lock. +pending: std.ArrayList(u8) = .empty, +/// This session's closed panes, oldest first. +closed: std.ArrayList(Closed) = .empty, + +fn clockNs() i128 { + var ts: std.c.timespec = .{ .sec = 0, .nsec = 0 }; + _ = std.c.clock_gettime(.REALTIME, &ts); + return @as(i128, ts.sec) * std.time.ns_per_s + ts.nsec; +} + +fn ioOf() std.Io { + return std.Io.Threaded.global_single_threaded.io(); +} + +/// One host file call, `f(args)`, made out of the turn (pardes.turn): a +/// store under a mount of this session's own tree is answered by this +/// session. Only the call: while a step is out nothing may change the core, +/// so the store and Recent change between these, never inside one. +fn host(comptime f: anytype, args: anytype) @typeInfo(@TypeOf(f)).@"fn".return_type.? { + pardes.turn.yield(); + defer pardes.turn.back(); + return @call(.auto, f, args); +} + +const cwd = std.Io.Dir.cwd; +const File = std.Io.File; +const Dir = std.Io.Dir; + +/// A new session's store at `path`: its id from the pid and the clock. +pub fn init(path: ?[]const u8) Store { + var s: Store = .{ .path = path }; + if (comptime pardes.hosted) { + s.pid = std.c.getpid(); + const now = clockNs(); + s.session = std.hash.Wyhash.hash(@intCast(s.pid), std.mem.asBytes(&now)); + } else s.session = 1; + return s; +} + +pub fn deinit(s: *Store, gpa: std.mem.Allocator) void { + for (s.closed.items) |c| freeClosed(gpa, c); + s.closed.deinit(gpa); + s.pending.deinit(gpa); +} + +fn freeClosed(gpa: std.mem.Allocator, c: Closed) void { + gpa.free(c.name); + gpa.free(c.body); +} + +/// A copy for the session a Restore makes: the same session (the same +/// process), its closed panes still its own. What is pending is the old +/// session's to write (its deinit does); the copies hold their bodies +/// until they are read back from the file. +pub fn clone(s: *const Store, gpa: std.mem.Allocator) Store { + var copy = s.*; + copy.pending = .empty; + copy.closed = .empty; + for (s.closed.items) |c| { + const name = gpa.dupe(u8, c.name) catch break; + const body = gpa.dupe(u8, c.body) catch { + gpa.free(name); + break; + }; + var kept = c; + kept.name = name; + kept.body = body; + kept.pending_at = null; + copy.closed.append(gpa, kept) catch { + freeClosed(gpa, kept); + break; + }; + } + return copy; +} + +// ---- reading ---- + +/// A window of the file, read ahead: records are parsed from it, and a +/// body that is skipped is never read. +const Reader = struct { + file: std.Io.File, + io: std.Io, + size: u64, + buf: []u8, + at: u64 = 0, + len: usize = 0, + + /// Bytes `[from, from + n)`, `n` at most the window; null past the end. + fn bytes(r: *Reader, from: u64, n: usize) ?[]const u8 { + if (n > r.buf.len or from + n > r.size) return null; + if (from < r.at or from + n > r.at + r.len) { + r.len = host(File.readPositionalAll, .{ r.file, r.io, r.buf, from }) catch return null; + r.at = from; + if (n > r.len) return null; + } + const o: usize = @intCast(from - r.at); + return r.buf[o..][0..n]; + } +}; + +const Rec = struct { + kind: u8, + at: u64, + body: u64, + len: usize, + crc: u32, + + fn end(rec: Rec) u64 { + return rec.body + rec.len + 1; + } +}; + +const Next = union(enum) { rec: Rec, partial, bad }; + +/// The record at `at`: whole, still being written (`partial`: its length +/// runs past the end), or not a record. +fn next(r: *Reader, at: u64) Next { + if (at >= r.size) return .partial; + const head = r.bytes(at, @intCast(@min(max_head, r.size - at))) orelse return .partial; + const nl = std.mem.indexOfScalar(u8, head, '\n') orelse return if (head.len < max_head) .partial else .bad; + const line = head[0..nl]; + if (line.len < 5 or line[0] != '@' or line[2] != ' ') return .bad; + var fields = std.mem.splitScalar(u8, line[3..], ' '); + const len = std.fmt.parseInt(usize, fields.next() orelse return .bad, 10) catch return .bad; + const crc_text = fields.next() orelse return .bad; + if (crc_text.len != 8 or fields.next() != null or len > max_record + max_meta) return .bad; + const crc = std.fmt.parseInt(u32, crc_text, 16) catch return .bad; + const rec: Rec = .{ .kind = line[1], .at = at, .body = at + nl + 1, .len = len, .crc = crc }; + if (rec.end() > r.size) return .partial; + const tail = r.bytes(rec.end() - 1, 1) orelse return .partial; + if (tail[0] != '\n') return .bad; + return .{ .rec = rec }; +} + +/// Whether `rec`'s body is the one its CRC says. +fn verify(r: *Reader, rec: Rec) bool { + var crc = std.hash.Crc32.init(); + var at = rec.body; + var left = rec.len; + while (left > 0) { + const n = @min(left, r.buf.len); + crc.update(r.bytes(at, n) orelse return false); + at += n; + left -= n; + } + return crc.final() == rec.crc; +} + +/// After garbage: the next `\n@` that starts a whole, valid record (or one +/// still being written), else the end. +fn resync(r: *Reader, from: u64) u64 { + var at = from; + while (at + 1 < r.size) : (at += 1) { + const b = r.bytes(at, 2) orelse return r.size; + if (b[0] != '\n' or b[1] != '@') continue; + switch (next(r, at + 1)) { + .rec => |rec| if (verify(r, rec)) return at + 1, + .partial => return at + 1, + .bad => {}, + } + } + return r.size; +} + +/// A closed pane's first line: ` +/// \t`. +const Meta = struct { + session: u64, + pid: i32, + serial: u32, + column: u32, + gainer: u32, + below: bool, + owner: u32, + rows: u16, + name: []const u8, + /// Where its dump starts in the body. + dump_at: usize, +}; + +fn parseMeta(body: []const u8) ?Meta { + const nl = std.mem.indexOfScalar(u8, body, '\n') orelse return null; + const tab = std.mem.indexOfScalar(u8, body[0..nl], '\t') orelse return null; + var f = std.mem.splitScalar(u8, body[0..tab], ' '); + var m: Meta = undefined; + m.session = std.fmt.parseInt(u64, f.next() orelse return null, 16) catch return null; + m.pid = std.fmt.parseInt(i32, f.next() orelse return null, 10) catch return null; + m.serial = std.fmt.parseInt(u32, f.next() orelse return null, 10) catch return null; + m.column = std.fmt.parseInt(u32, f.next() orelse return null, 10) catch return null; + m.gainer = std.fmt.parseInt(u32, f.next() orelse return null, 10) catch return null; + m.below = (std.fmt.parseInt(u1, f.next() orelse return null, 10) catch return null) == 1; + m.owner = std.fmt.parseInt(u32, f.next() orelse return null, 10) catch return null; + m.rows = std.fmt.parseInt(u16, f.next() orelse return null, 10) catch return null; + if (f.next() != null) return null; + m.name = body[tab + 1 .. nl]; + m.dump_at = nl + 1; + return m; +} + +/// The store read at start; the old `recent` file beside it read into the +/// list once, when there is no store yet, so nobody's list is lost. +pub fn load(s: *Store, p: *Pardes) void { + const path = s.path orelse return; + if (comptime !pardes.hosted) return; + defer s.loaded = true; + const io = ioOf(); + const file = host(Dir.openFile, .{ cwd(), io, path, Dir.OpenFileOptions{} }) catch |err| { + if (err != error.FileNotFound) return; + const dir = std.fs.path.dirname(path) orelse return; + var buf: [4096 + 16]u8 = undefined; + const old = std.fmt.bufPrint(&buf, "{s}/recent", .{dir}) catch return; + const bytes = host(Dir.readFileAlloc, .{ cwd(), io, old, p.gpa, std.Io.Limit.limited(1 << 20) }) catch return; + defer p.gpa.free(bytes); + p.recent.read(p.recentGpa(), bytes); + return; + }; + defer host(File.close, .{ file, io }); + const st = host(File.stat, .{ file, io }) catch return; + s.readFile(p, file, st); +} + +/// On use: what other windows wrote since this one last read, read. One +/// stat when nothing changed. +pub fn refresh(s: *Store, p: *Pardes) void { + const path = s.path orelse return; + if (comptime !pardes.hosted) return; + if (!s.loaded) return; + const io = ioOf(); + const st = host(Dir.statFile, .{ cwd(), io, path, Dir.StatFileOptions{} }) catch return; + if (st.inode == s.inode and st.size == s.end) return; + const file = host(Dir.openFile, .{ cwd(), io, path, Dir.OpenFileOptions{} }) catch return; + defer host(File.close, .{ file, io }); + const fst = host(File.stat, .{ file, io }) catch return; + s.readFile(p, file, fst); +} + +/// `file` read on from where this session left it, or all of it again +/// when it is another file than the one read so far. +fn readFile(s: *Store, p: *Pardes, file: File, st: File.Stat) void { + const gpa = p.recentGpa(); + const buf = gpa.alloc(u8, 64 << 10) catch return; + defer gpa.free(buf); + var r: Reader = .{ .file = file, .io = ioOf(), .size = st.size, .buf = buf }; + var whole = st.inode != s.inode or st.size < s.end; + // The same inode number may be a new file (one compaction freed it, + // the next took it): its header's generation says. + if (!whole and s.end > 0) { + switch (next(&r, 0)) { + .rec => |rec| whole = rec.kind != 'h' or headerGen(&r, rec) != s.gen, + else => whole = true, + } + } + if (whole) { + s.inode = st.inode; + s.end = 0; + s.gen = 0; + s.base = st.size; + s.garbage = false; + // Its closed panes are read again from it, at their offsets there; + // the ones in no file yet stay. + var w: usize = 0; + for (s.closed.items) |c| { + if (c.body.len == 0) { + freeClosed(gpa, c); + continue; + } + s.closed.items[w] = c; + w += 1; + } + s.closed.shrinkRetainingCapacity(w); + } + if (st.size == s.end) return; + s.end = s.scan(p, &r, s.end); +} + +fn headerGen(r: *Reader, rec: Rec) ?u64 { + if (rec.len > 64) return null; + const b = r.bytes(rec.body, rec.len) orelse return null; + if (!std.mem.startsWith(u8, b, magic ++ " ")) return null; + return std.fmt.parseInt(u64, b[magic.len + 1 ..], 16) catch null; +} + +/// The records from `from` applied; where reading stopped (before a +/// record still being written, or the end). +fn scan(s: *Store, p: *Pardes, r: *Reader, from: u64) u64 { + var at = from; + while (at < r.size) { + switch (next(r, at)) { + .partial => return at, + .bad => { + s.garbage = true; + // A file that does not start as a store is none: empty. + if (at == 0) return r.size; + at = resync(r, at + 1); + }, + .rec => |rec| { + if (at == 0) { + s.gen = (if (rec.kind == 'h') headerGen(r, rec) else null) orelse { + s.garbage = true; + return r.size; + }; + } else if (!s.apply(p, r, rec)) s.garbage = true; + at = rec.end(); + }, + } + } + return at; +} + +/// One record read: noted in Recent, or a closed pane of this session's +/// listed or unlisted. False when it is not what its header says. +fn apply(s: *Store, p: *Pardes, r: *Reader, rec: Rec) bool { + const gpa = p.recentGpa(); + switch (rec.kind) { + 'r' => { + if (rec.len > 8192) return false; + const b = r.bytes(rec.body, rec.len) orelse return false; + if (std.hash.Crc32.hash(b) != rec.crc) return false; + const e = recent.List.parseLine(b) orelse return false; + p.recent.note(gpa, e.path, e.nums[0], e.nums[1], e.nums[2], e.nums[3]); + }, + 'c' => { + // Only its first line is read: a closed pane is this session's + // or none of its business, and its dump is read when it comes + // back (`reopen`, which checks the CRC). + const b = r.bytes(rec.body, @min(rec.len, max_meta)) orelse return false; + const m = parseMeta(b) orelse return false; + if (m.session != s.session) return true; + s.list(gpa, m, rec.at, &.{}); + }, + 'x' => { + if (rec.len > 64) return false; + const b = r.bytes(rec.body, rec.len) orelse return false; + if (std.hash.Crc32.hash(b) != rec.crc) return false; + const sp = std.mem.indexOfScalar(u8, b, ' ') orelse return false; + const session = std.fmt.parseInt(u64, b[0..sp], 16) catch return false; + const serial = std.fmt.parseInt(u32, b[sp + 1 ..], 10) catch return false; + if (session == s.session) s.unlist(gpa, serial); + }, + // A header in the middle is no record. + 'h' => return false, + // A kind a newer pardes writes: passed over. + else => {}, + } + return true; +} + +/// A closed pane listed: from the file (`body` empty, its record at `at`) +/// or not in one yet. In the order closed, the oldest going past +/// `max_closed`. +fn list(s: *Store, gpa: std.mem.Allocator, m: Meta, at: u64, body: []u8) void { + for (s.closed.items) |c| if (c.serial == m.serial) { + gpa.free(body); + return; + }; + const name = gpa.dupe(u8, m.name) catch { + gpa.free(body); + return; + }; + const c: Closed = .{ .serial = m.serial, .column = m.column, .gainer = m.gainer, .below = m.below, .owner = m.owner, .rows = m.rows, .name = name, .at = at, .body = body }; + if (s.closed.items.len >= max_closed) freeClosed(gpa, s.closed.orderedRemove(0)); + // One read from the file goes before those in none yet: they are newer. + var i = s.closed.items.len; + if (body.len == 0) while (i > 0 and s.closed.items[i - 1].body.len > 0) : (i -= 1) {}; + s.closed.insert(gpa, i, c) catch freeClosed(gpa, c); +} + +fn unlist(s: *Store, gpa: std.mem.Allocator, serial: u32) void { + for (s.closed.items, 0..) |c, i| if (c.serial == serial) { + freeClosed(gpa, s.closed.orderedRemove(i)); + return; + }; +} + +/// The closed pane with this serial, if this session has it. +pub fn closedBySerial(s: *const Store, serial: u32) ?*Closed { + for (s.closed.items) |*c| if (c.serial == serial) return c; + return null; +} + +// ---- writing ---- + +fn frame(gpa: std.mem.Allocator, out: *std.ArrayList(u8), kind: u8, parts: []const []const u8) !void { + var len: usize = 0; + var crc = std.hash.Crc32.init(); + for (parts) |part| { + len += part.len; + crc.update(part); + } + try out.print(gpa, "@{c} {d} {x:0>8}\n", .{ kind, len, crc.final() }); + for (parts) |part| try out.appendSlice(gpa, part); + try out.append(gpa, '\n'); +} + +/// Pane `id`, about to close, kept as a record: what it was (a one-pane +/// Dump) and where (its column, its rows, what it was attached to). Null +/// for a pane that is no pane of the user's: a query pane, a preview, one +/// made and refused in the same step (never announced), or one whose dump +/// fails or is too big. `close` finishes it once its rows have gone. +pub fn keep(s: *Store, p: *Pardes, id: usize) ?Kept { + _ = s; + const pane = p.panes[id] orelse return null; + if (pane.fs.unannounced or pane.query != null) return null; + if (pane.file) |f| if (f.output) |o| if (o.from == .preview) return null; + const gpa = p.recentGpa(); + const arena = p.scratch.allocator(); + var dp = dump.dumpPane(p, arena, pane) catch return null; + var zon = oneDump(p, arena, dp) catch return null; + // A terminal's history is what makes it big: kept without it, it comes + // back a fresh shell in its directory. + if (zon.len > max_record) if (dp.terminal) |*t| { + t.stream = ""; + t.stream_b64 = ""; + dp.body = ""; + zon = oneDump(p, arena, dp) catch return null; + }; + if (zon.len > max_record) return null; + const what: []const u8 = if (pane.file) |f| f.path else if (pane.pdfPath()) |pdf| pdf else if (pane.image) |iv| iv.path else if (pane.command) |c| c else pane.cwdSlice(); + var name = gpa.alloc(u8, @min(what.len, 4096)) catch return null; + // One line, a tab its end: a newline or a tab in it is a space. + for (what[0..name.len], 0..) |c, i| name[i] = if (c == '\n' or c == '\t') ' ' else c; + const owned = gpa.dupe(u8, zon) catch { + gpa.free(name); + return null; + }; + const at = layout.findPane(p, id); + const owner = layout.ownerOf(p, id); + return .{ + .serial = pane.serial, + .column = if (at) |f| layout.columnSerial(p, f.col) else 0, + .owner = if (owner) |o| p.panes[o].?.serial else 0, + .idx = if (at) |f| f.idx else 0, + .rows = p.rects[id].h, + .name = name, + .dump = owned, + }; +} + +pub const Kept = struct { + serial: u32, + column: u32, + owner: u32, + /// Its place in its column, to say which side of the gainer it was. + idx: usize, + rows: u16, + name: []u8, + dump: []u8, + + pub fn free(k: Kept, gpa: std.mem.Allocator) void { + gpa.free(k.name); + gpa.free(k.dump); + } +}; + +/// A Dump of the one pane `dp`, as a Restore would read it. +fn oneDump(p: *Pardes, arena: std.mem.Allocator, dp: dump.Pane) ![]const u8 { + const ids = [_]usize{0}; + const columns = [_]dump.Column{.{ .panes = &ids }}; + const one = [_]dump.Pane{dp}; + const state: dump.State = .{ .screen = .{ .cols = p.screen_w, .rows = p.screen_h }, .columns = &columns, .panes = &one }; + try dump.validate(state); + var out: std.Io.Writer.Allocating = .init(arena); + try std.zon.stringify.serialize(state, .{}, &out.writer); + return out.written(); +} + +/// The pane `k` kept is gone, its rows given to `gainer` (a slot, after +/// they moved; null none): listed, and its record framed for the store. +pub fn close(s: *Store, p: *Pardes, k: Kept, gainer: ?usize) void { + const gpa = p.recentGpa(); + var below = false; + var gainer_serial: u32 = 0; + if (gainer) |g| if (p.panes[g]) |gp| { + gainer_serial = gp.serial; + // It went from just below the gainer's place, or it was the first + // and the rows went down. + if (layout.findPane(p, g)) |f| below = f.idx < k.idx; + }; + var meta_buf: [max_meta]u8 = undefined; + const meta = std.fmt.bufPrint(&meta_buf, "{x:0>16} {d} {d} {d} {d} {d} {d} {d}\t{s}\n", .{ + s.session, s.pid, k.serial, k.column, gainer_serial, @intFromBool(below), k.owner, k.rows, k.name, + }) catch { + k.free(gpa); + return; + }; + const m = parseMeta(meta).?; + const body = std.mem.concat(gpa, u8, &.{ meta, k.dump }) catch { + k.free(gpa); + return; + }; + gpa.free(k.dump); + const pending_at = s.pending.items.len; + const framed = if (s.path != null) blk: { + frame(gpa, &s.pending, 'c', &.{body}) catch break :blk false; + break :blk true; + } else false; + s.list(gpa, m, 0, body); + gpa.free(k.name); + if (framed) if (s.closedBySerial(m.serial)) |c| { + c.pending_at = pending_at; + }; +} + +/// Written out when anything changed, at the end of a step and at the end +/// (`wait`: the lock is waited for there, never in a step). +pub fn flush(s: *Store, p: *Pardes, wait: bool) void { + const gpa = p.recentGpa(); + if (!p.recent.dirty and s.pending.items.len == 0) return; + const path = if (comptime pardes.hosted) s.path else null; + if (path == null or !s.loaded) { + if (path == null) { + for (p.recent.entries.items) |*e| e.changed = false; + p.recent.dirty = false; + s.pending.clearRetainingCapacity(); + for (s.closed.items) |*c| c.pending_at = null; + } + return; + } + const io = ioOf(); + var name_buf: [4096 + 16]u8 = undefined; + const lock_path = std.fmt.bufPrint(&name_buf, "{s}.lock", .{path.?}) catch return; + const lock = host(Dir.createFile, .{ cwd(), io, lock_path, Dir.CreateFileOptions{ .truncate = false } }) catch return; + // Closing it lets go of the lock. + defer host(File.close, .{ lock, io }); + if (wait) { + host(File.lock, .{ lock, io, File.Lock.exclusive }) catch return; + } else if (!(host(File.tryLock, .{ lock, io, File.Lock.exclusive }) catch return)) return; + const file = host(Dir.createFile, .{ cwd(), io, path.?, Dir.CreateFileOptions{ .read = true, .truncate = false } }) catch return; + defer host(File.close, .{ file, io }); + const st = host(File.stat, .{ file, io }) catch return; + // Others' records first, so this window's go after them here too. + s.readFile(p, file, st); + // Under the lock, a record still "being written" is one whose writer + // died: garbage. + if (s.end < st.size) s.garbage = true; + p.recent.changedFirst(); + var i = p.recent.entries.items.len; + var line_buf: [4096 + 64]u8 = undefined; + while (i > 0) : (i -= 1) { + const e = &p.recent.entries.items[i - 1]; + if (!e.changed) continue; + e.changed = false; + var w = std.Io.Writer.fixed(&line_buf); + recent.List.writeEntry(e.*, &w) catch continue; + const line = std.mem.trimEnd(u8, w.buffered(), "\n"); + if (line.len > 0) frame(gpa, &s.pending, 'r', &.{line}) catch {}; + } + p.recent.dirty = false; + if (s.garbage or st.size == 0 or st.size + s.pending.items.len > s.cap or st.size > 2 * s.base + (1 << 20)) { + s.compact(p, file, st, path.?); + return; + } + host(File.writePositionalAll, .{ file, io, s.pending.items, st.size }) catch { + // Out of disk: kept for no one, as the old list was. + s.dropPending(gpa); + return; + }; + for (s.closed.items) |*c| if (c.pending_at) |off| { + c.at = st.size + off; + c.pending_at = null; + gpa.free(c.body); + c.body = &.{}; + }; + s.end = st.size + s.pending.items.len; + s.pending.clearRetainingCapacity(); +} + +fn dropPending(s: *Store, gpa: std.mem.Allocator) void { + _ = gpa; + s.pending.clearRetainingCapacity(); + for (s.closed.items) |*c| c.pending_at = null; +} + +fn alive(pid: i32) bool { + if (pid <= 0) return false; + const rc = std.c.kill(pid, @enumFromInt(0)); + return rc == 0 or std.c.errno(rc) == .PERM; +} + +/// Under the lock: the live records into `.new`, this window's +/// pending ones after them, renamed over the store; then read again whole. +fn compact(s: *Store, p: *Pardes, file: File, st: File.Stat, path: []const u8) void { + const gpa = p.recentGpa(); + const io = ioOf(); + defer s.dropPending(gpa); + const buf = gpa.alloc(u8, 64 << 10) catch return; + defer gpa.free(buf); + var r: Reader = .{ .file = file, .io = io, .size = st.size, .buf = buf }; + var fold: recent.List = .{}; + defer fold.deinit(gpa); + const Live = struct { at: u64, end: u64, session: u64, pid: i32, serial: u32, keep: bool = false }; + var lives: std.ArrayList(Live) = .empty; + defer lives.deinit(gpa); + const Gone = struct { session: u64, serial: u32 }; + var gone: std.ArrayList(Gone) = .empty; + defer gone.deinit(gpa); + var at: u64 = 0; + while (at < r.size) { + switch (next(&r, at)) { + .partial => break, + .bad => at = resync(&r, at + 1), + .rec => |rec| { + at = rec.end(); + if (rec.kind == 'h' or !verify(&r, rec)) continue; + const b = r.bytes(rec.body, @min(rec.len, max_meta)) orelse continue; + switch (rec.kind) { + 'r' => if (recent.List.parseLine(b)) |e| fold.note(gpa, e.path, e.nums[0], e.nums[1], e.nums[2], e.nums[3]), + 'c' => if (parseMeta(b)) |m| lives.append(gpa, .{ .at = rec.at, .end = rec.end(), .session = m.session, .pid = m.pid, .serial = m.serial }) catch {}, + 'x' => { + const sp = std.mem.indexOfScalar(u8, b, ' ') orelse continue; + gone.append(gpa, .{ + .session = std.fmt.parseInt(u64, b[0..sp], 16) catch continue, + .serial = std.fmt.parseInt(u32, b[sp + 1 ..], 10) catch continue, + }) catch {}; + }, + else => {}, + } + }, + } + } + // The closed panes kept: of running sessions, not brought back, the + // newest `max_closed` a session, the newest within half the cap. + var budget: u64 = s.cap / 2 -| s.pending.items.len; + var k = lives.items.len; + while (k > 0) : (k -= 1) { + const l = &lives.items[k - 1]; + const reopened = for (gone.items) |g| { + if (g.session == l.session and g.serial == l.serial) break true; + } else false; + if (reopened or (l.session != s.session and !alive(l.pid))) continue; + var newer: usize = 0; + for (lives.items[k..]) |o| if (o.keep and o.session == l.session) { + newer += 1; + }; + if (newer >= max_closed or l.end - l.at > budget) continue; + budget -= l.end - l.at; + l.keep = true; + } + var name_buf: [4096 + 16]u8 = undefined; + const new_path = std.fmt.bufPrint(&name_buf, "{s}.new", .{path}) catch return; + const out = host(Dir.createFile, .{ cwd(), io, new_path, Dir.CreateFileOptions{} }) catch return; + var ok = false; + defer if (!ok) { + host(File.close, .{ out, io }); + host(Dir.deleteFile, .{ cwd(), io, new_path }) catch {}; + }; + var head: std.ArrayList(u8) = .empty; + defer head.deinit(gpa); + var gen_buf: [64]u8 = undefined; + const now = clockNs(); + const gen = std.hash.Wyhash.hash(s.session, std.mem.asBytes(&now)); + frame(gpa, &head, 'h', &.{std.fmt.bufPrint(&gen_buf, magic ++ " {x}", .{gen}) catch return}) catch return; + var line_buf: [4096 + 64]u8 = undefined; + var i = fold.entries.items.len; + while (i > 0) : (i -= 1) { + var w = std.Io.Writer.fixed(&line_buf); + recent.List.writeEntry(fold.entries.items[i - 1], &w) catch continue; + const line = std.mem.trimEnd(u8, w.buffered(), "\n"); + if (line.len > 0) frame(gpa, &head, 'r', &.{line}) catch return; + } + host(File.writePositionalAll, .{ out, io, head.items, 0 }) catch return; + var off: u64 = head.items.len; + for (lives.items) |l| if (l.keep) { + var from = l.at; + while (from < l.end) { + const n: usize = @intCast(@min(buf.len, l.end - from)); + const b = r.bytes(from, n) orelse return; + host(File.writePositionalAll, .{ out, io, b, off }) catch return; + off += n; + from += n; + } + }; + host(File.writePositionalAll, .{ out, io, s.pending.items, off }) catch return; + host(File.sync, .{ out, io }) catch return; + host(File.close, .{ out, io }); + ok = true; + host(Dir.rename, .{ cwd(), new_path, cwd(), path, io }) catch { + host(Dir.deleteFile, .{ cwd(), io, new_path }) catch {}; + return; + }; + // Every closed pane of this session is in the new file now: read again + // from it, at its offsets there. + for (s.closed.items) |c| freeClosed(gpa, c); + s.closed.clearRetainingCapacity(); + s.inode = 0; + const again = host(Dir.openFile, .{ cwd(), io, path, Dir.OpenFileOptions{} }) catch return; + defer host(File.close, .{ again, io }); + const nst = host(File.stat, .{ again, io }) catch return; + s.readFile(p, again, nst); +} + +// ---- bringing a closed pane back ---- + +/// Closed pane `serial` of this session made again, where it was: beside +/// the pane its rows went to, taking them from that pane alone (attached +/// again to its owner when that is still open), else placed as a new pane +/// from `from`. False when it is not this session's, or its record is gone +/// or bad; the keyboard on it otherwise. +pub fn reopen(s: *Store, p: *Pardes, serial: u32, from: usize) bool { + s.refresh(p); + const gpa = p.recentGpa(); + const place = (s.closedBySerial(serial) orelse return false).*; + const body = s.bodyOf(p, place) orelse return false; + // Read from the file: this call's to free (`unlist` frees one held). + defer if (place.body.len == 0) gpa.free(body); + const m = parseMeta(body) orelse return false; + var parsed = dump.readZon(p.gpa, body[m.dump_at..], "closed pane") catch return false; + defer parsed.deinit(); + const free = p.freeSlot() orelse { + p.reportError(from, "Panes", error.NoPaneSlots); + return false; + }; + const src = parsed.value.panes[0]; + const pane = dump.restorePane(p, free, src) catch |err| { + p.reportError(from, "Panes", err); + return false; + }; + pane.collapsed = false; + const owner = if (place.owner != 0) p.paneBySerial(place.owner) else null; + const gainer = if (place.gainer != 0) p.paneBySerial(place.gainer) else null; + const placed = if (owner) |o| + layout.attachFrom(p, o, free, place.rows, o) + else if (gainer) |g| + layout.giveBack(p, free, g, place.below, place.rows) + else + false; + if (!placed) exec.placeNew(p, from, from, free, .doc); + if (layout.findPane(p, free) == null) { + p.removePane(free, null) catch {}; + return false; + } + // No room anywhere: refused, it closes at the step's end, still listed. + if (p.unplaced.isSet(free)) return false; + // Brought back: no longer listed, here or when read again. + var rec_buf: [64]u8 = undefined; + const rec = std.fmt.bufPrint(&rec_buf, "{x:0>16} {d}", .{ s.session, serial }) catch unreachable; + if (s.path != null) frame(gpa, &s.pending, 'x', &.{rec}) catch {}; + s.unlist(gpa, serial); + p.active = free; + if (layout.findPane(p, free)) |f| p.setActiveColumn(f.col); + p.sync(); + return true; +} + +/// A closed pane's record body: held here, or read from the file and +/// checked against its CRC (gpa; the caller frees it when it is not +/// `c.body`). +fn bodyOf(s: *Store, p: *Pardes, c: Closed) ?[]u8 { + if (c.body.len > 0) return c.body; + const path = s.path orelse return null; + if (comptime !pardes.hosted) return null; + const gpa = p.recentGpa(); + const io = ioOf(); + const file = host(Dir.openFile, .{ cwd(), io, path, Dir.OpenFileOptions{} }) catch return null; + defer host(File.close, .{ file, io }); + const st = host(File.stat, .{ file, io }) catch return null; + if (st.inode != s.inode) return null; + var head_buf: [max_head]u8 = undefined; + var r: Reader = .{ .file = file, .io = io, .size = st.size, .buf = &head_buf }; + const rec = switch (next(&r, c.at)) { + .rec => |rec| rec, + else => return null, + }; + if (rec.kind != 'c') return null; + const body = gpa.alloc(u8, rec.len) catch return null; + const n = host(File.readPositionalAll, .{ file, io, body, rec.body }) catch 0; + if (n != rec.len or std.hash.Crc32.hash(body) != rec.crc) { + gpa.free(body); + return null; + } + return body; +} + +/// `@p` naming a pane this session closed: its serial. +pub fn closedAddress(s: *const Store, word: []const u8) ?u32 { + const addr = @import("config.zig").pane_addr; + if (!std.mem.startsWith(u8, word, addr)) return null; + const digits = word[addr.len..]; + const end = for (digits, 0..) |ch, i| { + if (!std.ascii.isDigit(ch)) break i; + } else digits.len; + // `@p7` alone, or `@p7:` with nothing after it: the pane, no place in it. + if (end == 0 or (end < digits.len and !(digits[end] == ':' and end + 1 == digits.len))) return null; + const serial = std.fmt.parseInt(u32, digits[0..end], 10) catch return null; + return if (s.closedBySerial(serial) != null) serial else null; +} + +// ---- tests ---- + +const testing = std.testing; + +/// The store file of a test, in its own directory (never the user's). +fn testPath(tmp: *std.testing.TmpDir) ![]u8 { + var base_buf: [std.fs.max_path_bytes]u8 = undefined; + const dir = base_buf[0..try tmp.dir.realPath(testing.io, &base_buf)]; + return std.fs.path.join(testing.allocator, &.{ dir, "store" }); +} + +fn testWindow(path: []const u8) !*Pardes { + return Pardes.init(testing.allocator, .{ .tty_only = true, .cols = 120, .rows = 48, .store_path = path }); +} + +fn fileSize(path: []const u8) u64 { + const st = std.Io.Dir.cwd().statFile(testing.io, path, .{}) catch return 0; + return st.size; +} + +test "store: two windows share Recent, each reading the other's writes on use; a busy lock delays, never loses" { + if (comptime !pardes.hosted) return; + var tmp = testing.tmpDir(.{}); + defer tmp.cleanup(); + const path = try testPath(&tmp); + defer testing.allocator.free(path); + const a = try testWindow(path); + defer a.deinit(); + const b = try testWindow(path); + defer b.deinit(); + try testing.expect(a.store.session != b.store.session); + a.recent.opened(a.recentGpa(), "/w/a.zig"); + a.saveRecent(); + b.recent.opened(b.recentGpa(), "/w/b.zig"); + b.saveRecent(); + a.recent.closed(a.recentGpa(), "/w/a.zig", 7, 3); + a.saveRecent(); + // Each has both, in the order of the log: a closed last, then b. + a.store.refresh(a); + b.store.refresh(b); + for ([_]*Pardes{ a, b }) |w| { + try testing.expectEqual(@as(usize, 2), w.recent.entries.items.len); + try testing.expectEqualStrings("/w/a.zig", w.recent.entries.items[0].path); + try testing.expectEqualStrings("/w/b.zig", w.recent.entries.items[1].path); + try testing.expectEqual(@as(u32, 7), w.recent.get("/w/a.zig").?.line); + } + // Another window holding the lock: b's change waits in memory... + const lock_path = try std.fmt.allocPrint(testing.allocator, "{s}.lock", .{path}); + defer testing.allocator.free(lock_path); + const lock = try std.Io.Dir.cwd().createFile(testing.io, lock_path, .{ .truncate = false }); + try lock.lock(testing.io, .exclusive); + b.recent.opened(b.recentGpa(), "/w/c.zig"); + const size = fileSize(path); + b.saveRecent(); + try testing.expectEqual(size, fileSize(path)); + try testing.expect(b.recent.dirty); + // ...and is written at the next step after it is let go. + lock.close(testing.io); + b.saveRecent(); + try testing.expect(fileSize(path) > size); + a.store.refresh(a); + try testing.expectEqualStrings("/w/c.zig", a.recent.entries.items[0].path); + // A window started now folds the same list. + const c = try testWindow(path); + defer c.deinit(); + try testing.expectEqual(@as(usize, 3), c.recent.entries.items.len); + for (a.recent.entries.items, c.recent.entries.items) |x, y| try testing.expectEqualStrings(x.path, y.path); +} + +test "store: the cap holds, compaction keeps the newest, Recent keeps its 200" { + if (comptime !pardes.hosted) return; + var tmp = testing.tmpDir(.{}); + defer tmp.cleanup(); + const path = try testPath(&tmp); + defer testing.allocator.free(path); + const a = try testWindow(path); + defer a.deinit(); + a.store.cap = 48 << 10; + var name: [32]u8 = undefined; + var inodes: usize = 0; + var last_inode = a.store.inode; + for (0..3000) |i| { + const file = std.fmt.bufPrint(&name, "/w/file{d}.zig", .{i}) catch unreachable; + a.recent.opened(a.recentGpa(), file); + a.recent.closed(a.recentGpa(), file, 1, 1); + a.saveRecent(); + try testing.expect(fileSize(path) <= a.store.cap); + if (a.store.inode != last_inode) inodes += 1; + last_inode = a.store.inode; + } + try testing.expect(inodes > 2); + try testing.expectEqual(@as(usize, recent.cap), a.recent.entries.items.len); + try testing.expectEqualStrings("/w/file2999.zig", a.recent.entries.items[0].path); + const b = try testWindow(path); + defer b.deinit(); + try testing.expectEqual(@as(usize, recent.cap), b.recent.entries.items.len); + try testing.expectEqualStrings("/w/file2999.zig", b.recent.entries.items[0].path); + try testing.expectEqualStrings("/w/file2800.zig", b.recent.entries.items[recent.cap - 1].path); + // Closed panes' text counts too: the newest stay, within the cap. + a.store.cap = 256 << 10; + var text: [20 << 10]u8 = @splat('t'); + var serial: u32 = 0; + for (0..30) |i| { + a.newScratchBelow(a.active); + const id = a.active; + const f = &a.panes[id].?.file.?; + text[0] = @intCast('a' + i % 26); + @import("File.zig").setContent(a, f, try a.gpa.dupe(u8, &text)); + serial = a.panes[id].?.serial; + // Made outside a step: announced as a step's end would. + pardes.ctlfs.events.announce(a); + try a.removePane(id, null); + a.saveRecent(); + try testing.expect(fileSize(path) <= a.store.cap); + } + try testing.expect(a.store.closed.items.len < 30); + try testing.expectEqual(serial, a.store.closed.items[a.store.closed.items.len - 1].serial); + try testing.expect(a.store.reopen(a, serial, a.active)); + try testing.expectEqual(@as(u8, 'a' + 29 % 26), a.panes[a.active].?.file.?.content[0]); +} + +test "store: a garbage or torn file never stops pardes, records past garbage are read, the next writer mends it" { + if (comptime !pardes.hosted) return; + var tmp = testing.tmpDir(.{}); + defer tmp.cleanup(); + const path = try testPath(&tmp); + defer testing.allocator.free(path); + try std.Io.Dir.cwd().writeFile(testing.io, .{ .sub_path = path, .data = "\x00\xffnot a store at all\n@r 9 zz\n" }); + const a = try testWindow(path); + defer a.deinit(); + try testing.expectEqual(@as(usize, 0), a.recent.entries.items.len); + try testing.expect(a.store.garbage); + a.recent.opened(a.recentGpa(), "/w/a.zig"); + a.saveRecent(); + try testing.expect(!a.store.garbage); + // A torn record at the end (its writer died), then garbage, then a + // whole record: the whole one is read, the rest passed over. + var tail: std.ArrayList(u8) = .empty; + defer tail.deinit(testing.allocator); + try tail.appendSlice(testing.allocator, "@r 40 0000"); + try tail.appendSlice(testing.allocator, "\x00junk\n@x not a header\n"); + try frame(testing.allocator, &tail, 'r', &.{"3 1 0 0 /w/after.zig"}); + { + const f = try std.Io.Dir.cwd().openFile(testing.io, path, .{ .mode = .read_write }); + defer f.close(testing.io); + try f.writePositionalAll(testing.io, tail.items, (try f.stat(testing.io)).size); + } + const b = try testWindow(path); + defer b.deinit(); + try testing.expect(b.recent.get("/w/a.zig") != null); + try testing.expectEqual(@as(u32, 3), b.recent.get("/w/after.zig").?.line); + try testing.expect(b.store.garbage); + // A record half written (the length runs past the end) is waited for, + // not garbage: a reader reads it once it is whole. + var half: std.ArrayList(u8) = .empty; + defer half.deinit(testing.allocator); + try frame(testing.allocator, &half, 'r', &.{"5 1 0 0 /w/late.zig"}); + { + const f = try std.Io.Dir.cwd().openFile(testing.io, path, .{ .mode = .read_write }); + defer f.close(testing.io); + const end = (try f.stat(testing.io)).size; + try f.writePositionalAll(testing.io, half.items[0..10], end); + a.store.refresh(a); + try testing.expect(a.recent.get("/w/late.zig") == null); + try f.writePositionalAll(testing.io, half.items[10..], end + 10); + } + a.store.refresh(a); + try testing.expectEqual(@as(u32, 5), a.recent.get("/w/late.zig").?.line); + // The next write compacts it: a reader then finds no garbage. + b.recent.opened(b.recentGpa(), "/w/b.zig"); + b.saveRecent(); + const c = try testWindow(path); + defer c.deinit(); + try testing.expect(!c.store.garbage); + for ([_][]const u8{ "/w/a.zig", "/w/after.zig", "/w/late.zig", "/w/b.zig" }) |want| try testing.expect(c.recent.get(want) != null); +} + +test "store: a closed pane comes back where it was, its rows from the pane that took them, nothing else moving; Panes lists it, marked" { + if (comptime !pardes.hosted) return; + var tmp = testing.tmpDir(.{}); + defer tmp.cleanup(); + const path = try testPath(&tmp); + defer testing.allocator.free(path); + const p = try testWindow(path); + defer p.deinit(); + _ = try p.setTestFile("alpha\nbeta\n"); + p.newScratchBelow(0); + const sid = p.active; + @import("File.zig").setContent(p, &p.panes[sid].?.file.?, try p.gpa.dupe(u8, "kept text\n")); + const other = p.col_panes[0][1]; + p.newScratchBelow(0); + try testing.expect(layout.splitColumn(p, p.active, p.active, false)); + const far = p.active; + _ = other; + p.active = 0; + // Made outside a step: announced as a step's end would. + pardes.ctlfs.events.announce(p); + layout.compute(p); + const before = p.rects; + const serial = p.panes[sid].?.serial; + try p.removePane(sid, null); + layout.compute(p); + try testing.expectEqualDeep(before[far], p.rects[far]); + // Written to the store: brought back from the file, not memory. + p.saveRecent(); + try testing.expectEqual(@as(usize, 0), p.store.closedBySerial(serial).?.body.len); + try testing.expect(p.store.reopen(p, serial, 0)); + const back = p.active; + layout.compute(p); + try testing.expectEqualStrings("kept text\n", p.panes[back].?.file.?.content); + try testing.expect(p.panes[back].?.serial != serial); + // Its rect as it was, the one above as it was, the other column's + // untouched: its rows came from the pane that took them alone. + try testing.expectEqualDeep(before[sid], p.rects[back]); + try testing.expectEqualDeep(before[0], p.rects[0]); + try testing.expectEqualDeep(before[far], p.rects[far]); + try testing.expect(p.store.closedBySerial(serial) == null); + // Closed again: Panes lists it after the open ones, `(closed)`. + const again = p.panes[back].?.serial; + pardes.ctlfs.events.announce(p); + try p.removePane(back, null); + p.saveRecent(); + p.active = 0; + p.update(.{ .key = .{ .cp = ' ', .text = " " } }); + for ("bb") |ch| p.update(.{ .key = .{ .cp = ch, .text = &.{ch} } }); + const qid = for (p.panes, 0..) |slot, i| { + if (slot) |qp| if (qp.query != null) break i; + } else return error.NoQueryPane; + const q = p.panes[qid].?.query.?; + const row = for (q.items.items, 0..) |it, i| { + if (it.ref == again) break i; + } else return error.NotListed; + const line = @import("modal.zig").lineSlice(p.panes[qid].?.file.?.content, @intCast(row + 1)); + try testing.expect(std.mem.endsWith(u8, line, "(closed)")); + // Enter on it: back, and listed no more (nor in the store when read). + panes_mod.Query.land(p, qid, row); + const found = for (p.panes) |slot| { + if (slot) |pp| if (pp.file) |f| if (std.mem.eql(u8, f.content, "kept text\n")) break true; + } else false; + try testing.expect(found); + try testing.expect(p.store.closedBySerial(again) == null); + p.saveRecent(); + p.store.inode = 0; + p.store.refresh(p); + try testing.expect(p.store.closedBySerial(again) == null); + // Another session lists none of this one's. + const w = try testWindow(path); + defer w.deinit(); + try testing.expectEqual(@as(usize, 0), w.store.closed.items.len); +} + +const panes_mod = @import("panes.zig"); + +test "zz store timings on a 90 MiB store (STORE_TIMES=)" { + const dir_z = std.c.getenv("STORE_TIMES") orelse return error.SkipZigTest; + const gpa = testing.allocator; + const path = try std.fs.path.join(gpa, &.{ std.mem.span(dir_z), "store" }); + defer gpa.free(path); + // A store as another running session leaves it: 200 files, then 90 + // closed panes of 1 MiB each (this pid: alive, so a compaction keeps + // what fits). + { + var bytes: std.ArrayList(u8) = .empty; + defer bytes.deinit(gpa); + try frame(gpa, &bytes, 'h', &.{magic ++ " 1"}); + var line: [64]u8 = undefined; + for (0..200) |i| try frame(gpa, &bytes, 'r', &.{std.fmt.bufPrint(&line, "1 1 0 0 /w/file{d}.zig", .{i}) catch unreachable}); + const out = try std.Io.Dir.cwd().createFile(testing.io, path, .{}); + defer out.close(testing.io); + try out.writePositionalAll(testing.io, bytes.items, 0); + var off: u64 = bytes.items.len; + const big = try gpa.alloc(u8, 1 << 20); + defer gpa.free(big); + @memset(big, 'z'); + for (0..90) |i| { + bytes.clearRetainingCapacity(); + var meta: [128]u8 = undefined; + const m = std.fmt.bufPrint(&meta, "{x:0>16} {d} {d} 1 0 0 0 10\t/w/closed{d}\n", .{ @as(u64, 0xfeed), std.c.getpid(), i + 1, i }) catch unreachable; + try frame(gpa, &bytes, 'c', &.{ m, big }); + try out.writePositionalAll(testing.io, bytes.items, off); + off += bytes.items.len; + } + } + const t0 = nowNs(); + const p = try testWindow(path); + defer p.deinit(); + const load_ns = nowNs() - t0; + var t = nowNs(); + for (0..1000) |_| p.store.refresh(p); + const refresh_ns = (nowNs() - t) / 1000; + t = nowNs(); + var name: [32]u8 = undefined; + for (0..100) |i| { + const f = std.fmt.bufPrint(&name, "/w/new{d}.zig", .{i}) catch unreachable; + p.recent.opened(p.recentGpa(), f); + p.recent.closed(p.recentGpa(), f, 1, 1); + p.saveRecent(); + } + const flush_ns = (nowNs() - t) / 100; + const before = fileSize(path); + p.store.garbage = true; + p.recent.opened(p.recentGpa(), "/w/last.zig"); + t = nowNs(); + p.saveRecent(); + const compact_ns = nowNs() - t; + std.debug.print("store timings: load {d} us, refresh (unchanged) {d} ns, flush one record {d} us, compaction {d} -> {d} bytes {d} ms\n", .{ + load_ns / 1000, refresh_ns, flush_ns / 1000, before, fileSize(path), compact_ns / 1_000_000, + }); +} + +fn nowNs() u64 { + return @intCast(clockNs()); +} diff --git a/src/dump.zig b/src/dump.zig index 0ce44c40..140bc476 100644 --- a/src/dump.zig +++ b/src/dump.zig @@ -717,34 +717,7 @@ pub fn dumpState(p: *Pardes) !void { for (p.panes, 0..) |slot, id| { const pane = slot orelse continue; slot_to_pane[id] = panes_len; - const tag = try tagline.tagText(p, arena, pane); - const body = try body_layer.bodyText(p, arena, pane); - const scroll: usize = @intCast(@max(0, pane.scroll())); - var dp: Pane = if (pane.file) |*f| try pardes.panes.File.dumpPane( - p, - arena, - pane, - f, - tag, - body, - scroll, - if (f.output) |o| pardes.panes.Output.word(o.from) else "", - if (f.output) |*o| o.arg() else "", - ) else if (pane.hasPdf()) blk: { - if (comptime !pdf_enabled) unreachable; - const pv = &pane.pdf.?; - break :blk try pardes.panes.Image.dumpPane(p, arena, pane, tag, body, pv.page, pv.path, &.{}); - } else if (pane.image) |iv| - try pardes.panes.Image.dumpPane(p, arena, pane, tag, body, scroll, iv.path, iv.raw) - else - try pardes.panes.terminal.dumpPane(pane, arena, tag, body, scroll); - dp.tag_tail = pane.tag.own; - if (dp.file) |*df| { - const dot = ctlfs.pane.dotOf(pane); - df.dot = .{ dot.q0, dot.q1 }; - } - dp.serial = pane.serial; - dump_panes[panes_len] = dp; + dump_panes[panes_len] = try dumpPane(p, arena, pane); panes_len += 1; } // An attachment names its owner by its place in the dump: serials are @@ -814,6 +787,39 @@ pub fn dumpState(p: *Pardes) !void { p.emit(.write_dump); } +/// One pane as a dump keeps it, its strings in `arena`: a Restore's, and a +/// closed pane's in the store (Store.zig), which Panes brings back. +pub fn dumpPane(p: *Pardes, arena: std.mem.Allocator, pane: *pardes.panes.Pane) !Pane { + const tag = try tagline.tagText(p, arena, pane); + const body = try body_layer.bodyText(p, arena, pane); + const scroll: usize = @intCast(@max(0, pane.scroll())); + var dp: Pane = if (pane.file) |*f| try pardes.panes.File.dumpPane( + p, + arena, + pane, + f, + tag, + body, + scroll, + if (f.output) |o| pardes.panes.Output.word(o.from) else "", + if (f.output) |*o| o.arg() else "", + ) else if (pane.hasPdf()) blk: { + if (comptime !pdf_enabled) unreachable; + const pv = &pane.pdf.?; + break :blk try pardes.panes.Image.dumpPane(p, arena, pane, tag, body, pv.page, pv.path, &.{}); + } else if (pane.image) |iv| + try pardes.panes.Image.dumpPane(p, arena, pane, tag, body, scroll, iv.path, iv.raw) + else + try pardes.panes.terminal.dumpPane(pane, arena, tag, body, scroll); + dp.tag_tail = pane.tag.own; + if (dp.file) |*df| { + const dot = ctlfs.pane.dotOf(pane); + df.dot = .{ dot.q0, dot.q1 }; + } + dp.serial = pane.serial; + return dp; +} + /// The setting lines that differ from a fresh session's, as the root ctl /// reads them, less the ones a dump keeps apart. fn changedSettings(p: *Pardes, arena: std.mem.Allocator) ![]const []const u8 { @@ -901,7 +907,8 @@ fn initDump(gpa: std.mem.Allocator, opts: Options, zon_bytes: []const u8, previo if (old.last_dump) |d| p.last_dump = try gpa.dupe(u8, d); // Recent goes on across a Restore, the old session's own list. p.recent = old.recent.clone(p.recentGpa()); - p.recent_loaded = old.recent_loaded; + // The same session: its closed panes go on being its own. + p.store = old.store.clone(p.recentGpa()); } else p.loadRecent(); var parsed = try readZon(gpa, zon_bytes, "load"); defer parsed.deinit(); @@ -944,77 +951,7 @@ fn initDump(gpa: std.mem.Allocator, opts: Options, zon_bytes: []const u8, previo for (st.panes, 0..) |src, i| { if (i >= MAX_PANES) break; if (old_serials) |o| o.panes[i] = src.serial; - const pane: *pardes.panes.Pane = switch (src.kind) { - .terminal => terminal: { - const t = src.terminal.?; - // A host that runs shells gets them back: the old history - // above a new shell in the directory it was in. The web - // shell and an isolated build only ever replay it. - // A command pane comes back finished, showing what it said - // and how it ended: its command is not run again. - const live = comptime (terminal_panes and platform != .web and !isolated); - const revive = live and t.cwd.len <= effect_path_cap and t.command.len == 0; - const restored = try pardes.panes.terminal.restore(p, src, revive); - p.installPane(i, restored); - try restored.setOwnedCwd(t.cwd); - if (t.shell.len > 0) restored.shell = try gpa.dupe(u8, t.shell); - if (t.command.len > 0) { - restored.command = try gpa.dupe(u8, t.command); - restored.command_done = true; - restored.command_status = t.status; - } - if (revive) p.emitSpawn(i, restored.serial, t.cwd); - if (t.petscii and pardes.panes.terminal.petscii(restored) == false) pardes.panes.terminal.togglePetscii(restored); - break :terminal restored; - }, - .file => file: { - const restored = try pardes.panes.File.restore(p, i, src); - // A twin: on the earlier pane's buffer again. - if (src.file.?.twin_of) |j| if (j < i) pardes.panes.File.relink(p, j, i, src.file.?.dot); - break :file restored; - }, - .image => restore_image: { - const im = src.image.?; - if (pardes.panes.Pdf.isPath(im.path)) { - var raw: []u8 = if (im.bytes_b64.len > 0) - try decodeBytes(gpa, im.bytes_b64) - else - &.{}; - errdefer if (raw.len > 0) gpa.free(raw); - if (comptime pdf_enabled) { - if (pardes.panes.Pdf.openPane(p, i, im.path, src.scroll + 1, .last) catch null) |restored| { - if (raw.len > 0) gpa.free(raw); - raw = &.{}; - // Its fit and tint as they were (PdfFit, PdfTint). - const pv = &restored.pdf.?; - if (std.meta.stringToEnum(@TypeOf(pv.fit), im.pdf_fit)) |fit| if (fit != pv.fit) pardes.panes.Pdf.toggleFit(restored); - if (std.meta.stringToEnum(@TypeOf(pv.tint), im.pdf_tint)) |tint| while (pv.tint != tint) pardes.panes.Pdf.toggleTint(restored); - restored.cols = @max(1, src.cols); - restored.rows = @max(1, src.rows); - break :restore_image restored; - } - } - // If the source path is unavailable, retain its bytes - // as an ordinary file rather than dropping the pane. - const path = try gpa.dupe(u8, im.path); - errdefer gpa.free(path); - const content = if (raw.len > 0) raw else try gpa.dupe(u8, ""); - raw = &.{}; - errdefer if (content.len > 0) gpa.free(content); - const history = try pardes.panes.File.History.create(gpa); - errdefer gpa.destroy(history); - const restored = try p.newDocPane(i); - restored.file = .{ .path = path, .content = content, .history = history }; - restored.body.cur_pinned = true; - restored.cols = @max(1, src.cols); - restored.rows = @max(1, src.rows); - p.emit(.{ .watch = .{ .pane = @intCast(i), .on = true, .mode = .baseline_disk } }); - break :restore_image restored; - } - break :restore_image try pardes.panes.Image.restore(p, i, src); - }, - }; - tagline.restoreDumpTail(p, pane, src); + const pane = try restorePane(p, i, src); pane.vweight = src.vweight; pane.collapsed = src.collapsed; } @@ -1049,6 +986,85 @@ fn initDump(gpa: std.mem.Allocator, opts: Options, zon_bytes: []const u8, previo return p; } +/// Dump pane `src` made a pane again in slot `i`, installed (a fresh +/// serial) and not yet placed: a Restore's, and a closed pane Panes brings +/// back (Store.zig). +pub fn restorePane(p: *Pardes, i: usize, src: Pane) !*pardes.panes.Pane { + const gpa = p.gpa; + const pane: *pardes.panes.Pane = switch (src.kind) { + .terminal => terminal: { + const t = src.terminal.?; + // A host that runs shells gets them back: the old history + // above a new shell in the directory it was in. The web + // shell and an isolated build only ever replay it. + // A command pane comes back finished, showing what it said + // and how it ended: its command is not run again. + const live = comptime (terminal_panes and platform != .web and !isolated); + const revive = live and t.cwd.len <= effect_path_cap and t.command.len == 0; + const restored = try pardes.panes.terminal.restore(p, src, revive); + p.installPane(i, restored); + try restored.setOwnedCwd(t.cwd); + if (t.shell.len > 0) restored.shell = try gpa.dupe(u8, t.shell); + if (t.command.len > 0) { + restored.command = try gpa.dupe(u8, t.command); + restored.command_done = true; + restored.command_status = t.status; + } + if (revive) p.emitSpawn(i, restored.serial, t.cwd); + if (t.petscii and pardes.panes.terminal.petscii(restored) == false) pardes.panes.terminal.togglePetscii(restored); + break :terminal restored; + }, + .file => file: { + const restored = try pardes.panes.File.restore(p, i, src); + // A twin: on the earlier pane's buffer again. + if (src.file.?.twin_of) |j| if (j < i) pardes.panes.File.relink(p, j, i, src.file.?.dot); + break :file restored; + }, + .image => restore_image: { + const im = src.image.?; + if (pardes.panes.Pdf.isPath(im.path)) { + var raw: []u8 = if (im.bytes_b64.len > 0) + try decodeBytes(gpa, im.bytes_b64) + else + &.{}; + errdefer if (raw.len > 0) gpa.free(raw); + if (comptime pdf_enabled) { + if (pardes.panes.Pdf.openPane(p, i, im.path, src.scroll + 1, .last) catch null) |restored| { + if (raw.len > 0) gpa.free(raw); + raw = &.{}; + // Its fit and tint as they were (PdfFit, PdfTint). + const pv = &restored.pdf.?; + if (std.meta.stringToEnum(@TypeOf(pv.fit), im.pdf_fit)) |fit| if (fit != pv.fit) pardes.panes.Pdf.toggleFit(restored); + if (std.meta.stringToEnum(@TypeOf(pv.tint), im.pdf_tint)) |tint| while (pv.tint != tint) pardes.panes.Pdf.toggleTint(restored); + restored.cols = @max(1, src.cols); + restored.rows = @max(1, src.rows); + break :restore_image restored; + } + } + // If the source path is unavailable, retain its bytes + // as an ordinary file rather than dropping the pane. + const path = try gpa.dupe(u8, im.path); + errdefer gpa.free(path); + const content = if (raw.len > 0) raw else try gpa.dupe(u8, ""); + raw = &.{}; + errdefer if (content.len > 0) gpa.free(content); + const history = try pardes.panes.File.History.create(gpa); + errdefer gpa.destroy(history); + const restored = try p.newDocPane(i); + restored.file = .{ .path = path, .content = content, .history = history }; + restored.body.cur_pinned = true; + restored.cols = @max(1, src.cols); + restored.rows = @max(1, src.rows); + p.emit(.{ .watch = .{ .pane = @intCast(i), .on = true, .mode = .baseline_disk } }); + break :restore_image restored; + } + break :restore_image try pardes.panes.Image.restore(p, i, src); + }, + }; + tagline.restoreDumpTail(p, pane, src); + return pane; +} + test "a dump keeps the settings that differ from a fresh session's, and a restore applies them" { const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .tty_only = true }); diff --git a/src/layout.zig b/src/layout.zig index e674ccbf..efa79394 100644 --- a/src/layout.zig +++ b/src/layout.zig @@ -1070,6 +1070,32 @@ pub fn attachFrom(p: *Pardes, owner: usize, id: usize, rows: u16, giver: usize) return true; } +/// A closed pane brought back (Store.reopen) where it was: next to +/// `gainer`, the pane its rows went to when it closed, below it (under its +/// group) or above it, `rows` tall, those rows taken from `gainer` alone, +/// so no other pane moves. False when the gainer is folded or too short +/// to give a pane its minimum and keep its own. +pub fn giveBack(p: *Pardes, id: usize, gainer: usize, below: bool, rows: u16) bool { + const g = p.panes[gainer] orelse return false; + const nw = p.panes[id] orelse return false; + if (g.collapsed) return false; + compute(p); + const f = findPane(p, gainer) orelse return false; + // Its tag wraps at the column's width: measured there. + p.rects[id].w = p.col_w[f.col]; + const gh = p.rects[gainer].h; + const least = minRows(p, id); + const keeps = minRows(p, gainer); + if (gh < least + keeps) return false; + const give = std.math.clamp(rows, least, gh - keeps); + snapColWeights(p, f.col); + insert(p, f.col, if (below) groupEnd(p, f.col, f.idx) else f.idx, id); + g.vweight = @floatFromInt(gh - give); + nw.vweight = @floatFromInt(give); + compute(p); + return true; +} + /// Collapse on an owner with attachments: the whole group folds to its /// tags, every row it gave up to the one unfolded neighbour outside it, /// and unfolds again from that neighbour, as one pane's Collapse does. diff --git a/src/look.zig b/src/look.zig index cd8df4fc..ede7d910 100644 --- a/src/look.zig +++ b/src/look.zig @@ -1813,8 +1813,12 @@ pub fn lookAt(p: *Pardes, id: usize, operand_raw: []const u8) void { switch (found) { .none => lookUnresolved(p, id, pane, trimmed, std.mem.trimEnd(u8, txt, "\r\n")), .pane => |t| { - // `@p` names no open pane: a miss, said. - if (t.id >= MAX_PANES or p.panes[t.id] == null) return missed(p, id, "no pane {s}", .{pl.path[0..@min(pl.path.len, 32)]}); + // `@p` names no open pane: one this session closed comes + // back where it was (Store.reopen), any other is a miss, said. + if (t.id >= MAX_PANES or p.panes[t.id] == null) { + if (p.store.closedAddress(pl.path)) |serial| if (p.store.reopen(p, serial, id)) return; + return missed(p, id, "no pane {s}", .{pl.path[0..@min(pl.path.len, 32)]}); + } const target = p.panes[t.id].?; // A PDF's page past its last is a miss, as a line past a file's // end is: never the last page in its place (opening one, the diff --git a/src/main.zig b/src/main.zig index 9086fa90..26431324 100644 --- a/src/main.zig +++ b/src/main.zig @@ -707,7 +707,7 @@ fn nativeMain(std_init: std.process.Init) !void { opts.startup_config = found.bytes; opts.startup_config_path = found.path; opts.config_dir = found.dir; - opts.recent_path = recentPath(init.io, arena, init.environ_map); + opts.store_path = storePath(init.io, arena, init.environ_map); if (found.dir) |d| @import("crash.zig").setDir(d); if (detach) |name| { const named = if (name.len != 0) @@ -789,10 +789,11 @@ test { if (comptime pardes.font_picker) _ = @import("fonts.zig"); } -/// Where the list of files opened lately is kept: $XDG_STATE_HOME/pardes -/// /recent, else ~/.local/state/pardes/recent, the directory made if need -/// be; null with no home to keep it in (the list then lasts the session). -fn recentPath(io: std.Io, arena: std.mem.Allocator, env: *const std.process.Environ.Map) ?[]const u8 { +/// Where the store every window shares is kept (Store.zig): +/// $XDG_STATE_HOME/pardes/store, else ~/.local/state/pardes/store, the +/// directory made if need be; null with no home to keep it in (Recent and +/// the closed panes then last the session). +fn storePath(io: std.Io, arena: std.mem.Allocator, env: *const std.process.Environ.Map) ?[]const u8 { const dir = dir: { if (env.get("XDG_STATE_HOME")) |base| if (base.len != 0 and std.fs.path.isAbsolute(base)) break :dir std.fs.path.join(arena, &.{ base, "pardes" }) catch return null; @@ -801,5 +802,5 @@ fn recentPath(io: std.Io, arena: std.mem.Allocator, env: *const std.process.Envi break :dir std.fs.path.join(arena, &.{ home, ".local", "state", "pardes" }) catch return null; }; std.Io.Dir.cwd().createDirPath(io, dir) catch return null; - return std.fs.path.join(arena, &.{ dir, "recent" }) catch null; + return std.fs.path.join(arena, &.{ dir, "store" }) catch null; } diff --git a/src/ninep/tree.zig b/src/ninep/tree.zig index 59ef5ef4..7b107ea7 100644 --- a/src/ninep/tree.zig +++ b/src/ninep/tree.zig @@ -1110,6 +1110,10 @@ fn readFile(p: *Pardes, req: Req, target: Target) Reply { .ctl => ctl.readRoot(p, req), .commands => ctl.readCommands(p, req), .recent => recent: { + // Every window's files: what the others wrote since, read, + // unless a step is out mid-syscall (nothing may change the + // core under it): then the list as it was. + if (pardes.turn.out == 0) p.store.refresh(p); var text: std.Io.Writer.Allocating = .init(p.scratch.allocator()); pardes.panes.Output.recentText(p, &text.writer, false) catch break :recent Reply.fail(req.tag, E.NOMEM); p.fs.stage(p.gpa).appendSlice(p.gpa, text.written()) catch break :recent Reply.fail(req.tag, E.NOMEM); diff --git a/src/pardes.zig b/src/pardes.zig index 3c5cf6a7..7f79f094 100644 --- a/src/pardes.zig +++ b/src/pardes.zig @@ -16,6 +16,7 @@ const locations = @import("locations.zig"); pub const tagline = @import("tagline.zig"); pub const exec = @import("exec.zig"); const recent_files = @import("recent.zig"); +const Store = @import("Store.zig"); pub const mouse = @import("mouse.zig"); pub const normal = @import("normal.zig"); pub const edit = @import("edit.zig"); @@ -484,6 +485,7 @@ test { _ = @import("draw.zig"); _ = @import("dump.zig"); // its tests ran nowhere before _ = @import("recent.zig"); + _ = @import("Store.zig"); _ = @import("Presentation.zig"); _ = @import("animation.zig"); _ = @import("pager.zig"); @@ -4326,10 +4328,10 @@ pub const Options = struct { ninep_quic: ?[]const u8 = null, mounts: []const filesystem.Mount = &.{}, config_dir: ?[]const u8 = null, - /// Where the list of files opened lately is kept across sessions - /// (recent.zig), set by the host that has a state directory; none, it - /// lives as long as the session. - recent_path: ?[]const u8 = null, + /// The store every window shares (Store.zig): the files opened lately, + /// the panes closed. Set by the host that has a state directory; none, + /// they last as long as the session. + store_path: ?[]const u8 = null, startup_config_path: ?[]const u8 = null, image_allocator: ?std.mem.Allocator = null, pdf_allocator: ?std.mem.Allocator = null, @@ -4402,6 +4404,9 @@ pub const Pardes = struct { /// The files opened lately, closed ones too (recent.zig): `Recent`, /// /recent, and the jumplist's way back to a closed pane. recent: recent_files.List = .{}, + /// Where Recent is kept, shared with every other window, and the panes + /// this session closed, which Panes brings back (Store.zig). + store: Store = .{}, /// acme's Incl: the directories a look at a name that is nowhere else /// (`stdio.h`, ``) is tried in, in order. The session's, seeded /// with C's (/usr/include, /usr/local/include), kept in a dump. @@ -4410,9 +4415,6 @@ pub const Pardes = struct { /// the next takes. twin_groups: std.ArrayList(panes.File.TwinGroup) = .empty, next_twin: u32 = 1, - /// The kept list was read (or there was none): only then is it written, - /// so a session never writes over one it did not read. - recent_loaded: bool = false, jumps: [MAX_JUMPS]Loc = undefined, njumps: usize = 0, jcur: usize = 0, @@ -4852,29 +4854,15 @@ pub const Pardes = struct { return if (comptime hosted) std.heap.smp_allocator else p.gpa; } - /// The kept list of files opened lately, read once at start. + /// The store read once at start: a new session's, Recent from it. pub fn loadRecent(p: *Pardes) void { - const path = p.opts.recent_path orelse return; - if (comptime !hosted) return; - defer p.recent_loaded = true; - const bytes = filesystem.readFile(p.gpa, path) catch return; - defer p.gpa.free(bytes); - p.recent.read(p.recentGpa(), bytes); + p.store = Store.init(p.opts.store_path); + p.store.load(p); } - /// Written out when it changed, at the end of a step and at the end. + /// What changed written out, at the end of a step and at the end. pub fn saveRecent(p: *Pardes) void { - if (!p.recent.dirty) return; - p.recent.dirty = false; - const path = p.opts.recent_path orelse return; - if (comptime !hosted) return; - if (!p.recent_loaded) return; - var out: std.Io.Writer.Allocating = .init(p.gpa); - defer out.deinit(); - p.recent.write(&out.writer) catch return; - turn.yield(); - defer turn.back(); - std.Io.Dir.cwd().writeFile(std.Io.Threaded.global_single_threaded.io(), .{ .sub_path = path, .data = out.written() }) catch {}; + p.store.flush(p, false); } /// A file pane's path and dot, for the recent list (0 when none). @@ -4928,7 +4916,8 @@ pub const Pardes = struct { pub fn deinit(p: *Pardes) void { // Every file open now is closed with its dot, and the list kept. for (p.panes) |slot| if (slot) |pane| p.noteClosed(pane); - p.saveRecent(); + p.store.flush(p, true); + p.store.deinit(p.recentGpa()); p.recent.deinit(p.recentGpa()); for (p.incl.items) |dir| p.gpa.free(dir); p.incl.deinit(p.gpa); @@ -7230,12 +7219,16 @@ pub const Pardes = struct { const owner = layout.ownerOf(p, id); const place = layout.findPane(p, id); const emptied = if (place) |f| (if (p.col_n[f.col] == 1) f.col else null) else null; + // What it was and where, for Panes to bring back (Store.zig). + const kept = p.store.keep(p, id); + errdefer if (kept) |k| k.free(p.recentGpa()); // Before anything is torn down, so a failure here changes nothing. try p.deinitPane(pane); const gainer = layout.absorbVWeight(p, id, owner orelse to); const beside = if (emptied) |c| p.besideColumn(c, p.rects[id]) else null; layout.removePane(p, id); p.panes[id] = null; + if (kept) |k| p.store.close(p, k, gainer); // The finder's last pane takes the column with it. const finder_gone = if (emptied) |c| p.finder.emptied(p, c) else false; if (p.active != id) return; @@ -7257,6 +7250,8 @@ pub const Pardes = struct { } try p.detachCwds(parents[0..count]); for (ids[0..count], parents[0..count]) |closed, pane| { + // Kept for Panes; its column goes, so it comes back as a new pane. + if (p.store.keep(p, closed)) |k| p.store.close(p, k, null); p.retirePane(pane); layout.removePane(p, closed); p.panes[closed] = null; diff --git a/src/recent.zig b/src/recent.zig index 112cb59f..2e3aabde 100644 --- a/src/recent.zig +++ b/src/recent.zig @@ -1,9 +1,11 @@ //! The files opened lately, most recent first, those since closed too, as //! `Recent` lists them and a jump to a closed pane reopens them: a path -//! and where the dot was when it closed. Kept across sessions in a small -//! file under $XDG_STATE_HOME/pardes (Options.recent_path) when the host -//! gives one. acme has nothing like it (its dump and Load are the nearest): -//! a file closed by accident, its path forgotten, is found here again. +//! and where the dot was when it closed. Kept across sessions, and shared +//! by every window, in the store (Store.zig) when the host gives one: each +//! change is a record there, and the records other windows wrote are +//! `note`d here as they are read. acme has nothing like it (its dump and +//! Load are the nearest): a file closed by accident, its path forgotten, +//! is found here again. const std = @import("std"); @@ -22,11 +24,14 @@ pub const Entry = struct { /// cap drops. ponytail: a pane renamed away leaves its old path marked /// open until the session ends; kept rather than tracked by pane. open: bool = false, + /// Changed here since the store last heard of it: written out as a + /// record at the end of the step (Store.flush). + changed: bool = false, }; pub const List = struct { entries: std.ArrayList(Entry) = .empty, - /// Changed since it was last written out. + /// Some entry is `changed`. dirty: bool = false, pub fn deinit(l: *List, gpa: std.mem.Allocator) void { @@ -46,14 +51,8 @@ pub const List = struct { .path = gpa.dupe(u8, path) catch return, }; entry.open = true; - // The oldest closed file goes for it; an open one never does. - if (l.entries.items.len >= cap) { - var i = l.entries.items.len; - while (i > 0) : (i -= 1) if (!l.entries.items[i - 1].open) { - gpa.free(l.entries.orderedRemove(i - 1).path); - break; - }; - } + entry.changed = true; + l.dropOldest(gpa); l.entries.insert(gpa, 0, entry) catch { gpa.free(entry.path); entry = undefined; @@ -80,13 +79,58 @@ pub const List = struct { l.entries.items[i].aline = aline; l.entries.items[i].acol = acol; l.entries.items[i].open = false; + l.entries.items[i].changed = true; l.dirty = true; } + /// Full: the oldest closed file goes, to make room for one more; an + /// open one never does. + fn dropOldest(l: *List, gpa: std.mem.Allocator) void { + if (l.entries.items.len < cap) return; + var i = l.entries.items.len; + while (i > 0) : (i -= 1) if (!l.entries.items[i - 1].open) { + gpa.free(l.entries.orderedRemove(i - 1).path); + return; + }; + } + + /// A record read from the store (another window's, or this one's read + /// again): `path` was opened or closed there last, at that place. It + /// goes first, with that place; whether it is open HERE stays as it + /// was, and nothing is changed for the store to hear again. + pub fn note(l: *List, gpa: std.mem.Allocator, path: []const u8, line: u32, col: u32, aline: u32, acol: u32) void { + if (path.len == 0) return; + var entry: Entry = if (l.find(path)) |i| l.entries.orderedRemove(i) else blk: { + l.dropOldest(gpa); + break :blk .{ .path = gpa.dupe(u8, path) catch return }; + }; + entry.line = line; + entry.col = col; + entry.aline = aline; + entry.acol = acol; + l.entries.insert(gpa, 0, entry) catch { + gpa.free(entry.path); + entry = undefined; + }; + } + + /// This window's changes first again, in their order, after others' + /// records were noted over them: they are written after those, so + /// that is where every window's fold puts them. + pub fn changedFirst(l: *List) void { + var w: usize = 0; + for (0..l.entries.items.len) |i| if (l.entries.items[i].changed) { + const e = l.entries.items[i]; + std.mem.copyBackwards(Entry, l.entries.items[w + 1 .. i + 1], l.entries.items[w..i]); + l.entries.items[w] = e; + w += 1; + }; + } + /// A copy, for the session a Restore makes: its files closed until it /// opens them again. Out of memory, what was copied so far. pub fn clone(l: *const List, gpa: std.mem.Allocator) List { - var copy: List = .{ .dirty = true }; + var copy: List = .{ .dirty = l.dirty }; for (l.entries.items) |e| { const path = gpa.dupe(u8, e.path) catch break; var kept = e; @@ -105,14 +149,19 @@ pub const List = struct { } /// One line a file, ` `, most recent - /// first. + /// first: the old `recent` file, and a store record's body, a line. pub fn write(l: *const List, w: *std.Io.Writer) !void { + for (l.entries.items) |e| try writeEntry(e, w); + } + + pub fn writeEntry(e: Entry, w: *std.Io.Writer) !void { // A name with a newline in it would read back as two lines: not kept. - for (l.entries.items) |e| if (std.mem.indexOfScalar(u8, e.path, '\n') == null) + if (std.mem.indexOfScalar(u8, e.path, '\n') == null) try w.print("{d} {d} {d} {d} {s}\n", .{ e.line, e.col, e.aline, e.acol, e.path }); } - /// The lines `write` wrote; a line that is not one is passed over. + /// The lines `write` wrote (the old `recent` file), each changed for + /// the store to hear of; a line that is not one is passed over. pub fn read(l: *List, gpa: std.mem.Allocator, bytes: []const u8) void { var lines = std.mem.splitScalar(u8, bytes, '\n'); while (lines.next()) |line| { @@ -131,11 +180,25 @@ pub const List = struct { const path = rest; if (path.len == 0 or path[0] != '/' or l.find(path) != null) continue; const owned = gpa.dupe(u8, path) catch return; - l.entries.append(gpa, .{ .path = owned, .line = nums[0], .col = nums[1], .aline = nums[2], .acol = nums[3] }) catch { + l.entries.append(gpa, .{ .path = owned, .line = nums[0], .col = nums[1], .aline = nums[2], .acol = nums[3], .changed = true }) catch { gpa.free(owned); return; }; + l.dirty = true; + } + } + + /// One record's body read back: ` `. + pub fn parseLine(line: []const u8) ?struct { nums: [4]u32, path: []const u8 } { + var nums: [4]u32 = @splat(0); + var rest = line; + for (&nums) |*n| { + const sp = std.mem.indexOfScalar(u8, rest, ' ') orelse return null; + n.* = std.fmt.parseInt(u32, rest[0..sp], 10) catch return null; + rest = rest[sp + 1 ..]; } + if (rest.len == 0 or rest[0] != '/') return null; + return .{ .nums = nums, .path = rest }; } }; diff --git a/test/fs.py b/test/fs.py index 841dd32a..c0f0995c 100644 --- a/test/fs.py +++ b/test/fs.py @@ -711,7 +711,7 @@ def recent_survives_restart(binary): assert f'open {kept}\n' in client.read('/recent').decode() client.write(f'/pane/{serial}/ctl', b'Del\n') assert f'closed {kept}\n' in client.read('/recent').decode(), client.read('/recent') - assert (root / '.local' / 'state' / 'pardes' / 'recent').exists() + assert (root / '.local' / 'state' / 'pardes' / 'store').exists() with session(binary, root, 'recent2') as (client, _): listed = client.read('/recent').decode() assert f'closed {kept}\n' in listed, listed @@ -726,6 +726,45 @@ def recent_survives_restart(binary): assert f'open {kept}\n' in client.read('/recent').decode() +def del_twice(client, serial): + """Del, and again when the first refused over unsaved text.""" + try: + client.write(f'/pane/{serial}/ctl', b'Del\n') + except OSError: + client.write(f'/pane/{serial}/ctl', b'Del\n') + + +def store_shared_between_windows(binary): + """Two windows share one store (Store.zig): a file opened in one is in + the other's /recent at its next read, with no restart; a pane Del'd in + one comes back where it was from a look at its @p serial there, its text + with it, and only there.""" + with tempfile.TemporaryDirectory(prefix='pardes-store-') as directory: + root = Path(directory) + shared = root / 'shared.txt' + shared.write_bytes(b'one\ntwo\nthree\n') + with session(binary, root, 'store1') as (one, _), session(binary, root, 'store2') as (two, _): + serial = look(one, f'{shared}:3') + assert f'open {shared}\n' in one.read('/recent').decode() + assert f'closed {shared}\n' in two.read('/recent').decode(), two.read('/recent') + one.write(f'/pane/{serial}/ctl', b'Del\n') + assert f'closed {shared}\n' in one.read('/recent').decode() + scratch = new_pane(one, b'kept across a Del\n') + del_twice(one, scratch) + assert str(scratch) not in [row.split()[0] for row in one.read('/index').decode().splitlines()] + back = look(one, f'@p{scratch}') + assert one.read(f'/pane/{back}/body') == b'kept across a Del\n' + # The other window's session closed no such pane. + source = new_pane(two, b'') + try: + two.write(f'/pane/{source}/look', f'@p{scratch}\n'.encode()) + except OSError: + pass + assert b'kept across a Del' not in b''.join(two.read(f'/pane/{row.split()[0]}/body') + for row in two.read('/index').decode().splitlines()) + assert (root / '.local' / 'state' / 'pardes' / 'store').exists() + + def workflow_canary(binary): """One session driven as the dogfood agents drive it, asserting the log and the read-backs at every step: the canary for the main paths (the @@ -1163,6 +1202,7 @@ def test(binary, quic=False): putall_answers_after_its_saves(binary) workflow_canary(binary) recent_survives_restart(binary) + store_shared_between_windows(binary) python_repl_runs_one_line(binary) signal_cleans_up(binary) for options, message in [ -- cgit v1.3 From 4c635f357adb95235429d8905b8598a2643b4f3b Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Sat, 24 Oct 2026 13:55:12 -0300 Subject: drag 2/3: a pane's or column's grip let go past the window's edge opens it in a new window (Handover.zig) --- src/Handover.zig | 307 ++++++++++++++++++++++++++++++++++++++++++++++++ src/detached/server.zig | 3 +- src/detached/wire.zig | 6 +- src/dump.zig | 27 ++++- src/gui/gui.zig | 75 +++++++++++- src/host_io.zig | 14 +++ src/macos.zig | 3 +- src/main.zig | 4 + src/mouse.zig | 15 +++ src/pardes.zig | 24 ++++ 10 files changed, 467 insertions(+), 11 deletions(-) create mode 100644 src/Handover.zig (limited to 'src/main.zig') diff --git a/src/Handover.zig b/src/Handover.zig new file mode 100644 index 00000000..fdbe509b --- /dev/null +++ b/src/Handover.zig @@ -0,0 +1,307 @@ +//! Panes between windows, as a browser's tabs go between its windows. A +//! pane's grip, or a column's, released past the window's edge carries it +//! out: dumped alone (dump.dumpBytes, `carried`), it opens in a new window +//! of its own, `pardes-gui -l` of that dump. The pane closes here only once +//! the new window answers on its 9P socket, so its text is never in no +//! window at all; a failed handover leaves it where it was, and a pane +//! edited while it was on its way stays here too (both then have it). +//! +//! The core only dumps, and closes or keeps when told (`finish`); the host +//! writes the dump, and its worker (`carry`, on a thread of its own) spawns +//! the window and waits for it, posting how it went into host_io.Inbox. +const Handover = @This(); + +const std = @import("std"); +const builtin = @import("builtin"); +const pardes = @import("pardes.zig"); +const layout = @import("layout.zig"); +const dump = @import("dump.zig"); +const ninep_io = @import("9p_io.zig"); +const Pardes = pardes.Pardes; +const MAX_PANES = pardes.MAX_PANES; +const libc = std.c; + +/// The handover in flight, one at a time: its number, what it carries, +/// and each carried pane's serial and revision as it was dumped. +seq: u32 = 0, +flying: bool = false, +carried: dump.Carried = .pane, +column_serial: u32 = 0, +count: usize = 0, +serials: [MAX_PANES]u32 = @splat(0), +revisions: [MAX_PANES]u32 = @splat(0), +/// The dump the host sends, gpa-owned while the handover flies. +bytes: ?[]u8 = null, + +pub fn deinit(h: *Handover, gpa: std.mem.Allocator) void { + if (h.bytes) |b| gpa.free(b); + h.bytes = null; +} + +/// Pane slot `at` (with what is attached to it, or alone when it is itself +/// an attachment), or column `at`, released past the window's edge: dumped, +/// and the host asked to carry it. Only text panes travel: a terminal's +/// shell is this process's child and would die with the pane here. +pub fn begin(h: *Handover, p: *Pardes, carried: dump.Carried, at: usize) void { + var keep: [MAX_PANES]bool = @splat(false); + var ids: [MAX_PANES]usize = undefined; + var n: usize = 0; + switch (carried) { + .pane => { + const f = layout.findPane(p, at) orelse return; + const end = if (layout.ownerOf(p, at) == null) layout.groupEnd(p, f.col, f.idx) else f.idx + 1; + for (p.col_panes[f.col][f.idx..end]) |id| { + ids[n] = id; + n += 1; + } + }, + .column => { + if (at >= p.ncol or p.col_n[at] == 0) return; + for (p.col_panes[at][0..p.col_n[at]]) |id| { + ids[n] = id; + n += 1; + } + }, + } + const said = if (carried == .pane) at else ids[0]; + if (h.flying) return p.setMessage(said, "a pane is already on its way to another window"); + for (ids[0..n]) |id| { + const pane = p.panes[id] orelse return; + if (pane.file == null) return p.setMessage(said, if (pane.isTerminal()) + "a terminal stays in its window: its shell is this window's child" + else + "only text panes go to another window, for now"); + } + for (ids[0..n]) |id| keep[id] = true; + const bytes = dump.dumpBytes(p, &keep, carried) catch |err| return p.reportError(said, "handover", err); + h.deinit(p.gpa); + h.bytes = bytes; + h.seq +%= 1; + h.flying = true; + h.carried = carried; + h.column_serial = if (carried == .column) layout.columnSerial(p, at) else 0; + h.count = n; + for (ids[0..n], 0..) |id, i| { + const pane = p.panes[id].?; + h.serials[i] = pane.serial; + h.revisions[i] = pane.file.?.revision; + } + p.setMessage(said, if (carried == .pane) "to a new window…" else "the column, to a new window…"); + p.emit(.{ .hand_over = .{ .seq = h.seq } }); +} + +/// How the host's handover `seq` went: taken by `to` (failure null), or +/// not. Taken, its panes close here, unless one was edited since it was +/// dumped: that one stays, so neither window loses the edit. +pub fn finish(h: *Handover, p: *Pardes, seq: u32, to: []const u8, failure: ?[]const u8) void { + if (!h.flying or seq != h.seq) return; + h.flying = false; + h.deinit(p.gpa); + var buf: [320]u8 = undefined; + if (failure) |why| { + const at = p.paneBySerial(h.serials[0]) orelse p.active; + return p.reportFailure(at, std.fmt.bufPrint(&buf, "handover: {s}; the pane stays here", .{why}) catch "handover failed; the pane stays here"); + } + var kept: usize = 0; + for (h.serials[0..h.count], h.revisions[0..h.count]) |serial, revision| { + const id = p.paneBySerial(serial) orelse continue; // closed with its owner + const pane = p.panes[id].?; + if (pane.file == null or pane.file.?.revision != revision) { + // Out of its group, or the owner's close would take it along. + pane.attached_to = null; + kept += 1; + continue; + } + p.removePane(id, null) catch |err| { + kept += 1; + p.reportError(id, "handover", err); + }; + } + if (h.carried == .column) if (layout.columnBySerial(p, h.column_serial)) |c| { + if (p.col_n[c] == 0 and p.ncol > 1) layout.dropColumn(p, c); + }; + layout.compute(p); + p.setMessage(p.active, if (kept == 0) + std.fmt.bufPrint(&buf, "moved to {s}", .{to}) catch "moved" + else + std.fmt.bufPrint(&buf, "copied to {s}; edited on the way, kept here too", .{to}) catch "copied"); +} + +// ---- the host's half: a worker that carries the dump ---- + +/// A handover for a worker: the dump's file, and the window's geometry for +/// a new one. The worker owns it and frees it with `gpa`. +pub const Job = struct { + gpa: std.mem.Allocator, + seq: u32, + path: [:0]u8, + /// `--geometry=` for a new window: `WxH`, `+X+Y` when the host can place it. + geometry: [64]u8 = undefined, + geometry_len: usize = 0, + /// Where it says how it went: (seq, true, where) or (seq, false, why); + /// the words are borrowed for the call. + post: *const fn (ctx: ?*anyopaque, seq: u32, ok: bool, words: []const u8) void, + post_ctx: ?*anyopaque, +}; + +/// The file a handover's dump goes in: the runtime directory, the user's +/// alone, else the dump directory. Null-terminated, `gpa`'s. +pub fn dumpPath(gpa: std.mem.Allocator, seq: u32) ![:0]u8 { + var dir_buf: [1024]u8 = undefined; + const dir: []const u8 = if (libc.getenv("XDG_RUNTIME_DIR")) |x| std.mem.span(x) else dump.defaultDirectory(&dir_buf) orelse return error.NoDirectory; + return std.fmt.allocPrintSentinel(gpa, "{s}/pardes-handover-{d}-{d}.zon", .{ dir, libc.getpid(), seq }, 0); +} + +/// Runs the handover on its own thread, detached; it removes the dump's +/// file once someone has it, or nobody will. +pub fn start(job: *Job) !void { + const thread = try std.Thread.spawn(.{}, carry, .{job}); + thread.detach(); +} + +fn carry(job: *Job) void { + defer { + _ = libc.unlink(job.path); + job.gpa.free(job.path); + job.gpa.destroy(job); + } + var words: [256]u8 = undefined; + const pid = spawnWindow(job) catch |err| return job.post(job.post_ctx, job.seq, false, std.fmt.bufPrint(&words, "no new window: {s}", .{@errorName(err)}) catch "no new window"); + // Up when its registry entry answers: it read the dump before it + // listened (gui.localSession), so the file is no longer needed. + var entry_buf: [512]u8 = undefined; + const run = libc.getenv("XDG_RUNTIME_DIR") orelse ""; + const entry = std.fmt.bufPrint(&entry_buf, "{s}/9p/pardes/{d}", .{ std.mem.span(run), pid }) catch ""; + var waited: u32 = 0; + while (waited < 15_000) : (waited += 50) { + if (libc.kill(pid, @enumFromInt(0)) != 0) + return job.post(job.post_ctx, job.seq, false, "the new window ended before it was up"); + if (ninep_io.Client.readLimit(job.gpa, entry, "status", "status", 256)) |status| { + job.gpa.free(status); + return job.post(job.post_ctx, job.seq, true, std.fmt.bufPrint(&words, "a new window (pardes/{d})", .{pid}) catch "a new window"); + } else |_| {} + sleepMs(50); + } + _ = libc.kill(pid, libc.SIG.TERM); + job.post(job.post_ctx, job.seq, false, "the new window did not come up in 15 s"); +} + +fn sleepMs(ms: u32) void { + var ts: libc.timespec = .{ .sec = 0, .nsec = @as(isize, ms) * std.time.ns_per_ms }; + _ = libc.nanosleep(&ts, null); +} + +/// This program again, `-l` the dump: a new window, in a session of its own +/// (setsid) and not this one's child (forked twice), so it outlives this +/// window and leaves no zombie. Answers its pid. +fn spawnWindow(job: *Job) !libc.pid_t { + if (comptime builtin.os.tag != .linux) return error.Unsupported; + var exe_buf: [4096:0]u8 = undefined; + const n = libc.readlink("/proc/self/exe", &exe_buf, exe_buf.len - 1); + if (n <= 0) return error.NoExecutable; + exe_buf[@intCast(n)] = 0; + var geometry_z: [80:0]u8 = undefined; + const geometry = try std.fmt.bufPrintSentinel(&geometry_z, "--geometry={s}", .{job.geometry[0..job.geometry_len]}, 0); + const argv = [_:null]?[*:0]const u8{ &exe_buf, "-l", job.path, if (job.geometry_len > 0) geometry else null, null }; + var fds: [2]c_int = undefined; + if (libc.pipe(&fds) != 0) return error.NoPipe; + defer _ = libc.close(fds[0]); + const first = libc.fork(); + if (first < 0) { + _ = libc.close(fds[1]); + return error.NoFork; + } + if (first == 0) { + // Only async-signal-safe calls between fork and exec. + _ = libc.setsid(); + const second = libc.fork(); + if (second == 0) { + _ = libc.close(fds[1]); + _ = libc.execve(&exe_buf, &argv, @ptrCast(libc.environ)); + libc._exit(127); + } + _ = libc.write(fds[1], std.mem.asBytes(&second), @sizeOf(libc.pid_t)); + libc._exit(0); + } + _ = libc.close(fds[1]); + _ = libc.waitpid(first, null, 0); + var pid: libc.pid_t = 0; + if (libc.read(fds[0], std.mem.asBytes(&pid), @sizeOf(libc.pid_t)) != @sizeOf(libc.pid_t) or pid <= 0) return error.NoFork; + return pid; +} + +// ---- tests ---- + +/// Two text panes in one column, the lower one `/test.txt`'s twin made by +/// New, and the grip of pane `id` let go past the window's edge. +fn twoPanes(gpa: std.mem.Allocator) !*Pardes { + const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 30 }); + errdefer p.deinit(); + _ = try p.setTestFile("alpha\nbeta\n"); + try std.testing.expect(p.executeBuiltinLine(p.active, "New")); + p.sync(); + return p; +} + +fn releaseOutside(p: *Pardes, id: usize) void { + const r = p.rects[id]; + p.update(.{ .mouse = .{ .button = .left, .kind = .press, .col = r.x, .row = p.tagTop(p.panes[id].?, r) } }); + p.update(.{ .mouse = .{ .button = .left, .kind = .drag, .col = p.screen_w - 1, .row = r.y + 1 } }); + p.update(.{ .mouse = .{ .button = .left, .kind = .release, .col = p.screen_w - 1, .row = r.y + 1, .outside = true } }); +} + +test "a grip let go past the window's edge dumps its pane alone, and closes it only once another window has it" { + const p = try twoPanes(std.testing.allocator); + defer p.deinit(); + const f = layout.findPane(p, 0).?; + try std.testing.expect(p.col_n[f.col] == 2); + const other = p.col_panes[f.col][1 - f.idx]; + const before = p.rects[other]; + releaseOutside(p, 0); + // Dumped and asked for; nothing moved yet. + try std.testing.expect(p.handover.flying); + try std.testing.expect(p.drag == .none); + try std.testing.expect(p.panes[0] != null); + try std.testing.expectEqual(before, p.rects[other]); + var parsed = try dump.readZon(std.testing.allocator, p.handover.bytes.?, "test"); + defer parsed.deinit(); + try std.testing.expectEqual(@as(?dump.Carried, .pane), parsed.value.carried); + try std.testing.expectEqual(@as(usize, 1), parsed.value.panes.len); + try std.testing.expectEqual(@as(usize, 1), parsed.value.columns.len); + try std.testing.expectEqualStrings("/test.txt", parsed.value.panes[0].file.?.path); + // A second one waits for the first. + releaseOutside(p, other); + try std.testing.expect(p.panes[other] != null); + // Refused (no window took it): it stays. + p.update(.{ .handed = .{ .seq = p.handover.seq, .failure = "no window" } }); + try std.testing.expect(!p.handover.flying); + try std.testing.expect(p.panes[0] != null); + // Taken: it closes, and the pane beside it takes its rows (Del's rule). + releaseOutside(p, 0); + const serial = p.panes[0].?.serial; + p.update(.{ .handed = .{ .seq = p.handover.seq, .to = "pardes/1" } }); + try std.testing.expect(p.paneBySerial(serial) == null); + p.sync(); + try std.testing.expectEqual(@as(usize, 1), p.col_n[layout.findPane(p, other).?.col]); +} + +test "a pane edited while it is on its way to another window stays here too" { + const p = try twoPanes(std.testing.allocator); + defer p.deinit(); + releaseOutside(p, 0); + const pane = p.panes[0].?; + pane.file.?.revision += 1; // an edit after the dump + p.update(.{ .handed = .{ .seq = p.handover.seq, .to = "pardes/1" } }); + try std.testing.expect(p.panes[0] == pane); +} + +test "a terminal's grip let go past the edge stays: its shell is this window's" { + const p = try Pardes.init(std.testing.allocator, .{ .cols = 100, .rows = 30, .shells = 3 }); + defer p.deinit(); + p.update(.{ .resize = .{ .cols = 100, .rows = 30 } }); + const id = p.col_panes[1][0]; + try std.testing.expect(p.panes[id].?.isTerminal()); + releaseOutside(p, id); + try std.testing.expect(!p.handover.flying); + try std.testing.expect(p.panes[id] != null); +} diff --git a/src/detached/server.zig b/src/detached/server.zig index eefce93e..d7dda6ba 100644 --- a/src/detached/server.zig +++ b/src/detached/server.zig @@ -201,7 +201,8 @@ pub const Session = struct { }, .search => |b| s.core.update(.{ .search = b }), // Ptys are read in the loop's own poll, not through the inbox. - .output, .eof, .files_changed, .fs_ready => {}, + // No hand_over host entry here (a session with no window): none comes. + .output, .eof, .files_changed, .fs_ready, .handed => {}, } } return batch.len != 0; diff --git a/src/detached/wire.zig b/src/detached/wire.zig index 82614b4f..9890dc1a 100644 --- a/src/detached/wire.zig +++ b/src/detached/wire.zig @@ -856,7 +856,7 @@ fn clientTag(msg: ClientMsg) ClientTag { return switch (msg) { .event => |ev| switch (ev) { // Machine-local reports and 9P requests belong to the session owner. - .output, .eof, .exited, .lsp_resp, .pipe_resp, .search, .file_changed, .tick => unreachable, + .output, .eof, .exited, .lsp_resp, .pipe_resp, .search, .file_changed, .handed, .tick => unreachable, inline else => |_, t| @field(ClientTag, @tagName(t)), }, inline else => |_, t| @field(ClientTag, @tagName(t)), @@ -986,7 +986,7 @@ pub fn encodeClient(out: []u8, msg: ClientMsg) Error![]const u8 { .pointer_leave => {}, .focus => |focused| try w.writeByte(@intFromBool(focused)), // See `clientTag`: no tag, so nothing to encode. - .output, .eof, .exited, .lsp_resp, .pipe_resp, .search, .file_changed, .tick => unreachable, + .output, .eof, .exited, .lsp_resp, .pipe_resp, .search, .file_changed, .handed, .tick => unreachable, }, } try finishMessage(&w, at); @@ -1137,7 +1137,7 @@ pub fn clientBound(msg: ClientMsg) usize { .paste => |b| b.len, .command => |line| line.len, // See `clientTag`: not on this wire in this direction. - .output, .eof, .exited, .lsp_resp, .pipe_resp, .search, .file_changed, .tick => unreachable, + .output, .eof, .exited, .lsp_resp, .pipe_resp, .search, .file_changed, .handed, .tick => unreachable, }, }; } diff --git a/src/dump.zig b/src/dump.zig index 140bc476..0da2513f 100644 --- a/src/dump.zig +++ b/src/dump.zig @@ -283,6 +283,10 @@ pub const Column = struct { pub const Mount = struct { name: []const u8, dial: []const u8 }; +/// What a grip carried out of its window (Handover.zig): one pane with the +/// panes attached to it, or a whole column. A session's own dump is none. +pub const Carried = enum { pane, column }; + pub const State = struct { magic: []const u8 = magic, version: u32 = version, @@ -303,6 +307,8 @@ pub const State = struct { settings: []const []const u8 = &.{}, /// Incl's directories, in order; null in older dumps (the defaults). incl: ?[]const []const u8 = null, + /// A dump a grip carried to another window; null for a session's own. + carried: ?Carried = null, }; /// A header is a text like any other: it may hold newlines, but not a @@ -710,12 +716,24 @@ test "validation bounds pane restore state" { // ---- a whole editor to and from a dump (acme keeps this in rows.c) ---- pub fn dumpState(p: *Pardes) !void { + const bytes = try dumpBytes(p, null, null); + if (p.dump_out) |d| p.gpa.free(d); + p.dump_out = bytes; + p.emit(.write_dump); +} + +/// The dump of the panes `keep` marks (every pane for null), gpa-owned: a +/// whole session's, or what a grip carries to another window (Handover.zig), +/// `carried` saying which. Only the columns holding a kept pane are in it, +/// and a carried pane's column tag is its old column's no longer. +pub fn dumpBytes(p: *Pardes, keep: ?*const [MAX_PANES]bool, carried: ?Carried) ![]u8 { const arena = p.scratch.allocator(); var slot_to_pane: [MAX_PANES]?usize = @splat(null); var dump_panes: [MAX_PANES]Pane = undefined; var panes_len: usize = 0; for (p.panes, 0..) |slot, id| { const pane = slot orelse continue; + if (keep) |k| if (!k[id]) continue; slot_to_pane[id] = panes_len; dump_panes[panes_len] = try dumpPane(p, arena, pane); panes_len += 1; @@ -725,6 +743,7 @@ pub fn dumpState(p: *Pardes) !void { for (0..p.panes.len) |id| { const i = slot_to_pane[id] orelse continue; const owner = layout.ownerOf(p, id) orelse continue; + // An attachment carried without its owner stands on its own. dump_panes[i].attached_to = slot_to_pane[owner]; } // Zerox's twins: the text once, in the first; each other names it. @@ -753,9 +772,10 @@ pub fn dumpState(p: *Pardes) !void { column_ids[c][ids_len] = compact; ids_len += 1; }; + if (keep != null and ids_len == 0) continue; columns[columns_len] = .{ .serial = layout.columnSerial(p, c), - .tag = p.col_tags[c].own, + .tag = if (carried == .pane) null else p.col_tags[c].own, .weight = @as(f32, @floatFromInt(p.col_weight[c])) / @as(f32, @floatFromInt(column_weight_unit)), .panes = column_ids[c][0..ids_len], }; @@ -777,14 +797,13 @@ pub fn dumpState(p: *Pardes) !void { .mounts = mounts[0..p.fs.mounts.items.len], .settings = try changedSettings(p, arena), .incl = p.incl.items, + .carried = carried, }; try validate(state); var out: std.Io.Writer.Allocating = .init(p.gpa); errdefer out.deinit(); try std.zon.stringify.serialize(state, .{ .whitespace = true }, &out.writer); - if (p.dump_out) |d| p.gpa.free(d); - p.dump_out = try out.toOwnedSlice(); - p.emit(.write_dump); + return out.toOwnedSlice(); } /// One pane as a dump keeps it, its strings in `arena`: a Restore's, and a diff --git a/src/gui/gui.zig b/src/gui/gui.zig index 86d751f5..39eedf89 100644 --- a/src/gui/gui.zig +++ b/src/gui/gui.zig @@ -1938,11 +1938,27 @@ fn runNative(init: std.process.Init, opts_in: pardes.Options, attach: ?[]const u // opacity would dim the text as well. SDL requires this flag at creation. const surface_opacity = native_wayland; if (surface_opacity) win_flags |= c.SDL_WINDOW_TRANSPARENT; - const window = c.SDL_CreateWindow("pardes", 1120, 720, win_flags) orelse { + // `--geometry=WxH[+X+Y]`, as X11 programs take it. + var want_w: c_int = 1120; + var want_h: c_int = 720; + var want_at: ?[2]c_int = null; + if (opts_in.geometry) |spec| geometry: { + const x_at = std.mem.indexOfScalar(u8, spec, 'x') orelse break :geometry; + const plus = std.mem.indexOfAnyPos(u8, spec, x_at, "+-") orelse spec.len; + want_w = std.math.clamp(std.fmt.parseInt(c_int, spec[0..x_at], 10) catch break :geometry, 200, 16384); + want_h = std.math.clamp(std.fmt.parseInt(c_int, spec[x_at + 1 .. plus], 10) catch break :geometry, 120, 16384); + if (plus == spec.len) break :geometry; + const second = std.mem.indexOfAnyPos(u8, spec, plus + 1, "+-") orelse break :geometry; + const gx = std.fmt.parseInt(c_int, spec[plus + @intFromBool(spec[plus] == '+') .. second], 10) catch break :geometry; + const gy = std.fmt.parseInt(c_int, spec[second + @intFromBool(spec[second] == '+') ..], 10) catch break :geometry; + want_at = .{ gx, gy }; + } + const window = c.SDL_CreateWindow("pardes", want_w, want_h, win_flags) orelse { log.err("SDL_CreateWindow: {s}", .{c.SDL_GetError()}); return error.SdlInit; }; defer c.SDL_DestroyWindow(window); + if (want_at) |at| _ = c.SDL_SetWindowPosition(window, at[0], at[1]); updateDisplayScale(window); if (native_wayland) log.info("Wayland opacity: background-only transparent surface", .{}); // On Linux the desktop's own cursor theme draws them (the compositor's @@ -3198,7 +3214,12 @@ fn dispatch(g: *Gui, in: *Input, sev: *const c.SDL_Event) void { }; g.pointer_mapped = true; g.pointer_cell = mc; - in.post(.{ .mouse = pointerMouse(button, if (b.down) .press else .release, mc, pointerMods()) }); + var ev = pointerMouse(button, if (b.down) .press else .release, mc, pointerMods()); + // Let go past the window's edge (SDL follows a held button out + // of the window: Wayland's implicit grab, X11's capture). + const win = windowGeometry(g.window); + ev.outside = !b.down and (b.x < 0 or b.y < 0 or b.x >= win.window_w or b.y >= win.window_h); + in.post(.{ .mouse = ev }); }, c.SDL_EVENT_MOUSE_MOTION => { const m = sev.motion; @@ -3886,6 +3907,7 @@ const Shell = struct { .lsp = lsp, .pipe = pipe, .search = search, + .hand_over = handOver, }; const grid_vtable: pardes.Host.VTable = vt: { @@ -3984,6 +4006,11 @@ const Shell = struct { b.deinit(s.gpa); s.saw_event = true; }, + .handed => |h| { + s.core.update(.{ .handed = .{ .seq = h.seq, .to = if (h.ok) h.words else "", .failure = if (h.ok) null else h.words } }); + s.gpa.free(h.words); + s.saw_event = true; + }, .files_changed => check_files = true, .fs_ready => {}, }; @@ -4555,6 +4582,50 @@ fn search(ctx: ?*anyopaque, gen: u32) void { pardes.Stream.runHere(s.core, gen); } +/// Handover `seq`'s dump to its file, and a worker to carry it to another +/// window (Handover.start). A new window is as big as this one, and where +/// the pointer let go of it when the display lets a window say where it +/// goes (X11; on Wayland the compositor places it). +fn handOver(ctx: ?*anyopaque, seq: u32, bytes: []const u8) void { + const s = shellOf(ctx); + const Handover = pardes.Handover; + const path = Handover.dumpPath(s.gpa, seq) catch |err| return s.core.update(.{ .handed = .{ .seq = seq, .failure = @errorName(err) } }); + const fd = libc.open(path, .{ .ACCMODE = .WRONLY, .CREAT = true, .TRUNC = true, .CLOEXEC = true }, @as(libc.mode_t, 0o600)); + const written = fd >= 0 and host_io.writeFd(fd, bytes); + if (fd >= 0) _ = libc.close(fd); + if (!written) { + _ = libc.unlink(path); + s.gpa.free(path); + return s.core.update(.{ .handed = .{ .seq = seq, .failure = "cannot write its dump" } }); + } + const job = s.gpa.create(Handover.Job) catch { + _ = libc.unlink(path); + s.gpa.free(path); + return s.core.update(.{ .handed = .{ .seq = seq, .failure = "out of memory" } }); + }; + job.* = .{ .gpa = s.gpa, .seq = seq, .path = path, .post = Queue.pushHanded, .post_ctx = s.queue }; + if (s.gui) |g| { + var w: c_int = 0; + var h: c_int = 0; + _ = c.SDL_GetWindowSize(g.window, &w, &h); + var gx: f32 = 0; + var gy: f32 = 0; + _ = c.SDL_GetGlobalMouseState(&gx, &gy); + const placed = !std.mem.eql(u8, std.mem.span(c.SDL_GetCurrentVideoDriver()), "wayland"); + const geometry = (if (placed) + std.fmt.bufPrint(&job.geometry, "{d}x{d}+{d}+{d}", .{ w, h, @as(i32, @intFromFloat(gx)) - 40, @as(i32, @intFromFloat(gy)) - 10 }) + else + std.fmt.bufPrint(&job.geometry, "{d}x{d}", .{ w, h })) catch ""; + job.geometry_len = geometry.len; + } + Handover.start(job) catch |err| { + _ = libc.unlink(path); + s.gpa.free(path); + s.gpa.destroy(job); + return s.core.update(.{ .handed = .{ .seq = seq, .failure = @errorName(err) } }); + }; +} + fn pollCwds(core: *pardes.Pardes, ptys: *[pardes.MAX_PANES]?Pty) void { for (ptys, 0..) |slot, id| if (slot) |pt| { if (pt.fd < 0) continue; diff --git a/src/host_io.zig b/src/host_io.zig index f5d6f375..af284e84 100644 --- a/src/host_io.zig +++ b/src/host_io.zig @@ -51,6 +51,9 @@ pub const Host = struct { /// Start the streaming search of this generation on a worker /// (pardes.Stream.start); absent, it runs on the loop. search: ?*const fn (ctx: ?*anyopaque, gen: u32) void = null, + /// Carry the dump of handover `seq` to another window on a worker + /// (Handover.start), which answers through the inbox's `handed`. + hand_over: ?*const fn (ctx: ?*anyopaque, seq: u32, bytes: []const u8) void = null, }; }; @@ -135,6 +138,9 @@ pub const Inbox = struct { /// A streaming search's rows (pardes.Stream), of whatever generation: /// the core drops a stale one. search: pardes.Stream.Batch, + /// How a handover went (Handover.zig): `words` is where it went, or + /// why it did not; gpa-owned. + handed: struct { seq: u32, ok: bool, words: []u8 }, files_changed, fs_ready, @@ -148,6 +154,7 @@ pub const Inbox = struct { response.deinit(gpa); }, .search => |b| b.deinit(gpa), + .handed => |h| gpa.free(h.words), .eof, .files_changed, .fs_ready => {}, } } @@ -432,6 +439,13 @@ pub const Inbox = struct { q.push(.{ .pipe = response }); } + /// A handover's end (Handover.Job.post). + pub fn pushHanded(ctx: ?*anyopaque, seq: u32, ok: bool, words: []const u8) void { + const q: *Inbox = @ptrCast(@alignCast(ctx.?)); + const copy = q.gpa.dupe(u8, words) catch return; + q.push(.{ .handed = .{ .seq = seq, .ok = ok, .words = copy } }); + } + /// A streaming search's batch (pardes.Stream.start's sink). Never /// dropped for want of room, as output is not: the worker waits for /// room, a wait its cancel ends (false: it stops). diff --git a/src/macos.zig b/src/macos.zig index 7599a02d..8d372432 100644 --- a/src/macos.zig +++ b/src/macos.zig @@ -1104,7 +1104,8 @@ fn drainInbox(st: *State) bool { // ponytail: no `search` host entry here, so Stream runs on the loop. .search => |b| st.core.update(.{ .search = b }), // The SDL shell's: this one's file watches and 9P are its own. - .files_changed, .fs_ready => {}, + // ponytail: no hand_over host entry on macOS yet, so none comes. + .files_changed, .fs_ready, .handed => {}, } } for (0..pardes.MAX_PANES) |pane| { diff --git a/src/main.zig b/src/main.zig index 26431324..4e6b49bb 100644 --- a/src/main.zig +++ b/src/main.zig @@ -100,6 +100,8 @@ const help_text = \\ see the same screen \\ --attach= ...of the session called , which is what to \\ use when more than one is running + \\ --geometry=WxH[+X+Y] the window's size in points, and where it goes + \\ where the display lets a window say (X11) \\ -h, --help show this help and exit \\ --version print the version and exit \\ @@ -418,6 +420,8 @@ fn nativeMain(std_init: std.process.Init) !void { if (mounts_len == mounts.len) badArgs(init.io, "too many mounts (maximum {d})", .{mounts.len}); mounts[mounts_len] = .{ .name = name, .dial = dial }; mounts_len += 1; + } else if (std.mem.startsWith(u8, a, "--geometry=")) { + opts.geometry = a["--geometry=".len..]; } else if (std.mem.eql(u8, a, "--nested")) { opts.nested = true; } else if (std.mem.eql(u8, a, "-w") or std.mem.eql(u8, a, "--wait")) { diff --git a/src/mouse.zig b/src/mouse.zig index 3400afbe..d8f19059 100644 --- a/src/mouse.zig +++ b/src/mouse.zig @@ -477,6 +477,21 @@ pub fn handleMouse(p: *Pardes, event: Mouse) void { if (m.kind == .press) p.jumpBy(if (m.button == .back) -1 else 1); return; } + // A grip let go past the window's edge, as a browser's tab dragged out + // of its window: the pane or column goes to another window. Inside, the + // grip's drag is the layout move below, as it always was. + if (m.kind == .release and m.outside and m.button == config.select_button) switch (p.drag) { + .move => |d| { + p.drag = .none; + return p.handover.begin(p, .pane, d.id); + }, + .column_move => |d| { + p.drag = .none; + const column = layout.columnBySerial(p, d.serial) orelse return; + return p.handover.begin(p, .column, column); + }, + else => {}, + }; const raw_col = @min(m.col, p.screen_w -| 1); const raw_row = @min(m.row, p.screen_h -| 1); p.pointer_raw_col = raw_col; diff --git a/src/pardes.zig b/src/pardes.zig index 79a2e5a5..99231a57 100644 --- a/src/pardes.zig +++ b/src/pardes.zig @@ -28,6 +28,7 @@ pub const Macro = @import("Macro.zig"); pub const Pipe = @import("Pipe.zig"); pub const Stream = @import("Stream.zig"); pub const Finder = @import("Finder.zig"); +pub const Handover = @import("Handover.zig"); pub const colors = @import("colors.zig"); pub const Theme = colors.Theme; pub const themes = colors.themes; @@ -495,6 +496,7 @@ test { _ = @import("Stream.zig"); _ = @import("Finder.zig"); _ = @import("Tables.zig"); + _ = @import("Handover.zig"); } pub const Builtin = builtins.registry.Builtin(); @@ -3600,6 +3602,10 @@ pub const Mouse = struct { /// them there. A row of text never is one; a terminal, with no rule, /// resizes by the grip. rule_above: bool = false, + /// A release past the window's edge: a grip let go there carries its + /// pane or column out of the window (Handover.zig). col and row are + /// still the last cell inside. + outside: bool = false, }; pub const Key = struct { @@ -3690,6 +3696,9 @@ pub const Event = union(enum) { pointer_leave, /// The window gained (true) or lost the host's keyboard focus. focus: bool, + /// How the host's handover `seq` went (Handover.finish): taken by `to`, + /// or `failure` says why not. Borrowed for the step. + handed: struct { seq: u32, to: []const u8 = "", failure: ?[]const u8 = null }, tick, }; @@ -3737,6 +3746,9 @@ pub const Effect = union(enum) { /// Start the disk search of this generation (Stream.start) on a worker /// posting into the shell's inbox. search: struct { gen: u32 }, + /// Carry `handover.bytes`, the dump of handover `seq`, to another + /// window, answering with `handed` (Handover.zig). + hand_over: struct { seq: u32 }, /// Write what an Edit's `w` took (`Pipe.writes`), in order. edit_write, watch: struct { pane: u8, on: bool, mode: WatchMode = .reconcile }, @@ -4319,6 +4331,10 @@ pub const Options = struct { tty_toggle: u21 = config.tty_toggle_default, /// load a dump of another instance instead of spawning shells (acme -l) load_path: ?[]const u8 = null, + /// `--geometry=WxH[+X+Y]`: a pixel shell's window size, and where it + /// goes when the display lets it say (a pane carried out of another + /// window opens one as big as that, Handover.zig). + geometry: ?[]const u8 = null, nested: bool = false, /// The core of a `--detach` session (detached/server.zig): it has no /// terminal of its own, so Attach there is refused with why. @@ -4394,6 +4410,8 @@ pub const Pardes = struct { /// The finder column, where query panes stack with SearchPlace column /// (Finder.zig). finder: Finder = .{}, + /// A pane or column on its way to another window (Handover.zig). + handover: Handover = .{}, global_tag: Text = .{ .what = .workspace }, // derived each sync rects: [MAX_PANES]Rect = @splat(.{}), @@ -4955,6 +4973,7 @@ pub const Pardes = struct { for (p.spawn_dirs) |d| if (d) |dir| gpa.free(dir); p.pipe.deinit(gpa); p.stream.deinit(gpa); + p.handover.deinit(gpa); p.locations_cache.deinit(p.tree_sitter_gpa); p.fs.deinit(gpa); p.shell_rows.reset(gpa); @@ -5858,6 +5877,10 @@ pub const Pardes = struct { p.update(.{ .pipe_resp = .{ .id = q.id, .success = false, .outputs = &.{} } }), // No workers here (a test, a board): it runs on the loop. .search => |q| if (v.search) |f| f(p.host.ctx, q.gen) else Stream.runHere(p, q.gen), + // No windows here (a test, the tty): it stays. + .hand_over => |h| if (v.hand_over) |f| { + if (p.handover.bytes) |bytes| f(p.host.ctx, h.seq, bytes); + } else p.update(.{ .handed = .{ .seq = h.seq, .failure = "no other windows here" } }), .edit_write => { // Each write takes the bytes `w` took when it ran: the text // as it was before the Edit's changes. @@ -6133,6 +6156,7 @@ pub const Pardes = struct { .pinch => |scale| p.ov_pinch_scale = scale, .touch_scroll => |delta| p.ov_touch_scroll_delta = delta, .focus => |focused| p.window_focused = focused, + .handed => |h| p.handover.finish(p, h.seq, h.to, h.failure), .pointer_leave => { p.pointer_inside = false; p.pointer_body_hit = null; -- cgit v1.3