diff options
| author | Gabriel Schneider <[email protected]> | 2026-10-31 06:28:48 -0300 |
|---|---|---|
| committer | Gabriel Schneider <[email protected]> | 2026-10-31 06:28:48 -0300 |
| commit | a479792a1ab2b593642d7f648194bfa23ce01dba (patch) | |
| tree | 96ddee7d879a9084daa07db43b0b7910b072a785 /src/pardes.zig | |
| parent | e179cc44fe5060c76a5b00c41e53f11209f5acd9 (diff) | |
| parent | 4c761893e5b3fdae422622cfa02104ab36633045 (diff) | |
| download | pardes-a479792a1ab2b593642d7f648194bfa23ce01dba.tar.gz pardes-a479792a1ab2b593642d7f648194bfa23ce01dba.zip | |
Merge the upstream daemon and replicated client/server refactor
Diffstat (limited to 'src/pardes.zig')
| -rw-r--r-- | src/pardes.zig | 716 |
1 files changed, 544 insertions, 172 deletions
diff --git a/src/pardes.zig b/src/pardes.zig index c7ae6704..edab4a58 100644 --- a/src/pardes.zig +++ b/src/pardes.zig @@ -61,6 +61,13 @@ pub const config = @import("config.zig"); pub const pdf_enabled = panes.Pdf.enabled; pub const pdf = panes.Pdf.pdf; pub const memory = @import("memory.zig"); +pub const tape = @import("tape.zig"); +pub const walk = @import("walk.zig"); +pub const screen_state = if (terminal_panes) @import("screen_state.zig") else struct {}; +pub const views = @import("views.zig"); +pub const rollback = @import("rollback.zig"); +pub const replica = @import("replica.zig"); +pub const echo = @import("echo.zig"); pub const image = @import("image.zig"); pub const dump = @import("dump.zig"); pub const lsp = @import("lsp/lsp.zig"); @@ -165,6 +172,10 @@ pub const Turn = struct { /// a step. Nests: a directory listing that resolves each entry yields /// inside a yield, and only the outermost one lets go. pub fn yield(t: *Turn) void { + // A replica makes no syscall: each is a site of the tape's. One that + // is none stops a speculation and diverges a replay (it joins + // again), never the process (a window client's `Tty fish`, H17). + if (tape.replaying()) tape.stray(); const io = t.io orelse return; yield_depth += 1; if (yield_depth != 1) return; @@ -468,6 +479,10 @@ pub const Loc = struct { }; test { + _ = @import("rollback.zig"); + _ = @import("tape.zig"); + _ = @import("replica.zig"); + _ = @import("echo.zig"); _ = @import("modal.zig"); _ = @import("tagline.zig"); _ = @import("hunks.zig"); @@ -491,6 +506,7 @@ test { _ = @import("body_layer.zig"); _ = @import("draw.zig"); _ = @import("dump.zig"); // its tests ran nowhere before + _ = @import("upgrade.zig"); _ = @import("recent.zig"); _ = @import("Store.zig"); _ = @import("Presentation.zig"); @@ -504,6 +520,9 @@ test { _ = @import("Finder.zig"); _ = @import("Tables.zig"); _ = @import("Handover.zig"); + _ = @import("walk.zig"); + _ = screen_state; + _ = @import("views.zig"); } pub const Builtin = builtins.registry.Builtin(); @@ -538,53 +557,8 @@ fn drainForSavePath(p: *Pardes, buf: []u8) ?[]const u8 { return if (len) |n| buf[0..n] else null; } -fn drainForAttach(p: *Pardes) ?AttachRequest { - while (p.nextEffect()) |effect| p.perform(effect); - return p.takeAttach(); -} - -test "Attach asks for a session and tears nothing down" { - if (comptime !can_attach) return; - const gpa = std.testing.allocator; - const p = try Pardes.init(gpa, .{ .tty_only = true }); - defer p.deinit(); - while (p.nextEffect()) |_| {} - - // Bare means whichever session is there, and that is an EMPTY name rather - // than an absent request: the frontend still has to go and look. - try std.testing.expect(p.executeBuiltinLine(0, "Attach")); - const bare = drainForAttach(p) orelse return error.NoAttachAsked; - try std.testing.expectEqualStrings("", bare.name); - try std.testing.expectEqual(@as(u8, 0), bare.pane); - - // ...and the named form carries its tail, the way `Theme <name>` does. - try std.testing.expect(p.executeBuiltinLine(0, "Attach work")); - const named = drainForAttach(p) orelse return error.NoAttachAsked; - try std.testing.expectEqualStrings("work", named.name); - try std.testing.expect(p.takeAttach() == null); // taken once, then gone - - // The word only ASKS. A core that tore itself down here could not be handed - // back intact when the connect fails, and that is the entire guarantee. - try std.testing.expect(!p.quit); - try std.testing.expect(p.panes[0] != null); -} - -test "Attach in a detached session: bare is wrong #args, a name no session has says so, and nothing is asked" { - if (comptime !can_attach) return; - const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .detached_session = true }); - defer p.deinit(); - while (p.nextEffect()) |_| {} - const pane = p.panes[0].?; - try std.testing.expect(p.executeBuiltinLine(0, "Attach")); - try std.testing.expect(drainForAttach(p) == null); - try std.testing.expectStringStartsWith(pane.msg[0..pane.msg_len], "wrong #args"); - try std.testing.expect(p.executeBuiltinLine(0, "Attach zz-no-such-session-qq")); - try std.testing.expect(drainForAttach(p) == null); - try std.testing.expectEqualStrings("Attach: zz-no-such-session-qq: no such session", pane.msg[0..pane.msg_len]); -} - -test "Detach asks the frontend to leave, and says so when there is nothing to leave" { - if (comptime !can_attach) return; // compiled out where nothing polls `takeAttach` — see `can_attach` +test "Detach asks the host to let its terminal go, and says so when there is nothing to leave" { + if (comptime !can_attach) return; // the word is compiled out elsewhere: see `can_attach` const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .tty_only = true }); defer p.deinit(); @@ -804,6 +778,7 @@ test "TreeContext tag style preserves message rows and its opt-out survives rest pane.file.?.tree_context = true; pane.file.?.scroll = 8; pane.msg_len = 0; + p.sync(); _ = try p.render(p.scratch.allocator()); try std.testing.expect(p.settings.tree_context_tag_style); const full_height = p.surface.body_layers[0].viewport.h; @@ -811,6 +786,7 @@ test "TreeContext tag style preserves message rows and its opt-out survives rest try std.testing.expectEqual(FontRole.tagline, p.surface.body_layers[0].cells[0].style.font_role); pane.msg[0] = '!'; pane.msg_len = 1; + p.sync(); _ = try p.render(p.scratch.allocator()); // An overlay takes nothing: the message is a chip OVER the body's first // row, so the viewport keeps every row it had. @@ -828,10 +804,12 @@ test "TreeContext tag style preserves message rows and its opt-out survives rest try std.testing.expectEqualStrings("!", band.cells[p.tagCapacity(band.viewport.w) - 2].grapheme()); pane.msg_len = 0; p.leader_on = true; + p.sync(); _ = try p.render(p.scratch.allocator()); try std.testing.expectEqual(full_height, p.surface.body_layers[0].viewport.h); p.leader_on = false; try std.testing.expect(p.executeBuiltinLine(0, "TreeContextTagStyle")); + p.sync(); _ = try p.render(p.scratch.allocator()); try std.testing.expectEqual(@as(u16, 0), p.surface.body_layers[0].rows); try std.testing.expectEqual(@as(u16, 0), pane.body_rows); @@ -882,7 +860,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); @@ -892,7 +870,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); @@ -2063,14 +2041,6 @@ test "image dump restores source bytes renderer choices and exact custom tail" { pane.tag.own = try p.gpa.dupe(u8, " Keep Del"); try dump.dumpState(p); - var first_dump = try dump.readZon(gpa, p.dump_out.?, "image-first-dump"); - defer first_dump.deinit(); - const first = first_dump.value; - try std.testing.expect(first.panes[0].image.?.petscii); - try std.testing.expectEqual(dump.ImagePalette.terminal, first.panes[0].image.?.palette); - try std.testing.expect(!first.panes[0].image.?.ascii); - try std.testing.expectEqualStrings(" Keep Del", first.panes[0].tag_tail.?); - const restored = try dump.initFromDump(gpa, .{ .tty_only = true }, p.dump_out.?); defer restored.deinit(); const restored_pane = restored.panes[0].?; @@ -2081,18 +2051,11 @@ test "image dump restores source bytes renderer choices and exact custom tail" { try std.testing.expectEqualStrings(" Keep Del", tagline.curTail(restored_pane)); try std.testing.expectEqualSlices(u8, source, restored_pane.image.?.raw); + // And dumped again, its bytes still there. try dump.dumpState(restored); - var parsed = try dump.readZon(gpa, restored.dump_out.?, "image-redump"); - defer parsed.deinit(); - const redump = parsed.value; - const encoded = redump.panes[0].image.?.bytes_b64; - const decoded = try dump.decodeBytes(gpa, encoded); - defer gpa.free(decoded); - try std.testing.expectEqualSlices(u8, source, decoded); - try std.testing.expect(redump.panes[0].image.?.petscii); - try std.testing.expectEqual(dump.ImagePalette.terminal, redump.panes[0].image.?.palette); - try std.testing.expect(!redump.panes[0].image.?.ascii); - try std.testing.expectEqualStrings(" Keep Del", redump.panes[0].tag_tail.?); + const again = try dump.load(gpa, .{ .tty_only = true }, restored.dump_out.?, null); + defer again.deinit(); + try std.testing.expectEqualSlices(u8, source, again.panes[0].?.image.?.raw); } test "a Look on a directory does not type ls into an occupied terminal" { @@ -2394,25 +2357,30 @@ test "owned cwd EOF failure retains the pane and Del retries its close" { } test "owned cwd restore either copies the directory or preserves the old core" { + // No terminal: ghostty 1.4's snapshot decode leaks when an allocation + // inside it fails, and this fails every allocation of a Restore in turn + // (what pardes's own load made is freed, src/walk.zig rollback). var allocator = std.testing.FailingAllocator.init(std.testing.allocator, .{}); - const p = try Pardes.init(allocator.allocator(), .{ .tty_only = true }); + const p = try Pardes.init(allocator.allocator(), .{ .tty_only = true, .file = "/nonexistent/pardes-owned-cwd" }); defer p.deinit(); - p.setCwd(0, "/retained/terminal/directory"); + p.newScratchBelow(0); + const id = p.active; + try p.panes[id].?.setOwnedCwd("/retained/terminal/directory"); try dump.dumpState(p); - const original = p.panes[0].?; + const original = p.panes[id].?; var completed = false; for (0..256) |failure| { allocator.has_induced_failure = false; allocator.fail_index = allocator.alloc_index + failure; const replacement = dump.restore(p, p.dump_out.?, "test") catch { try std.testing.expect(allocator.has_induced_failure); - try std.testing.expectEqual(original, p.panes[0].?); + try std.testing.expectEqual(original, p.panes[id].?); try std.testing.expectEqualStrings("/retained/terminal/directory", original.cwdSlice()); continue; }; defer replacement.deinit(); - try std.testing.expectEqualStrings("/retained/terminal/directory", replacement.panes[0].?.cwdSlice()); - try std.testing.expectEqual(original, p.panes[0].?); + try std.testing.expectEqualStrings("/retained/terminal/directory", replacement.panes[id].?.cwdSlice()); + try std.testing.expectEqual(original, p.panes[id].?); if (!allocator.has_induced_failure) { completed = true; break; @@ -2903,7 +2871,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")); @@ -2967,8 +2937,7 @@ test "restored terminals keep monotonic nonzero pane identities" { const gpa = std.testing.allocator; const source = try Pardes.init(gpa, .{ .shells = 3 }); defer source.deinit(); - // Filter is a fresh presentation default, not emulator/dump state. Even a - // pane toggled off in the source session comes back with the default on. + // Filter is the pane's, and a dump keeps it: one toggled off comes back off. source.panes[1].?.tty_filter = false; try dump.dumpState(source); @@ -2981,7 +2950,7 @@ test "restored terminals keep monotonic nonzero pane identities" { for (restored.panes, 0..) |slot, id| { const pane = slot orelse continue; if (!pane.isTerminal()) continue; - try std.testing.expect(pane.tty_filter); + try std.testing.expectEqual(id != 1, pane.tty_filter); try std.testing.expect(pane.serial != 0); for (serials[0..n]) |seen| try std.testing.expect(pane.serial != seen); ids[n] = id; @@ -3629,6 +3598,7 @@ pub const Mouse = struct { pixel_x: f32, pixel_y: f32, metrics: RowMetrics, + place: Layer.Place = .{}, }; // sel indexing relies on left/middle/right being 0/1/2 pub const Button = enum { left, middle, right, wheel_up, wheel_down, wheel_left, wheel_right, none, back, forward }; @@ -3706,6 +3676,9 @@ pub const CellPixels = if (pdf_enabled) struct { h: u16 = 16, } else struct {}; +/// Said at a focus-in when the Host's `newer_build` answers yes (upgrade.zig). +pub const newer_build_words = "a newer pardes is installed: Upgrade (SPC s U) moves this session onto it"; + pub const Event = union(enum) { key: Key, mouse: Mouse, @@ -3750,12 +3723,15 @@ 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, }; -pub const attach_name_max = 256; - -pub const AttachRequest = struct { pane: u8, name: []const u8 }; +/// 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 }; @@ -3807,12 +3783,12 @@ pub const Effect = union(enum) { /// Write the build-time theme ring below the per-user config directory. /// The pane receives the completion/error message from the native host. dump_themes: struct { pane: u8 }, - attach: struct { pane: u8, name: Buf(attach_name_max) }, detach: struct { pane: u8 }, quit, fn Buf(comptime n: usize) type { return struct { + pub const replica = .{ .len = .{.{ "data", "len" }} }; data: [n]u8 = undefined, len: u16 = 0, pub const cap = n; @@ -4366,6 +4342,10 @@ pub const Boot = enum { pub const Options = struct { tty_only: bool = false, + /// The first view's frontend is a window (`Pardes.windowed`), as a + /// window's build says: an option, taped with the rest, so that a + /// window's build replaying a terminal's session starts as it did. + windowed: bool = platform == .gui, /// The layout to boot, when a host means one outright rather than leaving /// it to be read off the options below. `--tty` names `.tty`; a core /// booted for a test names nothing and gets `.tty_shell`. @@ -4387,9 +4367,6 @@ pub const Options = struct { /// window opens one as big as that, Handover.zig). geometry: ?[]const u8 = null, nested: bool = false, - /// The core of a `--detach` session (detached/server.zig): it has no - /// terminal of its own, so Attach there is refused with why. - detached_session: bool = false, startup_config: ?[]const u8 = null, ninep_name: []const u8 = "", ninep_tcp: ?[]const u8 = null, @@ -4451,7 +4428,10 @@ pub const Pardes = struct { // layout: columns own x by weight; panes own y by vweight within a column. ncol: usize = 0, col_weight: [MAX_COLS]u64 = @splat(column_weight_unit), - col_panes: [MAX_COLS][MAX_PANES]usize = undefined, + // Zeroed, not undefined: a digest takes the whole of it, a release + // build's heap leaves its unused slots whatever was there before, and + // two replicas must agree on them (src/replica.zig). + col_panes: [MAX_COLS][MAX_PANES]usize = @splat(@splat(0)), col_n: [MAX_COLS]usize = @splat(0), /// Each column's tag and the workspace's: Texts like a pane's tag, with /// no prefix, showing a default until someone edits them. @@ -4587,6 +4567,9 @@ 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). + /// The live view's frontend is a window (Event.frontend): what it draws, + /// and the words it takes (builtins.zig `here`). It starts as + /// `Options.windowed` says. windowed: bool = false, /// The last plain B1 click, for acme's double-click (text.c:881, /// textselect: a second click at the same point within 500 ms). @@ -4737,11 +4720,28 @@ pub const Pardes = struct { /// a Restore builtin wants this dump loaded into the live session; the /// shell consumes it via takeRestore each frame (restore contents stay host-fed) restore_req: ?[]const u8 = null, - restore_buf: [1024]u8 = undefined, - attach_req: ?AttachRequest = null, - attach_buf: [attach_name_max]u8 = undefined, + restore_buf: [1024]u8 = @splat(0), surface: Surface = .{}, + /// A replica's predicted echo (src/echo.zig), drawn over its terminals: + /// presentation, its own, in no digest and no rollback copy. Null on a + /// session's own core. + echo: ?*echo.Echo = null, + /// The view the fields above are of: whose layout, focus, pointer and + /// panes' cursors and scroll (views.zig). `views_open` says which views + /// there are, one a window or terminal; each not live is in `parked`. + view: u8 = 0, + views_open: u8 = 1, + /// The open views kept for their clients' rejoin (views.away). + views_away: u8 = 0, + parked: [views.max]?*views.Parked = @splat(null), + /// 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 @@ -4756,6 +4756,34 @@ pub const Pardes = struct { /// The message row's entry points, called from everywhere as /// `p.setMessage(...)`; they live with the rest of it in Messages.zig. + /// What the replay digest leaves out (src/walk.zig): what drawing + /// keeps, what is recomputed, and what only the session that performs + /// effects has. + pub const replica = .{ + .local = .{ + // A frame, and the animations and timings that make it. + "surface", "presentation", "frames", "chrome_animation", "lifts", "lift_serials", + "cursor_glide", "cursor_view", "cursor_crossing", "cursor_held", "frame_arena", "scratch", + "needs_frame", "present_skipped", "shell_continuous", "native_image_patches", + "echo", + // Drained by every pump before its digest; a replica's queues + // are its own. + "effects", "effects_head", "effects_len", "in_q", "in_head", "in_len", + // The views not live: written whenever one goes out, so the + // live one's slot is stale (views.zig). + "parked", "undrawn", + // How this process was started, and the last dump it made for + // its host to write: a session loaded elsewhere has its own. + "opts", "dump_out", + }, + .derived = .{ "shell_rows", "diff_output", "locations_cache", "retired_panes", "tty_filter_palette", "body_chrome" }, + // The host's handles, the 9P server's fids and log, the store file + // every window of the user shares (and Recent read from it), and + // the files of a host with no file system of its own. + .authority = .{ "host", "fs", "store", "recent", "fallback" }, + .len = .{ .{ "jumps", "njumps" }, .{ "look_src", "n_look_src" }, .{ "leader_keys", "leader_n" }, .{ "col_x", "ncol" }, .{ "col_w", "ncol" }, .{ "session_dir", "session_dir_len" } }, + }; + pub const setStatus = Messages.setStatus; pub const setMessage = Messages.setMessage; pub const reportError = Messages.reportError; @@ -4778,6 +4806,8 @@ pub const Pardes = struct { .pdf_gpa = opts.pdf_allocator orelse gpa, .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 = .{}, @@ -4794,12 +4824,26 @@ pub const Pardes = struct { return p; } + /// A new session, its tape written from here when PARDES_RECORD asks. pub fn init(gpa: std.mem.Allocator, opts: Options) !*Pardes { + tape.startFromEnv(); + const taped = tape.enter(null, .{ .init = opts }); + const p = initSession(gpa, opts) catch |err| { + tape.leave(null, taped); + return err; + }; + tape.leave(p, taped); + return p; + } + + fn initSession(gpa: std.mem.Allocator, opts: Options) !*Pardes { // A new session draws a tab at the default until `Tab` says otherwise. config.tab_now = config.tab_width; const p = try create(gpa, opts); errdefer p.deinit(); p.boot = Boot.of(opts); + // Asked once, at the start, whoever asks first after. + _ = p.sessionDir(); switch (p.boot) { .document => { const path = opts.file.?; @@ -4932,7 +4976,9 @@ pub const Pardes = struct { /// The store read once at start: a new session's, Recent from it. pub fn loadRecent(p: *Pardes) void { - p.store = Store.init(p.opts.store_path); + // A replica's store is its own, in memory: the recording session's + // file is every window's of its user (src/tape.zig). + p.store = Store.init(if (tape.replaying()) null else p.opts.store_path); p.store.load(p); } @@ -4954,7 +5000,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); } @@ -4989,13 +5038,45 @@ 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; } pub fn deinit(p: *Pardes) void { + const taped = tape.enter(p, .{ .deinit = tape.current(p) }); + tape.forget(p); + defer tape.leave(null, taped); if (comptime hosted) if (std.c.getenv("PARDES_FRAMES")) |path| p.frames.dump(std.mem.span(path)); // Every file open now is closed with its dot, and the list kept. for (p.panes) |slot| if (slot) |pane| p.noteClosed(pane); @@ -5024,6 +5105,7 @@ pub const Pardes = struct { slot.* = null; }; const gpa = p.gpa; + views.deinit(p); for (&p.col_tags) |*t| t.deinit(gpa); p.global_tag.deinit(gpa); p.registers.deinit(gpa); @@ -5056,6 +5138,8 @@ pub const Pardes = struct { /// shell feedback after write_dump: remember where the dump landed (the /// topbar grows a `Restore <path>` word pointing at it) pub fn setLastDump(p: *Pardes, path: []const u8) void { + const taped = tape.enter(p, .{ .set_last_dump = path }); + defer tape.leave(p, taped); p.pointRestoreAt(path); ctlfs.events.notePath(p, "dump", path); } @@ -5083,19 +5167,13 @@ pub const Pardes = struct { /// the shell polls this each frame: a pending Restore's dump path, or null pub fn takeRestore(p: *Pardes) ?[]const u8 { + const taped = tape.enter(p, .take_restore); + defer tape.leave(p, taped); const r = p.restore_req; p.restore_req = null; return r; } - /// the shell polls this each frame beside takeRestore: a pending Attach's - /// session and reporting pane, or null - pub fn takeAttach(p: *Pardes) ?AttachRequest { - const a = p.attach_req; - p.attach_req = null; - return a; - } - /// The workspace tag's height: one row while the setting keeps it, as /// acme's row tag is, zero once a native shell takes its commands over. /// Layout and hit testing read this rather than the constant, the way @@ -5150,6 +5228,9 @@ pub const Pardes = struct { for (p.panes, 0..) |slot, id| if (slot == pane) { if (watched) p.emit(.{ .watch = .{ .pane = @intCast(id), .on = false } }); if (pane.isTerminal()) p.emit(.{ .close_pty = .{ .pane = @intCast(id) } }); + // Its pty's end and its emulator are the authority's: a replica's + // speculation that closes a terminal waits for it. + if (pane.terminal != null) tape.poison("close a terminal"); ctlfs.events.noteRetire(p, pane); // ...and so do bytes still queued for the pty it no longer has. p.dropPendingWrite(id); @@ -5175,6 +5256,7 @@ pub const Pardes = struct { if (comptime pdf_enabled) if (pane.pdf) |*pv| panes.Pdf.deinitPane(p, pane, pv); if (pane.file) |*file| panes.File.deinit(p, pane, file); if (pane.ovl) |o| p.gpa.free(o.text); + views.tornDown(p, pane); pane.body.deinit(p.gpa); pane.tag.deinit(p.gpa); pane.input.deinit(p.gpa); @@ -5209,6 +5291,7 @@ pub const Pardes = struct { pane.serial = p.next_serial; p.rects[id] = .{}; p.panes[id] = pane; + views.installed(p, pane); panes.terminal.adoptSettings(p, pane); // /log hears of it once the update that made it ends, when it has // its file, name and place (`ctlfs.events.announce`). @@ -5449,6 +5532,8 @@ pub const Pardes = struct { /// The shell reports the spawned pane's working directory (and later cwd /// changes it observes, e.g. via /proc/<pid>/cwd before each frame). pub fn setCwd(p: *Pardes, id: usize, cwd: []const u8) void { + const taped = tape.enter(p, .{ .set_cwd = .{ .id = id, .cwd = cwd } }); + defer tape.leave(p, taped); const pane = p.panes[id] orelse return; // A command pane stays the directory's it was run for (newCommand). if (pane.command != null) return; @@ -5477,7 +5562,39 @@ pub const Pardes = struct { return if (selected.len == 0) config.defaultShell() else selected; } + /// A shell a dead session left, taken in (Adopt): a terminal pane made + /// for it as the Tty word makes one, its greeting off (the shell is up + /// already), whose spawn the host answers with that shell's pty. Its id, + /// or null with no room. An input, as every host write into the core + /// is: a replica of the session makes the same pane. + pub fn adoptShell(p: *Pardes) ?u8 { + const taped = tape.enter(p, .adopt_shell); + defer tape.leave(p, taped); + var newest: u32 = 0; + for (p.panes) |slot| if (slot) |pn| { + newest = @max(newest, pn.serial); + }; + _ = p.executeBuiltinLine(p.active, "Tty"); + for (p.panes, 0..) |slot, id| if (slot) |pn| if (pn.serial > newest and pn.isTerminal()) { + pn.greet = false; + return @intCast(id); + }; + return null; + } + + /// A terminal's reader failed (no end of file: the host closed its pty): + /// its pane takes keys again, and why is said. + pub fn readerFailed(p: *Pardes, id: u8, err: anyerror) void { + const taped = tape.enter(p, .{ .reader_failed = .{ .id = id, .err = err } }); + defer tape.leave(p, taped); + const pane = p.panes[id] orelse return; + pane.body.mode = .normal; + p.reportError(id, "terminal reader", err); + } + pub fn acknowledgeShell(p: *Pardes, id: usize, executable: []const u8, prompt_marks: bool) void { + const taped = tape.enter(p, .{ .acknowledge_shell = .{ .id = id, .executable = executable, .prompt_marks = prompt_marks } }); + defer tape.leave(p, taped); if (id < MAX_PANES) if (p.panes[id]) |pane| { ctlfs.pty.shellGone(p, pane, true); // a respawn replaced whatever ran pane.shell_failed = false; @@ -5500,8 +5617,14 @@ pub const Pardes = struct { p.settings.shell.pending = false; } + /// A window's font, asked and told (this and the three below): in every + /// hosted build, not only a window's, as only a window's host calls + /// them and a terminal's replica of a window's session must step as + /// the window does. pub fn takeFontRequest(p: *Pardes) ?[]const u8 { - if (comptime !font_picker) return null; + if (comptime !hosted) 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; @@ -5515,7 +5638,9 @@ pub const Pardes = struct { effective_size_hundredths: u16, unit: config.Runtime.FontSizeUnit, ) bool { - if (comptime !font_picker) return false; + if (comptime !hosted) 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; @@ -5530,7 +5655,9 @@ pub const Pardes = struct { effective_size_hundredths: u16, unit: config.Runtime.FontSizeUnit, ) bool { - if (comptime !font_picker) return false; + if (comptime !hosted) 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, @@ -5546,7 +5673,9 @@ pub const Pardes = struct { } pub fn rejectFont(p: *Pardes) void { - if (comptime !font_picker) return; + if (comptime !hosted) 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; @@ -5573,11 +5702,92 @@ pub const Pardes = struct { /// Something changed the core without going through `update` -- a watched /// file reloading under it, a theme file rewritten on disk. `pump` draws /// only when it has a reason to, and this is the reason. + /// A view of its own for a new client (a second window, a terminal + /// `pardes --attach`ed), as the live one is laid out; null at + /// views.max. Not live until `toView`. + pub fn openView(p: *Pardes) ?u8 { + const taped = tape.enter(p, .open_view); + defer tape.leave(p, taped); + // Every view taken: one kept for a client that has not come back + // for it (views.away) goes first. ponytail: no timer lets one go; + // until its place is wanted it costs a parked slot, and a terminal + // it sized last keeps that size until another view types into it. + if (@popCount(p.views_open) == views.max and p.views_away != 0) { + views.close(p, @ctz(p.views_away)); + p.sync(); + } + // What was queued since the last pump (a leaving client's view + // closed, a 9P request's step) done first, as every client of the + // tape does it here: a join dumps the session next, and a core + // loaded from a dump has no queue (Replica.initDump). + p.settle(); + p.needs_frame = true; + return views.open(p); + } + + /// The client of view `k` gone: its view goes, the others stay. The + /// last one stays the session's own. + pub fn closeView(p: *Pardes, k: u8) void { + const taped = tape.enter(p, .{ .close_view = k }); + defer tape.leave(p, taped); + views.close(p, k); + p.sync(); + // What its sync queued (a terminal it sized, sized again) done here, + // in its own unit on every side: the session's next pump is another + // unit, and a replica takes a copy only of a core with nothing + // queued (rollback.Copy.take). + p.settle(); + } + + /// The last client of a session no one else watches gone: its view + /// goes, and the session's own is laid out as it was (views.closeKeeping), + /// which the client's rejoin copies. Settled as `closeView` is. + pub fn leaveView(p: *Pardes, k: u8) void { + const taped = tape.enter(p, .{ .leave_view = k }); + defer tape.leave(p, taped); + views.closeKeeping(p, k); + p.sync(); + p.settle(); + } + + /// The client of view `k` gone, to join again for it (an Upgrade's + /// rejoin, a divergence's): its view kept as it is (views.away). + pub fn awayView(p: *Pardes, k: u8) void { + const taped = tape.enter(p, .{ .away_view = k }); + defer tape.leave(p, taped); + views.away(p, k); + } + + /// A client back for view `k`, kept for it (`awayView`): its own again, + /// as it left it; false when it was let go meanwhile. Settled as + /// `openView` is, for the join's dump next. + pub fn rejoinView(p: *Pardes, k: u8) bool { + const taped = tape.enter(p, .{ .rejoin_view = k }); + defer tape.leave(p, taped); + if (!views.isAway(p, k)) return false; + p.views_away &= ~(@as(u8, 1) << @intCast(k)); + p.settle(); + p.needs_frame = true; + return true; + } + + /// Into view `k`, before the input its client sent. + pub fn toView(p: *Pardes, k: u8) void { + if (k == p.view) return; + const taped = tape.enter(p, .{ .to_view = k }); + defer tape.leave(p, taped); + views.to(p, k); + } + pub fn invalidate(p: *Pardes) void { + const taped = tape.enter(p, .invalidate); + defer tape.leave(p, taped); p.needs_frame = true; } pub fn reloadWatchedFile(p: *Pardes, id: u8, bytes: []const u8) bool { + const taped = tape.enter(p, .{ .reload_watched_file = .{ .id = id, .bytes = bytes } }); + defer tape.leave(p, taped); p.invalidate(); look.invalidateLookHover(p, id); const applied = p.applyWatchedFileChanged(id, bytes); @@ -5594,6 +5804,8 @@ pub const Pardes = struct { } pub fn nextEffect(p: *Pardes) ?Effect { + const taped = tape.enter(p, .next_effect); + defer tape.leave(p, taped); p.refillPendingWrites(); if (p.effects_len == 0) { p.effects_head = 0; @@ -5730,6 +5942,8 @@ pub const Pardes = struct { /// on it, or written to it from now on, hears `error shell gone` /// rather than wait for a prompt that never comes. pub fn shellFailed(p: *Pardes, id: u8, err: anyerror) void { + const taped = tape.enter(p, .{ .shell_failed = .{ .id = id, .err = err } }); + defer tape.leave(p, taped); const pane = p.panes[id] orelse return; pane.shell_failed = true; ctlfs.pty.shellGone(p, pane, false); @@ -5751,6 +5965,8 @@ pub const Pardes = struct { /// A shell started again in a terminal whose shell runs (pty/ctl's /// exec) did not start: the host kept the running one, so only said. pub fn restartFailed(p: *Pardes, id: u8, err: anyerror) void { + const taped = tape.enter(p, .{ .restart_failed = .{ .id = id, .err = err } }); + defer tape.leave(p, taped); if (p.panes[id] == null) return; p.sayShellFailure(id, err); } @@ -5763,9 +5979,7 @@ pub const Pardes = struct { // The script is there; the program its `#!` names is not. var said: [320]u8 = undefined; var interp: [256]u8 = undefined; - var buf: [std.fs.max_path_bytes]u8 = undefined; - const Shell = if (comptime hosted) @import("host_io.zig").Shell else void; - const name: ?[]const u8 = if (comptime hosted) (if (Shell.find(pane.shell orelse p.shellBin(), &buf)) |f| Shell.missingInterpreter(f, &interp) else null) else null; + const name: ?[]const u8 = if (comptime hosted) tape.value(.interpreter, missingInterpreter, .{ pane.shell orelse p.shellBin(), &interp }) else null; p.reportFailure(id, if (name) |n| std.fmt.bufPrint(&said, "shell: interpreter {s} not found", .{n}) catch "shell: interpreter not found" else "shell: interpreter not found"); } else { p.reportError(id, "shell", err); @@ -5775,6 +5989,13 @@ pub const Pardes = struct { p.noteLateFailure(id); } + /// The program the shell's `#!` names that is not there, in `out`. + fn missingInterpreter(bin: []const u8, out: []u8) ?[]const u8 { + const Shell = @import("host_io.zig").Shell; + var buf: [std.fs.max_path_bytes]u8 = undefined; + return Shell.missingInterpreter(Shell.find(bin, &buf) orelse return null, out); + } + /// A Save makes the directories its file goes in, and any above them, /// first: one rule, for the pane's own name and `Save path` alike. A /// directory it cannot make leaves the write to fail and say why. @@ -5792,11 +6013,13 @@ pub const Pardes = struct { const local = if (comptime hosted) filesystem.localPath(dir) else null; const kind: ?std.Io.File.Kind = if (comptime hosted) (if (local) |l| exec.kindOf(l) else .directory) else .directory; const missing = err == error.FileNotFound or err == error.NotDir or kind != .directory; - const denied = missing and (if (comptime hosted) (if (local) |l| filesystem.deniedAbove(l) else false) else false); + const denied = missing and (if (comptime hosted) (if (local) |l| tape.value(.denied, filesystem.deniedAbove, .{l}) else false) else false); return .{ .dir = dir, .kind = kind, .missing = missing, .denied = denied }; } pub fn saveFailed(p: *Pardes, id: u8, path: []const u8, err: anyerror) void { + const taped = tape.enter(p, .{ .save_failed = .{ .id = id, .path = path, .err = err } }); + defer tape.leave(p, taped); if (p.panes[id]) |pane| if (pane.file) |*f| { // The `-%` spelling fs.zig already uses for "make this dirty". f.saved_revision = f.revision -% 1; @@ -5818,6 +6041,8 @@ pub const Pardes = struct { /// log, and the 9P write that asked for it fails with it, as a failed /// Save's does. pub fn dumpFailed(p: *Pardes, path: []const u8, err: anyerror) void { + const taped = tape.enter(p, .{ .dump_failed = .{ .path = path, .err = err } }); + defer tape.leave(p, taped); var what: [limits.host_path_cap + 8]u8 = undefined; const operation = std.fmt.bufPrint(&what, "Dump {s}", .{path}) catch "Dump"; // Into a DumpDir that is not there: said so, ENOENT, as a Save is; @@ -5860,6 +6085,8 @@ pub const Pardes = struct { } pub fn perform(p: *Pardes, e: Effect) void { + const taped = tape.enter(p, .{ .perform = e }); + defer tape.leave(p, taped); // A Save performed on one twin is every twin's (File.syncTwins). defer panes.File.syncTwins(p); const v = p.host.vtable; @@ -5981,11 +6208,6 @@ pub const Pardes = struct { }, .theme_file => |t| if (v.watch_theme) |f| f(p.host.ctx, t.generation, t.on), .dump_themes => |d| if (v.dump_themes) |f| f(p.host.ctx, d.pane), - .attach => |a| { - const name = a.name.slice(); - @memcpy(p.attach_buf[0..name.len], name); - p.attach_req = .{ .pane = a.pane, .name = p.attach_buf[0..name.len] }; - }, .detach => |d| if (v.detach) |f| f(p.host.ctx) else @@ -5995,32 +6217,36 @@ pub const Pardes = struct { } } - pub fn pump(p: *Pardes, h: Host) !void { - p.host = h; + pub fn pump(p: *Pardes, host: Host) !void { + p.host = host; + const taped = tape.enter(p, .pump); + defer tape.leave(p, taped); + // The host as the tape sees it, while it records. + const h = p.host; const v = h.vtable; if (v.wait_input) |f| { // Asleep until input or until core animation next needs a // frame; 0 is no timeout at all. // A render-time animation draws every loop: the wait only takes // what input is there. + // The clock read whether or not it is wanted: what a replica + // waits on is its own (a picture decoding wakes only a frame + // that draws it), and the tape has the same calls either way. + const now = if (v.now) |clock| clock(h.ctx) else p.now_ns; const timeout: u32 = if (p.continuous()) 1 else if (p.nextWake()) |due| wake: { - const now = if (v.now) |clock| clock(h.ctx) else p.now_ns; const ms = ((due -| now) + std.time.ns_per_ms - 1) / std.time.ns_per_ms; break :wake @intCast(std.math.clamp(ms, 1, std.math.maxInt(u32))); } else 0; f(h.ctx, timeout); } + // Detached, nobody's key dismisses a message: they go on the clock, + // here in the step, where the clock read is taped (the host's wait + // did it, untaped, and a replay kept a message its session had let + // go). + Messages.expireUnattended(p); p.frames.mark_start = FrameStats.nowNs(); if (v.now) |clock| p.advance(clock(h.ctx)); - // What a 9P open wrote in a row goes in once the writes pause. - ctlfs.pane.flushPausedBatch(p); - // ...and what a /pager open was written before its close. - ctlfs.ctl.fillClosedPagers(p); - // ...and the last line of an open closed with no newline after it. - ctlfs.runClosedLines(p); - while (p.nextQueued()) |ev| p.update(ev); - while (p.nextEffect()) |e| p.perform(e); - turn.bump(&turn.epoch); + p.settle(); // A quitting frame has already freed what it would draw. if (p.quit) return; if (v.poll_frame) |f| f(h.ctx); @@ -6034,12 +6260,19 @@ pub const Pardes = struct { // A pty streaming into an unwatched session spent most of its time // drawing what nobody looked at. if (v.watched) |f| if (!f(h.ctx)) return; - _ = p.frame_arena.reset(.{ .retain_with_limit = memory.limits.frame_kept }); - p.frames.mark_update = FrameStats.nowNs(); - p.frames.view = if (p.panes[p.active]) |pane| pane.scroll() else 0; - const surface = try p.render(p.frame_arena.allocator()); - p.frames.mark_render = FrameStats.nowNs(); - if (v.present) |f| f(h.ctx, surface); + // The other views first, each into its own window or terminal. + if (views.several(p)) try views.drawOthers(p, h); + // A replica client's view live (its input the last): its own + // process draws it. + if (p.undrawn & (@as(u8, 1) << @intCast(p.view)) == 0) { + _ = p.frame_arena.reset(.{ .retain_with_limit = memory.limits.frame_kept }); + p.frames.mark_update = FrameStats.nowNs(); + p.frames.view = if (p.panes[p.active]) |pane| pane.scroll() else 0; + const surface = try p.render(p.frame_arena.allocator()); + p.frames.mark_render = FrameStats.nowNs(); + if (v.present) |f| f(h.ctx, surface); + Stream.askAhead(p); + } // Settled before post_present: a shell ticks there, and what that // tick moves owes the next frame. const skipped = p.present_skipped; @@ -6051,6 +6284,32 @@ pub const Pardes = struct { p.frames.record(FrameStats.nowNs(), owed or p.continuous(), skipped); } + /// What a pump does between its wait and its frame: the queued inputs + /// and the effects. Also the session at a step boundary, taken now (an + /// Upgrade's dump, upgrade.zig). + pub fn settle(p: *Pardes) void { + // What a 9P open wrote in a row goes in once the writes pause. + ctlfs.pane.flushPausedBatch(p); + // ...and what a /pager open was written before its close. + ctlfs.ctl.fillClosedPagers(p); + // ...and the last line of an open closed with no newline after it. + ctlfs.runClosedLines(p); + while (p.nextQueued()) |ev| p.update(ev); + while (p.nextEffect()) |e| p.perform(e); + turn.bump(&turn.epoch); + } + + /// A replica client's input settled on the authority (src/replica.zig): + /// a pump that waits on nothing, reads no clock and draws nothing, so + /// the client's own core can apply the same at once and expect the + /// authority's tape of it to read the same. The session's own pump + /// draws it after. + pub fn step(p: *Pardes) void { + const taped = tape.enter(p, .step); + defer tape.leave(p, taped); + p.settle(); + } + /// One request of the control filesystem, from whichever thread has the /// turn (`pardes.turn`). Not an event: it neither sweeps nor resets /// anything the editor's own step may be in the middle of using, so it @@ -6058,6 +6317,8 @@ pub const Pardes = struct { /// that changes a pane costs a frame, which is why a round trip on a /// local socket costs microseconds and not a vsync. pub fn serveFs(p: *Pardes, req: ctlfs.Req) ctlfs.Reply { + const taped = tape.enter(p, .{ .serve_fs = req }); + defer tape.leave(p, taped); // The held write of an Edit whose commands run, asked again by a // retry of its park: still waiting, or its answer, never run twice. if (p.fs.edit_hold) |*h| if (h.names(req)) { @@ -6096,6 +6357,8 @@ pub const Pardes = struct { } pub fn update(p: *Pardes, ev: Event) void { + const taped = tape.enter(p, .{ .update = ev }); + defer tape.leave(p, taped); defer panes.File.syncTwins(p); defer p.reportFocus(); // A tick with nothing animating is the one event that cannot change @@ -6142,6 +6405,7 @@ pub const Pardes = struct { .tick => { Stream.step(p); Messages.advanceMessages(p); + for (p.panes) |slot| if (slot) |pane| if (pane.file) |*f| f.tables.step(pane.gpa, f); for (0..p.panes.len) |id| exec.flushReplEnter(p, id, false); }, else => {}, @@ -6210,6 +6474,7 @@ pub const Pardes = struct { .key => |key| { p.can_ask = true; defer p.can_ask = false; + p.typedInto(); p.handleKey(key); }, .mouse => |m| { @@ -6229,12 +6494,23 @@ pub const Pardes = struct { } } }, - .paste => |bytes| edit.applyPaste(p, bytes), + .paste => |bytes| { + p.typedInto(); + edit.applyPaste(p, bytes); + }, .command => |line| _ = p.executeBuiltinLine(p.active, line), .pinch => |scale| p.ov_pinch_scale = scale, .touch_scroll => |delta| p.ov_touch_scroll_delta = delta, - .focus => |focused| p.window_focused = focused, + .focus => |focused| { + p.window_focused = focused; + 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; @@ -6462,7 +6738,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). @@ -6527,7 +6803,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); } @@ -6707,11 +6983,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; @@ -6729,10 +7008,16 @@ pub const Pardes = struct { pub fn sessionDir(p: *Pardes) []const u8 { if (p.session_dir_len) |n| return p.session_dir[0..n]; if (comptime !hosted) return "/"; - if (std.c.getcwd(&p.session_dir, p.session_dir.len) == null) return "/"; - const n: u16 = @intCast(std.mem.indexOfScalar(u8, &p.session_dir, 0) orelse return "/"); - p.session_dir_len = n; - return p.session_dir[0..n]; + // The directory the session that recorded was started in. + const dir = tape.value(.cwd, processDir, .{&p.session_dir}) orelse return "/"; + std.mem.copyForwards(u8, &p.session_dir, dir); + p.session_dir_len = @intCast(dir.len); + return p.session_dir[0..dir.len]; + } + + fn processDir(buf: *[limits.host_path_cap]u8) ?[]const u8 { + if (std.c.getcwd(buf, buf.len) == null) return null; + return buf[0 .. std.mem.indexOfScalar(u8, buf, 0) orelse return null]; } /// The directory a word run from pane `id`'s text or tag runs in, or, @@ -7075,6 +7360,8 @@ pub const Pardes = struct { /// What was said of a failure just now on pane `id` is also the waiting /// 9P write's (9p_io, `fs.late_failure`). pub fn noteLateFailure(p: *Pardes, id: usize) void { + const taped = tape.enter(p, .{ .note_late_failure = id }); + defer tape.leave(p, taped); // Said by reportFailure just now: its words fitted whole, the // reason kept; else what the message row has. const said = if (p.fs.said_at == p.fs.failures and p.fs.said_len > 0) @@ -7250,9 +7537,11 @@ pub const Pardes = struct { // ---- dumb undo/redo: whole-state snapshots, one per edit op ---- pub fn acknowledgePanelPresentation(p: *Pardes, tracks: []const animation.Track) void { + const taped = tape.enter(p, .{ .acknowledge_panel_presentation = tracks }); + defer tape.leave(p, taped); p.presentation.acknowledge(p, tracks); if (p.pointer_inside and p.drag != .none) { - if (p.presentation.pointer(p.screen_w, p.screen_h, p.pointer_raw_col, p.pointer_raw_row)) |mapped| { + if (p.pointerCell(p.pointer_raw_col, p.pointer_raw_row)) |mapped| { p.hover_col = mapped.col; p.hover_row = mapped.row; mouse.dragUpdate(p, mapped.col, mapped.row, p.pointer_body_hit); @@ -7261,6 +7550,14 @@ pub const Pardes = struct { look.refreshLookHoverFromRaw(p); } + /// The cell of the session's grid a pointer at this cell of the frame + /// is over, seen through the frame (a pane sliding in): the recording + /// session's answer, whose frames these were (src/tape.zig). Null over + /// a pane on its way out. + pub fn pointerCell(p: *const Pardes, col: u16, row: u16) ?Presentation.CellPosition { + return tape.value(.pointer, Presentation.pointer, .{ &p.presentation, p.screen_w, p.screen_h, col, row }); + } + pub fn abandonPanelAnimations(p: *Pardes) void { p.presentation.cancel(); look.cancelLookHover(p); @@ -7269,9 +7566,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 { @@ -7442,10 +7755,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. @@ -7545,12 +7860,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; @@ -7568,6 +7884,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; @@ -7629,6 +7946,7 @@ pub const Pardes = struct { tagline.exitHeader(p); } p.reapPanes(); + if (views.several(p)) views.show(p); layout.compute(p); p.presentation.sync(p); p.trackJump(); @@ -7638,7 +7956,7 @@ pub const Pardes = struct { // hands it back to its body, and a name drafted there is dropped. if (id != p.active or p.header_focus) { pane.focus = .body; - if (pane.prompt == .name) pane.closePrompt(); + if (pane.prompt == .name and pane.prompt_view == p.view) pane.closePrompt(); } // A sweep over the tag is the tag's while it has the keyboard. const swept = pane.sel[sel_slot]; @@ -7656,6 +7974,10 @@ pub const Pardes = struct { state.reply_len = 0; }; const r = p.rects[id]; + // The session's part of the pane's view geometry (File.geometry), + // and its context declarations. + if (pane.file) |*f| panes.File.refreshContext(p, pane, f); + pane.view = .{ .wrap = p.settings.wrap, .layered = p.settings.tree_context_tag_style, .body_h = p.row_metrics.body_h, .tagline_h = p.row_metrics.tagline_h, .rect_h = r.h }; // The tag takes a row per line, leaving the body one row if it // had any; a folded pane shows its first line only. // Measured on the stack: this runs on every event, and not @@ -7712,7 +8034,9 @@ pub const Pardes = struct { // A terminal's pty follows its pane down to a row, whatever the // resize; only a folded one keeps the size it had, and one not // placed yet the grid it was made with. - if ((cols != pane.cols or rows != pane.rows) and (r.h > pane.tag_rows or (pane.isTerminal() and !pane.collapsed and r.h > 0))) { + if ((cols != pane.cols or rows != pane.rows) and (r.h > pane.tag_rows or (pane.isTerminal() and !pane.collapsed and r.h > 0)) and + (!pane.isTerminal() or p.sizes(pane))) + { // doc panes have no pty/emulator grid to reflow; just record // the size so bodyText renders the right number of rows if (pane.isTerminal()) { @@ -7725,15 +8049,19 @@ pub const Pardes = struct { pane.rows = rows; if (pane.file) |*file| file.syntax_dirty = true; } + pane.pan = panes.terminal.panFor(p, pane, r); // A directory pane's entries follow its width, as acme's // columns do (Dir.fit). if (pane.file) |file| if (file.listing != null and r.h > pane.tag_rows) panes.Dir.fit(p, pane, pane.cols); panes.terminal.releasePendingCommandIfReady(p, id, pane); + // Which bands a pane shows is the step's, as its geometry is: + // what is drawn under them, and where a click lands, read it. + Messages.collectNotices(p, pane, r, id); // The greeting `ls` of a new terminal in a directory is typed at // its shell's FIRST prompt, or never: typed later it would land // in whatever runs then, or in the middle of a line someone // typed (panes.terminal.greeting). - if (pane.greet and pane.isTerminal() and p.resize_count > 0) switch (panes.terminal.greeting(pane)) { + if (pane.greet and pane.isTerminal() and p.resize_count > 0) switch (tape.value(.prompt, panes.terminal.greeting, .{pane})) { .wait => {}, .never => pane.greet = false, .now => { @@ -7743,6 +8071,28 @@ pub const Pardes = struct { }, }; } + // A header's caret kept in its view, as a pane's is: the step's, not + // the frame's (paintHeaders draws what this leaves). + tagline.revealHeader(p); + } + + /// The view typing goes into is the one its terminal is sized for + /// (`sizes`). + fn typedInto(p: *Pardes) void { + if (p.panes[p.active]) |pane| pane.sized_by = p.view; + } + + /// Whether the live view sizes terminal `pane`: a terminal shown at two + /// sizes takes the size of the view that typed into it last, and any + /// view's once that one is gone. The others show it at that size, a + /// shorter one passed down to its cursor (`Pane.pan`, terminal.panFor). + // ponytail: a panned view's pointer reports to a terminal's program and + // its kitty images are placed as the unpanned rows are. + fn sizes(p: *Pardes, pane: *Pane) bool { + if (pane.sized_by == p.view) return true; + if (views.isOpen(p, pane.sized_by)) return false; + pane.sized_by = p.view; + return true; } pub fn theme(p: *const Pardes) *const Theme { @@ -7848,6 +8198,8 @@ pub const Pardes = struct { /// the look-hover delay) is jumped to its end in one step and drawn /// once. Idle, time is not banked: the next animation starts from now. pub fn advance(p: *Pardes, now_ns: u64) void { + const taped = tape.enter(p, .{ .advance = now_ns }); + defer tape.leave(p, taped); // The first time a shell's clock is seen, core time starts there. const started = p.clock_started; p.clock_started = true; @@ -7855,7 +8207,10 @@ pub const Pardes = struct { if (!started) p.stepped_ns = now_ns; const frame = animation.frame_ns; var moving: u32 = 0; - while (p.nextWake()) |due| { + // The session's ticks are the recording session's: a picture still + // decoding or a fade still moving asks for frames the way a message + // waiting to go does, and a replica that draws nothing has none. + while (tape.value(.wake, nextWake, .{p})) |due| { if (due > now_ns) break; // Only waiting until `due`: its counters move there at once. const held = (due - p.stepped_ns) / frame; @@ -7905,18 +8260,16 @@ pub const Pardes = struct { return p.haptic; } + /// A frontend's tag hit, if what it names is still there: resolved on + /// the place it carries (Layer.Place), not on this process's frame. pub fn reprojectTagHit(p: *const Pardes, tag_hit: TagHit) ?TagHit { - for (p.surface.tagLayers()) |*layer| { - if (layer.rows == 0 or layer.kind != tag_hit.kind or layer.id != tag_hit.id or layer.serial != tag_hit.serial) continue; - if (layer.kind == .pane) { - if (layer.id >= p.panes.len) return null; - const pane = p.panes[layer.id] orelse return null; - if (pane.serial != layer.serial) return null; - } - if (layer.kind == .column and (layer.id >= p.ncol or p.col_serial[layer.id] != layer.serial)) return null; - return layer.tagHit(tag_hit.pixel_x, tag_hit.pixel_y, @floatFromInt(tag_hit.metrics.body_w), @floatFromInt(tag_hit.metrics.body_h), @floatFromInt(tag_hit.metrics.tagline_w), @floatFromInt(tag_hit.metrics.tagline_h)) orelse continue; + if (tag_hit.kind == .pane) { + if (tag_hit.id >= p.panes.len) return null; + const pane = p.panes[tag_hit.id] orelse return null; + if (pane.serial != tag_hit.serial) return null; } - return null; + if (tag_hit.kind == .column and (tag_hit.id >= p.ncol or p.col_serial[tag_hit.id] != tag_hit.serial)) return null; + return Layer.tagAgain(tag_hit); } /// The pane's first body row: under the tag when it is on top, over it @@ -7936,12 +8289,9 @@ pub const Pardes = struct { return layer.capacity(p.row_metrics); } - pub fn reprojectBodyHit(p: *const Pardes, body_hit: Mouse.BodyHit) ?Mouse.BodyHit { - for (&p.surface.body_layers) |*layer| { - if (layer.rows == 0 or layer.serial != body_hit.serial) continue; - return layer.bodyHit(body_hit.pixel_x, body_hit.pixel_y, @floatFromInt(body_hit.metrics.body_w), @floatFromInt(body_hit.metrics.body_h), @floatFromInt(body_hit.metrics.tagline_w), @floatFromInt(body_hit.metrics.tagline_h)); - } - return null; + /// A frontend's body hit, resolved on the place it carries. + pub fn reprojectBodyHit(_: *const Pardes, body_hit: Mouse.BodyHit) ?Mouse.BodyHit { + return Layer.bodyAgain(body_hit); } // ---- render: build the canonical surface (draw.zig) ---- @@ -8204,8 +8554,12 @@ test "a prompt chip is a band with its caret, still on the grid, and only the ch // Inside it is chrome: mapped as body it would land on Sel row 0, which is // the TAG row, so a sweep there would highlight the tagline instead. + // The sweep closed the prompt, and its chip with it: open it again. pane.clearPointerSelection(0); pane.sel[0] = .{}; + p.startPrompt(pane, &pane.body, .{ .search = "/" }); + p.sync(); + try std.testing.expectEqual(left, pane.notices.left[0]); p.update(.{ .mouse = .{ .button = .left, .kind = .press, .col = r.x + r.w - 3, .row = row } }); p.update(.{ .mouse = .{ .button = .left, .kind = .drag, .col = r.x + r.w - 2, .row = row } }); p.update(.{ .mouse = .{ .button = .left, .kind = .release, .col = r.x + r.w - 2, .row = row } }); @@ -8591,6 +8945,9 @@ test "Esc back into a file leaves its view where it was" { const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .cols = 80, .rows = 24, .file = "src/memory.zig" }); defer p.deinit(); + // Rows are lines: the centring below counts lines, and a wrapped line + // above the cursor would push it out of the view it centres. + p.settings.wrap = false; p.update(.{ .resize = .{ .cols = 80, .rows = 24 } }); p.update(.{ .key = .{ .cp = 'n', .alt = true } }); // a shell under the doc const shell = p.active; @@ -8709,6 +9066,21 @@ test "Shift-Esc backs out to the previous pane in every mode, never into raw" { try std.testing.expect(p.active != 0); } +test "Esc in a column or the workspace tag gives the keyboard back to a pane, as Shift-Esc does" { + if (platform == .web) return; + const p = try Pardes.init(std.testing.allocator, .{ .cols = 80, .rows = 24, .file = "mise.toml" }); + defer p.deinit(); + p.update(.{ .key = .{ .cp = 'n', .alt = true } }); // a pane to go back to + for ([_]?usize{ 0, null }) |column| { + tagline.enterHeader(p, column); + try std.testing.expect(tagline.focusedHeader(p) != null); + const was = p.active; + p.update(.{ .key = .{ .cp = Key.escape } }); + try std.testing.expect(tagline.focusedHeader(p) == null); + try std.testing.expect(p.active != was); + } +} + test "window mode moves an outline and focuses it on Enter, Esc or a label" { const p = try Pardes.init(std.testing.allocator, .{ .cols = 120, .rows = 30 }); defer p.deinit(); @@ -9042,7 +9414,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)}; |
