From 60e956c332bc0aca49ea92e59fa1d1ec3ab418c2 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Thu, 19 Nov 2026 11:54:29 -0300 Subject: runtime: ONE session loop, which the terminal's and the window's sessions run (the reorganisation's runners, step 10c, its first part; the design round's rule L): runtime/session.zig's Loop(Frontend) holds what a session is apart from its frontend (its allocators and workers, its frame record, its core from an upgrade, a dump or new, the prompt files, the 9P listener, its replica clients' Peers) and runs it from start to end (the first effects, an upgrade's shells, the pump, the clients' boundary, an Upgrade, the daemon's notes, a Restore; the listener ended first, then the clients, the frontend's devices, the prompt files, the core), over a frontend of eleven calls (options, open, close, resumePtys, start, sent, upgradeAsked, note, watched, restoring, restored: each a difference the two still have, their devices being step 11's), and the two localSessions (193 and 189 lines) are now each frontend's Own (177 and 167); what differed is one behaviour now or a value the frontend gives: the end's order is the window's (the clients let go before the devices stop, where the terminal stopped its devices first), a session that quit does not restore in the same pass (the terminal's lacked the test), a Restore's new core is given the host by the session (no effect: pump sets it); Peers is the loop's, each Shell points at it (a client's at an empty one, as its value was); no other behaviour changes. Gate: tui core-test 837/980 (143 skipped), shell-test 1015/1018, term-test 15/15, pane-test 183/184, kitty-test 45/45, behaviour-test 275/275 and --replay 275/275, process-test lspcomplete and lspcompletemoved (the base's; winch and headersweep-restored failed once and passed on their retry); gui unit-test 1613/1617 with the base's BaselineHarnessMismatch; replicas --clients 5 (the soak's own session stand-in still) diverged 0, unequal 0, quiet checks 526/0, 550/0, 811/0, unlisted 0; daemon.py plain, --far, --window-clients, --upgrade from pardes-tree's pfx-base to this and back, --games (once failed at load 10, a client's keys stopped at a kind's pane; then the base and this alternated three times each at load 2-3, all pass); the macOS library for Linux and aarch64-macos and the FreeBSD tui configure; rollback-bench runs; the start to the first frame (the startup kit's start.py, ReleaseFast, no addons, medium.zig, the base against this): the terminal 54.3/53.4/53.4M -> 53.4/54.3/53.4M instructions, best of 25 8.4 -> 8.4 ms; the window offscreen 396/394/404M -> 395/401/397M, best of 10 229 -> 222 ms; gate-w run4-1 against tree1: frames 77/77 byte-identical in Debug, unit-test 1613/1617 (no failure the base has not), the alternated windows' pictures identical in all 10 runs, corpus2x -0.118% (noise 0.092%), perfops 97 counts within 0.1% (largest image-frame on large +0.026%) Co-Authored-By: Claude Opus Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T --- dev/gui/gui.zig | 342 +++++++++++++++++++++++++++----------------------------- 1 file changed, 163 insertions(+), 179 deletions(-) (limited to 'dev/gui') diff --git a/dev/gui/gui.zig b/dev/gui/gui.zig index 909c83c6..c4eba5db 100644 --- a/dev/gui/gui.zig +++ b/dev/gui/gui.zig @@ -31,6 +31,7 @@ const ninep_io = @import("runtime").ninep_io; const daemon = @import("runtime").daemon; const client_loop = @import("runtime").client; +const session_loop = @import("runtime").session; const upgrade = @import("runtime").upgrade; const replica = @import("core").replica; const tracy = @import("core").tracy; @@ -984,7 +985,8 @@ fn runNative(init: std.process.Init, opts_in: pardes.Options, detached: bool, di if (!test_mode and !c.SDL_SetWindowHitTest(window, hitTest, &g)) log.warn("SDL_SetWindowHitTest: {s}", .{c.SDL_GetError()}); if (dial) |to| return clientSession(init, &g, opts_in, test_mode, to); - try localSession(init, &g, opts_in, test_mode, detached); + var own: Own = .{ .g = &g, .test_mode = test_mode, .detached = detached }; + try session_loop.Loop(Own).run(init, opts_in, &own); } /// Detach: the window closed (and with it its swapchain or renderer); the @@ -1019,195 +1021,173 @@ fn reopenWindow(g: *Gui) bool { return true; } -fn localSession( - init: std.process.Init, +/// The session's own window (`runNative`): the frontend of the session loop +/// (runtime/session.zig), its devices the `Shell`'s, which draws it. +const Own = struct { g: *Gui, - opts_in: pardes.Options, test_mode: bool, detached: bool, -) !void { - const io = init.io; - const gpa = init.gpa; - const allocs = pardes.memory.init(gpa); - defer pardes.memory.deinit(); - host_io.startWorkers(allocs); - defer host_io.stopWorkers(); - var opts = opts_in; - opts.addons = pardes.Addon.scan(); - // Its frame timings, the window's to write as it draws (Pardes.frames). - var frames: pardes.FrameStats = .{}; - opts.frames = &frames; - opts.image_allocator = allocs.image; - opts.tree_sitter_allocator = allocs.tree_sitter; - opts.frame_allocator = allocs.frame; - var pw: c_int = 0; - var ph: c_int = 0; - if (opts.load_path != null) { - _ = c.SDL_GetWindowSizeInPixels(g.window, &pw, &ph); - opts.cols = @intCast(@max(1, @divTrunc(@as(u32, @intCast(@max(pw, 1))), g.cell_w))); - opts.rows = @intCast(@max(1, @divTrunc(@as(u32, @intCast(@max(ph, 1))), g.cell_h))); - } - var core = if (upgrade.resumed) |*rec| - try upgrade.load(gpa, allocs.pardes, opts, rec) - else if (opts.load_path) |lp| blk: { - const bytes = try @import("core").filesystem.readFile(gpa, lp); - defer gpa.free(bytes); - break :blk try pardes.dump.initFromDump(allocs.pardes, opts, bytes); - } else try pardes.Pardes.init(allocs.pardes, opts); - defer core.deinit(); - g.hit_core = core; - defer g.hit_core = null; - core.view().frontend.windowed = true; - core.view().frontend.native_images = true; - core.view().frontend.native_image_patches = true; - observeGuiFont(g, core); - syncTaglineFont(g, core); - - var prompt_rcs = host_io.Shell.prepare(); - defer prompt_rcs.deinit(); + ptys: [pardes.MAX_PANES]?Pty = @splat(null), + gens: [pardes.MAX_PANES]u32 = @splat(0), + queue: Queue = undefined, + pipe_tasks: PipeTasks = .{}, + inotify_fd: c_int = -1, + watch_reader: ?std.Thread = null, + watch_stop: [2]c_int = .{ -1, -1 }, + watches: file_watch.Table = @splat(null), + shell: Shell = undefined, + + const Session = session_loop.Loop(Own); + + /// A dump's layout is laid out at the window's size. + pub fn options(o: *Own, opts: *pardes.Options) void { + if (opts.load_path == null) return; + var pw: c_int = 0; + var ph: c_int = 0; + _ = c.SDL_GetWindowSizeInPixels(o.g.window, &pw, &ph); + opts.cols = @intCast(@max(1, @divTrunc(@as(u32, @intCast(@max(pw, 1))), o.g.cell_w))); + opts.rows = @intCast(@max(1, @divTrunc(@as(u32, @intCast(@max(ph, 1))), o.g.cell_h))); + } - 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, - .wake_fn = sdlWake, - }; - defer { - if (queue.lsp_task) |*task| task.future.cancel(io); + pub fn open(o: *Own, l: *Session) !pardes.Host { + const g = o.g; + const core = l.core; + g.hit_core = core; + core.view().frontend.windowed = true; + core.view().frontend.native_images = true; + core.view().frontend.native_image_patches = true; + observeGuiFont(g, core); + syncTaglineFont(g, core); + o.queue = .{ + .io = l.io, + .gpa = l.gpa, + .lsp_allocator = l.allocs.lsp, + .wake_fn = sdlWake, + }; + o.inotify_fd = file_watch.init(true); + o.shell = .{ + .core = core, + .gui = g, + .io = l.io, + .gpa = l.gpa, + .lsp_allocator = l.allocs.lsp, + .prompt_rcs = &l.prompt_rcs, + .ptys = &o.ptys, + .gens = &o.gens, + .queue = &o.queue, + .pipe_tasks = &o.pipe_tasks, + .inotify_fd = o.inotify_fd, + .watches = &o.watches, + .fs = l.fs, + .test_mode = o.test_mode, + .test_clock = if (o.test_mode) host_io.testClock() else null, + .test_hz = if (std.c.getenv("PARDES_TEST_HZ")) |hz| @max(1, std.fmt.parseInt(u64, std.mem.span(hz), 10) catch 60) else 60, + .peers = &l.peers, + }; + // A virtual clock never blinks: goldens and feel series hold still. + g.no_blink = o.shell.test_clock != null; + frame_probe = &l.frames; + frame_capture_dir = if (std.c.getenv("PARDES_FRAMES_CAPTURE")) |dir| std.mem.span(dir) else null; + const host = o.shell.host(); + core.host = host; + pardes.Kind.drawer = .{ .ctx = &o.shell, .go = kindDraw }; + l.peers.wake = sdlWake; + l.peers.detached = o.detached; + return host; + } + + pub fn close(o: *Own, l: *Session) void { + const io = l.io; + o.shell.fs = null; + host_io.setExitWake(null, null); + pardes.lsp.setStatusSink(null, null); + pardes.Kind.drawer = null; + o.shell.shutdownPtys(); + o.shell.job_tasks.cancelAll(io); + if (o.inotify_fd >= 0) { + if (o.watch_reader) |thread| { + _ = host_io.writeFd(o.watch_stop[1], "x"); + thread.join(); + } + for (o.watch_stop) |fd| if (fd >= 0) { + _ = libc.close(fd); + }; + file_watch.stop(o.inotify_fd); + _ = libc.close(o.inotify_fd); + o.inotify_fd = -1; + } + o.pipe_tasks.cancelAll(io); + if (o.queue.lsp_task) |*task| task.future.cancel(io); // Its worker may be waiting on the queue for room. - core.stream.cancelTask(); - queue.deinit(); + l.core.stream.cancelTask(); + o.queue.deinit(); + o.g.hit_core = null; } - var pipe_tasks: PipeTasks = .{}; - defer pipe_tasks.cancelAll(io); - var inotify_fd: c_int = file_watch.init(true); - var watch_reader: ?std.Thread = null; - var watch_stop: [2]c_int = .{ -1, -1 }; - defer if (inotify_fd >= 0) { - if (watch_reader) |thread| { - _ = host_io.writeFd(watch_stop[1], "x"); - thread.join(); - } - for (watch_stop) |fd| if (fd >= 0) { - _ = libc.close(fd); + + pub fn resumePtys(o: *Own, rec: *const upgrade.Record) void { + o.shell.resumePtys(rec); + } + + pub fn start(o: *Own, l: *Session) !void { + for (&o.ptys, 0..) |*slot, id| if (slot.*) |*pt| { + pt.reader = try o.queue.startReader(.{ .handle = pt.fd, .flags = .{ .nonblocking = false } }, @intCast(id), o.gens[id]); }; - file_watch.stop(inotify_fd); - _ = libc.close(inotify_fd); - inotify_fd = -1; - }; - var watches: file_watch.Table = @splat(null); - var fs = ninep_io.start(io, gpa, core); - defer if (fs) |f| f.deinit(gpa); + if (o.inotify_fd >= 0) { + o.watch_stop = try stopPipe(); + o.watch_reader = try std.Thread.spawn(.{}, watchThread, .{ o.inotify_fd, o.watch_stop[0], &o.queue }); + } + if (l.fs) |f| try f.watch(&o.queue, wakeFs); + + _ = c.SDL_StartTextInput(o.g.window); + // An upgraded session's window, its view's again. + if (upgrade.resumed) |*rec| if (!rec.fresh and !o.detached) o.shell.resumeWindow(); + + if (o.test_mode) setStdinRaw() catch {}; + o.shell.threads_ok = true; + pardes.lsp.setStatusSink(&o.queue, Queue.lspStatus); + host_io.setExitWake(&o.queue, Queue.wakeForExit); + if (o.detached) { + o.shell.closeTheWindow(); + // Nothing else may wake the first wait. + l.watch(); + } + } - var shell: Shell = .{ - .core = 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 = inotify_fd, - .watches = &watches, - .fs = fs, - .test_mode = test_mode, - .test_clock = if (test_mode) host_io.testClock() else null, - .test_hz = if (std.c.getenv("PARDES_TEST_HZ")) |hz| @max(1, std.fmt.parseInt(u64, std.mem.span(hz), 10) catch 60) else 60, - }; - defer shell.job_tasks.cancelAll(io); - defer shell.shutdownPtys(); - // A virtual clock never blinks: goldens and feel series hold still. - g.no_blink = shell.test_clock != null; - frame_probe = &frames; - frame_capture_dir = if (std.c.getenv("PARDES_FRAMES_CAPTURE")) |dir| std.mem.span(dir) else null; - const host = shell.host(); - core.host = host; - pardes.Kind.drawer = .{ .ctx = &shell, .go = kindDraw }; - defer pardes.Kind.drawer = null; - shell.peers = .{ .gpa = gpa, .io = io, .name = daemon.name(), .wake = sdlWake, .detached = detached }; - 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 - // directory to adopt them in. - if (upgrade.resumed) |*rec| { - shell.resumePtys(rec); - while (core.nextEffect()) |e| core.perform(e); - } - for (&ptys, 0..) |*slot, id| if (slot.*) |*pt| { - pt.reader = try queue.startReader(.{ .handle = pt.fd, .flags = .{ .nonblocking = false } }, @intCast(id), gens[id]); - }; - if (inotify_fd >= 0) { - watch_stop = try stopPipe(); - watch_reader = try std.Thread.spawn(.{}, watchThread, .{ inotify_fd, watch_stop[0], &queue }); + pub fn sent(_: *Own) void {} + + pub fn upgradeAsked(o: *Own) void { + if (o.shell.upgrade_asked) |pane| o.shell.upgradeNow(pane); } - if (fs) |f| try f.watch(&queue, wakeFs); - _ = c.SDL_StartTextInput(g.window); - // An upgraded session's window, its view's again. - if (upgrade.resumed) |*rec| if (!rec.fresh and !detached) shell.resumeWindow(); + pub fn note(o: *Own, n: daemon.Note) void { + deliverNote(&o.shell, n); + } - if (test_mode) setStdinRaw() catch {}; - shell.threads_ok = true; - pardes.lsp.setStatusSink(&queue, Queue.lspStatus); - defer pardes.lsp.setStatusSink(null, null); - host_io.setExitWake(&queue, Queue.wakeForExit); - defer host_io.setExitWake(null, null); - if (detached) { - shell.closeTheWindow(); - // Nothing else may wake the first wait. - 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(&shell, deliverNote); - if (core.quit) break; // a session that ended does not restore into one - if (core.takeRestore()) |rp| blk: { - const nc = host_io.restoreCore(gpa, core, rp, &shell.peers, inotify_fd, &watches) orelse break :blk; - pipe_tasks.cancelAll(io); - queue.discardCompletions(); - // One view, the window's (host_io.restoreCore). - shell.gview = 0; - shell.stopPtys(); - g.cells.clearImages(); - g.prepared_images.clearRetainingCapacity(); - nc.view().frontend.native_images = true; - nc.view().frontend.native_image_patches = true; - nc.host = host; - if (fs) |f| f.reset(nc); - nc.view().frontend.windowed = true; - core.deinit(); - core = nc; - g.hit_core = nc; - shell.core = nc; - shell.surface = null; - observeGuiFont(g, core); - syncTaglineFont(g, core); - } + pub fn watched(o: *Own) session_loop.Watched { + return .{ .fd = o.inotify_fd, .table = &o.watches }; } - if (fs) |f| { - f.deinit(gpa); - fs = null; - shell.fs = null; + pub fn restoring(o: *Own, nc: *pardes.Pardes) void { + o.pipe_tasks.cancelAll(o.shell.io); + o.queue.discardCompletions(); + // One view, the window's (host_io.restoreCore). + o.shell.gview = 0; + o.shell.stopPtys(); + o.g.cells.clearImages(); + o.g.prepared_images.clearRetainingCapacity(); + nc.view().frontend.native_images = true; + nc.view().frontend.native_image_patches = true; + nc.view().frontend.windowed = true; } -} + + pub fn restored(o: *Own, l: *Session) void { + o.g.hit_core = l.core; + o.shell.core = l.core; + o.shell.surface = null; + observeGuiFont(o.g, l.core); + syncTaglineFont(o.g, l.core); + } +}; /// A window's loop as a client of a session elsewhere (runtime/client.zig), /// over the window (`Client`). @@ -1525,6 +1505,7 @@ fn clientSession(init: std.process.Init, g: *Gui, opts_in: pardes.Options, test_ var pipe_tasks: PipeTasks = .{}; var watches: file_watch.Table = @splat(null); const prompt_rcs: host_io.Shell.PromptFiles = .{}; + var no_peers: replica.Peers = .{}; var shell: Shell = .{ .core = start.r.core(), .gui = g, @@ -1540,6 +1521,7 @@ fn clientSession(init: std.process.Init, g: *Gui, opts_in: pardes.Options, test_ .watches = &watches, .test_mode = test_mode, .client = &window, + .peers = &no_peers, }; window.shell = &shell; pardes.Kind.drawer = .{ .ctx = &shell, .go = kindDraw }; @@ -2490,8 +2472,9 @@ const Shell = struct { /// This window a replica client of a session elsewhere (`runClient`). client: ?*Client = null, /// The session's replica clients (core/replica.zig), on sockets: views - /// of their own with no window here. - peers: replica.Peers = .{}, + /// of their own with no window here; the session loop's + /// (runtime/session.zig), a client's none. + peers: *replica.Peers, /// 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 (tui.zig's `mail_only`). @@ -8173,7 +8156,8 @@ test "a detached GUI authority follows terminal directory changes with no window const rcs: host_io.Shell.PromptFiles = .{}; var pipes: PipeTasks = .{}; var watches: file_watch.Table = @splat(null); - var shell: Shell = .{ .core = core, .io = io, .gpa = gpa, .lsp_allocator = gpa, .prompt_rcs = &rcs, .ptys = &ptys, .gens = &gens, .queue = &queue, .pipe_tasks = &pipes, .inotify_fd = -1, .watches = &watches }; + var no_peers: replica.Peers = .{}; + var shell: Shell = .{ .core = core, .io = io, .gpa = gpa, .lsp_allocator = gpa, .prompt_rcs = &rcs, .ptys = &ptys, .gens = &gens, .queue = &queue, .pipe_tasks = &pipes, .inotify_fd = -1, .watches = &watches, .peers = &no_peers }; defer shell.shutdownPtys(); const child = try host_io.forkShell(null, 0, &rcs, "/bin/sh", start, 24, 80); ptys[0] = .{ .fd = child.file.handle, .pid = child.pid, .serial = core.panes[0].?.serial }; -- cgit v1.3