From 044da0f75ab5fb5be0213e512741860d95dad8e5 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Thu, 29 Oct 2026 11:14:38 -0300 Subject: tape: every input the core consumes recorded in turn order, replayed into replicas that must reach the same digests; the core's leaks of render, clock and host closed The recorder (src/tape.zig) is null unless PARDES_RECORD= names a tape (.tape); the local path pays a null check a call. It records a tree at the host boundary, both ways: each call the host makes into the core (`Input`: update, serveFs, pump, perform, the shell's acknowledgements and failures, a Restore, ...) with its arguments, and each call the core makes out -- a Host function (the vtable wrapped generically while recording) or a syscall of its own (`tape.site` for every old `turn.yield()`, `tape.value` for a clock or environment read) -- with its result; `done`/`ret` close each, a 9P request served while a step is out lands inside that step's syscall, and fields a host writes between calls (native_images, present_skipped, ...) are found by a diff at every crossing. After each call the host made at the top, the session's digest (src/walk.zig), one per field of the core, its stream and each pane, file and places. `PARDES_REPLAY= pardes` (main.zig) replays it with the same build into three replicas: two at different addresses (the first's memory held while the second runs) and one that never draws. A host call answers what it answered, a site returns what it returned, nothing is performed and no syscall is made; `turn.yield` panics in a replica, so a syscall no site covers is a stack trace; a call the recording did not make, or a digest that differs, is a divergence that names the fields. The headless replica steps over the presents it does not make, applying what the host told the core inside them. What the replicas found, fixed: - Render wrote core state. The view's geometry (wrap map, context rows, body layer rows) is File.geometry, a lazy cache keyed by a hash of what it is made of (revision, scroll, size, tags, tables read, context declarations, the session's view: wrap, layered context, row metrics, rect); the render makes it afresh, a step reading it makes it on demand (wrapAt, wrapRow, ensureCursorVisible). Context declarations, notice bands and the header's reveal are the step's (sync), the tables' reading the tick's (a first look of 4096 lines, a count, wherever it is asked; the rest a frame's clock budget a tick), and a view's paint-ahead is asked of the host as the frame is drawn rather than queued as an effect. - The clock: advance's wakes are the recording session's (a picture decoding or a fade adds no tick to a replica), as are the budgets of Places, Names and Tables (`tape.over`), a message's time of day (the stamp; msg_said_ms and the unattended expiry use the session clock), File.mtime, and the pump reads its clock whether or not it waits. - The host: the session directory (getcwd, asked once at init), $SHELL and its existence, $HOME for `~`, `Shell` naming one that is not there, a missing interpreter, a directory refused above, a deleted file, a pointer seen through a sliding pane (Pardes.pointerCell). - Worker handles (futures, the Io), the 9P server's state, the store file every window shares (a replica keeps its own in memory) and Recent read from it are authority-only; frames, animations and the render's caches local. Query rows' paints count apart from a view's. Terminals replay from their taped pty bytes and are digested as their active screen, cursor and scroll; kitty images are left out until phase 5's screen-state terminals. tagnav.golden: the header's caret reveal now runs every step, as a pane's does, not once per frame drawn, so after `g l B B` typed in one burst the bar stays scrolled as a human typing it sees it. Co-Authored-By: Claude Opus 5.5 --- src/exec.zig | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) (limited to 'src/exec.zig') diff --git a/src/exec.zig b/src/exec.zig index c14a648c..8f84d2c6 100644 --- a/src/exec.zig +++ b/src/exec.zig @@ -485,8 +485,10 @@ pub fn isFile(path: []const u8) bool { pub fn kindOf(path: []const u8) ?std.Io.File.Kind { var buf: [4096]u8 = undefined; const z = std.fmt.bufPrintSentinel(&buf, "{s}", .{path}, 0) catch return null; - pardes.turn.yield(); - defer pardes.turn.back(); + return pardes.tape.site(.kind, null, kindHost, .{z}); +} + +fn kindHost(z: [:0]const u8) ?std.Io.File.Kind { const stat = @import("fs.zig").statPath(std.Io.Threaded.global_single_threaded.io(), z, .{}) catch return null; return stat.kind; } @@ -1116,7 +1118,7 @@ pub fn applySettingBuiltin(p: *Pardes, setting: config.Runtime.Setting, arg: ?[] } if (comptime pardes.hosted) { var why: [320]u8 = undefined; - if (@import("host_io.zig").Shell.refusal(want[0..@min(want.len, 200)], &why)) |refused| { + if (pardes.tape.value(.shell, @import("host_io.zig").Shell.refusal, .{ want[0..@min(want.len, 200)], &why })) |refused| { var text: [340]u8 = undefined; return p.reportFailure(p.active, std.fmt.bufPrint(&text, "Shell: {s}", .{refused}) catch "Shell: no such shell"); } @@ -1161,10 +1163,7 @@ pub fn applySettingBuiltin(p: *Pardes, setting: config.Runtime.Setting, arg: ?[] for (p.panes, 0..) |slot, id| { p.surface.body_layers[id].rows = 0; const pane = slot orelse continue; - pane.body_rows = 0; - pane.body_visible_rows = 0; - pane.context_row_limit = null; - pane.wrap_n = 0; + pane.geometry_key = 0; } p.abandonPanelAnimations(); } -- cgit v1.3 From 2eb8860b2ca05c426f3962661441aaee13d3be44 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Thu, 29 Oct 2026 19:09:26 -0300 Subject: web: the browser shell builds again and loads a dump of a native build: a theme by its name, a field compiled out passed over, no disk asked; touch.dump replaces the hand-written ZON fixture Fixed for wasm32-freestanding: counts as usize, no threads, stb_image, tape or host stat there. touch.mjs follows the renderer's 13 tag-layer fields, helix's retuned colours and the tag column. Co-Authored-By: Claude Opus 5.5 --- build.zig | 12 +++--- build/snap.zig | 2 +- docs/web.md | 4 +- src/FrameStats.zig | 2 +- src/Store.zig | 2 +- src/Stream.zig | 2 +- src/dump.zig | 23 ++++++++--- src/exec.zig | 2 + src/image.zig | 22 ++++++++--- src/tape.zig | 4 ++ src/terminal.zig | 4 +- src/walk.zig | 38 ++++++++++++------ test/web-snapshots/README.md | 2 +- test/web-snapshots/touch-fixture.zig | 58 ++++++++++++++++++++++++++++ test/web-snapshots/touch.dump | Bin 0 -> 96576 bytes test/web-snapshots/touch.dump.zon | 73 ----------------------------------- test/web-snapshots/touch.mjs | 21 ++++++---- tools/web_fixture.py | 34 ++++++++++++++++ 18 files changed, 186 insertions(+), 119 deletions(-) create mode 100644 test/web-snapshots/touch-fixture.zig create mode 100644 test/web-snapshots/touch.dump delete mode 100644 test/web-snapshots/touch.dump.zon create mode 100644 tools/web_fixture.py (limited to 'src/exec.zig') diff --git a/build.zig b/build.zig index 962b6322..097fb1bf 100644 --- a/build.zig +++ b/build.zig @@ -108,7 +108,7 @@ pub fn build(b: *std.Build) void { const target = if (platform == .esp32p4) b.resolveTargetQuery(esp32p4_target) else requested_target; const requested_optimize = b.standardOptimizeOption(.{}); const static = b.option(bool, "static", "statically link") orelse false; - const dump_path = b.option([]const u8, "dump", "dump .zon embedded into the web shell (-Dplatform=web)"); + const dump_path = b.option([]const u8, "dump", "a Dump (a .dump file) embedded into the web shell (-Dplatform=web)"); // 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| @@ -196,7 +196,7 @@ pub fn build(b: *std.Build) void { // The browser shell is a freestanding wasm core plus ordinary web files. // JavaScript owns the loop and IO; HTML/CSS own rendering. - const web_step = b.step("web", "build the DOM browser shell into zig-out/web (-Dplatform=web -Dtarget=wasm32-freestanding -Ddump=)"); + const web_step = b.step("web", "build the DOM browser shell into zig-out/web (-Dplatform=web -Dtarget=wasm32-freestanding -Ddump=)"); const mupdf_check = b.step("mupdf-check", "compile, link, render, and search docs/design.pdf with MuPDF"); const pdf_bench_step = b.step("pdf-bench", "benchmark real MuPDF page rendering (-- [--json] [--reps N] [--warmup N] [--path FILE] [--page N] [--pages N])"); const pdf_sections_bench_step = b.step("pdf-sections-bench", "benchmark PDF outline/sections paths in ReleaseFast (-Doptimize=ReleaseFast -- [--json] [--reps N] [--warmup N])"); @@ -224,7 +224,7 @@ pub fn build(b: *std.Build) void { if (is_web and !is_web_target) return failBuild(b, web_step, "-Dplatform=web requires -Dtarget=wasm32-freestanding"); if (!is_web and (is_web_target or target.result.os.tag == .emscripten)) return failBuild(b, web_step, "wasm browser targets require -Dplatform=web"); - if (platform == .web and dump_path == null) return failBuild(b, web_step, "-Dplatform=web requires -Ddump= (the browser has no ptys; state replays from an embedded dump)"); + if (platform == .web and dump_path == null) return failBuild(b, web_step, "-Dplatform=web requires -Ddump= (the browser has no ptys; state replays from an embedded dump)"); if (enable_mupdf and is_web) return failBuild(b, web_step, "-Dmupdf=true is supported only by the native tty/Kitty and gui/SDL backends"); // The board's target is pinned (`target` above), so what is asked of // -Dtarget is checked, not what was resolved: another arch is refused, @@ -1140,7 +1140,7 @@ pub fn build(b: *std.Build) void { const obj = b.addObject(.{ .name = "pardes-esp32p4", .root_module = root_mod }); b.getInstallStep().dependOn(&b.addInstallFile(obj.getEmittedBin(), "pardes-esp32p4.o").step); - web_step.dependOn(&b.addFail("web needs -Dplatform=web -Dtarget=wasm32-freestanding -Ddump=").step); + web_step.dependOn(&b.addFail("web needs -Dplatform=web -Dtarget=wasm32-freestanding -Ddump=").step); } else if (platform == .macos) { const header = b.addTranslateC(.{ .root_source_file = b.path("src/macos/pardes.h"), @@ -1308,7 +1308,7 @@ pub fn build(b: *std.Build) void { run_unit.has_side_effects = true; unit_step.dependOn(&run_unit.step); if (testMatch(b, unit_profile, test_filters, unit_step)) |check| check.addArtifactArg(unit_tests); - web_step.dependOn(&b.addFail("web needs -Dplatform=web -Dtarget=wasm32-freestanding -Ddump=").step); + web_step.dependOn(&b.addFail("web needs -Dplatform=web -Dtarget=wasm32-freestanding -Ddump=").step); } else { var exe_name: []const u8 = if (platform == .gui) "pardes-gui" else "pardes"; if (target.result.os.tag != .linux or target.result.cpu.arch != .x86_64) @@ -1344,7 +1344,7 @@ pub fn build(b: *std.Build) void { const iso_step = b.step("run-isolated", "descend to a pardes with no host but the terminal"); iso_step.dependOn(&run_iso.step); } - web_step.dependOn(&b.addFail("web needs -Dplatform=web -Dtarget=wasm32-freestanding -Ddump=").step); + web_step.dependOn(&b.addFail("web needs -Dplatform=web -Dtarget=wasm32-freestanding -Ddump=").step); snap_build.addTty(b, .{ .exe = exe, diff --git a/build/snap.zig b/build/snap.zig index c1a26e64..dad23c53 100644 --- a/build/snap.zig +++ b/build/snap.zig @@ -118,7 +118,7 @@ pub fn addWeb(b: *std.Build) void { "-Dplatform=web", "-Dtarget=wasm32-freestanding", "-Dtree-sitter=zig", - "-Ddump=test/web-snapshots/touch.dump.zon", + "-Ddump=test/web-snapshots/touch.dump", "-p", "zig-out/web-snap-test", }); diff --git a/docs/web.md b/docs/web.md index 0a9783c9..b9d03b13 100644 --- a/docs/web.md +++ b/docs/web.md @@ -57,7 +57,7 @@ zig build web \ -Dplatform=web \ -Dtarget=wasm32-freestanding \ -Dtree-sitter=zig \ - -Ddump=test/web-snapshots/touch.dump.zon + -Ddump=test/web-snapshots/touch.dump ``` The output is in `zig-out/web`. Serve that directory over HTTP; browsers do not @@ -133,7 +133,7 @@ zig build web-harness \ -Dplatform=web \ -Dtarget=wasm32-freestanding \ -Dtree-sitter=zig \ - -Ddump=test/web-snapshots/touch.dump.zon + -Ddump=test/web-snapshots/touch.dump # Real headless Chrome, DOM rendering, and browser touch input. zig build web-e2e diff --git a/src/FrameStats.zig b/src/FrameStats.zig index 2287002e..c27e74af 100644 --- a/src/FrameStats.zig +++ b/src/FrameStats.zig @@ -173,7 +173,7 @@ pub fn record(stats: *FrameStats, end_ns: u64, moving: bool, skipped: bool) void if (stats.armed and @as(u64, gap) * std.time.ns_per_us * 2 > stats.period_ns * 3) stats.jank += 1; if (@as(u64, frame.update_us + frame.render_us + frame.present_us) * std.time.ns_per_us > stats.period_ns) stats.over_budget += 1; if (skipped) stats.skipped += 1; - stats.ring[stats.count % capacity] = frame; + stats.ring[@intCast(stats.count % capacity)] = frame; stats.count += 1; stats.last_end_ns = end_ns; stats.armed = moving; diff --git a/src/Store.zig b/src/Store.zig index 95f5368f..36215234 100644 --- a/src/Store.zig +++ b/src/Store.zig @@ -78,7 +78,7 @@ cap: u64 = max_bytes, session: u64 = 0, pid: i32 = 0, /// The file as read so far: its inode, generation and how far. -inode: std.Io.File.INode = 0, +inode: std.Io.File.INode = std.mem.zeroes(std.Io.File.INode), gen: u64 = 0, end: u64 = 0, /// Its length when first read whole: a file past twice that (and 1 MiB) diff --git a/src/Stream.zig b/src/Stream.zig index 8d9663dd..665241df 100644 --- a/src/Stream.zig +++ b/src/Stream.zig @@ -512,7 +512,7 @@ pub fn parseFor(p: *Pardes, id: usize) void { // Here and now: a small text, a host with no workers. var got: Collect = .{ .gpa = p.gpa }; defer got.batches.deinit(p.gpa); - parseWork(std.Io.Threaded.global_single_threaded.io(), job, &got, Collect.take); + parseWork(if (comptime pardes.hosted) std.Io.Threaded.global_single_threaded.io() else std.Io.failing, job, &got, Collect.take); for (got.batches.items) |*b| { receive(p, b); b.deinit(p.gpa); diff --git a/src/dump.zig b/src/dump.zig index abc52f5a..c33ac02c 100644 --- a/src/dump.zig +++ b/src/dump.zig @@ -142,11 +142,13 @@ pub fn defaultDirectory(buf: []u8) ?[]const u8 { /// A session's dump: its core, everything it is but what is the host's, /// the frame's or worked out again (`replica` in each type, src/walk.zig), -/// then its 9P mounts, which live with the 9P server's own state, and which -/// of its panes' files were on disk when it was made (one gone by its load -/// is said deleted: its text is nowhere else now). -const Session = walk.Dump(&.{ Pardes, []const filesystem.Mount, OnDisk }); -const SessionLoad = walk.Load(&.{ Pardes, []const filesystem.Mount, OnDisk }); +/// then its 9P mounts, which live with the 9P server's own state, which of +/// its panes' files were on disk when it was made (one gone by its load is +/// said deleted: its text is nowhere else now), and its theme's name: the +/// setting is a place in this build's ring of themes, another build's +/// ring is another. +const Session = walk.Dump(&.{ Pardes, []const filesystem.Mount, OnDisk, []const u8 }); +const SessionLoad = walk.Load(&.{ Pardes, []const filesystem.Mount, OnDisk, []const u8 }); const OnDisk = [MAX_PANES]bool; fn onDisk(pane: *const pardes.panes.Pane) bool { @@ -176,6 +178,8 @@ pub fn dumpBytes(p: *Pardes) ![]u8 { on.* = onDisk(pane); }; try d.put(OnDisk, &on_disk); + const theme: []const u8 = colors.themes[@min(p.settings.theme, colors.themes.len - 1)].name; + try d.put([]const u8, &theme); return d.finish(); } @@ -233,6 +237,12 @@ fn loadKnowing(gpa: std.mem.Allocator, opts: Options, bytes: []const u8, notes: } const was = try l.get(OnDisk); if (on_disk) |out| out.* = was; + const theme = try l.get([]const u8); + defer gpa.free(theme); + // This build's place for that theme; one it has not, its first. + p.settings.theme = for (colors.themes, 0..) |t, i| { + if (std.mem.eql(u8, t.name, theme)) break i; + } else if (p.settings.theme < colors.themes.len) p.settings.theme else 0; // A mount this process was started with stands; one of the same name // to elsewhere is refused, never silently put over it. for (mounts) |m| { @@ -411,7 +421,8 @@ fn revivePane(p: *Pardes, id: usize, pane: *pardes.panes.Pane, was_on_disk: bool // Its file gone from disk since the dump: its text is nowhere else, so // it is said deleted, and Del, Exit and Restore ask first. One never on // disk (a name not yet saved) comes back as it was. - if (was_on_disk and !onDisk(pane)) pardes.panes.File.deleted(p, @intCast(id)); + // (A host with no disk of its own, the web's, asks nothing.) + if (comptime pardes.hosted) if (was_on_disk and !onDisk(pane)) pardes.panes.File.deleted(p, @intCast(id)); } // ---- one pane to and from a dump: the store's, a handover's ---- diff --git a/src/exec.zig b/src/exec.zig index 8f84d2c6..df397b37 100644 --- a/src/exec.zig +++ b/src/exec.zig @@ -483,6 +483,8 @@ pub fn isFile(path: []const u8) bool { /// What `path` is on this host, null when it is not there; the turn out /// while it asks (it may be inside a mount this editor serves). pub fn kindOf(path: []const u8) ?std.Io.File.Kind { + // A freestanding build has no host to ask. + if (comptime !pardes.hosted) return null; var buf: [4096]u8 = undefined; const z = std.fmt.bufPrintSentinel(&buf, "{s}", .{path}, 0) catch return null; return pardes.tape.site(.kind, null, kindHost, .{z}); diff --git a/src/image.zig b/src/image.zig index 8f193674..9163730d 100644 --- a/src/image.zig +++ b/src/image.zig @@ -755,6 +755,13 @@ var started = false; extern fn stbi_info_from_memory(buffer: [*]const u8, len: c_int, x: *c_int, y: *c_int, comp: *c_int) c_int; +/// stb_image's header reader; a freestanding build has no stb_image (its +/// decoder is the shim in src/web/zstbi.zig), so no header reads as one. +fn stbiInfo(bytes: []const u8, w: *c_int, h: *c_int, c: *c_int) bool { + if (comptime !pardes.hosted) return false; + return stbi_info_from_memory(bytes.ptr, @intCast(bytes.len), w, h, c) == 1; +} + /// PNG and JPEG are ghostty's decoders (wuffs, which ghostty-vt links for /// kitty graphics) wherever ghostty-vt is in the build; stb_image is then /// compiled without them, and without the inflate only its PNG used @@ -787,7 +794,7 @@ fn headerSize(bytes: []const u8) ?Size { var iw: c_int = 0; var ih: c_int = 0; var ic: c_int = 0; - if (stbi_info_from_memory(bytes.ptr, @intCast(bytes.len), &iw, &ih, &ic) != 1) return null; + if (!stbiInfo(bytes, &iw, &ih, &ic)) return null; return .{ .w = @intCast(@max(0, iw)), .h = @intCast(@max(0, ih)) }; } @@ -828,7 +835,7 @@ pub fn readable(bytes: []const u8) bool { var c: c_int = 0; if (!started) return true; // ponytail: no stb_image yet (a unit test), so no judging if (comptime wuffs_images) if (format(bytes) != .other) return headerSize(bytes) != null; - return stbi_info_from_memory(bytes.ptr, @intCast(bytes.len), &w, &h, &c) == 1; + return stbiInfo(bytes, &w, &h, &c); } /// decode + downscale to RGBA, gpa-owned. Returns null on any failure — the @@ -929,6 +936,9 @@ const GridKey = struct { ascii: bool = true, }; +/// A host's thread; a freestanding build has none to have. +const Decoder = if (pardes.hosted) std.Thread else void; + pub const State = struct { /// What the replay digest leaves out (src/walk.zig): the picture as /// decoded from its bytes, off the loop as the render first wants it, @@ -947,12 +957,12 @@ pub const State = struct { grid: GlyphArt.Grid = .{ .cells = &.{}, .cols = 0, .rows = 0 }, grid_key: GridKey = .{}, /// The decode under way off the loop (ensureDecoded), and its answer. - decoder: ?std.Thread = null, + decoder: ?Decoder = null, decoded: std.atomic.Value(bool) = .init(false), answer: ?Decoded = null, pub fn deinit(state: *State, gpa: std.mem.Allocator) void { - if (state.decoder) |t| t.join(); + if (comptime pardes.hosted) if (state.decoder) |t| t.join(); if (state.answer) |a| gpa.free(a.rgba); gpa.free(state.path); if (state.rgba.len > 0) gpa.free(state.rgba); @@ -1026,11 +1036,11 @@ pub fn tagPrefix(arena: std.mem.Allocator, state: *const State, glyphs: bool) ![ /// docs' screenshot: all of it once on the frame before). /// ponytail: a thread a picture; a pool if many open at once. fn ensureDecoded(p: *pardes.Pardes, state: *State) void { - if (state.decoder) |t| { + if (comptime pardes.hosted) if (state.decoder) |t| { if (!state.decoded.load(.acquire)) return; t.join(); state.decoder = null; - } + }; if (state.answer) |decoded| { state.answer = null; state.rgba = decoded.rgba; diff --git a/src/tape.zig b/src/tape.zig index d4fb7756..84bdce29 100644 --- a/src/tape.zig +++ b/src/tape.zig @@ -163,6 +163,7 @@ pub const Tape = struct { } fn flush(t: *Tape) void { + if (comptime !pardes.hosted) return; // A tape in memory (a replica's, an authority's stream) is taken // by whoever holds it. if (t.fd < 0) return; @@ -710,6 +711,8 @@ pub fn value(comptime s: Site, comptime f: anytype, args: anytype) @typeInfo(@Ty fn call(comptime s: Site, a: ?std.mem.Allocator, comptime f: anytype, args: anytype, comptime yields: bool) @typeInfo(@TypeOf(f)).@"fn".return_type.? { const R = @typeInfo(@TypeOf(f)).@"fn".return_type.?; + // No tape where there is no host to record or replay one. + if (comptime !pardes.hosted) return if (yields) out(f, args) else @call(.auto, f, args); const t = on orelse return if (yields) out(f, args) else @call(.auto, f, args); const id: u16 = @as(u16, host_fns.len) + @backingInt(s); if (t.replay) { @@ -928,6 +931,7 @@ pub fn digestOf(p: *const Pardes) u64 { /// PARDES_RECORD set: the tape is written from the session's first call. pub fn startFromEnv() void { + if (comptime !pardes.hosted) return; if (on != null) return; const prefix = std.mem.span(libc.getenv("PARDES_RECORD") orelse return); if (prefix.len == 0) return; diff --git a/src/terminal.zig b/src/terminal.zig index ad35784f..bcb70110 100644 --- a/src/terminal.zig +++ b/src/terminal.zig @@ -254,7 +254,7 @@ pub const State = struct { return; } if (bytes.len < 8) return error.EndOfDump; - const n = std.mem.bytesToValue(u64, bytes[0..8]); + const n = std.math.cast(usize, std.mem.bytesToValue(u64, bytes[0..8])) orelse return error.EndOfDump; if (bytes.len - 8 < n) return error.EndOfDump; var arena: std.heap.ArenaAllocator = .init(gpa); defer arena.deinit(); @@ -797,7 +797,7 @@ pub fn create(gpa: std.mem.Allocator, cols: u16, rows: u16) !*Pane { // defaults to direct alone, which `kitten icat` and timg detect and // fall back from, base64 through the pty. What the program can read // it could send itself: it runs as the user, under pardes. - .kitty_image_loading_limits = if (images_enabled) .allWithTempDir(tempDir()) else .direct, + .kitty_image_loading_limits = if (images_enabled) .allWithTempDir(tempDir()) else if (@FieldType(ghostty_vt.Terminal.Options, "kitty_image_loading_limits") == void) {} else .direct, }); state.stream = .init(.{ .handler = .{ .inner = state.vt.vtHandler() }, .allocator = gpa }); state.reply_len = 0; diff --git a/src/walk.zig b/src/walk.zig index 328557a7..6f9cc34b 100644 --- a/src/walk.zig +++ b/src/walk.zig @@ -843,6 +843,10 @@ fn allocOf(comptime T: type, comptime name: []const u8) ?[]const u8 { return null; } +fn countOf(n: u64) DecodeError!usize { + return std.math.cast(usize, n) orelse error.BadDump; +} + /// An allocation a load made: what a reference to it finds, and what a /// failed load frees. const Made = struct { bytes: []u8, alignment: std.mem.Alignment, gpa: std.mem.Allocator, dead: bool = false }; @@ -931,6 +935,11 @@ pub fn Load(comptime roots: []const type) type { return std.mem.bytesToValue(T, try l.take(@sizeOf(T))); } + /// A count, as this machine counts (a wasm32 one has 32 bits). + fn count(l: *Self) DecodeError!usize { + return countOf(try l.scalar(u64)); + } + fn name(l: *Self) DecodeError![]const u8 { return l.take(try l.scalar(u16)); } @@ -962,9 +971,9 @@ pub fn Load(comptime roots: []const type) type { }, .optional, .one, .slice, .prefix, .error_union => t.child = try l.scalar(u32), .@"struct", .@"union" => { - const count = try l.scalar(u32); - if (count > l.bytes.len) return error.BadDump; - const list = try a.alloc(SrcField, count); + const nfields = try l.scalar(u32); + if (nfields > l.bytes.len) return error.BadDump; + const list = try a.alloc(SrcField, nfields); for (list) |*f| f.* = .{ .name = try l.name(), .ty = try l.scalar(u32) }; t.fields = list; }, @@ -1073,6 +1082,14 @@ pub fn Load(comptime roots: []const type) type { out.* = .{ .raw = raw }; return; } + // A field this build compiles out (a PDF slot where there is no + // MuPDF): passed over, said only when it held something. + if (comptime kindOf(Canon(T)) == .void) if (!l.same and l.src[ty].kind != .void) { + const held = l.src[ty].kind != .optional or (l.at < l.bytes.len and l.bytes[l.at] != 0); + try l.skip(ty); + if (held) l.note("{s}: not in this build", .{l.field}); + return; + }; if (!try l.kindMatches(T, ty)) return error.Incompatible; const s = l.src[ty]; if (comptime isList(T)) { @@ -1194,8 +1211,7 @@ pub fn Load(comptime roots: []const type) type { } else out.* = try l.errorNamed(@typeInfo(T).error_union.error_set); }, .custom => { - const n = try l.scalar(u64); - const bytes = try l.take(n); + const bytes = try l.take(try l.count()); T.dumpRead(out, l.gpa, bytes) catch |err| { if (err == error.OutOfMemory) return error.OutOfMemory; l.note("{s}: {t}", .{ l.field, err }); @@ -1204,7 +1220,7 @@ pub fn Load(comptime roots: []const type) type { if (comptime @hasDecl(T, "dumpFree")) try l.customs.append(l.own, .{ .ptr = out, .gpa = l.gpa, .free = @ptrCast(&T.dumpFree) }); }, .bitset => { - const bits = try l.scalar(u64); + const bits = try l.count(); out.* = try .initEmpty(l.gpa, bits); const words = (bits + @bitSizeOf(usize) - 1) / @bitSizeOf(usize); if (words > 0) @memcpy(std.mem.sliceAsBytes(out.masks[0..words]), try l.take(words * @sizeOf(usize))); @@ -1232,7 +1248,7 @@ pub fn Load(comptime roots: []const type) type { fn slice(l: *Self, comptime E: type, s: SrcType) DecodeError![]E { if (try l.ref()) |again| return @as([*]E, @ptrCast(@alignCast(again.ptr)))[0 .. again.len / @max(1, @sizeOf(E))]; - const n = try l.scalar(u64); + const n = try l.count(); if (n == 0) return &.{}; if (n > l.bytes.len) return error.BadDump; const many = try l.gpa.alloc(E, n); @@ -1264,7 +1280,7 @@ pub fn Load(comptime roots: []const type) type { // cannot be read is left out, not the array. const droppable = comptime @typeInfo(E) == .optional and @typeInfo(@typeInfo(E).optional.child) == .pointer; var failed = false; - for (0..n) |i| { + for (0..try countOf(n)) |i| { if (i >= keep) { try l.skip(ty); continue; @@ -1394,8 +1410,8 @@ pub fn Load(comptime roots: []const type) type { .error_union => if ((try l.take(1))[0] != 0) try l.skip(s.child) else { _ = try l.name(); }, - .custom => _ = try l.take(try l.scalar(u64)), - .bitset => _ = try l.take((try l.scalar(u64) + 63) / 64 * 8), + .custom => _ = try l.take(try l.count()), + .bitset => _ = try l.take((try l.count() + 63) / 64 * 8), } } @@ -1407,7 +1423,7 @@ pub fn Load(comptime roots: []const type) type { _ = try l.take(@intCast(n * size)); return; } - for (0..n) |_| try l.skip(ty); + for (0..try countOf(n)) |_| try l.skip(ty); } }; } diff --git a/test/web-snapshots/README.md b/test/web-snapshots/README.md index a7cd865e..999e8fad 100644 --- a/test/web-snapshots/README.md +++ b/test/web-snapshots/README.md @@ -1,6 +1,6 @@ # Browser interaction tests -`zig build web-snap` loads `touch.dump.zon` and runs `touch.mjs` in Chromium. +`zig build web-snap` loads `touch.dump` (`python3 -B tools/web_fixture.py test/web-snapshots/touch.dump` makes it: a native session on `touch-fixture.zig` at 100x30, theme helix, Verbose off) and runs `touch.mjs` in Chromium. The fixed source fixture exercises complete keyword styles, touch Look through the self filesystem, separator resizing, and scrolling without another Look. Assertions locate current pane geometry; no live project source or author paths diff --git a/test/web-snapshots/touch-fixture.zig b/test/web-snapshots/touch-fixture.zig new file mode 100644 index 00000000..b1d5d81e --- /dev/null +++ b/test/web-snapshots/touch-fixture.zig @@ -0,0 +1,58 @@ +pub fn choose(value: u32) []const u8 { + if (value == 42) return "touch fixture"; + return "/virtual/pane/1/body"; +} + +pub const rows = [_]u32{ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 17, + 18, + 19, + 20, + 21, + 22, + 23, + 24, + 25, + 26, + 27, + 28, + 29, + 30, + 31, + 32, + 33, + 34, + 35, + 36, + 37, + 38, + 39, + 40, + 41, + 42, + 43, + 44, + 45, + 46, + 47, + 48, + 49, + 50, +}; \ No newline at end of file diff --git a/test/web-snapshots/touch.dump b/test/web-snapshots/touch.dump new file mode 100644 index 00000000..bcc58352 Binary files /dev/null and b/test/web-snapshots/touch.dump differ diff --git a/test/web-snapshots/touch.dump.zon b/test/web-snapshots/touch.dump.zon deleted file mode 100644 index 230d29e7..00000000 --- a/test/web-snapshots/touch.dump.zon +++ /dev/null @@ -1,73 +0,0 @@ -.{ - .screen = .{ .cols = 100, .rows = 30 }, - .theme = "helix", - .columns = .{.{ .panes = .{0} }}, - .panes = .{.{ - .kind = .file, - .tag = "touch-fixture.zig", - .body = "", - .file = .{ - .path = "touch-fixture.zig", - .content = - \\pub fn choose(value: u32) []const u8 { - \\ if (value == 42) return "touch fixture"; - \\ return "/virtual/pane/1/body"; - \\} - \\ - \\pub const rows = [_]u32{ - \\ 0, - \\ 1, - \\ 2, - \\ 3, - \\ 4, - \\ 5, - \\ 6, - \\ 7, - \\ 8, - \\ 9, - \\ 10, - \\ 11, - \\ 12, - \\ 13, - \\ 14, - \\ 15, - \\ 16, - \\ 17, - \\ 18, - \\ 19, - \\ 20, - \\ 21, - \\ 22, - \\ 23, - \\ 24, - \\ 25, - \\ 26, - \\ 27, - \\ 28, - \\ 29, - \\ 30, - \\ 31, - \\ 32, - \\ 33, - \\ 34, - \\ 35, - \\ 36, - \\ 37, - \\ 38, - \\ 39, - \\ 40, - \\ 41, - \\ 42, - \\ 43, - \\ 44, - \\ 45, - \\ 46, - \\ 47, - \\ 48, - \\ 49, - \\ 50, - \\}; - , - }, - }}, -} diff --git a/test/web-snapshots/touch.mjs b/test/web-snapshots/touch.mjs index 69f8a4a5..3793c0f9 100644 --- a/test/web-snapshots/touch.mjs +++ b/test/web-snapshots/touch.mjs @@ -1,8 +1,9 @@ import assert from "node:assert/strict"; function tags(frame) { - // This fixture has workspace and column bars in its first two rows. - return frame.styleRows.flatMap((cells, y) => y > 1 && /^\s{3}\S/.test(frame.lines[y]) && cells.some((cell) => cell[2] & 128) ? [y] : []); + // This fixture has workspace and column bars in its first two rows; a + // pane's tag text starts after the two-cell marker gutter. + return frame.styleRows.flatMap((cells, y) => y > 1 && /^\s{2}\S/.test(frame.lines[y]) && cells.some((cell) => cell[2] & 128) ? [y] : []); } function pane(frame, name) { @@ -13,14 +14,17 @@ function pane(frame, name) { return { top, bottom, lines: frame.lines.slice(top + 1, bottom) }; } +// helix's keyword and string/number colours (src/themes/helix.zig). +const KW = 0xd776f9, STR = 0xf3cd7a; + function styled(frame) { const source = pane(frame, "touch-fixture.zig"); for (const [line, word, fg, bold] of [ - ["pub fn choose", "fn", 0xcf87e8, false], + ["pub fn choose", "fn", KW, false], ["pub fn choose", "choose", 0xbdbdbd, false], - ["if (value", "if", 0xcf87e8, false], - ["if (value", "42", 0xe3c78a, false], - ["if (value", '"touch fixture"', 0xe3c78a, false], + ["if (value", "if", KW, false], + ["if (value", "42", STR, false], + ["if (value", '"touch fixture"', STR, false], ]) { const row = source.lines.findIndex((text) => text.includes(line)); assert(row >= 0, `missing source line ${line}`); @@ -35,7 +39,7 @@ function styled(frame) { const number = /\b(\d+),/.exec(line); if (!number) continue; for (let x = number.index; x < number.index + number[1].length; x++) { - assert.equal(frame.styleRows[source.top + 1 + row][x][0], 0xe3c78a, `row ${row} number foreground`); + assert.equal(frame.styleRows[source.top + 1 + row][x][0], STR, `row ${row} number foreground`); } } } @@ -79,7 +83,8 @@ export default async function ({ grid, touch, wait, stable, delay, evaluate, mou renderer.render(); result.closedGapBorders=borders(); result.borderChangeInvalidates=renderer.layerRoot.firstChild!==withGap; - const tagValues=[2,2,0,42,1,0,1,1,1,1,0x334455]; + // The 13 fields of a tag layer: a one-line tag, its caret on line 0. + const tagValues=[2,2,0,42,1,0,1,1,1,1,0x334455,1,0]; wasm.pardes_tag_layer_limit=()=>1; wasm.pardes_tag_layer_value=(_,field)=>tagValues[field]; wasm.pardes_tag_layer_cells=()=>1024; diff --git a/tools/web_fixture.py b/tools/web_fixture.py new file mode 100644 index 00000000..06fc54cd --- /dev/null +++ b/tools/web_fixture.py @@ -0,0 +1,34 @@ +"""web_fixture.py PARDES OUT: the web shell's touch fixture as a dump of this +build: one pane on touch-fixture.zig at 100x30, theme helix. + + python3 -B tools/web_fixture.py test/web-snapshots/touch.dump +""" +import os, sys, time, shutil, struct, fcntl, termios +from pathlib import Path +sys.path.insert(0, str(Path(__file__).resolve().parent.parent / 'test')) +import fs # noqa: E402 + +binary, out = sys.argv[1], sys.argv[2] +root = Path('/tmp/pardes-web-fixture') # fixed: the dump names it +shutil.rmtree(root, ignore_errors=True) +root.mkdir(parents=True, mode=0o700) +shutil.copy(Path(__file__).resolve().parent.parent / 'test' / 'web-snapshots' / 'touch-fixture.zig', root / 'touch-fixture.zig') +# Set at startup, which announces nothing: a fixture with no message on +# its pane. +(root / 'config' / 'pardes').mkdir(parents=True) +(root / 'config' / 'pardes' / 'init').write_text('Theme helix\nVerbose off\n') +handles = {} +with fs.session(binary, root, 'web', tty=True, file=root / 'touch-fixture.zig', inherited={'PARDES_DAEMON': 'off'}, terminal=handles) as (client, address): + fcntl.ioctl(handles['input_fd'], termios.TIOCSWINSZ, struct.pack('HHHH', 30, 100, 0, 0)) + deadline = time.monotonic() + 10 + while client.screen()['cols'] != 100: + assert time.monotonic() < deadline + time.sleep(.01) + client.write('/ctl', b'Dump\n') + while b'\ndump ' not in client.read('/log'): + assert time.monotonic() < deadline + time.sleep(.01) + print(client.read('/index').decode()) + shutil.copy(root / 'web.dump.zon', out) +shutil.rmtree(root, ignore_errors=True) +print(os.path.getsize(out), 'bytes') -- cgit v1.3 From cb2688602b3f668790a9c35890973af80143697f Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Fri, 30 Oct 2026 06:25:57 -0300 Subject: gui: the window a replica client (pardes-gui --attach=: and :, as the tty's, far through ssh as amort's: its blobs by hash and its stream in zstd) and a window session serving replicas (a terminal's client or a window's): the client feeds its replica what its window does, read over its own view (views.within) and applied after, draws its view between steps, takes the stream on its own reader and rejoins as the tty's does (replica.Link, the client's half shared with it, the far path's Have with it); the session takes clients at its step boundary, one person's input a wait, a client's view no window of its own, its font and opacity answers taped; a client says its frontend first (Event.frontend, in wire 16 beside the far word) and the tty and window builds step alike (one desktop semantics: each has the other's words, which a view takes by its own frontend, builtins.registry.here); a check asked 300 ms after the last input and check, not per wake; test/daemon.py --window-clients Co-Authored-By: Claude Opus 5.5 --- src/Output.zig | 22 +- src/builtins.zig | 58 ++++- src/builtins_json.zig | 13 +- src/config.zig | 2 +- src/detached/wire.zig | 35 ++- src/draw.zig | 26 +-- src/exec.zig | 8 +- src/gui/gui.zig | 573 +++++++++++++++++++++++++++++++++++++++++++++----- src/main.zig | 27 ++- src/ninep/ctl.zig | 38 ++-- src/ninep/tree.zig | 2 +- src/pardes.zig | 50 ++++- src/replica.zig | 310 +++++++++++++++++++++++++++ src/tape.zig | 15 ++ src/tty/tty.zig | 311 +++++---------------------- src/views.zig | 54 +++-- test/daemon.py | 188 +++++++++++++++++ test/output.zig | 9 +- 18 files changed, 1351 insertions(+), 390 deletions(-) (limited to 'src/exec.zig') diff --git a/src/Output.zig b/src/Output.zig index 29e49180..359db1cf 100644 --- a/src/Output.zig +++ b/src/Output.zig @@ -905,7 +905,7 @@ fn openStepped(p: *Pardes, id: usize, from: Origin, content: []u8) !void { look.armLookWalk(p, free); } -fn helpContent(gpa: std.mem.Allocator, prefix: []const u8) ![]u8 { +fn helpContent(p: *const Pardes, gpa: std.mem.Allocator, prefix: []const u8) ![]u8 { const full_header = "pardes builtins, and how to run each:\nSPC and its keys, a chord, a button, the\ntopbar - or the name, executed anywhere.\n\n"; const group_header = "pardes builtins under SPC"; const calls_help = "\nCallstack: static caller chains,\nwith signatures and clickable call sites.\nCallers / Callees: one direction at a time.\n"; @@ -934,8 +934,10 @@ fn helpContent(gpa: std.mem.Allocator, prefix: []const u8) ![]u8 { } for (pardes.builtin_rows) |row| { // a path-less builtin filters as the empty path: in the full listing - // (which starts with nothing) and out of every group + // (which starts with nothing) and out of every group; a window's own + // word is none in a terminal's view if (!std.mem.startsWith(u8, row.path orelse "", prefix)) continue; + if (!builtins.registry.here(p, row.cmd)) continue; try w.print("{s}\n", .{row.line}); } if (show_calls_help) try w.writeAll(calls_help); @@ -966,21 +968,23 @@ fn helpContent(gpa: std.mem.Allocator, prefix: []const u8) ![]u8 { } pub fn openHelp(p: *Pardes, id: usize, prefix: []const u8) !void { - const content = try helpContent(p.gpa, prefix); + const content = try helpContent(p, p.gpa, prefix); // content is handed off unfreed on purpose: openRead adopts it or frees // it, and nothing between the alloc above and this line can fail. return openRead(p, id, .{ .cmd = .Help }, prefix, content); } test "full Help renders builtin rows, a call hierarchy guide, then language keys" { - const content = try helpContent(std.testing.allocator, ""); + const core = try Pardes.init(std.testing.allocator, .{ .tty_only = true }); + defer core.deinit(); + const content = try helpContent(core, std.testing.allocator, ""); defer std.testing.allocator.free(content); // FIRST blank line: the end of the header (the footer opens with one too) const body = content[(std.mem.indexOf(u8, content, "\n\n") orelse return error.MissingHelpHeader) + 2 ..]; var lines = std.mem.splitScalar(u8, body, '\n'); - for (pardes.builtin_rows) |row| + for (pardes.builtin_rows) |row| if (builtins.registry.here(core, row.cmd)) try std.testing.expectEqualStrings(row.line, lines.next() orelse return error.MissingBuiltinHelpRow); // The short call guide disambiguates the three related commands. @@ -995,7 +999,7 @@ test "full Help renders builtin rows, a call hierarchy guide, then language keys return error.MissingLanguageKeys); try std.testing.expect(std.mem.indexOf(u8, body, "\ngd gD gy gi gr goto: definition,\n") != null); // The language group also explains call commands, without the motion footer. - const group = try helpContent(std.testing.allocator, "l"); + const group = try helpContent(core, std.testing.allocator, "l"); defer std.testing.allocator.free(group); try std.testing.expect(std.mem.indexOf(u8, group, "language keys") == null); try std.testing.expect(std.mem.indexOf(u8, group, "Callstack: static caller chains") != null); @@ -1013,13 +1017,13 @@ pub fn openConfig(p: *Pardes, id: usize) !void { .locations = located.written(), .default_dump_dir = if (host_fs) (pardes.dump.defaultDirectory(&dir_buf) orelse "") else "", .startup_config_path = p.opts.startup_config_path, - .platform = @tagName(pardes.platform), + .platform = builtins.viewPlatform(p), .theme_name = p.theme().name, .theme_file = pardes.colors.loadedThemeFile(p), .compiled_default_shell = config.defaultShell(), .hover_delay_frames = config.look_preview_delay_frames, .native_images = p.native_images, - .capabilities = builtins.capabilities, + .capabilities = builtins.viewCapabilities(p), .state = &p.settings, }); const content = try out.toOwnedSlice(); @@ -1061,7 +1065,7 @@ pub fn openEffectCode(p: *Pardes, id: usize, argument: []const u8) !void { .transition, .scene => {}, else => return error.NotAnEffect, } - if (!setting.enabled(builtins.capabilities)) return error.EffectUnavailable; + if (!setting.enabled(builtins.viewCapabilities(p))) return error.EffectUnavailable; // Without -Dembed-sources the paths would name nothing this build can open. if (!limits.embedded_sources) return error.EffectUnavailable; const paths = effect_sources.forSetting(setting) orelse diff --git a/src/builtins.zig b/src/builtins.zig index 239edeaf..69ac3113 100644 --- a/src/builtins.zig +++ b/src/builtins.zig @@ -16,7 +16,8 @@ const builtin = @import("builtin"); const Header = @import("esp32p4_gpio.zig").Header; const limits = @import("memory.zig").limits; -pub const capabilities: config.Runtime.Capabilities = .{ +/// What this build's own frontend draws and its host does: the render's. +pub const frontend: config.Runtime.Capabilities = .{ .font_picker = pardes.font_picker, .panel_transitions = pardes.hosted, .scene_shaders = pardes.platform == .gui or pardes.platform == .macos, @@ -32,6 +33,30 @@ pub const capabilities: config.Runtime.Capabilities = .{ .lift = pardes.platform == .gui, }; +/// The terminal's build and the window's (docs/next-daemon.md, "Phase 6: +/// GUI replica notes"): each has the other's words, which a view takes as +/// its own frontend does (`viewCapabilities`), so a terminal's replica of a +/// window's session steps as the window's own does, and back. +pub const desktop = pardes.platform == .tty or pardes.platform == .gui; +const window_capabilities: config.Runtime.Capabilities = .{ .font_picker = true, .panel_transitions = true, .scene_shaders = true, .tagline_font_size = true, .window_opacity = true, .window_blur = false, .ligatures = true, .lift = true }; +const terminal_capabilities: config.Runtime.Capabilities = .{ .font_picker = false, .panel_transitions = true, .scene_shaders = false, .tagline_font_size = false, .window_opacity = false, .window_blur = false, .ligatures = false, .lift = false }; + +/// The words this build has: a desktop build's are the window's. +pub const capabilities: config.Runtime.Capabilities = if (desktop) window_capabilities else frontend; + +/// What the live view's frontend takes: a window's, or a terminal's +/// (`Pardes.windowed`, which its client says, Event.frontend). +pub fn viewCapabilities(p: *const Pardes) config.Runtime.Capabilities { + if (comptime !desktop) return frontend; + return if (p.windowed) window_capabilities else terminal_capabilities; +} + +/// The live view's frontend, by name (the Settings report's platform). +pub fn viewPlatform(p: *const Pardes) []const u8 { + if (comptime !desktop) return @tagName(pardes.platform); + return if (p.windowed) "gui" else "tty"; +} + /// Where a builtin acts: at the pane it runs from, or on the editor as a /// whole. acme keeps its window verbs on a window's ctl and its session /// commands elsewhere, as webfs and upas/fs keep session settings on a root @@ -93,6 +118,7 @@ fn isEnabled(comptime T: type) bool { return !@hasDecl(T, "enabled") or T.enabled; } + /// Why `word`, a builtin some build has, is none in this one: `GUI-only` /// for the GUI's own (`gui_only`), else `not in this build`; null for a /// word that is one here, or in no build. @@ -155,6 +181,21 @@ pub const OutputTraits = struct { // Keep enum-dependent signatures out of the outer declaration walk. pub const registry = struct { + /// Whether builtin `b` is one the live view's frontend takes: a window's + /// own words (a builtin that says `in_window`, the settings a terminal + /// cannot show) in a window's view alone. The rest of a build's words are + /// every view's. + pub fn here(p: *const Pardes, b: Builtin()) bool { + return hereFor(b, viewCapabilities(p), !desktop or p.windowed); + } + + /// `here` for a frontend of these capabilities, windowed or not. + pub fn hereFor(b: Builtin(), caps: config.Runtime.Capabilities, windowed: bool) bool { + inline for (comptime manualBuiltinList(), 0..) |T, i| if (@backingInt(b) == i) return !@hasDecl(T, "in_window") or windowed; + inline for (comptime settingList(), comptime manualBuiltinList().len..) |setting, i| if (@backingInt(b) == i) return setting.enabled(caps); + unreachable; + } + pub fn Builtin() type { // Duplicate-name validation compares every pair. @setEvalBranchQuota(200_000); @@ -453,11 +494,14 @@ test "Look does not announce itself on the message row; Del still does" { } test "Ligatures is a setting only in the shell that shapes text" { - const exists = @hasField(registry.Builtin(), "Ligatures"); - try std.testing.expectEqual(pardes.platform == .gui, exists); const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true }); defer p.deinit(); - try std.testing.expectEqual(exists, p.executeBuiltinLine(p.active, "Ligatures off")); + // A desktop build has the word, which a window's view takes alone. + try std.testing.expectEqual(desktop, @hasField(registry.Builtin(), "Ligatures")); + const exists = registry.here(p, .Ligatures); + try std.testing.expectEqual(pardes.platform == .gui, exists); + // Taken either way: run, or said to be GUI-only. + try std.testing.expect(p.executeBuiltinLine(p.active, "Ligatures off")); try std.testing.expectEqual(!exists, p.settings.ligatures); var storage: [8192]u8 = undefined; var out: std.Io.Writer = .fixed(&storage); @@ -468,7 +512,7 @@ test "Ligatures is a setting only in the shell that shapes text" { .compiled_default_shell = config.defaultShell(), .hover_delay_frames = null, .native_images = false, - .capabilities = capabilities, + .capabilities = viewCapabilities(p), .state = &p.settings, }); try std.testing.expectEqual(exists, std.mem.indexOf(u8, storage[0..out.end], "Ligatures off\n") != null); @@ -912,6 +956,7 @@ pub const Fonts = struct { pub const output: OutputTraits = .{ .name = config.fonts_buffer, .steps = true, .commands = true }; pub const enabled = capabilities.font_picker; pub const gui_only = true; + pub const in_window = true; pub fn run(c: Ctx) void { if (comptime enabled) apply(c) else unreachable; } @@ -1665,8 +1710,9 @@ pub const Pet = struct { pub const scope: Scope = .session; pub const takes_arg = true; pub const requires_arg = true; - pub const enabled = pardes.platform == .gui; + pub const enabled = desktop; pub const gui_only = true; + pub const in_window = true; pub fn run(c: Ctx) void { const name = std.mem.trim(u8, c.arg orelse return, " \t\r\n"); c.p.settings.pet = std.meta.stringToEnum(@TypeOf(c.p.settings.pet), name) orelse return; diff --git a/src/builtins_json.zig b/src/builtins_json.zig index 3598a3e2..489f1e22 100644 --- a/src/builtins_json.zig +++ b/src/builtins_json.zig @@ -20,9 +20,16 @@ fn lessName(_: void, a: Entry, b: Entry) bool { } pub fn write(w: *std.Io.Writer) !void { - var order: [pardes.builtin_rows.len]Entry = undefined; - for (pardes.builtin_rows, 0..) |row, i| order[i] = .{ .name = @tagName(row.cmd), .row = i }; - std.mem.sort(Entry, &order, {}, lessName); + var all: [pardes.builtin_rows.len]Entry = undefined; + var len: usize = 0; + // This build's own frontend's words (a desktop build has the other's + // too, which a view of its kind takes: builtins.zig `here`). + for (pardes.builtin_rows, 0..) |row, i| if (pardes.builtins.registry.hereFor(row.cmd, pardes.builtins.frontend, pardes.platform != .tty)) { + all[len] = .{ .name = @tagName(row.cmd), .row = i }; + len += 1; + }; + const order = all[0..len]; + std.mem.sort(Entry, order, {}, lessName); try w.writeAll("[\n"); for (order, 0..) |e, n| { const row = pardes.builtin_rows[e.row]; diff --git a/src/config.zig b/src/config.zig index 742e9010..ebca14ea 100644 --- a/src/config.zig +++ b/src/config.zig @@ -164,7 +164,7 @@ pub const leader_path = paths: { table.set(.Font, null); table.set(.TaglineSize, null); } - if (pardes.platform == .gui) table.set(.Pet, null); + if (builtins.Pet.enabled) table.set(.Pet, null); table.set(.MessageAnimation, null); table.set(.MessageLinger, null); table.set(.MessageFall, null); diff --git a/src/detached/wire.zig b/src/detached/wire.zig index 2f2b95c8..119601fc 100644 --- a/src/detached/wire.zig +++ b/src/detached/wire.zig @@ -11,28 +11,40 @@ const config = @import("pardes_config"); /// 16: a far client says so, the session sends it its blobs' hashes before /// the rest and only the blobs it asks for, all of it in zstd (phase 6's -/// content cache and zstd notes); 15: the session streams a replica its -/// dump and units, and terminal deltas both ways (phase 5 part B); 14: the hello names a session and +/// content cache and zstd notes), and a client says its frontend (a window +/// or a terminal) as its first input, a window replicating a terminal's +/// session and back (phase 6's GUI replica notes); 15: the session streams +/// a replica its dump and units, and terminal deltas both ways (phase 5 +/// 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 = 16; +/// The terminal's build and the window's step alike (`semantics`). +const family = switch (config.platform) { + .tty, .gui => "desktop", + else => @tagName(config.platform), +}; + /// What makes two cores step differently, hashed: a replica's hello carries /// its own, and one of another build is refused. The protocol, the release /// and commit, the platform and build options, every dependency's content /// hash (grammars, ghostty, Unicode) and the walker codec's assumptions /// (pointer width, byte order). Not the OS: a Linux client of a FreeBSD /// session is the main case, and what differs there is the host's, taped. +/// Nor the terminal's build against the window's: their cores step alike, +/// the GUI's own words by the view's frontend (builtins.zig `here`), so a +/// window replicates a terminal's session and a terminal a window's. /// ponytail: an unstamped build (Debug with -Dplatform, every test build) /// has no commit, so two dev trees of one release are told apart only by /// their options and dependencies; -Dstamp-commit stamps one. pub const semantics: u64 = blk: { @setEvalBranchQuota(1_000_000); break :blk std.hash.Wyhash.hash(0, std.fmt.comptimePrint( - "wire {d}\npardes {s} {s}\n{t} grammars {} {} {} {} mupdf {} themes {} workspace_tag {} sources {} board {d}x{d}\nusize {d} {t}\n{s}", + "wire {d}\npardes {s} {s}\n{s} grammars {} {} {} {} mupdf {} themes {} workspace_tag {} sources {} board {d}x{d}\nusize {d} {t}\n{s}", .{ version, config.version, config.commit orelse "unstamped", - config.platform, config.syntax_highlighting, config.syntax_zig_grammar, + family, config.syntax_highlighting, config.syntax_zig_grammar, config.syntax_minimal_grammars, config.syntax_full_grammars, config.mupdf, config.theme_animation, config.workspace_tag, config.embed_sources, config.esp32p4_cols, config.esp32p4_rows, @sizeOf(usize), @@ -78,6 +90,8 @@ pub const ClientTag = enum(u8) { touch_scroll = 0x1c, pointer_leave = 0x1d, focus = 0x1e, + /// Which frontend the client is: a window, or a terminal. + frontend = 0x20, }; const ButtonTag = enum(u8) { @@ -505,6 +519,11 @@ pub fn encodeClient(out: []u8, msg: ClientMsg) Error![]const u8 { .touch_scroll => |v| try w.writeInt(u32, @bitCast(v), .little), .pointer_leave => {}, .focus => |focused| try w.writeByte(@intFromBool(focused)), + .frontend => |f| { + try w.writeByte(@intFromBool(f.windowed)); + try w.writeByte(@intFromBool(f.native_images)); + try w.writeByte(@intFromBool(f.native_image_patches)); + }, // See `clientTag`: no tag, so nothing to encode. .output, .eof, .exited, .lsp_resp, .pipe_resp, .search, .file_changed, .handed, .tick => unreachable, }, @@ -577,6 +596,7 @@ pub fn decodeClient(tag: u8, payload: []const u8) Error!ClientMsg { .touch_scroll => .{ .event = .{ .touch_scroll = try getF32(&r) } }, .pointer_leave => .{ .event = .pointer_leave }, .focus => .{ .event = .{ .focus = try getBool(&r) } }, + .frontend => .{ .event = .{ .frontend = .{ .windowed = try getBool(&r), .native_images = try getBool(&r), .native_image_patches = try getBool(&r) } } }, }; try end(&r); return msg; @@ -594,7 +614,7 @@ pub fn clientBound(msg: ClientMsg) usize { .bye, .ping, .check, .far => 0, .screen_ack, .want => |bytes| bytes.len, .event => |ev| switch (ev) { - .mouse, .resize, .pdf_scroll, .pinch, .touch_scroll, .pointer_leave, .focus => 0, + .mouse, .resize, .pdf_scroll, .pinch, .touch_scroll, .pointer_leave, .focus, .frontend => 0, .key => |k| k.text.len, .paste => |b| b.len, .command => |line| line.len, @@ -732,9 +752,12 @@ test "detached wire: a session is never told to do a frontend's remembering" { // ...and how far it is, and which of the join's blobs it lacks. "far", "want", // ...and everything a person can do to a window. - "key", "mouse", "resize", + "key", "mouse", "resize", "paste", "command", "pdf_scroll", "pinch", "touch_scroll", "pointer_leave", "focus", + // ...and which of its frontends the person sits at: a window, or a + // terminal (what the view draws, and the words it takes). + "frontend", }; // One: the tag set is exactly that, named rather than counted, so diff --git a/src/draw.zig b/src/draw.zig index 03bc0cf9..8503197c 100644 --- a/src/draw.zig +++ b/src/draw.zig @@ -133,7 +133,7 @@ pub fn place(p: *Pardes, s: *Surface) void { // frame's own time, not the stepped animations' 16 ms grid. A grid // snaps (it has no in-between), and so does nothing that shows it. const shown = lift != .off or inactiveDim(p) != 0; - const motion = animation.Motion.of(if (shown and builtins.capabilities.lift) p.settings.motion else .off); + const motion = animation.Motion.of(if (shown and builtins.frontend.lift) p.settings.motion else .off); // A flavour exaggerates what is only a few pixels (Motion.gain). spring.retarget(if (id == p.active) animation.Motion.of(p.settings.motion).gain else 0, p.now_ns, motion); _ = spring.step(p.now_ns); @@ -224,7 +224,7 @@ fn glideCursor(p: *Pardes, s: *Surface) void { s.chrome.cursor_glide = 0; s.chrome.cursor_alpha = 1; s.chrome.cursor_idle_ms = std.math.maxInt(u32); - if (!builtins.capabilities.lift) return; + if (!builtins.frontend.lift) return; const box = focusedCursorBox(p, s) orelse { // No cursor drawn (a PDF or picture took focus, a program hid its // own): a glide under way has nowhere to land, and its springs, @@ -1737,7 +1737,7 @@ test "a lift is sampled at each frame's own time, and asks for frames only while const p = try Pardes.init(std.testing.allocator, .{ .cols = 80, .rows = 24 }); defer p.deinit(); // A grid has no in-between: there a lift snaps. - if (!builtins.capabilities.lift) return error.SkipZigTest; + if (!builtins.frontend.lift) return error.SkipZigTest; _ = try p.setTestFile("text\n"); p.newScratchBelow(0); var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); @@ -1912,7 +1912,7 @@ test "with no lift, no dim and no motion a focus switch asks for no frames" { test "each Motion flavour reaches the lift as its own trajectory" { // A grid snaps; the flavours are a pixel shell's. - if (!builtins.capabilities.lift) return error.SkipZigTest; + if (!builtins.frontend.lift) return error.SkipZigTest; const p = try Pardes.init(std.testing.allocator, .{ .cols = 80, .rows = 24 }); defer p.deinit(); _ = try p.setTestFile("text\n"); @@ -1951,7 +1951,7 @@ test "each Motion flavour reaches the lift as its own trajectory" { } test "the caret is its own body: a page leaves it still under the moving text, a wheel scroll lands its springs on its line's new row" { - if (!builtins.capabilities.lift) return error.SkipZigTest; + if (!builtins.frontend.lift) return error.SkipZigTest; const p = try Pardes.init(std.testing.allocator, .{ .cols = 80, .rows = 30 }); defer p.deinit(); var text: std.ArrayList(u8) = .empty; @@ -1995,7 +1995,7 @@ test "the caret is its own body: a page leaves it still under the moving text, a } test "the focused cursor glides a jump, eases a step, the thin caret too, and is exact at rest" { - if (!builtins.capabilities.lift) return error.SkipZigTest; + if (!builtins.frontend.lift) return error.SkipZigTest; const p = try Pardes.init(std.testing.allocator, .{ .cols = 80, .rows = 30 }); defer p.deinit(); _ = try p.setTestFile(std.mem.asBytes(&@as([20][20]u8, @splat("some text on a line\n".*)))); @@ -2078,7 +2078,7 @@ test "the focused cursor glides a jump, eases a step, the thin caret too, and is } test "a tag caret past its row's end glides to the tag's right edge, where the layer's is" { - if (!builtins.capabilities.lift) return error.SkipZigTest; + if (!builtins.frontend.lift) return error.SkipZigTest; const p = try Pardes.init(std.testing.allocator, .{ .cols = 60, .rows = 16 }); defer p.deinit(); p.update(.{ .resize = .{ .cols = 60, .rows = 16, .row_metrics = .{ .body_w = 10, .body_h = 20, .tagline_w = 6, .tagline_h = 12 } } }); @@ -2128,7 +2128,7 @@ test "a tag caret past its row's end glides to the tag's right edge, where the l } test "a terminal's cursor lands with scrolling output, never gliding against it" { - if (!builtins.capabilities.lift or !pardes.terminal_panes) return error.SkipZigTest; + if (!builtins.frontend.lift or !pardes.terminal_panes) return error.SkipZigTest; const p = try Pardes.init(std.testing.allocator, .{ .cols = 80, .rows = 12 }); defer p.deinit(); while (p.nextEffect()) |_| {} @@ -2323,7 +2323,7 @@ fn twoColumns(p: *Pardes, arena: *std.heap.ArenaAllocator) !void { } test "while its pane slides the cursor rides with it, at the same cell of the pane every frame" { - if (!builtins.capabilities.lift) return error.SkipZigTest; + if (!builtins.frontend.lift) return error.SkipZigTest; const p = try Pardes.init(std.testing.allocator, .{ .cols = 120, .rows = 20 }); defer p.deinit(); var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); @@ -2376,7 +2376,7 @@ test "while its pane slides the cursor rides with it, at the same cell of the pa } test "focus moved to another column glides from where the cursor was drawn" { - if (!builtins.capabilities.lift) return error.SkipZigTest; + if (!builtins.frontend.lift) return error.SkipZigTest; const p = try Pardes.init(std.testing.allocator, .{ .cols = 120, .rows = 20 }); defer p.deinit(); var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); @@ -2412,7 +2412,7 @@ test "focus moved to another column glides from where the cursor was drawn" { } test "a click that takes focus glides the cursor once, to where it lands on release" { - if (!builtins.capabilities.lift) return error.SkipZigTest; + if (!builtins.frontend.lift) return error.SkipZigTest; const p = try Pardes.init(std.testing.allocator, .{ .cols = 120, .rows = 20 }); defer p.deinit(); var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); @@ -2446,7 +2446,7 @@ test "a click that takes focus glides the cursor once, to where it lands on rele } test "focus moving to a pane with no cursor while the cursor glides lets the session go idle" { - if (!builtins.capabilities.lift) return error.SkipZigTest; + if (!builtins.frontend.lift) return error.SkipZigTest; const p = try Pardes.init(std.testing.allocator, .{ .cols = 120, .rows = 20 }); defer p.deinit(); var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); @@ -2475,7 +2475,7 @@ test "focus moving to a pane with no cursor while the cursor glides lets the ses } test "a pane focus reaches brightens on the same spring the one it leaves dims on, and Motion off snaps" { - if (!builtins.capabilities.lift) return error.SkipZigTest; + if (!builtins.frontend.lift) return error.SkipZigTest; const p = try Pardes.init(std.testing.allocator, .{ .cols = 80, .rows = 24 }); defer p.deinit(); _ = try p.setTestFile(std.mem.asBytes(&@as([4][20]u8, @splat("some text on a line\n".*)))); diff --git a/src/exec.zig b/src/exec.zig index df397b37..e1c13daa 100644 --- a/src/exec.zig +++ b/src/exec.zig @@ -1033,7 +1033,7 @@ fn applyInitText(p: *Pardes, text: []const u8, settings_only: bool) void { if (settings_only and setting == null and std.meta.stringToEnum(Builtin, word[0 .. std.mem.indexOfAny(u8, word, " \t+") orelse word.len]) != null) continue; // One init file serves the window and the terminal: a setting only // the other has (Font, GripWidth in a terminal) is no failure here. - if (setting) |s| if (!s.enabled(builtins.capabilities)) continue; + if (setting) |s| if (!s.enabled(builtins.viewCapabilities(p))) continue; const failures = p.fs.failures; const known = executeBuiltinLine(p, p.active, line); if (known and p.fs.failures == failures) continue; @@ -1057,6 +1057,12 @@ pub fn runBuiltin(p: *Pardes, b: Builtin, id: usize, txt: []const u8, arg: ?[]co /// `runBuiltin` saying whether a gesture on the pane's body made it. pub fn runBuiltinFrom(p: *Pardes, b: Builtin, id: usize, txt: []const u8, arg: ?[]const u8, from_body: bool) void { if (!normal.multiOnce(p)) return; // a builtin is per-keystroke, never per-cursor + // A window's own word in a terminal's view (Fonts, Lift): said, as a + // word a build lacks is, and never run. + if (!builtins.registry.here(p, b)) { + var said: [96]u8 = undefined; + return p.reportFailure(id, std.fmt.bufPrint(&said, "{s} is GUI-only, invalid here", .{@tagName(b)}) catch "GUI-only, invalid here"); + } // No pane at all (the window Delcol emptied): a word runs all the same, // with a stand-in that is no pane (New, Newcol, Exit are what make sense). const pane = p.panes[id] orelse (if (builtins.registry.scope(b) == .session or p.anyPane() == null) p.standIn() orelse return else return); diff --git a/src/gui/gui.zig b/src/gui/gui.zig index a88a7335..f62871c4 100644 --- a/src/gui/gui.zig +++ b/src/gui/gui.zig @@ -24,6 +24,8 @@ const ninep_io = @import("../9p_io.zig"); const daemon = @import("../daemon.zig"); const upgrade = @import("../upgrade.zig"); +const replica = @import("../replica.zig"); +const wire = @import("../detached/wire.zig"); const tracy = @import("../tracy.zig"); pub const c = @import("gui_c"); // SDL3 and font.h, translated by build.zig @@ -671,24 +673,29 @@ test "closing tombstone overlays but never owns canonical cells" { } fn updateCoreResize(core: *pardes.Pardes, cols: u16, rows: u16, cell_w: u32, cell_h: u32, tag_w: u32, tag_h: u32) bool { + core.update(resizeOf(core, cols, rows, cell_w, cell_h, tag_w, tag_h) orelse return false); + return true; +} + +/// The resize a window of `cols` by `rows` cells of these sizes is to the +/// live view, or null when it is that already. +fn resizeOf(core: anytype, cols: u16, rows: u16, cell_w: u32, cell_h: u32, tag_w: u32, tag_h: u32) ?pardes.Event { const metrics: pardes.RowMetrics = .{ .body_w = @intCast(cell_w), .body_h = @intCast(cell_h), .tagline_w = @intCast(tag_w), .tagline_h = @intCast(tag_h) }; const same_metrics = std.meta.eql(metrics, core.row_metrics); if (comptime pardes.pdf_enabled) { const cell_px_w: u16 = @intCast(@min(@max(1, cell_w), std.math.maxInt(u16))); const cell_px_h: u16 = @intCast(@min(@max(1, cell_h), std.math.maxInt(u16))); if (cols == core.screen_w and rows == core.screen_h and - cell_px_w == core.cell_pixels.w and cell_px_h == core.cell_pixels.h and same_metrics) return false; - core.update(.{ .resize = .{ + cell_px_w == core.cell_pixels.w and cell_px_h == core.cell_pixels.h and same_metrics) return null; + return .{ .resize = .{ .cols = cols, .rows = rows, .cell_pixels = .{ .w = cell_px_w, .h = cell_px_h }, .row_metrics = metrics, - } }); - } else { - if (cols == core.screen_w and rows == core.screen_h and same_metrics) return false; - core.update(.{ .resize = .{ .cols = cols, .rows = rows, .row_metrics = metrics } }); + } }; } - return true; + if (cols == core.screen_w and rows == core.screen_h and same_metrics) return null; + return .{ .resize = .{ .cols = cols, .rows = rows, .row_metrics = metrics } }; } const TouchSample = struct { x: f32 = 0, y: f32 = 0, pressure: f32 = 1 }; @@ -1963,12 +1970,23 @@ fn setTransitionFields( } } -pub const run = runNative; +pub fn run(init: std.process.Init, opts: pardes.Options, headless: bool) !void { + return runNative(init, opts, headless, null); +} + +/// `pardes-gui --attach=:` (and `:`, +/// through ssh, main.zig): this window a replica client of a session +/// elsewhere, as the tty's `remote` is a terminal's (`remoteSession`). +pub fn remote(init: std.process.Init, opts: pardes.Options, path: []const u8, session: []const u8, far: bool) !void { + return runNative(init, opts, false, .{ .path = path, .session = session, .far = far }); +} -fn runNative(init: std.process.Init, opts_in: pardes.Options, headless: bool) !void { +const Dial = struct { path: []const u8, session: []const u8, far: bool }; + +fn runNative(init: std.process.Init, opts_in: pardes.Options, headless: bool, dial: ?Dial) !void { const gpa = init.gpa; const env = init.environ_map; - if (env.get("PARDES_TEST_GRID") != null) return runGrid(init, opts_in); + if (dial == null and env.get("PARDES_TEST_GRID") != null) return runGrid(init, opts_in); const test_mode = env.get("PARDES_TEST") != null; const capture_dir = env.get("PARDES_TEST_CAPTURE_DIR"); @@ -2294,6 +2312,7 @@ fn runNative(init: std.process.Init, opts_in: pardes.Options, headless: bool) !v // compositor moves it, as it does a title bar. if (!test_mode and !c.SDL_SetWindowHitTest(window, hitTest, &g)) log.warn("SDL_SetWindowHitTest: {s}", .{c.SDL_GetError()}); + if (dial) |to| return remoteSession(init, &g, opts_in, test_mode, to); try localSession(init, &g, opts_in, test_mode, headless); } @@ -2458,6 +2477,10 @@ fn localSession( frame_capture_dir = if (std.c.getenv("PARDES_FRAMES_CAPTURE")) |dir| std.mem.span(dir) else null; const host = shell.host(); core.host = host; + shell.peers = .{ .gpa = gpa, .io = io, .name = daemon.name(), .wake = sdlWake, .alone_unattended = headless }; + defer shell.peers.deinit(); + // Before the core goes: each client sees its link end. + defer shell.peers.dropAll(shell.core); while (core.nextEffect()) |e| core.perform(e); // An upgraded session's shells, once a fresh session's own has a @@ -2496,20 +2519,25 @@ fn localSession( if (headless) { shell.closeTheWindow(); // Nothing else may wake the first wait. - daemon.watch(&queue, deliverNote); + daemon.watch(&shell, deliverNote); } while (!core.quit) { pardes.turn.bump(&pardes.turn.restores); try core.pump(host); + // Its unit to each replica client, and theirs taken in. + shell.peers.boundary(core); upgrade.locate(); // Asked in the step (the word), done between steps: the session whole. if (shell.upgrade_asked) |pane| shell.upgradeNow(pane); // A window asked for again, or an adopted shell, from the daemon's // thread through the queue; started after the first frame. - daemon.watch(&queue, deliverNote); + daemon.watch(&shell, deliverNote); if (core.quit) break; // a session that ended does not restore into one if (core.takeRestore()) |rp| blk: { + // ponytail: a Restore replaces the core its clients replicate; + // they are let go, and attach again (as the tty's). + shell.peers.dropAll(core); const bytes = filesystem.readRestore(gpa, rp, core.settings.dump_dir.get()) catch |err| { core.reportError(core.active, "Restore", err); break :blk; @@ -2525,6 +2553,7 @@ fn localSession( // the others close. shell.closeOtherWindows(); shell.gview = 0; + shell.windowed = 1; shell.stopPtys(); for (0..pardes.MAX_PANES) |wid| file_watch.watchPane( inotify_fd, @@ -2561,6 +2590,314 @@ fn localSession( } } +/// A window's link to a session elsewhere (`remoteSession`): what the +/// window's input made, fed to the replica once its own view is put back, +/// and what the link's reader took off the stream. +const Client = struct { + link: replica.Link, + io: std.Io, + gpa: std.mem.Allocator, + /// The window's inputs since the last feed, their texts in `texts`: + /// read over its own view (`Replica.within`), applied after it. + pending: std.ArrayListUnmanaged(pardes.Event) = .empty, + texts: std.heap.ArenaAllocator, + /// The reader's, under `lock`: what it took, and whether the link ended. + lock: std.Io.Mutex = .init, + inbox: std.ArrayListUnmanaged(replica.Said) = .empty, + taken: std.ArrayListUnmanaged(replica.Said) = .empty, + ended: bool = false, + + fn deinit(cl: *Client) void { + cl.pending.deinit(cl.gpa); + cl.texts.deinit(); + cl.inbox.deinit(cl.gpa); + cl.taken.deinit(cl.gpa); + } + + fn post(cl: *Client, ev: pardes.Event) void { + var e = ev; + const a = cl.texts.allocator(); + switch (e) { + .key => |*k| k.text = a.dupe(u8, k.text) catch "", + .paste, .command => |*b| b.* = a.dupe(u8, b.*) catch return, + else => {}, + } + cl.pending.append(cl.gpa, e) catch {}; + } + + /// What the window's input made, applied at once and sent. + fn feed(cl: *Client) void { + for (cl.pending.items) |ev| cl.link.input(ev); + cl.pending.clearRetainingCapacity(); + _ = cl.texts.reset(.retain_capacity); + } + + /// The reader's: a message of the stream, for the loop, which it wakes. + fn said(cl: *Client, msg: replica.Said) bool { + cl.lock.lockUncancelable(cl.io); + defer cl.lock.unlock(cl.io); + cl.inbox.append(cl.gpa, msg) catch return false; + sdlWake(null); + return true; + } + + /// What the reader took, in its order, and the link's end after it. + fn takeSaid(cl: *Client) void { + cl.lock.lockUncancelable(cl.io); + std.mem.swap(std.ArrayListUnmanaged(replica.Said), &cl.inbox, &cl.taken); + const ended = cl.ended; + cl.lock.unlock(cl.io); + for (cl.taken.items) |msg| { + // PARDES_TEST_LATENCY: when a terminal's delta came (an echo's). + if (msg == .screen) latencyNote("S {d}\n", .{monoNs()}); + cl.link.take(msg); + } + cl.taken.clearRetainingCapacity(); + if (ended) { + cl.link.quit = true; + cl.link.gone = true; + } + } + + /// Its own view drawn in the window, outside any step, as the tty's + /// client draws its terminal (tty.zig `Remote.draw`): what presenting + /// writes in the core (a frame skipped, one owed) is put back. + fn draw(cl: *Client, s: *Shell) void { + const r = cl.link.r; + const core = r.core(); + const skipped = core.present_skipped; + const needs = core.needs_frame; + core.frames.mark_start = pardes.FrameStats.nowNs(); + core.frames.mark_update = core.frames.mark_start; + r.draw(.{ .ctx = s, .f = present }); + core.frames.mark_render = core.frames.mark_update; + cl.link.owed = core.present_skipped; + core.frames.record(pardes.FrameStats.nowNs(), false, cl.link.owed); + core.present_skipped = skipped; + core.needs_frame = needs; + cl.link.drawn(s.presented); + } +}; + +/// The session's stream, onto the client's inbox: its units, and its end. +fn clientReader(cl: *Client, fd: c_int, rest: *replica.Framer) void { + replica.readLink(cl.gpa, fd, rest, cl, Client.said); + cl.lock.lockUncancelable(cl.io); + cl.ended = true; + cl.lock.unlock(cl.io); + sdlWake(null); +} + +/// What the window does over its own view (`Replica.within`), its inputs +/// posted to the client (`Input.remote`): an SDL event dispatched, its size +/// (the tagline's face too), the pointer under a frame that moved, the +/// timedemo's and the test feed's steps. +const OwnView = struct { + g: *Gui, + in: *Input, + s: *Shell, + sev: ?*const c.SDL_Event = null, + pointer: bool = false, + eof: bool = false, + + fn run(v: *OwnView, core: *pardes.Pardes) anyerror!void { + if (v.sev) |sev| return dispatch(v.g, v.in, sev); + const g = v.g; + if (fitTaglineFont(g, core.settings.font.tagline_percent)) v.s.remote.?.link.dirty = true; + const geom = windowCells(g); + if (resizeOf(core, geom.cols, geom.rows, g.cell_w, g.cell_h, g.tagline_width, g.tagline_height)) |ev| v.in.post(ev); + if (v.pointer) refreshPresentedPointer(g, v.in); + runDemo(g, v.in, core); + if (v.s.test_mode) { + const r = v.s.feed.pump(v.s.gpa, v.in, g) catch return error.TestFeed; + if (r.eof) v.eof = true; + } + } +}; + +/// `pardes-gui --attach=:`: the window, made as a session's +/// is, a replica client of that session (docs/next-daemon.md, "Phase 6: GUI +/// replica notes"). Its own core, loaded from the session's dump, applies +/// its input at once (src/replica.zig) and draws its own view; the +/// session's units are the truth it rolls back to. The tty's `remote`, with +/// a window for a terminal. +fn remoteSession(init: std.process.Init, g: *Gui, opts_in: pardes.Options, test_mode: bool, to: Dial) !void { + const io = init.io; + const gpa = init.gpa; + const Said = struct { + fn no(o: std.Io, comptime fmt: []const u8, args: anytype) noreturn { + var buf: [800]u8 = undefined; + std.Io.File.stderr().writeStreamingAll(o, std.fmt.bufPrint(&buf, "pardes-gui: --attach: " ++ fmt ++ "\n", args) catch "pardes-gui: --attach failed\n") catch {}; + std.process.exit(1); + } + }; + var why: [600]u8 = @splat(0); + // Far (through ssh, or PARDES_REPLICA_FAR=1): its join's blobs by hash + // and its stream in zstd, as the tty's client (replica.zig `Have`). + const far = if (init.environ_map.get("PARDES_REPLICA_FAR")) |v| std.mem.eql(u8, v, "1") else to.far; + var have_store: replica.Have = if (far) .init(io) else .{ .io = io }; + defer have_store.deinit(); + const have: ?*replica.Have = if (far) &have_store else null; + var dial_t0 = std.Io.Clock.awake.now(io).nanoseconds; + var joined = replica.dial(gpa, to.path, to.session, &why, have) orelse Said.no(io, "{s}", .{std.mem.sliceTo(&why, 0)}); + if (joined.semantics != wire.semantics) Said.no(io, "{s}", .{replica.Link.upgrade_words}); + + const allocs = pardes.memory.init(gpa); + defer pardes.memory.deinit(); + pardes.image.start(io, allocs.image); + if (comptime pardes.pdf_enabled) pardes.pdf.start(allocs.pdf); + pardes.syntax.start(allocs.tree_sitter); + defer { + pardes.image.stop(); + if (comptime pardes.pdf_enabled) pardes.pdf.stop(); + pardes.syntax.stop(); + } + var o = opts_in; + o.image_allocator = allocs.image; + o.pdf_allocator = allocs.pdf; + var r = replica.Link.load(gpa, &joined, o, &why, have) orelse Said.no(io, "{s}", .{std.mem.sliceTo(&why, 0)}); + var dial_ms: u64 = @intCast(@divTrunc(std.Io.Clock.awake.now(io).nanoseconds - dial_t0, std.time.ns_per_ms)); + + var client: Client = .{ .link = .{ .r = r, .fd = joined.fd }, .io = io, .gpa = gpa, .texts = .init(gpa) }; + defer client.deinit(); + const link = &client.link; + try link.fromEnv(gpa, init.environ_map); + defer link.deinit(gpa); + // A client spawns, watches and serves nothing: the Shell's tables are + // empty ones, there for what draws. + var ptys: [pardes.MAX_PANES]?Pty = @splat(null); + var gens: [pardes.MAX_PANES]u32 = @splat(0); + var queue: Queue = .{ .io = io, .gpa = gpa, .lsp_allocator = allocs.lsp }; + defer queue.deinit(); + var pipe_tasks: PipeTasks = .{}; + var watches: file_watch.Table = @splat(null); + const prompt_rcs: host_io.Shell.PromptFiles = .{}; + var shell: Shell = .{ + .core = r.core(), + .gui = g, + .io = io, + .gpa = gpa, + .lsp_allocator = allocs.lsp, + .prompt_rcs = &prompt_rcs, + .ptys = &ptys, + .gens = &gens, + .queue = &queue, + .pipe_tasks = &pipe_tasks, + .inotify_fd = -1, + .watches = &watches, + .test_mode = test_mode, + .remote = &client, + }; + defer shell.shaders.deinit(gpa, -1, &watches); + g.no_blink = test_mode; + defer g.hit_core = null; + _ = c.SDL_StartTextInput(g.window); + if (test_mode) setStdinRaw() catch {}; + // A join a pass: the first, and one after the replica diverged or the + // session let it go to upgrade. The window stays as it is. + while (true) { + r.gmtoff = joined.gmtoff; + const core = r.core(); + shell.core = core; + shell.gview = joined.view; + shell.surface = null; + g.hit_core = core; + frame_probe = &core.frames; + link.reset(r, joined.fd); + link.joinedAs(&joined, dial_ms); + client.ended = false; + // ponytail: why it joined again is the window's title (and its + // log) until a key, where a terminal's client draws it over its + // frame: a window's frame is the core's cells, which it cannot write. + var titled = link.notice_len > 0; + if (titled) { + var title: [260]u8 = undefined; + _ = c.SDL_SetWindowTitle(g.window, std.fmt.bufPrintSentinel(&title, "pardes: {s}", .{link.notice()}, 0) catch "pardes"); + log.warn("{s}", .{link.notice()}); + } + const reader = try std.Thread.spawn(.{}, clientReader, .{ &client, joined.fd, &joined.rest }); + var in: Input = .{ .core = core, .shell = &shell, .remote = &client }; + // What it is, then its size, are its view's first inputs. + link.input(.{ .frontend = .{ .windowed = true, .native_images = true, .native_image_patches = true } }); + var drew = false; + while (!link.quit) { + core.frames.period_ns = refreshNs(g); + syncLigatures(g, core); + { + var passes: [Post.max]ShaderBuild.Pass = undefined; + g.post.sync(gpa, g.device, g.swapchain_format, shell.shaders.view(&core.settings.post, &passes), shell.shaders.revision, core); + } + var own: OwnView = .{ .g = g, .in = &in, .s = &shell, .pointer = drew }; + r.within(&own, OwnView.run); + client.feed(); + if (own.eof) break; + // Its predicted echo judged and caught up, once a frame. + if (r.echoFrame()) link.dirty = true; + drew = false; + if (link.dirty) { + client.draw(&shell); + drew = shell.presented; + } + const predicting = r.echo.n > 0 or r.echo.cursor != null or r.echo.nd > 0; + var ms: c_int = if (test_mode) 16 else -1; + if (demoDue(g)) |due| ms = if (ms < 0) due else @min(ms, due); + if (predicting or link.owed) ms = if (ms < 0) frame_ms else @min(ms, frame_ms); + if (link.quietCheck()) |wait| ms = if (ms < 0) @intCast(wait) else @min(ms, @as(c_int, @intCast(wait))); + // Idle, its frame drawn: the next input needs no copy taken. + if (ms != 0) r.ready(); + var sev = std.mem.zeroes(c.SDL_Event); + g.input_seen = false; + var got = c.SDL_WaitEventTimeout(&sev, ms); + while (got) : (got = c.SDL_PollEvent(&sev)) { + if (sev.type == c.SDL_EVENT_USER) continue; + var one: OwnView = .{ .g = g, .in = &in, .s = &shell, .sev = &sev }; + r.within(&one, OwnView.run); + client.feed(); + if (link.quit) break; + } + client.takeSaid(); + r.settle(); + if (titled and link.notice_len == 0) { + titled = false; + _ = c.SDL_SetWindowTitle(g.window, "pardes"); + } + if (link.owed or r.echo.changed) link.dirty = true; + if (r.diverged != null) link.quit = true; + } + if (init.environ_map.get("PARDES_REPLICA_STATS")) |file| link.writeStats(file); + if (!link.gone) replica.bye(joined.fd); + // The reader ends with the link: what it took meanwhile is let go. + _ = libc.shutdown(joined.fd, 2); + reader.join(); + client.lock.lockUncancelable(io); + for (client.inbox.items) |msg| switch (msg) { + .unit, .screen, .refused => |b| std.heap.c_allocator.free(b), + .checked => {}, + }; + client.inbox.clearRetainingCapacity(); + client.lock.unlock(io); + _ = libc.close(joined.fd); + joined.rest.deinit(gpa); + if (!link.rejoins()) { + // What it made since it joined, kept for its next start. + if (have) |h| h.keep(r.core()); + r.deinit(); + if (link.gone) Said.no(io, "'{s}' let this client go (a Detach in it, or the session's end)", .{to.session}); + return; + } + // The session again, the core it leaves held meanwhile. + if (have) |h| h.leaving(r.core()); + dial_t0 = std.Io.Clock.awake.now(io).nanoseconds; + joined = replica.Link.redial(gpa, to.path, to.session, &why, have) orelse Said.no(io, "{s}", .{std.mem.sliceTo(&why, 0)}); + if (have) |h| h.left(); + r.deinit(); + r = replica.Link.load(gpa, &joined, o, &why, have) orelse Said.no(io, "{s}", .{std.mem.sliceTo(&why, 0)}); + dial_ms = @intCast(@divTrunc(std.Io.Clock.awake.now(io).nanoseconds - dial_t0, std.time.ns_per_ms)); + } +} + +const frame_ms: c_int = @intCast(pardes.animation.frame_ns / std.time.ns_per_ms); + fn runGrid(init: std.process.Init, opts_in: pardes.Options) !void { const io = init.io; const gpa = init.gpa; @@ -3090,14 +3427,33 @@ const Input = struct { /// The shell whose windows these are: a window closed while others /// stay takes its view with it (views.zig). shell: ?*Shell = null, + /// A replica client's (`remote`): its inputs go to its link, never + /// straight to the core, which only reads here. + remote: ?*Client = null, quit: bool = false, fn post(in: *Input, ev: pardes.Event) void { + if (in.remote) |r| return r.post(ev); + // The window's input is its own view's, a replica client's input + // the session's last or not. + if (in.shell) |s| if (s.core.view != s.gview) { + _ = s.windowView(); + }; if (in.core) |core| return core.update(ev); } fn close(in: *Input) void { - if (in.shell) |s| if (pardes.views.count(s.core) > 1) return s.closeView(s.core.view); + if (in.remote) |r| { + r.link.quit = true; + in.quit = true; + return; + } + if (in.shell) |s| { + if (s.windowsOpen() > 1) return s.closeView(s.core.view); + // The last window, with replica clients: they keep the session, + // as a Detach would, the daemon holding it. + if (s.peers.count() > 0 and daemon.kept()) return s.closeTheWindow(); + } if (in.core) |core| core.quit = true; in.quit = true; } @@ -3127,7 +3483,9 @@ fn dispatch(g: *Gui, in: *Input, sev: *const c.SDL_Event) void { updateDisplayScale(g.window); // Underlines are drawn into the glyphs a logical pixel thick. resetGlyphAtlas(g); - if (in.core) |core| core.needs_frame = true; + if (in.remote) |r| { + r.link.dirty = true; + } else if (in.core) |core| core.needs_frame = true; }, c.SDL_EVENT_WINDOW_FOCUS_GAINED => g.post.focus(true), c.SDL_EVENT_WINDOW_FOCUS_LOST => g.post.focus(false), @@ -3141,7 +3499,7 @@ fn dispatch(g: *Gui, in: *Input, sev: *const c.SDL_Event) void { c.SDL_EVENT_WINDOW_CLOSE_REQUESTED => in.close(), c.SDL_EVENT_WINDOW_FOCUS_GAINED => { in.post(.{ .focus = true }); - if (in.core) |core| upgrade.noticeNewer(core); + if (in.remote == null) if (in.core) |core| upgrade.noticeNewer(core); }, c.SDL_EVENT_WINDOW_FOCUS_LOST => in.post(.{ .focus = false }), c.SDL_EVENT_WINDOW_MOUSE_LEAVE => { @@ -3161,8 +3519,14 @@ fn dispatch(g: *Gui, in: *Input, sev: *const c.SDL_Event) void { const want = std.math.clamp(g.px + step, font_px_min, font_px_max); if (want != g.px) { g.px = want; - refitFont(g, in.core); - if (in.core) |core| observeGuiFont(g, core); + // A client's view is sized by its next loop, as its input. + if (in.remote) |r| { + refitFont(g, null); + r.link.dirty = true; + } else { + refitFont(g, in.core); + if (in.core) |core| observeGuiFont(g, core); + } } return; } @@ -3590,6 +3954,18 @@ fn wheelAt(g: *Gui, in: *Input, w: WheelTurn, mc: MouseCell) void { in.post(.{ .mouse = .{ .button = .wheel_down, .kind = .press, .col = mc.col, .row = mc.row, .tag_hit = mc.tag_hit, .body_hit = mc.body_hit, .ctrl = w.mods.ctrl, .shift = w.mods.shift, .alt = w.mods.alt } }); while (g.program_wheel <= -1) : (g.program_wheel += 1) in.post(.{ .mouse = .{ .button = .wheel_up, .kind = .press, .col = mc.col, .row = mc.row, .tag_hit = mc.tag_hit, .body_hit = mc.body_hit, .ctrl = w.mods.ctrl, .shift = w.mods.shift, .alt = w.mods.alt } }); + } else if (in.remote != null) { + // ponytail: a replica client's wheel moves the view a + // whole row a turn, with no glide and no touchpad's + // fraction: its core's clock is the session's, which + // moves only as its units come. + if (notchOf(w.y, w.integer_y)) |lines| { + g.program_wheel = @floatFromInt(lines); + } else g.program_wheel = accumulateWheelDelta(g.program_wheel, w.y); + while (g.program_wheel >= 1) : (g.program_wheel -= 1) + in.post(.{ .mouse = .{ .button = .wheel_down, .kind = .press, .col = mc.col, .row = mc.row, .shift = true } }); + while (g.program_wheel <= -1) : (g.program_wheel += 1) + in.post(.{ .mouse = .{ .button = .wheel_up, .kind = .press, .col = mc.col, .row = mc.row, .shift = true } }); } else { g.scroll_pane = id; g.scroll_col = mc.col; @@ -3680,10 +4056,11 @@ fn heldPointerButton(g: *const Gui) ?pardes.Mouse.Button { return null; } -fn refreshPresentedPointer(g: *Gui, core: *pardes.Pardes) void { +fn refreshPresentedPointer(g: *Gui, in: *Input) void { if (!g.pointer_present) return; + const core = in.core orelse return; const mc = mouseCell(g, core, g.pad_x, g.pad_y) orelse { - if (g.pointer_mapped) core.update(.pointer_leave); + if (g.pointer_mapped) in.post(.pointer_leave); g.pointer_mapped = false; return; }; @@ -3693,7 +4070,7 @@ fn refreshPresentedPointer(g: *Gui, core: *pardes.Pardes) void { g.pointer_cell = mc; if (!moved) return; const held = heldPointerButton(g); - core.update(.{ .mouse = .{ + in.post(.{ .mouse = .{ .button = held orelse .none, .kind = if (held != null) .drag else .motion, .col = mc.col, @@ -3806,6 +4183,22 @@ const Shell = struct { gview: u8 = 0, /// Upgrade was asked from this pane, to be done between steps (`upgradeNow`). upgrade_asked: ?u8 = null, + /// This window a replica client of a session elsewhere (`remote`). + remote: ?*Client = null, + /// The session's replica clients (src/replica.zig), on sockets: views + /// of their own with no window here (`windowed`). + peers: replica.Peers = .{}, + /// The views that are this process's windows (the rest are clients'). + windowed: u8 = 1, + /// This wait took only a replica's post (its input, its join): the pump + /// after it reads no new time, so it moves nothing the replicas' + /// speculations stand on (tty.zig's `mail_only`). + mail_only: bool = false, + waited: bool = false, + /// With replica clients, a wait takes one person's input (tty.zig + /// `split`): the next is held for the next wait. + took_input: bool = false, + held: ?c.SDL_Event = null, fn reap(s: *Shell) void { const now = std.Io.Clock.awake.now(s.queue.io).toMilliseconds(); @@ -3894,9 +4287,11 @@ const Shell = struct { /// window, for `pardes-gui --attach` to open one again. fn detachWindow(ctx: ?*anyopaque) void { const s = shellOf(ctx); + // A replica client's: its link ends. + if (s.peers.detach(s.core.view)) return; if (s.gui == null) return s.core.reportFailure(s.core.active, "Detach: no window is open"); // One of several: its window goes, and the session stays in the rest. - if (pardes.views.count(s.core) > 1) return s.closeView(s.core.view); + if (s.windowsOpen() > 1) return s.closeView(s.core.view); if (!daemon.kept()) return s.core.reportFailure(s.core.active, "Detach: no pardes daemon keeps this session; closing its window ends it"); s.closeTheWindow(); } @@ -3906,6 +4301,9 @@ const Shell = struct { const g = s.gui orelse return; const k = s.core.view; if (s.gview == k) return; + // A replica client's view has no window here: the Gui keeps the one + // it holds (`windowView` puts that view back when it acts). + if (s.windowed & (@as(u8, 1) << @intCast(k)) == 0) return; if (s.gview < s.windows.len) copyWindow(&s.windows[s.gview], g); copyWindow(g, &s.windows[k]); s.gview = k; @@ -3916,7 +4314,11 @@ const Shell = struct { if (!pardes.views.several(s.core)) return; const g = s.gui orelse return; const w = c.SDL_GetWindowFromEvent(sev) orelse return; - if (w == g.window) return; + // The Gui's window's, while a client's view is live: its own again. + if (w == g.window) { + _ = s.windowView(); + return; + } for (s.windows, 0..) |win, k| if (k != s.gview and pardes.views.isOpen(s.core, @intCast(k)) and win.window == w) { s.core.toView(@intCast(k)); return s.follow(); @@ -3950,10 +4352,20 @@ const Shell = struct { if (g.capture_dir.len > 0) std.Io.Dir.cwd().createDirPath(s.io, g.capture_dir) catch {}; } s.gview = k; + s.windowed |= @as(u8, 1) << @intCast(k); s.core.toView(k); s.core.needs_frame = true; } + /// The Gui's window's view live, for what the window does to its own + /// (its size, its scroll): a replica client's input may have been the + /// last. True when it was not, and is now. + fn windowView(s: *Shell) bool { + if (s.core.view == s.gview or !pardes.views.isOpen(s.core, s.gview)) return false; + s.core.toView(s.gview); + return true; + } + /// View `k`'s window closed while others stay: the view goes with it. fn closeView(s: *Shell, k: u8) void { const g = s.gui orelse return; @@ -3962,11 +4374,40 @@ const Shell = struct { closeWindow(g); releaseWindowParts(g, s.gpa); s.gview = std.math.maxInt(u8); + s.windowed &= ~(@as(u8, 1) << @intCast(k)); s.core.closeView(k); + // Into another window's view, if a client's was the one left live. + for (0..pardes.views.max) |i| if (s.windowed & (@as(u8, 1) << @intCast(i)) != 0 and pardes.views.isOpen(s.core, @intCast(i))) { + if (s.core.view != i) s.core.toView(@intCast(i)); + break; + }; s.follow(); s.core.needs_frame = true; } + /// With replica clients, a wait takes one person's input and its pump + /// makes one unit of it (tty.zig `split`): whether `sev`, a second, is + /// held for the next wait. Any event but a wake is no replica's post. + fn split(s: *Shell, sev: *const c.SDL_Event) bool { + if (sev.type != c.SDL_EVENT_USER) s.mail_only = false; + if (!s.peers.recording) return false; + switch (sev.type) { + c.SDL_EVENT_KEY_DOWN, c.SDL_EVENT_TEXT_INPUT, c.SDL_EVENT_MOUSE_BUTTON_DOWN, c.SDL_EVENT_MOUSE_BUTTON_UP, c.SDL_EVENT_MOUSE_MOTION, c.SDL_EVENT_MOUSE_WHEEL, c.SDL_EVENT_WINDOW_FOCUS_GAINED, c.SDL_EVENT_WINDOW_FOCUS_LOST, c.SDL_EVENT_WINDOW_MOUSE_LEAVE, c.SDL_EVENT_FINGER_DOWN, c.SDL_EVENT_FINGER_MOTION, c.SDL_EVENT_FINGER_UP, c.SDL_EVENT_PINCH_BEGIN, c.SDL_EVENT_PINCH_UPDATE => {}, + else => return false, + } + if (s.took_input) { + s.held = sev.*; + return true; + } + s.took_input = true; + return false; + } + + /// How many of the session's views are windows here. + fn windowsOpen(s: *const Shell) usize { + return @popCount(s.windowed & s.core.views_open); + } + /// The session's end: every window but the live one closed. fn closeOtherWindows(s: *Shell) void { const g = s.gui orelse return; @@ -3989,7 +4430,9 @@ const Shell = struct { s.gui = null; s.presented = false; s.surface = null; - s.core.unattended = true; + // Its clients look at it still (Peers keeps it attended). + s.peers.alone_unattended = true; + s.core.unattended = s.peers.count() == 0; daemon.setState(true); } @@ -4001,6 +4444,7 @@ const Shell = struct { } s.gui = g; s.parked = null; + s.peers.alone_unattended = false; s.core.unattended = false; s.core.needs_frame = true; resetScroll(g); @@ -4051,6 +4495,9 @@ const Shell = struct { }; s.drainQueue(); core.settle(); + // Its replica clients told, their views gone before the dump: each + // dials the session again once it is back. + s.peers.refuseAll(core, "the session is upgrading to another build of pardes"); var rec: upgrade.Record = .{ .link = daemon.link, .window = s.gui != null, .exe = path }; for (s.ptys, 0..) |slot, id| if (slot) |pt| if (pt.fd >= 0) rec.addPty(id, pt.pid, pt.fd); var at_buf: [1024:0]u8 = undefined; @@ -4100,6 +4547,7 @@ const Shell = struct { for (0..pardes.views.max) |i| { const k: u8 = @intCast(i); if (k != live and pardes.views.isOpen(s.core, k)) s.openAnotherWindow(k); + s.windowed |= @as(u8, 1) << @intCast(live); } s.core.toView(live); s.follow(); @@ -4200,6 +4648,7 @@ const Shell = struct { defer s.takeExits(); s.queue.takeInto(&s.batch); const msgs = &s.batch; + if (msgs.len > 0) s.mail_only = false; var check_files = false; for (msgs.slice()) |m| switch (m) { .output => |o| { @@ -4311,6 +4760,9 @@ fn waitInput(ctx: ?*anyopaque, timeout_ms: u32) void { const core = s.core; var in: Input = .{ .core = core, .shell = s }; s.follow(); + s.mail_only = true; + s.took_input = false; + defer s.waited = true; if (s.gui) |g| { var sev = std.mem.zeroes(c.SDL_Event); // Idle is asleep until an event: SDL's own, and the user events the @@ -4372,9 +4824,13 @@ fn waitInput(ctx: ?*anyopaque, timeout_ms: u32) void { ms = 0; } g.input_seen = false; + // An input held from the last wait (`split`) is this one's, at once. + const held = s.held; + s.held = null; + if (held) |h| sev = h; // The wait is the 9P connections' turn with the core. pardes.turn.rest(); - const got = c.SDL_WaitEventTimeout(&sev, ms); + const got = held != null or c.SDL_WaitEventTimeout(&sev, ms); pardes.turn.wake(); // A virtual clock: while a render-time animation moves, each loop // is a presented frame and moves it by one display frame @@ -4402,6 +4858,7 @@ fn waitInput(ctx: ?*anyopaque, timeout_ms: u32) void { // each would repeat hover and selection work the next undoes. var motion: ?c.SDL_Event = null; while (true) { + if (s.split(&sev)) break; if (sev.type == c.SDL_EVENT_MOUSE_MOTION and (motion == null or motion.?.motion.windowID == sev.motion.windowID)) { motion = sev; } else { @@ -4440,17 +4897,20 @@ fn waitInput(ctx: ?*anyopaque, timeout_ms: u32) void { // 1.9 ms spinning against 7-8 ms asleep (docs/next-anim.md). // ponytail: a core while something moves (~250 ms a scroll); a // sleep to a millisecond short of the tick if the power matters more. - while (paced and !g.input_seen) { + while (paced and !g.input_seen and s.held == null) { if (tick -| c.SDL_GetTicksNS() < 50 * std.time.ns_per_us) break; pardes.turn.rest(); const more = c.SDL_PollEvent(&sev); pardes.turn.wake(); if (more) { - s.route(&sev); - dispatch(g, &in, &sev); - while (c.SDL_PollEvent(&sev)) { + if (!s.split(&sev)) { s.route(&sev); dispatch(g, &in, &sev); + while (c.SDL_PollEvent(&sev)) { + if (s.split(&sev)) break; + s.route(&sev); + dispatch(g, &in, &sev); + } } } else { // The events asked for every 100 µs, the core busy between. @@ -4510,6 +4970,16 @@ fn pollFrame(ctx: ?*anyopaque) void { } return; }; + // A replica client's view live: the window's own view back before what + // the window does to it (its size, its scroll, its font). + if (core.view != s.gview) { + const geom = windowCells(g); + const own = if (core.parked[s.gview]) |slot| &slot.view else null; + const due = g.scroll_pane != null or g.scroll_notch != 0 or g.glide.moving() or + core.settings.font.tagline_percent != g.tagline_percent or core.settings.font.pending or + (own != null and resizeOf(own.?, geom.cols, geom.rows, g.cell_w, g.cell_h, g.tagline_width, g.tagline_height) != null); + if (due) _ = s.windowView(); + } syncWindowOpacity(g, core); core.frames.period_ns = refreshNs(g); syncTaglineFont(g, core); @@ -4680,16 +5150,8 @@ fn refreshNs(g: *const Gui) u64 { } fn finishWindowOpacity(core: *pardes.Pardes, applied: *u8, failure: ?[]const u8) void { - core.settings.window_opacity_pending = false; - if (failure) |reason| { - // Do not claim a value the compositor refused; an explicit retry of - // the same command will arm a new request. - core.settings.window_opacity = applied.*; - var buf: [256]u8 = undefined; - core.setMessage(core.active, std.fmt.bufPrint(&buf, "WindowOpacity: {s}", .{reason[0..@min(reason.len, 240)]}) catch "WindowOpacity: compositor rejected the request"); - } else { - applied.* = core.settings.window_opacity; - } + core.windowOpacityDone(applied.*, failure); + applied.* = core.settings.window_opacity; } fn syncWindowOpacity(g: *Gui, core: *pardes.Pardes) void { @@ -4758,7 +5220,9 @@ fn present(ctx: ?*anyopaque, surface: *const pardes.Surface) void { g.scene_failures +|= 1; log.err("scene target unavailable (attempt {d}/3)", .{g.scene_failures}); if (g.scene_failures >= 3) { - core.disableSceneEffects(); + // ponytail: a client's window keeps asking (its core is the + // session's to change). + if (s.remote == null) core.disableSceneEffects(); g.scene_failures = 0; } } else if (scene_requested and s.presented) g.scene_failures = 0; @@ -4772,12 +5236,20 @@ fn postPresent(ctx: ?*anyopaque) void { // the pump advances it all the same. if (!s.presented) return; const frame = s.surface orelse return; - refreshPresentedPointer(g, s.core); + // A client's view live: the window's frame is acknowledged when its + // own view is live and drawn. + if (s.core.view != s.gview) return; + var in: Input = .{ .core = s.core }; + refreshPresentedPointer(g, &in); s.core.acknowledgePanelPresentation(frame.panelTracks()); } fn guiNow(ctx: ?*anyopaque) u64 { const s = shellOf(ctx); + if (s.waited) { + s.waited = false; + if (s.mail_only and s.peers.count() > 0 and s.core.clock_started) return s.core.now_ns; + } return s.test_clock orelse s.paced_ns orelse c.SDL_GetTicksNS(); } @@ -4871,7 +5343,8 @@ fn takeShell(s: *Shell, pane: u8, a: Adoption) void { /// The daemon's thread: what it says, onto the queue (drainQueue). fn deliverNote(ctx: *anyopaque, note: daemon.Note) void { - const q: *Queue = @ptrCast(@alignCast(ctx)); + const s: *Shell = @ptrCast(@alignCast(ctx)); + const q = s.queue; switch (note) { .attach => |a| { // A terminal for a window session: the daemon refuses that kind @@ -4884,9 +5357,8 @@ fn deliverNote(ctx: *anyopaque, note: daemon.Note) void { 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 } }); }, - // ponytail: a window session serves no replica yet; a terminal's - // does (tty.zig). - .replica => |fd| daemon.refuseReplica(fd, "a window session takes no replica yet: run the session in a terminal, or --detach"), + // Joined at the next step boundary (Peers, any thread). + .replica => |fd| s.peers.handed(fd), } } @@ -7974,8 +8446,14 @@ fn syncLigatures(g: *Gui, core: *pardes.Pardes) void { } fn syncTaglineFont(g: *Gui, core: *pardes.Pardes) void { - const percent = core.settings.font.tagline_percent; - if (percent == g.tagline_percent) return; + if (!fitTaglineFont(g, core.settings.font.tagline_percent)) return; + const geom = windowCells(g); + _ = updateCoreResize(core, geom.cols, geom.rows, g.cell_w, g.cell_h, g.tagline_width, g.tagline_height); +} + +/// The tagline's face at `percent` of the body's: whether it changed. +fn fitTaglineFont(g: *Gui, percent: u8) bool { + if (percent == g.tagline_percent) return false; g.tagline_percent = percent; const tagline = taglineRaster(g.font, g.px, g.cell_w, g.cell_h, percent); g.tagline_px = tagline.px; @@ -7983,8 +8461,7 @@ fn syncTaglineFont(g: *Gui, core: *pardes.Pardes) void { g.tagline_baseline = tagline.baseline; g.tagline_height = tagline.height; resetGlyphAtlas(g); - const geom = windowCells(g); - _ = updateCoreResize(core, geom.cols, geom.rows, g.cell_w, g.cell_h, g.tagline_width, g.tagline_height); + return true; } /// What text draws, so a frame does not work it out again. `cells` is the diff --git a/src/main.zig b/src/main.zig index d4edc74d..ada5f3b9 100644 --- a/src/main.zig +++ b/src/main.zig @@ -109,7 +109,8 @@ const help_text = \\ --attach= ...the session called (its --9p or \\ --detach name, else its pid) \\ --attach=: a client of session on another machine, - \\ over `ssh -L` to its pardes-replica.sock + \\ a terminal's or a window's (either kind's + \\ session), over `ssh -L` to its pardes-replica.sock \\ ($PARDES_SSH: the ssh command, words, default \\ `ssh`; and \\ $PARDES_REMOTE_RUNTIME: its runtime directory, @@ -802,7 +803,6 @@ fn nativeMain(std_init: std.process.Init) !void { opts.store_path = storePath(init.io, arena, init.environ_map); if (found.dir) |d| @import("crash.zig").setDir(d); if (attach) |name| if (std.mem.lastIndexOfScalar(u8, name, ':')) |colon| { - if (comptime pardes.platform != .tty) badArgs(init.io, "a window is no replica client yet: run `pardes --attach={s}` in a terminal", .{name}); remoteAttach(init, opts, name[0..colon], name[colon + 1 ..]); }; if (attach) |name| if (!resuming) attachTo(init.io, name); @@ -981,12 +981,23 @@ fn commOf(pid: []const u8, buf: *[64]u8) []const u8 { return std.mem.trimEnd(u8, buf[0..@intCast(got)], "\n"); } -/// `pardes --attach=:`: a replica client (tty.zig `remote`), -/// through the socket `where` names, or through `ssh -L` of host `where`'s -/// replica socket to one of this process's. +/// The replica client of this build's frontend: a terminal's (tty.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 { + switch (pardes.platform) { + .tty => try @import("tty/tty.zig").remote(init, opts, path, name, far), + .gui => try @import("gui/gui.zig").remote(init, opts, path, name, far), + else => unreachable, + } +} + +/// `pardes --attach=:` (`pardes-gui` too): a replica client +/// (tty.zig and gui.zig `remote`), through the socket `where` names, or +/// through `ssh -L` of host `where`'s replica socket to one of this +/// process's. fn remoteAttach(init: std.process.Init, opts: pardes.Options, where: []const u8, name: []const u8) noreturn { const io = init.io; - if (comptime pardes.platform != .tty) unreachable; + if (comptime pardes.platform != .tty and pardes.platform != .gui) unreachable; const Say = struct { fn no(o: std.Io, comptime fmt: []const u8, args: anytype) noreturn { var buf: [700]u8 = undefined; @@ -995,7 +1006,7 @@ fn remoteAttach(init: std.process.Init, opts: pardes.Options, where: []const u8, } }; if (std.mem.indexOfScalar(u8, where, '/') != null) { - @import("tty/tty.zig").remote(init, opts, where, name, false) catch |err| Say.no(io, "{t}", .{err}); + clientOf(init, opts, where, name, false) catch |err| Say.no(io, "{t}", .{err}); std.process.exit(0); } // ssh -L : , until the socket here answers. @@ -1066,7 +1077,7 @@ fn remoteAttach(init: std.process.Init, opts: pardes.Options, where: []const u8, const ts: std.c.timespec = .{ .sec = 0, .nsec = 10 * std.time.ns_per_ms }; _ = std.c.nanosleep(&ts, null); } - @import("tty/tty.zig").remote(init, opts, here, name, true) catch |err| { + clientOf(init, opts, here, name, true) catch |err| { Ssh.end(); Say.no(io, "{t}", .{err}); }; diff --git a/src/ninep/ctl.zig b/src/ninep/ctl.zig index 1b9d73f5..2859304a 100644 --- a/src/ninep/ctl.zig +++ b/src/ninep/ctl.zig @@ -524,10 +524,12 @@ fn checkBuiltin(p: *Pardes, req: Req, line: []const u8, scope: builtins.Scope) ? break now; } else typed; const arg = if (sp) |s| std.mem.trim(u8, line[s + 1 ..], " \t") else ""; - const b = std.meta.stringToEnum(Builtin, word) orelse { + const here = if (std.meta.stringToEnum(Builtin, word)) |b| builtins.registry.here(p, b) else false; + const b = (if (here) std.meta.stringToEnum(Builtin, word) else null) orelse { // A setting this build's frontend cannot show (Lift, GripWidth on a - // terminal) is known, and says so rather than sound misspelt. - if (builtins.absentWhy(word) orelse if (config.Runtime.find(word) != null) @as([]const u8, "GUI-only") else null) |absent| { + // terminal, the window's own words in a terminal's view) is known, + // and says so rather than sound misspelt. + if (builtins.absentWhy(word) orelse if (config.Runtime.find(word) != null or std.meta.stringToEnum(Builtin, word) != null) @as([]const u8, "GUI-only") else null) |absent| { var why: [64]u8 = undefined; // EINVAL, a request this build cannot take, in words 9ns reads // as that: `invalid`. @@ -618,18 +620,24 @@ const e_prompt = "control message needs its argument"; /// What is not a setting -- platform, themes, where the config came from -- /// is /status's or the DumpConfig window's. fn writeSettings(p: *Pardes, w: *std.Io.Writer) !void { - try writeSettingsOf(p, &p.settings, w); + try writeSettingsFor(p, &p.settings, w, builtins.viewCapabilities(p)); try w.writeAll("LocationsConfig "); try p.locations_config.write(w); try w.writeByte('\n'); - if (comptime builtins.Pet.enabled) try w.print("Pet {s}\n", .{@tagName(p.settings.pet)}); + if (comptime builtins.Pet.enabled) if (builtins.registry.here(p, .Pet)) try w.print("Pet {s}\n", .{@tagName(p.settings.pet)}); } /// The setting words of `s`, one a line, as the root ctl reads them; a Dump /// keeps those that differ from a fresh session's (dump.zig). pub fn writeSettingsOf(p: *Pardes, s: *const config.Runtime, w: *std.Io.Writer) !void { - inline for (config.Runtime.settings) |setting| { + return writeSettingsFor(p, s, w, builtins.capabilities); +} + +/// ...those a frontend of `caps` takes (the root ctl's: the live view's). +fn writeSettingsFor(p: *Pardes, s: *const config.Runtime, w: *std.Io.Writer, caps: config.Runtime.Capabilities) !void { + inline for (config.Runtime.settings) |setting| skip: { if (comptime !setting.enabled(builtins.capabilities)) continue; + if (!setting.enabled(caps)) break :skip; const word = setting.word; switch (setting.action) { .toggle => |field| try w.print("{s} {s}\n", .{ word, if (@field(s, @tagName(field))) "on" else "off" }), @@ -909,8 +917,10 @@ fn stripCitations(text: []u8) []u8 { return text[0..out]; } -fn writeCommands(w: *std.Io.Writer) !void { +fn writeCommands(p: *const Pardes, w: *std.Io.Writer) !void { for (std.enums.values(Builtin)) |b| { + // A window's own word is none in a terminal's view. + if (!builtins.registry.here(p, b)) continue; // Edit is a pane's word the root's ctl takes too, at the active pane. const scope: []const u8 = if (b == .Edit) "both" else if (builtins.registry.scope(b) == .session) "root" else "pane"; try w.print("{s}{s} {s}", .{ @@ -938,16 +948,16 @@ fn writeCommands(w: *std.Io.Writer) !void { } } -pub fn commandsLen() u64 { +pub fn commandsLen(p: *const Pardes) u64 { var buf: [256]u8 = undefined; var counting: std.Io.Writer.Discarding = .init(&buf); - writeCommands(&counting.writer) catch return 0; + writeCommands(p, &counting.writer) catch return 0; return counting.fullCount(); } pub fn readCommands(p: *Pardes, req: Req) Reply { var text: std.Io.Writer.Allocating = .init(p.scratch.allocator()); - writeCommands(&text.writer) catch return Reply.fail(req.tag, E.NOMEM); + writeCommands(p, &text.writer) catch return Reply.fail(req.tag, E.NOMEM); p.fs.stage(p.gpa).appendSlice(p.gpa, text.written()) catch return Reply.fail(req.tag, E.NOMEM); return tree.stagedReply(p, req); } @@ -1362,7 +1372,9 @@ test "commands lists every builtin with its argument and the ctl that takes it" // Then, where the source has one, ` -- ` and what it does. if (words.next()) |dashes| try testing.expectEqualStrings("--", dashes); } - try testing.expectEqual(std.enums.values(Builtin).len, lines); + var here: usize = 0; + for (std.enums.values(Builtin)) |b| here += @intFromBool(builtins.registry.here(p, b)); + try testing.expectEqual(here, lines); for ([_][]const u8{ "\nDel arg pane -- ", "\nNewcol root -- ", "\nSave arg pane", "\nVerbose arg root on,off", "\nPlacement arg root acme,pardes", "\nUndo pane -- ", "\nEdit arg both -- acme's Edit" }) |row| try testing.expect(std.mem.indexOf(u8, listed.bytes, row) != null); } @@ -1738,6 +1750,8 @@ test "status reads the editor, and look and exec validate whole batches" { const gpa = testing.allocator; const p = try withFile(gpa, "Msg root\n"); defer p.deinit(); + // A terminal's view first (a window's build starts windowed). + p.windowed = false; const status = rd(p, root_status, 0, 4096); try testing.expectEqual(Status.ok, status.reply.status); var lines = std.mem.tokenizeScalar(u8, status.bytes, '\n'); @@ -2855,7 +2869,7 @@ test "a setting this frontend cannot show says GUI-only, and DumpDir reads back const p = try withFile(testing.allocator, "x\n"); defer p.deinit(); const root_ctl = @backingInt(tree.TopFile.ctl); - if (!builtins.capabilities.lift) { + if (!builtins.viewCapabilities(p).lift) { try testing.expectEqualStrings("Lift is GUI-only, invalid here \"Lift\"", wr(p, root_ctl, "Lift on\n").reply.ename); try testing.expectEqualStrings("GripWidth is GUI-only, invalid here \"GripWidth\"", wr(p, root_ctl, "GripWidth 120\n").reply.ename); // A builtin the GUI alone has, written to a ctl or an exec, never diff --git a/src/ninep/tree.zig b/src/ninep/tree.zig index bda2c1d1..bd87f5bc 100644 --- a/src/ninep/tree.zig +++ b/src/ninep/tree.zig @@ -678,7 +678,7 @@ fn topSize(p: *Pardes, f: TopFile) u64 { // one (a 9ns mount's splice), and a follower's reads go past it. .log => 0, .ctl => ctl.rootLen(p), - .commands => ctl.commandsLen(), + .commands => ctl.commandsLen(p), .focus => focus: { if (p.header_focus) break :focus 0; const pn = p.panes[p.active] orelse break :focus 0; diff --git a/src/pardes.zig b/src/pardes.zig index 2b1fae61..d7f35ed9 100644 --- a/src/pardes.zig +++ b/src/pardes.zig @@ -2868,7 +2868,9 @@ test "Pet command is SDL-only optional and validates its argument" { defer p.deinit(); try std.testing.expectEqual(.off, p.settings.pet); if (comptime platform != .gui) { - try std.testing.expect(std.meta.stringToEnum(builtins.registry.Builtin(), "Pet") == null); + // A terminal's view has the word and takes it not. + try std.testing.expect(p.executeBuiltinLine(p.active, "Pet cat")); + try std.testing.expectEqual(.off, p.settings.pet); return; } try std.testing.expect(p.executeBuiltinLine(p.active, "Pet cat")); @@ -3717,9 +3719,16 @@ pub const Event = union(enum) { /// How the host's handover `seq` went (Handover.finish): taken by `to`, /// or `failure` says why not. Borrowed for the step. handed: struct { seq: u32, to: []const u8 = "", failure: ?[]const u8 = null }, + /// The live view's frontend, which its replica client says first + /// (docs/next-daemon.md, "Phase 6: GUI replica notes"): a window, which + /// draws pictures itself and takes the GUI's own words, or a terminal. + frontend: Frontend, tick, }; +/// A view's frontend: what a client of a session elsewhere says it is. +pub const Frontend = struct { windowed: bool, native_images: bool = false, native_image_patches: bool = false }; + pub const PendingWrite = struct { bytes: []u8, off: usize = 0 }; /// `command` is Kill's: SIGTERM to the terminal's foreground job, and never @@ -4550,7 +4559,10 @@ pub const Pardes = struct { /// A pixel shell's window, which hears the pointer leave it: only then /// does /status say whether the pointer is over it (a terminal's mouse /// reports never say it left, so a tty would claim it for ever). - windowed: bool = false, + /// The live view's frontend is a window (Event.frontend): what it draws, + /// and the words it takes (builtins.zig `here`). A window's build + /// starts so, a terminal's not. + windowed: bool = platform == .gui, /// The last plain B1 click, for acme's double-click (text.c:881, /// textselect: a second click at the same point within 500 ms). last_click: ?struct { id: usize, on_tag: bool, row: i32, col: i32, ms: i64 } = null, @@ -5526,6 +5538,8 @@ pub const Pardes = struct { pub fn takeFontRequest(p: *Pardes) ?[]const u8 { if (comptime !font_picker) return null; + const taped = tape.enter(p, .take_font_request); + defer tape.leave(p, taped); if (!p.settings.font.pending or p.font_request_taken) return null; const path = p.settings.font.requested_path.get(); if (path.len == 0) return null; @@ -5540,6 +5554,8 @@ pub const Pardes = struct { unit: config.Runtime.FontSizeUnit, ) bool { if (comptime !font_picker) return false; + const taped = tape.enter(p, .{ .observe_font = .{ .name = effective_name, .size = effective_size_hundredths, .unit = unit } }); + defer tape.leave(p, taped); if (!p.settings.font.effective_name.set(effective_name)) return false; p.settings.font.effective_size_hundredths = effective_size_hundredths; p.settings.font.effective_size_unit = unit; @@ -5555,6 +5571,8 @@ pub const Pardes = struct { unit: config.Runtime.FontSizeUnit, ) bool { if (comptime !font_picker) return false; + const taped = tape.enter(p, .{ .acknowledge_font = .{ .name = effective_name, .size = effective_size_hundredths, .unit = unit } }); + defer tape.leave(p, taped); if (!p.settings.font.pending or !p.font_request_taken) return false; const changed = !std.mem.eql( u8, @@ -5571,6 +5589,8 @@ pub const Pardes = struct { pub fn rejectFont(p: *Pardes) void { if (comptime !font_picker) return; + const taped = tape.enter(p, .reject_font); + defer tape.leave(p, taped); if (!p.settings.font.pending or !p.font_request_taken) return; p.settings.font.pending = false; p.font_request_taken = false; @@ -6346,6 +6366,11 @@ pub const Pardes = struct { if (focused) if (p.host.vtable.newer_build) |f| if (f(p.host.ctx)) p.setMessage(p.active, newer_build_words); }, .handed => |h| p.handover.finish(p, h.seq, h.to, h.failure), + .frontend => |f| { + p.windowed = f.windowed; + p.native_images = f.native_images; + p.native_image_patches = f.native_image_patches; + }, .pointer_leave => { p.pointer_inside = false; p.pointer_body_hit = null; @@ -6818,11 +6843,14 @@ pub const Pardes = struct { p.leader_on = true; }; // a path-less builtin is a row here too (it is the same index Help - // reads), and SPC cannot reach one — so both scans skip it + // reads), and SPC cannot reach one — so both scans skip it; and a + // window's own word is no path in a terminal's view for (builtin_rows) |row| { + if (!builtins.registry.here(p, row.cmd)) continue; if (std.mem.eql(u8, row.path orelse continue, pfx)) return exec.runBuiltin(p, row.cmd, p.active, "", null); } for (builtin_rows) |row| { + if (!builtins.registry.here(p, row.cmd)) continue; if (std.mem.startsWith(u8, row.path orelse continue, pfx)) { p.leader_on = true; return; @@ -7398,9 +7426,25 @@ pub const Pardes = struct { /// A native post pass proved unavailable: the chain is emptied, which /// DumpConfig then reports. pub fn disableSceneEffects(p: *Pardes) void { + const taped = tape.enter(p, .disable_scene_effects); + defer tape.leave(p, taped); p.settings.post.clear(); } + /// The window's answer to a WindowOpacity: done, or `failure` says why + /// not, `applied` the opacity it keeps. + pub fn windowOpacityDone(p: *Pardes, applied: u8, failure: ?[]const u8) void { + const taped = tape.enter(p, .{ .window_opacity_done = .{ .applied = applied, .failure = failure } }); + defer tape.leave(p, taped); + p.settings.window_opacity_pending = false; + const reason = failure orelse return; + // Do not claim a value the compositor refused; an explicit retry of + // the same command will arm a new request. + p.settings.window_opacity = applied; + var buf: [256]u8 = undefined; + p.setMessage(p.active, std.fmt.bufPrint(&buf, "WindowOpacity: {s}", .{reason[0..@min(reason.len, 240)]}) catch "WindowOpacity: compositor rejected the request"); + } + // ---- doc panes ---- pub fn openTutorView(p: *Pardes, id: usize) !*Pane { diff --git a/src/replica.zig b/src/replica.zig index 9d12de70..32fd4fbe 100644 --- a/src/replica.zig +++ b/src/replica.zig @@ -910,6 +910,16 @@ pub const Replica = struct { pardes.views.drawOne(r.core(), r.view, present) catch {}; } + /// `f(ctx, core)` with its own view live, outside any step, as `draw` + /// draws it (views.within): what its frontend reads of its own view + /// (its pointer's cells, its size) while another client's input was the + /// session's last. + pub fn within(r: *Replica, ctx: anytype, comptime f: fn (@TypeOf(ctx), *Pardes) anyerror!void) void { + rollback.Epoch.select(&r.epoch); + defer rollback.Epoch.select(null); + pardes.views.within(r.core(), r.view, ctx, f) catch {}; + } + /// One of the authority's terminal messages (`Screens.flush`, or an /// answer to `screenRequests`), taken between units in stream order: a /// delta written into its pane's emulator, or fetched rows. The @@ -2486,6 +2496,306 @@ pub fn readStream(gpa: Allocator, fd: c_int, rest: *Framer, ctx: anytype, compti rest.run(gpa, fd, ctx, take); } +/// 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 }; + +/// 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 +/// it did not is freed here). +pub fn readLink(gpa: Allocator, fd: c_int, rest: *Framer, ctx: anytype, comptime post: fn (@TypeOf(ctx), Said) bool) void { + const Take = struct { + fn take(x: @TypeOf(ctx), tag: u8, payload: []const u8) bool { + const t = std.enums.fromInt(wire.ServerTag, tag) orelse return false; + const msg: Said = switch (t) { + .unit => .{ .unit = std.heap.c_allocator.dupe(u8, payload) catch return false }, + .screen => .{ .screen = 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 }, + .pong, .welcome, .dump, .blobs, .zstd => return true, + }; + if (!post(x, msg)) switch (msg) { + .unit, .screen, .refused => |b| std.heap.c_allocator.free(b), + .checked => {}, + }; + return msg != .refused; + } + }; + rest.run(gpa, fd, ctx, Take.take); +} + +/// A replica client's link to its session, the terminal's (tty.zig +/// `remote`) and the window's (gui.zig `remote`): its replica, its socket, +/// what the session said, and what it checks. Drawing is the frontend's. +pub const Link = struct { + r: *Replica, + fd: c_int, + quit: bool = false, + /// The session hung up. + gone: bool = false, + /// Something to draw: an input applied, a unit taken. + dirty: bool = true, + /// The last frame was held for the frontend's answer (a terminal's + /// FrameAck, a window's skipped image). + owed: bool = false, + /// PARDES_REPLICA_CHECK=: once quiet a while after a change, the + /// session's digest is asked, and whether this replica's agrees is + /// written there, a line a check. + check: ?[:0]const u8 = null, + changed: bool = false, + asked: bool = false, + /// When its own last input was, and its last check asked (`quietCheck` + /// waits a while after each). + input_ns: u64 = 0, + asked_ns: u64 = 0, + /// How many of its own inputs the session recorded otherwise when it + /// last drew: a frame after one that draws something is a rollback that + /// may have been seen (counted so: an upper bound, the frame shows the + /// inputs after it too). + mispredicted: u32 = 0, + visible: u32 = 0, + /// What the session said as it let this client go (the C heap's). + refused: ?[]u8 = null, + /// 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, + notice_len: usize = 0, + /// PARDES_TEST_DIVERGE=: once quiet after its n-th unit, its core + /// is put off the session's (a digested counter moved), the next unit's + /// digest finds it, and it joins again (test/daemon.py). + test_diverge: u32 = 0, + /// Put off so in this join: its checks are not written (they differ). + put_off: bool = false, + /// How its last join went (Joined's counts), and how long its dial and + /// load took (PARDES_REPLICA_STATS). + join: struct { blobs: u32 = 0, from_memory: u32 = 0, from_disk: u32 = 0, sent_bytes: u64 = 0 } = .{}, + join_ms: u64 = 0, + + pub const upgrade_words = "session upgraded to a newer pardes: upgrade this client too"; + + /// The replica the dial's dump makes, checked against the session as + /// it was dumped; null, and why in `why`. The dump is let go, a far + /// join's to the thread that keeps the blobs it was sent (`Have.store`). + pub fn load(gpa: Allocator, joined: *Joined, o: pardes.Options, why: []u8, have: ?*Have) ?*Replica { + defer { + if (have) |h| h.store(gpa, joined) else gpa.free(joined.dump); + joined.dump = &.{}; + } + const r = Replica.initDump(gpa, joined.client, joined.view, joined.dump, o) catch |err| { + _ = std.fmt.bufPrint(why, "the session's dump would not load: {t}\x00", .{err}) catch {}; + return null; + }; + // PARDES_NO_ECHO: no predicted echo (the gates' baseline). + if (std.c.getenv("PARDES_NO_ECHO") != null) r.echo.on = false; + if (!r.loaded(joined.digest)) { + r.deinit(); + _ = std.fmt.bufPrint(why, "the session's dump loaded as another session (a build's dump is not complete)\x00", .{}) catch {}; + return null; + } + return r; + } + + /// The test knobs the environment sets (PARDES_REPLICA_CHECK, + /// PARDES_TEST_DIVERGE). + pub fn fromEnv(c: *Link, gpa: Allocator, env: *const std.process.Environ.Map) !void { + if (env.get("PARDES_REPLICA_CHECK")) |file| c.check = try gpa.dupeSentinel(u8, file, 0); + if (env.get("PARDES_TEST_DIVERGE")) |n| c.test_diverge = std.fmt.parseInt(u32, n, 10) catch 0; + } + + pub fn deinit(c: *Link, gpa: Allocator) void { + if (c.check) |file| gpa.free(file); + if (c.refused) |words| std.heap.c_allocator.free(words); + } + + /// How its join went, its dial and load `ms`. + pub fn joinedAs(c: *Link, j: *const Joined, ms: u64) void { + c.join = .{ .blobs = j.blobs, .from_memory = j.from_memory, .from_disk = j.from_disk, .sent_bytes = j.sent_bytes }; + c.join_ms = ms; + } + + /// A join's link, from its start. + pub fn reset(c: *Link, r: *Replica, fd: c_int) void { + c.r = r; + c.fd = fd; + c.quit = false; + c.gone = false; + c.dirty = true; + c.owed = false; + c.changed = false; + c.asked = false; + c.mispredicted = 0; + c.put_off = false; + } + + pub fn notify(c: *Link, comptime fmt: []const u8, args: anytype) void { + const text = std.fmt.bufPrint(&c.notice_buf, fmt, args) catch c.notice_buf[0..]; + for (text) |*b| if (b.* < 0x20 or b.* > 0x7e) { + b.* = '?'; + }; + c.notice_len = text.len; + } + + pub fn notice(c: *const Link) []const u8 { + return c.notice_buf[0..c.notice_len]; + } + + /// The frontend's input: applied at once, and sent to the session. + pub fn input(c: *Link, ev: pardes.Event) void { + // Its notice read: a key of its own puts it away. + if (c.notice_len > 0 and (ev == .key or ev == .paste)) c.notice_len = 0; + c.input_ns = nowNs(); + const msg = c.r.input(ev) catch return; + if (!sendInput(c.fd, msg)) c.quit = true; + c.dirty = true; + } + + /// What the session streamed, in its order; the bytes are let go. + pub fn take(c: *Link, msg: Said) void { + switch (msg) { + .unit => |bytes| { + defer std.heap.c_allocator.free(bytes); + c.r.confirm(bytes); + if (c.test_diverge != 0 and c.r.stats.units >= c.test_diverge and c.r.quiet()) { + c.test_diverge = 0; + c.put_off = true; + c.r.core().next_serial +%= 1000; + } + if (c.r.moved) c.dirty = true; + c.r.moved = false; + c.changed = true; + }, + .screen => |bytes| { + defer std.heap.c_allocator.free(bytes); + if (c.r.screen(bytes)) |reply| if (!sendScreen(c.fd, reply)) { + c.quit = true; + }; + c.dirty = true; + }, + .checked => |d| c.checked(d), + .refused => |words| { + if (c.refused) |old| std.heap.c_allocator.free(old); + c.refused = words; + c.quit = true; + }, + } + if (c.r.diverged != null) c.quit = true; + } + + /// Its own view drawn, by the frontend (`drew` is whether anything was + /// written to it): a rollback it may have shown counted, and the + /// history rows it shows and does not hold (a scroll back) asked for, + /// blank until they come. + pub fn drawn(c: *Link, drew: bool) void { + if (c.r.stats.mispredicted > c.mispredicted) { + c.mispredicted = c.r.stats.mispredicted; + if (drew) c.visible += 1; + } + c.dirty = false; + while (c.r.screenRequest()) |req| if (!sendScreen(c.fd, req)) { + c.quit = true; + break; + }; + } + + /// Each pass of the frontend's loop: quiet (nothing of its own + /// pending) 300 ms after its last input and its last check, and + /// changed since, the session's digest is asked once, answered in + /// stream order after the units before it (a session that pumps on, a + /// window's test feed, sends a unit a frame; the check's own wakes it + /// once). The wake it wants, ms. + pub fn quietCheck(c: *Link) ?u32 { + if (c.check == null or !c.changed or c.asked or !c.r.quiet()) return null; + const quiet_ns = 300 * std.time.ns_per_ms; + const since = nowNs() -| @max(c.input_ns, c.asked_ns); + if (since < quiet_ns) return @intCast((quiet_ns - since) / std.time.ns_per_ms + 1); + c.changed = false; + c.asked = askCheck(c.fd); + c.asked_ns = nowNs(); + return null; + } + + /// The session's digest against this replica's, if it is quiet still. + fn checked(c: *Link, theirs: u64) void { + c.asked = false; + const path = c.check orelse return; + if (!c.r.quiet() or c.put_off) return; + const mine = c.r.digest(); + var buf: [96]u8 = undefined; + const line = (if (mine == theirs) std.fmt.bufPrint(&buf, "agree {x:0>16}\n", .{mine}) else std.fmt.bufPrint(&buf, "differ {x:0>16} {x:0>16}\n", .{ mine, theirs })) catch return; + appendTo(path, line); + } + + /// PARDES_REPLICA_STATS=: how its inputs and the session's units + /// went, a line at its end (test/daemon.py, the gates). + pub fn writeStats(c: *Link, path: []const u8) void { + const st = &c.r.stats; + var buf: [600]u8 = undefined; + const e = &c.r.echo.stats; + const line = std.fmt.bufPrint(&buf, "inputs {d} at_once {d} stopped {d} units {d} fast {d} neutral {d} mispredicted {d} foreign {d} visible {d} rtt_us {d} spec_us {d}/{d} copy_us {d}/{d} rollback_us {d}/{d} join_ms {d} blobs {d} from_memory {d} from_disk {d} sent_kb {d} echo {d}/{d} confirmed {d} missed {d}\n", .{ + st.inputs, st.speculated, st.stopped, st.units, st.fast, + c.r.neutral, st.mispredicted, st.foreign, c.visible, c.r.rtt_ns / 1000, + pctOf(st.spec_ns.items, 50) / 1000, pctOf(st.spec_ns.items, 99) / 1000, pctOf(st.copy_ns.items, 50) / 1000, pctOf(st.copy_ns.items, 99) / 1000, pctOf(st.rollback_ns.items, 50) / 1000, + pctOf(st.rollback_ns.items, 99) / 1000, c.join_ms, c.join.blobs, c.join.from_memory, c.join.from_disk, + c.join.sent_bytes >> 10, e.predicted, e.predicted + e.unpredicted, e.confirmed, e.mispredicted, + }) catch return; + var z: [4096]u8 = undefined; + appendTo(std.fmt.bufPrintSentinel(&z, "{s}", .{path}, 0) catch return, line); + } + + /// The link ended: whether the client joins again, and why in its + /// notice (it diverged, or the session let it go to upgrade). + pub fn rejoins(c: *Link) bool { + if (c.r.diverged) |reason| { + c.notify("joined again: this client diverged from the session ({s})", .{reason}); + return true; + } + if (c.refused) |words| { + c.notify("joined again: {s}", .{words}); + std.heap.c_allocator.free(words); + c.refused = null; + return true; + } + return false; + } + + /// The session again, after a divergence or an upgrade: an upgrade's + /// takes the time its exec and load take, and its daemon's, so it is + /// dialled every 100 ms for 20 s. A far client's (`have`) holds the + /// core it leaves meanwhile (`Have.leaving`): its blobs are not sent + /// again. Null, and why in `why`. + pub fn redial(gpa: Allocator, path: []const u8, session: []const u8, why: *[600]u8, have: ?*Have) ?Joined { + var tries: u32 = 0; + while (true) : (tries += 1) { + why.* = @splat(0); + if (dial(gpa, path, session, why, have)) |j| { + if (j.semantics == wire.semantics) return j; + bye(j.fd); + _ = libc.close(j.fd); + var jj = j; + jj.rest.deinit(gpa); + gpa.free(j.dump); + _ = std.fmt.bufPrint(why, "{s}\x00", .{upgrade_words}) catch {}; + return null; + } + if (std.mem.indexOf(u8, std.mem.sliceTo(why, 0), "runs another build") != null) { + _ = std.fmt.bufPrint(why, "{s}\x00", .{upgrade_words}) catch {}; + return null; + } + if (tries > 200) return null; + const ts: libc.timespec = .{ .sec = 0, .nsec = 100 * std.time.ns_per_ms }; + _ = libc.nanosleep(&ts, null); + } + } +}; + +fn appendTo(path: [:0]const u8, line: []const u8) void { + const fd = libc.open(path, .{ .ACCMODE = .WRONLY, .CREAT = true, .APPEND = true, .CLOEXEC = true }, @as(libc.mode_t, 0o644)); + if (fd < 0) return; + _ = libc.write(fd, line.ptr, line.len); + _ = libc.close(fd); +} + pub fn digestOf(a: *Authority) u64 { const was = Stepping.begin(&a.t, null); defer was.end(); diff --git a/src/tape.zig b/src/tape.zig index f0766bd1..70a22ab0 100644 --- a/src/tape.zig +++ b/src/tape.zig @@ -61,6 +61,15 @@ pub const Input = union(enum) { open_view, close_view: u8, to_view: u8, + /// What a window says of its font and its opacity (gui.zig). + take_font_request, + observe_font: Font, + acknowledge_font: Font, + reject_font, + disable_scene_effects, + window_opacity_done: struct { applied: u8, failure: ?[]const u8 }, + + pub const Font = struct { name: []const u8, size: u16, unit: pardes.config.Runtime.FontSizeUnit }; }; /// The core's own syscalls (each `turn.yield()`s around itself), numbered @@ -544,6 +553,12 @@ pub const Tape = struct { .open_view => _ = p.openView(), .close_view => |k| p.closeView(k), .to_view => |k| p.toView(k), + .take_font_request => _ = p.takeFontRequest(), + .observe_font => |f| _ = p.observeFont(f.name, f.size, f.unit), + .acknowledge_font => |f| _ = p.acknowledgeFont(f.name, f.size, f.unit), + .reject_font => p.rejectFont(), + .disable_scene_effects => p.disableSceneEffects(), + .window_opacity_done => |w| p.windowOpacityDone(w.applied, w.failure), } t.finishInput(); } diff --git a/src/tty/tty.zig b/src/tty/tty.zig index 2007c6f7..a1a28181 100644 --- a/src/tty/tty.zig +++ b/src/tty/tty.zig @@ -156,14 +156,8 @@ pub const Command = struct { replica: posix.fd_t, /// A replica's reader posted: the step boundary takes it in. replica_mail, - /// A replica client's: what the session streamed (replica.Client). - unit: []u8, - /// ...a terminal's delta or rows, before the units after it. - screen: []u8, - /// ...why it let this client go (an Upgrade's exec), the stream's end. - refused: []u8, - /// The session's digest, asked by PARDES_REPLICA_CHECK. - checked: u64, + /// A replica client's: what the session streamed (replica.Link). + said: replica.Said, link_gone, } = .nop; }; @@ -1274,191 +1268,42 @@ pub fn run(init: std.process.Init, opts: pardes.Options, term: Term) !void { try localSession(init, opts, &screen, &loop, &paste_buf); } -/// A replica client's link to its session (`remote`). +/// A replica client's link to its session (`remote`), drawn here. const Remote = struct { - r: *replica.Replica, - fd: posix.fd_t, - quit: bool = false, - /// The session hung up. - gone: bool = false, - /// Something to draw: an input applied, a unit taken. - dirty: bool = true, - /// The last frame was held for the terminal's answer (FrameAck). - owed: bool = false, - /// PARDES_REPLICA_CHECK=: once quiet a while after a change, the - /// session's digest is asked, and whether this replica's agrees is - /// written there, a line a check. - check: ?[:0]const u8 = null, - changed: bool = false, - asked: bool = false, - /// How many of its own inputs the session recorded otherwise when it - /// last drew: a frame after one that writes to the terminal is a - /// rollback that may have been seen (counted so: an upper bound, the - /// frame shows the inputs after it too). - mispredicted: u32 = 0, - visible: u32 = 0, - /// What the session said as it let this client go (owned, the C heap's). - refused: ?[]u8 = null, - /// 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, - notice_len: usize = 0, - /// PARDES_TEST_DIVERGE=: once quiet after its n-th unit, its core - /// is put off the session's (a digested counter moved), the next unit's - /// digest finds it, and it joins again (test/daemon.py). - test_diverge: u32 = 0, - /// Put off so in this join: its checks are not written (they differ). - put_off: bool = false, - /// How its last join went (replica.Joined's counts), and how long its - /// dial and load took (PARDES_REPLICA_STATS). - join: struct { blobs: u32 = 0, from_memory: u32 = 0, from_disk: u32 = 0, sent_bytes: u64 = 0 } = .{}, - join_ms: u64 = 0, - - /// The replica the dial's dump makes, checked against the session as - /// it was dumped; null, and why in `why`. The dump is let go, a far - /// join's to the thread that keeps the blobs it was sent (`Have.store`). - fn load(gpa: std.mem.Allocator, joined: *replica.Joined, o: pardes.Options, why: []u8, have: ?*replica.Have) ?*replica.Replica { - defer { - if (have) |h| h.store(gpa, joined) else gpa.free(joined.dump); - joined.dump = &.{}; - } - const r = replica.Replica.initDump(gpa, joined.client, joined.view, joined.dump, o) catch |err| { - _ = std.fmt.bufPrint(why, "the session's dump would not load: {t}\x00", .{err}) catch {}; - return null; - }; - // PARDES_NO_ECHO: no predicted echo (the gates' baseline). - if (std.c.getenv("PARDES_NO_ECHO") != null) r.echo.on = false; - if (!r.loaded(joined.digest)) { - r.deinit(); - _ = std.fmt.bufPrint(why, "the session's dump loaded as another session (a build's dump is not complete)\x00", .{}) catch {}; - return null; - } - return r; - } - - /// A join's link, from its start. - fn reset(c: *Remote, r: *replica.Replica, fd: posix.fd_t) void { - c.r = r; - c.fd = fd; - c.quit = false; - c.gone = false; - c.dirty = true; - c.owed = false; - c.changed = false; - c.asked = false; - c.mispredicted = 0; - c.put_off = false; - } - - fn notify(c: *Remote, comptime fmt: []const u8, args: anytype) void { - const text = std.fmt.bufPrint(&c.notice_buf, fmt, args) catch c.notice_buf[0..]; - for (text) |*b| if (b.* < 0x20 or b.* > 0x7e) { - b.* = '?'; - }; - c.notice_len = text.len; - } - - /// PARDES_REPLICA_STATS=: how its inputs and the session's units - /// went, a line at its end (test/daemon.py, the gates). - fn writeStats(c: *Remote, path: []const u8) void { - const st = &c.r.stats; - var buf: [600]u8 = undefined; - const line = std.fmt.bufPrint(&buf, "inputs {d} at_once {d} stopped {d} units {d} fast {d} neutral {d} mispredicted {d} foreign {d} visible {d} rtt_us {d} spec_us {d}/{d} copy_us {d}/{d} rollback_us {d}/{d} join_ms {d} blobs {d} from_memory {d} from_disk {d} sent_kb {d}\n", .{ - st.inputs, st.speculated, st.stopped, st.units, st.fast, - c.r.neutral, st.mispredicted, st.foreign, c.visible, c.r.rtt_ns / 1000, - pct(st.spec_ns.items, 50) / 1000, pct(st.spec_ns.items, 99) / 1000, pct(st.copy_ns.items, 50) / 1000, pct(st.copy_ns.items, 99) / 1000, pct(st.rollback_ns.items, 50) / 1000, - pct(st.rollback_ns.items, 99) / 1000, c.join_ms, c.join.blobs, c.join.from_memory, c.join.from_disk, - c.join.sent_bytes >> 10, - }) catch return; - var z: [4096]u8 = undefined; - const pz = std.fmt.bufPrintSentinel(&z, "{s}", .{path}, 0) catch return; - const fd = libc.open(pz, .{ .ACCMODE = .WRONLY, .CREAT = true, .APPEND = true, .CLOEXEC = true }, @as(libc.mode_t, 0o644)); - if (fd < 0) return; - _ = libc.write(fd, line.ptr, line.len); - _ = libc.close(fd); - } - - fn pct(samples: []u64, p: usize) u64 { - if (samples.len == 0) return 0; - std.mem.sort(u64, samples, {}, std.sort.asc(u64)); - return samples[@min(samples.len - 1, samples.len * p / 100)]; - } - - /// The session's digest against this replica's, if it is quiet still. - fn checked(c: *Remote, theirs: u64) void { - c.asked = false; - const path = c.check orelse return; - if (!c.r.quiet() or c.put_off) return; - const mine = c.r.digest(); - var buf: [96]u8 = undefined; - const line = (if (mine == theirs) std.fmt.bufPrint(&buf, "agree {x:0>16}\n", .{mine}) else std.fmt.bufPrint(&buf, "differ {x:0>16} {x:0>16}\n", .{ mine, theirs })) catch return; - const fd = libc.open(path, .{ .ACCMODE = .WRONLY, .CREAT = true, .APPEND = true, .CLOEXEC = true }, @as(libc.mode_t, 0o644)); - if (fd < 0) return; - _ = libc.write(fd, line.ptr, line.len); - _ = libc.close(fd); - } + link: replica.Link, /// The client's own view drawn on its terminal, outside any step: the /// replica's digest stays the session's (views.drawOne). What the host /// writes in the core as it presents (a frame skipped, one owed) is put /// back, as the frame statistics are this process's. fn draw(c: *Remote, s: *Shell) void { - const core = c.r.core(); + const r = c.link.r; + const core = r.core(); const skipped = core.present_skipped; const needs = core.needs_frame; core.frames.mark_start = pardes.FrameStats.nowNs(); core.frames.mark_update = core.frames.mark_start; - c.r.draw(.{ .ctx = s, .f = Shell.present }); + r.draw(.{ .ctx = s, .f = Shell.present }); core.frames.mark_render = core.frames.mark_update; - if (c.r.stats.mispredicted > c.mispredicted) { - c.mispredicted = c.r.stats.mispredicted; - if (core.frames.bytes > 0) c.visible += 1; - } - c.owed = core.present_skipped; - core.frames.record(pardes.FrameStats.nowNs(), false, c.owed); + const drew = core.frames.bytes > 0; + c.link.owed = core.present_skipped; + core.frames.record(pardes.FrameStats.nowNs(), false, c.link.owed); core.present_skipped = skipped; core.needs_frame = needs; - c.dirty = false; - // The history rows it shows and does not hold (a scroll back), - // asked for: blank until they come. - while (c.r.screenRequest()) |req| if (!replica.sendScreen(c.fd, req)) { - c.quit = true; - break; - }; + c.link.drawn(drew); } }; /// The session's stream, onto the loop: its units, and its end. fn linkReader(gpa: std.mem.Allocator, fd: posix.fd_t, rest: *replica.Framer, loop: *Loop, done: *std.atomic.Value(bool)) void { defer done.store(true, .release); - const Take = struct { - fn take(l: *Loop, tag: u8, payload: []const u8) bool { - const t = std.enums.fromInt(wire.ServerTag, tag) orelse return false; - switch (t) { - .unit => { - const bytes = std.heap.c_allocator.dupe(u8, payload) catch return false; - l.postEvent(.{ .unit = bytes }) catch std.heap.c_allocator.free(bytes); - }, - .check => { - const d = (wire.decodeServer(tag, payload) catch return false).check; - l.postEvent(.{ .checked = d }) catch {}; - }, - .screen => { - const bytes = std.heap.c_allocator.dupe(u8, payload) catch return false; - l.postEvent(.{ .screen = bytes }) catch std.heap.c_allocator.free(bytes); - }, - .refused => { - const words = (wire.decodeServer(tag, payload) catch return false).refused; - const bytes = std.heap.c_allocator.dupe(u8, words) catch return false; - l.postEvent(.{ .refused = bytes }) catch std.heap.c_allocator.free(bytes); - return false; - }, - .pong, .welcome, .dump, .blobs, .zstd => {}, - } + const Post = struct { + fn post(l: *Loop, said: replica.Said) bool { + l.postEvent(.{ .said = said }) catch return false; return true; } }; - replica.readStream(gpa, fd, rest, loop, Take.take); + replica.readLink(gpa, fd, rest, loop, Post.post); loop.postEvent(.link_gone) catch {}; } @@ -1489,7 +1334,7 @@ pub fn remote(init: std.process.Init, opts: pardes.Options, path: []const u8, se const have: ?*replica.Have = if (far) &have_store else null; var dial_t0 = std.Io.Clock.awake.now(io).nanoseconds; var joined = replica.dial(gpa, path, session, &why, have) orelse Said.no(io, "{s}", .{std.mem.sliceTo(&why, 0)}); - if (joined.semantics != wire.semantics) Said.no(io, "{s}", .{upgrade_words}); + if (joined.semantics != wire.semantics) Said.no(io, "{s}", .{replica.Link.upgrade_words}); const allocs = pardes.memory.init(gpa); defer pardes.memory.deinit(); @@ -1504,7 +1349,7 @@ pub fn remote(init: std.process.Init, opts: pardes.Options, path: []const u8, se var o = opts; o.image_allocator = allocs.image; o.pdf_allocator = allocs.pdf; - var r = Remote.load(gpa, &joined, o, &why, have) orelse Said.no(io, "{s}", .{std.mem.sliceTo(&why, 0)}); + var r = replica.Link.load(gpa, &joined, o, &why, have) orelse Said.no(io, "{s}", .{std.mem.sliceTo(&why, 0)}); // Its join's time, the dial and the load (PARDES_REPLICA_STATS). var dial_ms: u64 = @intCast(@divTrunc(std.Io.Clock.awake.now(io).nanoseconds - dial_t0, std.time.ns_per_ms)); @@ -1528,10 +1373,10 @@ pub fn remote(init: std.process.Init, opts: pardes.Options, path: []const u8, se var loop: Loop = .init(io, &screen.tty, &screen.vx); var frame_arena: std.heap.ArenaAllocator = .init(allocs.frame); defer frame_arena.deinit(); - var link: Remote = .{ .r = r, .fd = joined.fd }; - if (init.environ_map.get("PARDES_REPLICA_CHECK")) |file| link.check = try gpa.dupeSentinel(u8, file, 0); - defer if (link.check) |file| gpa.free(file); - if (init.environ_map.get("PARDES_TEST_DIVERGE")) |n| link.test_diverge = std.fmt.parseInt(u32, n, 10) catch 0; + var remote_link: Remote = .{ .link = .{ .r = r, .fd = joined.fd } }; + const link = &remote_link.link; + try link.fromEnv(gpa, init.environ_map); + defer link.deinit(gpa); var sh: Shell = .{ .io = io, .gpa = gpa, @@ -1543,7 +1388,7 @@ pub fn remote(init: std.process.Init, opts: pardes.Options, path: []const u8, se .paste_buf = &paste_buf, .inotify_fd = -1, .from = joined.view, - .remote = &link, + .remote = &remote_link, }; try startInput(&loop, &screen); @@ -1561,18 +1406,18 @@ pub fn remote(init: std.process.Init, opts: pardes.Options, path: []const u8, se sh.terms[joined.view] = &screen; screen.feed.view = joined.view; link.reset(r, joined.fd); - link.join = .{ .blobs = joined.blobs, .from_memory = joined.from_memory, .from_disk = joined.from_disk, .sent_bytes = joined.sent_bytes }; - link.join_ms = dial_ms; + link.joinedAs(&joined, dial_ms); var reader_done: std.atomic.Value(bool) = .init(false); const reader = try std.Thread.spawn(.{}, linkReader, .{ gpa, joined.fd, &joined.rest, &loop, &reader_done }); - // Its size is its view's first input. + // What it is, then its size, are its view's first inputs. + link.input(.{ .frontend = .{ .windowed = false } }); screen.size = null; sh.winched(); screen.vx.queueRefresh(); while (!link.quit) { // Its predicted echo judged and caught up, once a frame. if (r.echoFrame()) link.dirty = true; - if (link.dirty) link.draw(&sh); + if (link.dirty) remote_link.draw(&sh); const first = (loop.tryEvent() catch null) orelse idle: { // Idle, its frame drawn: the next key needs no copy taken. r.ready(); @@ -1596,14 +1441,7 @@ pub fn remote(init: std.process.Init, opts: pardes.Options, path: []const u8, se if (link.owed or r.echo.changed) link.dirty = true; // Predictions out: judged a frame at a time while they are. if (r.echo.n > 0 or r.echo.cursor != null or r.echo.nd > 0) requestWake(io, @intCast(pardes.animation.frame_ns / std.time.ns_per_ms)); - if (link.check != null) { - // Quiet a while after a change: asked once (a wake, then the - // next quiet one). - if (first == .wake and link.changed and !link.asked and r.quiet()) { - link.changed = false; - link.asked = replica.askCheck(joined.fd); - } else if (link.changed and r.quiet()) requestWake(io, 300); - } + if (link.quietCheck()) |ms| requestWake(io, ms); if (r.diverged != null) link.quit = true; } if (init.environ_map.get("PARDES_REPLICA_STATS")) |file| link.writeStats(file); @@ -1616,7 +1454,10 @@ pub fn remote(init: std.process.Init, opts: pardes.Options, path: []const u8, se while (true) { const ended = reader_done.load(.acquire); while (loop.tryEvent() catch null) |ev| switch (ev) { - .unit, .screen, .refused => |b| std.heap.c_allocator.free(b), + .said => |said| switch (said) { + .unit, .screen, .refused => |b| std.heap.c_allocator.free(b), + .checked => {}, + }, .paste => |b| gpa.free(@constCast(b)), else => {}, }; @@ -1627,13 +1468,7 @@ pub fn remote(init: std.process.Init, opts: pardes.Options, path: []const u8, se _ = libc.close(joined.fd); joined.rest.deinit(gpa); // Why it joins again, in a line over its frame until a key. - if (r.diverged) |reason| { - link.notify("joined again: this client diverged from the session ({s})", .{reason}); - } else if (link.refused) |words| { - link.notify("joined again: {s}", .{words}); - std.heap.c_allocator.free(words); - link.refused = null; - } else { + if (!link.rejoins()) { // What it made since it joined, kept for its next start. if (have) |h| h.keep(r.core()); r.deinit(); @@ -1644,38 +1479,16 @@ pub fn remote(init: std.process.Init, opts: pardes.Options, path: []const u8, se return; } // The session again, the core it leaves held meanwhile: its blobs - // are not sent again. An upgrade's takes the time its exec and load - // take, and its daemon's. + // are not sent again. if (have) |h| h.leaving(r.core()); - var tries: u32 = 0; dial_t0 = std.Io.Clock.awake.now(io).nanoseconds; - joined = while (true) : (tries += 1) { - why = @splat(0); - if (replica.dial(gpa, path, session, &why, have)) |j| { - if (j.semantics == wire.semantics) break j; - replica.bye(j.fd); - _ = libc.close(j.fd); - var jj = j; - jj.rest.deinit(gpa); - gpa.free(j.dump); - screen.leave(); - Said.no(io, "{s}", .{upgrade_words}); - } - const words = std.mem.sliceTo(&why, 0); - if (std.mem.indexOf(u8, words, "runs another build") != null) { - screen.leave(); - Said.no(io, "{s}", .{upgrade_words}); - } - if (tries > 200) { - screen.leave(); - Said.no(io, "{s}", .{words}); - } - const ts: libc.timespec = .{ .sec = 0, .nsec = 100 * std.time.ns_per_ms }; - _ = libc.nanosleep(&ts, null); + joined = replica.Link.redial(gpa, path, session, &why, have) orelse { + screen.leave(); + Said.no(io, "{s}", .{std.mem.sliceTo(&why, 0)}); }; if (have) |h| h.left(); r.deinit(); - r = Remote.load(gpa, &joined, o, &why, have) orelse { + r = replica.Link.load(gpa, &joined, o, &why, have) orelse { screen.leave(); Said.no(io, "{s}", .{std.mem.sliceTo(&why, 0)}); }; @@ -1683,7 +1496,6 @@ pub fn remote(init: std.process.Init, opts: pardes.Options, path: []const u8, se } } -const upgrade_words = "session upgraded to a newer pardes: upgrade this client too"; /// A terminal a session draws on, while it has one: entered (raw, the /// alternate screen, mouse and paste reports) and left (all of it put back, @@ -2191,11 +2003,7 @@ const Shell = struct { /// (applied at once there, and sent to the session). fn feed(s: *Shell, ev: pardes.Event) void { const c = s.remote orelse return s.core.update(ev); - // Its notice read: a key of its own puts it away. - if (c.notice_len > 0 and (ev == .key or ev == .paste)) c.notice_len = 0; - const msg = c.r.input(ev) catch return; - if (!replica.sendInput(c.fd, msg)) c.quit = true; - c.dirty = true; + c.link.input(ev); } /// Whether a terminal of this process's shows the session, or @@ -2800,7 +2608,7 @@ const Shell = struct { }, .quit => { if (s.remote) |c| { - c.quit = true; + c.link.quit = true; return true; } // One of several: its view goes with it. @@ -2827,39 +2635,16 @@ const Shell = struct { s.input_seen = true; }, .replica_mail => s.input_seen = true, - .unit => |bytes| { - if (s.remote) |c| { - c.r.confirm(bytes); - if (c.test_diverge != 0 and c.r.stats.units >= c.test_diverge and c.r.quiet()) { - c.test_diverge = 0; - c.put_off = true; - c.r.core().next_serial +%= 1000; - } - if (c.r.moved) c.dirty = true; - c.r.moved = false; - c.changed = true; - } - std.heap.c_allocator.free(bytes); - }, - .screen => |bytes| { - if (s.remote) |c| { - if (c.r.screen(bytes)) |reply| if (!replica.sendScreen(c.fd, reply)) { - c.quit = true; - }; - c.dirty = true; - } - std.heap.c_allocator.free(bytes); + .said => |said| if (s.remote) |c| { + c.link.take(said); + if (said == .refused) return true; + } else switch (said) { + .unit, .screen, .refused => |b| std.heap.c_allocator.free(b), + .checked => {}, }, - .checked => |d| if (s.remote) |c| c.checked(d), - .refused => |words| if (s.remote) |c| { - if (c.refused) |old| std.heap.c_allocator.free(old); - c.refused = words; - c.quit = true; - return true; - } else std.heap.c_allocator.free(words), .link_gone => if (s.remote) |c| { - c.quit = true; - c.gone = true; + c.link.quit = true; + c.link.gone = true; return true; }, .focus_in => s.feed(.{ .focus = true }), @@ -3055,7 +2840,7 @@ const Shell = struct { const flashed = sc.flash.apply(s.frame.allocator(), shadowed, s.core, truecolor) catch shadowed; const trailed = sc.trail.apply(s.frame.allocator(), flashed, s.core, truecolor) catch flashed; paintCells(win, trailed.cells, trailed.cols, trailed.rows); - if (s.remote) |c| if (c.notice_len > 0) noticeLine(win, c.notice_buf[0..c.notice_len], trailed.cols, trailed.rows); + if (s.remote) |c| if (c.link.notice_len > 0) noticeLine(win, c.link.notice(), trailed.cols, trailed.rows); tz_cells.end(); for (surface.images[0..surface.nimages]) |maybe| { const place = maybe orelse continue; diff --git a/src/views.zig b/src/views.zig index 361d14a3..b9731089 100644 --- a/src/views.zig +++ b/src/views.zig @@ -523,6 +523,19 @@ pub const Present = struct { ctx: ?*anyopaque, f: ?*const fn (?*anyopaque, *cons /// are the slot's again (else a frame drawn would take them from a view, /// and a replica that draws nothing would keep them). fn drawParked(p: *Pardes, k: u8, present: Present) !void { + try unparked(p, k, present, drawLive); + copy(&drawn_fields, &p.parked[k].?.view, p); +} + +fn drawLive(present: Present, p: *Pardes) anyerror!void { + _ = p.frame_arena.reset(.{ .retain_with_limit = pardes.memory.limits.frame_kept }); + const surface = try p.render(p.frame_arena.allocator()); + if (present.f) |f| f(present.ctx, surface); +} + +/// `f(ctx, p)` with parked view `k` unparked, its slot's selections its own +/// again after (`drawParked`). +fn unparked(p: *Pardes, k: u8, ctx: anytype, comptime f: fn (@TypeOf(ctx), *Pardes) anyerror!void) !void { var sels: [MAX_PANES]struct { []Text.SelRange, u16 } = undefined; for (p.panes, 0..) |s, id| if (s) |pane| { sels[id] = .{ pane.pv[k].body.sels, pane.pv[k].body.nsel }; @@ -532,10 +545,7 @@ fn drawParked(p: *Pardes, k: u8, present: Present) !void { pane.pv[k].body.sels = sels[id][0]; pane.pv[k].body.nsel = sels[id][1]; }; - _ = p.frame_arena.reset(.{ .retain_with_limit = pardes.memory.limits.frame_kept }); - const surface = try p.render(p.frame_arena.allocator()); - if (present.f) |f| f(present.ctx, surface); - copy(&drawn_fields, &p.parked[k].?.view, p); + try f(ctx, p); } /// View `k` drawn and presented outside any step, by a replica client @@ -543,12 +553,32 @@ fn drawParked(p: *Pardes, k: u8, present: Present) !void { /// view put back after exactly as it was, so the replica's digest is the /// authority's still. No post_present, as there. pub fn drawOne(p: *Pardes, k: u8, present: Present) !void { - if (k == p.view or !isOpen(p, k)) { - _ = p.frame_arena.reset(.{ .retain_with_limit = pardes.memory.limits.frame_kept }); - const surface = try p.render(p.frame_arena.allocator()); - if (present.f) |f| f(present.ctx, surface); - return; - } + if (k == p.view or !isOpen(p, k)) return drawLive(present, p); + const Draw = struct { + fn draw(pr: Present, q: *Pardes, kk: u8) anyerror!void { + try drawParked(q, kk, pr); + } + }; + try withParked(p, k, present, Draw.draw); +} + +/// `f(ctx, p)` with view `k` live, outside any step, and the live view put +/// back after exactly as it was, as `drawOne` draws one: what a replica +/// client's frontend reads of its own view (its pointer's cells, its size) +/// while another client's input was the session's last. `f` reads only. +pub fn within(p: *Pardes, k: u8, ctx: anytype, comptime f: fn (@TypeOf(ctx), *Pardes) anyerror!void) !void { + if (k == p.view or !isOpen(p, k)) return f(ctx, p); + const Read = struct { + fn read(x: @TypeOf(ctx), q: *Pardes, kk: u8) anyerror!void { + try unparked(q, kk, x, f); + } + }; + try withParked(p, k, ctx, Read.read); +} + +/// The live view parked, `f(ctx, p, k)`, and the live view put back after +/// exactly as it was. +fn withParked(p: *Pardes, k: u8, ctx: anytype, comptime f: fn (@TypeOf(ctx), *Pardes, u8) anyerror!void) !void { const live = p.view; park(p); defer { @@ -562,10 +592,10 @@ pub fn drawOne(p: *Pardes, k: u8, present: Present) !void { pane.cols = pv.cols; pane.rows = pv.rows; } - if (pane.file) |*f| f.scroll = pv.scroll; + if (pane.file) |*file| file.scroll = pv.scroll; }; } - try drawParked(p, k, present); + try f(ctx, p, k); } // ---- tests ---- diff --git a/test/daemon.py b/test/daemon.py index d9ca7153..ebee286f 100644 --- a/test/daemon.py +++ b/test/daemon.py @@ -25,6 +25,9 @@ private HOME and runtime directory: the replica clients alone python3 -B test/daemon.py --far the far clients and their blob cache alone + python3 -B test/daemon.py --window-clients + window replica clients (hidden, offscreen) of a terminal's session, + at 0/30/80/207 ms, and a window's session serving replicas """ import fcntl import os @@ -528,6 +531,189 @@ def manage(binary): 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 + pipe's lone ESC would hold for the next key).""" + + def __init__(self, root, name, argv, env): + (root / name).mkdir() + self.err = root / f'{name}.err' + self.p = subprocess.Popen(argv, env=dict(env, PARDES_TEST='1', PARDES_TEST_CAPTURE_DIR=str(root / name), SDL_VIDEO_DRIVER='offscreen'), + cwd=root, stdin=subprocess.PIPE, stdout=subprocess.DEVNULL, stderr=open(self.err, 'w'), start_new_session=True) + self.pid = self.p.pid + + def keys(self, text): + self.p.stdin.write(text.replace(b'\x1b', b'\x1b[27u')) + self.p.stdin.flush() + + def said(self): + return self.err.read_text(errors='replace') if self.err.exists() else '' + + def close(self): + if self.p.poll() is None: + self.p.stdin.close() + self.p.wait(timeout=15) + return self.p.returncode + + +def window_clients(binary, gui_binary): + """Window replica clients (`pardes-gui --attach=:`): of a + terminal's detached session, directly and through the delay relay at + 30, 80 and 207 ms, beside a terminal's client, one put off the session's + state that joins again, one that detaches; and a window's session served + to a terminal's client and a window's. Each one's keys in the session's + text, every client's digest the session's once quiet; nothing left.""" + scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn' + scratch.mkdir(parents=True, exist_ok=True) + root = Path(tempfile.mkdtemp(prefix='wc-', dir=os.environ.get('TMPDIR') or 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') + notes = root / 'notes.txt' + notes.write_text(''.join(f'line {i} of the notes\n' for i in range(300))) + started = [] + terms = [] + windows = [] + try: + sess = subprocess.Popen([binary, '--detach=files', str(notes)], env=env, cwd=root, stdin=subprocess.DEVNULL, + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True) + started.append(sess.pid) + sock = root / 'pardes-replica.sock' + wait_for('the replica socket', sock.exists) + wait_for('the session\'s 9P socket', (root / 'pardes-9p-files.sock').exists) + nine = Client(root / 'pardes-9p-files.sock') + pane = next(int(row.split()[0]) for row in nine.read('/index').splitlines() if row.split()[1] == b'text') + body = lambda: nine.read(f'/pane/{pane}/body') + alone = fds(sess.pid) + # A terminal's client beside the windows, typing as they do. + ta = Term(30, 100) + terms.append(ta) + a = ta.spawn([binary, f'--attach={sock}:files'], dict(env, PARDES_REPLICA_CHECK=str(root / 'a.check'))) + started.append(a.pid) + wait_for('the terminal client\'s first frame', lambda: b'line 3 of the notes' in ta.text(), timeout=30) + agreements = [] + for i, rtt in enumerate((0, 30, 80, 207)): + to = sock + relay = None + if rtt: + relay = subprocess.Popen([sys.executable, '-B', str(Path(__file__).parent / 'delay_relay.py'), + str(root / f'relay{rtt}.sock'), str(sock), '--delay', str(rtt / 2)], + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + started.append(relay.pid) + wait_for('the relay', (root / f'relay{rtt}.sock').exists) + to = root / f'relay{rtt}.sock' + check = root / f'w{rtt}.check' + w = Window(root, f'w{rtt}', [gui_binary, f'--attach={to}:files'], dict(env, PARDES_REPLICA_CHECK=str(check))) + windows.append(w) + started.append(w.pid) + seen = len(checks(root / 'a.check')) + w.keys(b'jjjjjjj' * (i + 1) + f'Ofrom-window-{rtt}\x1b'.encode()) + os.write(ta.master, b'jjjjOfrom-terminal-%d\x1b' % rtt) + wait_for(f'the window\'s and the terminal\'s keys ({rtt} ms)', lambda: f'from-window-{rtt}'.encode() in body() + and b'from-terminal-%d' % rtt in body(), timeout=30) + wait_for('the terminal client normal again', lambda: normal_again(ta), timeout=20) + wait_for(f'the window client agrees ({rtt} ms)', lambda: agreed(check, 0), timeout=30) + wait_for('the terminal client agrees', lambda: agreed(root / 'a.check', seen), timeout=30) + # Moved and scrolled, its own view only: agreed again. + n = len(checks(check)) + w.keys(b'jjjjjkkk\x06\x06\x02') + wait_for(f'the window client agrees again ({rtt} ms)', lambda: agreed(check, n), timeout=30) + agreements.append(len(checks(check))) + assert w.close() == 0, w.said()[-800:] + if relay: + relay.kill() + relay.wait() + # One put off the session's state (PARDES_TEST_DIVERGE): the next + # unit it replays finds it, it joins again, and its keys after go in. + dcheck = root / 'wd.check' + wd = Window(root, 'wd', [gui_binary, f'--attach={sock}:files'], dict(env, PARDES_REPLICA_CHECK=str(dcheck), PARDES_TEST_DIVERGE='1')) + windows.append(wd) + started.append(wd.pid) + time.sleep(2) + wd.keys(b'jj') + time.sleep(.5) + os.write(ta.master, b'jj') + wait_for('the window client diverged and joined again', lambda: 'joined again' in wd.said(), timeout=30) + assert wd.p.poll() is None + seen = len(checks(dcheck)) + wd.keys(b'Oafter-rejoin-W\x1b') + wait_for('the window\'s keys after its rejoin', lambda: b'after-rejoin-W' in body(), timeout=30) + wait_for('the window client agrees after its rejoin', lambda: agreed(dcheck, seen), timeout=30) + # Detach typed in it: it alone goes, and says why. + 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:] + os.write(ta.master, b' sD') + wait_for('the terminal client let go', lambda: a.poll() is not None, timeout=10) + wait_for('the session\'s fds level', lambda: fds(sess.pid) == alone, timeout=10) + print(f'daemon: window clients of a terminal\'s session at 0/30/80/207 ms beside a terminal\'s, digests agreed ' + f'{agreements} and {len(checks(root / "a.check"))} times; one put off the session\'s state joined again and ' + f'agreed {len(checks(dcheck))} times; one detached') + try: + nine.write(f'/pane/{pane}/exec', b'Exit\n') + except OSError as e: + # An edited file asks before it goes. + assert 'Exit again' in str(e), e + nine.write(f'/pane/{pane}/exec', b'Exit\n') + sess.wait(timeout=10) + nine.socket.close() + # A window's session (its daemon on, as a desktop's is), served to a + # terminal's client and a window's, the window typing as they do. + win = Window(root, 'win', [gui_binary, '--9p=win', str(notes)], dict(env, PARDES_DAEMON='on')) + windows.append(win) + started.append(win.pid) + wait_for('the window session\'s 9P socket', (root / 'pardes-9p-win.sock').exists, timeout=30) + wait_for('the replica socket', sock.exists) + nine = Client(root / 'pardes-9p-win.sock') + pane = next(int(row.split()[0]) for row in nine.read('/index').splitlines() if row.split()[1] == b'text') + tb = Term(30, 100) + terms.append(tb) + b = tb.spawn([binary, f'--attach={sock}:win'], dict(env, PARDES_REPLICA_CHECK=str(root / 'b.check'))) + started.append(b.pid) + wait_for('the terminal client\'s first frame', lambda: b'line 3 of the notes' in tb.text(), timeout=30) + wg = Window(root, 'wg', [gui_binary, f'--attach={sock}:win'], dict(env, PARDES_REPLICA_CHECK=str(root / 'g.check'))) + windows.append(wg) + started.append(wg.pid) + time.sleep(2) + os.write(tb.master, b'jjjOfrom-T\x1b') + wg.keys(b'jjjjjjOfrom-G\x1b') + win.keys(b'jjjjjjjjjOfrom-W\x1b') + wait_for('everyone\'s keys in the window\'s session', lambda: all(x in body() for x in (b'from-T', b'from-G', b'from-W')), timeout=30) + wait_for('the terminal client normal again', lambda: normal_again(tb), timeout=20) + for k in range(3): + nb, ng = len(checks(root / 'b.check')), len(checks(root / 'g.check')) + os.write(tb.master, b'jk') + wg.keys(b'kj') + win.keys(b'jj') + wait_for('the terminal client agrees with the window', lambda: agreed(root / 'b.check', nb), timeout=30) + wait_for('the window client agrees with the window', lambda: agreed(root / 'g.check', ng), timeout=30) + assert wg.close() == 0, wg.said()[-800:] + os.write(tb.master, b' sD') + wait_for('the terminal client let go', lambda: b.poll() is not None, timeout=10) + assert win.p.poll() is None + print(f'daemon: a window\'s session served a terminal\'s client and a window\'s, digests agreed ' + f'{len(checks(root / "b.check"))} and {len(checks(root / "g.check"))} times') + win.close() + nine.socket.close() + wait_for('nothing left', lambda: not [p for p in processes(root) if alive(p)], timeout=15) + print('daemon: window clients\' sessions ended, nothing left behind') + finally: + for t in terms: + t.close() + for w in windows: + if w.p.poll() is None: + w.p.kill() + for pid in started + processes(root): + try: + os.kill(pid, signal.SIGKILL) + except OSError: + pass + shutil.rmtree(root, ignore_errors=True) + + def joins(path): """A replica client's joins (PARDES_REPLICA_STATS, a line a link): how many blobs each listed, how many it held already from the core it left @@ -1341,6 +1527,8 @@ if __name__ == '__main__': manage(sys.argv[2]) elif sys.argv[1:2] == ['--far']: far(sys.argv[2]) + elif sys.argv[1:2] == ['--window-clients']: + window_clients(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 '--gui' in sys.argv: diff --git a/test/output.zig b/test/output.zig index 2d872bd1..2b8bf1f5 100644 --- a/test/output.zig +++ b/test/output.zig @@ -684,7 +684,8 @@ test "every enabled setting builtin mutates the State Config reports" { var chosen_font: ?[]const u8 = null; var buf: [512]u8 = undefined; for (config.Runtime.settings) |setting| { - if (!setting.enabled(builtins.capabilities)) continue; + // The view's own (a terminal's takes no window's words). + if (!setting.enabled(builtins.viewCapabilities(p))) continue; const command: []const u8 = switch (setting.action) { .theme => try std.fmt.bufPrint(&buf, "{s} acme", .{setting.word}), .shell => try std.fmt.bufPrint(&buf, "{s} fish", .{setting.word}), @@ -716,7 +717,7 @@ test "every enabled setting builtin mutates the State Config reports" { "Theme acme\n", "Shell fish\n", }) |line| try std.testing.expect(std.mem.indexOf(u8, report, line) != null); - const transition = if (!builtins.capabilities.panel_transitions) + const transition = if (!builtins.viewCapabilities(p).panel_transitions) "PanelSlide unsupported\n" else if (p.settings.panel_transition == .off) "PanelSlide off\n" @@ -724,12 +725,12 @@ test "every enabled setting builtin mutates the State Config reports" { try std.fmt.bufPrint(&buf, "{s} on\n", .{config.Runtime.findAction(.{ .transition = p.settings.panel_transition }).?.word}); try std.testing.expect(std.mem.indexOf(u8, report, transition) != null); // A bare word turns a bundled pass on at its default level. - const scene_status = if (builtins.capabilities.scene_shaders) "2" else "unsupported"; + const scene_status = if (builtins.viewCapabilities(p).scene_shaders) "2" else "unsupported"; for ([_][]const u8{"Crt"}) |name| { const line = try std.fmt.bufPrint(&buf, "{s} {s}\n", .{ name, scene_status }); try std.testing.expect(std.mem.indexOf(u8, report, line) != null); } - const tagline = if (!builtins.capabilities.tagline_font_size) + const tagline = if (!builtins.viewCapabilities(p).tagline_font_size) "TaglineSize unsupported\n" else try std.fmt.bufPrint(&buf, "TaglineSize {d}\n", .{p.settings.font.tagline_percent}); -- cgit v1.3 From 5af775e9817395af39792cc609b832394d4a4fb8 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Fri, 30 Oct 2026 15:15:01 -0300 Subject: replica: what only the authority holds, a step reads off the tape (tape.authority): the store's closed panes and Recent, a script's hold on a pane's events, the 9P socket, the session's config directory and startup file; a replica's own are never read, and never put back by a rollback The Panes picker's closed rows, Recent's rows, a closed pane brought back (a Look at @pN, a Panes row), a jump to a closed file and the +Jumps rows read `p.store` and `p.recent`, `.authority` state a replica keeps on its own: its store has no file, its Recent only what it replayed since it joined. The rows made of them went into digested state, so every client of a session diverged together after a Del (H4), every client that joined after one diverged at its first unit forever (H11: trackJump dropped a closed file's jumps at every step when Recent did not know the file), a client's Del of a file the session's Recent knew made the stat the session skipped (H12: noteClosed looked in Recent first), and a client on another machine read its own store (H13). - tape.authority: poison, then a value read: the authority's answer is taped, a replay takes it, a speculation waits for it. One site, `.authority`. - Readers through it: Query's Recent and closed-pane rows, Store.reopen's record, Pardes.recentByHash (jumps, +Jumps), mouse.reportRange's readers check (a script reading a pane's events takes a look or exec: `pane.fs.readers`, the 9P server's), Tty9p's socket check, Pardes.configDir and startupPath (ThemeFile, DumpThemes, Config, DumpConfig, an init file saved), DumpConfig's dump directory. - trackJump no longer reads Recent at every step: a closed file's jump stays; the jump to it drops that file's entries when Recent has forgotten it, as when the file is gone. - noteClosed asks the host (recentKeeps, a taped stat) before it looks in Recent: the same syscall on every side. - The tty toggle, read on every key, is session state: Pardes.tty_toggle, from the options when the core is made, dumped. - The rollback copy no longer saves `store` and `recent` (rollback.zig `unsaved`): their bytes put back pointed at lists the host's heap (recentGpa) had freed, which the epoch never holds. A speculated Del then a Panes listing read a freed name (H8, the segfault). Tests, each failing before: a rollback leaves the store and Recent as a speculation left them; a replica joined after a pane closed has the session's jump to it, its Panes and Recent rows, asked by either (and the variant hunt's Recent written by another window); a replica's Del of a file its session's Recent knows asks the host what the session asked. Co-Authored-By: Claude Opus 5.5 --- src/Output.zig | 10 ++++-- src/Query.zig | 21 +++++++----- src/Store.zig | 46 ++++++++++++++++++++----- src/builtins.zig | 4 +-- src/colors.zig | 5 +-- src/echo.zig | 2 +- src/exec.zig | 9 +++-- src/look.zig | 2 +- src/mouse.zig | 15 ++++++-- src/pardes.zig | 75 ++++++++++++++++++++++++++++++---------- src/replica.zig | 102 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/rollback.zig | 51 ++++++++++++++++++++++++++-- src/tape.zig | 19 +++++++++++ 13 files changed, 311 insertions(+), 50 deletions(-) (limited to 'src/exec.zig') diff --git a/src/Output.zig b/src/Output.zig index 359db1cf..7c8b7f59 100644 --- a/src/Output.zig +++ b/src/Output.zig @@ -1005,6 +1005,12 @@ test "full Help renders builtin rows, a call hierarchy guide, then language keys try std.testing.expect(std.mem.indexOf(u8, group, "Callstack: static caller chains") != null); } +/// Where a dump goes by default, as the session's environment says (the +/// authority's, `tape.authority`): in `buf`. +fn dumpDirectory(buf: []u8) []const u8 { + return pardes.dump.defaultDirectory(buf) orelse ""; +} + pub fn openConfig(p: *Pardes, id: usize) !void { var out: std.Io.Writer.Allocating = .init(p.gpa); errdefer out.deinit(); @@ -1015,8 +1021,8 @@ pub fn openConfig(p: *Pardes, id: usize) !void { try p.locations_config.write(&located.writer); try config.Runtime.writeReport(&out.writer, .{ .locations = located.written(), - .default_dump_dir = if (host_fs) (pardes.dump.defaultDirectory(&dir_buf) orelse "") else "", - .startup_config_path = p.opts.startup_config_path, + .default_dump_dir = if (host_fs) pardes.tape.authority(dumpDirectory, .{@as([]u8, &dir_buf)}) else "", + .startup_config_path = p.startupPath(), .platform = builtins.viewPlatform(p), .theme_name = p.theme().name, .theme_file = pardes.colors.loadedThemeFile(p), diff --git a/src/Query.zig b/src/Query.zig index 49f58a0e..2f417a68 100644 --- a/src/Query.zig +++ b/src/Query.zig @@ -48,6 +48,7 @@ const memory = @import("memory.zig"); const Names = @import("Names.zig"); const Places = @import("Places.zig"); const Stream = @import("Stream.zig"); +const Store = @import("Store.zig"); const Surface = @import("surface.zig").Surface; const Pardes = pardes.Pardes; const Pane = panes.Pane; @@ -591,12 +592,9 @@ fn startSource(p: *Pardes, id: usize, q: *Query, source: Source, owner_id: ?usiz if (p.fs.serving) Stream.step(p); }, .recent => { - // Every window's files: what the others wrote since, read. - p.store.refresh(p); var out: std.Io.Writer.Allocating = .init(gpa); defer out.deinit(); - Output.recentText(p, &out.writer, true) catch {}; - var lines = std.mem.splitScalar(u8, out.written(), '\n'); + var lines = std.mem.splitScalar(u8, pardes.tape.authority(recentRows, .{ p, &out }), '\n'); while (lines.next()) |ln| { if (ln.len == 0) continue; const rel = Names.relative(ln, dir); @@ -617,10 +615,9 @@ fn startSource(p: *Pardes, id: usize, q: *Query, source: Source, owner_id: ?usiz } // Then the panes this session closed, the latest first, each // `(closed)` and dimmer (makeNameRows): Enter brings one back - // where it was. Its name alone is matched, not the word. - var i = p.store.closed.items.len; - while (i > 0) : (i -= 1) { - const c = p.store.closed.items[i - 1]; + // where it was. Its name alone is matched, not the word. The + // store's, which a replica has from the authority. + for (pardes.tape.authority(Store.closedNames, .{p})) |c| { var buf: [4096 + 48]u8 = undefined; const row = std.fmt.bufPrint(&buf, config.pane_addr ++ "{d} {s}" ++ closed_word, .{ c.serial, Names.relative(c.name, dir) }) catch continue; const key_at = std.mem.indexOfScalar(u8, row, ' ').? + 1; @@ -652,6 +649,14 @@ fn startSource(p: *Pardes, id: usize, q: *Query, source: Source, owner_id: ?usiz /// What a Panes row of a closed pane ends with. const closed_word = " (closed)"; +/// Every window's files, as a Recent query lists them: what the others +/// wrote since, read first. The store's (`tape.authority`): in `out`. +fn recentRows(p: *Pardes, out: *std.Io.Writer.Allocating) []const u8 { + p.store.refresh(p); + Output.recentText(p, &out.writer, true) catch {}; + return out.written(); +} + /// The owner's declarations, from a parse that already exists: its sticky /// headers' (TreeContext) at this revision, or the locations cache's. None /// is made here, on the loop, unless `small` and the text is small: a diff --git a/src/Store.zig b/src/Store.zig index 36215234..9c726705 100644 --- a/src/Store.zig +++ b/src/Store.zig @@ -468,6 +468,21 @@ fn unlist(s: *Store, gpa: std.mem.Allocator, serial: u32) void { }; } +/// A closed pane as Panes lists it: its serial and what its row shows. +pub const Named = struct { serial: u32, name: []const u8 }; + +/// This session's closed panes, the latest first (scratch; the names the +/// store's): what a step lists of them (`tape.authority`). +pub fn closedNames(p: *Pardes) []const Named { + const items = p.store.closed.items; + const out = p.scratch.allocator().alloc(Named, items.len) catch return &.{}; + for (out, 0..) |*o, i| { + const c = items[items.len - 1 - i]; + o.* = .{ .serial = c.serial, .name = c.name }; + } + return out; +} + /// The closed pane with this serial, if this session has it. pub fn closedBySerial(s: *const Store, serial: u32) ?*Closed { for (s.closed.items) |*c| if (c.serial == serial) return c; @@ -785,12 +800,10 @@ fn compact(s: *Store, p: *Pardes, file: File, st: File.Stat, path: []const u8) v /// from `from`. False when it is not this session's, or its record is gone /// or bad; the keyboard on it otherwise. pub fn reopen(s: *Store, p: *Pardes, serial: u32, from: usize) bool { - s.refresh(p); const gpa = p.recentGpa(); - const place = (s.closedBySerial(serial) orelse return false).*; - const body = s.bodyOf(p, place) orelse return false; - // Read from the file: this call's to free (`unlist` frees one held). - defer if (place.body.len == 0) gpa.free(body); + // The store's: a replica has the authority's (`tape.authority`). + const place = pardes.tape.authority(record, .{ s, p, serial }) orelse return false; + const body = place.body; const m = parseMeta(body) orelse return false; const free = p.freeSlot() orelse { p.reportError(from, "Panes", error.NoPaneSlots); @@ -826,6 +839,21 @@ pub fn reopen(s: *Store, p: *Pardes, serial: u32, from: usize) bool { return true; } +/// Where a closed pane goes back, and its record's body (scratch). +pub const Record = struct { gainer: u32, below: bool, owner: u32, rows: u16, body: []const u8 }; + +/// Closed pane `serial`'s record, the store read on first; null when it is +/// not this session's, or its record is gone or bad. +fn record(s: *Store, p: *Pardes, serial: u32) ?Record { + s.refresh(p); + const c = (s.closedBySerial(serial) orelse return null).*; + const body = s.bodyOf(p, c) orelse return null; + // Read from the file: this call's to free (`unlist` frees one held). + defer if (c.body.len == 0) p.recentGpa().free(body); + const copy = p.scratch.allocator().dupe(u8, body) catch return null; + return .{ .gainer = c.gainer, .below = c.below, .owner = c.owner, .rows = c.rows, .body = copy }; +} + /// A closed pane's record body: held here, or read from the file and /// checked against its CRC (gpa; the caller frees it when it is not /// `c.body`). @@ -855,8 +883,9 @@ fn bodyOf(s: *Store, p: *Pardes, c: Closed) ?[]u8 { return body; } -/// `@p` naming a pane this session closed: its serial. -pub fn closedAddress(s: *const Store, word: []const u8) ?u32 { +/// `@p` alone, the pane and no place in it: its serial, for a pane +/// this session closed to come back by (`reopen` says whether it did). +pub fn closedAddress(word: []const u8) ?u32 { const addr = @import("config.zig").pane_addr; if (!std.mem.startsWith(u8, word, addr)) return null; const digits = word[addr.len..]; @@ -865,8 +894,7 @@ pub fn closedAddress(s: *const Store, word: []const u8) ?u32 { } else digits.len; // `@p7` alone, or `@p7:` with nothing after it: the pane, no place in it. if (end == 0 or (end < digits.len and !(digits[end] == ':' and end + 1 == digits.len))) return null; - const serial = std.fmt.parseInt(u32, digits[0..end], 10) catch return null; - return if (s.closedBySerial(serial) != null) serial else null; + return std.fmt.parseInt(u32, digits[0..end], 10) catch null; } // ---- tests ---- diff --git a/src/builtins.zig b/src/builtins.zig index 69ac3113..97cdc5a0 100644 --- a/src/builtins.zig +++ b/src/builtins.zig @@ -941,7 +941,7 @@ pub const DumpThemes = struct { pub const enabled = pardes.hosted; pub fn run(c: Ctx) void { if (comptime enabled) { - if (c.p.opts.config_dir == null) { + if (c.p.configDir() == null) { c.p.reportError(c.id, "dump themes", error.NoConfigDirectory); return; } @@ -1607,7 +1607,7 @@ pub const Help = struct { pub const Config = struct { pub const scope: Scope = .session; pub fn run(c: Ctx) void { - const path = c.p.opts.startup_config_path orelse + const path = c.p.startupPath() orelse return c.p.reportFailure(c.id, "Config: no startup file here: no configuration directory"); var real_buf: [4096]u8 = undefined; const real = if (pardes.filesystem.resolveOs(path, &real_buf)) |r| r.path else null; diff --git a/src/colors.zig b/src/colors.zig index c016434b..cc417ccb 100644 --- a/src/colors.zig +++ b/src/colors.zig @@ -677,14 +677,15 @@ pub fn requestThemeFile(p: *Pardes, id: usize, argument: []const u8) void { } const absolute = std.fs.path.isAbsolute(input); - if (!absolute and p.opts.config_dir == null) { + const config_dir = if (absolute) null else p.configDir(); + if (!absolute and config_dir == null) { p.reportError(id, "theme file", error.NoConfigDirectory); return; } var joined: [4095]u8 = undefined; const resolved = if (absolute) input else path: { - const dir = p.opts.config_dir.?; + const dir = config_dir.?; const separator = if (dir.len > 0 and dir[dir.len - 1] != std.Io.Dir.path.sep) std.Io.Dir.path.sep_str else ""; break :path std.fmt.bufPrint(&joined, "{s}{s}{s}", .{ dir, separator, input }) catch { p.reportError(id, "theme file", error.PathTooLong); diff --git a/src/echo.zig b/src/echo.zig index 4acd3d11..4560930c 100644 --- a/src/echo.zig +++ b/src/echo.zig @@ -500,7 +500,7 @@ fn forwarded(c: *const Pardes, ev: pardes.Event) bool { else => return false, }; if (k.cp == Key.escape) return false; - return !(k.ctrl and (k.cp == c.opts.tty_toggle or k.cp == 'v' or k.cp == 'V')); + return !(k.ctrl and (k.cp == c.tty_toggle or k.cp == 'v' or k.cp == 'V')); } fn blank(cp: u21) bool { diff --git a/src/exec.zig b/src/exec.zig index e1c13daa..c5218279 100644 --- a/src/exec.zig +++ b/src/exec.zig @@ -411,11 +411,16 @@ pub fn spawnTty(p: *Pardes, from: usize) ?*Pane { pub fn spawnV9fsTty(p: *Pardes, from: usize) void { if (comptime !hosted or @import("builtin").os.tag != .linux) return p.reportError(from, "Tty9p", error.LinuxRequired); - if (p.fs.socket_path.len == 0) + // The 9P server's: a replica has the authority's answer. + if (!pardes.tape.authority(servesSocket, .{p})) return p.reportError(from, "Tty9p", error.SessionSocketRequired); _ = spawnTtyWithMount(p, from, true); } +fn servesSocket(p: *Pardes) bool { + return p.fs.socket_path.len != 0; +} + fn spawnTtyWithMount(p: *Pardes, from: usize, v9fs: bool) ?*Pane { // No pane asking (an empty window's tag): the session's directory, as // New's scratch is. @@ -1009,7 +1014,7 @@ pub fn applyStartupConfig(p: *Pardes) void { /// setting lines: a command in it (`Newcol`) is the session's start, and /// would not be right twice. pub fn reapplyInitFile(p: *Pardes, path: []const u8, text: []const u8) void { - const init_path = p.opts.startup_config_path orelse return; + const init_path = p.startupPath() orelse return; if (!std.mem.eql(u8, init_path, path)) return; applyInitText(p, text, true); } diff --git a/src/look.zig b/src/look.zig index 226c96e3..09a22266 100644 --- a/src/look.zig +++ b/src/look.zig @@ -1816,7 +1816,7 @@ pub fn lookAt(p: *Pardes, id: usize, operand_raw: []const u8) void { // `@p` names no open pane: one this session closed comes // back where it was (Store.reopen), any other is a miss, said. if (t.id >= MAX_PANES or p.panes[t.id] == null) { - if (p.store.closedAddress(pl.path)) |serial| if (p.store.reopen(p, serial, id)) return; + if (@TypeOf(p.store).closedAddress(pl.path)) |serial| if (p.store.reopen(p, serial, id)) return; return missed(p, id, "no pane {s}", .{pl.path[0..@min(pl.path.len, 32)]}); } const target = p.panes[t.id].?; diff --git a/src/mouse.zig b/src/mouse.zig index 67ebf7cf..3281f48a 100644 --- a/src/mouse.zig +++ b/src/mouse.zig @@ -990,10 +990,17 @@ fn reportGesture( operand: exec.PointerOperand, chord_arg: ?[]const u8, ) bool { - if ((p.panes[id] orelse return false).fs.readers == 0) return false; return reportRange(p, id, cmd, text, on_tag, gestureRange(p, id, text, on_tag, operand), chord_arg); } +/// Whether a script reads pane `id`'s events, and so takes its looks and +/// execs: the 9P server's, the authority's alone (a replica has its +/// answer, `tape.authority`). +fn readsEvents(p: *Pardes, id: usize) bool { + const pane = p.panes[id] orelse return false; + return pane.fs.readers != 0; +} + /// An event reader told of a look or an exec of `text` at `range` of the /// tag or body, by a click or a key alike: false when the pane has none. pub fn reportRange( @@ -1006,7 +1013,7 @@ pub fn reportRange( chord_arg: ?[]const u8, ) bool { const scripted = p.panes[id] orelse return false; - if (scripted.fs.readers == 0) return false; + if (!pardes.tape.authority(readsEvents, .{ p, id })) return false; const is_look = cmd == config.look_cmd; const action: ctlfs.events.Action = if (is_look) (if (on_tag) .tag_look else .body_look) @@ -1020,7 +1027,9 @@ pub fn reportRange( if (is_look) { if (!named and std.mem.indexOfAny(u8, text, "/.:") != null) flag |= ctlfs.events.flag_filename; } else if (chord_arg != null) flag |= ctlfs.events.flag_chorded; - if (!ctlfs.events.noteAction(p, id, action, range.q0, range.q1, flag, text)) return false; + // Taken whether or not this process's server has the reader: the + // session's said it has (a replica's has none). + _ = ctlfs.events.noteAction(p, id, action, range.q0, range.q1, flag, text); // A chorded exec's argument follows as two records, its text and where // it came from (`file:#q0,#q1`, empty when that is not known), as acme // sends them (exec.c:182-188); the pane keeps it for the write-back. diff --git a/src/pardes.zig b/src/pardes.zig index f0d2cd0c..36ce6bdb 100644 --- a/src/pardes.zig +++ b/src/pardes.zig @@ -857,7 +857,7 @@ test "Togglettymode builtin and keyboard chord share mode transitions including try std.testing.expectEqual(Text.Mode.tty, pane.body.mode); try std.testing.expect(p.executeBuiltinLine(0, "Togglettymode")); try std.testing.expectEqual(Text.Mode.normal, pane.body.mode); - p.update(.{ .key = .{ .cp = p.opts.tty_toggle, .ctrl = true } }); + p.update(.{ .key = .{ .cp = p.tty_toggle, .ctrl = true } }); try std.testing.expectEqual(Text.Mode.tty, pane.body.mode); // The tag has its own mode: the body keeps tty while the tag is typed into. tagline.enterTag(p, pane); @@ -867,7 +867,7 @@ test "Togglettymode builtin and keyboard chord share mode transitions including try std.testing.expectEqual(Text.Mode.normal, pane.body.mode); try std.testing.expect(pane.focus == .body); tagline.enterTag(p, pane); - p.update(.{ .key = .{ .cp = p.opts.tty_toggle, .ctrl = true } }); + p.update(.{ .key = .{ .cp = p.tty_toggle, .ctrl = true } }); try std.testing.expectEqual(Text.Mode.tty, pane.body.mode); try std.testing.expect(pane.focus == .body); @@ -4732,6 +4732,10 @@ pub const Pardes = struct { /// The views no frontend here draws: a replica client's, which its own /// process draws (src/replica.zig). A pump skips them. undrawn: u8 = 0, + /// The Ctrl key into a terminal's tty mode and out (`--tty-toggle`): the + /// session's, taken from its options when it is made, so a dump carries + /// it to a replica, whose own options are its process's. + tty_toggle: u21 = config.tty_toggle_default, /// per-update scratch (paneCursorLines, selection text); reset each update scratch: std.heap.ArenaAllocator, /// The arena each frame's Surface text is built in, reset by `pump`. Hosts @@ -4797,6 +4801,7 @@ pub const Pardes = struct { .tree_sitter_gpa = opts.tree_sitter_allocator orelse gpa, .opts = opts, .windowed = opts.windowed, + .tty_toggle = opts.tty_toggle, .col_tags = @splat(.{ .what = .column, .gpa = gpa }), .global_tag = .{ .what = .workspace, .gpa = gpa }, .fs = .{}, @@ -4989,7 +4994,10 @@ pub const Pardes = struct { /// Recent keeps it. fn noteClosed(p: *Pardes, pane: *const Pane) void { const d = recentPlace(pane) orelse return; - if (p.recent.get(d.path) == null and !recentKeeps(d.path)) return; + // The host asked first, always: what Recent holds is the + // authority's, and a step that asked only when it did not know the + // file would ask on one side and not the other. + if (!recentKeeps(d.path) and p.recent.get(d.path) == null) return; p.recent.closedSel(p.recentGpa(), d.path, d.line, d.col, d.aline, d.acol); } @@ -5024,9 +5032,38 @@ pub const Pardes = struct { }; } - /// The recent entry a closed jump names, by its path's hash. - pub fn recentByHash(p: *const Pardes, hash: u64) ?recent_files.Entry { - for (p.recent.entries.items) |e| if (std.hash.Wyhash.hash(0, e.path) == hash) return e; + /// The session's configuration directory and startup file, as a step + /// reads them: its process's options, so the authority's + /// (`tape.authority`); a replica's are its own process's. + pub fn configDir(p: *Pardes) ?[]const u8 { + return tape.authority(optsConfigDir, .{p}); + } + + pub fn startupPath(p: *Pardes) ?[]const u8 { + return tape.authority(optsStartupPath, .{p}); + } + + fn optsConfigDir(p: *Pardes) ?[]const u8 { + return p.opts.config_dir; + } + + fn optsStartupPath(p: *Pardes) ?[]const u8 { + return p.opts.startup_config_path; + } + + /// The recent entry a closed jump names, by its path's hash, its path + /// in scratch. Recent is the authority's (every window of its user + /// writes it): a replica has its answer (`tape.authority`). + pub fn recentByHash(p: *Pardes, hash: u64) ?recent_files.Entry { + return tape.authority(recentFound, .{ p, hash }); + } + + fn recentFound(p: *Pardes, hash: u64) ?recent_files.Entry { + for (p.recent.entries.items) |e| if (std.hash.Wyhash.hash(0, e.path) == hash) { + var found = e; + found.path = p.scratch.allocator().dupe(u8, e.path) catch return null; + return found; + }; return null; } @@ -6607,7 +6644,7 @@ pub const Pardes = struct { if (header == null and pane.isTerminal() and pane.body.mode == .tty and pane.focus == .body and pane.prompt == .none) { p.leader_on = false; p.ctrl_w_pending = false; - if (key.ctrl and !key.alt and key.cp == p.opts.tty_toggle) + if (key.ctrl and !key.alt and key.cp == p.tty_toggle) return p.toggleTty(p.active); // With ProgramEsc on, bare Escape leaves only at a shell prompt // (Shift-Esc, above, always). @@ -6672,7 +6709,7 @@ pub const Pardes = struct { } return; } - const tty_toggle = key.ctrl and key.cp == p.opts.tty_toggle; + const tty_toggle = key.ctrl and key.cp == p.tty_toggle; if (pane.isTerminal() and tty_toggle) { return p.toggleTty(p.active); } @@ -7624,10 +7661,12 @@ pub const Pardes = struct { if (i == p.jcur) cur = w; // survives -> lands at w; dies -> the next one does var kept = j; const live = if (j.serial == 0) false else if (p.panes[j.pane]) |pane| pane.serial == j.serial else false; - // A file's pane closed: its entry stays, closed, while the recent - // list knows the file, and a jump to it opens it again. + // A file's pane closed: its entry stays, closed, and a jump to it + // opens it again from Recent, or drops it when Recent has + // forgotten it (`jumpBy`: Recent is the authority's, read when + // it is wanted, not at every step). if (!live) { - if (j.path_hash == 0 or p.recentByHash(j.path_hash) == null) continue; + if (j.path_hash == 0) continue; kept.serial = 0; // Open again in some pane (a look, Recent): the entry is that // pane's, and closed only while no pane has the file. @@ -7727,12 +7766,13 @@ pub const Pardes = struct { // A closed file's entry: opened again at its dot, placed as a look // places it, and the entry is that pane from here on. if (j.serial == 0) { - const e = p.recentByHash(j.path_hash) orelse return; - // Deleted since: its entries go, it is said, and the step goes - // on to the next place, never stuck on one that cannot open. - if (!recentKeeps(e.path)) { + const found = p.recentByHash(j.path_hash); + // Deleted since, or Recent has forgotten it: its entries go (the + // first said), and the step goes on to the next place, never + // stuck on one that cannot open. + if (found == null or !recentKeeps(found.?.path)) { var said: [recent_path_cap + 32]u8 = undefined; - p.setMessage(p.active, std.fmt.bufPrint(&said, "{s}: deleted, skipped", .{e.path}) catch "deleted, skipped"); + if (found) |e| p.setMessage(p.active, std.fmt.bufPrint(&said, "{s}: deleted, skipped", .{e.path}) catch "deleted, skipped"); const hash = j.path_hash; var w: usize = 0; var cur = p.jcur; @@ -7750,6 +7790,7 @@ pub const Pardes = struct { // round takes one file's entries away, so it ends. return p.jumpBy(delta); } + const e = found.?; const from = p.active; look.reopenAt(p, from, e.path, .{ .line = @max(1, j.line), .col = if (j.pdf) 0 else @max(1, j.col) }); const opened = p.panes[p.active] orelse return; @@ -9284,7 +9325,7 @@ test "raw tty forwards Ctrl letters and former global shortcuts to the child" { _ = drainWrites(p, &buf); edit.setYank(p, "register text"); for ('a'..'z' + 1) |letter| { - if (letter == p.opts.tty_toggle) continue; // editor/TTY mode shortcut + if (letter == p.tty_toggle) continue; // editor/TTY mode shortcut if (letter == 'v') continue; // the window's paste, asserted just below p.update(.{ .key = .{ .cp = @intCast(letter), .ctrl = true } }); const expected = [_]u8{@intCast(letter - 'a' + 1)}; diff --git a/src/replica.zig b/src/replica.zig index d6a2e0ef..8b1d84f4 100644 --- a/src/replica.zig +++ b/src/replica.zig @@ -3337,3 +3337,105 @@ test "a far join is sent each blob once: joined again with them on disk or in th try std.testing.expectEqual(@as(u64, 0), j.sent_bytes); endJoin(&j, &have); } + +/// A replica joined from the session's dump as it is now, between units, +/// as `Peers.join` sends it: its state, its blobs put back where they go. +fn joinedNow(a: *Authority, id: u16, view: u8) !*Replica { + const gpa = std.testing.allocator; + const was = Stepping.begin(&a.t, null); + var blobs: std.ArrayListUnmanaged(walk.Deferred) = .empty; + defer blobs.deinit(a.core.gpa); + const state = try pardes.dump.dumpJoin(a.core, &blobs); + defer a.core.gpa.free(state); + tape.resync(&a.t); + was.end(); + var whole: std.ArrayListUnmanaged(u8) = .empty; + defer whole.deinit(gpa); + var pos: usize = 0; + for (blobs.items) |b| { + try whole.appendSlice(gpa, state[pos..b.at]); + try whole.appendSlice(gpa, b.bytes); + pos = b.at; + } + try whole.appendSlice(gpa, state[pos..]); + return Replica.initDump(gpa, id, view, whole.items, .{ .cols = 80, .rows = 24 }); +} + +fn agrees(a: *Authority, r: *Replica) !void { + if (r.diverged) |why| std.debug.print("diverged: {s}\n", .{why}); + try std.testing.expect(r.diverged == null); + try std.testing.expect(r.quiet()); + try std.testing.expectEqual(digestOf(a), r.digest()); +} + +test "a replica joined after a pane closed: the session's jump to it, its Panes and Recent rows, asked by either" { + const gpa = std.testing.allocator; + const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host(), false); + defer a.deinit(); + // A file looked at and closed: a jump to it, Recent's, a closed pane. + var cwd: [std.fs.max_path_bytes]u8 = undefined; + var line: [std.fs.max_path_bytes + 32]u8 = undefined; + const dir = std.mem.span(@as([*:0]u8, @ptrCast(std.c.getcwd(&cwd, cwd.len) orelse return error.NoCwd))); + _ = try a.local(.{ .command = try std.fmt.bufPrint(&line, "Look {s}/build.zig.zon", .{dir}) }); + _ = try a.local(.{ .command = "Del" }); + try std.testing.expectEqual(@as(usize, 1), a.core.store.closed.items.len); + try std.testing.expect(a.core.njumps > 1); + // What another window of the user's wrote to the store, which the + // session read (src/variants_test.zig's case, the variant hunt's). + a.core.recent.opened(a.core.recentGpa(), try std.fmt.bufPrint(&line, "{s}/build.zig", .{dir})); + const r = try joinedNow(a, 1, 0); + defer r.deinit(); + try std.testing.expectEqual(digestOf(a), r.digest()); + r.confirm(try a.local(.{ .key = .{ .cp = 'j', .text = "j" } })); + r.confirm(try a.local(.{ .command = "Search Panes" })); + r.confirm(try a.local(.{ .command = "Search Recent" })); + try agrees(a, r); + // The replica's own: it waits for the session's rows. + for ([_][]const u8{ "Search Panes", "Search Recent" }) |asked| { + const msg = try gpa.dupe(u8, try r.input(.{ .command = asked })); + defer gpa.free(msg); + r.confirm(try a.take(msg)); + r.settle(); + } + try agrees(a, r); + // The closed pane brought back by the replica's Look at it: the + // session's record of it, off the tape. + { + const closed = try std.fmt.bufPrint(&line, "Look @p{d}", .{a.core.store.closed.items[0].serial}); + const msg = try gpa.dupe(u8, try r.input(.{ .command = closed })); + defer gpa.free(msg); + r.confirm(try a.take(msg)); + r.settle(); + try std.testing.expectEqual(@as(usize, 0), a.core.store.closed.items.len); + try agrees(a, r); + r.confirm(try a.local(.{ .command = "Del" })); + } + // A jump back onto the closed file: opened again, from Recent. + for (0..3) |_| { + const msg = try gpa.dupe(u8, try r.input(.{ .key = .{ .cp = 'o', .ctrl = true } })); + defer gpa.free(msg); + r.confirm(try a.take(msg)); + r.settle(); + } + try agrees(a, r); +} + +test "a replica's Del of a file its session's Recent knows asks the host what the session asked" { + const gpa = std.testing.allocator; + const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host(), false); + defer a.deinit(); + var cwd: [std.fs.max_path_bytes]u8 = undefined; + var line: [std.fs.max_path_bytes + 32]u8 = undefined; + const dir = std.mem.span(@as([*:0]u8, @ptrCast(std.c.getcwd(&cwd, cwd.len) orelse return error.NoCwd))); + _ = try a.local(.{ .command = try std.fmt.bufPrint(&line, "Look {s}/build.zig.zon", .{dir}) }); + // Joined while it is open: in the session's Recent, in no replica's. + const r = try joinedNow(a, 1, 0); + defer r.deinit(); + const msg = try gpa.dupe(u8, try r.input(.{ .command = "Del" })); + defer gpa.free(msg); + r.confirm(try a.take(msg)); + r.settle(); + try std.testing.expectEqual(@as(usize, 1), a.core.store.closed.items.len); + try agrees(a, r); +} + diff --git a/src/rollback.zig b/src/rollback.zig index b0394d22..bb3ac2dc 100644 --- a/src/rollback.zig +++ b/src/rollback.zig @@ -399,7 +399,7 @@ pub const Copy = struct { const s = @typeInfo(T).@"struct"; inline for (s.field_names, s.field_types, s.field_attrs) |name, F, attr| { if (attr.@"comptime") continue; - if (comptime (annotated(T, "local", name) or annotated(T, "derived", name)) and unsaved(name)) continue; + if (comptime (annotated(T, "local", name) or annotated(T, "derived", name) or annotated(T, "authority", name)) and unsaved(name)) continue; const at = @intFromPtr(&@field(v, name)); if (comptime walk.lengthOf(T, name) != null and @typeInfo(F) == .array) { try c.save(at, walk.lengthIn(v, comptime walk.lengthOf(T, name).?) * @sizeOf(@typeInfo(F).array.child)); @@ -436,10 +436,15 @@ fn annotatedStruct(comptime T: type) bool { /// (numbers, and a static name), and the rows a terminal was last read as /// (a grid's worth of text, emptied when a copy is taken and when it is /// put back: src/replica.zig), and a replica's predicted echo (src/echo.zig: -/// the replica's, never its core's). +/// the replica's, never its core's). And the store and Recent, a replica's +/// own: on the host's heap (Pardes.recentGpa), which the epoch never puts a +/// free off for, so their bytes put back would point at what is freed. A +/// step reads what the authority holds of them off the tape +/// (tape.authority), never a replica's. fn unsaved(comptime name: []const u8) bool { return std.mem.eql(u8, name, "effects") or std.mem.eql(u8, name, "in_q") or std.mem.eql(u8, name, "frames") or - std.mem.eql(u8, name, "shell_rows") or std.mem.eql(u8, name, "echo"); + std.mem.eql(u8, name, "shell_rows") or std.mem.eql(u8, name, "echo") or std.mem.eql(u8, name, "store") or + std.mem.eql(u8, name, "recent"); } fn annotated(comptime T: type, comptime kind: []const u8, comptime name: []const u8) bool { @@ -601,3 +606,43 @@ test "a file's location rows are pinned whole, with what they own, and come back p.deinit(); try std.testing.expectEqual(@as(usize, 0), e.live.count()); } + +/// `Look `, the name a file of the repository's, absolute. +fn lookAt(buf: []u8, name: []const u8) ![]const u8 { + var cwd: [std.fs.max_path_bytes]u8 = undefined; + const dir = std.c.getcwd(&cwd, cwd.len) orelse return error.NoCwd; + return std.fmt.bufPrint(buf, "Look {s}/{s}", .{ std.mem.span(@as([*:0]u8, @ptrCast(dir))), name }); +} + +test "a rollback leaves the store and Recent as a speculation left them: they live on the host's heap, which no copy holds" { + var e: Epoch = .{ .child = std.testing.allocator }; + defer e.deinit(); + const gpa = e.allocator(); + const p = try Pardes.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml", .image_allocator = gpa, .pdf_allocator = gpa, .tree_sitter_allocator = gpa, .frame_allocator = gpa }); + p.pump(.{}) catch {}; + var line: [std.fs.max_path_bytes + 16]u8 = undefined; + p.update(.{ .command = try lookAt(&line, "build.zig.zon") }); + p.update(.{ .command = "Del" }); + p.pump(.{}) catch {}; + try std.testing.expectEqual(@as(usize, 1), p.store.closed.items.len); + // Both lists full to what they hold: the next of each moves them. + p.store.closed.shrinkAndFree(p.recentGpa(), p.store.closed.items.len); + p.recent.entries.shrinkAndFree(p.recentGpa(), p.recent.entries.items.len); + const recents = p.recent.entries.items.len; + var c: Copy = .{}; + defer c.deinit(); + try c.take(&e, p); + // A speculation opens a file and closes it (a Del a replica applies at + // once), and is undone. + p.update(.{ .command = try lookAt(&line, "build.zig") }); + p.update(.{ .command = "Del" }); + p.pump(.{}) catch {}; + c.restore(); + // What the store and Recent hold is where they say it is. + try std.testing.expectEqual(@as(usize, 2), p.store.closed.items.len); + try std.testing.expect(std.mem.endsWith(u8, p.store.closed.items[1].name, "build.zig")); + try std.testing.expectEqual(recents + 1, p.recent.entries.items.len); + p.deinit(); + try std.testing.expectEqual(@as(usize, 0), e.live.count()); +} + diff --git a/src/tape.zig b/src/tape.zig index 3c8dd765..b16f39f9 100644 --- a/src/tape.zig +++ b/src/tape.zig @@ -107,6 +107,8 @@ pub const Site = enum(u16) { /// command printed (a pty/run's answer): a screen-state replica's /// emulator is the last delta's until the next. prompt, + /// What the authority alone holds and a step reads (`authority`). + authority, }; /// What the sites return. wire.semantics hashes their shape with the @@ -125,6 +127,10 @@ pub const results = .{ anyerror![]u8, anyerror!void, terminal.Told, ?pardes.ctlfs.pty.Printed, @typeInfo(@TypeOf(terminal.greeting)).@"fn".return_type.?, + // What only the authority holds (`authority`): a closed pane's record, + // Recent's entry for a closed jump, the closed panes' names. + ?@import("Store.zig").Record, ?@import("recent.zig").Entry, + []const @import("Store.zig").Named, }; /// What a host reports to the core as failed (`shell_failed`, `save_failed`, @@ -813,6 +819,19 @@ pub fn value(comptime s: Site, comptime f: anytype, args: anytype) @typeInfo(@Ty return call(s, null, f, args, false); } +/// A read of what the authority alone holds (`.authority` state a step +/// makes digested state from: the store's closed panes and Recent, which +/// every window of its user writes; the 9P server's readers and socket), +/// taped as `value` is; a speculation that reaches it waits for the +/// authority's answer, as at a host call. A replica's own is never read. +/// What it returns is the tape's arena's on a replay: `f` returns what +/// lives to the step's end (scratch, or the authority's own), and the +/// caller copies what it keeps. +pub fn authority(comptime f: anytype, args: anytype) @typeInfo(@TypeOf(f)).@"fn".return_type.? { + poison(); + return value(.authority, f, args); +} + fn call(comptime s: Site, a: ?std.mem.Allocator, comptime f: anytype, args: anytype, comptime yields: bool) @typeInfo(@TypeOf(f)).@"fn".return_type.? { const R = @typeInfo(@TypeOf(f)).@"fn".return_type.?; comptime { -- cgit v1.3 From c07baa7bf83039600a54b261eaae7fdd4d673768 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Fri, 30 Oct 2026 21:06:51 -0300 Subject: builtins: Tty9p is a word of every hosted build, not a Linux build's alone, so a build's words, the rows of its Help, are the same on FreeBSD: a Linux client of a box session made SPC ?'s +Help with one row more than its session's and joined again (`pane 4.file.content`, and `.splice` over a +Help made again: two of the box soak's three divergences); whether its host is Linux is the authority's answer (tape.authority), so a replica of a FreeBSD session refuses Tty9p as its session does; test/cross_replay.py's session runs Help (a FreeBSD tape replayed here diverged at its pane's content) Co-Authored-By: Claude Opus 5.5 --- src/builtins.zig | 5 ++++- src/builtins_json.zig | 2 +- src/config.zig | 2 +- src/exec.zig | 10 ++++++++-- test/cross_replay.py | 7 ++++--- 5 files changed, 18 insertions(+), 8 deletions(-) (limited to 'src/exec.zig') diff --git a/src/builtins.zig b/src/builtins.zig index b101e34d..38a4d835 100644 --- a/src/builtins.zig +++ b/src/builtins.zig @@ -1487,8 +1487,11 @@ pub const Tty = struct { }; /// A Linux terminal with the current session mounted through kernel v9fs. +/// A word of every hosted build, Linux's or not: a build's words are its +/// Help's rows, which a replica of another build's session makes as its +/// session did (a Linux client of a FreeBSD one diverged at SPC ?). pub const Tty9p = struct { - pub const enabled = pardes.hosted and @import("builtin").os.tag == .linux; + pub const enabled = pardes.hosted; pub fn run(c: Ctx) void { exec.spawnV9fsTty(c.p, c.id); } diff --git a/src/builtins_json.zig b/src/builtins_json.zig index 489f1e22..3402b2ee 100644 --- a/src/builtins_json.zig +++ b/src/builtins_json.zig @@ -74,7 +74,7 @@ pub fn write(w: *std.Io.Writer) !void { test "docs/typ/builtins-.json is what the registry says now" { // a terminal build checks its file, a window build its own; both are - // Linux builds' lists (Tty9p is Linux's) + // Linux builds' lists if (comptime @import("builtin").os.tag != .linux) return error.SkipZigTest; const file = switch (pardes.platform) { .tty => "builtins-tty.json", diff --git a/src/config.zig b/src/config.zig index ebca14ea..c1f1981c 100644 --- a/src/config.zig +++ b/src/config.zig @@ -2283,7 +2283,7 @@ const doc_typ = struct { for (std.enums.values(Builtin)) |b| if (leader_path.get(b)) |p| if (std.mem.eql(u8, p, path[0..n])) return true; for (leader_args) |la| if (std.mem.eql(u8, la.path, path[0..n])) return true; - // A word this build leaves out (Tty9p off Linux) keeps its leader in the other's. + // A word this build leaves out keeps its leader in the other's. var buf: [96]u8 = undefined; const needle = std.fmt.bufPrint(&buf, "\"leader\": \"{s}\"", .{k}) catch return false; return std.mem.indexOf(u8, other_build, needle) != null; diff --git a/src/exec.zig b/src/exec.zig index c5218279..af312c45 100644 --- a/src/exec.zig +++ b/src/exec.zig @@ -409,14 +409,20 @@ pub fn spawnTty(p: *Pardes, from: usize) ?*Pane { } pub fn spawnV9fsTty(p: *Pardes, from: usize) void { - if (comptime !hosted or @import("builtin").os.tag != .linux) + if (comptime !hosted) return p.reportError(from, "Tty9p", error.LinuxRequired); + // The session's host's and its 9P server's: a replica, of another + // build too (a Linux client of a FreeBSD session), has their answers. + if (!pardes.tape.authority(onLinux, .{})) return p.reportError(from, "Tty9p", error.LinuxRequired); - // The 9P server's: a replica has the authority's answer. if (!pardes.tape.authority(servesSocket, .{p})) return p.reportError(from, "Tty9p", error.SessionSocketRequired); _ = spawnTtyWithMount(p, from, true); } +fn onLinux() bool { + return @import("builtin").os.tag == .linux; +} + fn servesSocket(p: *Pardes) bool { return p.fs.socket_path.len != 0; } diff --git a/test/cross_replay.py b/test/cross_replay.py index 9ce7d152..21367ca1 100644 --- a/test/cross_replay.py +++ b/test/cross_replay.py @@ -20,8 +20,9 @@ Restore of a dump that is not there (errors the host reports, anyerrors). It greps and finds, as a script does, which a 9P write runs on the loop: its reads are a tape site (a replica of a session a script greps in read no file and diverged). And it holds what a digest must name the same in -every build: a +LocationsConfig, whose origin is a Builtin, and a file -pane renamed (H19: no Linux client could join a FreeBSD session so). +every build: a +LocationsConfig, whose origin is a Builtin, a file +pane renamed (H19: no Linux client could join a FreeBSD session so), and +a +Help, which lists the build's words (Tty9p was a Linux build's alone). """ import os import shutil @@ -75,7 +76,7 @@ def record(binary, out): started.append(int(status['pid'])) pane = next(int(row.split()[0]) for row in c.read('/index').splitlines() if row.split()[1] == b'text') for line in (f'Look {root / "fifo"}', f'Look {root / "dir"}', f'Save {root / "a.txt" / "x"}', - f'Restore {root / "nothing.dump"}', 'Grep hello', 'Find txt', 'LocationsConfig'): + f'Restore {root / "nothing.dump"}', 'Grep hello', 'Find txt', 'LocationsConfig', 'Help'): try: c.write(f'/pane/{pane}/exec', line.encode() + b'\n') except Exception: -- cgit v1.3