diff options
Diffstat (limited to 'src')
| -rw-r--r-- | src/Output.zig | 22 | ||||
| -rw-r--r-- | src/builtins.zig | 58 | ||||
| -rw-r--r-- | src/builtins_json.zig | 13 | ||||
| -rw-r--r-- | src/config.zig | 2 | ||||
| -rw-r--r-- | src/detached/wire.zig | 35 | ||||
| -rw-r--r-- | src/draw.zig | 26 | ||||
| -rw-r--r-- | src/exec.zig | 8 | ||||
| -rw-r--r-- | src/gui/gui.zig | 573 | ||||
| -rw-r--r-- | src/main.zig | 27 | ||||
| -rw-r--r-- | src/ninep/ctl.zig | 38 | ||||
| -rw-r--r-- | src/ninep/tree.zig | 2 | ||||
| -rw-r--r-- | src/pardes.zig | 50 | ||||
| -rw-r--r-- | src/replica.zig | 310 | ||||
| -rw-r--r-- | src/tape.zig | 15 | ||||
| -rw-r--r-- | src/tty/tty.zig | 311 | ||||
| -rw-r--r-- | src/views.zig | 54 |
16 files changed, 1158 insertions, 386 deletions
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=<socket>:<session>` (and `<host>:<session>`, +/// 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 }); +} + +const Dial = struct { path: []const u8, session: []const u8, far: bool }; -fn runNative(init: std.process.Init, opts_in: pardes.Options, headless: bool) !void { +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=<where>:<session>`: 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=<name> ...the session called <name> (its --9p or \\ --detach name, else its pid) \\ --attach=<host>:<name> a client of session <name> 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=<where>:<name>`: 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=<where>:<name>` (`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 <here>:<there> <host>, 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=<file>: 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=<n>: 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=<file>: 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=<file>: 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=<n>: 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=<file>: 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 ---- |
