diff options
Diffstat (limited to 'dev')
| -rw-r--r-- | dev/gui/gui.zig | 448 | ||||
| -rw-r--r-- | dev/tui/tui.zig | 277 |
2 files changed, 339 insertions, 386 deletions
diff --git a/dev/gui/gui.zig b/dev/gui/gui.zig index a632f67a..66b7328d 100644 --- a/dev/gui/gui.zig +++ b/dev/gui/gui.zig @@ -30,6 +30,7 @@ const c_heap = @import("c_heap"); const ninep_io = @import("runtime").ninep_io; const daemon = @import("runtime").daemon; +const client_loop = @import("runtime").client; const upgrade = @import("runtime").upgrade; const replica = @import("core").replica; const tracy = @import("core").tracy; @@ -785,9 +786,7 @@ pub fn runClient(init: std.process.Init, opts: pardes.Options, path: []const u8, 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, detached: bool, dial: ?Dial) !void { +fn runNative(init: std.process.Init, opts_in: pardes.Options, detached: bool, dial: ?client_loop.Dial) !void { const gpa = init.gpa; const env = init.environ_map; @@ -1210,11 +1209,17 @@ fn localSession( } } -/// A window's link to a session elsewhere (`clientSession`): what the -/// window's input made, fed to the replica after each event, and what the +/// A window's loop as a client of a session elsewhere (runtime/client.zig), +/// over the window (`Client`). +const ClientLoop = client_loop.Loop(Client); +/// The session's own window's `present`, which the client's calls. +const presentShell = present; + +/// A window as a replica client's frontend (`clientSession`): what the +/// window's input made, fed to the loop after each event, and what the /// link's reader took off the stream. const Client = struct { - link: replica.Link, + loop: *ClientLoop = undefined, io: std.Io, gpa: std.mem.Allocator, /// The window's inputs since the last feed, their texts in `texts`. @@ -1224,11 +1229,26 @@ const Client = struct { lock: std.Io.Mutex = .init, inbox: std.ArrayListUnmanaged(replica.Said) = .empty, taken: std.ArrayListUnmanaged(replica.Said) = .empty, - ended: bool = false, + link_ended: bool = false, /// The size the window last posted while its view is not that size /// yet (the session has not taken it, or speculation stopped at it): /// posted once, not again each pass while it waits. posted: ?@FieldType(pardes.Event, "resize") = null, + /// The window, the shell its frames are drawn through, the input it + /// routes (its core this join's), and the client's joins. + g: *Gui = undefined, + shell: *Shell = undefined, + in: Input = undefined, + joins: *client_loop.Start = undefined, + test_mode: bool = false, + /// A frame presented this pass (the pointer is refreshed under it), the + /// last one owed again for its own motion or blink, why it joined + /// again shown in its title, and this pass's motion and blink. + drew: bool = false, + again_due: bool = false, + titled: bool = false, + moving: bool = false, + blink: ?Blink = null, fn deinit(cl: *Client) void { cl.pending.deinit(cl.gpa); @@ -1250,22 +1270,160 @@ const Client = struct { /// What the window's input made, applied at once and sent; what the /// window reads beside its frame (Gui.facts) as its view is now. - fn feed(cl: *Client, g: *Gui) void { - const r = cl.link.r; + fn feed(cl: *Client, l: *ClientLoop) void { + const r = l.link.r; for (cl.pending.items) |ev| { const predicted = r.echo.stats.predicted; - cl.link.input(ev); + l.input(ev); // PARDES_TEST_LATENCY: the input, and whether it shows at once // (applied, or its echo predicted), for the frame that shows it. latencyNote("I {d} {d} {d}\n", .{ r.next_seq - 1, monoNs(), @intFromBool(r.applied == r.pending.items.len or r.echo.stats.predicted > predicted) }); } - if (cl.pending.items.len > 0 and r.core().live == r.view) pardes.draw.facts(r.core(), &g.facts); + if (cl.pending.items.len > 0 and r.core().live == r.view) pardes.draw.facts(r.core(), &cl.g.facts); cl.pending.clearRetainingCapacity(); _ = cl.texts.reset(.retain_capacity); } + /// A join's first: the window's tables on its core, why it joined + /// again in its title, what it is. + pub fn start(cl: *Client, l: *ClientLoop) void { + const g = cl.g; + const core = l.link.r.core(); + g.session_font_request = null; + cl.shell.core = core; + cl.shell.gview = cl.joins.joined.view; + cl.shell.surface = null; + g.hit_core = core; + g.frame = null; + cl.posted = null; + cl.link_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. + cl.titled = l.link.notice_len > 0; + if (cl.titled) { + var title: [260]u8 = undefined; + _ = c.SDL_SetWindowTitle(g.window, std.fmt.bufPrintSentinel(&title, "pardes: {s}", .{l.link.notice()}, 0) catch "pardes"); + log.warn("{s}", .{l.link.notice()}); + } + cl.in = .{ .core = core, .shell = cl.shell, .client = cl }; + // What it is, then its size (`own`), are its view's first inputs. + l.input(.{ .frontend = .{ .windowed = true, .native_images = true, .native_image_patches = true } }); + cl.drew = false; + cl.again_due = false; + } + + /// The window's own work over the frame it shows (Gui.facts): the + /// session's font followed, a touchpad's fraction, the tagline's face, + /// its size posted, the pointer under a frame that moved, the + /// timedemo's and the test feed's steps. The test feed's end ends it. + pub fn own(cl: *Client, l: *ClientLoop) bool { + const g = cl.g; + const gpa = cl.gpa; + const link = &l.link; + l.frames.period_ns = refreshNs(g); + if (syncReplicaFont(g, &cl.in.core.settings.font, gpa)) link.dirty = true; + if (scrollRows(g, &cl.in, gpa)) link.dirty = true; + if (fitTaglineFont(g, g.facts.tagline_percent)) link.dirty = true; + const geom = windowCells(g); + if (resizeOf(&g.facts, geom.cols, geom.rows, g.cell_w, g.cell_h, g.tagline_width, g.tagline_height)) |ev| { + if (cl.posted == null or !std.meta.eql(cl.posted.?, ev.resize)) cl.in.post(ev); + cl.posted = ev.resize; + } else cl.posted = null; + if (cl.drew) refreshPresentedPointer(g, &cl.in); + cl.drew = false; + runDemo(g, &cl.in, cl.in.core); + const eof = cl.test_mode and (cl.shell.feed.pump(gpa, &cl.in, g) catch false); + cl.feed(l); + if (eof) return false; + if (cl.in.redraw) link.dirty = true; + cl.in.redraw = false; + return true; + } + + /// A blink, the window's own motion: the last frame again, moved on, + /// as the session's own window draws it (pollFrame). + pub fn again(cl: *Client, _: *ClientLoop) bool { + if (!cl.again_due or !cl.shell.presented) return false; + const frame = cl.shell.surface orelse return false; + cl.g.now_ns = cl.shell.ownNow(); + cl.shell.presented = renderFrame(cl.g, cl.gpa, frame) catch false; + cl.drew = cl.shell.presented; + return true; + } + + /// The window's own motions (its glide, its caret, a jump's trail) + /// and its blink are on its clock: no unit need come. A latency + /// trace's feed paces the loop, as the session's own window's + /// (waitInput): its poll on stdin is the wait, and SDL's, which polls + /// a clock and a lock a millisecond at a time with the offscreen + /// driver, is not waited too (a frame a loop more). A frame owed + /// (a skipped swapchain image) is tried again a frame on: nothing + /// else wakes the window for it. + pub fn deadline(cl: *Client, l: *ClientLoop) u32 { + const g = cl.g; + cl.again_due = false; + const minimized = !cl.test_mode and c.SDL_GetWindowFlags(g.window) & (c.SDL_WINDOW_MINIMIZED | c.SDL_WINDOW_OCCLUDED) != 0; + cl.moving = !minimized and frontendMoving(g); + cl.blink = if (minimized or cl.shell.surface == null) null else blinkNow(g, g.facts.cursor_blink); + if (latency_fd >= 0) return client_loop.forever; + var ms: u32 = if (cl.test_mode) 16 else client_loop.forever; + if (demoDue(g)) |due| ms = @min(ms, @as(u32, @intCast(due))); + if (l.link.owed) ms = @min(ms, @as(u32, @intCast(frame_ms))); + // A touchpad's fraction settling onto a row (scrollRows). + if (cl.moving or g.scroll_lag != 0 or g.scroll_delta != 0) { + const frame_wait: u32 = @intCast(@max(1, (refreshNs(g) + std.time.ns_per_ms - 1) / std.time.ns_per_ms)); + ms = @min(ms, frame_wait); + } + if (cl.blink) |b| if (if (b.edge) refreshNs(g) else b.next_ns) |ns| { + ms = @min(ms, @as(u32, @intCast(@min(std.math.maxInt(c_int), ns / std.time.ns_per_ms + 1)))); + }; + return ms; + } + + /// SDL's wait: each event dispatched and fed; then what the reader + /// took, the window's own pictures' draws done. + pub fn wait(cl: *Client, l: *ClientLoop, ms: u32) void { + const g = cl.g; + const link = &l.link; + if (cl.shell.surface != null) startGamepads(g); + const sdl_ms: c_int = if (latency_fd >= 0) 0 else if (ms == client_loop.forever) -1 else @intCast(@min(ms, std.math.maxInt(c_int))); + var sev = std.mem.zeroes(c.SDL_Event); + g.input_seen = false; + var got = c.SDL_WaitEventTimeout(&sev, sdl_ms); + const timed_out = !got; + while (got) : (got = c.SDL_PollEvent(&sev)) { + if (sev.type == c.SDL_EVENT_USER) continue; + dispatch(g, &cl.in, &sev); + cl.feed(l); + if (cl.in.redraw) link.dirty = true; + cl.in.redraw = false; + if (link.quit) break; + } + cl.takeSaid(l); + // Its draws done (api.draw: this window's own pictures). + if (cl.shell.takeDraws()) link.dirty = true; + if (cl.titled and link.notice_len == 0) { + cl.titled = false; + _ = c.SDL_SetWindowTitle(g.window, "pardes"); + } + if (cl.moving or (cl.blink != null and (cl.blink.?.edge or timed_out))) cl.again_due = true; + } + + /// Its own view drawn in the window, as the tty's client draws its + /// terminal; its render's end is marked as it presents (`present`). + pub fn present(ctx: ?*anyopaque, surface: *const pardes.Surface) bool { + const cl: *Client = @ptrCast(@alignCast(ctx.?)); + return presentShell(cl.shell, surface); + } + + pub fn drawn(cl: *Client) client_loop.Drawn { + cl.drew = cl.shell.presented; + return .{ .drew = cl.shell.presented, .moving = frontendMoving(cl.g) }; + } + /// The reader's: a message of the stream, for the loop, which it wakes. - fn said(cl: *Client, msg: replica.Said) bool { + pub 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; @@ -1273,60 +1431,54 @@ const Client = struct { return true; } + /// The reader's: the link ended. + pub fn ended(cl: *Client) void { + cl.lock.lockUncancelable(cl.io); + cl.link_ended = true; + cl.lock.unlock(cl.io); + sdlWake(null); + } + + /// What the reader took and the loop did not, let go. + pub fn drop(cl: *Client) void { + cl.lock.lockUncancelable(cl.io); + defer cl.lock.unlock(cl.io); + for (cl.inbox.items) |msg| switch (msg) { + .unit, .screen, .refused, .blob => |b| std.heap.c_allocator.free(b), + .checked => {}, + }; + cl.inbox.clearRetainingCapacity(); + } + /// What the reader took, in its order, and the link's end after it. - fn takeSaid(cl: *Client) void { + fn takeSaid(cl: *Client, l: *ClientLoop) void { cl.lock.lockUncancelable(cl.io); std.mem.swap(std.ArrayListUnmanaged(replica.Said), &cl.inbox, &cl.taken); - const ended = cl.ended; + const link_ended = cl.link_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); + l.take(msg); // And after a unit, the first of its own inputs not confirmed. if (msg == .unit) { - const r = cl.link.r; + const r = l.link.r; latencyNote("U {d} {d}\n", .{ monoNs(), if (r.pending.items.len > 0) r.pending.items[0].seq else r.next_seq }); } } cl.taken.clearRetainingCapacity(); - if (ended) { - cl.link.quit = true; - cl.link.gone = true; + if (link_ended) { + l.link.quit = true; + l.link.gone = true; } } - - /// Its own view drawn in the window, outside any step, as the tty's - /// client draws its terminal (tui.zig `Client.draw`), its timings this - /// process's (`frame_probe`). - fn draw(cl: *Client, s: *Shell) void { - const frames = frame_probe.?; - frames.mark_start = pardes.FrameStats.nowNs(); - frames.mark_update = frames.mark_start; - // Its render's end is marked as it presents (`present`). - frames.mark_render = frames.mark_update; - cl.link.owed = !cl.link.r.draw(.{ .ctx = s, .f = present }); - frames.record(pardes.FrameStats.nowNs(), if (s.gui) |g| frontendMoving(g) else false, cl.link.owed); - 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); -} - /// `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 (core/replica.zig) and draws its own view; the -/// session's units are the truth it rolls back to. The tty's `runClient`, with -/// a window for a terminal. -fn clientSession(init: std.process.Init, g: *Gui, opts_in: pardes.Options, test_mode: bool, to: Dial) !void { +/// replica notes"), the client loop over it (runtime/client.zig), as the +/// tty's `runClient` is over a terminal. +fn clientSession(init: std.process.Init, g: *Gui, opts_in: pardes.Options, test_mode: bool, to: client_loop.Dial) !void { const io = init.io; const gpa = init.gpa; const Said = struct { @@ -1336,53 +1488,32 @@ fn clientSession(init: std.process.Init, g: *Gui, opts_in: pardes.Options, test_ 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; - const allocs = pardes.memory.init(gpa); - defer pardes.memory.deinit(); - pardes.Term.start(allocs.image); - pardes.Kind.heap = allocs.addon; - pardes.syntax.start(allocs.tree_sitter); - defer { - pardes.Term.stop(); - pardes.syntax.stop(); - } - var o = opts_in; - o.image_allocator = allocs.image; - var distrusted: pardes.Addon.Distrusted = .{}; - o.distrusted = &distrusted; + var start: client_loop.Start = undefined; // Its frame timings, this process's (Pardes.frames). - var frames: pardes.FrameStats = .{}; - o.frames = &frames; - frame_probe = &frames; - var joined: replica.Joined = undefined; - var r = replica.join(gpa, &joined, to.path, to.session, o, have, &why, null) orelse Said.no(io, "{s}", .{std.mem.sliceTo(&why, 0)}); + frame_probe = &start.frames; + if (!start.open(init, opts_in, to)) Said.no(io, "{s}", .{start.said()}); + defer start.close(); - 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); + var window: Client = .{ .io = io, .gpa = gpa, .texts = .init(gpa), .g = g, .joins = &start, .test_mode = test_mode }; + defer window.deinit(); + var loop = try ClientLoop.init(&window, &start); + defer loop.link.deinit(gpa); + window.loop = &loop; // 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, .wake_fn = sdlWake }; + var queue: Queue = .{ .io = io, .gpa = gpa, .lsp_allocator = start.allocs.lsp, .wake_fn = sdlWake }; 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(), + .core = start.r.core(), .gui = g, .io = io, .gpa = gpa, - .lsp_allocator = allocs.lsp, + .lsp_allocator = start.allocs.lsp, .prompt_rcs = &prompt_rcs, .ptys = &ptys, .gens = &gens, @@ -1391,8 +1522,9 @@ fn clientSession(init: std.process.Init, g: *Gui, opts_in: pardes.Options, test_ .inotify_fd = -1, .watches = &watches, .test_mode = test_mode, - .client = &client, + .client = &window, }; + window.shell = &shell; pardes.Kind.drawer = .{ .ctx = &shell, .go = kindDraw }; defer pardes.Kind.drawer = null; defer shell.job_tasks.cancelAll(io); @@ -1400,148 +1532,10 @@ fn clientSession(init: std.process.Init, g: *Gui, opts_in: pardes.Options, test_ 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) { - const core = r.core(); - g.session_font_request = null; - shell.core = core; - shell.gview = joined.view; - shell.surface = null; - g.hit_core = core; - g.frame = null; - link.reset(r, &joined); - client.posted = null; - 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, .client = &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; - var again = false; - while (!link.quit) { - frames.period_ns = refreshNs(g); - // The window's own work over the frame it shows (Gui.facts): - // the session's font followed, a touchpad's fraction, the - // tagline's face, its size posted, the pointer under a frame - // that moved, the timedemo's and the test feed's steps. - if (syncReplicaFont(g, &core.settings.font, gpa)) link.dirty = true; - if (scrollRows(g, &in, gpa)) link.dirty = true; - if (fitTaglineFont(g, g.facts.tagline_percent)) link.dirty = true; - const geom = windowCells(g); - if (resizeOf(&g.facts, geom.cols, geom.rows, g.cell_w, g.cell_h, g.tagline_width, g.tagline_height)) |ev| { - if (client.posted == null or !std.meta.eql(client.posted.?, ev.resize)) in.post(ev); - client.posted = ev.resize; - } else client.posted = null; - if (drew) refreshPresentedPointer(g, &in); - runDemo(g, &in, core); - const eof = test_mode and (shell.feed.pump(gpa, &in, g) catch false); - client.feed(g); - if (eof) break; - if (in.redraw) link.dirty = true; - in.redraw = false; - // 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; - } else if (again and shell.presented) if (shell.surface) |frame| { - // A blink, the window's own motion: the last frame again, - // moved on, as the session's own window draws it (pollFrame). - g.now_ns = shell.ownNow(); - shell.presented = renderFrame(g, gpa, frame) catch false; - drew = shell.presented; - }; - again = false; - // The window's own motions (its glide, its caret, a jump's - // trail) and its blink are on its clock: no unit need come. - const minimized = !test_mode and c.SDL_GetWindowFlags(g.window) & (c.SDL_WINDOW_MINIMIZED | c.SDL_WINDOW_OCCLUDED) != 0; - const moving = !minimized and frontendMoving(g); - const blink = if (minimized or shell.surface == null) null else blinkNow(g, g.facts.cursor_blink); - const predicting = r.echo.n > 0 or r.echo.cursor != null or r.echo.nd > 0; - // A latency trace's feed paces the loop, as the session's own - // window's (waitInput): its poll on stdin is the wait, and SDL's, - // which polls a clock and a lock a millisecond at a time with - // the offscreen driver, is not waited too (a frame a loop more). - var ms: c_int = if (latency_fd >= 0) 0 else 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); - // A touchpad's fraction settling onto a row (scrollRows). - if (moving or g.scroll_lag != 0 or g.scroll_delta != 0) { - const frame_wait: c_int = @intCast(@max(1, (refreshNs(g) + std.time.ns_per_ms - 1) / std.time.ns_per_ms)); - ms = if (ms < 0) frame_wait else @min(ms, frame_wait); - } - if (blink) |b| if (if (b.edge) refreshNs(g) else b.next_ns) |ns| { - const wait: c_int = @intCast(@min(std.math.maxInt(c_int), ns / std.time.ns_per_ms + 1)); - ms = if (ms < 0) wait else @min(ms, wait); - }; - 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 or latency_fd >= 0) r.ready(); - if (shell.surface != null) startGamepads(g); - var sev = std.mem.zeroes(c.SDL_Event); - g.input_seen = false; - var got = c.SDL_WaitEventTimeout(&sev, ms); - const timed_out = !got; - while (got) : (got = c.SDL_PollEvent(&sev)) { - if (sev.type == c.SDL_EVENT_USER) continue; - dispatch(g, &in, &sev); - client.feed(g); - if (in.redraw) link.dirty = true; - in.redraw = false; - if (link.quit) break; - } - client.takeSaid(); - // Its draws done (api.draw: this window's own pictures). - if (shell.takeDraws()) link.dirty = true; - r.settle(); - // A rollback since it drew: drawn again, never moved on from - // cells the copy put back. - if (r.moved) { - r.moved = false; - link.dirty = true; - } - 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 (moving or (blink != null and (blink.?.edge or timed_out))) again = 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, r.diverged != null); - // 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, .blob => |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. - r = replica.join(gpa, &joined, to.path, to.session, o, have, &why, r) orelse Said.no(io, "{s}", .{std.mem.sliceTo(&why, 0)}); + switch (try loop.run(&start)) { + .done => {}, + .gone => Said.no(io, "'{s}' let this client go (a Detach in it, or the session's end)", .{to.session}), + .failed => Said.no(io, "{s}", .{start.said()}), } } @@ -1836,7 +1830,7 @@ const Input = struct { fn close(in: *Input) void { if (in.client) |r| { - r.link.quit = true; + r.loop.link.quit = true; in.quit = true; return; } @@ -2266,7 +2260,7 @@ fn setFontPx(g: *Gui, in: *Input, want: f32) void { g.px = want; if (in.client) |r| { refitFont(g, null); - r.link.dirty = true; + r.loop.link.dirty = true; } else { refitFont(g, in.core); observeGuiFont(g, in.core); @@ -8114,7 +8108,7 @@ test "trackpad rotation never types search keys into an insert-mode file or raw const core = try pardes.Pardes.init(gpa, .{ .cols = 60, .rows = 16 }); defer core.deinit(); _ = try core.setTestFile("unchanged\n"); - var client: Client = .{ .link = undefined, .io = std.testing.io, .gpa = gpa, .texts = .init(gpa) }; + var client: Client = .{ .io = std.testing.io, .gpa = gpa, .texts = .init(gpa) }; defer client.deinit(); var in: Input = .{ .core = core, .client = &client }; var g: Gui = undefined; @@ -8186,7 +8180,7 @@ test "detached trackpad scrolling keeps fractions local and queues whole rows fo var arena: std.heap.ArenaAllocator = .init(gpa); defer arena.deinit(); _ = try core.render(arena.allocator()); - var client: Client = .{ .link = undefined, .io = std.testing.io, .gpa = gpa, .texts = .init(gpa) }; + var client: Client = .{ .io = std.testing.io, .gpa = gpa, .texts = .init(gpa) }; defer client.deinit(); var in: Input = .{ .core = core, .client = &client }; const id = core.view().active; diff --git a/dev/tui/tui.zig b/dev/tui/tui.zig index 5903e448..c2f3dbf1 100644 --- a/dev/tui/tui.zig +++ b/dev/tui/tui.zig @@ -16,6 +16,7 @@ const file_watch = @import("../file_watch.zig"); const selection_pipe = @import("core").selection_pipe; const ninep_io = @import("runtime").ninep_io; const daemon = @import("runtime").daemon; +const client_loop = @import("runtime").client; const host_io = @import("../host_io.zig"); const upgrade = @import("runtime").upgrade; const replica = @import("core").replica; @@ -619,44 +620,106 @@ 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 (`runClient`), drawn here. -const Client = struct { - link: replica.Link, +/// A replica client's terminal (`runClient`): the frontend of the client +/// loop (runtime/client.zig), its view drawn here as the session draws its +/// terminals'. +const Client = client_loop.Loop(Tty); - /// The client's own view drawn on its terminal, outside any step: the - /// replica's digest stays the session's (views.drawOne); the frame - /// statistics are this process's (`Shell.frames`). - fn draw(c: *Client, s: *Shell) void { - const frames = s.frames; - frames.mark_start = pardes.FrameStats.nowNs(); - frames.mark_update = frames.mark_start; - c.link.owed = !c.link.r.draw(.{ .ctx = s, .f = Shell.present }); - frames.mark_render = frames.mark_update; - const drew = frames.bytes > 0; - frames.record(pardes.FrameStats.nowNs(), false, c.link.owed); - c.link.drawn(drew); +const Tty = struct { + sh: *Shell, + screen: *Screen, + loop: *Loop, + joins: *client_loop.Start, + + /// A join's first inputs: what it is, then its size. + pub fn start(t: *Tty, l: *Client) void { + t.sh.core = l.link.r.core(); + t.sh.own = t.joins.joined.view; + l.input(.{ .frontend = .{ .windowed = false } }); + t.screen.size = null; + t.sh.winched(); + t.screen.vx.queueRefresh(); } -}; -/// 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 Post = struct { - fn post(l: *Loop, said: replica.Said) bool { - l.postEvent(.{ .said = said }) catch return false; - return true; + /// A terminal's own work is all in its wait. + pub fn own(_: *Tty, _: *Client) bool { + return true; + } + + /// The tty's own motions (its glide, a jump's trail): the last frame + /// again, moved on, as the session's terminal draws them (`ownFrame`), + /// not rendered again. One the terminal's answer holds is skipped (the + /// next tick's moves on). + pub fn again(t: *Tty, l: *Client) bool { + const core = l.link.r.core(); + if (!t.sh.moving() or core.surface.cells.len == 0) return false; + _ = Shell.present(t.sh, &core.surface); + return true; + } + + /// An event already queued is the wait's at once; otherwise the + /// session's own wait: an input drawn at once, the session's units and + /// deltas a frame a tick at most, the tty's own motions on its grid of + /// ticks (`waitInput`). + pub fn deadline(t: *Tty, _: *Client) u32 { + if (t.loop.tryEvent() catch null) |ev| { + t.sh.held = ev; + return 0; } - }; - replica.readLink(gpa, fd, rest, loop, Post.post); - loop.postEvent(.link_gone) catch {}; -} + return client_loop.forever; + } + + /// Its inputs go to the loop through `Shell.feed`, the session's + /// stream through `.said`; the terminal's capabilities, once it has + /// answered, enabled and drawn. + pub fn wait(t: *Tty, l: *Client, ms: u32) void { + Shell.waitInput(t.sh, if (ms == client_loop.forever) 0 else ms); + const screen = t.screen; + if (screen.caps_pending and screen.vx.queries_done.load(.unordered)) { + screen.caps_pending = false; + screen.vx.enableDetectedFeatures(screen.tty.writer()) catch {}; + screen.vx.queueRefresh(); + l.link.dirty = true; + } + } + + pub fn present(ctx: ?*anyopaque, surface: *const pardes.Surface) bool { + const t: *Tty = @ptrCast(@alignCast(ctx.?)); + return Shell.present(t.sh, surface); + } + + /// Whether it wrote anything to the terminal (Shell.present counts + /// the bytes); its motions draw frames the timings do not count. + pub fn drawn(t: *Tty) client_loop.Drawn { + return .{ .drew = t.sh.frames.bytes > 0, .moving = false }; + } + + /// The session's stream, onto the loop. + pub fn said(t: *Tty, msg: replica.Said) bool { + t.loop.postEvent(.{ .said = msg }) catch return false; + return true; + } + + pub fn ended(t: *Tty) void { + t.loop.postEvent(.link_gone) catch {}; + } + + /// What the reader and the terminal posted, let go. + pub fn drop(t: *Tty) void { + while (t.loop.tryEvent() catch null) |ev| switch (ev) { + .said => |msg| switch (msg) { + .unit, .screen, .refused, .blob => |b| std.heap.c_allocator.free(b), + .checked => {}, + }, + .paste => |b| t.sh.gpa.free(@constCast(b)), + else => {}, + }; + } +}; /// `pardes --attach=<socket>:<session>` (and `<host>:<session>`, through /// ssh, main.zig): this terminal a replica client of a session elsewhere -/// (docs/next-daemon.md, "Phase 5 part B notes"). Its own core, loaded -/// from the session's dump, applies its keys at once (core/replica.zig); -/// the session's units are the truth it rolls back to. Its own view of the -/// session is drawn here, as the session draws its terminals'. +/// (docs/next-daemon.md, "Phase 5 part B notes"), the client loop over it. pub fn runClient(init: std.process.Init, opts: pardes.Options, path: []const u8, session: []const u8, far_link: bool) !void { const io = init.io; const gpa = init.gpa; @@ -667,33 +730,9 @@ pub fn runClient(init: std.process.Init, opts: pardes.Options, path: []const u8, std.process.exit(1); } }; - var why: [600]u8 = @splat(0); - // Far (through ssh, or PARDES_REPLICA_FAR=1): its join's blobs by hash, - // those it holds kept from the link, and its stream in zstd. A client - // on this machine's own socket is sent the dump whole, as before: a - // hash and a compression there cost more than the bytes. - const far = if (init.environ_map.get("PARDES_REPLICA_FAR")) |v| std.mem.eql(u8, v, "1") else far_link; - 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; - const allocs = pardes.memory.init(gpa); - defer pardes.memory.deinit(); - pardes.Term.start(allocs.image); - pardes.Kind.heap = allocs.addon; - pardes.syntax.start(allocs.tree_sitter); - defer { - pardes.Term.stop(); - pardes.syntax.stop(); - } - var o = opts; - o.image_allocator = allocs.image; - var distrusted: pardes.Addon.Distrusted = .{}; - o.distrusted = &distrusted; - // Its frame timings, this process's (Pardes.frames). - var frames: pardes.FrameStats = .{}; - o.frames = &frames; - var joined: replica.Joined = undefined; - var r = replica.join(gpa, &joined, path, session, o, have, &why, null) orelse Said.no(io, "{s}", .{std.mem.sliceTo(&why, 0)}); + var start: client_loop.Start = undefined; + if (!start.open(init, opts, .{ .path = path, .session = session, .far = far_link })) Said.no(io, "{s}", .{start.said()}); + defer start.close(); var winch_set = posix.sigemptyset(); posix.sigaddset(&winch_set, posix.SIG.WINCH); @@ -714,27 +753,27 @@ pub fn runClient(init: std.process.Init, opts: pardes.Options, path: []const u8, var paste_buf: std.Io.Writer.Allocating = .init(gpa); defer paste_buf.deinit(); var loop: Loop = .init(io, &screen.tty, &screen.vx); - var frame_arena: std.heap.ArenaAllocator = .init(allocs.frame); + var frame_arena: std.heap.ArenaAllocator = .init(start.allocs.frame); defer frame_arena.deinit(); - var client_link: Client = .{ .link = .{ .r = r, .fd = joined.fd } }; - const link = &client_link.link; - try link.fromEnv(gpa, init.environ_map); - defer link.deinit(gpa); + var tty: Tty = undefined; + var c = try Client.init(&tty, &start); + defer c.link.deinit(gpa); var sh: Shell = .{ .io = io, .gpa = gpa, - .lsp_gpa = allocs.lsp, - .core = r.core(), - .frames = &frames, + .lsp_gpa = start.allocs.lsp, + .core = start.r.core(), + .frames = &start.frames, .prompt_rcs = undefined, .loop = &loop, .frame = &frame_arena, .paste_buf = &paste_buf, .inotify_fd = -1, - .own = joined.view, + .own = start.joined.view, .screen = &screen, - .client = &client_link, + .client = &c, }; + tty = .{ .sh = &sh, .screen = &screen, .loop = &loop, .joins = &start }; pardes.Kind.drawer = .{ .ctx = &sh, .go = Shell.draw }; defer pardes.Kind.drawer = null; @@ -743,96 +782,16 @@ pub fn runClient(init: std.process.Init, opts: pardes.Options, path: []const u8, (try std.Thread.spawn(.{}, winchWatch, .{&loop})).detach(); (try std.Thread.spawn(.{}, wakeWatch, .{ io, &loop })).detach(); try screen.vx.queryTerminalSend(screen.tty.writer()); - // A join a pass: the first, and one after the replica diverged or the - // session let it go to upgrade. The terminal stays as it is. - while (true) { - sh.core = r.core(); - sh.own = joined.view; - link.reset(r, &joined); - var reader_done: std.atomic.Value(bool) = .init(false); - const reader = try std.Thread.spawn(.{}, linkReader, .{ gpa, joined.fd, &joined.rest, &loop, &reader_done }); - // 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) { - client_link.draw(&sh); - } else if (sh.moving() and r.core().surface.cells.len != 0) { - // The tty's own motions (its glide, a jump's trail): the last - // frame again, moved on, as the session's terminal draws them - // (`ownFrame`), not rendered again. One the terminal's answer - // holds is skipped (the next tick's moves on). - _ = Shell.present(&sh, &r.core().surface); - link.again += 1; - } - // Idle, its frame drawn: the next key needs no copy taken. - if (loop.tryEvent() catch null) |ev| sh.held = ev else r.ready(); - // The session's own wait: an input drawn at once, the session's - // units and deltas a frame a tick at most, the tty's own motions - // on its grid of ticks; predictions judged a frame at a time. - var wait: u32 = if (r.echo.n > 0 or r.echo.cursor != null or r.echo.nd > 0) @intCast(pardes.frame_ns / std.time.ns_per_ms) else 0; - if (link.quietCheck()) |ms| wait = if (wait == 0) ms else @min(wait, ms); - Shell.waitInput(&sh, wait); - r.settle(); - // A rollback since it drew (`toConfirmed`): its frame is drawn - // again, never moved on from cells the copy put back. - if (r.moved) { - r.moved = false; - link.dirty = true; - } - if (screen.caps_pending and screen.vx.queries_done.load(.unordered)) { - screen.caps_pending = false; - screen.vx.enableDetectedFeatures(screen.tty.writer()) catch {}; - screen.vx.queueRefresh(); - link.dirty = true; - } - 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, r.diverged != null); - // The link's reader ends with the link, posting as it goes: what it - // and the terminal posted is let go until it has. Its end is read - // before the drain, not after: its last post (`link_gone`) comes - // just before it, and left queued it ended the next link at once. - _ = libc.shutdown(joined.fd, 2); - while (true) { - const ended = reader_done.load(.acquire); - while (loop.tryEvent() catch null) |ev| switch (ev) { - .said => |said| switch (said) { - .unit, .screen, .refused, .blob => |b| std.heap.c_allocator.free(b), - .checked => {}, - }, - .paste => |b| gpa.free(@constCast(b)), - else => {}, - }; - if (ended) break; - std.Thread.yield() catch {}; - } - reader.join(); - _ = libc.close(joined.fd); - joined.rest.deinit(gpa); - // Why it joins again, in a line over its frame until a key. - 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) { - screen.leave(); - Said.no(io, "'{s}' let this client go (a Detach in it, or the session's end)", .{session}); - } - return; - } - // The session again, the core it leaves held meanwhile: its blobs - // are not sent again. - r = replica.join(gpa, &joined, path, session, o, have, &why, r) orelse { + switch (try c.run(&start)) { + .done => {}, + .gone => { screen.leave(); - Said.no(io, "{s}", .{std.mem.sliceTo(&why, 0)}); - }; + Said.no(io, "'{s}' let this client go (a Detach in it, or the session's end)", .{session}); + }, + .failed => { + screen.leave(); + Said.no(io, "{s}", .{start.said()}); + }, } } @@ -1267,7 +1226,7 @@ const Shell = struct { /// (applied at once there, and sent to the session). fn feed(s: *Shell, ev: pardes.Event) void { const c = s.client orelse return s.core.update(ev); - c.link.input(ev); + c.input(ev); } /// Whether a terminal of this process's shows the session, or @@ -1761,7 +1720,7 @@ const Shell = struct { else => false, }; if (echo) s.focused_ns = @intCast(std.Io.Clock.awake.now(s.io).nanoseconds); - c.link.take(said); + c.take(said); if (said == .refused) return true; } else switch (said) { .unit, .screen, .refused, .blob => |b| std.heap.c_allocator.free(b), |
