summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--abi/wire.zig43
-rw-r--r--build.zig110
-rw-r--r--build/core.zig109
-rw-r--r--build/library.zig49
-rw-r--r--build/patches.zig5
-rw-r--r--build/tools.zig7
-rw-r--r--core/CHANGELOG.md23
-rw-r--r--core/Core.zig17
-rw-r--r--core/Dir.zig2
-rw-r--r--core/File.zig15
-rw-r--r--core/Output.zig2
-rw-r--r--core/Plumb.zig2
-rw-r--r--core/Query.zig7
-rw-r--r--core/Stream.zig16
-rw-r--r--core/body_layer.zig5
-rw-r--r--core/builtins.zig4
-rw-r--r--core/config.zig2
-rw-r--r--core/draw.zig1
-rw-r--r--core/dump.zig7
-rw-r--r--core/edit_cmd.zig4
-rw-r--r--core/exec.zig2
-rw-r--r--core/fs.zig15
-rw-r--r--core/grammar_manifest.zig4
-rw-r--r--core/keys.zig3
-rw-r--r--core/lib_syntax.zig4
-rw-r--r--core/look.zig16
-rw-r--r--core/mouse.zig1
-rw-r--r--core/ninep/pty.zig14
-rw-r--r--core/ninep/tree.zig15
-rw-r--r--core/panes.zig14
-rw-r--r--core/replica.zig459
-rw-r--r--core/root.zig4
-rw-r--r--core/syntax.zig113
-rw-r--r--core/tape.zig2
-rw-r--r--dev/Inbox.zig75
-rw-r--r--dev/Ptys.zig34
-rw-r--r--dev/file_watch.zig14
-rw-r--r--dev/gui/gui.zig106
-rw-r--r--dev/host_io.zig55
-rw-r--r--dev/tui/tui.zig207
-rw-r--r--docs/next-editor.md4
-rw-r--r--docs/next-run.md13
-rw-r--r--docs/next-terminal.md2
-rw-r--r--docs/typ/building.typ81
-rw-r--r--docs/typ/command-line.txt6
-rw-r--r--runtime/9p_io.zig6
-rw-r--r--runtime/client.zig58
-rw-r--r--runtime/daemon.zig105
-rw-r--r--runtime/main.zig146
-rw-r--r--runtime/session.zig49
-rw-r--r--runtime/upgrade.zig12
-rw-r--r--test/behaviour/panes.zig1
-rw-r--r--test/behaviour/settings.zig2
-rw-r--r--test/consumer/bench.zig (renamed from test/lib/bench.zig)0
-rw-r--r--test/consumer/build.zig42
-rw-r--r--test/consumer/build.zig.zon16
-rw-r--r--test/consumer/editor.zig (renamed from test/lib/editor.zig)0
-rw-r--r--test/consumer/lib.zig (renamed from test/lib/lib.zig)0
-rw-r--r--test/daemon.py594
-rw-r--r--test/delay_relay.py10
-rw-r--r--test/e2e_harness.zig18
-rw-r--r--test/fs_namespace.zig3
-rw-r--r--test/lib/build.zig34
-rw-r--r--test/lib/build.zig.zon10
-rw-r--r--test/output.zig11
-rw-r--r--test/panes.zig12
-rw-r--r--test/process.zig3
-rw-r--r--test/process/terminals.zig9
-rw-r--r--test/process/tty_terminals.zig4
-rw-r--r--test/replicas.zig3
-rw-r--r--test/terminal.zig2
71 files changed, 2061 insertions, 782 deletions
diff --git a/abi/wire.zig b/abi/wire.zig
index 1f7d02d2..6c86685d 100644
--- a/abi/wire.zig
+++ b/abi/wire.zig
@@ -10,6 +10,8 @@ const pardes = @import("core");
const config = @import("pardes_options");
const build_info = @import("build_info");
+/// 24: a bye's byte says the client's window was closed (2), which ends a
+/// pair's session at its last client;
/// 23: a pane of a kind's frame names its rasters by key, their pixels
/// crossing before it as strips of 4 MiB at most over the rows it shows
/// (screen kind 5), and a replica lacking one asks for its pane again
@@ -36,7 +38,7 @@ const build_info = @import("build_info");
/// part B); 14: the hello names a session and
/// carries the semantics hash, and a ping is answered (phase 5's
/// groundwork); 13: the frames went (phase 3).
-pub const version: u16 = 23;
+pub const version: u16 = 24;
/// The terminal's build and the window's step alike (`semantics`).
const family = switch (config.platform) {
@@ -63,18 +65,19 @@ const family = switch (config.platform) {
pub const semantics: u64 = blk: {
@setEvalBranchQuota(1_000_000);
// The grammar set as the four words it was hashed as when it was four
- // options (highlighting, zig, minimal, full), so the hash stays.
+ // options (highlighting, zig, minimal, full), so the hash of a minimal
+ // or a full set stays: every set has highlighting, `none` no grammar.
const g = config.grammars;
// The two long ones (the dependencies, 2.5 KB, and the tape's shape,
// 11 KB) joined on, not formatted: formatting them at comptime was 5 %
// of a compile of the core.
break :blk std.hash.Wyhash.hash(0, std.fmt.comptimePrint(
- "wire {d}\npardes {s} {s}\n{s} grammars {} {} {} {} workspace_tag {} sources {}\nusize {d} {t}\n",
+ "wire {d}\npardes {s} {s}\n{s} grammars true {} {} {} workspace_tag {} sources {}\nusize {d} {t}\n",
.{
- version, build_info.version, build_info.commit orelse "unstamped",
- family, g != .disabled, g != .disabled,
- g == .minimal or g == .full, g == .full, config.workspace_tag,
- config.embed_sources, @sizeOf(usize), builtin.cpu.arch.endian(),
+ version, build_info.version, build_info.commit orelse "unstamped",
+ family, g != .none, g != .none,
+ g == .full, config.workspace_tag, config.embed_sources,
+ @sizeOf(usize), builtin.cpu.arch.endian(),
},
) ++ build_info.deps ++ "\n" ++ pardes.tape.shape);
};
@@ -191,6 +194,10 @@ pub const ServerTag = enum(u8) {
/// unit naming it: the hash, the whole's length and this piece's place
/// (u64le each), then at most 1 MiB of it (core/replica.zig).
blob = 0x0a,
+ /// The session's last word on a link: it ended, with its exit code.
+ ended = 0x0b,
+ /// ...or this client left it running (a Detach typed in it): its name.
+ left = 0x0c,
};
pub const ServerMsg = union(ServerTag) {
@@ -208,6 +215,8 @@ pub const ServerMsg = union(ServerTag) {
blobs: []const u8,
zstd: []const u8,
blob: []const u8,
+ ended: u8,
+ left: []const u8,
};
/// A message's header, for a payload sent on its own (a unit, a dump's
@@ -243,6 +252,8 @@ pub fn decodeServer(tag: u8, payload: []const u8) Error!ServerMsg {
.blobs => return .{ .blobs = payload },
.zstd => return .{ .zstd = payload },
.blob => return .{ .blob = payload },
+ .ended => .{ .ended = try r.takeByte() },
+ .left => .{ .left = try r.take(try r.takeInt(u16, .little)) },
};
try end(&r);
return msg;
@@ -267,6 +278,8 @@ pub fn encodeServer(out: []u8, msg: ServerMsg) Error![]const u8 {
.pong => |v| try w.writeInt(u64, v, .little),
.dump, .unit, .screen, .blobs, .zstd, .blob => |bytes| try w.writeAll(bytes),
.check => |v| try w.writeInt(u64, v, .little),
+ .ended => |code| try w.writeByte(code),
+ .left => |name| try putSlice16(&w, name),
}
try finishMessage(&w, at);
return w.buffered();
@@ -285,8 +298,9 @@ pub fn helloVersion(payload: []const u8) Error!u16 {
/// one call and no longer.
pub const ClientMsg = union(enum) {
hello: Hello,
- /// The client's end: `again`, it joins again for its view at once.
- bye: struct { again: bool = false },
+ /// The client's end: `again`, it joins again for its view at once;
+ /// `close`, its window was closed (a pair's session ends at its last).
+ bye: struct { again: bool = false, close: bool = false },
/// A round trip's probe, answered `pong` with the same value.
ping: u64,
screen_ack: []const u8,
@@ -503,7 +517,8 @@ pub fn encodeClient(out: []u8, msg: ClientMsg) Error![]const u8 {
try putSlice16(&w, h.session);
try w.writeByte(h.view orelse 0xff);
},
- .bye => |b| try w.writeByte(@intFromBool(b.again)),
+ // 0 it leaves, 1 it joins again, 2 its window was closed.
+ .bye => |b| try w.writeByte(if (b.close) 2 else @intFromBool(b.again)),
.ping => |v| try w.writeInt(u64, v, .little),
.screen_ack, .want => |bytes| try w.writeAll(bytes),
.check => {},
@@ -573,7 +588,12 @@ pub fn decodeClient(tag: u8, payload: []const u8) Error!ClientMsg {
else => |k| k,
},
} },
- .bye => .{ .bye = .{ .again = try getBool(&r) } },
+ .bye => .{ .bye = switch (try r.takeByte()) {
+ 0 => .{},
+ 1 => .{ .again = true },
+ 2 => .{ .close = true },
+ else => return error.BadValue,
+ } },
.ping => .{ .ping = try r.takeInt(u64, .little) },
.screen_ack => return .{ .screen_ack = payload },
.check => .check,
@@ -688,6 +708,7 @@ test "detached wire: every Event variant round-trips" {
try testing.expectEqualStrings("work", got.hello.session);
}
try testing.expect((try roundClient(&buf, .{ .bye = .{ .again = true } })).bye.again);
+ try testing.expect((try roundClient(&buf, .{ .bye = .{ .close = true } })).bye.close);
try testing.expectEqual(@as(?u8, 2), (try roundClient(&buf, .{ .hello = .{ .session = "work", .view = 2 } })).hello.view);
try testing.expectEqual(@as(u64, 0xfeed_beef_0000_0001), (try roundClient(&buf, .{ .ping = 0xfeed_beef_0000_0001 })).ping);
{
diff --git a/build.zig b/build.zig
index fc0c5044..125f4dcc 100644
--- a/build.zig
+++ b/build.zig
@@ -1,3 +1,40 @@
+//! pardes: the editor, and the library it is for a program that draws
+//! source text itself. `zig build -Dplatform=tui` (or `gui`, `macos`)
+//! builds the editor; docs/typ/building.typ has the rest.
+//!
+//! A package that depends on pardes is given its syntax, `pardes-syntax`
+//! (`core/lib_syntax.zig`):
+//!
+//! const pardes = b.dependency("pardes", .{
+//! .target = target,
+//! .optimize = optimize,
+//! .grammars = .minimal,
+//! });
+//! exe.root_module.addImport("pardes-syntax", pardes.module("pardes-syntax"));
+//!
+//! and, when it asks, the text pane, `pardes-editor`
+//! (`core/lib_editor.zig`), here with a grammar of its own handed in at
+//! run time:
+//!
+//! const pardes = b.dependency("pardes", .{
+//! .target = target,
+//! .optimize = optimize,
+//! .grammars = .none,
+//! .editor = true,
+//! });
+//! exe.root_module.addImport("pardes-editor", pardes.module("pardes-editor"));
+//!
+//! `.grammars`: the tree-sitter grammars compiled in: `none` (the runtime
+//! alone), `minimal` (C, C++ and Zig) or `full` (all of them; the default).
+//! `.editor`: exports `pardes-editor` besides `pardes-syntax`, and with it
+//! fetches uucode, mvzr and vaxis.
+//!
+//! Every dependency but tree-sitter's runtime is lazy in the manifest, so
+//! such a package fetches what it asked for and nothing else.
+//! `pardes-editor` has `pardes-syntax` in it as `.syntax`: a file belongs
+//! to one module, so a package imports one of the two. `test/consumer` is
+//! such a package, with both shapes; `lib-test`, which `unit-test` runs,
+//! builds and runs it.
const std = @import("std");
const builtin = @import("builtin");
const core = @import("build/core.zig");
@@ -8,6 +45,7 @@ const macos = @import("build/macos.zig");
const tools = @import("build/tools.zig");
const tests = @import("build/tests.zig");
const process_build = @import("build/process.zig");
+const patches = @import("build/patches.zig");
/// The package manifest, imported untyped (build/core.zig has the reason).
const zon = @import("build.zig.zon");
@@ -32,12 +70,17 @@ pub const PerfBuild = struct {
pub const macos_min_version: std.SemanticVersion = .{ .major = 13, .minor = 0, .patch = 0 };
-pub const TreeSitterGrammars = enum { disabled, zig, minimal, full };
+pub const TreeSitterGrammars = enum { none, minimal, full };
pub fn build(b: *std.Build) void {
- // A package that depends on pardes takes its library; nothing of the
- // editor is configured for it.
- if (!b.isRoot()) return @import("build/library.zig").build(b);
+ // What a package that depends on pardes may ask for (the head comment).
+ // pardes's own build takes the mode and the grammars too, and its target
+ // below, whose default -Dplatform says.
+ const optimize = b.standardOptimizeOption(.{});
+ const grammars = b.option(TreeSitterGrammars, "grammars", "the tree-sitter grammars compiled in: none (the runtime alone), minimal (C, C++ and Zig) or full (all of them; the default)") orelse .full;
+ if (!b.isRoot()) return library(b, b.standardTargetOptions(.{}), optimize, grammars, b.option(bool, "editor", "exports pardes-editor besides pardes-syntax, and with it fetches uucode, mvzr and vaxis") orelse false);
+
+ // Everything below is pardes's own: the editor, its tests and tools.
// This configure reads the environment (HOME, XDG_DATA_HOME,
// HX_HARNESS), the clock (-Dtest-rebuild) and vendor/themes and
// vendor/queries without telling the configure cache, so it is never
@@ -79,7 +122,6 @@ pub fn build(b: *std.Build) void {
},
},
});
- const optimize = b.standardOptimizeOption(.{});
// one substring, because that is what a dev loop needs: see the unit-test
// step for why the whole-binary run is worth narrowing
const test_filters: []const []const u8 = if (b.option([]const u8, "test-filter", "run only tests whose name contains this")) |f|
@@ -108,7 +150,6 @@ pub fn build(b: *std.Build) void {
}),
});
const c_optimize: std.lang.Optimize = if (optimize == .debug) .fast else optimize;
- const tree_sitter_grammars = b.option(TreeSitterGrammars, "tree-sitter", "tree-sitter grammar set: disabled, zig, minimal (c/c++/zig), full") orelse .full;
const tracy = b.option([]const u8, "tracy", "enable Tracy profiling; supply the path to a Tracy source checkout");
const macos_sdk = b.option([]const u8, "macos-sdk", "the macOS SDK a gui built for macOS from another system takes SDL's headers and frameworks from");
const macos_identity = b.option([]const u8, "macos-identity", "codesigning identity for pardes.app (default: ad-hoc)") orelse "-";
@@ -141,7 +182,7 @@ pub fn build(b: *std.Build) void {
const pdf_scroll_bench_step = b.step("pdf-scroll-bench", "benchmark fast continuous-strip PDF scrolling in ReleaseFast (-Doptimize=ReleaseFast -- [--json] [--reps N] [--warmup N] [--path FILE])");
const shell_cfg: core.ShellConfig = .{
- .tree_sitter_grammars = tree_sitter_grammars,
+ .tree_sitter_grammars = grammars,
.tracy = tracy,
.workspace_tag = workspace_tag,
.embed_sources = embed_sources,
@@ -175,8 +216,8 @@ pub fn build(b: *std.Build) void {
// core.module.
const root_set = core.module(b, parts, .{ .root = if (platform == .macos) "runtime/macos.zig" else "runtime/main.zig", .platform = platform, .builtin_addons = compiled_in, .tracy = true, .util = true });
const root_mod = root_set.root;
- // hxdiff's headless core and pardes-isolate are the primary shell's
- // configuration compiled two more ways, not two more frontends.
+ // hxdiff's headless core is the primary shell's configuration compiled
+ // another way, not another frontend.
const core_cfg: core.Core = .{ .root = "core/root.zig", .platform = platform, .builtin_addons = compiled_in, .tracy = true };
const core_set = core.module(b, parts, core_cfg);
const core_module = core_set.root;
@@ -186,7 +227,6 @@ pub fn build(b: *std.Build) void {
// and shell-test runs them all with one.
const lean_cfg: core.Core = .{ .root = "core/root.zig", .platform = platform, .builtin_addons = compiled_in, .terminal = false };
const core_lean = core.module(b, parts, lean_cfg);
- const isolated_mod: ?*std.Build.Module = if (platform == .tui) core.module(b, parts, .{ .root = "runtime/main.zig", .platform = platform, .builtin_addons = compiled_in, .isolated = true }).root else null;
// `zig build static`'s: the addons compiled in (Addon.zig). Linked
// statically on musl alone, as glibc links only dynamically; the gui's
// is dynamic (SDL and the GPU need the display's libraries) with the
@@ -270,17 +310,6 @@ pub fn build(b: *std.Build) void {
static_step.dependOn(&b.addFail("static is the terminal's on musl (-Dplatform=tui -Dtarget=x86_64-linux-musl) or the gui's (-Dplatform=gui)").step);
const run = b.addRunArtifact(exe);
b.step("run", "descend to the pardes").dependOn(&run.step);
- if (isolated_mod) |iso| {
- const iso_exe = b.addExecutable(.{
- .name = "pardes-isolate",
- .root_module = iso,
- });
- const run_iso = b.addRunArtifact(iso_exe);
- // Something to look at on arrival, read out of the binary itself.
- 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);
- }
const addon_libs: []const *std.Build.Step.Compile = if (a.pdf.lib) |l| b.allocator.dupe(*std.Build.Step.Compile, &.{ a.image_addon, l }) catch @panic("OOM") else &.{a.image_addon};
// The scripted language server the tests' sessions and the tty cases ask.
@@ -371,3 +400,42 @@ fn installHome(b: *std.Build, artifact: *std.Build.Step.Compile, home_bin: ?[]co
copy.has_side_effects = true;
b.getInstallStep().dependOn(&copy.step);
}
+
+/// What a package that depends on pardes is given (the head comment):
+/// `pardes-syntax`, the grammars, highlighting and themes, over tree-sitter
+/// and the grammars of its set alone; and with `editor`, `pardes-editor`,
+/// whose uucode, mvzr and vaxis (with what its build names) are fetched
+/// then and only then. Of vaxis it takes the grapheme width, which uucode
+/// alone feeds.
+fn library(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.lang.Optimize, grammars: TreeSitterGrammars, editor: bool) void {
+ var threaded: std.Io.Threaded = .init(b.allocator, .{});
+ defer threaded.deinit();
+ const io = threaded.io();
+ const mod = b.addModule("pardes-syntax", .{
+ .target = target,
+ .optimize = optimize,
+ .root_source_file = b.path("core/lib_syntax.zig"),
+ .link_libc = true,
+ });
+ // A library's options: its grammars, nothing stamped, no window.
+ const cfg: core.ShellConfig = .{ .tree_sitter_grammars = grammars };
+ mod.addOptions("pardes_options", core.options(b, cfg, .{ .root = "core/lib_syntax.zig", .platform = .tui, .terminal = false }, false));
+ const ts = core.treeSitter(b, io, target, if (optimize == .debug) .fast else optimize, grammars);
+ const themes = core.generatedThemes(b, io, target, optimize);
+ mod.addImport("generated_themes", themes);
+ ts.wire(mod);
+ mod.addImport("c_heap", b.createModule(.{ .target = target, .optimize = optimize, .root_source_file = b.path("core/c_heap.zig") }));
+ if (!editor) return;
+ const uucode = core.uucodeModule(b, target, optimize) orelse return;
+ const mvzr = patches.mvzr(b, patches.tool(b), b.dependencyLazy("mvzr", .{ .target = target, .optimize = optimize }) catch return, target, optimize);
+ const vaxis_dep = b.dependencyLazy("vaxis", .{ .target = target, .optimize = optimize, .external_uucode = true }) catch return;
+ const width = b.addWriteFiles();
+ _ = width.addCopyFile(vaxis_dep.path("src/gwidth.zig"), "gwidth.zig");
+ const vaxis = b.createModule(.{
+ .target = target,
+ .optimize = optimize,
+ .root_source_file = width.add("vaxis.zig", "pub const gwidth = @import(\"gwidth.zig\");\n"),
+ .imports = &.{.{ .name = "uucode", .module = uucode }},
+ });
+ _ = core.editorModule(b, "pardes-editor", target, optimize, cfg, .{ .themes = themes, .ts = ts, .uucode = uucode, .mvzr = mvzr, .vaxis = vaxis });
+}
diff --git a/build/core.zig b/build/core.zig
index 4e4a748b..b668211d 100644
--- a/build/core.zig
+++ b/build/core.zig
@@ -83,7 +83,6 @@ pub fn options(b: *std.Build, cfg: ShellConfig, c: Core, pdf: bool) *std.Build.S
o.addOption(Platform, "platform", c.platform);
o.addOption(TreeSitterGrammars, "grammars", cfg.tree_sitter_grammars);
o.addOption(bool, "terminal", c.terminal);
- o.addOption(bool, "isolated", c.isolated);
o.addOption(bool, "builtin_addons", c.builtin_addons);
// ...the pdf one only when it is built (-Dpdf=false leaves it out).
o.addOption(bool, "builtin_pdf", c.builtin_addons and pdf);
@@ -146,15 +145,15 @@ pub fn generatedThemes(b: *std.Build, io: std.Io, target: std.Build.ResolvedTarg
}
pub const TreeSitter = struct {
- mod: ?*std.Build.Module,
- queries: ?*std.Build.Step.Options,
+ mod: *std.Build.Module,
+ queries: *std.Build.Step.Options,
libs: std.ArrayList(*std.Build.Step.Compile),
/// tree-sitter, the grammars' parsers and their queries, into `m`.
pub fn wire(ts: TreeSitter, m: *std.Build.Module) void {
- if (ts.mod) |x| m.addImport("tree-sitter", x);
+ m.addImport("tree-sitter", ts.mod);
for (ts.libs.items) |lib| m.linkLibrary(lib);
- if (ts.queries) |x| m.addOptions("ts_queries", x);
+ m.addOptions("ts_queries", ts.queries);
}
};
@@ -163,61 +162,51 @@ pub const TreeSitter = struct {
/// A grammar not fetched yet is asked for and left out: the configure runs
/// again once it is there.
pub fn treeSitter(b: *std.Build, io: std.Io, target: std.Build.ResolvedTarget, c_optimize: std.lang.Optimize, tree_sitter_grammars: TreeSitterGrammars) TreeSitter {
- var ts_mod: ?*std.Build.Module = null;
- var ts_queries_opts: ?*std.Build.Step.Options = null;
+ const tree_sitter_mod = b.dependency("tree_sitter", .{ .target = target, .optimize = c_optimize }).module("tree_sitter");
var ts_libs: std.ArrayList(*std.Build.Step.Compile) = .empty;
- if (tree_sitter_grammars != .disabled) {
- const tree_sitter_mod = b.dependency("tree_sitter", .{ .target = target, .optimize = c_optimize }).module("tree_sitter");
- ts_mod = tree_sitter_mod;
+ const ts_queries = b.addOptions();
+ inline for (grammar_manifest.all) |g| {
+ if (tree_sitter_grammars == .full or (tree_sitter_grammars == .minimal and g.tier == .minimal)) grammar: {
+ const dep = b.dependencyLazy(g.dep, .{}) catch break :grammar;
+ const upstream = configureRead(b, io, dep.builder.root, g.query, 0x100000) catch @panic("read " ++ g.name ++ " highlights");
+ // the patterns that colour, filtered here once and not in
+ // every compile, and the whole query, the filter's test's
+ const query = std.mem.concat(b.allocator, u8, &.{ upstream, g.highlights_extra }) catch @panic("OOM");
+ ts_queries.addOption([]const u8, g.name ++ "_highlights_unfiltered", query);
+ ts_queries.addOption([]const u8, g.name ++ "_highlights", grammar_manifest.colorQuery(query, b.allocator.alloc(u8, query.len) catch @panic("OOM")));
+ // helix's textobject queries, vendored (vendor/queries); a
+ // grammar without one gets none
+ const objects = configureRead(b, io, b.root, "vendor/queries/" ++ g.name ++ "/textobjects.scm", 0x100000) catch "";
+ ts_queries.addOption([]const u8, g.name ++ "_textobjects", objects);
+ // and their indent queries, beside them
+ const indents = configureRead(b, io, b.root, "vendor/queries/" ++ g.name ++ "/indents.scm", 0x100000) catch "";
+ ts_queries.addOption([]const u8, g.name ++ "_indents", indents);
- const ts_queries = b.addOptions();
- inline for (grammar_manifest.all) |g| {
- if (tree_sitter_grammars == .full or
- (tree_sitter_grammars == .minimal and g.tier != .full) or
- (tree_sitter_grammars == .zig and g.tier == .zig))
- grammar: {
- const dep = b.dependencyLazy(g.dep, .{}) catch break :grammar;
- const upstream = configureRead(b, io, dep.builder.root, g.query, 0x100000) catch @panic("read " ++ g.name ++ " highlights");
- // the patterns that colour, filtered here once and not in
- // every compile, and the whole query, the filter's test's
- const query = std.mem.concat(b.allocator, u8, &.{ upstream, g.highlights_extra }) catch @panic("OOM");
- ts_queries.addOption([]const u8, g.name ++ "_highlights_unfiltered", query);
- ts_queries.addOption([]const u8, g.name ++ "_highlights", grammar_manifest.colorQuery(query, b.allocator.alloc(u8, query.len) catch @panic("OOM")));
- // helix's textobject queries, vendored (vendor/queries); a
- // grammar without one gets none
- const objects = configureRead(b, io, b.root, "vendor/queries/" ++ g.name ++ "/textobjects.scm", 0x100000) catch "";
- ts_queries.addOption([]const u8, g.name ++ "_textobjects", objects);
- // and their indent queries, beside them
- const indents = configureRead(b, io, b.root, "vendor/queries/" ++ g.name ++ "/indents.scm", 0x100000) catch "";
- ts_queries.addOption([]const u8, g.name ++ "_indents", indents);
-
- const lib = b.addLibrary(.{
- .name = "tree-sitter-" ++ g.name,
- .root_module = b.createModule(.{ .target = target, .optimize = c_optimize, .link_libc = true }),
- .linkage = .static,
- });
- // Every allocation a grammar's external scanner makes goes to the
- // runtime's allocator, which syntax.zig points at a Zig one:
- // TREE_SITTER_REUSE_ALLOCATOR for the scanners that use
- // ts_malloc, and core/tree_sitter_heap.h for the ones that call
- // malloc themselves.
- const ts_cflags = [_][]const u8{
- "-fno-sanitize=function",
- "-DTREE_SITTER_REUSE_ALLOCATOR",
- // From the compiler's working directory, the root
- // package's: pardes's own, or the one that depends on it.
- "-include",
- b.root.joinString(b.allocator, "core/tree_sitter_heap.h") catch @panic("OOM"),
- };
- 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 });
- lib.root_module.addIncludePath(dep.path(g.src));
- ts_libs.append(b.allocator, lib) catch @panic("OOM");
- }
+ const lib = b.addLibrary(.{
+ .name = "tree-sitter-" ++ g.name,
+ .root_module = b.createModule(.{ .target = target, .optimize = c_optimize, .link_libc = true }),
+ .linkage = .static,
+ });
+ // Every allocation a grammar's external scanner makes goes to the
+ // runtime's allocator, which syntax.zig points at a Zig one:
+ // TREE_SITTER_REUSE_ALLOCATOR for the scanners that use
+ // ts_malloc, and core/tree_sitter_heap.h for the ones that call
+ // malloc themselves.
+ const ts_cflags = [_][]const u8{
+ "-fno-sanitize=function",
+ "-DTREE_SITTER_REUSE_ALLOCATOR",
+ // From the compiler's working directory, the root
+ // package's: pardes's own, or the one that depends on it.
+ "-include",
+ b.root.joinString(b.allocator, "core/tree_sitter_heap.h") catch @panic("OOM"),
+ };
+ 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 });
+ lib.root_module.addIncludePath(dep.path(g.src));
+ ts_libs.append(b.allocator, lib) catch @panic("OOM");
}
- ts_queries_opts = ts_queries;
}
- return .{ .mod = ts_mod, .queries = ts_queries_opts, .libs = ts_libs };
+ return .{ .mod = tree_sitter_mod, .queries = ts_queries, .libs = ts_libs };
}
/// uucode with pardes's configuration (uucode_config.zig), which ghostty
@@ -308,8 +297,6 @@ pub const Core = struct {
platform: Platform,
/// The terminal module; without it (core-test) a shell boot is a scratch pane.
terminal: bool = true,
- /// pardes-isolate's: no host but the terminal.
- isolated: bool = false,
/// The addons compiled in and registered at start (Addon.zig): the
/// static step's, and every core off Linux, whose loader has no memfd.
builtin_addons: bool = false,
@@ -368,7 +355,7 @@ pub fn module(b: *std.Build, p: Parts, c: Core) Modules {
const root = if (!in_runtime) m else if (std.mem.eql(u8, c.root, "runtime/root.zig")) runtime else b.createModule(.{ .target = p.target, .optimize = p.optimize, .root_source_file = b.path(c.root), .link_libc = true });
// Each options module once, so that the modules share it: a file is in
// one module of a compilation.
- const ts_queries = if (p.ts.queries) |q| q.createModule() else null;
+ const ts_queries = p.ts.queries.createModule();
const doc_typ = p.doc_typ.createModule();
const pardes_options = options(b, p.cfg, c, p.pdf != null).createModule();
const build_info = p.info.createModule();
@@ -380,8 +367,8 @@ pub fn module(b: *std.Build, p: Parts, c: Core) Modules {
x.addImport("plain", p.plain);
x.addImport("pardes_addon", p.kind);
x.addImport("generated_themes", p.themes);
- if (p.ts.mod) |ts| x.addImport("tree-sitter", ts);
- if (ts_queries) |q| x.addImport("ts_queries", q);
+ x.addImport("tree-sitter", p.ts.mod);
+ x.addImport("ts_queries", ts_queries);
x.addImport("mvzr", p.mvzr);
x.addImport("c_heap", p.c_heap);
x.addImport("vaxis", p.vaxis);
diff --git a/build/library.zig b/build/library.zig
deleted file mode 100644
index 8a23debc..00000000
--- a/build/library.zig
+++ /dev/null
@@ -1,49 +0,0 @@
-const std = @import("std");
-const TreeSitterGrammars = @import("../build.zig").TreeSitterGrammars;
-const core = @import("core.zig");
-const patches = @import("patches.zig");
-
-/// pardes as a library, all a package that depends on it is given: the
-/// `pardes-syntax` module (core/lib_syntax.zig), the grammars, highlighting
-/// and themes for a program that draws source text itself. It takes
-/// tree-sitter and the grammars of its `tree-sitter` option and no other
-/// dependency, so nothing else is fetched (build.zig.zon). test/lib is such
-/// a package, which `lib-test` builds.
-pub fn build(b: *std.Build) void {
- const target = b.standardTargetOptions(.{});
- const optimize = b.standardOptimizeOption(.{});
- const tree_sitter_grammars = b.option(TreeSitterGrammars, "tree-sitter", "tree-sitter grammar set: disabled, zig, minimal (c/c++/zig), full") orelse .full;
- var threaded: std.Io.Threaded = .init(b.allocator, .{});
- defer threaded.deinit();
- const io = threaded.io();
- const mod = b.addModule("pardes-syntax", .{
- .target = target,
- .optimize = optimize,
- .root_source_file = b.path("core/lib_syntax.zig"),
- .link_libc = true,
- });
- // A library's options: its grammars, nothing stamped, no window.
- const cfg: core.ShellConfig = .{ .tree_sitter_grammars = tree_sitter_grammars };
- mod.addOptions("pardes_options", core.options(b, cfg, .{ .root = "core/lib_syntax.zig", .platform = .tui, .terminal = false }, false));
- const ts = core.treeSitter(b, io, target, if (optimize == .debug) .fast else optimize, tree_sitter_grammars);
- const themes = core.generatedThemes(b, io, target, optimize);
- mod.addImport("generated_themes", themes);
- ts.wire(mod);
- mod.addImport("c_heap", b.createModule(.{ .target = target, .optimize = optimize, .root_source_file = b.path("core/c_heap.zig") }));
- // The editor, `pardes-editor`, to a package that asks for it: uucode,
- // mvzr and vaxis (with what its build names) are fetched then and only
- // then. Of vaxis it takes the grapheme width, which uucode alone feeds.
- if (!(b.option(bool, "editor", "also export `pardes-editor`, the text pane as a library (fetches uucode, mvzr and vaxis)") orelse false)) return;
- const uucode = core.uucodeModule(b, target, optimize) orelse return;
- const mvzr = patches.mvzr(b, patches.tool(b), b.dependencyLazy("mvzr", .{ .target = target, .optimize = optimize }) catch return, target, optimize);
- const vaxis_dep = b.dependencyLazy("vaxis", .{ .target = target, .optimize = optimize, .external_uucode = true }) catch return;
- const width = b.addWriteFiles();
- _ = width.addCopyFile(vaxis_dep.path("src/gwidth.zig"), "gwidth.zig");
- const vaxis = b.createModule(.{
- .target = target,
- .optimize = optimize,
- .root_source_file = width.add("vaxis.zig", "pub const gwidth = @import(\"gwidth.zig\");\n"),
- .imports = &.{.{ .name = "uucode", .module = uucode }},
- });
- _ = core.editorModule(b, "pardes-editor", target, optimize, cfg, .{ .themes = themes, .ts = ts, .uucode = uucode, .mvzr = mvzr, .vaxis = vaxis });
-}
diff --git a/build/patches.zig b/build/patches.zig
index 7c7b2d60..7d87b9f1 100644
--- a/build/patches.zig
+++ b/build/patches.zig
@@ -34,7 +34,8 @@ fn apply(b: *std.Build, patch: *std.Build.Step.Compile, dep: *std.Build.Dependen
/// startup width queries' `CSI 1;1R` arrived as two F3s, which a shell
/// pane took for text (build/patches/vaxis_parser.zig).
/// - ESC before a CSI or SS3 key (rxvt's Alt+arrow) is Alt on that key,
-/// not Alt+Escape followed by `[A` as text.
+/// not Alt+Escape followed by `[A` as text; before anything else (a
+/// mouse report: Alt is in its button) it is the Escape key.
/// - 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.
@@ -56,7 +57,7 @@ const vaxis_parser = [_]Edit{
\\ if (inner.n == 0) return inner;
\\ if (inner.event) |*event| switch (event.*) {
\\ .key_press, .key_release => |*key| key.mods.alt = true,
- \\ else => {},
+ \\ else => return .{ .event = .{ .key_press = .{ .codepoint = Key.escape } }, .n = 1 },
\\ };
\\ inner.n += 1;
\\ return inner;
diff --git a/build/tools.zig b/build/tools.zig
index 62e9817a..a4b41dd7 100644
--- a/build/tools.zig
+++ b/build/tools.zig
@@ -250,12 +250,13 @@ pub fn add(b: *std.Build, c: struct {
if (testMatch(b, c.unit_profile, c.test_filters, syntax_test_step)) |check| check.addArtifactArg(syntax_test);
// The library as a package that depends on pardes is given it
- // (`library`): test/lib's own `zig build test`, over the packages
+ // (`library`): test/consumer's own `zig build test`, over the packages
// this checkout has fetched.
const lib_test = b.addSystemCommand(&.{ b.graph.zig_exe, "build", "test", "--pkg-dir", "../../zig-pkg" });
- lib_test.setCwd(b.path("test/lib"));
+ lib_test.setName("zig build test in test/consumer, a package that depends on pardes");
+ lib_test.setCwd(b.path("test/consumer"));
lib_test.has_side_effects = true;
- const lib_test_step = b.step("lib-test", "build and test the library from a package that depends on pardes (test/lib)");
+ const lib_test_step = b.step("lib-test", "build and test the library from a package that depends on pardes (test/consumer)");
lib_test_step.dependOn(&lib_test.step);
const history = b.addExecutable(.{
diff --git a/core/CHANGELOG.md b/core/CHANGELOG.md
index fe9adec8..faa02ade 100644
--- a/core/CHANGELOG.md
+++ b/core/CHANGELOG.md
@@ -2,6 +2,10 @@
## Unreleased
+- `pardes new --detach[=NAME]` returns once the session runs (registered
+ and listening), printing its name, exit 0; the session runs on in a
+ session of its own. `pardes --detach=NAME` without `new` is still the
+ session itself, until it ends.
- `pardes attach NAME` (and `pardes-gui attach NAME`) is always a client:
a process of its own with its own view, whatever the session was
started in. A session's own terminal or window is only the one it was
@@ -9,8 +13,9 @@
back. Before, an attach to a detached terminal's session handed it this
terminal (the attach waiting as its stub), and `pardes-gui attach` asked
a detached window's session to open its own window again and exited 0.
- A client's Detach ends it with "'NAME' let this client go" and exit 1,
- where the stub said "detached from 'NAME'" and exited 0. Bare, `pardes
+ A client's Detach ends it with "detached from 'NAME', which is still
+ running" and exit 0, as the stub's did (the session's last word on a
+ link, `left`); a session's end, with its code (`ended`). Bare, `pardes
attach` takes the one detached session, else the one session, of either
kind; with several it names them all.
@@ -232,9 +237,9 @@
grammars, highlighting, declarations, syntax tree and themes as the
editor has them, for a program that draws source text itself. Every
dependency but tree-sitter's runtime is lazy in the manifest, so such a
- package fetches the runtime and the grammars of its `tree-sitter` set
+ package fetches the runtime and the grammars of its `grammars` set
and nothing else; `zig build lib-test`, which `unit-test` runs, builds
- one (`test/lib`). The markdown grammar is pinned by its commit: its
+ one (`test/consumer`). The markdown grammar is pinned by its commit: its
branch has moved, and a fresh checkout could not fetch it.
- Enter, `o` and `O` give the new line helix's indent where the file's
@@ -590,6 +595,16 @@
- A scroll in the window never moves the tree-sitter context rows: the
body glides under them.
+- `zig build run-isolated` and its `pardes-isolate` are gone: the
+ terminal's pardes with no host but the terminal and no filesystem had
+ not compiled for some releases, and nothing ran it. So is
+ `-Dtree-sitter=disabled`, a pardes with no tree-sitter, which did not
+ compile either; every build has tree-sitter's runtime. The grammar set
+ is `-Dgrammars` (`.grammars` for a package that depends on pardes, no
+ longer `.@"tree-sitter"`): `none`, the runtime alone, where a program
+ hands in a grammar of its own at run time, `minimal` or `full`; the
+ `zig` set, which `none` replaces, is gone.
+
## 0.24
- Edit runs all of acme's commands: `< | >` through your Shell (one undo
diff --git a/core/Core.zig b/core/Core.zig
index a92d35ae..e736d43b 100644
--- a/core/Core.zig
+++ b/core/Core.zig
@@ -2074,7 +2074,7 @@ pub fn nextWake(p: *const Pardes) ?u64 {
};
// Del's question goes up at the end of its delay: a frame then, and
// none after (stepped time has reached it).
- for (p.panes) |slot| if (slot) |pane| if (pane.prompt == .del_side and pane.question_due_ns > p.clock.stepped_ns) {
+ for (p.panes) |slot| if (slot) |pane| if (pane.prompt == .del_side and pane.question_due_ns > p.clock.stepped_ns and pane.question_due_ns != Pane.question_asked) {
const wait = @max(1, (pane.question_due_ns - p.clock.stepped_ns + frame_ns - 1) / frame_ns);
frames = if (frames) |soonest| @min(soonest, wait) else wait;
};
@@ -2115,6 +2115,10 @@ fn advanceInner(p: *Pardes, now_ns: u64) void {
p.clock.started = true;
p.clock.now_ns = now_ns;
if (!started) p.clock.stepped_ns = now_ns;
+ // Del's question asked since the last advance: its delay from now.
+ for (p.panes) |slot| if (slot) |pane| if (pane.question_due_ns == Pane.question_asked) {
+ pane.question_due_ns = now_ns + config.del_question_delay_ns;
+ };
const frame = frame_ns;
var moving: u32 = 0;
// The session's ticks are the recording session's: a picture still
@@ -2274,6 +2278,15 @@ pub const Options = struct {
startup_config: ?[]const u8 = null,
ninep_name: []const u8 = "",
ninep_tcp: ?[]const u8 = null,
+ /// This process's end of a socket pair its launch made (runtime/main.zig,
+ /// PARDES_PAIR): a session's first client is on it, taken before its
+ /// first effects (runtime/session.zig); a client's session is on it,
+ /// its first join made there with no hello (replica.join).
+ pair: ?c_int = null,
+ /// A client exec'd at an Upgrade (runtime/client.zig `execAgain`,
+ /// PARDES_JOIN_VIEW): the view it had, which the session kept for it
+ /// (views.away), joined again for as a rejoin dials (replica.join).
+ join_view: ?u8 = null,
mounts: []const filesystem.Mount = &.{},
config_dir: ?[]const u8 = null,
/// Where what outlives the session is kept (Db.zig): the user's state
@@ -2503,7 +2516,6 @@ test "LocationsConfig command reports partial updates and survives restore" {
}
test "TreeContext rows in the tag style keep the message rows" {
- 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" ++ (std.mem.asBytes(&@as([30][16]u8, @splat(" // body\n".*)))) ++ " }\n};\n");
@@ -2546,7 +2558,6 @@ test "TreeContext rows in the tag style keep the message rows" {
}
test "TreeContext command and custom tag survive a workspace round trip" {
- if (comptime !syntax.enabled) return error.SkipZigTest;
const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true });
defer p.deinit();
const pane = try p.setTestFile("pub fn main() void {}\n");
diff --git a/core/Dir.zig b/core/Dir.zig
index 29c5cdc8..869a7cd5 100644
--- a/core/Dir.zig
+++ b/core/Dir.zig
@@ -47,7 +47,6 @@ pub fn ofName(name: []const u8) []const u8 {
/// dotfiles too; a directory's, a link to one's too, ending in `/`; sorted
/// bytewise, the `/` counted; each ending in a newline.
pub fn read(tape: *pardes.tape.Tape, gpa: std.mem.Allocator, dir: []const u8) ![]u8 {
- if (comptime !filesystem.platform_has_fs) return error.FileNotFound;
const local = filesystem.localPath(dir) orelse return error.NotLocal;
// Its own copy: the caller's may be a pane's, gone while the turn is out.
var own: [4096]u8 = undefined;
@@ -294,7 +293,6 @@ test "a wide character counts its cells, not its bytes" {
}
test "a directory reads as acme lists it: dotfiles kept, . and .. not, directories and links to them marked, sorted bytewise" {
- if (comptime !filesystem.platform_has_fs) return;
var tmp = testing.tmpDir(.{});
defer tmp.cleanup();
const io = testing.io;
diff --git a/core/File.zig b/core/File.zig
index 325abee9..ceb6d03b 100644
--- a/core/File.zig
+++ b/core/File.zig
@@ -2312,7 +2312,6 @@ test "a pager's text is a diff when it holds a diff header or a unified hunk" {
}
test "a long line is painted only around the caret" {
- if (!syntax.enabled) return;
const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 80, .rows = 24 });
defer p.deinit();
const line = try std.testing.allocator.alloc(u8, 600 << 10);
@@ -2357,6 +2356,20 @@ test "a caret deep in a long line scrolls the view sideways to it, measured from
try std.testing.expectEqual(@as(i32, 0), pane.hscroll);
}
+test "a caret left of a view scrolled sideways is not drawn in the gutter" {
+ const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 80, .rows = 24 });
+ defer p.deinit();
+ p.settings.wrap = false;
+ const pane = try p.setTestFile("short1 END_A_MARKER_WAY_OUT_RIGHT_padpadpadpadpadpadpadpadpadpadpad_TAIL\n");
+ var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);
+ defer arena.deinit();
+ try std.testing.expect((try p.render(arena.allocator())).cursor != null);
+ // One wheel notch (4 columns) of the 7 the gutter is: the caret, at
+ // column 0, was drawn 3 columns into the gutter.
+ pane.hscroll = 4;
+ try std.testing.expect((try p.render(arena.allocator())).cursor == null);
+}
+
test "undo and redo walk back and forth through every step of random edits, joined entries and all" {
const gpa = std.testing.allocator;
const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24 });
diff --git a/core/Output.zig b/core/Output.zig
index 759bada9..c7bfde14 100644
--- a/core/Output.zig
+++ b/core/Output.zig
@@ -907,7 +907,7 @@ pub fn openBuild(p: *Pardes, id: usize) !void {
@tagName(builtin.abi), @tagName(build_options.platform),
});
try w.print("grammars {s}\naddons {s}\nsemantics {x:0>16}\n\ndependencies\n{s}", .{
- if (build_options.grammars == .full) "full" else if (build_options.grammars == .minimal) "minimal" else "none",
+ @tagName(build_options.grammars),
if (build_options.builtin_addons) "compiled in" else "loaded from <prefix>/lib/pardes/addons",
@import("wire").semantics,
build_info.deps,
diff --git a/core/Plumb.zig b/core/Plumb.zig
index aeebfc64..f51ddace 100644
--- a/core/Plumb.zig
+++ b/core/Plumb.zig
@@ -1314,7 +1314,6 @@ test "plumb: a set rewrites the message for good, attr delete of one absent fail
}
test "plumb: isfile and isdir find a name as Look does, past its place, in the message's directory then Incl's; $file is where" {
- if (!fs.platform_has_fs) return;
var tmp = testing.tmpDir(.{});
defer tmp.cleanup();
try tmp.dir.writeFile(testing.io, .{ .sub_path = "it.zig", .data = "x\n" });
@@ -1482,7 +1481,6 @@ test "plumb: plan9port's basic parses, its ¡-￿ classes UTF-8's bytes and its
}
test "plumb: the Plumb word opens the plumbing file, include basic until one is saved; saved, or read at boot, its rules are in force, a bad one said with its line" {
- if (!fs.platform_has_fs) return;
var tmp = testing.tmpDir(.{});
defer tmp.cleanup();
var dir_buf: [4096]u8 = undefined;
diff --git a/core/Query.zig b/core/Query.zig
index 704206e6..ebb44155 100644
--- a/core/Query.zig
+++ b/core/Query.zig
@@ -2294,7 +2294,6 @@ fn settle(p: *Pardes) void {
}
test "Find: names fuzzy per keystroke, the group born with its +Preview, nothing else moves, Enter promotes the preview in place" {
- if (!filesystem.platform_has_fs) return;
var tmp = std.testing.tmpDir(.{});
defer tmp.cleanup();
try tmp.dir.createDirPath(std.testing.io, "src");
@@ -2346,7 +2345,6 @@ test "Find: names fuzzy per keystroke, the group born with its +Preview, nothing
}
test "Grep: lines of the files under the owner's directory, under their file; All: every pane's, under @pN in serial order, a line once" {
- if (!filesystem.platform_has_fs) return;
var tmp = std.testing.tmpDir(.{});
defer tmp.cleanup();
try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "b.zig", .data = "const needle = 1;\nconst hay = 2;\nneedle needle\n" });
@@ -2568,7 +2566,6 @@ test "Enter on a frozen query pane's rows after its text was edited: no row to l
}
test "a query row's place is its text: the match tinted after it, B3 on it opens the place, the rows saved and read again still Look" {
- if (!filesystem.platform_has_fs) return;
var tmp = std.testing.tmpDir(.{});
defer tmp.cleanup();
const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 120, .rows = 48 });
@@ -2627,7 +2624,6 @@ test "a query row's place is its text: the match tinted after it, B3 on it opens
}
test "the +Preview: the query's hits in its file are its places, the row's one current and selected, coloured as the file is" {
- if (!filesystem.platform_has_fs) return;
var tmp = std.testing.tmpDir(.{});
defer tmp.cleanup();
const text = "const needle = 1;\nconst hay = 2;\nfn f() void {\n _ = needle;\n}\npub const needle_too = needle;\n";
@@ -2662,7 +2658,6 @@ test "the +Preview: the query's hits in its file are its places, the row's one c
sel = pv.body.primaryRange(pv.file.?.content, 0);
try std.testing.expectEqual(expected.items[2].start, @min(sel.anchor, sel.head));
// its colours the file's, as its own pane paints them
- if (!syntax.enabled) return;
var frame = std.heap.ArenaAllocator.init(std.testing.allocator);
defer frame.deinit();
_ = try p.render(frame.allocator());
@@ -2674,7 +2669,6 @@ test "the +Preview: the query's hits in its file are its places, the row's one c
}
test "a row's address is the shortest path a Look from the query pane resolves: in its directory, under it, above it, else absolute" {
- if (!filesystem.platform_has_fs) return;
if (!pardes.lsp.supports.contains(.references)) return;
var tmp = std.testing.tmpDir(.{});
defer tmp.cleanup();
@@ -2716,7 +2710,6 @@ test "a row's address is the shortest path a Look from the query pane resolves:
}
test "a query row's address reaches every way a look arrives: an empty look written back to event and the whole row written to look, as the mouse on it" {
- if (!filesystem.platform_has_fs) return;
var tmp = std.testing.tmpDir(.{});
defer tmp.cleanup();
const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 120, .rows = 48 });
diff --git a/core/Stream.zig b/core/Stream.zig
index 6f99b504..1f4a7405 100644
--- a/core/Stream.zig
+++ b/core/Stream.zig
@@ -478,7 +478,6 @@ fn parseWork(io: std.Io, job: *TextJob, ctx: ?*anyopaque, sink: Sink) void {
}
fn now() u64 {
- if (comptime !filesystem.platform_has_fs) return 0;
const t = std.Io.Clock.awake.now(std.Io.Threaded.global_single_threaded.io());
return @intCast(@max(0, t.nanoseconds));
}
@@ -635,10 +634,6 @@ pub fn runHere(p: *Pardes, gen: u32, comptime in_call: bool) void {
};
return;
}
- if (comptime !filesystem.platform_has_fs) {
- p.stream.state = .failed;
- return;
- }
const s = &p.stream;
if (gen != s.gen or s.state != .searching) return;
const job = makeJob(p.gpa, s) catch |err| {
@@ -1163,7 +1158,6 @@ const Rogue = struct {
};
test "Stream: a stale generation's rows never land in the query pane, however two generations race (walk and rg)" {
- if (comptime !filesystem.platform_has_fs) return;
var tmp = testing.tmpDir(.{});
defer tmp.cleanup();
var root_buf: [4096]u8 = undefined;
@@ -1243,7 +1237,6 @@ test "Stream: a stale generation's rows never land in the query pane, however tw
}
test "Stream: the listing of files for Find on a worker, a cap of hits stops the walk on the loop" {
- if (comptime !filesystem.platform_has_fs) return;
var tmp = testing.tmpDir(.{});
defer tmp.cleanup();
var root_buf: [4096]u8 = undefined;
@@ -1273,7 +1266,6 @@ test "Stream: the listing of files for Find on a worker, a cap of hits stops the
}
test "Stream: a big text's declarations are parsed on a worker, never the loop, and the rows of its / regroup under them" {
- if (comptime !filesystem.platform_has_fs) return;
const p = try Pardes.init(testing.allocator, .{ .tty_only = true, .cols = 120, .rows = 40 });
defer p.deinit();
var text: std.ArrayList(u8) = .empty;
@@ -1312,7 +1304,6 @@ test "Stream: a big text's declarations are parsed on a worker, never the loop,
}
test "Stream: a scroll's colours are painted ahead on a worker, so PageDown after PageDown parses nothing on the frame" {
- if (comptime !filesystem.platform_has_fs or !syntax.enabled) return;
const p = try Pardes.init(testing.allocator, .{ .tty_only = true, .cols = 120, .rows = 40 });
defer p.deinit();
var text: std.ArrayList(u8) = .empty;
@@ -1355,7 +1346,6 @@ test "Stream: a scroll's colours are painted ahead on a worker, so PageDown afte
}
test "Stream: a Grep stops at its 2000 lines and waits; More in the query pane's tag goes on" {
- if (comptime !filesystem.platform_has_fs) return;
var tmp = testing.tmpDir(.{});
defer tmp.cleanup();
var root_buf: [4096]u8 = undefined;
@@ -1404,8 +1394,7 @@ test "Stream: a Grep stops at its 2000 lines and waits; More in the query pane's
}
test "Stream: a Grep's rows recoloured are made again, never written, and a dump of them dropped by an edit loads to its digest" {
- if (comptime !filesystem.platform_has_fs) return;
- if (!syntax.enabled or !syntax.readyApart("c.zig")) return;
+ if (!syntax.readyApart("c.zig")) return;
var tmp = testing.tmpDir(.{});
defer tmp.cleanup();
// Rows enough that a digest keeps a word for them (walk's blob_min).
@@ -1476,8 +1465,7 @@ test "Stream: a Grep's rows recoloured are made again, never written, and a dump
}
test "Stream: a Grep's rows are coloured as their file's language colours them, the file painted on a worker, the match tint on top" {
- if (comptime !filesystem.platform_has_fs) return;
- if (!syntax.enabled or !syntax.readyApart("c.zig")) return;
+ if (!syntax.readyApart("c.zig")) return;
var tmp = testing.tmpDir(.{});
defer tmp.cleanup();
const text = "const std = @import(\"std\");\npub fn value() u32 {\n return 42; // value\n}\n";
diff --git a/core/body_layer.zig b/core/body_layer.zig
index 7dc097ad..1582136c 100644
--- a/core/body_layer.zig
+++ b/core/body_layer.zig
@@ -512,7 +512,10 @@ pub fn renderBody(p: *Pardes, s: *Surface, arena: std.mem.Allocator, pane: *Pane
)
else
ccol;
- if (prow >= pane.tag_rows and cx >= 0 and prow < body_bottom and cx < tw)
+ // Left of a view scrolled sideways it is off the view, not
+ // in the gutter.
+ const left: i32 = if (pane.file != null) panes.File.gutterWidth(pane) else 0;
+ if (prow >= pane.tag_rows and cx >= left and prow < body_bottom and cx < tw)
s.cursor = .{ .x = tx + @as(u16, @intCast(cx)), .y = body_y + @as(u16, @intCast(prow - pane.tag_rows)), .bar = pane.body.mode == .insert };
}
} else if (pane.terminal != null) visible: {
diff --git a/core/builtins.zig b/core/builtins.zig
index 39c06206..894478fd 100644
--- a/core/builtins.zig
+++ b/core/builtins.zig
@@ -698,11 +698,9 @@ pub const Fonts = struct {
/// Show the declarations enclosing the top row at the pane's head, on or off.
pub const TreeContext = struct {
- pub const enabled = pardes.syntax.enabled;
pub const takes_arg = true;
pub fn run(c: Ctx) void {
- if (comptime !enabled) unreachable;
if (!panes.File.supportsContext(c.pane)) return c.p.reportFailure(c.id, "TreeContext: only a source file the parser knows has context");
const file = &c.pane.file.?;
const arg = std.mem.trim(u8, c.arg orelse "", " \t\r\n");
@@ -1042,7 +1040,7 @@ pub const Del = struct {
!c.pane.collapsed and c.pane.prompt == .none)
{
c.pane.prompt = .del_side;
- c.pane.question_due_ns = exec.clockNow(c.p) + config.del_question_delay_ns;
+ c.pane.question_due_ns = Pane.question_asked;
c.p.view().active = c.id;
var rec: [32]u8 = undefined;
pardes.ctlfs.events.notePath(c.p, "ask", std.fmt.bufPrint(&rec, "{d} del k j", .{c.pane.serial}) catch unreachable); // a u32 fits 32
diff --git a/core/config.zig b/core/config.zig
index 3dbfe566..f43604ad 100644
--- a/core/config.zig
+++ b/core/config.zig
@@ -159,7 +159,7 @@ pub const leader_path = paths: {
if (builtins.capabilities.pixels) table.set(.GripWidth, null);
table.set(.InactiveDim, null);
if (builtins.capabilities.pixels) table.set(.Pet, null);
- if (builtins.TreeContext.enabled) table.set(.TreeContext, null);
+ table.set(.TreeContext, null);
table.set(.ThemeFile, null);
table.set(.DumpThemes, null);
table.set(.Mount, null);
diff --git a/core/draw.zig b/core/draw.zig
index 5ff31af6..b87eb56f 100644
--- a/core/draw.zig
+++ b/core/draw.zig
@@ -1295,7 +1295,6 @@ test "a wide glyph cut by a tag's or a notice's edge is joined into the grid as
}
test "a body with context rows is painted once, and the grid's rows are what a plain paint of it gives" {
- 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" ++ (std.mem.asBytes(&@as([30][21]u8, @splat(" // body line\n".*)))) ++ " }\n};\n");
diff --git a/core/dump.zig b/core/dump.zig
index 3d248010..7ce54bce 100644
--- a/core/dump.zig
+++ b/core/dump.zig
@@ -11,7 +11,6 @@ const exec = @import("exec.zig");
const colors = @import("colors.zig");
const config = @import("config.zig");
const platform = pardes.platform;
-const isolated = pardes.isolated;
const MAX_PANES = pardes.MAX_PANES;
const MAX_COLS = pardes.MAX_COLS;
const effect_path_cap = pardes.effect_path_cap;
@@ -665,13 +664,11 @@ fn revivePane(p: *Pardes, id: usize, pane: *pardes.panes.Pane, was_on_disk: bool
if (pane.terminal != null) {
// A command pane comes back finished, showing what it said: its
// command is not run again. A host that runs shells starts one
- // under the history in the old one's directory; an isolated build
- // only shows it.
+ // under the history in the old one's directory.
if (pane.command != null) {
pane.command_done = true;
return;
}
- if (comptime isolated) return;
if (pane.cwdSlice().len > effect_path_cap) return;
// Its shell not there, made ready for a new one: what the old
// shell was, ran and said is gone with it (the REPL it ran, the
@@ -1063,7 +1060,6 @@ test "a pane restored with unsaved text is asked about by Exit, Restore, Del and
test "a loaded terminal's history stays above its banner, the cursor where it was" {
if (pardes.Term.ops == null) return error.SkipZigTest; // it reads the emulator
- if (comptime isolated) return error.SkipZigTest;
const gpa = std.testing.allocator;
const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 40, .rows = 12 });
defer p.deinit();
@@ -1085,7 +1081,6 @@ test "a loaded terminal's history stays above its banner, the cursor where it wa
test "an upgraded session's dump keeps its views and its running terminal as they were, and settings the startup config would change" {
if (pardes.Term.ops == null) return error.SkipZigTest; // a shell, dumped and loaded
- if (comptime isolated) return error.SkipZigTest;
const gpa = std.testing.allocator;
const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 40, .rows = 12, .startup_config = "Verbose off\n" });
defer p.deinit();
diff --git a/core/edit_cmd.zig b/core/edit_cmd.zig
index 9f1f7862..9a5c6865 100644
--- a/core/edit_cmd.zig
+++ b/core/edit_cmd.zig
@@ -610,7 +610,6 @@ test "an Edit whose file is edited while its commands run is refused whole" {
}
test "X over open files, w, e, r, f, B and D on panes and the disk" {
- if (comptime !filesystem.platform_has_fs) return error.SkipZigTest;
const gpa = testing.allocator;
var tmp = testing.tmpDir(.{});
defer tmp.cleanup();
@@ -687,7 +686,6 @@ test "X over open files, w, e, r, f, B and D on panes and the disk" {
}
test "an Edit's w to a file changed on disk is refused once, as Save is, and the others are written" {
- if (comptime !filesystem.platform_has_fs) return error.SkipZigTest;
var tmp = testing.tmpDir(.{});
defer tmp.cleanup();
try tmp.dir.writeFile(testing.io, .{ .sub_path = "a.txt", .data = "a\n" });
@@ -723,7 +721,6 @@ test "an Edit's w to a file changed on disk is refused once, as Save is, and the
}
test "an Edit with no command runs beside one whose commands run, unless it touches what that one changes" {
- if (comptime !filesystem.platform_has_fs) return error.SkipZigTest;
var tmp = testing.tmpDir(.{});
defer tmp.cleanup();
try tmp.dir.writeFile(testing.io, .{ .sub_path = "other.txt", .data = "x\n" });
@@ -784,7 +781,6 @@ test "a session that ends while an Edit's commands run lets the Edit go" {
}
test "e and r say a file that cannot be read as Get says it" {
- if (comptime !filesystem.platform_has_fs) return error.SkipZigTest;
const p = try th.withFile(testing.allocator, "x\n");
defer p.deinit();
const ctl = tree.Node.of(th.serialOf(p), .ctl);
diff --git a/core/exec.zig b/core/exec.zig
index 74037db0..18b519ff 100644
--- a/core/exec.zig
+++ b/core/exec.zig
@@ -708,7 +708,7 @@ pub fn executeFrom(p: *Pardes, id: usize, txt: []const u8, from_body: bool) ?usi
const pad = std.math.clamp(max_row - cursor_abs, 0, @as(i32, pane.rows));
for (0..@intCast(pad)) |_| p.emitWrite(id, "\r");
};
- pane.noteCommand(cmd);
+ pane.noteCommand(cmd, panes.Term.prompt(pane.terminal).started);
if (pane.queuePendingCommand(cmd) catch |err| {
p.reportError(.at(id), "queue command", err);
return id;
diff --git a/core/fs.zig b/core/fs.zig
index 0797beb0..6e5829e1 100644
--- a/core/fs.zig
+++ b/core/fs.zig
@@ -163,7 +163,6 @@ fn osNode(p: *pardes.Pardes, path: []const u8) !u64 {
/// outlives the yield, and nothing is staged into the shared reply buffer
/// until the turn is back.
pub fn osHandle(p: *pardes.Pardes, req: Req) Reply {
- if (comptime !platform_has_fs) return Reply.fail(req.tag, E.NOENT);
const path = osPath(p, req.node) orelse return Reply.fail(req.tag, E.NOENT);
if (req.op == .release) return .{ .tag = req.tag };
const stat = p.tape.site(.os_stat, null, osStat, .{path}) catch return Reply.fail(req.tag, E.NOENT);
@@ -307,7 +306,6 @@ pub fn statPath(io: std.Io, path: []const u8, options: std.Io.Dir.StatFileOption
/// does: one already there is no failure. A failure shows at the open
/// that follows.
pub fn makeDirs(tape: *pardes.tape.Tape, dir: []const u8) void {
- if (comptime !platform_has_fs) return;
if (dir.len == 0) return;
tape.site(.make_dirs, null, makeDirsHost, .{dir});
}
@@ -320,7 +318,6 @@ fn makeDirsHost(io: std.Io, dir: []const u8) void {
/// 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.Io.Dir.path.dirname(d)) {
var z: [4096]u8 = undefined;
@@ -443,7 +440,6 @@ fn userHome(name: []const u8) ?[]const u8 {
}
pub fn resolveOs(tape: *pardes.tape.Tape, path: []const u8, out: *[4096]u8) ?Resolved {
- if (comptime !platform_has_fs) return null;
var z: [4096]u8 = undefined;
const path_z = std.fmt.bufPrintSentinel(&z, "{s}", .{path}, 0) catch return null;
return tape.site(.resolve, null, resolveHost, .{ path_z, out });
@@ -676,8 +672,6 @@ fn findEmbeddedSource(path: []const u8, allow_root_suffix: bool) ?Source {
return null;
}
-pub const platform_has_fs = !pardes.isolated;
-
fn isDir(path: [*:0]const u8) bool {
const fd = libc.open(path, .{ .ACCMODE = .RDONLY, .DIRECTORY = true, .CLOEXEC = true });
if (fd < 0) return false;
@@ -719,8 +713,8 @@ pub fn restorePath(tape: *pardes.tape.Tape, typed: []const u8, dir_setting: []co
fn readFileLimit(tape: *pardes.tape.Tape, gpa: std.mem.Allocator, path: []const u8, limit: usize) ![]u8 {
if (std.mem.indexOfScalar(u8, path, 0) != null) return error.OpenFailed;
- if (!platform_has_fs or std.mem.startsWith(u8, path, "/virtual/")) {
- const archive_path = if (std.mem.startsWith(u8, path, "/virtual/")) path[9..] else path;
+ if (std.mem.startsWith(u8, path, "/virtual/")) {
+ const archive_path = path[9..];
var normalized_buf: [4096]u8 = undefined;
const normalized = normalizeVirtualPath(archive_path, &normalized_buf) orelse return error.OpenFailed;
const source = findEmbeddedSource(normalized, true) orelse return error.OpenFailed;
@@ -1215,7 +1209,6 @@ test "self files share the regular file limit without preallocating it" {
}
test "bounded reads accept exact OS file lengths and empty files" {
- if (!platform_has_fs) return error.SkipZigTest;
const gpa = std.testing.allocator;
const p = try Pardes.init(gpa, .{ .tty_only = true });
defer p.deinit();
@@ -1327,7 +1320,7 @@ test "bounded reads release terminal snapshots after success and size refusal" {
}
test "bounded reads probe size-unknown proc files at the exact limit" {
- if (!platform_has_fs or @import("builtin").os.tag != .linux) return error.SkipZigTest;
+ if (@import("builtin").os.tag != .linux) return error.SkipZigTest;
const gpa = std.testing.allocator;
const p = try Pardes.init(gpa, .{ .tty_only = true });
defer p.deinit();
@@ -1379,7 +1372,6 @@ test "self file reads release partial allocations when memory runs out" {
}
test "oversized OS files fail before allocating their contents" {
- if (!platform_has_fs) return error.SkipZigTest;
var tmp = std.testing.tmpDir(.{});
defer tmp.cleanup();
const file = try tmp.dir.createFile(std.testing.io, "oversized", .{});
@@ -1481,7 +1473,6 @@ test "a leading ~ is home, from HOME or else the passwd entry" {
}
test "Restore prefers default directory then falls back to original path" {
- if (!platform_has_fs) return error.SkipZigTest;
const gpa = std.testing.allocator;
var tmp = std.testing.tmpDir(.{});
defer tmp.cleanup();
diff --git a/core/grammar_manifest.zig b/core/grammar_manifest.zig
index 711c31a4..b4ff30b9 100644
--- a/core/grammar_manifest.zig
+++ b/core/grammar_manifest.zig
@@ -5,7 +5,7 @@
const std = @import("std");
-pub const Tier = enum { zig, minimal, full };
+pub const Tier = enum { minimal, full };
pub const Grammar = struct {
name: []const u8,
@@ -58,7 +58,7 @@ pub const all = [_]Grammar{
\\"#" @keyword
\\
},
- .{ .name = "zig", .dep = "ts_zig", .exts = &.{ ".zig", ".zon" }, .tier = .zig },
+ .{ .name = "zig", .dep = "ts_zig", .exts = &.{ ".zig", ".zon" }, .tier = .minimal },
};
/// The names a language goes by besides its grammar's: a fence's `py`,
diff --git a/core/keys.zig b/core/keys.zig
index 72e3bb3b..8bfe8315 100644
--- a/core/keys.zig
+++ b/core/keys.zig
@@ -717,6 +717,9 @@ test "the Del question shows only once its delay is up: a quick SPC d j never se
p.update(.{ .key = .{ .cp = 'd' } });
const pane = p.panes[mid].?;
try std.testing.expectEqual(Pane.Prompt.del_side, pane.prompt);
+ // Its time is the next advance's (the host's clock, in its pump).
+ try std.testing.expectEqual(Pane.question_asked, pane.question_due_ns);
+ p.advance(asked_at);
try std.testing.expectEqual(asked_at + config.del_question_delay_ns, pane.question_due_ns);
// Asked, and nothing on the band yet.
_ = try p.render(frame.allocator());
diff --git a/core/lib_syntax.zig b/core/lib_syntax.zig
index a25af884..f4f85820 100644
--- a/core/lib_syntax.zig
+++ b/core/lib_syntax.zig
@@ -4,7 +4,7 @@
//! coloured as pardes has it. Nothing is copied here: these are the editor's
//! own grammars and highlighting (syntax.zig), themes (colors.zig) and line
//! arithmetic (modal.zig), under the names they have there. Whatever is
-//! named here compiles with tree-sitter and the grammars alone; test/lib
+//! named here compiles with tree-sitter and the grammars alone; test/consumer
//! imports it as such a package and holds it to that.
//!
//! A language is told by a path's extension, as in the editor; `pathFor`
@@ -15,7 +15,7 @@ const colors = @import("colors.zig");
const modal = @import("modal.zig");
/// Every grammar pardes knows (`all`), by name or alias (`byName`) and by
-/// path (`byPath`). The build's `tree-sitter` option says which of them are
+/// path (`byPath`). The build's `grammars` option says which of them are
/// compiled in, and `supportsPath` answers for this build.
pub const grammars = @import("grammar_manifest.zig");
pub const supportsPath = syntax.supportsPath;
diff --git a/core/look.zig b/core/look.zig
index 1023a532..1d296775 100644
--- a/core/look.zig
+++ b/core/look.zig
@@ -7,7 +7,6 @@ const exec = @import("exec.zig");
const Plumb = @import("Plumb.zig");
const config = @import("config.zig");
const diff = @import("diff.zig");
-const platform_has_fs = filesystem.platform_has_fs;
const layout = @import("layout.zig");
const modal = @import("modal.zig");
const tagline = @import("tagline.zig");
@@ -1758,7 +1757,6 @@ test "parsePathLine: `end` separates a whole-token target from a lenient read" {
}
test "lookableSpan peels prose punctuation off a path, largest first" {
- if (!platform_has_fs) return;
var realbuf: [4096]u8 = undefined;
try std.testing.expectEqualDeep(
@as(?Span, .{ .start = 0, .end = "core/look.zig".len }),
@@ -1782,7 +1780,6 @@ test "lookableSpan peels prose punctuation off a path, largest first" {
}
test "lookableLineSpan takes the row's location and stops before its text" {
- if (!platform_has_fs) return;
var realbuf: [4096]u8 = undefined;
try std.testing.expectEqualDeep(
@as(?Span, .{ .start = 0, .end = "core/look.zig:12:5-9".len }),
@@ -1813,7 +1810,6 @@ test "lookableLineSpan takes the row's location and stops before its text" {
}
test "lookableLineSpan prefers the longest run, so a blank inside a path is one span" {
- if (!platform_has_fs) return;
var realbuf: [4096]u8 = undefined;
const io = std.testing.io;
var tmp = std.testing.tmpDir(.{});
@@ -2054,7 +2050,6 @@ test "a pointer resting where a look-hover found nothing does not wake the core
}
test "Look on each kind of diff line opens the new file at the line it names" {
- if (!platform_has_fs) return;
const numbered = "line 1\nline 2\nline 3\nline 4\nline 5\nline 6\nline 7\nline 8\nline 9\n" ++
"line 10\nline 11\nline 12\nline 13\nline 14\nline 15\n";
const diff_text =
@@ -2116,7 +2111,6 @@ test "Look on each kind of diff line opens the new file at the line it names" {
}
test "Look on plain diff -u output: names as written, timestamps cut, next to the diff" {
- if (!platform_has_fs) return;
const diff_text = "--- old/x.zig\t2026-09-30 10:00:00.000000000 +0000\n" ++
"+++ new/x.zig\t2026-09-30 11:00:00.000000000 +0000\n" ++
"@@ -1,2 +1,3 @@\n" ++
@@ -2136,7 +2130,6 @@ test "Look on plain diff -u output: names as written, timestamps cut, next to th
}
test "Look on a diff: headers and a hunk line's prefix are the whole line, hover and click alike" {
- if (!platform_has_fs) return;
const numbered = "one\ntwo\nthree\nfour\nfive\nsix\n";
const diff_text =
\\diff --git a/src/old.zig b/src/new.zig
@@ -2223,7 +2216,6 @@ test "Look on a diff: headers and a hunk line's prefix are the whole line, hover
}
test "a click, a 9P whole-line look and an empty event write-back take one expansion on every kind of diff line, a blank context line too" {
- if (!platform_has_fs) return;
const diff_text =
\\diff --git a/src/new.zig b/src/new.zig
\\--- a/src/new.zig
@@ -2286,7 +2278,6 @@ test "a click, a 9P whole-line look and an empty event write-back take one expan
}
test "every entry point to Look takes one expansion: a diff line and a file:12:5: line land in one place by each" {
- if (!platform_has_fs) return;
const numbered = "l1\nl2\nl3\nl4\nl5\nl6\nl7\nl8\nl9\nl10\nl11\nline 12 here\nl13\n";
const diff_text =
\\diff --git a/src/x.zig b/src/x.zig
@@ -2378,7 +2369,6 @@ test "every entry point to Look takes one expansion: a diff line and a file:12:5
}
test "a tag word looked at by a click and by Enter is one record to an event reader; an exec on a diff line takes its word, never the address" {
- if (!platform_has_fs) return;
const diff_text =
\\diff --git a/src/x.zig b/src/x.zig
\\--- a/src/x.zig
@@ -2449,7 +2439,6 @@ test "a tag word looked at by a click and by Enter is one record to an event rea
}
test "Incl's directories find a name found nowhere else, <name> too; bare Incl lists them, Incl - empties them, and a dump keeps them" {
- if (!platform_has_fs) return;
var tmp = std.testing.tmpDir(.{});
defer tmp.cleanup();
try tmp.dir.createDirPath(std.testing.io, "inc");
@@ -2489,7 +2478,6 @@ test "Incl's directories find a name found nowhere else, <name> too; bare Incl l
test "LookNext in a command pane walks its own file:line places, whoever walked last" {
if (pardes.Term.ops == null) return error.SkipZigTest; // a command pane
- if (!platform_has_fs) return;
var tmp = std.testing.tmpDir(.{});
defer tmp.cleanup();
try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "x.c", .data = "a\nb\nc\n" });
@@ -2546,7 +2534,6 @@ test "Look outside a diff pane expands and looks as ever" {
}
test "Look on a diff under each git prefix opens the repository's file, and a real a/ directory under --no-prefix" {
- if (!platform_has_fs) return;
const Case = struct { text: []const u8, file: []const u8 };
const cases = [_]Case{
.{ .text = "diff --git a/src/x.zig b/src/x.zig\n--- a/src/x.zig\n+++ b/src/x.zig\n@@ -1,2 +1,2 @@\n-one\n+uno\n two\n", .file = "/src/x.zig" },
@@ -2573,7 +2560,6 @@ test "Look on a diff under each git prefix opens the repository's file, and a re
}
test "Look on a diff line is the look of the address it names, selected by hand: a cached patch, the checkout elsewhere" {
- if (!platform_has_fs) return;
const io = std.testing.io;
const patch = "diff --git a/entry/src/entry.rs b/entry/src/entry.rs\n--- a/entry/src/entry.rs\n+++ b/entry/src/entry.rs\n" ++
"@@ -1,2 +1,2 @@\n-fn old() {}\n+fn new() {}\n fn kept() {}\n";
@@ -2635,7 +2621,6 @@ test "Look on a diff line is the look of the address it names, selected by hand:
}
test "Plumb: a look sends what it looks at, the rules written first: a rule's word or port takes it, a name open in a pane is focused unsent, one nothing takes is Look's own" {
- if (!platform_has_fs) return;
var tmp = std.testing.tmpDir(.{});
defer tmp.cleanup();
try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "pic.svg", .data = "<svg/>" });
@@ -2687,7 +2672,6 @@ test "Plumb: a look sends what it looks at, the rules written first: a rule's wo
test "Plumb: a commit hash looked at in a git work tree is git show's, paged; outside one Diff declines, and the word is searched for" {
if (pardes.Term.ops == null) return error.SkipZigTest; // a command pane
- if (!platform_has_fs) return;
var tmp = std.testing.tmpDir(.{});
defer tmp.cleanup();
try tmp.dir.createDir(std.testing.io, ".git", .default_dir);
diff --git a/core/mouse.zig b/core/mouse.zig
index 1882b691..465d8a01 100644
--- a/core/mouse.zig
+++ b/core/mouse.zig
@@ -1819,7 +1819,6 @@ test "a press on a notice's chip is the same state whichever frame this process
// The same through a body hit (edit.pointerTextSelection, a sweep's drag),
// on a compact body layer (TreeContext), which a pixel shell inverts.
test "a body press, drag and release are the same state whichever frame this process drew last" {
- if (comptime !pardes.syntax.enabled) return error.SkipZigTest;
const gpa = std.testing.allocator;
const a = try Pardes.init(gpa, .{ .tty_only = true, .cols = 60, .rows = 16 });
defer a.deinit();
diff --git a/core/ninep/pty.zig b/core/ninep/pty.zig
index 938f3366..4b0cee66 100644
--- a/core/ninep/pty.zig
+++ b/core/ninep/pty.zig
@@ -220,7 +220,7 @@ pub fn writeRun(p: *Pardes, req: Req, id: usize, pane: *Pane) Reply {
for (line) |c| if (c < ' ' and c != '\t') return tree.failText(req.tag, E.INVAL, e_bad_line);
const pf = &pane.fs;
if (pane.terminal == null) return tree.failText(req.tag, E.INVAL, e_bad_line);
- const marks = pardes.Term.prompt(pane.terminal);
+ const marks = marksOf(pane);
if (pane.shell_failed) {
// Its shell never started: no prompt is coming to wait for.
answer(p, slot, "error shell gone", .{});
@@ -288,7 +288,7 @@ pub fn noteMarks(p: *Pardes, id: usize, pane: *Pane) void {
if (pane.terminal == null) return;
const pf = &pane.fs;
const slot = waitingRun(p, pane) orelse return;
- const marks = pardes.Term.prompt(pane.terminal);
+ const marks = marksOf(pane);
if (slot.phase == .waiting) {
if (pf.unmarked) {
answer(p, slot, "error no prompt marks", .{});
@@ -305,7 +305,7 @@ pub fn noteMarks(p: *Pardes, id: usize, pane: *Pane) void {
if (pardes.Term.modes(pane.terminal).alternate) pane.feedOutput(p, "\x1b[?1049l");
p.emitWrite(id, slot.line);
p.emitWrite(id, "\r");
- pane.noteCommand(slot.line);
+ pane.noteCommand(slot.line, marks.started);
// The run is the shell's first command: a greeting `ls` typed at the
// same prompt would run after it, and its C would be taken for ours.
pane.greet = false;
@@ -360,6 +360,14 @@ pub fn noteMarks(p: *Pardes, id: usize, pane: *Pane) void {
finish(p, slot, pane, done.status);
}
+/// The shell's marks as the session's emulator has them (taped), as a
+/// run's step reads them: a screen-state replica's emulator is the last
+/// delta's, which comes at a frame and can be a unit behind the one it
+/// replays.
+fn marksOf(pane: *const Pane) pardes.Term.Prompt {
+ return pardes.tape.value(.prompt, pardes.Term.prompt, .{pane.terminal});
+}
+
/// Answers a run whose command ended with `status`: the header and the
/// output it printed.
fn finish(p: *Pardes, slot: *Run, pane: *Pane, status_code: ?i32) void {
diff --git a/core/ninep/tree.zig b/core/ninep/tree.zig
index 46a4e3d2..1eaaa8cb 100644
--- a/core/ninep/tree.zig
+++ b/core/ninep/tree.zig
@@ -928,9 +928,11 @@ fn open(p: *Pardes, req: Req, target: Target) Reply {
};
},
};
- const i = for (p.fs.opens, 0..) |o, i| {
- if (o.node == 0) break i;
- } else return Reply.fail(req.tag, E.NFILE);
+ // The handle every later request of this open names: the session's 9P
+ // server's, told to a replica as the answer it was. A client joined
+ // since holds none of the opens made before it, and its first free
+ // record would be another than the session's.
+ const i = p.tape.authority(freeOpen, .{p}) orelse return Reply.fail(req.tag, E.NFILE);
const o = &p.fs.opens[i];
o.* = .{ .node = req.node, .what = what };
if (resultsFile(target)) {
@@ -969,6 +971,13 @@ fn open(p: *Pardes, req: Req, target: Target) Reply {
return .{ .tag = req.tag, .handle = @intCast(i + 1) };
}
+/// The first open record free.
+fn freeOpen(p: *Pardes) ?u64 {
+ return for (p.fs.opens, 0..) |o, i| {
+ if (o.node == 0) break i;
+ } else null;
+}
+
/// 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 {
diff --git a/core/panes.zig b/core/panes.zig
index 574c697e..1c103bd1 100644
--- a/core/panes.zig
+++ b/core/panes.zig
@@ -53,6 +53,10 @@ pub const Pane = struct {
return @backingInt(id);
}
};
+ /// Del's question asked, its time not had yet: the step that asks
+ /// reads no clock (a far client's would wait on the session's), and
+ /// core time is the last frame's, seconds old in an idle session.
+ pub const question_asked: u64 = std.math.maxInt(u64);
/// The words that throw unsaved text away (builtins.zig warnModified).
pub const Discarding = enum { Exit, Restore, get, Del, Delcol };
@@ -218,7 +222,9 @@ pub const Pane = struct {
repl_enter: u8 = 0,
repl_enter_due_ns: u64 = 0,
/// When Del's question (`del_side`) goes up on the notice band, on the
- /// shell's clock (config.del_question_delay_ns after it was asked).
+ /// shell's clock (config.del_question_delay_ns after it was asked):
+ /// `question_asked` until the next advance, which counts the delay
+ /// from its own time (Core.advance).
question_due_ns: u64 = 0,
/// A question with its answers in it (`repl_choice`).
question: [96]u8 = undefined,
@@ -1026,11 +1032,11 @@ pub const Pane = struct {
/// started, for Kill: it runs from the shell's next C mark to its D.
/// ponytail: of several lines queued for a shell not up yet, only the
/// last is remembered, as the first of them.
- pub fn noteCommand(pane: *Pane, line: []const u8) void {
- const state = pane.terminal orelse return;
+ pub fn noteCommand(pane: *Pane, line: []const u8, started: u32) void {
+ if (pane.terminal == null) return;
const said = std.mem.trim(u8, line, " \t");
const word = said[0 .. std.mem.indexOfAny(u8, said, " \t") orelse said.len];
- var sent: @typeInfo(@FieldType(Pane, "sent_command")).optional.child = .{ .seq = Term.prompt(state).started +% 1 };
+ var sent: @typeInfo(@FieldType(Pane, "sent_command")).optional.child = .{ .seq = started +% 1 };
sent.len = @intCast(@min(word.len, sent.word.len));
@memcpy(sent.word[0..sent.len], word[0..sent.len]);
pane.sent_command = sent;
diff --git a/core/replica.zig b/core/replica.zig
index 14f441b3..49787c76 100644
--- a/core/replica.zig
+++ b/core/replica.zig
@@ -1673,6 +1673,8 @@ pub const Peer = struct {
/// Its bye said it joins again for its view (a divergence's rejoin):
/// kept for it (views.away), not closed. Its reader's, read after its end.
again: bool = false,
+ /// ...or that its window was closed (Peers.closed).
+ close: bool = false,
/// Its number in the session's `Screens`.
sid: u16 = 0,
/// Inputs read (each one's seq, as the client numbered them).
@@ -1888,6 +1890,16 @@ pub const Peer = struct {
peer.cond.signal(io);
}
+ /// Its last message: queued, and its writer ends once it is written.
+ fn last(peer: *Peer, words: []const u8) void {
+ const io = peer.peers.io;
+ peer.send(&.{words});
+ peer.lock.lockUncancelable(io);
+ peer.closing = true;
+ peer.cond.signal(io);
+ peer.lock.unlock(io);
+ }
+
fn writeLoop(peer: *Peer) void {
const io = peer.peers.io;
defer peer.done.store(true, .release);
@@ -1922,7 +1934,9 @@ pub const Peer = struct {
switch (t) {
.hello => return false,
.bye => {
- peer.again = (wire.decodeClient(tag, payload) catch return false).bye.again;
+ const b = (wire.decodeClient(tag, payload) catch return false).bye;
+ peer.again = b.again;
+ peer.close = b.close;
return false;
},
.ping => {
@@ -2045,6 +2059,10 @@ pub const Peers = struct {
/// No frontend of its own (the host says): with no client either, the
/// session is unattended.
detached: bool = false,
+ /// Its last client left by closing its window, and no Detach was typed
+ /// in any (`kept`): a pair's session ends there (runtime/session.zig).
+ closed: bool = false,
+ kept: bool = false,
/// The worst a join cost the session's step, and the last one's dump.
join_ns: u64 = 0,
each_join: std.ArrayListUnmanaged(u64) = .empty,
@@ -2231,7 +2249,10 @@ pub const Peers = struct {
}
}
- fn join(ps: *Peers, core: *Pardes, joining: Joining) void {
+ /// A client on `joining.fd` joined: a dump of the session now, its
+ /// threads started. At a step boundary (`boundary`), or a session's
+ /// first client before its first effects (runtime/session.zig).
+ pub fn join(ps: *Peers, core: *Pardes, joining: Joining) void {
const fd = joining.fd;
const t0 = nowNs();
defer {
@@ -2341,6 +2362,7 @@ pub const Peers = struct {
core.undrawn &= ~(@as(u8, 1) << @intCast(peer.view));
ps.closeViewOf(core, peer, peer.again);
if (ps.count() == 0) core.unattended = ps.detached;
+ if (ps.count() == 0 and peer.close and !ps.kept) ps.closed = true;
ps.seq += 1;
ps.unit(0, ps.seq);
ps.letGo(peer);
@@ -2402,14 +2424,14 @@ pub const Peers = struct {
if (ps.count() == 0) return;
var out: [600]u8 = undefined;
const words = wire.encodeServer(&out, .{ .refused = why }) catch return;
- const io = ps.io;
- for (ps.list) |slot| if (slot) |peer| {
- peer.send(&.{words});
- peer.lock.lockUncancelable(io);
- peer.closing = true;
- peer.cond.signal(io);
- peer.lock.unlock(io);
- };
+ for (ps.list) |slot| if (slot) |peer| peer.last(words);
+ ps.flushed200();
+ // Each joins again for its view, kept in the dump (views.away).
+ ps.drop(core, true);
+ }
+
+ /// What each client was sent goes first, for up to 200 ms.
+ fn flushed200(ps: *Peers) void {
const until = nowNs() + 200 * std.time.ns_per_ms;
while (nowNs() < until) {
const busy = for (ps.list) |slot| {
@@ -2419,8 +2441,6 @@ pub const Peers = struct {
const ts: libc.timespec = .{ .sec = 0, .nsec = 2 * std.time.ns_per_ms };
_ = libc.nanosleep(&ts, null);
}
- // Each joins again for its view, kept in the dump (views.away).
- ps.drop(core, true);
}
/// A join's dump and pins let go: written, or its client gone.
@@ -2443,16 +2463,27 @@ pub const Peers = struct {
daemon.clients(pids[0..n]);
}
- /// Detach typed in client view `k`'s: its link ends (its reader says
- /// it is gone, and the next boundary lets it go).
+ /// Detach typed in client view `k`'s: told it left the session running
+ /// (`left`), its last word; the client goes, and its reader says so.
pub fn detach(ps: *Peers, k: u8) bool {
for (ps.list) |slot| if (slot) |peer| if (peer.view == k) {
- _ = libc.shutdown(peer.fd, 2);
+ ps.kept = true;
+ var out: [wire.max_name + 8]u8 = undefined;
+ peer.last(wire.encodeServer(&out, .{ .left = ps.name[0..@min(ps.name.len, wire.max_name)] }) catch unreachable);
return true;
};
return false;
}
+ /// The session ends with `code`: every client told so (`ended`), its
+ /// last word, before the links are let go (`dropAll`).
+ pub fn ended(ps: *Peers, code: u8) void {
+ var out: [16]u8 = undefined;
+ const words = wire.encodeServer(&out, .{ .ended = code }) catch unreachable;
+ for (ps.list) |slot| if (slot) |peer| peer.last(words);
+ ps.flushed200();
+ }
+
fn stop(ps: *Peers, core: *Pardes) void {
if (!ps.recording) return;
pardes.panes.resizeDeferred(core);
@@ -2576,13 +2607,14 @@ pub fn dial(gpa: Allocator, path: []const u8, session: []const u8, why: []u8, ha
}
/// `dial`'s, on a connection made: the hello, then the join. The
-/// connection is closed if the join fails.
-fn joinOn(gpa: Allocator, fd: c_int, session: []const u8, why: []u8, have: ?*Have, view: ?u8) ?Joined {
+/// connection is closed if the join fails. No session named: no hello, a
+/// pair's (Options.pair), whose session took it as its first client.
+fn joinOn(gpa: Allocator, fd: c_int, session: ?[]const u8, why: []u8, have: ?*Have, view: ?u8) ?Joined {
var out: [wire.hello_max + 16]u8 = undefined;
- const hello = wire.encodeClient(&out, .{ .hello = .{ .session = session, .view = view } }) catch {
+ const hello = if (session) |name| wire.encodeClient(&out, .{ .hello = .{ .session = name, .view = view } }) catch {
_ = libc.close(fd);
return said(why, "that session's name is too long", .{});
- };
+ } else out[0..0];
// Its first word, in the same write: whether it is far.
const far = wire.encodeClient(out[hello.len..], .{ .far = have != null }) catch unreachable;
var j: Joined = .{ .fd = fd, .pid = 0, .client = 0, .view = 0, .gmtoff = 0, .dump = &.{} };
@@ -2906,16 +2938,17 @@ pub fn askCheck(fd: c_int) bool {
return writeAll(fd, wire.encodeClient(&out, .check) catch unreachable);
}
-/// The client's last word: `again`, it joins again for its view at once.
-pub fn bye(fd: c_int, again: bool) void {
+/// The client's last word: `again`, it joins again for its view at once;
+/// `close`, its window was closed.
+pub fn bye(fd: c_int, how: @FieldType(wire.ClientMsg, "bye")) void {
var out: [16]u8 = undefined;
- if (wire.encodeClient(&out, .{ .bye = .{ .again = again } })) |b| _ = writeAll(fd, b) else |_| {}
+ if (wire.encodeClient(&out, .{ .bye = how })) |b| _ = writeAll(fd, b) else |_| {}
}
/// What the session streams a client after its dump, as its frontend's loop
/// takes it: a unit's and a terminal message's bytes and a refusal's words
/// on the C heap, the loop's to free.
-pub const Said = union(enum) { unit: []u8, screen: []u8, checked: u64, refused: []u8, blob: []u8 };
+pub const Said = union(enum) { unit: []u8, screen: []u8, checked: u64, refused: []u8, blob: []u8, ended: u8, left };
/// The session's stream off `fd`, each message handed to `post` until the
/// link ends (a refusal ends it too); `post` says whether it took it (one
@@ -2930,13 +2963,16 @@ pub fn readLink(gpa: Allocator, fd: c_int, rest: *Framer, ctx: anytype, comptime
.blob => .{ .blob = std.heap.c_allocator.dupe(u8, payload) catch return false },
.check => .{ .checked = (wire.decodeServer(tag, payload) catch return false).check },
.refused => .{ .refused = std.heap.c_allocator.dupe(u8, (wire.decodeServer(tag, payload) catch return false).refused) catch return false },
+ .ended => .{ .ended = (wire.decodeServer(tag, payload) catch return false).ended },
+ .left => .left,
.pong, .welcome, .dump, .blobs, .zstd => return true,
};
if (!post(x, msg)) switch (msg) {
.unit, .screen, .refused, .blob => |b| std.heap.c_allocator.free(b),
- .checked => {},
+ .checked, .ended, .left => {},
};
- return msg != .refused;
+ // A last word ends the stream.
+ return msg == .unit or msg == .screen or msg == .checked or msg == .blob;
}
};
rest.run(gpa, fd, ctx, Take.take);
@@ -2946,11 +2982,30 @@ pub fn readLink(gpa: Allocator, fd: c_int, rest: *Framer, ctx: anytype, comptime
if (!post(ctx, .{ .refused = words })) std.heap.c_allocator.free(words);
}
+/// A join's failure that is its session's end, whenever it came (the
+/// session or its daemon gone, or hung up before the dump was whole): a
+/// client joining again then goes as at a hang-up (`.gone`), in the same
+/// words, never as a join that failed.
+pub fn ended(why: []const u8) bool {
+ const words = std.mem.sliceTo(why, 0);
+ for ([_][]const u8{ "the session hung up", "nothing answers at ", "no session called " }) |w|
+ if (std.mem.startsWith(u8, words, w)) return true;
+ return false;
+}
+
/// The words a client goes with when its session runs another build now.
const upgrade_words = "session upgraded to a newer pardes: upgrade this client too";
+/// A join's failure that is its session's running another build now: a
+/// client whose own start path holds a newer one execs that instead
+/// (runtime/client.zig).
+pub fn otherBuild(why: []const u8) bool {
+ return std.mem.endsWith(u8, std.mem.sliceTo(why, 0), upgrade_words);
+}
+
/// A replica client's join, the terminal's and the window's alike (their
-/// `runClient`): the session at `path` dialled, its build checked to be this
+/// `runClient`): the session at `path` dialled (or, first, the one on its
+/// pair, `o.pair`), its build checked to be this
/// one's, and its dump loaded into a replica checked against the session
/// as it was dumped. Or, `old` given, joined again once old's link has
/// ended, for old's view (`redial`): the core it leaves held meanwhile so
@@ -2963,6 +3018,7 @@ pub fn join(gpa: Allocator, j: *Joined, path: []const u8, session: []const u8, o
const t0 = nowNs();
if (old) |prev| {
j.* = redial(gpa, path, session, why, have, prev.diverged == null, j.view) orelse {
+ if (ended(why)) return null;
var words: [600]u8 = undefined;
const said_ = std.mem.sliceTo(why, 0);
@memcpy(words[0..said_.len], said_);
@@ -2971,7 +3027,10 @@ pub fn join(gpa: Allocator, j: *Joined, path: []const u8, session: []const u8, o
};
if (have) |h| h.left();
prev.deinit();
- } else j.* = sameBuild(gpa, dial(gpa, path, session, why, have, null) orelse return null, why) orelse return null;
+ } else j.* = (if (o.join_view) |v|
+ redial(gpa, path, session, why, have, true, v)
+ else
+ sameBuild(gpa, (if (o.pair) |fd| joinOn(gpa, fd, null, why, have, null) else dial(gpa, path, session, why, have, null)) orelse return null, why)) orelse return null;
defer {
if (have) |h| h.store(gpa, j) else gpa.free(j.dump);
j.dump = &.{};
@@ -3006,7 +3065,7 @@ pub fn join(gpa: Allocator, j: *Joined, path: []const u8, session: []const u8, o
/// an upgrade under way may not have said yet.
fn sameBuild(gpa: Allocator, j: Joined, why: []u8) ?Joined {
if (j.semantics == wire.semantics) return j;
- bye(j.fd, false);
+ bye(j.fd, .{});
_ = libc.close(j.fd);
var jj = j;
jj.rest.deinit(gpa);
@@ -3027,7 +3086,10 @@ fn redial(gpa: Allocator, path: []const u8, session: []const u8, why: *[600]u8,
while (true) : (tries += 1) {
why.* = @splat(0);
if (dial(gpa, path, session, why, have, view)) |j| return sameBuild(gpa, j, why);
- if (std.mem.indexOf(u8, std.mem.sliceTo(why, 0), "runs another build") != null) {
+ // Another build, or another protocol (the daemon moved with its
+ // session): no dial again will do.
+ const words = std.mem.sliceTo(why, 0);
+ if (std.mem.indexOf(u8, words, "runs another build") != null or std.mem.indexOf(u8, words, "run the same pardes at both ends") != null) {
_ = std.fmt.bufPrint(why, "{s}\x00", .{upgrade_words}) catch {};
return null;
}
@@ -3044,6 +3106,8 @@ pub const Link = struct {
r: *Replica,
fd: c_int,
quit: bool = false,
+ /// ...because its window was closed: said in its bye.
+ close: bool = false,
/// The session hung up.
gone: bool = false,
/// Something to draw: an input applied, a unit taken.
@@ -3073,6 +3137,9 @@ pub const Link = struct {
visible: u32 = 0,
/// What the session said as it let this client go (the C heap's).
refused: ?[]u8 = null,
+ /// Its last word: it ended, with this code; or this client left it.
+ ended: ?u8 = null,
+ left: bool = false,
/// A line over its frame, until its next key (`notify`): why it joined
/// again. The client's own, never the session's core.
notice_buf: [240]u8 = undefined,
@@ -3191,6 +3258,14 @@ pub const Link = struct {
c.refused = words;
c.quit = true;
},
+ .ended => |code| {
+ c.ended = code;
+ c.quit = true;
+ },
+ .left => {
+ c.left = true;
+ c.quit = true;
+ },
}
if (c.r.diverged != null) c.quit = true;
}
@@ -3571,6 +3646,14 @@ test "a client joining again after a divergence is told at once that its session
const t0 = nowNs();
try std.testing.expect(redial(std.testing.allocator, "/nonexistent/pardes-replica.sock", "gone", &why, null, false, 1) == null);
try std.testing.expect(nowNs() - t0 < 100 * std.time.ns_per_ms);
+ try std.testing.expect(ended(&why));
+ // Its session ending as it joins: hung up before the dump was whole,
+ // its end too, said as the end it is.
+ var fds: [2]c_int = undefined;
+ try std.testing.expectEqual(0, libc.socketpair(libc.AF.UNIX, libc.SOCK.STREAM, 0, &fds));
+ _ = libc.close(fds[1]);
+ try std.testing.expect(joinOn(std.testing.allocator, fds[0], "gone", &why, null, 1) == null);
+ try std.testing.expect(ended(&why));
}
test "a replica's own keys apply at once, confirm on the fast path, and end at the authority's digest" {
@@ -4389,6 +4472,119 @@ test "bytes: a client joins from a dump with its terminals whole, and every side
try sameTerminals(b.a, late);
}
+test "a session's first client on the socket it starts with (Options.pair), joined there with no hello before the session's first effects: the boot shell's spawn and first bytes reach it and the digests agree" {
+ try firstOnPair(false);
+}
+
+test "bytes: a session's first client on its pair, taken before its first effects, has the boot shell's first bytes with no reload of them (the session's one at the join is of its emulator before any byte, the client's none); a client after them makes every side reload" {
+ try firstOnPair(true);
+}
+
+/// A session's first client on a socket pair (runtime/session.zig's, then
+/// the client's first join on its end), the session's first effects after:
+/// its boot shell spawned, its first bytes output; the client quiet and
+/// checked. Bytes: the client loaded as the soak's bytes clients are
+/// (`replica.join` loads the screen-state kind until the switch).
+fn firstOnPair(bytes: bool) !void {
+ if (pardes.Term.ops == null) return error.SkipZigTest; // a shell
+ const gpa = std.testing.allocator;
+ const Spawns = struct {
+ fn spawn(ctx: ?*anyopaque, _: pardes.Pane.Id, _: []const u8) void {
+ const n: *u32 = @ptrCast(@alignCast(ctx.?));
+ n.* += 1;
+ }
+ const vtable: pardes.Host.VTable = .{ .watched = TestHost.watched, .spawn = spawn };
+ };
+ var spawns: u32 = 0;
+ var fds: [2]c_int = undefined;
+ if (libc.socketpair(libc.AF.UNIX, libc.SOCK.STREAM | libc.SOCK.CLOEXEC, 0, &fds) != 0) return error.NoSocket;
+ const opts: pardes.Options = .{ .cols = 80, .rows = 24, .boot = .tty };
+ const core = try Pardes.init(gpa, opts);
+ defer core.deinit();
+ core.host = .{ .ctx = &spawns, .vtable = &Spawns.vtable };
+ var ps: Peers = .{ .gpa = gpa, .io = std.testing.io, .name = "pair", .bytes = bytes, .detached = true };
+ defer ps.deinit();
+ defer live_peers = null;
+ defer ps.dropAll(core);
+ const reloads = pardes.Term.reloads.n;
+ ps.join(core, .{ .fd = fds[0] });
+ var j: Joined = undefined;
+ var why: [600]u8 = @splat(0);
+ const r = if (bytes) r: {
+ j = joinOn(gpa, fds[1], null, &why, null, null) orelse return error.JoinFailed;
+ defer gpa.free(j.dump);
+ const r = try Replica.initDump(gpa, j.client, j.view, j.dump, opts);
+ r.t.screen_state = false;
+ r.core().echo = null;
+ break :r r;
+ } else r: {
+ var o = opts;
+ o.pair = fds[1];
+ break :r join(gpa, &j, "", "", o, null, &why, null) orelse {
+ std.debug.print("the join failed: {s}\n", .{std.mem.sliceTo(&why, 0)});
+ return error.JoinFailed;
+ };
+ };
+ defer r.deinit();
+ defer {
+ _ = libc.close(j.fd);
+ j.rest.deinit(gpa);
+ }
+ try std.testing.expect(r.loaded(j.digest));
+ // The first effects, the boot shell's spawn among them; its first bytes.
+ while (core.nextEffect()) |e| core.perform(e);
+ try std.testing.expectEqual(@as(u32, 1), spawns);
+ const shell: u8 = for (core.panes, 0..) |slot, id| {
+ if (slot) |pane| if (pane.isTerminal()) break @intCast(id);
+ } else return error.NoShell;
+ core.update(.{ .output = .{ .pane = .at(shell), .bytes = "first$ " } });
+ ps.boundary(core);
+ // Its check, answered after every unit and terminal message before it.
+ try std.testing.expect(askCheck(j.fd));
+ while (!ps.mail.load(.acquire)) std.Thread.yield() catch {};
+ ps.boundary(core);
+ const Take = struct {
+ r: *Replica,
+ fd: c_int,
+ digest: ?u64 = null,
+ fn take(t: *@This(), tag: u8, payload: []const u8) bool {
+ switch (std.enums.fromInt(wire.ServerTag, tag) orelse return false) {
+ .unit => t.r.confirm(payload),
+ .screen => if (t.r.screen(payload)) |reply| {
+ _ = sendScreen(t.fd, reply);
+ },
+ .check => {
+ t.digest = (wire.decodeServer(tag, payload) catch return false).check;
+ return false;
+ },
+ else => {},
+ }
+ return true;
+ }
+ };
+ var take: Take = .{ .r = r, .fd = j.fd };
+ j.rest.run(gpa, j.fd, &take, Take.take);
+ r.settle();
+ if (r.diverged) |w| std.debug.print("diverged: {s}\n", .{w});
+ try std.testing.expect(r.diverged == null);
+ try std.testing.expectEqual(take.digest.?, r.digest());
+ // Bytes: the session's reload at the join, of an emulator that held
+ // nothing yet (Pardes.init made it, the spawn is a first effect); the
+ // client loaded it from the dump and replayed every byte since.
+ try std.testing.expectEqual(reloads + @intFromBool(bytes), pardes.Term.reloads.n);
+ var arena: std.heap.ArenaAllocator = .init(gpa);
+ defer arena.deinit();
+ const rows = try pardes.Term.viewport(r.core().panes[shell].?.terminal.?, arena.allocator(), false);
+ try std.testing.expect(std.mem.indexOf(u8, rows[0], "first$") != null);
+ if (!bytes) return;
+ // One that comes after the shell's bytes: every side reloads.
+ var late: [2]c_int = undefined;
+ if (libc.socketpair(libc.AF.UNIX, libc.SOCK.STREAM | libc.SOCK.CLOEXEC, 0, &late) != 0) return error.NoSocket;
+ defer _ = libc.close(late[1]);
+ ps.join(core, .{ .fd = late[0] });
+ try std.testing.expectEqual(reloads + 2, pardes.Term.reloads.n);
+}
+
test "bytes: a session's output past a unit's bound is cut into units under it, between two reads" {
if (pardes.Term.ops == null) return error.SkipZigTest; // a shell
const gpa = std.testing.allocator;
@@ -5004,7 +5200,6 @@ test "a client joined from a dump moves through another view's pane as the sessi
}
test "a client joined from a dump makes a `/` query's rows as the session does, though only the session has drawn its owner" {
- if (comptime !pardes.syntax.enabled) return error.SkipZigTest;
const gpa = std.testing.allocator;
const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "build.zig" }, TestHost.host(), false);
defer a.deinit();
@@ -6542,7 +6737,6 @@ test "a client joined from a dump makes a `/` query's rows as the session does,
}
}
};
- if (comptime !pardes.syntax.enabled) return error.SkipZigTest;
const gpa = std.testing.allocator;
const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "build.zig" }, .{ .vtable = &WorkerSearch.vtable }, false);
defer a.deinit();
@@ -6700,3 +6894,206 @@ test "a far client's replay of a message its session's host stamped takes the se
try agrees(a, r);
try std.testing.expect(try shows(r.core(), "--:--:-- yanked x"));
}
+
+// A script's `pty/run` in a shell (ninep/pty.zig): the open, the line, the
+// marks that end it, its answer read and the open released, each a step of
+// the session's, with a client that joined from a dump taking every unit.
+test "a client joined from a dump takes a 9P pty/run in a shell as the session does: the line sent at the prompt, its end answered" {
+ if (pardes.Term.ops == null) return error.SkipZigTest; // a shell
+ const gpa = std.testing.allocator;
+ const RunHost = struct {
+ fn taken(_: ?*anyopaque, _: pardes.Pane.Id) bool {
+ return false;
+ }
+ fn write(_: ?*anyopaque, _: pardes.Pane.Id, _: []const u8) void {}
+ const vtable: pardes.Host.VTable = .{ .watched = TestHost.watched, .tty_taken = taken, .pty_write = write };
+ };
+ const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .boot = .tty }, .{ .vtable = &RunHost.vtable }, false);
+ defer a.deinit();
+ const r = try Replica.init(gpa, 1, try a.unit(0, 0), false);
+ defer r.deinit();
+ const shell: u8 = for (a.core.panes, 0..) |slot, id| {
+ if (slot) |pane| if (pane.isTerminal()) break @intCast(id);
+ } else return error.NoShell;
+ const prompt = "\x1b]133;A;cl=line;aid=pardes\x07$ \x1b]133;B;aid=pardes\x07";
+ a.output(.{ .output = .{ .pane = .at(shell), .bytes = prompt ++ "ls\r\n\x1b]133;C;aid=pardes\x07a b\r\n\x1b]133;D;0;aid=pardes\x07" ++ prompt } });
+ r.confirm((try a.pending()).?);
+ r.settle();
+ // A script's listing open, held across the join (a reader of /index).
+ {
+ const was = Stepping.begin(&a.t, null);
+ _ = a.core.serveFs(.{ .tag = 9, .op = .open, .node = @backingInt(pardes.ctlfs.TopFile.index) });
+ was.end();
+ a.seq += 1;
+ r.confirm(try a.unit(0, a.seq));
+ r.settle();
+ }
+ const joined = (try a.join(2, null)).?;
+ defer gpa.free(joined.dump);
+ r.confirm(joined.unit);
+ const late = try Replica.initDump(gpa, 2, joined.view, joined.dump, .{ .cols = 80, .rows = 24 });
+ defer late.deinit();
+ late.t.screen_state = false;
+ late.core().echo = null;
+ try std.testing.expectEqual(joined.digest, late.digest());
+ const node = pardes.ctlfs.Node.of(a.core.panes[shell].?.serial, .pty_run);
+ const Serve = struct {
+ fn serve(s: *Authority, rs: []const *Replica, req: pardes.ctlfs.Req) !pardes.ctlfs.Reply {
+ const was = Stepping.begin(&s.t, null);
+ const reply = s.core.serveFs(req);
+ s.core.pump(s.host) catch {};
+ was.end();
+ s.seq += 1;
+ const u = try s.unit(0, s.seq);
+ for (rs) |x| {
+ x.confirm(u);
+ x.settle();
+ }
+ return reply;
+ }
+ fn output(s: *Authority, rs: []const *Replica, pane: u8, bytes: []const u8) !void {
+ s.output(.{ .output = .{ .pane = .at(pane), .bytes = bytes } });
+ const u = (try s.pending()).?;
+ for (rs) |x| {
+ x.confirm(u);
+ x.settle();
+ }
+ }
+ };
+ const both = [_]*Replica{ r, late };
+ const h = (try Serve.serve(a, &both, .{ .tag = 1, .op = .open, .node = node, .omode = 2 })).handle;
+ _ = try Serve.serve(a, &both, .{ .tag = 2, .op = .write, .node = node, .handle = h, .data = "true\n" });
+ try Serve.output(a, &both, shell, "true\r\n\x1b]133;C;aid=pardes\x07\x1b]133;D;0;aid=pardes\x07" ++ prompt);
+ const answer = try Serve.serve(a, &both, .{ .tag = 3, .op = .read, .node = node, .handle = h, .size = 64 });
+ try std.testing.expectEqualStrings("exit 0\n", a.core.fsPayload(answer));
+ _ = try Serve.serve(a, &both, .{ .tag = 4, .op = .release, .node = node, .handle = h, .opened = true });
+ try Serve.output(a, &both, shell, "\x1b]133;A;cl=line;aid=pardes\x07");
+ try agrees(a, r);
+ try agrees(a, late);
+}
+
+// The same run with the terminals crossing as screen state (a session's
+// clients', until the switch to bytes): a replica's emulator is the
+// deltas', its marks not the session's.
+test "a client of screen-state terminals takes a 9P pty/run in a shell as the session does" {
+ if (pardes.Term.ops == null) return error.SkipZigTest; // a shell
+ const gpa = std.testing.allocator;
+ const RunHost = struct {
+ fn taken(_: ?*anyopaque, _: pardes.Pane.Id) bool {
+ return false;
+ }
+ fn write(_: ?*anyopaque, _: pardes.Pane.Id, _: []const u8) void {}
+ const vtable: pardes.Host.VTable = .{ .watched = TestHost.watched, .tty_taken = taken, .pty_write = write };
+ };
+ const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .boot = .tty }, .{ .vtable = &RunHost.vtable }, true);
+ defer a.deinit();
+ var screens: Screens = .init(gpa);
+ defer screens.deinit(a.core);
+ const peer = try screens.addPeer();
+ const r = try Replica.init(gpa, 1, try a.unit(0, 0), true);
+ defer r.deinit();
+ const shell: u8 = for (a.core.panes, 0..) |slot, id| {
+ if (slot) |pane| if (pane.isTerminal()) break @intCast(id);
+ } else return error.NoShell;
+ const Step = struct {
+ var second: ?*Replica = null;
+ fn take(s: *Authority, sc: *Screens, p: u16, x: *Replica, u: []const u8) !void {
+ const gpa_ = std.testing.allocator;
+ const kept = try gpa_.dupe(u8, u);
+ defer gpa_.free(kept);
+ // The unit first, its screens at the frame after (Peers).
+ x.confirm(kept);
+ x.settle();
+ if (second) |y| {
+ y.confirm(kept);
+ y.settle();
+ }
+ try deliver(s, sc, p, x, .flush);
+ if (second) |y| try deliver(s, sc, p + 1, y, .flush);
+ }
+ fn serve(s: *Authority, sc: *Screens, p: u16, x: *Replica, req: pardes.ctlfs.Req) !pardes.ctlfs.Reply {
+ const was = Stepping.begin(&s.t, null);
+ const reply = s.core.serveFs(req);
+ s.core.pump(s.host) catch {};
+ was.end();
+ s.seq += 1;
+ try take(s, sc, p, x, try s.unit(0, s.seq));
+ return reply;
+ }
+ fn output(s: *Authority, sc: *Screens, p: u16, x: *Replica, pane: u8, bytes: []const u8) !void {
+ s.output(.{ .output = .{ .pane = .at(pane), .bytes = bytes } });
+ try take(s, sc, p, x, (try s.pending()).?);
+ }
+ };
+ const prompt = "\x1b]133;A;cl=line;aid=pardes\x07$ \x1b]133;B;aid=pardes\x07";
+ try Step.output(a, &screens, peer, r, shell, prompt ++ "ls\r\n\x1b]133;C;aid=pardes\x07a b\r\n\x1b]133;D;0;aid=pardes\x07" ++ prompt);
+ // A second client joins now, from the session's dump.
+ const joined = (try a.join(2, null)).?;
+ defer gpa.free(joined.dump);
+ try Step.take(a, &screens, peer, r, joined.unit);
+ const late = try Replica.initDump(gpa, 2, joined.view, joined.dump, .{ .cols = 80, .rows = 24 });
+ defer late.deinit();
+ const peer2 = try screens.addPeer();
+ try deliver(a, &screens, peer2, late, .flush);
+ Step.second = late;
+ defer Step.second = null;
+ const node = pardes.ctlfs.Node.of(a.core.panes[shell].?.serial, .pty_run);
+ for (0..2) |_| {
+ const h = (try Step.serve(a, &screens, peer, r, .{ .tag = 1, .op = .open, .node = node, .omode = 2 })).handle;
+ _ = try Step.serve(a, &screens, peer, r, .{ .tag = 2, .op = .write, .node = node, .handle = h, .data = "true\n" });
+ try Step.output(a, &screens, peer, r, shell, "true\r\n\x1b]133;C;aid=pardes\x07\x1b]133;D;0;aid=pardes\x07" ++ prompt);
+ const answer = try Step.serve(a, &screens, peer, r, .{ .tag = 3, .op = .read, .node = node, .handle = h, .size = 64 });
+ try std.testing.expectEqualStrings("exit 0\n", a.core.fsPayload(answer));
+ _ = try Step.serve(a, &screens, peer, r, .{ .tag = 4, .op = .release, .node = node, .handle = h, .opened = true });
+ }
+ try agrees(a, r);
+ try agrees(a, late);
+}
+
+// Del with a pane above and below asks which way the space goes, its
+// question shown once a delay is up (builtins.zig): its time was the
+// host's clock read in the step, an answering entry a speculation stops at.
+test "a far client's Del with panes above and below is applied at once, and its question's time is the session's" {
+ const gpa = std.testing.allocator;
+ const Clocked = struct {
+ var now_ns: u64 = 7 * std.time.ns_per_s;
+ fn now(_: ?*anyopaque) u64 {
+ return now_ns;
+ }
+ const vtable: pardes.Host.VTable = .{ .watched = TestHost.watched, .now = now };
+ };
+ const a = try Authority.init(gpa, .{ .cols = 80, .rows = 30, .file = "mise.toml" }, .{ .vtable = &Clocked.vtable }, false);
+ defer a.deinit();
+ _ = try a.local(.{ .command = "New" });
+ const mid = a.core.view().active;
+ _ = try a.local(.{ .command = "New" });
+ {
+ const was = Stepping.begin(&a.t, null);
+ defer was.end();
+ a.core.view().active = mid;
+ }
+ const r = try joinedFresh(a);
+ defer r.deinit();
+ var sent: std.ArrayListUnmanaged([]u8) = .empty;
+ defer {
+ for (sent.items) |m| gpa.free(m);
+ sent.deinit(gpa);
+ }
+ Clocked.now_ns += std.time.ns_per_s;
+ try key(r, ' ', &sent);
+ try key(r, 'd', &sent);
+ try std.testing.expectEqual(@as(usize, 2), r.applied);
+ try std.testing.expect(r.core().panes[mid].?.prompt == .del_side);
+ for (sent.items) |m| {
+ r.confirm(try a.take(m));
+ r.settle();
+ }
+ try std.testing.expectEqual(@as(u32, 0), r.stats.mispredicted);
+ try agrees(a, r);
+ // The question shows a delay after it was asked, on the session's clock.
+ a.pump();
+ r.confirm((try a.pending()).?);
+ r.settle();
+ try agrees(a, r);
+ try std.testing.expectEqual(Clocked.now_ns + pardes.config.del_question_delay_ns, r.core().panes[mid].?.question_due_ns);
+}
diff --git a/core/root.zig b/core/root.zig
index 45948189..5300ce93 100644
--- a/core/root.zig
+++ b/core/root.zig
@@ -103,8 +103,6 @@ pub const platform = @import("pardes_options").platform;
pub const version = @import("build_info").version;
pub const commit: ?[]const u8 = @import("build_info").commit;
-pub const isolated = @import("pardes_options").isolated;
-
pub const font_picker = platform == .gui or platform == .macos;
/// Whose turn it is with the core (Turn.zig): one per process, like the
@@ -632,7 +630,7 @@ const machine_lines = [_]struct { []const u8, usize, []const u8 }{
.{ "hunks.zig", 1, "a test helper's file read" },
.{ "look.zig", 6, "openLink's fork (the host's: a view's frontend opens a link) and a remote's error name" },
.{ "memory.zig", 7, "the memory regions themselves (mmap, madvise, their locks)" },
- .{ "replica.zig", 70, "the client and session engines: sockets, threads, clocks, the blob cache, traces" },
+ .{ "replica.zig", 73, "the client and session engines: sockets, threads, clocks, the blob cache, traces" },
.{ "rollback.zig", 1, "a test helper's directory" },
.{ "root.zig", 4, "dev's modules re-exported (host_io, file_watch, glide, fonts)" },
.{ "selection_pipe.zig", 14, "a pipe's child processes and their files: the host's `pipe` entry" },
diff --git a/core/syntax.zig b/core/syntax.zig
index ba3851ab..19831ec2 100644
--- a/core/syntax.zig
+++ b/core/syntax.zig
@@ -7,17 +7,11 @@ const regexp = @import("regexp.zig");
const c_heap = @import("c_heap");
const diff = @import("diff.zig");
-pub const enabled = config.grammars != .disabled;
-const minimal_grammars = config.grammars == .minimal or config.grammars == .full;
+const minimal_grammars = config.grammars != .none;
const full_grammars = config.grammars == .full;
-pub const ts = if (enabled) @import("tree-sitter") else struct {
- pub const Language = opaque {};
- pub const Query = opaque {};
- pub const Parser = opaque {};
- pub const QueryCursor = opaque {};
-};
-const ts_queries = if (enabled) @import("ts_queries") else struct {};
+pub const ts = @import("tree-sitter");
+const ts_queries = @import("ts_queries");
const LanguageFn = *const fn () callconv(.c) *const ts.Language;
@@ -43,7 +37,6 @@ const Spec = struct {
fn grammarSelected(comptime g: grammar_manifest.Grammar) bool {
return switch (g.tier) {
- .zig => enabled,
.minimal => minimal_grammars,
.full => full_grammars,
};
@@ -92,28 +85,24 @@ extern fn ts_set_allocator(
) void;
pub fn start(gpa: std.mem.Allocator) void {
- if (comptime enabled) {
- std.debug.assert(!syntax_started);
- stop();
- syntax_allocator = gpa;
- syntax_started = true;
- ts_set_allocator(syntax_heap.malloc, syntax_heap.calloc, syntax_heap.realloc, syntax_heap.free);
- }
+ std.debug.assert(!syntax_started);
+ stop();
+ syntax_allocator = gpa;
+ syntax_started = true;
+ ts_set_allocator(syntax_heap.malloc, syntax_heap.calloc, syntax_heap.realloc, syntax_heap.free);
}
pub fn stop() void {
- if (comptime enabled) {
- for (&specs) |*spec| dropSpec(spec);
- forgetLanguages();
- for (&diff_pieces) |*slot| {
- if (slot.*) |piece| syntax_allocator.free(piece.styles);
- slot.* = null;
- }
- diff_clock = 0;
- ts_set_allocator(null, null, null, null);
- syntax_started = false;
- syntax_allocator = undefined;
+ for (&specs) |*spec| dropSpec(spec);
+ forgetLanguages();
+ for (&diff_pieces) |*slot| {
+ if (slot.*) |piece| syntax_allocator.free(piece.styles);
+ slot.* = null;
}
+ diff_clock = 0;
+ ts_set_allocator(null, null, null, null);
+ syntax_started = false;
+ syntax_allocator = undefined;
}
const Selected = struct {
@@ -254,7 +243,6 @@ fn runQuery(styles: []u8, sel: Selected, tree: *ts.Tree, base: usize) void {
pub fn highlightFileRange(gpa: std.mem.Allocator, path: []const u8, content: []const u8, start_raw: usize, end_raw: usize) ![]u8 {
const zone = tracy.zone(@src(), "highlightFileRange");
defer zone.end();
- if (!enabled) return &.{};
const selected = (try forExt(std.Io.Dir.path.extension(path))) orelse return &.{};
const start_byte = @min(start_raw, content.len);
const end_byte = @max(start_byte, @min(end_raw, content.len));
@@ -269,7 +257,6 @@ pub fn highlightFileRange(gpa: std.mem.Allocator, path: []const u8, content: []c
/// no injections (markdown's and typst's reach the shared parsers), made
/// ready here, on the loop, so the worker only reads its query.
pub fn readyApart(path: []const u8) bool {
- if (!enabled) return false;
const selected = (forExt(std.Io.Dir.path.extension(path)) catch return false) orelse return false;
return !std.mem.eql(u8, selected.name, "markdown") and !std.mem.eql(u8, selected.name, "typst");
}
@@ -278,7 +265,6 @@ pub fn readyApart(path: []const u8) bool {
/// parse and a query cursor of its own, the grammar's query shared (it
/// is only read); `halt` ends the parse early. After `readyApart`.
pub fn highlightApart(gpa: std.mem.Allocator, path: []const u8, source: []const u8, halt: *const std.atomic.Value(bool)) ![]u8 {
- if (comptime !enabled) return &.{};
const shared = (try forExt(std.Io.Dir.path.extension(path))) orelse return &.{};
const tree = try parseApart(shared.lang, source, halt);
defer tree.destroy();
@@ -335,7 +321,6 @@ pub const ContextDeclaration = struct {
};
pub fn supportsPath(path: []const u8) bool {
- if (!enabled) return false;
return byExt(std.Io.Dir.path.extension(path)) != null;
}
@@ -345,7 +330,6 @@ pub fn supportsPath(path: []const u8) bool {
/// since its parse (`editTree`), the parse reuses what those left alone: a
/// character typed into a 9k-line file costs a few hundred µs, not 50 ms.
pub fn parseTree(path: []const u8, content: []const u8, old: ?*anyopaque) ?*anyopaque {
- if (!enabled) return null;
const selected = (forExt(std.Io.Dir.path.extension(path)) catch return null) orelse return null;
const tree = selected.parser.parseString(content, @ptrCast(@alignCast(old))) orelse return null;
if (held_trees) |h| h.born.append(h.meta, @ptrCast(tree)) catch {};
@@ -357,7 +341,6 @@ pub fn parseTree(path: []const u8, content: []const u8, old: ?*anyopaque) ?*anyo
/// places follow the edit; what it says of the edited bytes is stale until
/// `parseTree` with it.
pub fn editTree(tree: *anyopaque, before: []const u8, old: []const u8, ins: []const u8) void {
- if (!enabled) return;
const from = advance(.{ .row = 0, .column = 0 }, before);
const t: *ts.Tree = @ptrCast(@alignCast(tree));
t.edit(.{
@@ -387,7 +370,6 @@ pub const HeldTrees = struct {
};
pub fn freeTree(tree: *anyopaque) void {
- if (!enabled) return;
if (held_trees) |h| {
for (h.born.items, 0..) |t, i| if (t == tree) {
_ = h.born.swapRemove(i);
@@ -400,7 +382,6 @@ pub fn freeTree(tree: *anyopaque) void {
}
pub fn destroyTree(tree: *anyopaque) void {
- if (!enabled) return;
const t: *ts.Tree = @ptrCast(@alignCast(tree));
t.destroy();
}
@@ -412,7 +393,7 @@ pub const Span = struct { from: usize, to: usize };
/// The spans `walk` takes the byte range [from, to) to, into `out`; `at` is
/// the range's cursor. None when the tree has nothing to say there.
pub fn walkNodes(tree_ptr: *anyopaque, walk: NodeWalk, from: usize, to: usize, at: usize, out: []Span) usize {
- if (!enabled or out.len == 0) return 0;
+ if (out.len == 0) return 0;
const tree: *const ts.Tree = @ptrCast(@alignCast(tree_ptr));
const lo: u32 = @intCast(@min(from, std.math.maxInt(u32)));
const hi: u32 = @intCast(@min(to, std.math.maxInt(u32)));
@@ -497,7 +478,6 @@ fn objectQuery(path: []const u8) ?*ts.Query {
/// The grammar's indent query for `path` (core/indent.zig) and the
/// grammar's name; null when it has none.
pub fn indentQuery(path: []const u8) ?struct { *ts.Query, []const u8 } {
- if (!enabled) return null;
const spec = specFor(path) orelse return null;
return .{ lazyQuery(spec, &spec.indents) orelse return null, spec.name };
}
@@ -563,7 +543,6 @@ fn matchSpan(q: *const ts.Query, match: anytype, capture: u32, text: []const u8)
/// `mi`/`ma`: the smallest `object.inside` (or `.around`) holding byte `at`
/// (helix textobject_treesitter). None without a query or such an object.
pub fn objectAt(path: []const u8, tree_ptr: *anyopaque, text: []const u8, object: Object, around: bool, at: usize) ?Span {
- if (!enabled) return null;
const q = objectQuery(path) orelse return null;
var buf: [32]u8 = undefined;
const want = std.fmt.bufPrint(&buf, "{s}.{s}", .{ objectName(object), if (around) "around" else "inside" }) catch return null;
@@ -587,7 +566,6 @@ pub fn objectAt(path: []const u8, tree_ptr: *anyopaque, text: []const u8, object
/// previous one ending before it (helix goto_treesitter_object), from the
/// first of `.movement`, `.around`, `.inside` the query names.
pub fn objectNext(path: []const u8, tree_ptr: *anyopaque, text: []const u8, object: Object, forward: bool, at: usize) ?Span {
- if (!enabled) return null;
const q = objectQuery(path) orelse return null;
var buf: [32]u8 = undefined;
const capture = for ([_][]const u8{ "movement", "around", "inside" }) |kind| {
@@ -628,7 +606,7 @@ pub const SourceAnalysis = struct {
};
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 .{};
+ if (content.len == 0 or (!want_declarations and !want_colors)) return .{};
const selected = (try forExt(std.Io.Dir.path.extension(path))) orelse return .{};
const tree = selected.parser.parseString(content, null) orelse return .{};
defer tree.destroy();
@@ -652,7 +630,6 @@ pub fn contextDeclarations(gpa: std.mem.Allocator, path: []const u8, content: []
/// (`parseApart`). `halt` ends the parse and the walk early
/// (error.Canceled): a 1.2 MB file is seconds in a Debug build.
pub fn declarationsApart(gpa: std.mem.Allocator, path: []const u8, content: []const u8, halt: *const std.atomic.Value(bool)) ![]ContextDeclaration {
- if (comptime !enabled) return &.{};
if (content.len == 0) return &.{};
const ext = std.Io.Dir.path.extension(path);
const spec = specs: for (&specs) |*spec| {
@@ -796,7 +773,6 @@ pub fn highlightLocations(gpa: std.mem.Allocator, content: []const u8, start_byt
const start_byte = @min(start_byte_raw, content.len);
const end_byte = @max(start_byte, @min(end_byte_raw, content.len));
const source = content[start_byte..end_byte];
- if (!enabled) return &.{};
const styles = try gpa.alloc(u8, source.len);
errdefer gpa.free(styles);
@memset(styles, 0);
@@ -829,7 +805,7 @@ pub fn highlightLocations(gpa: std.mem.Allocator, content: []const u8, start_byt
/// padded location column. This also colors context whose location is hidden.
/// Consecutive source rows share one parse, retaining multiline syntax.
pub fn highlightLocationRows(gpa: std.mem.Allocator, content: []const u8, rows: []const locations.Row) ![]u8 {
- if (!enabled or content.len == 0 or rows.len == 0) return &.{};
+ if (content.len == 0 or rows.len == 0) return &.{};
const styles = try gpa.alloc(u8, content.len);
errdefer gpa.free(styles);
@memset(styles, 0);
@@ -1111,7 +1087,7 @@ const DiffWindow = struct {
};
fn paintDiffPiece(gpa: std.mem.Allocator, window: DiffWindow, bytes: []const u8, at: usize, kinds: []const diff.Kind, path: []const u8) !void {
- const selected: ?Selected = if (enabled and syntax_started) (forExt(std.Io.Dir.path.extension(path)) catch null) else null;
+ const selected: ?Selected = if (syntax_started) (forExt(std.Io.Dir.path.extension(path)) catch null) else null;
if (selected) |sel| {
const hash = std.hash.Wyhash.hash(std.hash.Wyhash.hash(0, sel.name), bytes);
diff_clock += 1;
@@ -1269,7 +1245,6 @@ test {
}
test "every vendored textobject and indent query compiles against its grammar" {
- if (!enabled) return;
var failed: usize = 0;
for (&specs) |*spec| for ([_]Lazy{ spec.objects, spec.indents }, [_][]const u8{ "textobjects", "indents" }) |lazy, what| {
if (lazy.src.len == 0) continue;
@@ -1285,7 +1260,6 @@ test "every vendored textobject and indent query compiles against its grammar" {
}
test "syntax context nested Zig containers and multiline function signatures" {
- if (!enabled) return;
const gpa = std.testing.allocator;
start(gpa);
defer stop();
@@ -1317,7 +1291,7 @@ test "syntax context nested Zig containers and multiline function signatures" {
}
test "syntax context Python class and function body excludes first statement" {
- if (!enabled or !full_grammars) return;
+ if (!full_grammars) return;
const gpa = std.testing.allocator;
start(gpa);
defer stop();
@@ -1330,7 +1304,6 @@ test "syntax context Python class and function body excludes first statement" {
}
test "syntax context multiline bindings and C++ namespaces preserve declaration starts" {
- if (!enabled) return;
const gpa = std.testing.allocator;
start(gpa);
defer stop();
@@ -1340,7 +1313,7 @@ test "syntax context multiline bindings and C++ namespaces preserve declaration
try std.testing.expectEqual(@as(usize, 1), zig_declarations.len);
try std.testing.expectEqual(@as(usize, 0), zig_declarations[0].start_line);
try std.testing.expectEqual(@as(usize, 1), zig_declarations[0].header_end_line);
- if (!minimal_grammars and !full_grammars) return;
+ if (!minimal_grammars) return;
const cpp_source = "namespace example {\nstruct Outer {\n int run() {\n return 1;\n }\n};\n}\n";
const cpp_declarations = try contextDeclarations(gpa, "nested.cpp", cpp_source);
defer gpa.free(cpp_declarations);
@@ -1352,7 +1325,7 @@ test "syntax context multiline bindings and C++ namespaces preserve declaration
}
test "syntax context Rust modules impls and methods remain nested" {
- if (!enabled or !full_grammars) return;
+ if (!full_grammars) return;
const gpa = std.testing.allocator;
start(gpa);
defer stop();
@@ -1368,7 +1341,7 @@ test "syntax context Rust modules impls and methods remain nested" {
}
test "syntax formatted locations color hidden context and preserve multiline source" {
- if (!enabled or (!minimal_grammars and !full_grammars)) return;
+ if (!minimal_grammars) return;
const gpa = std.testing.allocator;
start(gpa);
defer stop();
@@ -1393,7 +1366,7 @@ test "syntax formatted locations color hidden context and preserve multiline sou
}
test "syntax formatted locations separate alignment from Markdown indentation" {
- if (!enabled or !full_grammars) return;
+ if (!full_grammars) return;
const gpa = std.testing.allocator;
start(gpa);
defer stop();
@@ -1409,7 +1382,6 @@ test "syntax formatted locations separate alignment from Markdown indentation" {
}
test "syntax a results row is coloured by the file its location names" {
- if (!enabled) return;
start(std.testing.allocator);
defer stop();
const gpa = std.testing.allocator;
@@ -1432,7 +1404,6 @@ test "syntax a results row is coloured by the file its location names" {
}
test "syntax a buffer with no locations in it keeps no highlights at all" {
- if (!enabled) return;
start(std.testing.allocator);
defer stop();
const content = "nothing has been said yet\n0: save: AccessDenied (x2)\n";
@@ -1460,7 +1431,7 @@ test "syntax codeAfterLocation takes whole-token locations and nothing else" {
}
test "syntax default full grammar set highlights Typst source" {
- if (!enabled or !full_grammars) return;
+ if (!full_grammars) return;
start(std.testing.allocator);
defer stop();
@@ -1483,7 +1454,7 @@ test "syntax default full grammar set highlights Typst source" {
}
test "syntax Typst markup constructs paint and raw blocks inject their language" {
- if (!enabled or !full_grammars) return;
+ if (!full_grammars) return;
start(std.testing.allocator);
defer stop();
@@ -1527,7 +1498,7 @@ test "syntax Typst markup constructs paint and raw blocks inject their language"
}
test "syntax markdown highlights markup, injects inline spans and fenced code blocks" {
- if (!enabled or !full_grammars) return;
+ if (!full_grammars) return;
start(std.testing.allocator);
defer stop();
@@ -1559,7 +1530,7 @@ test "syntax markdown highlights markup, injects inline spans and fenced code bl
}
test "syntax inline fast path agrees with full Markdown query" {
- if (!enabled or !full_grammars) return;
+ if (!full_grammars) return;
start(std.testing.allocator);
defer stop();
const selected = (try forLang("markdown_inline")).?;
@@ -1606,7 +1577,7 @@ test "syntax inline fast path agrees with full Markdown query" {
}
test "syntax plain Markdown keeps block styles without starting the inline parser" {
- if (!enabled or !full_grammars) return;
+ if (!full_grammars) return;
start(std.testing.allocator);
defer stop();
const source = "# Heading\n\nPlain prose.\n\n indented code\n";
@@ -1648,7 +1619,6 @@ test "syntax highlightDiff colors unified diff lines by prefix" {
}
test "syntax a Zig hunk is coloured as Zig, each side parsed whole" {
- if (!enabled) return;
start(std.testing.allocator);
defer stop();
const diff_text =
@@ -1689,7 +1659,7 @@ test "syntax a Zig hunk is coloured as Zig, each side parsed whole" {
}
test "syntax a Python hunk is coloured as Python" {
- if (!enabled or !full_grammars) return;
+ if (!full_grammars) return;
start(std.testing.allocator);
defer stop();
const diff_text =
@@ -1710,7 +1680,6 @@ test "syntax a Python hunk is coloured as Python" {
}
test "syntax a deleted file's lines are coloured in its language" {
- if (!enabled) return;
start(std.testing.allocator);
defer stop();
const diff_text =
@@ -1730,7 +1699,6 @@ test "syntax a deleted file's lines are coloured in its language" {
}
test "syntax a hunk in no known language keeps the line colours" {
- if (!enabled) return;
start(std.testing.allocator);
defer stop();
const diff_text =
@@ -1747,7 +1715,6 @@ test "syntax a hunk in no known language keeps the line colours" {
}
test "syntax git diff output in a command pane is told and coloured by its rows" {
- if (!enabled) return;
start(std.testing.allocator);
defer stop();
// A command pane's rows: its command line, then git's output, with one
@@ -1780,7 +1747,6 @@ test "syntax git diff output in a command pane is told and coloured by its rows"
}
test "syntax a section's small hunks share one parse" {
- if (!enabled) return;
const gpa = std.testing.allocator;
start(gpa);
defer stop();
@@ -1802,7 +1768,6 @@ test "syntax a section's small hunks share one parse" {
}
test "syntax a hunk painted once is kept, and a long one is parsed in pieces" {
- if (!enabled) return;
const gpa = std.testing.allocator;
start(gpa);
defer stop();
@@ -1832,7 +1797,6 @@ test "syntax a hunk painted once is kept, and a long one is parsed in pieces" {
}
test "syntax result fragments preserve source indentation and inline markup" {
- if (!enabled) return;
start(std.testing.allocator);
defer stop();
const fixtures = [_]struct { path: []const u8, source: []const u8 }{
@@ -1862,7 +1826,6 @@ test "syntax result fragments preserve source indentation and inline markup" {
}
test "syntax query filtering preserves upstream colors" {
- if (!enabled) return;
var allocator: std.heap.DebugAllocator(.{ .stack_trace_frames = 0, .safety = true }) = .init;
defer if (allocator.deinit() != .ok) @panic("leaked syntax query allocations");
start(allocator.allocator());
@@ -1893,7 +1856,6 @@ test "syntax query filtering preserves upstream colors" {
}
test "syntax Zig keyword captures cover both bytes beyond line ten thousand" {
- if (!enabled) return;
start(std.testing.allocator);
defer stop();
const code = "pub fn main() void {\n if (true) return;\n}\n";
@@ -1911,7 +1873,6 @@ test "syntax Zig keyword captures cover both bytes beyond line ten thousand" {
}
test "syntax allocator switching clears default-runtime caches" {
- if (!enabled) return;
const source = "fn main() void {}";
const initial = try highlightFileRange(std.testing.allocator, "a.zig", source, 0, source.len);
std.testing.allocator.free(initial);
@@ -1927,7 +1888,7 @@ test "syntax allocator switching clears default-runtime caches" {
}
test "syntax location context snapshots retain omitted multiline comment scope" {
- if (!enabled or (!minimal_grammars and !full_grammars)) return;
+ if (!minimal_grammars) return;
const gpa = std.testing.allocator;
start(gpa);
defer stop();
@@ -1953,7 +1914,6 @@ test "syntax location context snapshots retain omitted multiline comment scope"
}
test "syntax declaration locations clear snapshots without muting ordinary context" {
- if (!enabled) return;
const gpa = std.testing.allocator;
start(gpa);
defer stop();
@@ -1973,7 +1933,7 @@ test "syntax declaration locations clear snapshots without muting ordinary conte
}
test "syntax stacked addresses do not split multiline source groups" {
- if (!enabled or (!minimal_grammars and !full_grammars)) return;
+ if (!minimal_grammars) return;
const gpa = std.testing.allocator;
start(gpa);
defer stop();
@@ -1998,7 +1958,6 @@ test "syntax stacked addresses do not split multiline source groups" {
}
test "syntax source analysis preserves declarations and injected colors" {
- if (!enabled) return;
const gpa = std.testing.allocator;
start(gpa);
defer stop();
@@ -2059,7 +2018,7 @@ test "syntax source analysis preserves declarations and injected colors" {
}
test "tables are the pipe_tables tree-sitter finds" {
- if (!enabled or !full_grammars) return;
+ if (!full_grammars) return;
start(std.testing.allocator);
defer stop();
const Tables = @import("Tables.zig");
@@ -2128,7 +2087,6 @@ test "tables are the pipe_tables tree-sitter finds" {
}
test "a kept tree told its edits parses to the fresh parse's tree, places and all" {
- if (!enabled) return error.SkipZigTest;
const gpa = std.testing.allocator;
const a = "const std = @import(\"std\");\n\nfn f(x: u32) u32 {\n return x;\n}\n\ntest \"t\" {\n _ = f(1);\n}\n";
const old_tree = parseTree("a.zig", a, null) orelse return error.NoTree;
@@ -2168,7 +2126,6 @@ test "a kept tree told its edits parses to the fresh parse's tree, places and al
}
test "syntax: a grammar handed in at run time colours and walks as the one compiled in" {
- if (!enabled) return error.SkipZigTest;
const gpa = std.testing.allocator;
start(gpa);
defer stop();
diff --git a/core/tape.zig b/core/tape.zig
index 34c9f1da..09985d15 100644
--- a/core/tape.zig
+++ b/core/tape.zig
@@ -160,7 +160,7 @@ pub const results = .{
// Recent's entry for a closed jump, the closed panes' names.
?@import("Store.zig").Record,
?@import("recent.zig").Entry, []const @import("Store.zig").Named,
- @import("Kind.zig").Outcome,
+ @import("Kind.zig").Outcome, pardes.Term.Prompt,
};
/// What a host reports to the core as failed (`shell_failed`, `save_failed`,
diff --git a/dev/Inbox.zig b/dev/Inbox.zig
index aac1f7a1..d733b971 100644
--- a/dev/Inbox.zig
+++ b/dev/Inbox.zig
@@ -47,8 +47,12 @@ pub const Msg = union(enum) {
}
};
-pub const capacity = 512;
-pub const output_capacity = capacity - pardes.MAX_PANES;
+/// The ring's room: output up to `output_capacity` (a reader waits for
+/// more), an Adopt's shells beyond it (one note's: never lost to a flood),
+/// and each pane's end of file beyond those (lost to neither).
+pub const output_capacity = 512 - pardes.MAX_PANES;
+const adopt_capacity = output_capacity + pardes.MAX_PANES + 1;
+pub const capacity = adopt_capacity + pardes.MAX_PANES;
pub const Batch = struct {
items: [capacity + 2 * selection_pipe.Tasks.capacity + 2]Msg = undefined,
@@ -63,6 +67,11 @@ gpa: std.mem.Allocator,
lsp_allocator: std.mem.Allocator,
/// The query in flight; the UI thread's alone (spawnLsp, teardown).
lsp_task: ?Lsp.Task = null,
+/// The `|` pipes' and the addons' jobs' and draws' workers in flight, each
+/// posting its answer here (`pushPipe`, `pushJob`); the loop's thread's
+/// alone: joined as their answers land (`land`), canceled at the end.
+pipe_tasks: selection_pipe.Tasks = .{},
+job_tasks: selection_pipe.Tasks = .{},
/// Wakes the host's loop after a push from another thread: an SDL
/// event, a macOS runtime callback. Null: nobody to wake (tests).
wake_fn: ?*const fn (?*anyopaque) void = null,
@@ -77,6 +86,11 @@ len: usize = 0,
closed: bool = false,
files_changed: bool = false,
readers: [pardes.MAX_PANES]?u32 = @splat(null),
+/// Each pane's reads read out of its pty and not yet applied (`applied`):
+/// a command's exit is told only once none is (Ptys.unapplied), since
+/// the poll that asks whether its output is in (CommandWatch.due) cannot
+/// see a read the reader holds or the queue does.
+unapplied: [pardes.MAX_PANES]std.atomic.Value(u32) = @splat(.init(0)),
waiting: usize = 0,
lsp_id: ?u32 = null,
completions: [2 * selection_pipe.Tasks.capacity + 1]Msg = undefined,
@@ -101,6 +115,12 @@ pub fn acceptReader(q: *Inbox, pane: pardes.Pane.Id, gen: u32) void {
q.readers[pane.index()] = gen;
}
+/// One of `pane`'s reads applied, or dropped unapplied.
+pub fn applied(q: *Inbox, pane: pardes.Pane.Id) void {
+ const n = &q.unapplied[pane.index()];
+ if (n.load(.acquire) > 0) _ = n.fetchSub(1, .acq_rel);
+}
+
pub fn cancelReader(q: *Inbox, pane: pardes.Pane.Id, gen: u32) void {
q.lock();
defer q.unlock();
@@ -114,7 +134,10 @@ pub fn cancelReader(q: *Inbox, pane: pardes.Pane.Id, gen: u32) void {
.eof => |e| e.pane == pane and e.gen == gen,
else => false,
};
- if (matches) q.removeAt(i).deinit(q.gpa, q.lsp_allocator) else i += 1;
+ if (matches) {
+ if (msg == .output) q.applied(pane);
+ q.removeAt(i).deinit(q.gpa, q.lsp_allocator);
+ } else i += 1;
}
q.space.broadcast(q.io);
}
@@ -189,7 +212,7 @@ pub fn push(q: *Inbox, m: Msg) void {
return;
}
std.debug.assert(q.len < q.items.len);
- } else if (q.len >= output_capacity) {
+ } else if (q.len >= @as(usize, if (m == .adopted) adopt_capacity else output_capacity)) {
q.unlock();
m.deinit(q.gpa, q.lsp_allocator);
return;
@@ -262,9 +285,11 @@ pub fn close(q: *Inbox) void {
}
pub fn deinit(q: *Inbox) void {
- // The query in flight ends first: what it still delivers is dropped.
+ // The workers in flight end first: what they still deliver is dropped.
if (q.lsp_task) |*t| t.future.cancel(q.io);
q.lsp_task = null;
+ q.pipe_tasks.cancelAll(q.io);
+ q.job_tasks.cancelAll(q.io);
q.close();
std.debug.assert(q.waiting == 0);
}
@@ -291,11 +316,14 @@ fn readPty(q: *Inbox, pty: std.Io.File, pane: pardes.Pane.Id, gen: u32) void {
},
};
if (n == 0) continue;
+ // Counted at once: out of the pty, the poll no longer sees it.
+ _ = q.unapplied[pane.index()].fetchAdd(1, .acq_rel);
const bytes = q.gpa.dupe(u8, buf[0..n]) catch |err| {
+ q.applied(pane);
failure = err;
break;
};
- if (!q.pushOutput(pane, gen, bytes)) return;
+ if (!q.pushOutput(pane, gen, bytes)) return q.applied(pane);
}
q.push(.{ .eof = .{ .pane = pane, .gen = gen, .failure = failure } });
}
@@ -311,9 +339,10 @@ pub fn startLsp(q: *Inbox, core: *pardes.Pardes, e: Lsp.Request) void {
Lsp.start(q.io, q.lsp_allocator, core, &q.lsp_task, e, q, pushLspRows);
}
-/// A language server's answer or status line taken off the queue, to the
-/// core (whichever frontend took it).
-pub fn landLsp(q: *Inbox, core: *pardes.Pardes, m: Msg) void {
+/// A worker's answer taken off the queue, to the core (whichever frontend
+/// took it), its worker joined: a language server's answer or status line,
+/// a pipe's, a search's rows, an addon's job or draw, a handover's end.
+pub fn land(q: *Inbox, core: *pardes.Pardes, m: Msg) void {
switch (m) {
.lsp => |l| {
core.update(.{ .lsp_resp = .{ .id = l.id, .rows = l.rows } });
@@ -324,7 +353,30 @@ pub fn landLsp(q: *Inbox, core: *pardes.Pardes, m: Msg) void {
core.setStatus(.at(core.view().active), pardes.Messages.Message.stamp(&mbuf, "lsp", text));
q.lsp_allocator.free(text);
},
- else => unreachable,
+ .pipe => |response_value| {
+ var response = response_value;
+ core.update(.{ .pipe_resp = .{
+ .id = response.id,
+ .success = response.success,
+ .outputs = response.outputs,
+ .failure = response.failure,
+ } });
+ response.deinit(q.gpa);
+ q.pipe_tasks.finish(q.io, response_value.id);
+ },
+ .search => |b| {
+ core.update(.{ .search = b });
+ b.deinit(q.gpa);
+ },
+ .kind_job => |j| {
+ q.job_tasks.finish(q.io, j.id);
+ j.land(core);
+ },
+ .handed => |h| {
+ core.update(.{ .handed = .{ .seq = h.seq, .to = if (h.ok) h.words else "", .failure = if (h.ok) null else h.words } });
+ q.gpa.free(h.words);
+ },
+ .output, .eof, .files_changed, .fs_ready, .adopted => unreachable,
}
}
@@ -340,12 +392,13 @@ pub fn lspStatus(ctx: ?*anyopaque, text: []const u8) void {
q.push(.{ .lsp_status = copy });
}
-/// A `|` job's answer (selection_pipe.start's sink).
+/// An addon's job or draw done (KindJob.go's sink).
pub fn pushJob(ctx: ?*anyopaque, j: *KindJob) void {
const q: *Inbox = @ptrCast(@alignCast(ctx.?));
q.push(.{ .kind_job = j });
}
+/// A `|` pipe's answer (selection_pipe.start's sink).
pub fn pushPipe(ctx: ?*anyopaque, response: selection_pipe.Response) void {
const q: *Inbox = @ptrCast(@alignCast(ctx.?));
q.push(.{ .pipe = response });
diff --git a/dev/Ptys.zig b/dev/Ptys.zig
index 16a31939..583e3c38 100644
--- a/dev/Ptys.zig
+++ b/dev/Ptys.zig
@@ -180,6 +180,7 @@ pub fn close(p: *Ptys, id: pardes.Pane.Id) void {
/// A reader's read, off the queue (freed here).
pub fn output(p: *Ptys, core: *pardes.Pardes, o: @FieldType(Inbox.Msg, "output")) void {
defer p.queue.gpa.free(o.bytes);
+ defer p.queue.applied(o.pane);
if (p.gens[o.pane.index()] == o.gen) core.update(.{ .output = .{ .pane = o.pane, .bytes = o.bytes } });
}
@@ -213,6 +214,11 @@ pub fn takeExits(p: *Ptys, core: *pardes.Pardes) void {
host_io.takeExits(core, &p.slots, p, closeWatched);
}
+/// Whether pane `id` has reads not yet applied (host_io.takeExits).
+pub fn unapplied(p: *const Ptys, id: usize) bool {
+ return p.queue.unapplied[id].load(.acquire) > 0;
+}
+
fn closeWatched(p: *Ptys, id: usize) void {
p.close(.at(id));
}
@@ -401,3 +407,31 @@ test "a post of an older generation is passed over" {
try std.testing.expect(std.mem.indexOf(u8, text, "old session") == null);
try std.testing.expect(std.mem.indexOf(u8, text, "current session") != null);
}
+
+test "a command's exit is told after its output a reader read, however long that waits in the queue" {
+ const gpa = std.testing.allocator;
+ const core = try pardes.Pardes.init(gpa, .{ .tty_only = true });
+ defer core.deinit();
+ var queue: Inbox = .{ .io = std.testing.io, .gpa = gpa, .lsp_allocator = gpa };
+ defer queue.deinit();
+ var p = testing(&queue);
+ defer p.deinit();
+ // A command done (reaped), its pty held open by what it left running
+ // (the pipe's write end): no end of file, and no output in the kernel
+ // once the reader has read it.
+ var fds: [2]c_int = undefined;
+ if (libc.pipe(&fds) != 0) return error.PipeFailed;
+ defer _ = libc.close(fds[1]);
+ p.slots[0] = .{ .fd = fds[0], .pid = 0, .cmd = .{ .watched = true, .fd = fds[0], .exited = true, .status = 0 } };
+ p.slots[0].?.reader = try queue.startReader(.{ .handle = fds[0], .flags = .{ .nonblocking = false } }, .at(0), p.gens[0]);
+ try std.testing.expect(host_io.writeFd(fds[1], "LAST"));
+ const until = std.Io.Clock.awake.now(std.testing.io).toMilliseconds() + 2_000;
+ while (queue.len == 0 and std.Io.Clock.awake.now(std.testing.io).toMilliseconds() < until) try std.testing.io.sleep(.fromMilliseconds(1), .awake);
+ try std.testing.expectEqual(@as(usize, 1), queue.len);
+ p.takeExits(core);
+ try std.testing.expect(!p.slots[0].?.cmd.told);
+ var batch = queue.take();
+ for (batch.slice()) |msg| p.output(core, msg.output);
+ p.takeExits(core);
+ try std.testing.expect(p.slots[0].?.cmd.told);
+}
diff --git a/dev/file_watch.zig b/dev/file_watch.zig
index 58229d90..c575f436 100644
--- a/dev/file_watch.zig
+++ b/dev/file_watch.zig
@@ -761,7 +761,7 @@ pub fn identify(io: std.Io, path: []const u8) !Identity {
}
test "a restored file is watched again: one clean takes what its file became since the dump, one unsaved keeps its text" {
- if (comptime !supported or !filesystem.platform_has_fs) return;
+ if (comptime !supported) return;
const io = std.testing.io;
const gpa = std.testing.allocator;
for ([_]bool{ false, true }) |dirty| {
@@ -803,7 +803,7 @@ test "a restored file is watched again: one clean takes what its file became sin
}
test "a Zerox twin's save wakes its other twin's watch, which says nothing: their text is the file's already" {
- if (comptime !supported or !filesystem.platform_has_fs) return;
+ if (comptime !supported) return;
const io = std.testing.io;
var tmp = std.testing.tmpDir(.{});
defer tmp.cleanup();
@@ -835,7 +835,7 @@ test "a Zerox twin's save wakes its other twin's watch, which says nothing: thei
}
test "ordinary file watches still reconcile changes between open and watch" {
- if (comptime !supported or !filesystem.platform_has_fs) return;
+ if (comptime !supported) return;
const io = std.testing.io;
const gpa = std.testing.allocator;
var tmp = std.testing.tmpDir(.{});
@@ -870,7 +870,7 @@ test "ordinary file watches still reconcile changes between open and watch" {
}
test "a kind's pane whose file changed between its open and its watch opens again from it" {
- if (comptime !supported or !filesystem.platform_has_fs) return;
+ if (comptime !supported) return;
const io = std.testing.io;
const gpa = std.testing.allocator;
var tmp = std.testing.tmpDir(.{});
@@ -899,7 +899,7 @@ test "a kind's pane whose file changed between its open and its watch opens agai
}
test "explicit OS directory watches refresh prefix-preserving listings" {
- if (comptime !supported or !filesystem.platform_has_fs) return;
+ if (comptime !supported) return;
const gpa = std.testing.allocator;
const core = try pardes.Pardes.init(gpa, .{ .tty_only = true });
defer core.deinit();
@@ -1012,7 +1012,7 @@ test "theme watch reloads valid ZON and keeps the last theme across a bad save"
}
test "a watched file deleted wakes the watch at once, and its pane says so" {
- if (comptime !supported or !filesystem.platform_has_fs or builtin.os.tag != .linux) return;
+ if (comptime !supported or builtin.os.tag != .linux) return;
const io = std.testing.io;
const gpa = std.testing.allocator;
var tmp = std.testing.tmpDir(.{});
@@ -1045,7 +1045,7 @@ test "a watched file deleted wakes the watch at once, and its pane says so" {
}
test "a session's watches: a marked file's change posted to the queue, the reader ended at the end" {
- if (comptime !supported or !filesystem.platform_has_fs) return;
+ if (comptime !supported) return;
const io = std.testing.io;
const gpa = std.testing.allocator;
var tmp = std.testing.tmpDir(.{});
diff --git a/dev/gui/gui.zig b/dev/gui/gui.zig
index ab33abe9..521f685f 100644
--- a/dev/gui/gui.zig
+++ b/dev/gui/gui.zig
@@ -379,7 +379,6 @@ fn sdlWake(_: ?*anyopaque) void {
sev.type = c.SDL_EVENT_USER;
_ = c.SDL_PushEvent(&sev);
}
-const PipeTasks = selection_pipe.Tasks;
const output_capacity = Queue.output_capacity;
const Gui = struct {
@@ -991,7 +990,6 @@ const Own = struct {
g: *Gui,
test_mode: bool,
detached: bool,
- pipe_tasks: PipeTasks = .{},
shell: Shell = undefined,
const Session = session_loop.Loop(Own);
@@ -1024,7 +1022,6 @@ const Own = struct {
.lsp_allocator = l.allocs.lsp,
.ptys = &l.ptys,
.queue = &l.inbox,
- .pipe_tasks = &o.pipe_tasks,
.watches = &l.watches,
.fs = l.fs,
.test_mode = o.test_mode,
@@ -1044,15 +1041,10 @@ const Own = struct {
return host;
}
- pub fn close(o: *Own, l: *Session) void {
- const io = l.io;
+ pub fn close(o: *Own, _: *Session) void {
o.shell.fs = null;
host_io.setExitWake(null, null);
pardes.Kind.drawer = null;
- o.shell.job_tasks.cancelAll(io);
- o.pipe_tasks.cancelAll(io);
- // Its worker may be waiting on the queue for room.
- l.core.stream.cancelTask();
o.g.hit_core = null;
}
@@ -1079,12 +1071,7 @@ const Own = struct {
if (o.shell.upgrade_asked) |pane| o.shell.upgradeNow(pane);
}
- pub fn note(o: *Own, n: daemon.Note) void {
- deliverNote(&o.shell, n);
- }
-
pub fn restoring(o: *Own, nc: *pardes.Pardes) void {
- o.pipe_tasks.cancelAll(o.shell.io);
// One view, the window's (host_io.restoreCore).
o.shell.gview = 0;
o.g.cells.clearImages();
@@ -1356,7 +1343,7 @@ const Client = struct {
defer cl.lock.unlock(cl.io);
for (cl.inbox.items) |msg| switch (msg) {
.unit, .screen, .refused, .blob => |b| std.heap.c_allocator.free(b),
- .checked => {},
+ .checked, .ended, .left => {},
};
cl.inbox.clearRetainingCapacity();
}
@@ -1415,7 +1402,6 @@ fn clientSession(init: std.process.Init, g: *Gui, opts_in: pardes.Options, test_
var queue: Queue = .{ .io = io, .gpa = gpa, .lsp_allocator = start.allocs.lsp, .wake_fn = sdlWake };
defer queue.deinit();
var ptys: host_io.Ptys = .{ .queue = &queue, .prompt_rcs = undefined };
- var pipe_tasks: PipeTasks = .{};
var no_watches: file_watch.Watches = .{ .io = io, .gpa = gpa, .queue = &queue };
var no_peers: replica.Peers = .{};
var shell: Shell = .{
@@ -1426,7 +1412,6 @@ fn clientSession(init: std.process.Init, g: *Gui, opts_in: pardes.Options, test_
.lsp_allocator = start.allocs.lsp,
.ptys = &ptys,
.queue = &queue,
- .pipe_tasks = &pipe_tasks,
.watches = &no_watches,
.test_mode = test_mode,
.client = &window,
@@ -1435,7 +1420,6 @@ fn clientSession(init: std.process.Init, g: *Gui, opts_in: pardes.Options, test_
window.shell = &shell;
pardes.Kind.drawer = .{ .ctx = &shell, .go = kindDraw };
defer pardes.Kind.drawer = null;
- defer shell.job_tasks.cancelAll(io);
g.no_blink = test_mode;
defer g.hit_core = null;
_ = c.SDL_StartTextInput(g.window);
@@ -1444,6 +1428,22 @@ fn clientSession(init: std.process.Init, g: *Gui, opts_in: pardes.Options, test_
.done => {},
.gone => Said.no(io, "'{s}' let this client go (a Detach in it, or the session's end)", .{to.session}),
.failed => Said.no(io, "{s}", .{start.said()}),
+ // A new process's window: the build at its start path, exec'd.
+ .upgrade => |view| Said.no(io, "{s}", .{client_loop.execAgain(&start, view)}),
+ .left => {
+ var said: [600]u8 = undefined;
+ std.Io.File.stderr().writeStreamingAll(io, std.fmt.bufPrint(&said, "pardes-gui: detached from '{s}', which is still running; come back with `pardes-gui attach {s}`\n", .{ to.session, to.session }) catch "pardes-gui: detached\n") catch {};
+ std.process.exit(0);
+ },
+ .ended => |code| {
+ // A pair's window is its session's parent: its status once it
+ // is gone, as the terminal's (tui.zig `runClient`).
+ if (opts_in.pair != null) {
+ var status: c_int = 0;
+ while (libc.waitpid(@intCast(start.joined.pid), &status, 0) < 0 and libc.errno(-1) == .INTR) {}
+ }
+ std.process.exit(code);
+ },
}
}
@@ -1495,6 +1495,7 @@ const StdinFeed = struct {
// so a driver exercises the real pointer path (pixel to cell,
// tag and body hits). SGR mouse carries only cells.
// finger;<kind>;<id>;<x>;<y>;<pressure>
+ // close: the window's close button
// One the read cut short, or what may yet begin one, waits for
// the next read.
const rest = f.buf[seq_start..len];
@@ -1558,6 +1559,12 @@ const StdinFeed = struct {
dispatch(gp, in, &sev);
c.SDL_SetModState(before);
}
+ } else if (std.mem.eql(u8, event[0..semi], "close")) {
+ if (g) |gp| {
+ var sev = std.mem.zeroes(c.SDL_Event);
+ sev.type = c.SDL_EVENT_WINDOW_CLOSE_REQUESTED;
+ dispatch(gp, in, &sev);
+ }
} else if (std.mem.eql(u8, event[0..semi], "finger")) {
if (parseFinger(fields)) |finger| if (g) |gp| {
var wpw: c_int = 0;
@@ -1738,6 +1745,8 @@ const Input = struct {
fn close(in: *Input) void {
if (in.client) |r| {
+ // Its bye says so: a pair's session ends at its last client's.
+ r.loop.link.close = true;
r.loop.link.quit = true;
in.quit = true;
return;
@@ -2351,8 +2360,6 @@ const Shell = struct {
queue: *Queue,
/// What drainQueue takes each wakeup, kept rather than rebuilt.
batch: Queue.Batch = .{},
- pipe_tasks: *PipeTasks,
- job_tasks: PipeTasks = .{},
/// The session's file watches (runtime/session.zig's); a client's,
/// none.
watches: *file_watch.Watches,
@@ -2561,10 +2568,7 @@ const Shell = struct {
fn takeDraws(s: *Shell) bool {
s.queue.takeInto(&s.batch);
for (s.batch.slice()) |m| switch (m) {
- .kind_job => |j| {
- s.job_tasks.finish(s.io, j.id);
- j.land(s.core);
- },
+ .kind_job => s.queue.land(s.core, m),
else => m.deinit(s.gpa, s.lsp_allocator),
};
return s.batch.slice().len > 0;
@@ -2580,33 +2584,10 @@ const Shell = struct {
for (msgs.slice()) |m| switch (m) {
.output => |o| s.ptys.output(s.core, o),
.eof => |e| s.ptys.eof(s.core, e),
- .lsp, .lsp_status => s.queue.landLsp(s.core, m),
- .pipe => |response_value| {
- var response = response_value;
- s.core.update(.{ .pipe_resp = .{
- .id = response.id,
- .success = response.success,
- .outputs = response.outputs,
- .failure = response.failure,
- } });
- response.deinit(s.gpa);
- s.pipe_tasks.finish(s.io, response_value.id);
- },
- .search => |b| {
- s.core.update(.{ .search = b });
- b.deinit(s.gpa);
- },
- .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);
- },
- .kind_job => |j| {
- s.job_tasks.finish(s.io, j.id);
- j.land(s.core);
- },
.files_changed => check_files = true,
.fs_ready => {},
.adopted => |a| s.ptys.adoptions.adoptShell(s.core, a.pid, a.fd),
+ else => s.queue.land(s.core, m),
};
if (check_files) s.watches.reload(s.core);
}
@@ -3113,21 +3094,6 @@ fn guiNow(ctx: ?*anyopaque) u64 {
return s.test_clock orelse s.paced_ns orelse c.SDL_GetTicksNS();
}
-/// The daemon's thread: what it says, onto the queue (drainQueue).
-fn deliverNote(ctx: *anyopaque, note: daemon.Note) void {
- const s: *Shell = @ptrCast(@alignCast(ctx));
- const q = s.queue;
- switch (note) {
- .relinked => q.wake(),
- .adopted => |a| {
- for (a.pids[0..a.n], a.fds[0..a.n]) |pid, fd| q.push(.{ .adopted = .{ .pid = pid, .fd = fd } });
- q.push(.{ .adopted = .{ .pid = 0, .fd = -1 } });
- },
- // Joined at the next step boundary (Peers, any thread).
- .replica => |j| s.peers.handed(j.fd, j.view),
- }
-}
-
fn writeDump(ctx: ?*anyopaque, bytes: []const u8) void {
host_io.writeDump(shellOf(ctx).core, bytes);
}
@@ -3178,7 +3144,7 @@ fn lsp(ctx: ?*anyopaque, req: host_io.Lsp.Request) void {
fn pipe(ctx: ?*anyopaque, id: u32) void {
const s = shellOf(ctx);
- if (s.threads_ok) return selection_pipe.start(s.io, s.gpa, s.core, s.pipe_tasks, id, s.queue, Queue.pushPipe);
+ if (s.threads_ok) return selection_pipe.start(s.io, s.gpa, s.core, &s.queue.pipe_tasks, id, s.queue, Queue.pushPipe);
s.core.update(.{ .pipe_resp = .{ .id = id, .success = false, .outputs = &.{} } });
s.core.reportError(.at(s.core.view().active), "pipe", error.WorkersUnavailable);
}
@@ -3186,13 +3152,13 @@ fn pipe(ctx: ?*anyopaque, id: u32) void {
/// A draw (api.draw) on a worker, as a job is.
fn kindDraw(ctx: ?*anyopaque, j: *host_io.KindJob) bool {
const s = shellOf(ctx);
- return (s.threads_ok or s.client != null) and host_io.KindJob.go(s.io, &s.job_tasks, j, s.queue, Queue.pushJob);
+ return (s.threads_ok or s.client != null) and host_io.KindJob.go(s.io, &s.queue.job_tasks, j, s.queue, Queue.pushJob);
}
fn kindJob(ctx: ?*anyopaque, id: pardes.Pane.Id, serial: u32, token: u32) void {
const pane = id.index();
const s = shellOf(ctx);
- if (s.threads_ok) return host_io.KindJob.start(s.io, s.core, &s.job_tasks, pane, serial, token, s.queue, Queue.pushJob);
+ if (s.threads_ok) return host_io.KindJob.start(s.io, s.core, &s.queue.job_tasks, pane, serial, token, s.queue, Queue.pushJob);
host_io.KindJob.runHere(s.core, pane, serial, token);
}
@@ -5976,7 +5942,6 @@ test "GUI worker setup failures finish matching LSP and pipe requests" {
.lsp_allocator = failing.allocator(),
};
defer queue.deinit();
- var tasks: PipeTasks = .{};
core.lspRequest(core.view().active, .status, "");
const req: host_io.Lsp.Request = .{
.id = core.lsp_ask.wait.?.id,
@@ -6008,11 +5973,11 @@ test "GUI worker setup failures finish matching LSP and pipe requests" {
core.update(.{ .key = .{ .cp = 't', .text = "tr a-z A-Z" } });
core.update(.{ .key = .{ .cp = pardes.Key.enter } });
const pipe_id = core.pipe.wait.?.id;
- selection_pipe.start(failing_io, failing.allocator(), core, &tasks, pipe_id, &queue, Queue.pushPipe);
+ selection_pipe.start(failing_io, failing.allocator(), core, &queue.pipe_tasks, pipe_id, &queue, Queue.pushPipe);
try std.testing.expect(core.pipe.wait == null);
try std.testing.expectEqualStrings("abc", pane.file.?.content);
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.pipe_tasks.len);
try std.testing.expectEqual(@as(usize, 0), queue.len);
}
}
@@ -7676,9 +7641,8 @@ test "a detached GUI authority follows terminal directory changes with no window
const rcs: host_io.Shell.PromptFiles = .{};
var ptys: host_io.Ptys = .{ .queue = &queue, .prompt_rcs = &rcs, .gens = @splat(1) };
defer ptys.deinit();
- var pipes: PipeTasks = .{};
var no_peers: replica.Peers = .{};
- var shell: Shell = .{ .core = core, .io = io, .gpa = gpa, .lsp_allocator = gpa, .ptys = &ptys, .queue = &queue, .pipe_tasks = &pipes, .watches = undefined, .peers = &no_peers };
+ var shell: Shell = .{ .core = core, .io = io, .gpa = gpa, .lsp_allocator = gpa, .ptys = &ptys, .queue = &queue, .watches = undefined, .peers = &no_peers };
const child = try host_io.forkShell(null, 0, &rcs, "/bin/sh", start, 24, 80);
ptys.slots[0] = .{ .fd = child.file.handle, .pid = child.pid };
try std.testing.expect(host_io.writeFd(child.file.handle, "cd child\n"));
diff --git a/dev/host_io.zig b/dev/host_io.zig
index 5465fc7a..a22bf5ce 100644
--- a/dev/host_io.zig
+++ b/dev/host_io.zig
@@ -1105,6 +1105,8 @@ pub fn takeExits(core: *pardes.Pardes, ptys: anytype, ctx: anytype, comptime clo
for (ptys, 0..) |*slot, id| {
const pt = slotPty(slot) orelse continue;
if (!pt.cmd.watched or !pt.cmd.due()) continue;
+ // Its output read and not yet applied (a host whose reader counts).
+ if (comptime @hasDecl(@TypeOf(ctx.*), "unapplied")) if (!pt.cmd.eof and ctx.unapplied(id)) continue;
pt.cmd.told = true;
const eof = pt.cmd.eof;
core.update(.{ .exited = .{ .pane = .at(id), .status = pt.cmd.status } });
@@ -2265,11 +2267,62 @@ test "PTY EOF reserve cannot evict terminal output" {
for (0..pardes.MAX_PANES) |pane| queue.push(.{ .eof = .{ .pane = .at(pane), .gen = 1 } });
var batch = queue.take();
defer for (batch.slice()) |msg| msg.deinit(gpa, gpa);
- try std.testing.expectEqual(Inbox.capacity, batch.len);
+ try std.testing.expectEqual(Inbox.output_capacity + pardes.MAX_PANES, batch.len);
for (batch.items[0..Inbox.output_capacity]) |msg| try std.testing.expectEqualStrings("before", msg.output.bytes);
for (batch.items[Inbox.output_capacity..batch.len], 0..) |msg, pane| try std.testing.expectEqual(pane, msg.eof.pane.index());
}
+test "a search's rows posted into a full queue wait for room: a take lets them in, a cancel ends the wait and frees them" {
+ const gpa = std.testing.allocator;
+ const io = std.testing.io;
+ var queue: Inbox = .{ .io = io, .gpa = gpa, .lsp_allocator = gpa };
+ defer queue.deinit();
+ queue.acceptReader(.at(0), 1);
+ const Post = struct {
+ fn run(q: *Inbox, posted: *?bool) void {
+ const rows = std.testing.allocator.dupe(u8, "a.txt:1:1-2 hit\n") catch return;
+ posted.* = Inbox.pushSearch(q, .{ .gen = 1, .rows = rows });
+ }
+ };
+ for ([_]bool{ false, true }) |cancel| {
+ // The loop busy: its queue full of output.
+ for (0..Inbox.output_capacity) |_| queue.push(.{ .output = .{ .pane = .at(0), .gen = 1, .bytes = try gpa.dupe(u8, "busy") } });
+ var posted: ?bool = null;
+ var worker = try io.concurrent(Post.run, .{ &queue, &posted });
+ try PtyTests.waitBlocked(&queue);
+ if (cancel) worker.cancel(io) else {
+ var batch = queue.take();
+ for (batch.slice()) |msg| msg.deinit(gpa, gpa);
+ worker.await(io);
+ }
+ try std.testing.expectEqual(!cancel, posted.?);
+ var rest = queue.take();
+ defer for (rest.slice()) |msg| msg.deinit(gpa, gpa);
+ try std.testing.expectEqual(@as(usize, if (cancel) Inbox.output_capacity else 1), rest.len);
+ if (!cancel) try std.testing.expectEqualStrings("a.txt:1:1-2 hit\n", rest.items[0].search.rows);
+ try std.testing.expectEqual(@as(usize, 0), queue.waiting);
+ }
+}
+
+test "an Adopt's shells are taken in whatever output fills the queue" {
+ const gpa = std.testing.allocator;
+ var queue: Inbox = .{ .io = std.testing.io, .gpa = gpa, .lsp_allocator = gpa };
+ defer queue.deinit();
+ queue.acceptReader(.at(0), 1);
+ for (0..Inbox.output_capacity) |_| queue.push(.{ .output = .{ .pane = .at(0), .gen = 1, .bytes = try gpa.dupe(u8, "flood") } });
+ var fds: [2]c_int = undefined;
+ if (libc.pipe(&fds) != 0) return error.PipeFailed;
+ defer _ = libc.close(fds[1]);
+ queue.push(.{ .adopted = .{ .pid = 42, .fd = fds[0] } });
+ queue.push(.{ .adopted = .{ .pid = 0, .fd = -1 } });
+ var batch = queue.take();
+ defer for (batch.slice()) |msg| msg.deinit(gpa, gpa);
+ try std.testing.expectEqual(Inbox.output_capacity + 2, batch.len);
+ try std.testing.expectEqual(@as(libc.pid_t, 42), batch.items[Inbox.output_capacity].adopted.pid);
+ try std.testing.expectEqual(fds[0], batch.items[Inbox.output_capacity].adopted.fd);
+ try std.testing.expectEqual(@as(libc.pid_t, 0), batch.items[Inbox.output_capacity + 1].adopted.pid);
+}
+
test "completions retain their arrival order across LSP and pipes" {
const gpa = std.testing.allocator;
var queue: Inbox = .{ .io = std.testing.io, .gpa = gpa, .lsp_allocator = gpa, .lsp_id = 2 };
diff --git a/dev/tui/tui.zig b/dev/tui/tui.zig
index 543be3aa..72028b04 100644
--- a/dev/tui/tui.zig
+++ b/dev/tui/tui.zig
@@ -97,15 +97,14 @@ fn kittyShmProbe(w: *std.Io.Writer, feed: *Feed) void {
w.flush() catch {};
}
-/// What the loop's queue carries: a terminal's input, a pane's output, a
-/// worker's answer, a wake.
+/// What the loop's queue carries: a terminal's input, a wake, what a
+/// replica client's reader hands over. A pane's output, a worker's answer
+/// and the daemon's notes are the session's queue's (Inbox, `takeQueue`).
const Msg = union(enum) {
nop,
/// The terminal's input ended: its end of file, a hangup. A session
/// a daemon keeps carries on detached; any other ends.
quit,
- /// A shell a dead session left, its pty's master (daemon.Note.adopted).
- adopted: struct { pid: posix.pid_t, fd: posix.fd_t },
/// A timed wait ran out: the core's next wake has come.
wake,
/// A SIGWINCH: a terminal changed size (Shell.winched).
@@ -120,14 +119,7 @@ const Msg = union(enum) {
paste: []const u8,
paste_start,
paste_end,
- pipe_done: selection_pipe.Response,
- /// A streaming search's rows (pardes.Stream).
- search_rows: pardes.Stream.Batch,
- /// A kind's job done on a worker (host_io.KindJob).
- kind_job: *host_io.KindJob,
fs_ready,
- /// A replica's connection, handed over by the daemon (Peers).
- replica: daemon.Joining,
/// A replica's reader posted: the step boundary takes it in.
replica_mail,
/// A replica client's: what the session streamed (replica.Link).
@@ -369,8 +361,6 @@ const TestReader = struct {
}
};
-const PipeTasks = selection_pipe.Tasks;
-
/// A watched child exited: wake the loop, which takes it (`takeExits`).
fn wakeForExit(ctx: ?*anyopaque) void {
const loop: *Loop = @ptrCast(@alignCast(ctx.?));
@@ -710,7 +700,7 @@ const Tty = struct {
while (t.loop.tryEvent() catch null) |ev| switch (ev) {
.said => |msg| switch (msg) {
.unit, .screen, .refused, .blob => |b| std.heap.c_allocator.free(b),
- .checked => {},
+ .checked, .ended, .left => {},
},
.paste => |b| t.sh.gpa.free(@constCast(b)),
else => {},
@@ -760,7 +750,7 @@ pub fn runClient(init: std.process.Init, opts: pardes.Options, path: []const u8,
var c = try Client.init(&tty, &start);
defer c.link.deinit(gpa);
// A client has no clients of its own, and spawns nothing: its pty
- // table an empty one over an empty queue.
+ // table an empty one over a queue that carries its draws alone.
var no_peers: replica.Peers = .{};
var no_inbox: host_io.Inbox = .{ .io = io, .gpa = gpa, .lsp_allocator = start.allocs.lsp };
defer no_inbox.deinit();
@@ -783,6 +773,8 @@ pub fn runClient(init: std.process.Init, opts: pardes.Options, path: []const u8,
.ptys = &no_ptys,
};
tty = .{ .sh = &sh, .screen = &screen, .loop = &loop, .joins = &start };
+ no_inbox.wake_fn = Shell.wakeForQueue;
+ no_inbox.wake_ctx = &sh;
pardes.Kind.drawer = .{ .ctx = &sh, .go = Shell.draw };
defer pardes.Kind.drawer = null;
@@ -797,10 +789,32 @@ pub fn runClient(init: std.process.Init, opts: pardes.Options, path: []const u8,
screen.leave();
Said.no(io, "'{s}' let this client go (a Detach in it, or the session's end)", .{session});
},
+ .left => {
+ screen.leave();
+ var said: [600]u8 = undefined;
+ std.Io.File.stderr().writeStreamingAll(io, std.fmt.bufPrint(&said, "pardes: detached from '{s}', which is still running; come back with `pardes attach {s}`\n", .{ session, session }) catch "pardes: detached\n") catch {};
+ std.process.exit(0);
+ },
+ .ended => |code| {
+ screen.leave();
+ // A pair's client is its session's parent: its status once it
+ // is gone, as a terminal's job ends with its program.
+ if (opts.pair != null) {
+ var status: c_int = 0;
+ while (libc.waitpid(@intCast(start.joined.pid), &status, 0) < 0 and libc.errno(-1) == .INTR) {}
+ }
+ std.process.exit(code);
+ },
.failed => {
screen.leave();
Said.no(io, "{s}", .{start.said()});
},
+ .upgrade => |view| {
+ // The blink: its screen left, the build at its start path
+ // exec'd, which enters it again.
+ screen.leave();
+ Said.no(io, "{s}", .{client_loop.execAgain(&start, view)});
+ },
}
}
@@ -985,19 +999,8 @@ const Own = struct {
stopInput(io, &o.screen.thread);
pardes.Kind.drawer = null;
host_io.setExitWake(null, null);
- sh.pipe_tasks.cancelAll(io);
- sh.job_tasks.cancelAll(io);
- // Its worker may be waiting on the loop's queue for room.
- sh.core.stream.cancelTask();
while (loop.tryEvent() catch null) |ev| switch (ev) {
.paste => |b| gpa.free(@constCast(b)),
- .pipe_done => |response_value| {
- var response = response_value;
- response.deinit(gpa);
- },
- .search_rows => |b| b.deinit(gpa),
- .kind_job => |j| j.drop(),
- .adopted => |a| _ = libc.close(a.fd),
else => {},
};
o.screen.art.deinit(gpa);
@@ -1033,14 +1036,9 @@ const Own = struct {
if (o.sh.upgrade_asked) |pane| o.sh.upgradeNow(pane);
}
- pub fn note(o: *Own, n: daemon.Note) void {
- deliverNote(o.loop, n);
- }
-
pub fn restoring(o: *Own, nc: *pardes.Pardes) void {
const sh = &o.sh;
const io = sh.io;
- sh.pipe_tasks.cancelAll(io);
// One view, the terminal's (host_io.restoreCore).
const live = o.screen;
stopInput(io, &live.thread);
@@ -1069,24 +1067,6 @@ fn clearNativeImages(
kitty_handles.clearRetainingCapacity();
}
-/// The daemon's thread: what it says, onto the loop's queue.
-fn deliverNote(ctx: *anyopaque, note: daemon.Note) void {
- const loop: *Loop = @ptrCast(@alignCast(ctx));
- switch (note) {
- // A full queue wakes it anyway.
- .relinked => _ = loop.tryPostEvent(.nop) catch false,
- .adopted => |a| {
- for (a.pids[0..a.n], a.fds[0..a.n]) |pid, fd| loop.postEvent(.{ .adopted = .{ .pid = pid, .fd = fd } }) catch {
- _ = libc.close(fd);
- };
- loop.postEvent(.{ .adopted = .{ .pid = 0, .fd = -1 } }) catch {};
- },
- .replica => |j| loop.postEvent(.{ .replica = j }) catch {
- _ = libc.close(j.fd);
- },
- }
-}
-
/// A replica reader's post: the session's wait ends, and its step
/// boundary takes the post in.
fn wakeForReplica(ctx: ?*anyopaque) void {
@@ -1124,8 +1104,6 @@ const Shell = struct {
batch: host_io.Inbox.Batch = .{},
batch_at: usize = 0,
queue_woken: std.atomic.Value(bool) = .init(false),
- pipe_tasks: PipeTasks = .{},
- job_tasks: PipeTasks = .{},
threads_ok: bool = false,
check_files: bool = false,
in_paste: bool = false,
@@ -1190,17 +1168,9 @@ const Shell = struct {
}
fn host(s: *Shell) host_io.Host {
- return .{ .ctx = s, .vtable = if (comptime pardes.isolated) &isolated_vtable else &vtable };
+ return .{ .ctx = s, .vtable = &vtable };
}
- const isolated_vtable: host_io.Host.VTable = .{
- .wait_input = waitInput,
- .now = clockNow,
- .present = presentFrame,
- .post_present = postPresent,
- .poll_frame = ownFrame,
- };
-
const vtable: host_io.Host.VTable = .{
.wait_input = waitInput,
.now = clockNow,
@@ -1264,10 +1234,10 @@ const Shell = struct {
/// and the shell has its terminal again), the session left running.
fn detach(ctx: ?*anyopaque) void {
const s = of(ctx);
- // A replica client's: its link ends.
+ if (!daemon.kept()) return s.core.reportFailure(s.core.view().active, "Detach: no pardes daemon lists this session (it is its terminal's job)");
+ // A replica client's: its last word, and its link ends.
if (s.peers.detach(s.core.live)) return;
if (s.detached()) return s.core.reportFailure(s.core.view().active, "Detach: detached already (no terminal of its own)");
- if (!daemon.kept()) return s.core.reportFailure(s.core.view().active, "Detach: no pardes daemon lists this session (it is its terminal's job)");
s.leaveTerminal();
}
@@ -1307,6 +1277,10 @@ const Shell = struct {
const core = s.core;
var why: [800]u8 = undefined;
const path = upgrade.exe() orelse return core.reportFailure(pane, "Upgrade: this process does not know the path it was started from");
+ // A client of a session no daemon keeps is a pair's first (no other
+ // can attach): let go, it has no socket to find the session again
+ // by, and the session would end with its last link.
+ if (s.peers.count() > 0 and daemon.link < 0) return core.reportFailure(pane, "Upgrade: no daemon keeps this session, so its client could not join it again; this session stays as it is");
// 9P is served while the new binary is asked (its clients' clunks
// and reads after the word are answered), and not after.
pardes.turn.rest();
@@ -1503,11 +1477,9 @@ const Shell = struct {
// is held for the next wait: `split`).
s.takeQueue();
// An exit's wake (a .nop) or output an exit waited behind: told
- // here, inside the step, so the frame after it shows it; not while
- // reads taken off the queue wait their steps (`takeQueue`): one of
- // them may be the command's own last output, which its exit would
- // be drawn above (CommandWatch.due cannot see it).
- if (s.batch_at == s.batch.len) s.takeExits();
+ // here, inside the step, so the frame after it shows it (a read
+ // still to be applied holds it back: Ptys.unapplied).
+ s.takeExits();
s.reloadWatched();
}
@@ -1577,10 +1549,7 @@ const Shell = struct {
return true;
}
// The terminal went: a session the daemon keeps carries on
- // without it, to be attached again. Gone before the first
- // frame, the reader that takes the daemon's `ok` (kept
- // waits on it) is not started yet: started here.
- daemon.watch(s.loop, deliverNote);
+ // without it, to be attached again.
if (daemon.kept()) {
if (!s.detached()) s.leaveTerminal();
return true;
@@ -1588,11 +1557,6 @@ const Shell = struct {
core.quit = true;
return true;
},
- .adopted => |a| s.ptys.adoptions.adoptShell(s.core, a.pid, a.fd),
- .replica => |j| {
- s.peers.handed(j.fd, j.view);
- s.input_seen = true;
- },
.replica_mail => if (s.peers.urgent.swap(false, .acq_rel)) {
s.input_seen = true;
},
@@ -1608,10 +1572,10 @@ const Shell = struct {
};
if (echo) s.focused_ns = @intCast(std.Io.Clock.awake.now(s.io).nanoseconds);
c.take(said);
- if (said == .refused) return true;
+ if (said == .refused or said == .ended or said == .left) return true;
} else switch (said) {
.unit, .screen, .refused, .blob => |b| std.heap.c_allocator.free(b),
- .checked => {},
+ .checked, .ended, .left => {},
},
.link_gone => if (s.client) |c| {
c.link.quit = true;
@@ -1648,27 +1612,6 @@ const Shell = struct {
s.paste_buf.clearRetainingCapacity();
},
.fs_ready => {},
- .pipe_done => |response_value| {
- var response = response_value;
- core.update(.{ .pipe_resp = .{
- .id = response.id,
- .success = response.success,
- .outputs = response.outputs,
- .failure = response.failure,
- } });
- response.deinit(s.gpa);
- s.pipe_tasks.finish(s.io, response_value.id);
- },
- .search_rows => |b| {
- core.update(.{ .search = b });
- b.deinit(s.gpa);
- },
- .kind_job => |j| {
- s.job_tasks.finish(s.io, j.id);
- j.land(core);
- // A client's draw done: its frame is its own to draw again.
- if (s.client) |cl| cl.link.dirty = true;
- },
}
return false;
}
@@ -1877,7 +1820,8 @@ const Shell = struct {
}
/// What the session's queue holds: its ptys' output (`waitInput`
- /// paces it; the focused pane's is its echo) and their ends of file.
+ /// paces it; the focused pane's is its echo), their ends of file and
+ /// the workers' answers.
/// A read a step, as the terminal's own queue gave them: the frame
/// after one shows it before what came after it (a command's last line
/// before its exit scrolls it away), the rest kept for the next wait.
@@ -1905,8 +1849,14 @@ const Shell = struct {
},
.eof => |e| s.ptys.eof(s.core, e),
.files_changed => s.check_files = true,
- .lsp, .lsp_status => s.ptys.queue.landLsp(s.core, m),
- else => m.deinit(s.gpa, s.lsp_gpa),
+ .kind_job => {
+ s.ptys.queue.land(s.core, m);
+ // A client's draw done: its frame is its own to draw again.
+ if (s.client) |cl| cl.link.dirty = true;
+ },
+ .adopted => |a| s.ptys.adoptions.adoptShell(s.core, a.pid, a.fd),
+ .fs_ready => {},
+ else => s.ptys.queue.land(s.core, m),
}
}
}
@@ -1961,50 +1911,29 @@ const Shell = struct {
s.core.update(.{ .pipe_resp = .{ .id = id, .success = false, .outputs = &.{} } });
return s.core.reportError(.at(s.core.view().active), "pipe", error.WorkersUnavailable);
}
- selection_pipe.start(s.io, s.gpa, s.core, &s.pipe_tasks, id, s, deliverPipe);
+ const q = s.ptys.queue;
+ selection_pipe.start(s.io, s.gpa, s.core, &q.pipe_tasks, id, q, host_io.Inbox.pushPipe);
}
fn search(ctx: ?*anyopaque, gen: u32) void {
const s = of(ctx);
- if (s.threads_ok) return pardes.Stream.start(s.io, s.gpa, s.core, gen, s, deliverSearch);
+ if (s.threads_ok) return pardes.Stream.start(s.io, s.gpa, s.core, gen, s.ptys.queue, host_io.Inbox.pushSearch);
pardes.Stream.runHere(s.core, gen, true);
}
/// A draw (api.draw) on a worker, as a job is.
fn draw(ctx: ?*anyopaque, j: *host_io.KindJob) bool {
const s = of(ctx);
- return (s.threads_ok or s.client != null) and host_io.KindJob.go(s.io, &s.job_tasks, j, s, struct {
- fn deliver(c: ?*anyopaque, k: *host_io.KindJob) void {
- of(c).loop.postEvent(.{ .kind_job = k }) catch k.drop();
- }
- }.deliver);
+ const q = s.ptys.queue;
+ return (s.threads_ok or s.client != null) and host_io.KindJob.go(s.io, &q.job_tasks, j, q, host_io.Inbox.pushJob);
}
fn job(ctx: ?*anyopaque, id: pardes.Pane.Id, serial: u32, token: u32) void {
const pane = id.index();
const s = of(ctx);
if (!s.threads_ok) return host_io.KindJob.runHere(s.core, pane, serial, token);
- host_io.KindJob.start(s.io, s.core, &s.job_tasks, pane, serial, token, s, struct {
- fn deliver(c: ?*anyopaque, j: *host_io.KindJob) void {
- of(c).loop.postEvent(.{ .kind_job = j }) catch j.drop();
- }
- }.deliver);
- }
-
- /// The loop's queue waits for room (a wait the worker's cancel ends).
- fn deliverSearch(ctx: ?*anyopaque, batch: pardes.Stream.Batch) bool {
- const s = of(ctx);
- s.loop.postEvent(.{ .search_rows = batch }) catch {
- batch.deinit(s.gpa);
- return false;
- };
- return true;
- }
-
- fn deliverPipe(ctx: ?*anyopaque, response: selection_pipe.Response) void {
- const s = of(ctx);
- var owned = response;
- s.loop.postEvent(.{ .pipe_done = owned }) catch owned.deinit(s.gpa);
+ const q = s.ptys.queue;
+ host_io.KindJob.start(s.io, s.core, &q.job_tasks, pane, serial, token, q, host_io.Inbox.pushJob);
}
};
@@ -2441,6 +2370,22 @@ test "an ESC read by itself is the Escape key at once" {
t.vx.caps.kitty_keyboard = false;
}
+test "an Escape read with the click after it is the Escape key, then the click" {
+ var t: TestInput = undefined;
+ try t.init();
+ defer t.deinit();
+ // A busy session reads them in one: no terminal sends Alt on a mouse
+ // report as an ESC before it (it is in the report's button).
+ var reader: TestReader = .{ .parts = &.{"\x1b\x1b[<1;105;9M"} };
+ try readInput(&t.loop, &reader, &t.vx, &t.feed);
+ try std.testing.expectEqual(.winsize, std.meta.activeTag((try t.loop.tryEvent()).?));
+ const escape = (try t.loop.tryEvent()).?.key_press;
+ try std.testing.expectEqual(vaxis.Key.escape, escape.codepoint);
+ try std.testing.expect(!escape.mods.alt);
+ try std.testing.expectEqual(.mouse, std.meta.activeTag((try t.loop.tryEvent()).?));
+ try std.testing.expect(try t.loop.tryEvent() == null);
+}
+
test "a frame's answer is taken wherever the reads cut it, and never typed" {
const gpa = std.testing.allocator;
var t: TestInput = undefined;
@@ -2737,7 +2682,7 @@ test "TTY worker setup failures finish matching LSP and pipe requests" {
try std.testing.expect(core.pipe.wait == null);
try std.testing.expectEqualStrings("abc", pane.file.?.content);
try std.testing.expect(queue.lsp_task == null);
- try std.testing.expectEqual(@as(usize, 0), shell.pipe_tasks.len);
+ try std.testing.expectEqual(@as(usize, 0), queue.pipe_tasks.len);
}
}
diff --git a/docs/next-editor.md b/docs/next-editor.md
index e7168256..4b62f6b0 100644
--- a/docs/next-editor.md
+++ b/docs/next-editor.md
@@ -72,7 +72,7 @@ registers before it writes anything. A ring never refuses: it drops its
oldest snapshots, never part of one (an undo ring holds at least one whole
text, checked at compile time).
-**Measured** (test/lib `zig build bench`, a text in C's shape, a key typed
+**Measured** (test/consumer `zig build bench`, a text in C's shape, a key typed
into its middle, 200 keys, this machine): a key at 1, 16, 64 KiB is 13,
173 and 692 µs in Debug (270k, 3.1M, 12.2M instructions) and 0.7, 7.7 and
30 µs in ReleaseFast: the 64 KiB key is 4% of a 16 ms frame in Debug. A
@@ -82,7 +82,7 @@ text's and the cursor's); the first after a jump moves the gap, 3, 5 and
optimised in every mode): once a changed key, not a frame, so no
incremental re-parse.
-A package taking the editor (test/lib) compiles cold in 6.4 s (126e9
+A package taking the editor (test/consumer) compiles cold in 6.4 s (126e9
instructions), an edit of its own file in 0.95 s plainly and 0.09-0.11 s
under `--watch -fincremental`. pardes itself: core-test's full recompile
238.8e9 instructions before and after; the typing cells of `zig build
diff --git a/docs/next-run.md b/docs/next-run.md
index 74eab197..c2d3488b 100644
--- a/docs/next-run.md
+++ b/docs/next-run.md
@@ -56,11 +56,11 @@ work` (or `pardes-gui attach work`) is a client of the detached session,
its own process in this terminal or window. What differs from having the
session's own frontend back: the client is a second process (a terminal's
10-16 MB, a window's about 110 MB); an addon that is not plain runs in the
-session alone (its panes show a line saying so); its Detach, or its
-terminal closing, ends the client with "'work' let this client go" and exit
-1, where the stub said "detached from 'work'" and exit 0 (the last word a
-session sends its client, and exit codes, are the next steps: "B" in
-`.scratch/sketch/reports/pardes-last-step-design.md`).
+session alone (its panes show a line saying so); its Detach ends the
+client with "detached from 'work', which is still running" and exit 0, as
+the stub's did: the session's last word on a link says which of two things
+happened, `left` (a Detach in that client) or `ended` with the session's
+exit code, which the client exits with.
## What it removed
@@ -212,6 +212,3 @@ session takes back.
own (the daemon's list, and so /sessions, still says `attached`, a wire
word). After the change that frontend can only be the first one: is
"has a frontend" the word, or "with its first frontend"?
-- A client's Detach exits 1 with "let this client go", where the stub's
- said "detached from" and exited 0: the session's last word to a client
- (step B of the last-step design) would let it say which.
diff --git a/docs/next-terminal.md b/docs/next-terminal.md
index ad21ef9b..a34fc0f2 100644
--- a/docs/next-terminal.md
+++ b/docs/next-terminal.md
@@ -161,7 +161,7 @@ The ptys stay host resources:
- The records the terminal writes (cells, placements) live in the interface module, or in a leaf module surface.zig's types are moved into. surface.zig today imports `pardes.zig` (surface.zig:3), so its cell types have to be lifted out.
- **Registration.**
- main.zig hands the core `&term.ops` (`Pardes.Options.terminal`, or one global set at start beside `pardes.turn`).
- - Every root that builds a product imports `term`: the exe, the static build, `run-isolated`, the gui.
+ - Every root that builds a product imports `term`: the exe, the static build, the gui.
- `core_module` does not. build.zig's `wireCore` stops giving it ghostty-vt, wuffs and zstbi, and core-test's link loses `-lc++`.
- **The no-terminal core.** A core with no terminal ops (only a test can build one) boots to a scratch pane and says once "no terminal in this build". Words that make terminals (`Term`, `Repl`, an exec with no idle shell) refuse in words. `takesCommandLine` is false.
- **The test fixtures.** This is decided at Phase 1 from the count of tests that need a real shell, as opposed to the ones that merely boot one:
diff --git a/docs/typ/building.typ b/docs/typ/building.typ
index 8bfcb85b..d4732fa9 100644
--- a/docs/typ/building.typ
+++ b/docs/typ/building.typ
@@ -60,7 +60,7 @@ must share with its session; `pardes --help` lists every flag.
[`-Dplatform`], [`tui`, `gui`, `macos`; absent: the tui and SDL shells together, installed into `~/.local`],
[`-Dpdf`], [bool: build the pdf addon, fetching MuPDF the first time; default on once MuPDF is fetched, and off Linux],
[`-Djpx`], [bool, `true`: JPEG 2000, and with it scanned PDFs],
- [`-Dtree-sitter`], [`disabled`, `zig`, `minimal`, `full`; `full`],
+ [`-Dgrammars`], [the tree-sitter grammars compiled in: `none` (the runtime alone), `minimal` (C, C++ and Zig) or `full` (all of them; the default)],
[`-Dembed-sources`], [bool, `false`: serve the sources under #file("/src")],
[`-Dhome-install`], [bool: a bare `zig build` also copies the binaries into `~/.local/bin` and the addon steps theirs into `$XDG_DATA_HOME/pardes/addons`, default true; with `-Dplatform` only `true` copies, and the addons alone],
[`-Dstamp-commit`], [bool: the git commit in `--version` and crash records; on for release builds and the `~/.local` install],
@@ -92,23 +92,50 @@ moves an anchor fails that file's step. Each table says why, edit by edit.
== As a library <library>
-A Zig package that depends on pardes is given one module and nothing of
-the editor: `pardes-syntax` (`core/lib_syntax.zig`), for a program that
-draws source text itself and wants it parsed and coloured as pardes has
-it.
+As `build.zig`'s head comment says it, word for word:
+
+A package that depends on pardes is given its syntax, `pardes-syntax`
+(`core/lib_syntax.zig`):
```
-// build.zig.zon
-.pardes = .{ .path = "../pardes" },
-// build.zig
const pardes = b.dependency("pardes", .{
.target = target,
.optimize = optimize,
- .@"tree-sitter" = .minimal,
+ .grammars = .minimal,
});
exe.root_module.addImport("pardes-syntax", pardes.module("pardes-syntax"));
```
+and, when it asks, the text pane, `pardes-editor`
+(`core/lib_editor.zig`), here with a grammar of its own handed in at
+run time:
+
+```
+const pardes = b.dependency("pardes", .{
+ .target = target,
+ .optimize = optimize,
+ .grammars = .none,
+ .editor = true,
+});
+exe.root_module.addImport("pardes-editor", pardes.module("pardes-editor"));
+```
+
+`.grammars`: the tree-sitter grammars compiled in: `none` (the runtime
+alone), `minimal` (C, C++ and Zig) or `full` (all of them; the default).
+`.editor`: exports `pardes-editor` besides `pardes-syntax`, and with it
+fetches uucode, mvzr and vaxis.
+
+Every dependency but tree-sitter's runtime is lazy in the manifest, so
+such a package fetches what it asked for and nothing else.
+`pardes-editor` has `pardes-syntax` in it as `.syntax`: a file belongs
+to one module, so a package imports one of the two. `test/consumer` is
+such a package, with both shapes; `lib-test`, which `unit-test` runs,
+builds and runs it.
+
+`build.zig.zon` names pardes by its path: `.pardes = .{ .path = "../pardes" }`.
+
+=== The syntax
+
It is the editor's own code under the names it has there. A language is
told by a path's extension, as in the editor, and `pathFor` gives a path
for a language's name.
@@ -122,35 +149,21 @@ for a language's name.
[`start`, `stop`], [tree-sitter's allocator, and the end of the parsers kept per language],
)
-The `tree-sitter` option is the build's own: `zig`, `minimal` (C, C++
-and Zig) or `full`, the default. Every dependency but tree-sitter's
-runtime is lazy in the manifest, so the package fetches the runtime and
-its set's grammars and compiles those alone; pardes's own build asks for
-what it is missing in one round. Zig still unpacks a lazy package whose
-archive its global cache already holds; `--pkg-dir` (or `ZIG_LOCAL_PKG_DIR`)
-at pardes's `zig-pkg` shares the one copy. What a pane measures stays
-out: a cell's width is vaxis's and uucode's, and a tab is
-`config.tab_width` cells wherever it stands. `test/lib` is such a
-package, and `zig build lib-test` builds and runs it.
+pardes's own build takes `-Dgrammars` too, and asks for what it is
+missing in one round. Zig still unpacks a lazy package whose archive its
+global cache already holds; `--pkg-dir` (or `ZIG_LOCAL_PKG_DIR`) at
+pardes's `zig-pkg` shares the one copy. What a pane measures stays out: a
+cell's width is vaxis's and uucode's, and a tab is `config.tab_width`
+cells wherever it stands.
=== The editor
`pardes-editor` (`core/lib_editor.zig`) is the text pane as a library:
helix's keys on a text kept in memory, no files, commands, builtins,
-prompts or views. A package asks for it, and is then given uucode, mvzr
-and vaxis's grapheme width besides; one that does not fetches nothing more.
-It has `pardes-syntax` in it as `.syntax`: a file belongs to one module, so
-a package imports one of the two.
-
-```
-const pardes = b.dependency("pardes", .{
- .target = target,
- .optimize = optimize,
- .@"tree-sitter" = .minimal,
- .editor = true,
-});
-exe.root_module.addImport("pardes-editor", pardes.module("pardes-editor"));
-```
+prompts or views. Of vaxis it takes the grapheme width alone. With
+`.grammars = .none` it has no grammar of pardes's: a program hands its
+own in at run time (`Language`, below), linking the grammar's parser
+itself, as `test/consumer` does with C's.
The editor is a value of plain data, `Editor(capacity)`: no pointer, no
allocator, every capacity in its type, so a program keeps it where it
@@ -186,7 +199,7 @@ zig build kitty-harness kitty graphics through a pane end to end (a fake kitt
kitten icat and chafa too when installed)
zig build syntax-test tree-sitter tests without building the editor
zig build syntax deterministic per-byte highlighting snapshots
-zig build lib-test the library, from a package that depends on pardes (test/lib);
+zig build lib-test the library, from a package that depends on pardes (test/consumer);
unit-test runs it too
zig build hxlib helix's cases on the library's editor (-- --parity: against the file pane)
zig build behaviour-test behaviour through the 9P tree, in process (test/behaviour/),
diff --git a/docs/typ/command-line.txt b/docs/typ/command-line.txt
index 3c73fed4..0ced145f 100644
--- a/docs/typ/command-line.txt
+++ b/docs/typ/command-line.txt
@@ -95,8 +95,10 @@ See also: ps, attach
Start a session here, even in a pane of another: in this terminal for
pardes, a window for pardes-gui, or with --detach none until one
-attaches. Bare `pardes` takes the same flags, and starts one unless
-it is in a pane (where it hands its FILE to that session).
+attaches, which returns once the session runs and prints its name.
+Bare `pardes` takes the same flags, and starts one unless it is in a
+pane (where it hands its FILE to that session); its --detach is the
+session itself, until it ends (a supervisor's way).
Usage:
pardes new [flags] [FILE]
diff --git a/runtime/9p_io.zig b/runtime/9p_io.zig
index bcb0f81b..aaca377d 100644
--- a/runtime/9p_io.zig
+++ b/runtime/9p_io.zig
@@ -1896,7 +1896,9 @@ pub const Client = struct {
/// 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.
+ /// Twrites at rising offsets. Untimed once connected: the answer comes
+ /// when the session's step has run, however long a loaded machine
+ /// takes over 256 MiB, and a session that died ends the connection.
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;
@@ -1905,6 +1907,7 @@ pub const Client = struct {
errdefer said = remote;
const s = try startSession(dial, path);
defer endSession(s, false);
+ s.deadline = std.math.maxInt(i64);
const fid = try walkTo(s, names[0..n], &remote);
_ = try s.ask(.{ .open = .{ .fid = fid, .mode = ninep.ordwr } }, &remote);
var written: usize = 0;
@@ -1914,7 +1917,6 @@ pub const Client = struct {
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);
diff --git a/runtime/client.zig b/runtime/client.zig
index 544be588..329bdab3 100644
--- a/runtime/client.zig
+++ b/runtime/client.zig
@@ -37,6 +37,7 @@ const std = @import("std");
const libc = std.c;
const pardes = @import("core");
const replica = pardes.replica;
+const upgrade = @import("upgrade.zig");
/// A wait with no wake of its own: until an input or a message.
pub const forever: u32 = std.math.maxInt(u32);
@@ -92,6 +93,8 @@ pub const Start = struct {
s.o.distrusted = &s.distrusted;
// Its frame timings, this process's (Pardes.frames).
s.o.frames = &s.frames;
+ // Exec'd at an Upgrade (`execAgain`): for the view it had.
+ if (init.environ_map.get("PARDES_JOIN_VIEW")) |v| s.o.join_view = std.fmt.parseInt(u8, v, 10) catch null;
s.r = replica.join(s.gpa, &s.joined, dial.path, dial.session, s.o, s.have, &s.why, null) orelse return false;
return true;
}
@@ -109,9 +112,46 @@ pub const Start = struct {
}
};
-/// How a client's joins ended: it quit, the session let it go, or it could
-/// not join again (`Start.said`).
-pub const Ended = enum { done, gone, failed };
+/// How a client's joins ended: it quit, the session let it go, it could
+/// not join again (`Start.said`), it left the session running (a Detach in
+/// it), the session ended, with its code, or it runs another build now and
+/// one is installed at this client's start path since it started: the
+/// frontend lets its screen go and execs that, for this view (`execAgain`).
+pub const Ended = union(enum) { done, gone, failed, left, ended: u8, upgrade: u8 };
+
+/// An Upgrade's client again (`Ended.upgrade`), its frontend's screen let
+/// go: this process exec'd as the file at its start path, an attach of the
+/// same session through the same socket (a far one's forward, its ssh this
+/// process's child still), joining for `view` (PARDES_JOIN_VIEW; far,
+/// PARDES_REPLICA_FAR). The terminal's blink: no record crosses the exec.
+/// Returns only when the exec failed: why.
+pub fn execAgain(s: *Start, view: u8) []const u8 {
+ const path = upgrade.exe() orelse return "Upgrade: this client does not know the path it was started from";
+ var at_buf: [4200]u8 = undefined;
+ const at = std.fmt.bufPrintSentinel(&at_buf, "--attach={s}:{s}", .{ s.dial.path, s.dial.session }, 0) catch return "Upgrade: the session's socket's path is too long to attach again by";
+ const argv = [_:null]?[*:0]const u8{ path, at };
+ var view_buf: [32]u8 = undefined;
+ const joining = std.fmt.bufPrintSentinel(&view_buf, "PARDES_JOIN_VIEW={d}", .{view}, 0) catch unreachable; // a u8 fits 32
+ var n: usize = 0;
+ while (libc.environ[n] != null) n += 1;
+ const envp = s.gpa.allocSentinel(?[*:0]const u8, n + 2, null) catch return "Upgrade: no memory for this client's environment";
+ var k: usize = 0;
+ for (libc.environ[0..n]) |e| {
+ const entry = std.mem.span(e.?);
+ if (std.mem.startsWith(u8, entry, "PARDES_JOIN_VIEW=") or std.mem.startsWith(u8, entry, "PARDES_REPLICA_FAR=")) continue;
+ envp[k] = e;
+ k += 1;
+ }
+ envp[k] = joining.ptr;
+ k += 1;
+ if (s.have != null) {
+ envp[k] = "PARDES_REPLICA_FAR=1";
+ k += 1;
+ }
+ envp[k] = null;
+ _ = libc.execve(path, &argv, envp.ptr);
+ return "Upgrade: the build at this client's start path would not start";
+}
pub fn Loop(comptime Frontend: type) type {
return struct {
@@ -141,6 +181,8 @@ pub fn Loop(comptime Frontend: type) type {
/// the session let it go to upgrade; the frontend stays as it is.
pub fn run(l: *L, s: *Start) !Ended {
const link = &l.link;
+ // Its start path's file, for an Upgrade's question (`upgrade`).
+ upgrade.locate();
while (true) {
link.reset(s.r, &s.joined);
l.fe.start(l);
@@ -151,7 +193,7 @@ pub fn Loop(comptime Frontend: type) type {
l.after();
}
if (s.env.get("PARDES_REPLICA_STATS")) |file| link.writeStats(file);
- if (!link.gone) replica.bye(s.joined.fd, s.r.diverged != null);
+ if (!link.gone) replica.bye(s.joined.fd, .{ .again = s.r.diverged != null, .close = link.close });
// The link's reader ends with the link, posting as it goes:
// what it posted is let go until it has (a terminal's queue
// is bounded: a reader blocked on it would never end).
@@ -170,11 +212,17 @@ pub fn Loop(comptime Frontend: type) type {
// What it made since it joined, kept for its next start.
if (s.have) |h| h.keep(s.r.core());
s.r.deinit();
+ if (link.left) return .left;
+ if (link.ended) |code| return .{ .ended = code };
return if (link.gone) .gone else .done;
}
// The session again, the core it leaves held meanwhile: its
// blobs are not sent again.
- s.r = replica.join(s.gpa, &s.joined, s.dial.path, s.dial.session, s.o, s.have, &s.why, s.r) orelse return .failed;
+ s.r = replica.join(s.gpa, &s.joined, s.dial.path, s.dial.session, s.o, s.have, &s.why, s.r) orelse {
+ if (replica.ended(&s.why)) return .gone;
+ if (replica.otherBuild(&s.why) and upgrade.replaced()) return .{ .upgrade = s.joined.view };
+ return .failed;
+ };
}
}
diff --git a/runtime/daemon.zig b/runtime/daemon.zig
index 80e1cc09..9b566e60 100644
--- a/runtime/daemon.zig
+++ b/runtime/daemon.zig
@@ -290,10 +290,11 @@ fn hello(fd: c_int, k: Kind, pid: libc.pid_t, named: []const u8, detached: bool)
/// This session's registration (`register`), which forkShell and the hosts
/// tell of their ptys; -1 with none (no daemon, or PARDES_DAEMON=off).
pub var link: c_int = -1;
-/// The daemon said `ok` to the hello, and the link has not ended since;
-/// `gone` once it has ended for good (`readNotes`).
-var up = std.atomic.Value(bool).init(false);
-var gone = std.atomic.Value(bool).init(false);
+/// The hello's answer, as the reader took it (`readNotes`): `up`, the
+/// daemon said `ok` and the link has not ended since; `gone`, it has ended
+/// for good; `asked` until either (and while a new daemon is dialled).
+const Answer = enum(u32) { asked, up, gone };
+var answer = std.atomic.Value(Answer).init(.asked);
/// The session is ending (`quit`): its link's end is no daemon's death.
var quitting = std.atomic.Value(bool).init(false);
/// A new daemon took the hello since the last one died: the rest of what
@@ -306,6 +307,8 @@ var detached_now = std.atomic.Value(bool).init(false);
var name_buf: [128]u8 = undefined;
var name_len: usize = 0;
var reader: ?std.Thread = null;
+/// Where the reader hands each note (`notesTo`).
+var notes: ?struct { ctx: *anyopaque, deliver: *const fn (ctx: *anyopaque, note: Note) void } = null;
pub fn name() []const u8 {
return name_buf[0..name_len];
@@ -314,12 +317,22 @@ pub fn name() []const u8 {
/// Whether a daemon keeps this session: what Detach, and a terminal's end,
/// need, or the session would be left where nothing can attach to it. A
/// daemon just started answers the hello once it runs, so this waits for
-/// that answer (up to 2 s): never on a startup's path, only on those two.
+/// that answer, or the link's end, whenever they come: never on a startup's
+/// path, only on those two. The reader takes it: started here if the first
+/// frame has not started it yet.
pub fn kept() bool {
if (link < 0) return false;
- var waited: u32 = 0;
- while (!up.load(.acquire) and !gone.load(.acquire) and waited < 2000) : (waited += 1) sleepMs(1);
- return up.load(.acquire);
+ watch();
+ if (reader == null) return false;
+ const io = std.Io.Threaded.global_single_threaded.io();
+ while (answer.load(.acquire) == .asked) io.futexWaitUncancelable(Answer, &answer.raw, .asked);
+ return answer.load(.acquire) == .up;
+}
+
+/// The reader's word on the hello's answer, to `kept` waiting on it.
+fn settle(a: Answer) void {
+ answer.store(a, .release);
+ std.Io.Threaded.global_single_threaded.io().futexWake(Answer, &answer.raw, 1);
}
/// The name a session goes by: its 9P socket's (`--9p=`, `--detach=`), else
@@ -438,11 +451,18 @@ pub const Note = union(enum) {
pub const Joining = struct { fd: c_int, view: ?u8 = null };
-/// Hands every note the daemon sends on to `deliver`, on a thread of its
+/// Where every note the daemon sends goes, once `watch` has started the
+/// reader: the session's, before its first step.
+pub fn notesTo(ctx: *anyopaque, deliver: *const fn (ctx: *anyopaque, note: Note) void) void {
+ notes = .{ .ctx = ctx, .deliver = deliver };
+}
+
+/// Hands every note the daemon sends on (`notesTo`), on a thread of its
/// own, until the link ends (`quit`). Called each loop: started once.
-pub fn watch(ctx: *anyopaque, deliver: *const fn (ctx: *anyopaque, note: Note) void) void {
+pub fn watch() void {
+ const n = notes orelse return;
if (link < 0 or reader != null) return;
- reader = std.Thread.spawn(.{}, readNotes, .{ link, ctx, deliver }) catch null;
+ reader = std.Thread.spawn(.{}, readNotes, .{ link, n.ctx, n.deliver }) catch null;
}
fn readNotes(fd: c_int, ctx: *anyopaque, deliver: *const fn (ctx: *anyopaque, note: Note) void) void {
@@ -452,7 +472,7 @@ fn readNotes(fd: c_int, ctx: *anyopaque, deliver: *const fn (ctx: *anyopaque, no
var words = std.mem.tokenizeScalar(u8, got.words, ' ');
const verb = words.next() orelse "";
if (std.meta.stringToEnum(enum { ok, replica, adopted }, verb)) |v| switch (v) {
- .ok => up.store(true, .release),
+ .ok => settle(.up),
.replica => {
const view = std.fmt.parseInt(u8, words.next() orelse "", 10) catch null;
if (got.nfds >= 1) deliver(ctx, .{ .replica = .{ .fd = got.fds[0], .view = view } });
@@ -482,12 +502,12 @@ fn readNotes(fd: c_int, ctx: *anyopaque, deliver: *const fn (ctx: *anyopaque, no
// link's end is what wakes this, never a timer. One that never took
// it (another build's daemon), or the session's own end, is not:
// an end begun while it dialled finds the new link (`quit`).
- if (!up.swap(false, .acq_rel) or quitting.load(.acquire) or !redial(fd) or quitting.load(.acquire)) break;
+ if (answer.swap(.asked, .acq_rel) != .up or quitting.load(.acquire) or !redial(fd) or quitting.load(.acquire)) break;
retell.store(true, .release);
deliver(ctx, .relinked);
}
// Not kept, until the session's end.
- gone.store(true, .release);
+ settle(.gone);
}
/// A new connection in the place of `fd`, the link (its number kept, so
@@ -600,6 +620,12 @@ fn stubWait(session: libc.pid_t, pipe: c_int) noreturn {
const said = buf[0..len];
const out = std.Io.File.stderr();
const io = std.Io.Threaded.global_single_threaded.io();
+ // `new --detach`'s session runs (`launched`): its name, for a script.
+ if (said.len > 0 and said[0] == 'r') {
+ var text: [520]u8 = undefined;
+ std.Io.File.stdout().writeStreamingAll(io, std.fmt.bufPrint(&text, "{s}\n", .{said[1..]}) catch said[1..]) catch {};
+ libc._exit(0);
+ }
if (said.len > 0 and said[0] == 'd') {
var text: [700]u8 = undefined;
const who = said[1..];
@@ -695,6 +721,57 @@ pub fn forkSession(conn: c_int) ?void {
stubWait(pid, pipe[0]);
}
+/// `pardes new --detach`: the session forked off in a session of its own,
+/// its stdin /dev/null, and this process its stub until the session runs
+/// (`launched`): it then prints the name and exits 0, or with the
+/// session's status if it ended first. Returns in the session, called
+/// `named` (else by its pid); when no fork can be made, here, which is
+/// then the session.
+pub fn launch(named: []const u8) void {
+ var pipe: [2]c_int = undefined;
+ if (libc.pipe(&pipe) != 0) return;
+ ninep_io.setCloexec(pipe[0]);
+ ninep_io.setCloexec(pipe[1]);
+ const pid = libc.fork();
+ if (pid < 0) {
+ _ = libc.close(pipe[0]);
+ _ = libc.close(pipe[1]);
+ return;
+ }
+ if (pid == 0) {
+ _ = libc.close(pipe[0]);
+ _ = libc.setsid();
+ const null_fd = libc.open("/dev/null", .{ .ACCMODE = .RDWR, .CLOEXEC = true }, @as(libc.mode_t, 0));
+ if (null_fd >= 0) _ = libc.dup2(null_fd, 0);
+ if (null_fd > 0) _ = libc.close(null_fd);
+ stub = pipe[1];
+ launching = true;
+ setName(named);
+ return;
+ }
+ _ = libc.close(pipe[1]);
+ stubWait(pid, pipe[0]);
+}
+
+/// Forked by `launch`, and its stub not told yet.
+var launching = false;
+
+/// The session of a `new --detach` runs: registered (the daemon took its
+/// hello, when there is one) and listening. Its stub told, with its name;
+/// its stdout and stderr, still the launch's until now, let go.
+pub fn launched() void {
+ if (!launching) return;
+ launching = false;
+ _ = kept();
+ tellStub(stub, "r{s}", .{name()});
+ stub = -1;
+ const null_fd = libc.open("/dev/null", .{ .ACCMODE = .RDWR, .CLOEXEC = true }, @as(libc.mode_t, 0));
+ if (null_fd < 0) return;
+ _ = libc.dup2(null_fd, 1);
+ _ = libc.dup2(null_fd, 2);
+ if (null_fd > 2) _ = libc.close(null_fd);
+}
+
// ---- the daemon ----
const Conn = struct {
diff --git a/runtime/main.zig b/runtime/main.zig
index a791ffec..a21eb83f 100644
--- a/runtime/main.zig
+++ b/runtime/main.zig
@@ -323,8 +323,10 @@ const cmds = std.EnumArray(Cmd, Doc).init(.{
.doc =
\\Start a session here, even in a pane of another: in this terminal for
\\pardes, a window for pardes-gui, or with --detach none until one
- \\attaches. Bare `pardes` takes the same flags, and starts one unless
- \\it is in a pane (where it hands its FILE to that session).
+ \\attaches, which returns once the session runs and prints its name.
+ \\Bare `pardes` takes the same flags, and starts one unless it is in a
+ \\pane (where it hands its FILE to that session); its --detach is the
+ \\session itself, until it ends (a supervisor's way).
,
.examples = &.{
.{ "pardes new", "a session here, its shell pane in tty mode" },
@@ -1155,27 +1157,37 @@ fn nativeMain(std_init: std.process.Init) !void {
upgrade.resumed = upgrade.Record.decode(args[1][upgrade.flag.len..]) catch badArgs(init.io, "--upgraded: a record this build cannot read", .{});
};
const resuming = upgrade.resumed != null;
+ // A window's pair's session (`pair`): the pardes beside a pardes-gui,
+ // exec'd in its child, its first client on the fd named, the window's
+ // arguments after it.
+ const paired: ?c_int = if (!resuming and args.len > 1 and std.mem.startsWith(u8, args[1], upgrade.paired_flag))
+ std.fmt.parseInt(c_int, args[1][upgrade.paired_flag.len..], 10) catch badArgs(init.io, "{s}: not a descriptor", .{args[1]})
+ else
+ null;
var session_only = true;
var new_session = false;
+ // `pardes new`: with --detach it returns once the session runs.
+ var new_verb = false;
var explicit_tty = false;
var detach: ?[]const u8 = null;
var attach: ?[]const u8 = null;
var positional: ?[:0]const u8 = null;
var wait = false;
- var i: usize = if (resuming) 2 else 1;
+ var i: usize = if (resuming or paired != null) 2 else 1;
// A command's name first: new and attach go on to start or join a
// session, with the flags after them; the rest are done in `command`.
- if (!resuming and args.len > 1) if (std.meta.stringToEnum(Cmd, args[1])) |cmd| switch (cmd) {
+ if (!resuming and args.len > i) if (std.meta.stringToEnum(Cmd, args[i])) |cmd| switch (cmd) {
.new => {
new_session = true;
- i = 2;
+ new_verb = true;
+ i += 1;
},
.attach => {
- const named = args.len > 2 and args[2].len > 0 and args[2][0] != '-';
- attach = if (named) args[2] else "";
- i = if (named) 3 else 2;
+ const named = args.len > i + 1 and args[i + 1].len > 0 and args[i + 1][0] != '-';
+ attach = if (named) args[i + 1] else "";
+ i += if (named) 2 else 1;
},
- else => runCommand(init, cmd, args[2..]),
+ else => runCommand(init, cmd, args[i + 1 ..]),
};
while (i < args.len) : (i += 1) {
const a = args[i];
@@ -1282,12 +1294,6 @@ fn nativeMain(std_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
@@ -1522,11 +1528,8 @@ fn nativeMain(std_init: std.process.Init) !void {
// detached session, as `pardes --detach` (`ps` says tty), its
// windows clients. Without one there, it carries on as a window's.
if (comptime pardes.platform == .gui) if (!resuming) {
- var exe: [4096]u8 = undefined;
- const n = std.c.readlink("/proc/self/exe", &exe, exe.len);
- if (n > 0) if (std.Io.Dir.path.dirname(exe[0..@intCast(n)])) |bin| if (args.len < 64) {
- var path_buf: [4104]u8 = undefined;
- const path = std.fmt.bufPrintSentinel(&path_buf, "{s}/pardes", .{bin}, 0) catch unreachable; // 4096 + 8 fits
+ var path_buf: [4104]u8 = undefined;
+ if (pardesBeside(&path_buf)) |path| if (args.len < 64) {
var argv: [64:null]?[*:0]const u8 = @splat(null);
argv[0] = path.ptr;
for (args[1..], 1..) |a, k| argv[k] = a.ptr;
@@ -1537,6 +1540,9 @@ fn nativeMain(std_init: std.process.Init) !void {
// socket holds already (a plain session is named by its pid too).
if (name.len != 0 and !resuming and ninep_io.taken(name)) die(init.io, "a session named {s} is already running", .{name});
if (opts.ninep_name.len == 0) opts.ninep_name = name;
+ // `new --detach` forks the session and returns once it runs; the
+ // flag alone is the session itself (a supervisor's, a harness's).
+ if (new_verb and !resuming) daemon.launch(opts.ninep_name);
// Said where it was started (stderr, as the log says it): no pane
// anyone sees would show it. The session runs on, with no 9P.
var pid_buf: [16]u8 = undefined;
@@ -1565,6 +1571,19 @@ fn nativeMain(std_init: std.process.Init) !void {
};
detached = if (pardes.platform == .gui) !rec.window else rec.nttys == 0;
daemon.resumeLink(rec.link, rec.stub, kind, opts.ninep_name, detached);
+ } else if (paired) |fd| {
+ // A window's pair's session: its first client on `fd`, the daemon
+ // its own to dial (and to start, when none runs).
+ opts.pair = fd;
+ term = .detached;
+ detached = true;
+ if (daemon.wanted()) _ = daemon.register(null, kind, opts.ninep_name, true);
+ } else if (detach == null and std.c.getenv("PARDES_PAIR") != null) {
+ // The last step's way, behind its variable until it is the default:
+ // this terminal or window a client of a session forked off for it
+ // (`pair`).
+ pair(init, &opts, args);
+ term = .detached;
} else if (daemon.wanted()) {
if (detach != null or pardes.platform == .gui) {
_ = daemon.register(null, kind, opts.ninep_name, detach != null);
@@ -1701,6 +1720,85 @@ fn commOf(io: std.Io, pid: []const u8, buf: *[64]u8) []const u8 {
return std.mem.trimEnd(u8, std.Io.Dir.cwd().readFile(io, path, buf) catch return "", "\n");
}
+/// The terminal's binary beside this one, as /proc names this one (Linux),
+/// in `buf`.
+fn pardesBeside(buf: *[4104]u8) ?[:0]const u8 {
+ var exe: [4096]u8 = undefined;
+ const n = std.c.readlink("/proc/self/exe", &exe, exe.len);
+ if (n <= 0) return null;
+ const bin = std.Io.Dir.path.dirname(exe[0..@intCast(n)]) orelse return null;
+ return std.fmt.bufPrintSentinel(buf, "{s}/pardes", .{bin}, 0) catch unreachable; // 4096 + 8 fits
+}
+
+/// PARDES_PAIR: `pardes` in a terminal, or `pardes-gui`, as a session and
+/// its first client over a socket pair (docs/next-run.md; the last step's
+/// design, 1.1 and 1.2). The daemon dialled first, as for a stub; then a
+/// fork: the parent the CLIENT (the shell's job, the terminal its own,
+/// signals reach what draws; or the window), its first join on its end of
+/// the pair; the child the SESSION (setsid, 0, 1 and 2 on /dev/null,
+/// detached), its end of the pair its first client, taken before its first
+/// effects (runtime/session.zig). A window's child execs the `pardes`
+/// beside it (`--paired=FD` first, its arguments after), which dials the
+/// daemon itself: a window's session loop is woken through SDL (gui.zig
+/// `sdlWake`), a terminal's needs none. Returns in a terminal's session;
+/// the client exits. No fork to be had: returns, and this process is the
+/// session, with no terminal: said by the caller's run. A window with no
+/// `pardes` beside it returns at once, its own session as before.
+fn pair(init: std.process.Init, opts: *pardes.Options, args: []const [:0]const u8) void {
+ var path_buf: [4104]u8 = undefined;
+ var fd_buf: [32]u8 = undefined;
+ var argv: [64:null]?[*:0]const u8 = @splat(null);
+ if (pardes.platform == .gui) {
+ const path = pardesBeside(&path_buf) orelse return;
+ if (args.len >= argv.len - 1 or std.c.access(path, std.c.X_OK) != 0) return;
+ argv[0] = path.ptr;
+ for (args[1..], 2..) |a, k| argv[k] = a.ptr;
+ }
+ const conn: ?c_int = if (pardes.platform == .tui and daemon.wanted()) daemon.connect(true) else null;
+ var fds: [2]c_int = undefined;
+ if (std.c.socketpair(std.c.AF.UNIX, std.c.SOCK.STREAM | std.c.SOCK.CLOEXEC, 0, &fds) != 0)
+ die(init.io, "no socket pair for a session and its terminal", .{});
+ if (pardes.platform == .gui) argv[1] = (std.fmt.bufPrintSentinel(&fd_buf, upgrade.paired_flag ++ "{d}", .{fds[0]}, 0) catch unreachable).ptr; // an fd fits 32
+ // The session laid out at the terminal's size: no reflow at the join.
+ var ws: std.posix.winsize = undefined;
+ if (pardes.platform == .tui and std.c.ioctl(0, std.posix.T.IOCGWINSZ, &ws) == 0 and ws.col > 0 and ws.row > 0) {
+ opts.cols = ws.col;
+ opts.rows = ws.row;
+ }
+ const pid = std.c.fork();
+ if (pid < 0) die(init.io, "no fork for a session and its terminal", .{});
+ if (pid == 0) {
+ _ = std.c.close(fds[1]);
+ _ = std.c.setsid();
+ const null_fd = std.c.open("/dev/null", .{ .ACCMODE = .RDWR, .CLOEXEC = true }, @as(std.c.mode_t, 0));
+ if (null_fd >= 0) for (0..3) |i| {
+ _ = std.c.dup2(null_fd, @intCast(i));
+ };
+ if (null_fd > 2) _ = std.c.close(null_fd);
+ if (pardes.platform == .gui) {
+ // Its end of the pair across the exec.
+ _ = std.c.fcntl(fds[0], std.c.F.SETFD, @as(c_int, 0));
+ _ = execvp(argv[0].?, &argv);
+ std.c._exit(127);
+ }
+ opts.pair = fds[0];
+ // The daemon is the client's to start; the hello is this one's.
+ daemon.startPending(false);
+ if (conn) |c| _ = daemon.register(c, .tty, opts.ninep_name, true);
+ return;
+ }
+ _ = std.c.close(fds[0]);
+ if (conn) |c| _ = std.c.close(c);
+ daemon.startPending(true);
+ var name_buf: [16]u8 = undefined;
+ const name = if (opts.ninep_name.len != 0) opts.ninep_name else std.fmt.bufPrint(&name_buf, "{d}", .{pid}) catch unreachable; // a pid fits 16
+ var sock_buf: [ninep_io.sun_path_len:0]u8 = undefined;
+ var o = opts.*;
+ o.pair = fds[1];
+ clientOf(init, o, daemon.replicaSocket(&sock_buf) orelse "", name, false) catch |err| die(init.io, "{t}", .{err});
+ std.process.exit(0);
+}
+
/// The replica client of this build's frontend: a terminal's (tui.zig) or a
/// window's (gui.zig).
fn clientOf(init: std.process.Init, opts: pardes.Options, path: []const u8, name: []const u8, far: bool) !void {
@@ -1787,8 +1885,11 @@ fn attachClient(init: std.process.Init, opts: pardes.Options, where: []const u8,
Ssh.child = pid;
Ssh.path = here;
_ = atexit(Ssh.end);
+ // Its file is there a moment before ssh listens on it: until a
+ // connect answers.
var waited: u32 = 0;
- while (std.meta.isError(std.Io.Dir.cwd().access(io, here, .{}))) : (waited += 1) {
+ const probe = while (true) : (waited += 1) {
+ if (cloud9.transport.connectFd(.{ .unix = here }, cloud9.transport.nowMs() + 100)) |fd| break fd else |_| {}
var status: c_int = 0;
if (std.c.waitpid(pid, &status, std.c.W.NOHANG) == pid) {
Ssh.child = 0;
@@ -1797,7 +1898,8 @@ fn attachClient(init: std.process.Init, opts: pardes.Options, where: []const u8,
if (waited > 3000) die(io, "--attach: ssh to {s} set up no forward in 30 s", .{where});
const ts: std.c.timespec = .{ .sec = 0, .nsec = 10 * std.time.ns_per_ms };
_ = std.c.nanosleep(&ts, null);
- }
+ };
+ _ = std.c.close(probe);
clientOf(init, opts, here, name, true) catch |err| die(io, "--attach: {t}", .{err});
std.process.exit(0);
}
diff --git a/runtime/session.zig b/runtime/session.zig
index b1558d9f..9c8446e3 100644
--- a/runtime/session.zig
+++ b/runtime/session.zig
@@ -6,10 +6,10 @@
//! posts, `Inbox`), its ptys (`Ptys`) and the files it watches
//! (`file_watch.Watches`): a step, its unit to the clients and theirs
//! taken in, an Upgrade or a Restore between steps; and the order its
-//! parts end in. Its other devices (the LSP's and the pipes' and addons'
-//! jobs, the session's own input) are still its frontend's (each `Shell`);
-//! the language servers' answers come through its queue (`Inbox.startLsp`).
-//! What a frontend does is:
+//! parts end in. Its workers (a language server's query, the pipes, the
+//! addons' jobs and draws, a search) answer through its queue, which holds
+//! their tasks and ends them (`Inbox.land`, `Inbox.deinit`); the session's
+//! own input is its frontend's (each `Shell`). What a frontend does is:
//!
//! - `options(o)`: before the core: what it gives the core it starts (a
//! window's size, for a dump's layout).
@@ -25,8 +25,6 @@
//! session's first wait (`l.watch`).
//! - `sent()`: after each step's unit went to the clients.
//! - `upgradeAsked()`: an Upgrade asked in the step, done (it execs).
-//! - `note(n)`: what the daemon says (an adopted shell, a client's
-//! connection, a new daemon's hello taken), onto its queue.
//! - `restoring(nc)`, `restored(l)`: a Restore's new core, before it
//! replaces the old one (its devices let go, what it is told of the
//! frontend) and after (its own view of it again).
@@ -91,6 +89,8 @@ pub fn Loop(comptime Frontend: type) type {
l.peers = .{ .gpa = l.gpa, .io = l.io, .name = daemon.name() };
l.inbox = .{ .io = l.io, .gpa = l.gpa, .lsp_allocator = l.allocs.lsp };
defer l.inbox.deinit();
+ // A search's worker may be waiting on the queue for room.
+ defer l.core.stream.cancelTask();
// The language servers' status lines, from the first effects on.
pardes.lsp.setStatusSink(&l.inbox, host_io.Inbox.lspStatus);
defer pardes.lsp.setStatusSink(null, null);
@@ -101,9 +101,14 @@ pub fn Loop(comptime Frontend: type) type {
l.host = try fe.open(&l);
defer fe.close(&l);
+ daemon.notesTo(&l, note);
defer l.peers.deinit();
// Before the core goes: each client sees its link end.
defer l.peers.dropAll(l.core);
+ // A first client on the socket it was started with, before its
+ // first effects: it has every terminal from its first byte, and
+ // no reload (Core.openView).
+ if (o.pair) |fd| l.peers.join(l.core, .{ .fd = fd });
l.effects();
// ...and its shells, once a fresh session's own has a directory
// to adopt them in.
@@ -114,12 +119,19 @@ pub fn Loop(comptime Frontend: type) type {
l.ptys.start(l.core);
l.watches.start();
try fe.start(&l);
+ // A `new --detach`'s launch returns now.
+ daemon.launched();
while (!l.core.quit) {
pardes.turn.bump(&pardes.turn.restores);
try l.core.pump(l.host);
// Its unit to each replica client, and theirs taken in.
l.peers.boundary(l.core);
+ // A pair's session with no daemon ends with its last link:
+ // nothing could attach to it again; with one, when its last
+ // client closed its window (a close, not a loss), no Detach
+ // typed in any.
+ if (o.pair != null and l.peers.count() == 0 and (daemon.link < 0 or l.peers.closed)) break;
fe.sent();
upgrade.locate();
// Asked in the step (the word), done between steps: the
@@ -133,6 +145,8 @@ pub fn Loop(comptime Frontend: type) type {
if (l.core.quit) break;
if (l.core.takeRestore()) |rp| l.restore(rp);
}
+ // The clients' last word: the session ended (Exit).
+ l.peers.ended(0);
// Its serve threads read the core: they end first.
if (l.fs) |f| {
f.deinit(l.gpa);
@@ -144,17 +158,28 @@ pub fn Loop(comptime Frontend: type) type {
while (l.core.nextEffect()) |e| l.core.perform(e);
}
- /// What the daemon says, onto the frontend's queue (once: its
+ /// What the daemon says, onto the session's queue (once: its
/// reader is started by the first call); and a daemon started
/// since the last one died told the shells' masters it held.
pub fn watch(l: *L) void {
if (daemon.relinked()) l.ptys.tellDaemon();
- daemon.watch(l.fe, note);
+ daemon.watch();
}
+ /// The daemon's thread: an adopted shell onto the queue (taken
+ /// in the frontend's wait), a client's connection to `Peers`
+ /// (joined at the next step boundary), a new daemon's hello taken
+ /// a wake (`watch` tells it the rest).
fn note(ctx: *anyopaque, n: daemon.Note) void {
- const fe: *Frontend = @ptrCast(@alignCast(ctx));
- fe.note(n);
+ const l: *L = @ptrCast(@alignCast(ctx));
+ switch (n) {
+ .relinked => l.inbox.wake(),
+ .adopted => |a| {
+ for (a.pids[0..a.n], a.fds[0..a.n]) |pid, fd| l.inbox.push(.{ .adopted = .{ .pid = pid, .fd = fd } });
+ l.inbox.push(.{ .adopted = .{ .pid = 0, .fd = -1 } });
+ },
+ .replica => |j| l.peers.handed(j.fd, j.view),
+ }
}
/// A Restore: the core its dump makes replaces this one, its clients
@@ -163,7 +188,9 @@ pub fn Loop(comptime Frontend: type) type {
fn restore(l: *L, path: []const u8) void {
const nc = host_io.restoreCore(l.gpa, l.core, path, &l.peers, l.watches.fd, &l.watches.table) orelse return;
l.fe.restoring(nc);
- // An answer to the old core's query is turned away.
+ // The old core's pipes end, and an answer to its query is
+ // turned away.
+ l.inbox.pipe_tasks.cancelAll(l.io);
l.inbox.discardCompletions();
l.ptys.stop();
nc.host = l.host;
diff --git a/runtime/upgrade.zig b/runtime/upgrade.zig
index 2a8d6edf..37d4890b 100644
--- a/runtime/upgrade.zig
+++ b/runtime/upgrade.zig
@@ -22,6 +22,9 @@ const pardes = @import("core");
pub const supported = builtin.os.tag == .linux or builtin.os.tag == .freebsd;
pub const flag = "--upgraded=";
+/// A window's pair's session's first word (main.zig `pair`): its first
+/// client's fd, which an Upgrade does not name again (that client joined).
+pub const paired_flag = "--paired=";
/// What this build says it is (`pardes --version`'s first line).
pub const version_line = if (pardes.commit) |c| "pardes " ++ pardes.version ++ " (" ++ c ++ ")" else "pardes " ++ pardes.version;
@@ -46,6 +49,7 @@ var located = false;
/// deleted).
pub fn remember(args: []const [:0]const u8) void {
given = if (args.len > 1 and std.mem.startsWith(u8, args[1], flag)) args[2..] else if (args.len > 0) args[1..] else &.{};
+ if (given.len > 0 and std.mem.startsWith(u8, given[0], paired_flag)) given = given[1..];
if (resumed) |*rec| if (rec.exe.len > 0 and rec.exe.len < exe_buf.len) {
@memcpy(exe_buf[0..rec.exe.len], rec.exe);
exe_buf[rec.exe.len] = 0;
@@ -91,6 +95,14 @@ pub fn newer() bool {
return true;
}
+/// Another file at its start path than the one it started from: a build
+/// installed there since (`locate` first). A client's question at an
+/// Upgrade (client.zig).
+pub fn replaced() bool {
+ const was = started_inode orelse return false;
+ return (inodeOf(exe() orelse return false) orelse return false) != was;
+}
+
pub fn exe() ?[:0]const u8 {
return if (exe_len == 0) null else exe_buf[0..exe_len :0];
}
diff --git a/test/behaviour/panes.zig b/test/behaviour/panes.zig
index dcde9c4d..4d4c812c 100644
--- a/test/behaviour/panes.zig
+++ b/test/behaviour/panes.zig
@@ -888,7 +888,6 @@ test "panes: truncating body empties it, and a stat says the length after" {
}
test "panes: a rename colours a source its new name's language names, its text unchanged" {
- if (@import("pardes_options").grammars == .disabled) return error.SkipZigTest;
var s = try Session.initFile(std.testing.allocator, "fn check() void {}\n");
defer s.deinit();
const n = try s.focused();
diff --git a/test/behaviour/settings.zig b/test/behaviour/settings.zig
index cacee701..a6e09f35 100644
--- a/test/behaviour/settings.zig
+++ b/test/behaviour/settings.zig
@@ -158,7 +158,6 @@ test "settings: Back and Forward written to exec keep to the focused file" {
});
}
-const syntax = @import("pardes_options").grammars != .disabled;
/// The style /screen draws the cell `into` cells into the first place
/// `text` is drawn.
@@ -190,7 +189,6 @@ fn keywordsIn(s: *Session, want: []const u8) !usize {
}
test "settings: keywords stay coloured in every row a pane grows into" {
- if (!syntax) return error.SkipZigTest;
var s = try Session.initFile(std.testing.allocator, std.mem.asBytes(&@as([100][33]u8, @splat("pub fn f() void { if (true) {} }\n".*))));
defer s.deinit();
try s.write(s.at("/pane/{d}/name", .{try s.focused()}), "/resize.zig\n");
diff --git a/test/lib/bench.zig b/test/consumer/bench.zig
index 7e945064..7e945064 100644
--- a/test/lib/bench.zig
+++ b/test/consumer/bench.zig
diff --git a/test/consumer/build.zig b/test/consumer/build.zig
new file mode 100644
index 00000000..ca63bb6e
--- /dev/null
+++ b/test/consumer/build.zig
@@ -0,0 +1,42 @@
+//! A package that depends on pardes, as a program would (build.zig's head
+//! comment has its lines): pardes's `lib-test`, which `unit-test` runs,
+//! runs `zig build test` here. `pardes-syntax` with the minimal grammars,
+//! as a program that draws source text itself takes it; and
+//! `pardes-editor` with no grammar of pardes's and one of its own, C's,
+//! compiled here from the package pardes pins and handed in at run time,
+//! as sketchbook's `examples/live` takes it.
+const std = @import("std");
+
+pub fn build(b: *std.Build) void {
+ const target = b.standardTargetOptions(.{});
+ const optimize = b.standardOptimizeOption(.{});
+ const syntax = b.dependency("pardes", .{ .target = target, .optimize = optimize, .grammars = .minimal });
+ const editor = b.dependency("pardes", .{ .target = target, .optimize = optimize, .grammars = .none, .editor = true });
+ // The grammar of its own: C's, from the package pardes's manifest pins
+ // (so `--pkg-dir` at pardes's zig-pkg has it), as that package builds it.
+ const grammar = b.dependency("ts_c", .{ .target = target, .optimize = .ReleaseFast, .@"build-shared" = false }).artifact("tree-sitter-c");
+ const step = b.step("test", "colour, outline and walk a C and a Zig source through pardes's syntax, and edit a text with its editor and a grammar of this package's");
+ // A file belongs to one module: the syntax alone, and the editor (which
+ // has it as `.syntax`), each a test of its own.
+ for ([_]struct { []const u8, []const u8, *std.Build.Dependency }{ .{ "lib.zig", "pardes-syntax", syntax }, .{ "editor.zig", "pardes-editor", editor } }) |t| {
+ const mod = b.createModule(.{
+ .target = target,
+ .optimize = optimize,
+ .root_source_file = b.path(t[0]),
+ .imports = &.{.{ .name = t[1], .module = t[2].module(t[1]) }},
+ });
+ if (t[2] == editor) mod.linkLibrary(grammar);
+ step.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = mod })).step);
+ }
+ // What a key costs, a page count and a parse: `zig build bench -- <KiB> <keys>`.
+ const bench = b.addExecutable(.{ .name = "bench", .root_module = b.createModule(.{
+ .target = target,
+ .optimize = optimize,
+ .root_source_file = b.path("bench.zig"),
+ .imports = &.{.{ .name = "pardes-editor", .module = editor.module("pardes-editor") }},
+ }) });
+ bench.root_module.linkLibrary(grammar);
+ const run_bench = b.addRunArtifact(bench);
+ run_bench.addPassthruArgs();
+ b.step("bench", "a key typed into the library's editor at a size, its pages and a parse").dependOn(&run_bench.step);
+}
diff --git a/test/consumer/build.zig.zon b/test/consumer/build.zig.zon
new file mode 100644
index 00000000..c367775b
--- /dev/null
+++ b/test/consumer/build.zig.zon
@@ -0,0 +1,16 @@
+.{
+ .name = .pardes_consumer,
+ .version = "0.0.0",
+ .dependencies = .{
+ .pardes = .{ .path = "../.." },
+ // The grammar this package hands pardes's editor: the one pardes's
+ // own manifest pins, so `--pkg-dir` at its zig-pkg has it.
+ .ts_c = .{
+ .url = "git+https://github.com/pierrelgol/tree-sitter-c#67949e4c8dc630c18a522919f2bde2e025a0d025",
+ .hash = "tree_sitter_c-0.24.2-y5boS-htQACe3pz6jHq4tpS8dB6WIo4-zk_ct7lAjvQT",
+ },
+ },
+ .minimum_zig_version = "0.17.1",
+ .paths = .{""},
+ .fingerprint = 0xb5ce4ba417a79812,
+}
diff --git a/test/lib/editor.zig b/test/consumer/editor.zig
index 22690915..22690915 100644
--- a/test/lib/editor.zig
+++ b/test/consumer/editor.zig
diff --git a/test/lib/lib.zig b/test/consumer/lib.zig
index 7e297920..7e297920 100644
--- a/test/lib/lib.zig
+++ b/test/consumer/lib.zig
diff --git a/test/daemon.py b/test/daemon.py
index 52c7d1e6..b28d16ea 100644
--- a/test/daemon.py
+++ b/test/daemon.py
@@ -25,8 +25,13 @@ private HOME and runtime directory:
`ssh -L` forwards, say), timed
python3 -B test/daemon.py --clients <pardes>
the replica clients alone
+ python3 -B test/daemon.py --launch <pardes>
+ `pardes new --detach` returns once its session runs
+ python3 -B test/daemon.py --pair <pardes>
+ PARDES_PAIR: a terminal's session and its first client
python3 -B test/daemon.py --relink <pardes>
- the daemon killed: its sessions register again with the next
+ the daemon killed: its sessions register again with the next; and
+ one stopped: an Adopt waits for its answer to the hello
python3 -B test/daemon.py --far <pardes>
the far clients and their blob cache alone, and a file by its hash
python3 -B test/daemon.py --games <pardes> <lib> [seconds]
@@ -236,7 +241,7 @@ class Replica:
"""A replica's connection (abi/wire.zig): length-prefixed
messages, a tag byte and a little-endian u32 length. It is a near
client: its first word after the hello says so."""
- WIRE = 23
+ WIRE = 24
def __init__(self, path, timeout=10):
self.path, self.timeout = path, timeout
@@ -265,8 +270,11 @@ class Replica:
is read, whole. A daemon of another replica protocol (an older
build's, across an Upgrade) is dialled again in its own."""
name = session.encode()
- self.send(0x01, struct.pack('<HQH', wire or self.WIRE, build, len(name)) + name + b'\xff')
- self.send(0x06, b'\x00')
+ # Its first word (not far) in the same write, as a client's join
+ # sends it (core/replica.zig joinOn): a refused hello's connection
+ # is closed, and a second write after it would meet that.
+ hello = struct.pack('<HQH', wire or self.WIRE, build, len(name)) + name + b'\xff'
+ self.s.sendall(struct.pack('<BI', 0x01, len(hello)) + hello + struct.pack('<BIB', 0x06, 1, 0))
tag, body = self.read()
if tag == 0x01:
pid, n = struct.unpack_from('<IH', body)
@@ -479,10 +487,10 @@ def clients(binary):
wait_for('client A out of insert mode', lambda: normal_again(ta))
wait_for('client A agrees again', lambda: agreed(root / 'a.check', seen))
assert sess.poll() is None
- # Detach typed in it: it alone goes.
+ # Detach typed in it: it alone goes, and says so (exit 0).
os.write(ta.master, b' sD')
wait_for('client A let go', lambda: a.poll() is not None, timeout=10)
- assert b'let this client go' in ta.text(), ta.text()[-300:]
+ assert a.returncode == 0 and b"detached from 'files', which is still running" in ta.text(), ta.text()[-300:]
# A third client, a shell: its keys wait for the session (a pty
# write), its output comes back in units, the same on both sides.
nine.write(f'/pane/{pane}/exec', b'Term\n')
@@ -526,6 +534,238 @@ def clients(binary):
shutil.rmtree(root, ignore_errors=True)
+def launch(binary):
+ """`pardes new --detach=NAME` returns once its session is registered
+ and listening: exit 0, the name on stdout, the session a process of its
+ own in a session of its own, listed by `ps` and answering 9P at once;
+ bare `--detach`, its pid is its name; a name taken is refused in words,
+ exit 1; `pardes --detach=NAME` (no `new`) is still the session itself;
+ nothing left behind."""
+ scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn'
+ scratch.mkdir(parents=True, exist_ok=True)
+ root = Path(tempfile.mkdtemp(prefix='rl-', dir=scratch))
+ env = {k: v for k, v in os.environ.items() if not k.startswith('PARDES_') and 'PAGER' not in k}
+ env.update(HOME=str(root), XDG_RUNTIME_DIR=str(root), XDG_CONFIG_HOME=str(root / 'config'),
+ TERM='xterm-256color', SHELL=shutil.which('bash') or '/bin/bash', PARDES_NOTIME='1')
+ (root / 'config' / 'pardes').mkdir(parents=True)
+ (root / 'config' / 'pardes' / 'init').write_text('Shell bash\nMessageLinger 0\n')
+ (root / 'notes.txt').write_text('notes\n')
+
+ def cli(*args, timeout=30):
+ return subprocess.run([binary, *args], env=env, cwd=root, capture_output=True, timeout=timeout,
+ stdin=subprocess.DEVNULL)
+
+ def status_pid(name):
+ with Client(root / f'pardes-9p-{name}.sock') as c:
+ return int(dict(line.split(maxsplit=1) for line in c.read('/status').decode().splitlines())['pid'])
+
+ try:
+ t0 = time.monotonic()
+ try:
+ out = cli('new', '--detach=work', 'notes.txt', timeout=15)
+ except subprocess.TimeoutExpired:
+ raise AssertionError(f'launch: `new --detach=work` had not returned after {time.monotonic() - t0:.1f} s')
+ took = time.monotonic() - t0
+ assert out.returncode == 0 and out.stdout == b'work\n', out
+ # Registered and listening when it returned: no wait here.
+ assert (root / 'pardes-9p-work.sock').exists(), list(root.iterdir())
+ pid = status_pid('work')
+ listed = cli('ps').stdout.decode()
+ assert f'session work {pid} (tty, detached)' in listed, listed
+ assert alive(pid) and os.getsid(pid) == pid, (pid, os.getsid(pid))
+ out = cli('new', '--detach')
+ assert out.returncode == 0 and out.stdout.strip().isdigit(), out
+ unnamed = int(out.stdout)
+ assert status_pid(str(unnamed)) == unnamed and f'session {unnamed} {unnamed} (tty, detached)' in cli('ps').stdout.decode()
+ taken = cli('new', '--detach=work')
+ assert taken.returncode == 1 and taken.stderr == b'pardes: a session named work is already running\n', taken
+ # The flag alone runs the session in this process, as a supervisor
+ # or a harness wants it.
+ fg = subprocess.Popen([binary, '--detach=fg'], env=env, cwd=root, stdin=subprocess.DEVNULL,
+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True)
+ wait_for('the foreground session\'s socket', (root / 'pardes-9p-fg.sock').exists)
+ assert status_pid('fg') == fg.pid and fg.poll() is None
+ print(f'launch: `new --detach=work` returned 0 in {took:.2f} s with its name, session {pid} listed and listening '
+ f'in a session of its own; unnamed it said {unnamed}; a taken name refused; `--detach=fg` is its own session')
+ for name in ('work', str(unnamed), 'fg'):
+ assert cli('kill', name).returncode == 0
+ fg.wait(timeout=10)
+ wait_for('nothing left', lambda: not [p for p in processes(root) if alive(p)], timeout=10)
+ print('launch: nothing left behind')
+ finally:
+ for p in processes(root):
+ try:
+ os.kill(p, signal.SIGKILL)
+ except OSError:
+ pass
+ shutil.rmtree(root, ignore_errors=True)
+
+
+def pair(binary):
+ """PARDES_PAIR: `pardes FILE` in a terminal is a session forked off for
+ it with this terminal its first client (the last step's design, 1.1):
+ the job the client, the terminal its own; the session its child, in a
+ session of its own, registered (`ps`: detached, the client listed),
+ the file drawn, keys in, the digests agreed once quiet; the session's
+ Exit ends both. With no daemon the client killed outright ends the
+ session (its last link). Nothing left behind."""
+ scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn'
+ scratch.mkdir(parents=True, exist_ok=True)
+ root = Path(tempfile.mkdtemp(prefix='rp-', dir=scratch))
+ env = {k: v for k, v in os.environ.items() if not k.startswith('PARDES_') and 'PAGER' not in k}
+ env.update(HOME=str(root), XDG_RUNTIME_DIR=str(root), XDG_CONFIG_HOME=str(root / 'config'),
+ TERM='xterm-256color', SHELL=shutil.which('bash') or '/bin/bash', PARDES_NOTIME='1', PARDES_PAIR='1')
+ (root / 'config' / 'pardes').mkdir(parents=True)
+ (root / 'config' / 'pardes' / 'init').write_text('Shell bash\nMessageLinger 0\n')
+ notes = root / 'notes.txt'
+ notes.write_text(''.join(f'line {i} of the notes\n' for i in range(30)))
+ terms = []
+
+ def session_of(name):
+ sock = root / f'pardes-9p-{name}.sock'
+ wait_for(f'session {name}\'s 9P socket', sock.exists)
+ nine = Client(sock)
+ return nine, int(dict(line.split(maxsplit=1) for line in nine.read('/status').decode().splitlines())['pid'])
+
+ try:
+ t = Term(30, 100)
+ terms.append(t)
+ c = t.spawn([binary, '--9p=pair', str(notes)], dict(env, PARDES_REPLICA_CHECK=str(root / 'pair.check')))
+ nine, session = session_of('pair')
+ assert session != c.pid and ppid(session) == c.pid and os.getsid(session) == session, (session, c.pid)
+ wait_for('the file drawn on the terminal', lambda: b'line 3 of the notes' in t.text(), timeout=30)
+ listed = lambda: subprocess.run([binary, 'ps'], env=env, capture_output=True).stdout.decode()
+ wait_for('the client listed', lambda: f'session pair {session} (tty, detached)' in listed()
+ and f'client {c.pid} ' in listed())
+ pane = next(int(row.split()[0]) for row in nine.read('/index').splitlines() if row.split()[1] == b'text')
+ os.write(t.master, b'Ofrom-the-pair\x1b')
+ wait_for('its keys in the session\'s text', lambda: b'from-the-pair' in nine.read(f'/pane/{pane}/body'))
+ wait_for('out of insert mode', lambda: normal_again(t))
+ wait_for('the client agrees once quiet', lambda: agreed(root / 'pair.check', 0))
+ exit_session(nine, pane)
+ code = c.wait(timeout=60)
+ assert code == 0 and not alive(session), (code, alive(session))
+ print(f'pair: client {c.pid} (the job) and session {session} (its child, setsid, listed detached with the client); '
+ f'drawn, typed, agreed; Exit ended both (the client exit {code})')
+ nine.socket.close()
+ lone = Term(24, 80)
+ terms.append(lone)
+ c2 = lone.spawn([binary, '--9p=lone', str(notes)], dict(env, PARDES_DAEMON='off'))
+ nine2, session2 = session_of('lone')
+ wait_for('the lone pair drawn', lambda: b'line 3 of the notes' in lone.text(), timeout=30)
+ # An Upgrade refused, with why: its client could not find it again.
+ nine2.write('/ctl', b'Upgrade\n')
+ wait_for('the Upgrade refused', lambda: 'its client could not join it again' in screen_text(nine2), timeout=20)
+ assert alive(session2) and c2.poll() is None
+ nine2.socket.close()
+ os.kill(c2.pid, signal.SIGKILL)
+ c2.wait(timeout=10)
+ wait_for('the lone session ended with its last link', lambda: not alive(session2), timeout=20)
+ wait_for('nothing left', lambda: not [p for p in processes(root) if alive(p)], timeout=20)
+ print(f'pair: with no daemon, an Upgrade refused in words; client {c2.pid} killed outright, its session {session2} ended; nothing left behind')
+ finally:
+ for p in processes(root):
+ try:
+ os.kill(p, signal.SIGKILL)
+ except OSError:
+ pass
+ for t in terms:
+ t.close()
+ shutil.rmtree(root, ignore_errors=True)
+
+
+def pair_rows(binary):
+ """PARDES_PAIR, the shell's view (the last step's design, 1.1) and a
+ session's lifetime (2.2 B), one row a step. With a daemon: a Detach in
+ the pair's client says so and exits 0, the session runs on (listed); an
+ attach is a client again; TERM to the client puts its terminal back and
+ the session runs on; so does a KILL, and a closed terminal (HUP): each a
+ loss, not a close. With none: a Detach refused (nothing could attach),
+ the client on; its terminal closed, the session ends with its last link."""
+ scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn'
+ scratch.mkdir(parents=True, exist_ok=True)
+ root = Path(tempfile.mkdtemp(prefix='rq-', dir=scratch))
+ env = {k: v for k, v in os.environ.items() if not k.startswith('PARDES_') and 'PAGER' not in k}
+ env.update(HOME=str(root), XDG_RUNTIME_DIR=str(root), XDG_CONFIG_HOME=str(root / 'config'),
+ TERM='xterm-256color', SHELL=shutil.which('bash') or '/bin/bash', PARDES_NOTIME='1', PARDES_PAIR='1')
+ (root / 'config' / 'pardes').mkdir(parents=True)
+ (root / 'config' / 'pardes' / 'init').write_text('Shell bash\nMessageLinger 0\n')
+ notes = root / 'notes.txt'
+ notes.write_text(''.join(f'line {i} of the notes\n' for i in range(30)))
+ terms = []
+
+ def listed():
+ return subprocess.run([binary, 'ps'], env=env, capture_output=True).stdout.decode()
+
+ def drawn(t):
+ wait_for('drawn', lambda: b'line 3 of the notes' in t.text(), timeout=30)
+
+ def typed_detach(t, nine, pane):
+ # Its view the live one (it typed last), then the word.
+ os.write(t.master, b'j')
+ time.sleep(.3)
+ nine.write(f'/pane/{pane}/exec', b'Detach\n')
+
+ def started(name, e):
+ t = Term(30, 100)
+ terms.append(t)
+ c = t.spawn([binary, f'--9p={name}', str(notes)], e)
+ wait_for('the socket', (root / f'pardes-9p-{name}.sock').exists)
+ nine = Client(root / f'pardes-9p-{name}.sock')
+ session = int(dict(line.split(maxsplit=1) for line in nine.read('/status').decode().splitlines())['pid'])
+ pane = next(int(row.split()[0]) for row in nine.read('/index').splitlines() if row.split()[1] == b'text')
+ drawn(t)
+ return t, c, nine, session, pane
+
+ try:
+ t, c, nine, session, pane = started('rows', env)
+ typed_detach(t, nine, pane)
+ assert c.wait(timeout=20) == 0, c.returncode
+ wait_for('the detach said', lambda: b"pardes: detached from 'rows', which is still running; come back with `pardes attach rows`" in t.text())
+ assert alive(session) and f'session rows {session} (tty, detached)' in listed()
+ print('pair rows: Detach in the client: said, exit 0; the session runs on, listed')
+ for how in ('TERM', 'KILL', 'HUP'):
+ tt = Term(30, 100)
+ terms.append(tt)
+ a = tt.spawn([binary, 'attach', 'rows'], env)
+ drawn(tt)
+ wait_for('the client listed', lambda: f'client {a.pid} ' in listed())
+ if how == 'HUP':
+ tt.close()
+ terms.remove(tt)
+ else:
+ os.kill(a.pid, getattr(signal, 'SIG' + how))
+ a.wait(timeout=20)
+ if how == 'TERM':
+ wait_for('its terminal put back', lambda: tt.text().rfind(b'\x1b[?1049l') > tt.text().rfind(b'\x1b[?1049h'))
+ wait_for('the client unlisted', lambda: f'client {a.pid} ' not in listed())
+ assert alive(session), how
+ print(f'pair rows: a client ended by {how}: the session runs on')
+ nine.socket.close()
+ assert subprocess.run([binary, 'kill', 'rows'], env=env, capture_output=True, timeout=30).returncode == 0
+ wait_for('the session ended', lambda: not alive(session), timeout=30)
+ t, c, nine, session, pane = started('lone', dict(env, PARDES_DAEMON='off'))
+ typed_detach(t, nine, pane)
+ time.sleep(1)
+ assert c.poll() is None and alive(session), 'a Detach with no daemon is refused'
+ nine.socket.close()
+ t.close()
+ terms.remove(t)
+ c.wait(timeout=20)
+ wait_for('the lone session ended with its last link', lambda: not alive(session), timeout=20)
+ wait_for('nothing left', lambda: not [p for p in processes(root) if alive(p)], timeout=20)
+ print('pair rows: no daemon: a Detach refused, the client on; its terminal closed, the session ended; nothing left')
+ finally:
+ for p in processes(root):
+ try:
+ os.kill(p, signal.SIGKILL)
+ except OSError:
+ pass
+ for t in terms:
+ t.close()
+ shutil.rmtree(root, ignore_errors=True)
+
+
def manage(binary):
"""`pardes --ps`, `--kill=NAME` and `--kill-all`: two detached sessions
and their shells listed, one session killed outright and its shell
@@ -736,6 +976,78 @@ def relink(binary):
shutil.rmtree(root, ignore_errors=True)
+def answer_late(binary):
+ """A session's Adopt asked at once, while its daemon has not answered
+ its hello (stopped 3 s, as a loaded machine can keep it), and before
+ the session's reader of the daemon has run: answered when the daemon
+ answers, never refused on a clock (daemon.zig `kept`)."""
+ scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn'
+ scratch.mkdir(parents=True, exist_ok=True)
+ root = Path(tempfile.mkdtemp(prefix='ra-', dir=scratch))
+ env = {k: v for k, v in os.environ.items() if not k.startswith('PARDES_') and 'PAGER' not in k}
+ env.update(HOME=str(root), XDG_RUNTIME_DIR=str(root), XDG_CONFIG_HOME=str(root / 'config'),
+ TERM='xterm-256color', SHELL=shutil.which('bash') or '/bin/bash', PARDES_NOTIME='1')
+ (root / 'config' / 'pardes').mkdir(parents=True)
+ (root / 'config' / 'pardes' / 'init').write_text('Shell bash\nMessageLinger 0\n')
+ started = []
+ terms = []
+ wake = None
+ try:
+ term = Term()
+ terms.append(term)
+ stub = term.spawn([binary, '--tty', '--9p=one'], env)
+ started.append(stub.pid)
+ wait_for('the first session', (root / 'pardes-9p-one.sock').exists)
+ one = Client(root / 'pardes-9p-one.sock')
+ session = int(dict(line.split(maxsplit=1) for line in one.read('/status').decode().splitlines())['pid'])
+ started.append(session)
+ shell_pid = int(run(one, terminals(one)[0], b'echo $$\n').split(b'\n')[1])
+ started.append(shell_pid)
+ daemon = [p for p in processes(root) if cmdline(p)[1:2] == [b'--daemon']][0]
+ started.append(daemon)
+ wait_for('its shell listed', lambda: f'shell {shell_pid}' in subprocess.run(
+ [binary, '--ps'], env=env, capture_output=True, timeout=30).stdout.decode())
+ os.kill(session, signal.SIGKILL)
+ one.socket.close()
+ wait_for('the killed session gone', lambda: not alive(session))
+ os.kill(daemon, signal.SIGSTOP)
+ wake = threading.Timer(3, lambda: os.kill(daemon, signal.SIGCONT))
+ wake.start()
+ term = Term()
+ terms.append(term)
+ stub = term.spawn([binary, '--tty', '--9p=two'], env)
+ started.append(stub.pid)
+ wait_for('the next session', (root / 'pardes-9p-two.sock').exists)
+ two = Client(root / 'pardes-9p-two.sock', timeout=30)
+ started.append(int(dict(line.split(maxsplit=1) for line in two.read('/status').decode().splitlines())['pid']))
+ before = set(terminals(two))
+ asked = time.monotonic()
+ two.write(f'/pane/{min(before)}/exec', b'Adopt\n')
+ took = time.monotonic() - asked
+ pane = wait_for('the adopted pane', lambda: set(terminals(two)) - before).pop()
+ assert run(two, pane, b'echo $$\n').split(b'\n')[1] == str(shell_pid).encode()
+ print(f'answer late: an Adopt asked while the daemon was stopped waited {took:.1f} s for its answer, '
+ f'and shell {shell_pid} was adopted')
+ exit_session(two, pane)
+ two.socket.close()
+ wait_for('the shells hung up', lambda: not alive(shell_pid))
+ wait_for('the daemon gone once idle', lambda: not alive(daemon), timeout=5)
+ finally:
+ if wake:
+ wake.cancel()
+ for t in terms:
+ try:
+ t.close()
+ except OSError:
+ pass
+ for pid in started + processes(root):
+ try:
+ os.kill(pid, signal.SIGKILL)
+ except (ProcessLookupError, PermissionError):
+ pass
+ shutil.rmtree(root, ignore_errors=True)
+
+
class Window:
"""A pardes-gui in test mode, its window offscreen and hidden, its keys
written to its stdin (the test feed: Escape as `CSI 27 u`, which a
@@ -966,10 +1278,10 @@ def window_clients(binary, gui_binary):
wait_for('the window\'s keys after the upgrade', lambda: b'after-upgrade-W' in body(), timeout=30)
wait_for('the window client agrees after the upgrade', lambda: agreed(dcheck, seen), timeout=30)
assert wd.p.poll() is None
- # Detach typed in it: it alone goes, and says why.
+ # Detach typed in it: it alone goes, and says so (exit 0).
wd.keys(b' sD')
wait_for('the window client let go', lambda: wd.p.poll() is not None, timeout=15)
- assert 'let this client go' in wd.said(), wd.said()[-500:]
+ assert wd.p.returncode == 0 and "detached from 'files', which is still running" in wd.said(), wd.said()[-500:]
# A link a line: the first join sent every blob, its rejoins held them.
links = joins(root / 'wd.stats')
assert len(links) == 3 and links[0]['blobs'] > 0 and links[0]['from_memory'] + links[0]['from_disk'] == 0, links
@@ -1183,12 +1495,13 @@ def far(binary):
f_join = joins(root / 'f.stats')[0]
assert f_join['from_disk'] > 0 and cached(cache) <= (1 << 20) + (64 << 10), (f_join, cached(cache))
far_joins(root / 'pardes-replica.sock', 'files', binary, 200)
- # Through ssh (a stand-in forwarding as `ssh -L` does): a client
- # refused and one detached each end their ssh and its socket (one
- # refused left both, 2026-10-30).
+ # Through ssh (a stand-in forwarding as `ssh -L` does, its socket
+ # bound 0.5 s before it listens: the client dials until it answers):
+ # a client refused and one detached each end their ssh and its
+ # socket (one refused left both, 2026-10-30).
fake = root / 'ssh'
fake.write_text('#!/bin/sh\nwhile [ $# -gt 0 ]; do case $1 in -L) fwd=$2; shift;; esac; shift; done\n'
- f'exec {sys.executable} -B {Path(__file__).parent / "delay_relay.py"} "${{fwd%%:*}}" "${{fwd#*:}}" --delay 0\n')
+ f'exec {sys.executable} -B {Path(__file__).parent / "delay_relay.py"} "${{fwd%%:*}}" "${{fwd#*:}}" --delay 0 --bound 500\n')
fake.chmod(0o755)
senv = dict(env, PARDES_SSH=str(fake), PARDES_REMOTE_RUNTIME=str(root), TMPDIR=str(root))
@@ -1272,7 +1585,10 @@ def by_hash(binary):
started.append(sess.pid)
wait_for('the replica socket', (root / 'pardes-replica.sock').exists)
wait_for('the session\'s 9P socket', (root / 'pardes-9p-files.sock').exists)
- nine = Client(root / 'pardes-9p-files.sock')
+ # Each reply waited for as long as the opens it answers take: the
+ # 17 MiB file's Look took 1.6-6.6 s in a Debug build at a load of
+ # 35 (ninep.py's 5 s is a reply's whole wait).
+ nine = Client(root / 'pardes-9p-files.sock', timeout=60)
pane = next(int(row.split()[0]) for row in nine.read('/index').splitlines() if row.split()[1] == b'text')
(ta, a), (tf, f) = client('a', False), client('f', True)
seen = {n: len(checks(root / f'{n}.check')) for n in 'af'}
@@ -1653,8 +1969,12 @@ def main(binary, cycles):
clients(binary)
far(binary)
by_hash(binary)
+ launch(binary)
+ pair(binary)
+ pair_rows(binary)
manage(binary)
relink(binary)
+ answer_late(binary)
shell = terminals(client)[0]
shell_pid = int(run(client, shell, b'echo $$\n').split(b'\n')[1])
started.append(shell_pid)
@@ -1689,8 +2009,8 @@ def main(binary, cycles):
terminal closed: it ends; the session and its shell run on."""
if how == 'detach':
client.write(f'/pane/{shell}/exec', b'Detach\n')
- assert c.wait(timeout=10) == 1, c.returncode
- wait_for('the client says it was let go', lambda: b'let this client go' in term.text())
+ assert c.wait(timeout=10) == 0, c.returncode
+ wait_for('the client says it detached', lambda: b"detached from 'work', which is still running" in term.text())
else:
term.close()
c.wait(timeout=10)
@@ -1818,8 +2138,8 @@ def main(binary, cycles):
# The end: the session quits, its shells hang up, its client and
# the daemon go.
exit_session(client, pane)
- assert stub.wait(timeout=10) == 1, stub.returncode
- wait_for('the client says it was let go', lambda: b'let this client go' in term.text())
+ assert stub.wait(timeout=10) == 0, stub.returncode
+ assert b'let this client go' not in term.text(), term.text()[-300:]
client.socket.close()
term.close()
wait_for('the adopted shell hung up', lambda: not alive(shell_pid))
@@ -1936,6 +2256,90 @@ def gui(binary, cycles):
shutil.rmtree(root, ignore_errors=True)
+def gui_pair(gui_binary):
+ """PARDES_PAIR in a window (the last step's design, 1.2): `pardes-gui
+ FILE` is a window client and a session with no SDL, the `pardes` beside
+ it exec'd in a child (a window's session needs SDL for its wake, a
+ terminal's binary none): the session the window's child, in a session
+ of its own, listed detached with the window its client; the file in
+ the window's first frame, keys in. The window's close ends the session,
+ its last client (a CLOSE); the window killed leaves it running (a LOSS),
+ and with no daemon the session ends with its last link. Test mode:
+ hidden windows, offscreen."""
+ binary = gui_binary.replace('pardes-gui', 'pardes')
+ scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn'
+ scratch.mkdir(parents=True, exist_ok=True)
+ root = Path(tempfile.mkdtemp(prefix='rgp-', dir=scratch))
+ env = {k: v for k, v in os.environ.items() if not k.startswith('PARDES_') and 'PAGER' not in k}
+ env.update(HOME=str(root), XDG_RUNTIME_DIR=str(root), XDG_CONFIG_HOME=str(root / 'config'),
+ SHELL='/bin/bash', PARDES_NOTIME='1', PARDES_DAEMON='on', TERM='xterm-256color', PARDES_PAIR='1')
+ (root / 'config' / 'pardes').mkdir(parents=True)
+ (root / 'config' / 'pardes' / 'init').write_text('Shell bash\nMessageLinger 0\n')
+ notes = root / 'notes.txt'
+ notes.write_text(''.join(f'line {i} of the notes\n' for i in range(30)))
+ windows = []
+
+ def listed():
+ return subprocess.run([binary, 'ps'], env=env, capture_output=True, timeout=30).stdout.decode()
+
+ def started(name, e):
+ w = Window(root, name, [gui_binary, f'--9p={name}', str(notes)], e)
+ windows.append(w)
+ sock = root / f'pardes-9p-{name}.sock'
+ wait_for(f'session {name}\'s 9P socket', sock.exists, timeout=30)
+ nine = Client(sock)
+ session = int(dict(line.split(maxsplit=1) for line in nine.read('/status').decode().splitlines())['pid'])
+ assert session != w.pid and ppid(session) == w.pid and os.getsid(session) == session, (session, w.pid)
+ assert Path(cmdline(session)[0].decode()).name == 'pardes', ('the session is the pardes beside it', cmdline(session))
+ wait_for('the window\'s first frame', lambda: (root / name / 'latest.ppm').exists(), timeout=30)
+ pane = next(int(row.split()[0]) for row in nine.read('/index').splitlines() if row.split()[1] == b'text')
+ assert nine.read(f'/pane/{pane}/body').startswith(b'line 0 of the notes'), 'the file is the session\'s'
+ return w, nine, session, pane
+
+ try:
+ w, nine, session, pane = started('gp', env)
+ wait_for('the window listed its client', lambda: f'session gp {session} (tty, detached)' in listed()
+ and f'client {w.pid} ' in listed())
+ w.keys(b'Ofrom-the-window\x1b')
+ wait_for('its keys in the session\'s text', lambda: b'from-the-window' in nine.read(f'/pane/{pane}/body'))
+ # The close button (the test feed's word for it): its last client
+ # closed, the session ends.
+ w.p.stdin.write(b'\x1b]777;close\x07')
+ w.p.stdin.flush()
+ assert w.p.wait(timeout=30) == 0, (w.p.returncode, w.said()[-400:])
+ wait_for('the session ended with its window', lambda: not alive(session), timeout=20)
+ nine.socket.close()
+ print(f'pair window: client {w.pid} (the window) and session {session} (the pardes beside it, exec\'d in its child, '
+ 'setsid, listed detached with the window); drawn, typed; the window closed ended both')
+ w, nine, session, pane = started('gl', env)
+ wait_for('the client listed', lambda: f'client {w.pid} ' in listed())
+ os.kill(w.pid, signal.SIGKILL)
+ w.p.wait(timeout=10)
+ wait_for('the client unlisted', lambda: f'client {w.pid} ' not in listed())
+ assert alive(session) and f'session gl {session} (tty, detached)' in listed(), listed()
+ nine.socket.close()
+ assert subprocess.run([binary, 'kill', 'gl'], env=env, capture_output=True, timeout=30).returncode == 0
+ wait_for('the session ended', lambda: not alive(session), timeout=30)
+ print('pair window: the window killed: the session runs on, listed (a loss); killed by name')
+ w, nine, session, pane = started('gn', dict(env, PARDES_DAEMON='off'))
+ nine.socket.close()
+ os.kill(w.pid, signal.SIGKILL)
+ w.p.wait(timeout=10)
+ wait_for('the lone session ended with its last link', lambda: not alive(session), timeout=20)
+ wait_for('nothing left', lambda: not [p for p in processes(root) if alive(p)], timeout=20)
+ print('pair window: with no daemon, the window killed, its session ended; nothing left behind')
+ finally:
+ for w in windows:
+ if w.p.poll() is None:
+ w.p.kill()
+ for p in processes(root):
+ try:
+ os.kill(p, signal.SIGKILL)
+ except OSError:
+ pass
+ shutil.rmtree(root, ignore_errors=True)
+
+
def screen_text(client):
shown = client.screen()
cells = ''.join(cell[0] for cell in shown['cells'])
@@ -2116,7 +2520,9 @@ def upgrades(old, new):
# its terminal and its stub's pipe let go once its stub is told
# (two fewer).
def level():
- gone = 2 if b'detached from' in term2.text() else 1
+ # (A client of a build that execs at an Upgrade comes back: its
+ # connection is the session's again.)
+ gone = 2 if b'detached from' in term2.text() else 0 if knows_exec(old) and stub2.poll() is None else 1
return fds_before[0] - 2 - gone + min(state_fds(session), 1) - state_before, fds_before[1]
try:
wait_for('the fds level', lambda: (fds(session), fds(daemon)) == level(), timeout=5)
@@ -2136,7 +2542,9 @@ def upgrades(old, new):
# build's own, let go (a session shows one frontend of its own now),
# its stub told.
wait_for('the second terminal redrawn or let go', lambda: b'\x1b[?1049h' in term2.text()[before[1]:] or
- (stub2.poll() is not None and (b'detached from' in term2.text() or b'upgrade this client too' in term2.text())))
+ (stub2.poll() is not None and (b'detached from' in term2.text() or b'upgrade this client too' in term2.text()
+ or b'run the same pardes at both ends' in term2.text())),
+ timeout=30)
wait_for('the word said', lambda: 'Upgrade: now pardes' in screen_text(client))
# The daemon lists the session under its new build.
said = Replica(root / 'pardes-replica.sock').hello('work', new_build)
@@ -2225,7 +2633,10 @@ def upgrades(old, new):
install(new, binary)
os.kill(session, signal.SIGKILL)
stub.wait(timeout=10)
- stub2.wait(timeout=10)
+ try:
+ stub2.wait(timeout=30)
+ except subprocess.TimeoutExpired:
+ raise AssertionError(('the second terminal\'s client on', cmdline(stub2.pid), term2.text()[-1200:]))
client.socket.close()
term.close()
term2.close()
@@ -2238,10 +2649,15 @@ def upgrades(old, new):
sock = root / 'pardes-9p-again.sock'
wait_for('the next session', sock.exists)
client = Client(sock)
- started.append(int(dict(line.split(maxsplit=1) for line in client.read('/status').decode().splitlines())['pid']))
- # Its reader of the daemon starts after its first frame: an Adopt
- # before that waits for an `ok` nobody reads, and is refused.
+ again = int(dict(line.split(maxsplit=1) for line in client.read('/status').decode().splitlines())['pid'])
+ started.append(again)
+ # A build before daemon.zig's `kept` waited for the hello's answer
+ # (the new-to-old run) refused an Adopt before its reader of the
+ # daemon ran (after its first frame), or within 2 s of a slow `ok`:
+ # it is asked once the daemon lists it (answer_late tests the wait).
wait_for('the next session\'s first frame', lambda: b'\x1b[?1049h' in term.text())
+ wait_for('the next session listed by the daemon', lambda: f'session again {again} ' in subprocess.run(
+ [str(binary), '--ps'], env=env, capture_output=True, timeout=30).stdout.decode())
before = set(terminals(client))
client.write(f'/pane/{min(before)}/exec', b'Adopt\n')
pane = wait_for('the adopted pane', lambda: set(terminals(client)) - before).pop()
@@ -2265,6 +2681,124 @@ def upgrades(old, new):
shutil.rmtree(root, ignore_errors=True)
+def knows_exec(binary):
+ """Whether a build's client execs the build at its start path at an
+ Upgrade, for the view it is handed (PARDES_JOIN_VIEW)."""
+ return b'PARDES_JOIN_VIEW' in Path(binary).read_bytes()
+
+
+def upgrade_clients(old, new):
+ """Upgrade with near clients (the last step's design, 1.4): a session
+ (`new --detach`) with a terminal client and a window client attached,
+ each in its own view with a pane of its own there, onto another build installed at the path all three were
+ started from. A client of a build that execs (its start path holding
+ another file than the one it runs, the session another build than its
+ own) comes back on the build at its start path, the same process, for
+ its view: the terminal's leaves its screen and enters it again (the
+ blink), the window is a new one; in ITS view when that build joins for
+ a view it is handed (PARDES_JOIN_VIEW), else in a view of its own. One
+ of a build before it is let go and told to upgrade too. The session's
+ shell alive throughout; nothing left behind."""
+ old_gui, new_gui = old.with_name('pardes-gui'), new.with_name('pardes-gui')
+ scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn'
+ scratch.mkdir(parents=True, exist_ok=True)
+ root = Path(tempfile.mkdtemp(prefix='ruc-', dir=scratch))
+ env = {k: v for k, v in os.environ.items() if not k.startswith('PARDES_') and 'PAGER' not in k}
+ env.update(HOME=str(root), XDG_RUNTIME_DIR=str(root), XDG_CONFIG_HOME=str(root / 'config'),
+ TERM='xterm-256color', SHELL=shutil.which('bash') or '/bin/bash', PARDES_NOTIME='1')
+ (root / 'config' / 'pardes').mkdir(parents=True)
+ (root / 'config' / 'pardes' / 'init').write_text('Shell bash\nMessageLinger 0\n')
+ (root / 'bin').mkdir()
+ binary, gui_binary = root / 'bin' / 'pardes', root / 'bin' / 'pardes-gui'
+ install(old, binary)
+ install(old_gui, gui_binary)
+ terms = []
+ procs = []
+
+ def still(check, key):
+ """Its view the live one (made_live's, for either client)."""
+ seen = len(checks(check))
+ key(b'gg')
+ wait_for('the client\'s key stepped', lambda: agreed(check, seen + 1), timeout=30)
+
+ try:
+ out = subprocess.run([str(binary), 'new', '--detach=up'], env=env, cwd=root, capture_output=True, timeout=30)
+ assert out.returncode == 0, out
+ sock = root / 'pardes-9p-up.sock'
+ nine = Client(sock)
+ session = int(dict(line.split(maxsplit=1) for line in nine.read('/status').decode().splitlines())['pid'])
+ shell = terminals(nine)[0]
+ shell_pid = int(run(nine, shell, b'echo $$\n').split(b'\n')[1])
+ t = Term(30, 100)
+ terms.append(t)
+ tc = t.spawn([str(binary), 'attach', 'up'], dict(env, PARDES_REPLICA_CHECK=str(root / 't.check')))
+ procs.append(tc)
+ wait_for('the terminal client drawn', lambda: b'\x1b[?1049h' in t.text(), timeout=30)
+ w = Window(root, 'w', [str(gui_binary), 'attach', 'up'], dict(env, PARDES_REPLICA_CHECK=str(root / 'w.check')))
+ procs.append(w.p)
+ wait_for('the window client drawn', lambda: (root / 'w' / 'latest.ppm').exists(), timeout=30)
+ tkey = lambda b: os.write(t.master, b) # noqa: E731
+ # Each client's view live in turn, a pane of its own made there (New).
+ owners = ((w.keys, root / 'w.check'), (tkey, root / 't.check'))
+ mine = []
+ for key, check in owners:
+ still(check, key)
+ shown = view_panes(nine)
+ nine.write('/exec', b'New\n')
+ mine.append(wait_for('a pane in the client\'s view', lambda: view_panes(nine) - shown).pop())
+ for (key, check), pane, theirs in zip(owners, mine, reversed(mine)):
+ still(check, key)
+ assert pane in view_panes(nine) and theirs not in view_panes(nine), ('each its own view', pane, theirs, nine.read('/layout'))
+ install(new, binary)
+ install(new_gui, gui_binary)
+ mark = len(t.text())
+ nine.write('/ctl', b'Upgrade\n')
+ nine.socket.close()
+ wait_for('the session on the new build', lambda: exe_of(session) == (str(binary), True), timeout=30)
+ nine = reconnect(sock)
+ if not knows_exec(old):
+ # A build before the exec: let go, dialled again for 20 s, told.
+ assert tc.wait(timeout=60) == 1 and w.p.wait(timeout=60) == 1, (tc.returncode, w.p.returncode)
+ said = t.text()[mark:] + w.said().encode()
+ assert b'upgrade this client too' in said or b'run the same pardes at both ends' in said, said[-600:]
+ print('upgrade with clients: the clients of a build before it were let go, dialled again, and told to upgrade too')
+ else:
+ wait_for('the terminal client on the new build', lambda: exe_of(tc.pid) == (str(binary), True), timeout=30)
+ wait_for('the window client on the new build', lambda: exe_of(w.pid) == (str(gui_binary), True), timeout=30)
+ # The blink: its screen left, and entered again.
+ wait_for('the terminal entered again', lambda: t.text().rfind(b'\x1b[?1049h') > t.text().rfind(b'\x1b[?1049l') > mark, timeout=30)
+ assert tc.poll() is None and w.p.poll() is None
+ for (key, check), pane, theirs in zip(owners, mine, reversed(mine)):
+ still(check, key)
+ if knows_exec(new):
+ shown = view_panes(nine)
+ assert pane in shown and theirs not in shown, ('its own view again', pane, theirs, nine.read('/layout'))
+ print('upgrade with clients: a terminal client and a window client exec\'d the build at their start path, the same processes, '
+ + ('each back in its own view, its own pane in it' if knows_exec(new) else 'each in a view of its own (that build joins for no view it is handed)'))
+ assert alive(shell_pid) and ppid(shell_pid) == session
+ for p in procs:
+ if p.poll() is None:
+ p.terminate()
+ p.wait(timeout=20)
+ nine.socket.close()
+ assert subprocess.run([str(binary), 'kill', 'up'], env=env, capture_output=True, timeout=30).returncode == 0
+ wait_for('the session ended', lambda: not alive(session), timeout=30)
+ wait_for('nothing left', lambda: not [p for p in processes(root) if alive(p)], timeout=20)
+ print('upgrade with clients: the shell ran on throughout; nothing left behind')
+ finally:
+ for p in procs:
+ if p.poll() is None:
+ p.kill()
+ for p in processes(root):
+ try:
+ os.kill(p, signal.SIGKILL)
+ except OSError:
+ pass
+ for t in terms:
+ t.close()
+ shutil.rmtree(root, ignore_errors=True)
+
+
def gui_upgrades(old, new):
"""Upgrade in a window session (test mode: hidden windows, captured):
its window, a client window, an unsaved edit and a shell's job, onto
@@ -2359,12 +2893,23 @@ if __name__ == '__main__':
gui_upgrades(Path(sys.argv[3]).resolve(), Path(sys.argv[4]).resolve())
elif sys.argv[1:2] == ['--upgrade']:
upgrades(Path(sys.argv[2]).resolve(), Path(sys.argv[3]).resolve())
+ # With a pardes-gui beside each: the clients carried too.
+ if all(Path(a).resolve().with_name('pardes-gui').exists() for a in sys.argv[2:4]):
+ upgrade_clients(Path(sys.argv[2]).resolve(), Path(sys.argv[3]).resolve())
+ elif sys.argv[1:2] == ['--upgrade-clients']:
+ upgrade_clients(Path(sys.argv[2]).resolve(), Path(sys.argv[3]).resolve())
elif sys.argv[1:2] == ['--clients']:
clients(sys.argv[2])
elif sys.argv[1:2] == ['--manage']:
manage(sys.argv[2])
+ elif sys.argv[1:2] == ['--launch']:
+ launch(sys.argv[2])
+ elif sys.argv[1:2] == ['--pair']:
+ pair(sys.argv[2])
+ pair_rows(sys.argv[2])
elif sys.argv[1:2] == ['--relink']:
relink(sys.argv[2])
+ answer_late(sys.argv[2])
elif sys.argv[1:2] == ['--games']:
games(sys.argv[2], sys.argv[3], float(sys.argv[4]) if len(sys.argv) > 4 else 10)
elif sys.argv[1:2] == ['--far']:
@@ -2380,8 +2925,11 @@ if __name__ == '__main__':
pdf_window(sys.argv[2], sys.argv[3])
elif sys.argv[1:2] == ['--ping']:
ping(sys.argv[2], sys.argv[3], sys.argv[4], int(sys.argv[5]) if len(sys.argv) > 5 else 50)
+ elif sys.argv[1:2] == ['--pair-gui']:
+ gui_pair(sys.argv[2])
elif '--gui' in sys.argv:
args = [a for a in sys.argv[1:] if a != '--gui']
gui(args[0], int(args[1]) if len(args) > 1 else 50)
+ gui_pair(args[0])
else:
main(sys.argv[1], int(sys.argv[2]) if len(sys.argv) > 2 else 50)
diff --git a/test/delay_relay.py b/test/delay_relay.py
index c600a3aa..b0d48e38 100644
--- a/test/delay_relay.py
+++ b/test/delay_relay.py
@@ -8,7 +8,7 @@ the ones before it have crossed at that rate, then waits out the delay. An
optional jitter adds up to that many ms more to each chunk's delay, at
random, its order kept (a chunk never overtakes the one before it).
- python3 -B test/delay_relay.py LISTEN TARGET --delay MS [--rate MB/s] [--jitter MS]
+ python3 -B test/delay_relay.py LISTEN TARGET --delay MS [--rate MB/s] [--jitter MS] [--bound MS]
python3 -B test/delay_relay.py --self-check
An address is a path (a Unix socket) or host:port (TCP). The one-way
@@ -46,7 +46,9 @@ def dial(address):
return s
-def listen(address):
+def listen(address, bound=0.0):
+ """Bound, then listening `bound` s later (an ssh -L's socket file is
+ there a moment before it answers)."""
family, addr = parse(address)
s = socket.socket(family)
if family == socket.AF_UNIX:
@@ -57,6 +59,7 @@ def listen(address):
else:
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind(addr)
+ time.sleep(bound)
s.listen(64)
return s
@@ -260,8 +263,9 @@ def main():
ap.add_argument('--delay', type=float, required=True, help='one-way delay, ms')
ap.add_argument('--rate', type=float, help='a bandwidth cap, MB/s')
ap.add_argument('--jitter', type=float, default=0, help='up to this many ms more a chunk, at random')
+ ap.add_argument('--bound', type=float, default=0, help='ms between the bind and the listen')
a = ap.parse_args()
- listener = listen(a.listen)
+ listener = listen(a.listen, a.bound / 1000)
print(f'relaying {a.listen} -> {a.target}, {a.delay} ms each way'
+ (f', {a.rate} MB/s' if a.rate else '') + (f', jitter {a.jitter} ms' if a.jitter else ''), flush=True)
try:
diff --git a/test/e2e_harness.zig b/test/e2e_harness.zig
index f7d65b03..26e942e7 100644
--- a/test/e2e_harness.zig
+++ b/test/e2e_harness.zig
@@ -149,9 +149,25 @@ pub const Harness = struct {
return true;
}
+ /// The app ended as closing its terminal ends it: the master closed (its
+ /// hangup), the app given `end_ms` to end, SIGKILLed only after, and
+ /// reaped: what it ends at its own end (its shells, its language servers'
+ /// groups) does not outlive the case.
pub fn deinit(self: *Harness) void {
- posix.kill(self.pid, posix.SIG.KILL) catch {};
_ = libc.close(self.master);
+ const end_ms = 5000;
+ const until = nowMs() + end_ms;
+ var status: c_int = 0;
+ var none: [0]posix.pollfd = .{};
+ while (libc.waitpid(self.pid, &status, libc.W.NOHANG) == 0) {
+ if (nowMs() < until) {
+ _ = posix.poll(&none, 5) catch 0;
+ continue;
+ }
+ posix.kill(self.pid, posix.SIG.KILL) catch {};
+ _ = libc.waitpid(self.pid, &status, 0);
+ break;
+ }
self.stream.deinit();
self.gpa.destroy(self.raw);
self.term.deinit(self.gpa);
diff --git a/test/fs_namespace.zig b/test/fs_namespace.zig
index ceda8158..90b610a9 100644
--- a/test/fs_namespace.zig
+++ b/test/fs_namespace.zig
@@ -118,7 +118,6 @@ test "transactional restore preserves host capabilities and advances pane identi
}
test "filesystem resolves OS first then virtual with explicit mounts and parent paths" {
- if (!filesystem.platform_has_fs) return error.SkipZigTest;
const gpa = std.testing.allocator;
var tmp = std.testing.tmpDir(.{});
defer tmp.cleanup();
@@ -185,7 +184,6 @@ test "filesystem resolves OS first then virtual with explicit mounts and parent
}
test "explicit OS file opens and restores keep their names and request watches" {
- if (!filesystem.platform_has_fs) return error.SkipZigTest;
const gpa = std.testing.allocator;
var tmp = std.testing.tmpDir(.{});
defer tmp.cleanup();
@@ -286,7 +284,6 @@ test "owned cwd failed file opens never publish a pane or retain a reservation"
}
test "images decode through explicit filesystem mounts, and a dump's pane reads its file again through the same mount" {
- if (!filesystem.platform_has_fs) return error.SkipZigTest;
const gpa = std.testing.allocator;
var tmp = std.testing.tmpDir(.{});
defer tmp.cleanup();
diff --git a/test/lib/build.zig b/test/lib/build.zig
deleted file mode 100644
index 436517d4..00000000
--- a/test/lib/build.zig
+++ /dev/null
@@ -1,34 +0,0 @@
-//! A package that depends on pardes for its library, as a program that draws
-//! source text itself would: pardes's `lib-test` step runs `zig build test`
-//! here, so the `pardes-syntax` module is built the way such a package
-//! builds it (build.zig's `library`), with the minimal grammars, and
-//! `pardes-editor`, the text pane as a library, which it asks for.
-const std = @import("std");
-
-pub fn build(b: *std.Build) void {
- const target = b.standardTargetOptions(.{});
- const optimize = b.standardOptimizeOption(.{});
- const pardes = b.dependency("pardes", .{ .target = target, .optimize = optimize, .@"tree-sitter" = .minimal, .editor = true });
- const step = b.step("test", "colour, outline and walk a C and a Zig source through pardes's library, and edit a text with its editor");
- // A file belongs to one module: the syntax alone, and the editor (which
- // has it as `.syntax`), each a test of its own.
- for ([_][2][]const u8{ .{ "lib.zig", "pardes-syntax" }, .{ "editor.zig", "pardes-editor" } }) |t| {
- const tests = b.addTest(.{ .root_module = b.createModule(.{
- .target = target,
- .optimize = optimize,
- .root_source_file = b.path(t[0]),
- .imports = &.{.{ .name = t[1], .module = pardes.module(t[1]) }},
- }) });
- step.dependOn(&b.addRunArtifact(tests).step);
- }
- // What a key costs, a page count and a parse: `zig build bench -- <KiB> <keys>`.
- const bench = b.addExecutable(.{ .name = "bench", .root_module = b.createModule(.{
- .target = target,
- .optimize = optimize,
- .root_source_file = b.path("bench.zig"),
- .imports = &.{.{ .name = "pardes-editor", .module = pardes.module("pardes-editor") }},
- }) });
- const run_bench = b.addRunArtifact(bench);
- run_bench.addPassthruArgs();
- b.step("bench", "a key typed into the library's editor at a size, its pages and a parse").dependOn(&run_bench.step);
-}
diff --git a/test/lib/build.zig.zon b/test/lib/build.zig.zon
deleted file mode 100644
index d8c31c3f..00000000
--- a/test/lib/build.zig.zon
+++ /dev/null
@@ -1,10 +0,0 @@
-.{
- .name = .pardes_lib_test,
- .version = "0.0.0",
- .dependencies = .{
- .pardes = .{ .path = "../.." },
- },
- .minimum_zig_version = "0.17.1",
- .paths = .{""},
- .fingerprint = 0x3f9948734dd377c7,
-}
diff --git a/test/output.zig b/test/output.zig
index c5ddddd5..77de7649 100644
--- a/test/output.zig
+++ b/test/output.zig
@@ -138,7 +138,7 @@ test "location producers retain rendered location match and diagnostic styles" {
} else if (origin == .search or origin == .cmd) {
try std.testing.expectEqual(pardes.Color{ .rgb = chrome.search_bg }, first.style.bg);
}
- if (!diagnostic and pardes.syntax.enabled) {
+ if (!diagnostic) {
const number = start + std.mem.indexOf(u8, code, "42").?;
try std.testing.expectEqual(pardes.Color{ .rgb = p.theme().num }, outputCell(p, surface, id, number).style.fg);
}
@@ -428,7 +428,6 @@ test "Mini dump preserves its exact virtual snapshot and body writes detach colo
}
test "Mini syntax colors survive themes and rendering without source access" {
- if (!pardes.syntax.enabled) return error.SkipZigTest;
var tmp = std.testing.tmpDir(.{});
defer tmp.cleanup();
try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "demo.zig", .data = "pub fn main() void {\n if (true) return;\n}\n" });
@@ -619,7 +618,6 @@ fn selectedOutputText(pane: *const pardes.Pane) ?[]const u8 {
}
test "LookNext/LookPrev skips formatted context and selects comment match locations" {
- if (!pardes.syntax.enabled) return error.SkipZigTest;
for ([_]panes.Output.Origin{ .search, .{ .query = .references } }) |origin| {
for ([_]bool{ false, true }) |tslocations| {
const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 100, .rows = 30 });
@@ -786,7 +784,7 @@ test "identical result refresh keeps warm content caches without allocation" {
const index = try panes.File.lineIndex(p.gpa, file);
const styles = try std.testing.allocator.dupe(u8, file.highlights);
defer std.testing.allocator.free(styles);
- if (@import("pardes_options").grammars != .disabled) try std.testing.expect(styles.len > 0);
+ try std.testing.expect(styles.len > 0);
const revision = file.revision;
const saved_revision = file.saved_revision;
const body_ptr = file.content.ptr;
@@ -1048,7 +1046,6 @@ test "result alignment chunks assign boundary context to nearest match with prev
}
test "declaration context ellipses mark only final header lines before omitted source" {
- if (!pardes.syntax.enabled) return error.SkipZigTest;
const text = "const Outer = struct {\n" ++
"\n" ++
" pub fn run(\n" ++
@@ -1161,7 +1158,6 @@ test "LSP occurrence tint follows the supplied source span through context" {
}
test "result context upper bound stops at earliest enclosing declaration" {
- if (!pardes.syntax.enabled) return error.SkipZigTest;
const text = "// unrelated prelude\n" ++
"const unrelated = 1;\n" ++
"\n" ++
@@ -1227,7 +1223,6 @@ test "result context upper bound stops at earliest enclosing declaration" {
}
test "stacked search and LSP results retain source tint navigation and dump ownership" {
- if (!pardes.syntax.enabled) return error.SkipZigTest;
const first = "\tfoo + 界 + foo;";
const second = " return foo;";
const source_text = "const Box = struct {\n fn run() void {\n" ++ first ++ "\n const neighbor = 42;\n" ++ second ++ "\n }\n};\n";
@@ -1348,7 +1343,6 @@ 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" ++
@@ -1429,7 +1423,6 @@ test "location analysis cache refreshes unsaved ancestry and query context" {
}
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;
diff --git a/test/panes.zig b/test/panes.zig
index f4061590..38eb0a71 100644
--- a/test/panes.zig
+++ b/test/panes.zig
@@ -152,7 +152,6 @@ const BodyHitTests = struct {
}
test "compact TreeContext mouse follows source rows in reclaimed space" {
- if (!syntax.enabled) return error.SkipZigTest;
const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 64, .rows = 18 });
defer p.deinit();
p.view().row_metrics = .{ .body_w = 10, .body_h = 20, .tagline_w = 8, .tagline_h = 10 };
@@ -201,7 +200,6 @@ const BodyHitTests = struct {
const LineNumberLookTests = struct {
test "right-click on a line number looks at that line, sticky context headers included" {
- if (!syntax.enabled) return error.SkipZigTest;
const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 64, .rows = 18 });
defer p.deinit();
p.view().row_metrics = .{ .body_w = 10, .body_h = 20, .tagline_w = 8, .tagline_h = 10 };
@@ -259,7 +257,6 @@ const TreeContextTests = struct {
}
test "TreeContext separators mark source gaps without splitting multiline signatures" {
- 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" ++ std.mem.asBytes(&@as([30][16]u8, @splat(" // body\n".*))) ++ " }\n};\n");
@@ -291,7 +288,6 @@ const TreeContextTests = struct {
test "TreeContext Look to an open file discards the old viewport extent" {
for ([_]bool{ false, true }) |context| {
- 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" ++ std.mem.asBytes(&@as([100][12]u8, @splat(" // body\n".*))) ++ "}\n");
@@ -316,7 +312,6 @@ const TreeContextTests = struct {
}
test "TreeContext sticky declarations preserve the body while clicked and edited" {
- 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, source);
@@ -368,7 +363,6 @@ const TreeContextTests = struct {
}
test "TreeContext unwrapped headers map Unicode and survive source replacement" {
- 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" ++ std.mem.asBytes(&@as([12][15]u8, @splat(" _ = value;\n".*))) ++ "}\n");
@@ -407,7 +401,6 @@ const TreeContextTests = struct {
}
test "TreeContext clipped headers leave wrapped body cursor coordinates intact" {
- if (!syntax.enabled) return error.SkipZigTest;
const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 24, .rows = 12 });
defer p.deinit();
const body = " // 012345678901234567890123456789界tail";
@@ -1717,7 +1710,6 @@ const OutputTests = struct {
}
test "Callstack aligns source below locations and keeps exact emphasis and navigation" {
- if (!syntax.enabled) return error.SkipZigTest;
const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 80, .rows = 30 });
defer p.deinit();
const source = " pub fn caller(\n value: u32,\n ) void {\n work(value);\n }\n";
@@ -1759,7 +1751,6 @@ const OutputTests = struct {
}
test "Callstack signatures share unsaved tree context and keep guides out of Look selections" {
- if (!syntax.enabled) return error.SkipZigTest;
const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 110, .rows = 30 });
defer p.deinit();
const source = "const Box = struct {\n" ++
@@ -1853,7 +1844,6 @@ const OutputTests = struct {
}
test "Locations context uses unsaved sources and navigation visits only matches" {
- if (!syntax.enabled) return error.SkipZigTest;
const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 100, .rows = 30 });
defer p.deinit();
p.locations_config.layout = .@"inline";
@@ -1968,7 +1958,6 @@ const OutputTests = struct {
}
test "Locations visible declarations are muted and stars count scopes rather than signature lines" {
- if (!syntax.enabled) return error.SkipZigTest;
const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 120, .rows = 40 });
defer p.deinit();
p.locations_config.layout = .@"inline";
@@ -3541,7 +3530,6 @@ test "cancelled normal gestures leave no count or subprefix through raw tty mode
}
test "Zig keywords keep every rendered byte colored across line-number widths" {
- if (!syntax.enabled) return error.SkipZigTest;
const gpa = std.testing.allocator;
const samples = [_][]const u8{
"pub fn main() void { if (true) {} }\n",
diff --git a/test/process.zig b/test/process.zig
index 8bcbddeb..e2a4f592 100644
--- a/test/process.zig
+++ b/test/process.zig
@@ -916,7 +916,8 @@ pub const Child = struct {
while (environ[i]) |kv| {
const entry = std.mem.span(kv);
const eq = std.mem.indexOfScalar(u8, entry, '=') orelse entry.len;
- if (std.mem.startsWith(u8, entry, "PARDES_") or std.mem.indexOf(u8, entry[0..eq], "PAGER") != null) {
+ // PARDES_PAIR kept: the suite run as pairs (main.zig `pair`).
+ if ((std.mem.startsWith(u8, entry, "PARDES_") and !std.mem.startsWith(u8, entry, "PARDES_PAIR=")) or std.mem.indexOf(u8, entry[0..eq], "PAGER") != null) {
var name: [256]u8 = undefined;
const n = std.fmt.bufPrintSentinel(&name, "{s}", .{entry[0..@min(eq, 255)]}, 0) catch _exit(126);
_ = unsetenv(n);
diff --git a/test/process/terminals.zig b/test/process/terminals.zig
index 24772ced..d9c3bcca 100644
--- a/test/process/terminals.zig
+++ b/test/process/terminals.zig
@@ -262,7 +262,9 @@ fn rawKey(gpa: std.mem.Allocator, exe: [:0]const u8) !void {
/// thousand: nothing printed is nothing kept), then a probe typed and
/// taken back with ^U.
fn drive(gpa: std.mem.Allocator, exe: [:0]const u8, script: []const u8, key: ?u8, rows: usize) !void {
- var d = try process.Detached.start(gpa, exe, "agent", .{});
+ // No builtin announces itself: Term's name would linger on the screen
+ // (MessageLinger, 800 ms) and go between `before` and ^U's answer.
+ var d = try process.Detached.start(gpa, exe, "agent", .{ .init = "Verbose off\n" });
defer d.deinit();
const f = &d.files;
try d.put("command.sh", f.at("exec /bin/sh -c '{s}'\n", .{script}));
@@ -300,7 +302,10 @@ fn drive(gpa: std.mem.Allocator, exe: [:0]const u8, script: []const u8, key: ?u8
try f.write(data, "\x15");
const back_by = eh.nowMs() + 10_000;
while (!std.mem.eql(u8, try f.screen(), before)) {
- if (eh.nowMs() > back_by) return error.ScreenNotRestored;
+ if (eh.nowMs() > back_by) {
+ std.debug.print("before:\n{s}\nafter ^U:\n{s}\n", .{ before, try f.screen() });
+ return error.ScreenNotRestored;
+ }
sleepMs(10);
}
}
diff --git a/test/process/tty_terminals.zig b/test/process/tty_terminals.zig
index d5540818..dfb027e2 100644
--- a/test/process/tty_terminals.zig
+++ b/test/process/tty_terminals.zig
@@ -844,7 +844,9 @@ fn exec_bigdrag(gpa: std.mem.Allocator, exe: [:0]const u8) !void {
try t.drag("middle", "150", 31);
try t.drag("middle", "198", 59);
try t.release("middle", "198", 59);
- try t.stable(500, 8000);
+ // Bash fails each swept chunk as a command, one by one: under load
+ // that runs well past 8 s, so the quiet is waited for once, with the
+ // cap the sweep's other waits have.
try t.stable(800, 30000);
// still alive: type and execute a marker command
try t.press("left", "105", 41);
diff --git a/test/replicas.zig b/test/replicas.zig
index 7bf79055..6a6d43b4 100644
--- a/test/replicas.zig
+++ b/test/replicas.zig
@@ -699,7 +699,7 @@ fn ended(cl: *Client, c: usize, net: *Net, now: u64, totals: *Totals, run_: Run,
const r = cl.r.?;
const link = &cl.loop.link;
// Its link ended by the session (a Detach), it says nothing more.
- if (!link.gone) replica.bye(link.fd, r.diverged != null);
+ if (!link.gone) replica.bye(link.fd, .{ .again = r.diverged != null });
try drain(cl, c, net, now);
cl.live = 0;
if (r.diverged) |why| {
@@ -1120,7 +1120,6 @@ const Soak = struct {
}
pub fn upgradeAsked(_: *Soak) void {}
- pub fn note(_: *Soak, _: anytype) void {}
pub fn restoring(_: *Soak, _: *pardes.Pardes) void {}
pub fn restored(_: *Soak, _: *SessionLoop) void {}
diff --git a/test/terminal.zig b/test/terminal.zig
index b7b9cd33..ec050c7a 100644
--- a/test/terminal.zig
+++ b/test/terminal.zig
@@ -203,7 +203,6 @@ test "a terminal's dump restores the cells it drew, its history and where its vi
}
test "a restored command pane comes back finished, its command not run again" {
- if (comptime pardes.isolated) return error.SkipZigTest;
const gpa = std.testing.allocator;
const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 60, .rows = 16 });
defer p.deinit();
@@ -233,7 +232,6 @@ test "a restored command pane comes back finished, its command not run again" {
}
test "a restored terminal keeps its history above a marker and gets a shell where it was" {
- if (comptime pardes.isolated) return error.SkipZigTest;
const gpa = std.testing.allocator;
const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 40, .rows = 12 });
defer p.deinit();