diff options
| -rw-r--r-- | build.zig | 1 | ||||
| -rw-r--r-- | build/tests.zig | 4 | ||||
| -rw-r--r-- | core/replica.zig | 168 | ||||
| -rw-r--r-- | dev/gui/gui.zig | 465 | ||||
| -rw-r--r-- | dev/tui/tui.zig | 293 | ||||
| -rw-r--r-- | runtime/client.zig | 391 | ||||
| -rw-r--r-- | runtime/root.zig | 2 | ||||
| -rw-r--r-- | test/replicas.zig | 604 |
8 files changed, 1318 insertions, 610 deletions
@@ -330,6 +330,7 @@ pub fn build(b: *std.Build) void { .root_set = root_set, .core_wire = core_set.wire, .core_module = core_module, + .core_runtime = core_set.runtime, .core_cfg = core_cfg, .exe = exe, .ghostty_vt_for_tests = a.ghostty_vt, diff --git a/build/tests.zig b/build/tests.zig index fe9e1355..50d3dd02 100644 --- a/build/tests.zig +++ b/build/tests.zig @@ -16,6 +16,8 @@ pub fn add(b: *std.Build, c: struct { /// The wire (abi/wire.zig) on the core's configuration: shell-test's. core_wire: *std.Build.Module, core_module: *std.Build.Module, + /// The runtime beside core_module: the client loop the soak runs. + core_runtime: *std.Build.Module, /// core_module's configuration, for the test roots that run on its imports. core_cfg: core.Core, exe: *std.Build.Step.Compile, @@ -146,7 +148,7 @@ pub fn add(b: *std.Build, c: struct { // The replicas' soak, its clients showing a picture, a game of life and // a PDF (docs/design.pdf) from these libraries, as a user's addons are // loaded. - const replicas = program(b, "pardes-replicas", "test/replicas.zig", c.target, c.optimize, &.{ .{ .name = "pardes", .module = c.core_module }, .{ .name = "term", .module = c.parts.term } }); + const replicas = program(b, "pardes-replicas", "test/replicas.zig", c.target, c.optimize, &.{ .{ .name = "pardes", .module = c.core_module }, .{ .name = "runtime", .module = c.core_runtime }, .{ .name = "term", .module = c.parts.term } }); const run_replicas = b.addRunArtifact(replicas); for ([_]?*std.Build.Step.Compile{ c.image_addon, life_lib, c.pdf_addon }) |l| if (l) |lib| { run_replicas.addArg("--addon"); diff --git a/core/replica.zig b/core/replica.zig index f290cdb3..ae2616b7 100644 --- a/core/replica.zig +++ b/core/replica.zig @@ -562,8 +562,6 @@ pub const Stats = struct { speculated: u32 = 0, /// Stopped at a host call, a syscall or an emulator: waits one RTT. stopped: u32 = 0, - /// Not tried: an event of the view's (a resize, the pointer), phase 4's. - unspeculated: u32 = 0, /// The authority's unit was the pending head, recorded the same. fast: u32 = 0, /// The copy put back: the head recorded otherwise (a guess of the clock @@ -837,6 +835,16 @@ pub const Replica = struct { /// The replica's own input: applied at once when it can be, and the /// message for the authority returned (valid until the next call). pub fn input(r: *Replica, ev: pardes.Event) ![]const u8 { + const msg = try r.pend(ev); + r.applyPended(ev); + return msg; + } + + /// An input's first half: stamped, numbered and pending, its message + /// for the authority returned (valid until the next call), which a + /// client sends before it applies it (`applyPended`, Link.input): the + /// session starts its step while the client speculates. + pub fn pend(r: *Replica, ev: pardes.Event) ![]const u8 { r.stats.inputs += 1; const seq = r.next_seq; r.next_seq += 1; @@ -855,13 +863,18 @@ pub const Replica = struct { const msg = try r.gpa.dupe(u8, room[0 .. head_len + stamp_len + n]); try r.pending.append(r.gpa, .{ .seq = seq, .msg = msg, .sent_ns = nowNs(), .guess = g }); r.dirty = true; - r.settle(); - if (r.t.screen_state and r.diverged == null) r.echo.typed(r.core(), r.view, ev, seq, r.applied == r.pending.items.len); r.out.clearRetainingCapacity(); try r.out.appendSlice(r.gpa, msg); return r.out.items; } + /// An input's second half (`pend`'s, the last): applied at once when it + /// can be, its echo predicted. + pub fn applyPended(r: *Replica, ev: pardes.Event) void { + r.settle(); + if (r.t.screen_state and r.diverged == null) r.echo.typed(r.core(), r.view, ev, r.next_seq - 1, r.applied == r.pending.items.len); + } + /// One unit of the authority's stream, in its order. pub fn confirm(r: *Replica, msg: []const u8) void { if (r.diverged != null) return; @@ -3010,6 +3023,9 @@ pub const Link = struct { /// waits a while after each). input_ns: u64 = 0, asked_ns: u64 = 0, + /// The clock those read, when not the machine's: a simulation's (the + /// soak's, test/replicas.zig), as `Echo.now` is. + now: ?u64 = null, /// 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 @@ -3032,11 +3048,21 @@ pub const Link = struct { /// 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, + /// Its view's yanks, pastes and links (Pardes.View.yanks) its + /// frontend has done: from the joined dump's, so a join does none + /// again (client.zig `asks`). + yanks: u32 = 0, + pastes: u32 = 0, + links: u32 = 0, /// Frames it drew whole (`drawn`), and the last one presented again /// moved on (its own motion), for PARDES_REPLICA_STATS. draws: u32 = 0, again: u32 = 0, + fn time(c: *const Link) u64 { + return c.now orelse nowNs(); + } + /// 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 { @@ -3063,6 +3089,11 @@ pub const Link = struct { c.asked = false; c.mispredicted = 0; c.put_off = false; + if (r.core().views[r.view]) |v| { + c.yanks = v.yanks; + c.pastes = v.pastes; + c.links = v.links; + } } pub fn notify(c: *Link, comptime fmt: []const u8, args: anytype) void { @@ -3081,9 +3112,11 @@ pub const Link = struct { 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; + c.input_ns = c.time(); + // Sent first: the session steps it while this replica speculates. + const msg = c.r.pend(ev) catch return; if (!sendInput(c.fd, msg)) c.cut(); + c.r.applyPended(ev); c.dirty = true; } @@ -3157,12 +3190,12 @@ pub const Link = struct { pub fn quietCheck(c: *Link) ?u32 { if (!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); + const since = c.time() -| @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); if (!c.asked) c.cut(); - c.asked_ns = nowNs(); + c.asked_ns = c.time(); return null; } @@ -5249,7 +5282,10 @@ test "a client's n in a kind's pane is a motion: it steps to the next place a re /// The kinds of pane the walk below stands in: a file's, a plain kind's, /// a shell's raw (its program has the keys) and a shell's in normal mode /// (pardes's own keys over its history). `any` is a row's for all four. -const On = enum { any, file, kind, shell, shell_normal }; +/// `addon`: a kind whose state is its own on the session (a PDF's), which +/// the walk does not stand in (its Still has no search, place or word): +/// the soak's (test/replicas.zig) PDF and pictures are, judged by name. +const On = enum { any, file, kind, shell, shell_normal, addon }; /// What a far client may wait a round trip for (the user's line, P14: a /// side effect on the system may be slow; motions, edits and layout are @@ -5301,12 +5337,31 @@ const may_wait = [_]Wait{ .{ .what = "DumpConfig", .on = .any, .stop = "the authority's own state", .why = "the config file written" }, .{ .what = "ThemeFile *", .on = .any, .stop = "the authority's own state", .why = "a theme file, the session's" }, .{ .what = "DumpThemes", .on = .any, .stop = "the authority's own state", .why = "the theme files written" }, + // A search's rows: the session's worker or its loop writes them, and + // whether it has a worker is not the client's to know (12a); a + // +Preview's text is read from the session's disk. + .{ .what = "Search *", .on = .any, .stop = "search", .why = "a search's rows, the session's worker's" }, + .{ .what = "Search *", .on = .any, .stop = "preview", .why = "a +Preview's file, from the session's disk" }, + // A kind's own state on the session (a PDF's document): asking it. + .{ .what = "*", .on = .addon, .stop = "a kind's search", .why = "a search in a kind's pane: its own state, the session's" }, + .{ .what = "*", .on = .addon, .stop = "a kind's address", .why = "a place in a kind's pane (`Look doc.pdf:3`): its own state" }, + .{ .what = "*", .on = .addon, .stop = "a kind's close", .why = "a kind's pane closed: its state let go on the session" }, + .{ .what = "*", .on = .addon, .stop = "a kind's word", .why = "a word to a kind (a key it takes as one): its own state" }, + .{ .what = "*", .on = .addon, .stop = "a kind's open", .why = "a kind's pane opened (`Life`): its state made on the session" }, } ++ (if (pardes.platform == .gui) [_]Wait{ // A window's view (the font words are a window's). .{ .what = "Font *", .on = .any, .stop = "fonts", .why = "the session's machine's fonts, its disk" }, .{ .what = "Fonts", .on = .any, .stop = "fonts", .why = "the session's machine's fonts, its disk" }, } else [_]Wait{}); +/// Whether a stop of that name (`Tape.poisoned_by`) is one `may_wait` +/// lists for something: the soak's (test/replicas.zig) judge of its +/// clients' inputs, which it cannot name as the walk does. +pub fn mayWait(stop: []const u8) bool { + for (may_wait) |row| if (std.mem.eql(u8, row.stop, stop)) return true; + return false; +} + /// The keys the walk types: every printable one, and the specials a /// frontend reads; each plain, with Ctrl and with Alt. const walk_keys = keys: { @@ -5376,53 +5431,58 @@ fn keyName(buf: []u8, k: pardes.Key) []const u8 { return std.fmt.bufPrint(buf, "{s}{u}", .{ mod, k.cp }) catch unreachable; } -/// A session's host with every entry a step may ask, each doing nothing: -/// a client's step stops, or goes on, as against a real session's (a -/// client's tape offers only the entries its session's host has). The -/// loop's own (`now`, `wait_input`, the frame's) no step asks. -const FullHost = struct { - fn Noop(comptime F: type) type { - const info = @typeInfo(@typeInfo(@typeInfo(F).optional.child).pointer.child).@"fn"; - const R = info.return_type.?; - const P = info.param_types; - return switch (P.len) { - 1 => struct { - fn f(_: ?*anyopaque) R { - return std.mem.zeroes(R); - } - }, - 2 => struct { - fn f(_: ?*anyopaque, _: P[1].?) R { - return std.mem.zeroes(R); - } - }, - 3 => struct { - fn f(_: ?*anyopaque, _: P[1].?, _: P[2].?) R { - return std.mem.zeroes(R); - } - }, - 4 => struct { - fn f(_: ?*anyopaque, _: P[1].?, _: P[2].?, _: P[3].?) R { - return std.mem.zeroes(R); - } - }, - 5 => struct { - fn f(_: ?*anyopaque, _: P[1].?, _: P[2].?, _: P[3].?, _: P[4].?) R { - return std.mem.zeroes(R); - } - }, - else => @compileError("a host entry of more arguments"), - }; - } - const vtable = table: { - var v: pardes.Host.VTable = .{}; - for (@typeInfo(pardes.Host.VTable).@"struct".field_names) |name| { - if (std.mem.eql(u8, name, "now") or std.mem.eql(u8, name, "wait_input") or std.mem.eql(u8, name, "present") or - std.mem.eql(u8, name, "post_present") or std.mem.eql(u8, name, "poll_frame")) continue; - @field(v, name) = &Noop(@FieldType(pardes.Host.VTable, name)).f; +/// `v` with every entry a step may ask that it leaves out doing nothing +/// (answering zero): a client's step stops, or goes on, as against a real +/// session's (a client's tape offers only the entries its session's host +/// has). The loop's own (`now`, `wait_input`, the frame's) no step asks. +pub fn everyEntry(comptime v: pardes.Host.VTable) pardes.Host.VTable { + const Noop = struct { + fn Of(comptime F: type) type { + const info = @typeInfo(@typeInfo(@typeInfo(F).optional.child).pointer.child).@"fn"; + const R = info.return_type.?; + const P = info.param_types; + return switch (P.len) { + 1 => struct { + fn f(_: ?*anyopaque) R { + return std.mem.zeroes(R); + } + }, + 2 => struct { + fn f(_: ?*anyopaque, _: P[1].?) R { + return std.mem.zeroes(R); + } + }, + 3 => struct { + fn f(_: ?*anyopaque, _: P[1].?, _: P[2].?) R { + return std.mem.zeroes(R); + } + }, + 4 => struct { + fn f(_: ?*anyopaque, _: P[1].?, _: P[2].?, _: P[3].?) R { + return std.mem.zeroes(R); + } + }, + 5 => struct { + fn f(_: ?*anyopaque, _: P[1].?, _: P[2].?, _: P[3].?, _: P[4].?) R { + return std.mem.zeroes(R); + } + }, + else => @compileError("a host entry of more arguments"), + }; } - break :table v; }; + var all = v; + for (@typeInfo(pardes.Host.VTable).@"struct".field_names) |name| { + if (std.mem.eql(u8, name, "now") or std.mem.eql(u8, name, "wait_input") or std.mem.eql(u8, name, "present") or + std.mem.eql(u8, name, "post_present") or std.mem.eql(u8, name, "poll_frame")) continue; + if (@field(all, name) == null) @field(all, name) = &Noop.Of(@FieldType(pardes.Host.VTable, name)).f; + } + return all; +} + +/// A session's host with every entry a step may ask, each doing nothing. +const FullHost = struct { + const vtable = everyEntry(.{}); fn host() pardes.Host { return .{ .vtable = &vtable }; } diff --git a/dev/gui/gui.zig b/dev/gui/gui.zig index f9dae69c..237b7b85 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,177 @@ 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) }; + } + + /// What its view asked of this machine (client.zig `asks`): register + /// `+` to the desktop's clipboard, the clipboard's text sent as a paste, + /// a link opened. + pub fn copy(cl: *Client, text: []const u8) void { + putClipboard(cl.gpa, text); + } + + pub fn paste(_: *Client, l: *ClientLoop) void { + const text = takeClipboard() orelse return; + defer c.SDL_free(text.ptr); + l.input(.{ .paste = text }); + } + + pub fn open(_: *Client, url: []const u8) void { + look.openLink(url); + } + /// 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 +1448,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 +1505,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 +1539,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 +1549,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 +1847,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 +2277,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 +8125,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 +8197,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 c6247f00..5a42ae5e 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,122 @@ 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 }; + } + + /// What its view asked of this machine (client.zig `asks`): register + /// `+` to the terminal's clipboard (OSC 52), its clipboard asked for + /// (the answer comes back as a paste, `Shell.feed`), a link opened. + pub fn copy(t: *Tty, text: []const u8) void { + const sc = t.screen; + if (text.len > 0) sc.vx.copyToSystemClipboard(sc.tty.writer(), text, t.sh.gpa) catch {}; + } + + pub fn paste(t: *Tty, _: *Client) void { + t.screen.vx.requestSystemClipboard(t.screen.tty.writer()) catch {}; + } + + pub fn open(_: *Tty, url: []const u8) void { + look.openLink(url); + } + + /// 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 +746,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 +769,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 +798,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 +1242,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 +1736,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), diff --git a/runtime/client.zig b/runtime/client.zig new file mode 100644 index 00000000..544be588 --- /dev/null +++ b/runtime/client.zig @@ -0,0 +1,391 @@ +//! A replica client's loop: the terminal's (dev/tui `runClient`) and the +//! window's (dev/gui `clientSession`) alike, each over a frontend of its +//! own. Its own core, loaded from the session's dump, applies its input at +//! once (core/replica.zig); the session's units are the truth it rolls back +//! to. The link and the replica are inside it; what a frontend does is: +//! +//! per pass, in its order: +//! - `own(l) bool`: the frontend's own work over the frame it shows, +//! before anything is drawn (a window's size posted, its font +//! followed, a touchpad's rows, the pointer, the timedemo, a test's +//! feed; a terminal has none). False ends the loop (a test feed's end). +//! - `again(l) bool`: nothing to draw, but its own motion (a glide, a +//! blink, a jump's trail) goes on: the last frame again, moved on; +//! whether it was presented. +//! - `deadline(l) u32`: when it wants to be woken for its own sake, ms +//! (`forever`: never); 0 when it holds an input already (a terminal's +//! queued key) or something is due at once. The loop wakes it a frame +//! on while an echo is predicted, and for the quiet check. +//! - `wait(l, ms)`: until an input, a message of the session's stream or +//! `ms`: its inputs go in through `l.input`, the stream's messages +//! through `l.take`, in their order. +//! - `present(fe, surface) bool` (views.Present's): a frame shown, or held +//! for the frontend's answer (owed); and `drawn() Drawn`, read after it: +//! whether it wrote anything, and whether its own motion goes on. +//! - `copy(text)`, `paste(l)`, `open(url)`: what its view asked of the +//! machine it is shown on (the user's ruling: a client's yank fills +//! the CLIENT's clipboard): register `+` to its clipboard, its +//! clipboard asked for and sent back as a paste (through `l.input`, +//! now or as its answer comes), a link opened. +//! per join: +//! - `start(l)`: a join's first inputs (what it is, its size). +//! - `said(msg) bool`, `ended()`: the session's stream, from the reader's +//! thread, onto the frontend's own queue (a terminal's event loop, a +//! window's inbox and SDL's wake), so that its wait wakes for them. +//! - `drop()`: what the reader queued, let go once the link has ended. +const std = @import("std"); +const libc = std.c; +const pardes = @import("core"); +const replica = pardes.replica; + +/// A wait with no wake of its own: until an input or a message. +pub const forever: u32 = std.math.maxInt(u32); +const frame_ms: u32 = @intCast(pardes.frame_ns / std.time.ns_per_ms); + +/// What a frame showed, read after its present. +pub const Drawn = struct { drew: bool, moving: bool }; + +/// The session a client dials: a socket's path or `<host>` (through ssh), +/// the session's name, and whether it is far (its blobs by hash, its stream +/// compressed). +pub const Dial = struct { path: []const u8, session: []const u8, far: bool }; + +/// What a client holds across its joins: its allocators, the addons it +/// distrusts, its frame timings (Pardes.frames), the blobs it keeps when +/// far, and its replica and link as joined. Made in place (`open`). +pub const Start = struct { + gpa: std.mem.Allocator, + env: *std.process.Environ.Map, + dial: Dial, + have_store: replica.Have, + have: ?*replica.Have = null, + allocs: pardes.memory.Allocators, + o: pardes.Options, + distrusted: pardes.Addon.Distrusted = .{}, + frames: pardes.FrameStats = .{}, + joined: replica.Joined = undefined, + r: *replica.Replica = undefined, + why: [600]u8 = @splat(0), + + /// The client's process made ready and its first join: false, and why + /// (`said`), when it cannot join. + pub fn open(s: *Start, init: std.process.Init, opts: pardes.Options, dial: Dial) bool { + const io = init.io; + // 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: 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 dial.far; + s.* = .{ + .gpa = init.gpa, + .env = init.environ_map, + .dial = dial, + .have_store = if (far) .init(io) else .{ .io = io }, + .allocs = pardes.memory.init(init.gpa), + .o = opts, + }; + if (far) s.have = &s.have_store; + pardes.Term.start(s.allocs.image); + pardes.Kind.heap = s.allocs.addon; + pardes.syntax.start(s.allocs.tree_sitter); + s.o.image_allocator = s.allocs.image; + s.o.distrusted = &s.distrusted; + // Its frame timings, this process's (Pardes.frames). + s.o.frames = &s.frames; + s.r = replica.join(s.gpa, &s.joined, dial.path, dial.session, s.o, s.have, &s.why, null) orelse return false; + return true; + } + + pub fn close(s: *Start) void { + pardes.Term.stop(); + pardes.syntax.stop(); + pardes.memory.deinit(); + s.have_store.deinit(); + } + + /// Why it could not join. + pub fn said(s: *const Start) []const u8 { + return std.mem.sliceTo(&s.why, 0); + } +}; + +/// How a client's joins ended: it quit, the session let it go, or it could +/// not join again (`Start.said`). +pub const Ended = enum { done, gone, failed }; + +pub fn Loop(comptime Frontend: type) type { + return struct { + const L = @This(); + + link: replica.Link, + fe: *Frontend, + frames: *pardes.FrameStats, + + pub fn init(fe: *Frontend, s: *Start) !L { + var l: L = .{ .link = .{ .r = s.r, .fd = s.joined.fd }, .fe = fe, .frames = &s.frames }; + try l.link.fromEnv(s.gpa, s.env); + return l; + } + + /// The frontend's input: applied at once, and sent to the session. + pub fn input(l: *L, ev: pardes.Event) void { + l.link.input(ev); + } + + /// A message of the session's stream, in its order. + pub fn take(l: *L, msg: replica.Said) void { + l.link.take(msg); + } + + /// A join a pass: the first, and one after the replica diverged or + /// the session let it go to upgrade; the frontend stays as it is. + pub fn run(l: *L, s: *Start) !Ended { + const link = &l.link; + while (true) { + link.reset(s.r, &s.joined); + l.fe.start(l); + var done: std.atomic.Value(bool) = .init(false); + const reader = try std.Thread.spawn(.{}, read, .{ l, s, &done }); + while (!link.quit) { + if (!l.pass()) break; + l.after(); + } + if (s.env.get("PARDES_REPLICA_STATS")) |file| link.writeStats(file); + if (!link.gone) replica.bye(s.joined.fd, s.r.diverged != null); + // The link's reader ends with the link, posting as it goes: + // what it posted is let go until it has (a terminal's queue + // is bounded: a reader blocked on it would never end). + _ = libc.shutdown(s.joined.fd, 2); + while (true) { + const ended = done.load(.acquire); + l.fe.drop(); + if (ended) break; + std.Thread.yield() catch {}; + } + reader.join(); + _ = libc.close(s.joined.fd); + s.joined.rest.deinit(s.gpa); + // Why it joins again is in its notice until a key. + if (!link.rejoins()) { + // What it made since it joined, kept for its next start. + if (s.have) |h| h.keep(s.r.core()); + s.r.deinit(); + return if (link.gone) .gone else .done; + } + // The session again, the core it leaves held meanwhile: its + // blobs are not sent again. + s.r = replica.join(s.gpa, &s.joined, s.dial.path, s.dial.session, s.o, s.have, &s.why, s.r) orelse return .failed; + } + } + + /// The session's stream, onto the frontend's queue: its messages, + /// and its end. + fn read(l: *L, s: *Start, done: *std.atomic.Value(bool)) void { + defer done.store(true, .release); + replica.readLink(s.gpa, s.joined.fd, &s.joined.rest, l.fe, Frontend.said); + l.fe.ended(); + } + + /// A pass up to its wait, and the wait: false when the frontend + /// ended the loop. + pub fn pass(l: *L) bool { + const ms = l.before() orelse return false; + l.fe.wait(l, ms); + return true; + } + + /// The loop of a frontend that is woken from outside (the soak's, + /// test/replicas.zig, whose clock and link are a simulation's): + /// what woke it taken already (`input`, `take`), the rest of the + /// pass and the next up to its wait, as `run` goes round. + pub fn woken(l: *L) void { + l.after(); + if (!l.link.quit) _ = l.pass(); + } + + /// A pass up to its wait: the frontend's own work, its predicted + /// echo judged and caught up (once a frame), its view drawn if + /// anything changed (else its own motion moved on), and how long + /// it may wait; idle, the copy is taken so that the next input + /// needs none. Null: the frontend ended it. + pub fn before(l: *L) ?u32 { + const link = &l.link; + const r = link.r; + if (!l.fe.own(l)) return null; + if (r.echoFrame()) link.dirty = true; + if (link.dirty) l.draw() else if (l.fe.again(l)) link.again += 1; + var ms = l.fe.deadline(l); + if (r.echo.n > 0 or r.echo.cursor != null or r.echo.nd > 0) ms = @min(ms, frame_ms); + if (link.quietCheck()) |quiet| ms = @min(ms, quiet); + if (ms != 0) r.ready(); + return ms; + } + + /// The pass after its wait: its inputs settled; a rollback since it + /// drew is drawn again, never moved on from cells the copy put + /// back, and so is a frame owed or an echo changed. + pub fn after(l: *L) void { + const link = &l.link; + const r = link.r; + r.settle(); + if (r.moved) { + r.moved = false; + link.dirty = true; + } + if (link.owed or r.echo.changed) link.dirty = true; + if (r.diverged != null) link.quit = true; + l.asks(); + } + + /// What the view asked of its frontend since it last looked (the + /// session's host does not do it for a view a client draws): a + /// yank's register `+` copied out, the clipboard asked for, a link + /// opened. Each once: a count a rollback put back and made again + /// is not a second. + fn asks(l: *L) void { + const link = &l.link; + const c = link.r.core(); + const v = if (c.views[link.r.view]) |*v| v else return; + if (ahead(v.yanks, link.yanks)) { + link.yanks = v.yanks; + l.fe.copy(c.registers.text(c.gpa, '+') orelse ""); + } + if (ahead(v.pastes, link.pastes)) { + link.pastes = v.pastes; + l.fe.paste(l); + } + if (ahead(v.links, link.links)) { + link.links = v.links; + l.fe.open(v.link.slice()); + } + } + + fn ahead(now: u32, seen: u32) bool { + return @as(i32, @bitCast(now -% seen)) > 0; + } + + /// Its own view drawn by the frontend, outside any step: the + /// replica's digest stays the session's (views.drawOne); the frame + /// timings are this process's. + fn draw(l: *L) void { + const frames = l.frames; + frames.mark_start = pardes.FrameStats.nowNs(); + frames.mark_update = frames.mark_start; + // A frontend that marks its render's end does so as it presents. + frames.mark_render = frames.mark_update; + l.link.owed = !l.link.r.draw(.{ .ctx = l.fe, .f = Frontend.present }); + const shown = l.fe.drawn(); + frames.record(pardes.FrameStats.nowNs(), shown.moving, l.link.owed); + l.link.drawn(shown.drew); + } + }; +} + +// ---- a client's clipboard and links are its frontend's ---- + +/// A frontend that draws nothing and counts what its view asked of it. +const Null = struct { + copied: u32 = 0, + pasted: u32 = 0, + opened: u32 = 0, + text: [64]u8 = undefined, + text_len: usize = 0, + url: [64]u8 = undefined, + url_len: usize = 0, + + const L = Loop(Null); + pub fn own(_: *Null, _: *L) bool { + return true; + } + pub fn again(_: *Null, _: *L) bool { + return false; + } + pub fn deadline(_: *Null, _: *L) u32 { + return forever; + } + pub fn wait(_: *Null, _: *L, _: u32) void {} + pub fn present(_: ?*anyopaque, _: *const pardes.Surface) bool { + return true; + } + pub fn drawn(_: *Null) Drawn { + return .{ .drew = true, .moving = false }; + } + pub fn copy(n: *Null, text: []const u8) void { + n.copied += 1; + n.text_len = @min(text.len, n.text.len); + @memcpy(n.text[0..n.text_len], text[0..n.text_len]); + } + pub fn paste(n: *Null, _: *L) void { + n.pasted += 1; + } + pub fn open(n: *Null, url: []const u8) void { + n.opened += 1; + n.url_len = @min(url.len, n.url.len); + @memcpy(n.url[0..n.url_len], url[0..n.url_len]); + } +}; + +/// The session's host, which counts what it is asked of the clipboard and +/// links. +const AskedHost = struct { + yanked: u32 = 0, + asked: u32 = 0, + linked: u32 = 0, + fn of(ctx: ?*anyopaque) *AskedHost { + return @ptrCast(@alignCast(ctx.?)); + } + fn setClipboard(ctx: ?*anyopaque, _: []const u8) void { + of(ctx).yanked += 1; + } + fn readClipboard(ctx: ?*anyopaque) void { + of(ctx).asked += 1; + } + fn openLink(ctx: ?*anyopaque, _: []const u8) void { + of(ctx).linked += 1; + } + const vtable = replica.everyEntry(.{ .set_clipboard = setClipboard, .read_clipboard = readClipboard, .open_link = openLink }); + fn host(h: *AskedHost) pardes.Host { + return .{ .ctx = h, .vtable = &vtable }; + } +}; + +test "a client's yank, paste and link reach its own frontend once each, through the loop, and the session's host is asked none of them" { + const gpa = std.testing.allocator; + var h: AskedHost = .{}; + const a = try replica.Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, h.host(), false); + defer a.deinit(); + _ = try a.unit(0, 0); + const j = (try a.join(1, null)) orelse return error.NoView; + defer gpa.free(j.dump); + const r = try replica.Replica.initDump(gpa, 1, j.view, j.dump, .{ .cols = 80, .rows = 24 }); + defer r.deinit(); + var fds: [2]c_int = undefined; + if (libc.socketpair(libc.AF.UNIX, libc.SOCK.STREAM | libc.SOCK.CLOEXEC, 0, &fds) != 0) return error.NoSocket; + defer for (fds) |fd| { + _ = libc.close(fd); + }; + var frames: pardes.FrameStats = .{}; + var n: Null = .{}; + var l: Null.L = .{ .link = .{ .r = r, .fd = fds[1] }, .fe = &n, .frames = &frames }; + const joined: replica.Joined = .{ .fd = fds[1], .pid = 0, .client = 1, .view = j.view, .gmtoff = 0, .dump = &.{} }; + l.link.reset(r, &joined); + _ = l.pass(); + var sink: [1 << 14]u8 = undefined; + for ([_][]const u8{ "ClipYank", "ClipPaste", "Look https://ziglang.org" }) |cmd| { + l.input(.{ .command = cmd }); + const msg = try gpa.dupe(u8, r.out.items); + defer gpa.free(msg); + // At once, by its own step; and not again when the session's unit + // confirms it. + l.woken(); + l.take(.{ .unit = try std.heap.c_allocator.dupe(u8, try a.take(msg)) }); + l.woken(); + _ = libc.read(fds[0], &sink, sink.len); + } + try std.testing.expectEqual(@as(u32, 1), n.copied); + try std.testing.expectEqual(@as(u32, 1), n.pasted); + try std.testing.expectEqual(@as(u32, 1), n.opened); + try std.testing.expectEqualStrings("https://ziglang.org", n.url[0..n.url_len]); + try std.testing.expectEqual(@as(u32, 0), h.yanked + h.asked + h.linked); + try std.testing.expect(r.diverged == null and r.quiet()); +} diff --git a/runtime/root.zig b/runtime/root.zig index 3297db5e..61db8cbe 100644 --- a/runtime/root.zig +++ b/runtime/root.zig @@ -4,6 +4,7 @@ //! (main.zig, macos.zig) sits beside it as a module of its own, naming it //! and `core`. pub const daemon = @import("daemon.zig"); +pub const client = @import("client.zig"); pub const upgrade = @import("upgrade.zig"); pub const crash = @import("crash.zig"); pub const addon_test = @import("addon_test.zig"); @@ -12,6 +13,7 @@ pub const ninep = @import("9p.zig"); test { _ = daemon; + _ = client; _ = upgrade; _ = ninep_io; _ = ninep_io.Client; diff --git a/test/replicas.zig b/test/replicas.zig index 857dcd75..69207970 100644 --- a/test/replicas.zig +++ b/test/replicas.zig @@ -1,7 +1,7 @@ //! pardes-replicas: a session and its clients in one process -//! (core/replica.zig), each a process of its own for what a process holds -//! (`Proc`): the session's own frontend typing in its view and drawing it, -//! and each client (a terminal's loop or a window's, by turns) joined from +//! (core/replica.zig): the session's own frontend typing in its view and +//! drawing it, and each client (THE client loop, runtime/client.zig, over a +//! terminal's frontend or a window's, by turns, drawing no pixels) joined from //! the session's dump for a view of its own, typing at once over its own //! delayed, jittered link, as monkey.zig's scripts type at a tty, through //! the real `replica.Link` on a socket pair: it draws its view, asks for @@ -40,6 +40,7 @@ const std = @import("std"); const libc = std.c; const pardes = @import("pardes"); const replica = pardes.replica; +const client_loop = @import("runtime").client; const screen_state = @import("term").screen_state; const Echo = pardes.Echo; const Key = pardes.Key; @@ -101,8 +102,6 @@ const Host = struct { h.echo.append(gpa, .{ .pane = pane, .bytes = gpa.dupe(u8, bytes) catch return }) catch {}; } - fn ignore(_: ?*anyopaque, _: []const u8) void {} - fn now(ctx: ?*anyopaque) u64 { const h: *Host = @ptrCast(@alignCast(ctx.?)); return h.now_ns; @@ -127,8 +126,10 @@ const Host = struct { j.land(h.core.?); } - const vtable: pardes.Host.VTable = .{ .watched = watched, .pty_write = ptyWrite, .set_clipboard = ignore, .job = job }; - const clocked_vtable: pardes.Host.VTable = .{ .watched = watched, .pty_write = ptyWrite, .set_clipboard = ignore, .now = now, .detach = detach, .job = job }; + // Every entry a step may ask (a client's tape offers only those its + // session's host has): what is not the soak's does nothing. + const vtable = replica.everyEntry(.{ .watched = watched, .pty_write = ptyWrite, .job = job }); + const clocked_vtable = replica.everyEntry(.{ .watched = watched, .pty_write = ptyWrite, .now = now, .detach = detach, .job = job }); fn host(h: *Host) pardes.Host { return .{ .ctx = h, .vtable = if (h.clocked) &clocked_vtable else &vtable }; @@ -198,7 +199,15 @@ const Totals = struct { inputs: u64 = 0, speculated: u64 = 0, stopped: u64 = 0, - unspeculated: u64 = 0, + /// Inputs that stopped at a name `replica.may_wait` does not list + /// (`judgeStops`), and what stopped them all, a count a name. + unlisted: u64 = 0, + /// The wakes the clients' loops asked for, and the frames they drew. + wakes: u64 = 0, + draws: u64 = 0, + /// The clients' views' yanks, pastes and links their frontends did. + asked: [3]u64 = @splat(0), + stops: [32]struct { name: []const u8 = "", n: u64 = 0 } = @splat(.{}), units: u64 = 0, fast: u64 = 0, mispredicted: u64 = 0, @@ -250,7 +259,11 @@ const Totals = struct { t.inputs += s.inputs; t.speculated += s.speculated; t.stopped += s.stopped; - t.unspeculated += s.unspeculated; + for (s.stops) |st| if (st.n > 0) for (&t.stops) |*have| if (have.n == 0 or std.mem.eql(u8, have.name, st.name)) { + have.name = st.name; + have.n += st.n; + break; + }; t.units += s.units; t.fast += s.fast; t.mispredicted += s.mispredicted; @@ -274,7 +287,8 @@ const Totals = struct { /// page and at a search's hit (plain kinds a client runs as the session /// does, `looks` past the texts), the keys after going to its pane; a /// search (`/`, a pattern, Enter), a sweep of B1 over the PDF and its -/// wheel; now and then a client's Detach. +/// wheel; a yank to the system clipboard and a paste from it; now and +/// then a client's Detach. fn nextEvent(random: std.Random, buf: *[64]u8, aim: Aim, looks: []const []const u8, script: *Script) pardes.Event { const typed = "abcdefghijklmnopqrstuvwxyz0123456789 -_=+,:;()"; const normal = "hjklwbe0$xpuyoOiaAIdcv.nN%sC"; @@ -305,7 +319,7 @@ fn nextEvent(random: std.Random, buf: *[64]u8, aim: Aim, looks: []const []const for (buf[0..n]) |*c| c.* = typed[random.uintLessThan(usize, typed.len)]; return .{ .paste = buf[0..n] }; }, - 36 => return .{ .command = switch (random.uintLessThan(u8, 14)) { + 36 => return .{ .command = switch (random.uintLessThan(u8, 16)) { 0 => "Newcol", 1 => "Zerox", 2 => "Undo", @@ -314,14 +328,17 @@ fn nextEvent(random: std.Random, buf: *[64]u8, aim: Aim, looks: []const []const 5 => "Search Recent", 6, 7 => looks[random.uintLessThan(usize, looks.len)], 8 => "Del", - // A tab's width: every pane's layout, and a process global - // (config.tab_now) its step writes. + // A tab's width: every pane's layout. 9 => "Tab 2", 10 => "Tab 8", 11 => "Life", // Its link ended by the session (the session's own view's, // its terminal's: none here). 12 => if (random.uintLessThan(u8, 4) == 0) "Detach" else "Undo", + // The system clipboard, the client's own frontend's (client.zig + // `asks`): a yank of the selection to it, a paste from it. + 13 => "ClipYank", + 14 => "ClipPaste", else => return .{ .key = .{ .cp = if (random.boolean()) 'o' else 'i', .ctrl = true } }, } }, 37 => return .{ .resize = .{ .cols = @intCast(random.intRangeAtMost(u16, 60, 120)), .rows = @intCast(random.intRangeAtMost(u16, 16, 40)) } }, @@ -407,31 +424,18 @@ fn screenHash(t: *screen_state.Terminal) u64 { return h.hasher.final(); } -/// What a client's process holds apart from the session's, where the soak -/// runs them all in one: the kinds it caught breaking PA_PLAIN, handed to -/// each core it joins with (`Options.distrusted`). No process global stands -/// in for a core's state any more (the tab's width is the core's): `enter` -/// and `current` are left for the loops' rewrite to delete. -const Proc = struct { - distrusted: pardes.Addon.Distrusted = .{}, - - var current: ?*Proc = null; - - fn enter(p: *Proc) void { - current = p; - } -}; - -/// A client of the session: a process of its own (`proc`) whose loop is -/// the terminal's (tui.zig `runClient`) or the window's (gui.zig -/// `clientSession`), over the real `replica.Link` on a socket pair whose -/// other end the soak reads as the session's Peer does (`drain`). It joins -/// from the session's dump, may be refused (every view taken), leaves, and -/// joins again for its view after a divergence. +/// A client of the session: a process of its own whose loop is THE client +/// loop (runtime/client.zig, the terminal's and the window's) over this +/// frontend, a terminal's or a window's by turns: it draws no pixels but +/// counts its frames and keeps the facts a window reads beside them, and +/// its wait is the delayed link's next message for it (a wake it asks for +/// goes through the net). Its link is the real `replica.Link` on a socket +/// pair whose other end the soak reads as the session's Peer does +/// (`drain`). It joins from the session's dump, may be refused (every view +/// taken), leaves, and joins again for its view after a divergence. const Client = struct { kind: enum { tty, window }, - proc: Proc = .{}, - link: replica.Link = undefined, + loop: ClientLoop = undefined, r: ?*replica.Replica = null, fds: [2]c_int = .{ -1, -1 }, check: [:0]u8 = undefined, @@ -458,11 +462,13 @@ const Client = struct { left: usize, cols: u16, rows: u16, - last_input: u64 = 0, - asked_at: u64 = 0, + /// The wake its loop's wait asked for (0: none: one at a time, as a + /// real wait's timeout is; an earlier one replaces it), and how many. wake_at: u64 = 0, + wakes: u64 = 0, + /// Its view's yanks, pastes and links its frontend did. + asked: [3]u64 = @splat(0), drew: bool = false, - resize: ?pardes.Event = null, /// What it types in a row (a search, a sweep). script: Script = .{}, /// gui.zig `Client.posted`: a size posted once while it waits. @@ -472,52 +478,95 @@ const Client = struct { facts: pardes.Facts = .{}, frames: pardes.FrameStats = .{}, resizes: u32 = 0, + /// What its process holds apart from the session's: the kinds it + /// caught breaking PA_PLAIN, handed to each core it joins with. + distrusted: pardes.Addon.Distrusted = .{}, + /// What stopped its inputs as last judged (`judgeStops`). + stops: @FieldType(replica.Stats, "stops") = @splat(.{}), + /// Where it is (`clients[c]`), the net its wakes go through, and the + /// soak's time now. + c: usize = 0, + net: *Net = undefined, + now: u64 = 0, + + /// A join's first inputs: what it is, then its size (a window's from + /// its own pass over its view, `own`). + pub fn start(cl: *Client, l: *ClientLoop) void { + l.input(.{ .frontend = if (cl.kind == .window) .{ .windowed = true, .native_images = true, .native_image_patches = true } else .{ .windowed = false } }); + if (cl.kind == .tty) l.input(.{ .resize = .{ .cols = cl.cols, .rows = cl.rows } }); + } + + /// gui.zig's client pass over the frame it shows (Gui.facts): the + /// window's size against the view's, a resize posted when they differ + /// (once while it waits), its facts as its view is then. + pub fn own(cl: *Client, l: *ClientLoop) bool { + if (cl.kind != .window) return true; + const v = &cl.facts; + const metrics: pardes.RowMetrics = .{ .body_w = 9, .body_h = 18, .tagline_w = 9, .tagline_h = 18 }; + if (cl.cols == v.screen_w and cl.rows == v.screen_h and v.cell_pixels.w == 9 and v.cell_pixels.h == 18 and std.meta.eql(metrics, v.row_metrics)) { + cl.posted = null; + return true; + } + const ev: pardes.Event = .{ .resize = .{ .cols = cl.cols, .rows = cl.rows, .cell_pixels = .{ .w = 9, .h = 18 }, .row_metrics = metrics } }; + if (cl.posted == null or !std.meta.eql(cl.posted.?, ev.resize)) { + l.input(ev); + cl.resizes += 1; + const r = l.link.r; + if (r.core().live == r.view) pardes.draw.facts(r.core(), &cl.facts); + } + cl.posted = ev.resize; + return true; + } + + /// No motion of its own. + pub fn again(_: *Client, _: *ClientLoop) bool { + return false; + } + + /// A terminal holds a key already one pass in four (its queue had + /// one): no copy is taken then. + pub fn deadline(cl: *Client, _: *ClientLoop) u32 { + return if (cl.kind == .tty and cl.net.random.uintLessThan(u8, 4) == 0) 0 else client_loop.forever; + } - fn present(ctx: ?*anyopaque, surface: *const pardes.Surface) bool { + /// Its wait is the next message for it; a wake it wants (a frame on + /// while an echo is predicted, the quiet check) is one, on the soak's + /// clock. + pub fn wait(cl: *Client, _: *ClientLoop, ms: u32) void { + if (ms == client_loop.forever or ms == 0) return; + const due = cl.now + @as(u64, ms) * 1000; + if (cl.wake_at != 0 and cl.wake_at <= due) return; + cl.wake_at = due; + cl.wakes += 1; + cl.net.send(.{ .at = due, .n = 0, .kind = .wake, .who = @intCast(cl.c + 1), .bytes = &.{}, .gen = cl.live }) catch {}; + } + + pub fn present(ctx: ?*anyopaque, surface: *const pardes.Surface) bool { const cl: *Client = @ptrCast(@alignCast(ctx.?)); cl.drew = true; cl.facts = surface.facts.*; return true; } - /// tui.zig `Client.draw` (gui.zig's is the same): its own view drawn - /// outside any step, its timings its own. - fn draw(cl: *Client) void { - const r = cl.r.?; - cl.frames.mark_start = pardes.FrameStats.nowNs(); - cl.frames.mark_update = cl.frames.mark_start; - cl.drew = false; - cl.link.owed = !r.draw(.{ .ctx = cl, .f = present }); - cl.frames.mark_render = cl.frames.mark_update; - cl.frames.record(pardes.FrameStats.nowNs(), false, cl.link.owed); - cl.link.drawn(cl.drew); + pub fn drawn(cl: *Client) client_loop.Drawn { + defer cl.drew = false; + return .{ .drew = cl.drew, .moving = false }; } - /// gui.zig's client pass over the frame it shows (Gui.facts): the - /// window's size against the view's, a resize posted when they differ. - fn own(cl: *Client) void { - const v = &cl.facts; - const metrics: pardes.RowMetrics = .{ .body_w = 9, .body_h = 18, .tagline_w = 9, .tagline_h = 18 }; - if (cl.cols == v.screen_w and cl.rows == v.screen_h and v.cell_pixels.w == 9 and v.cell_pixels.h == 18 and std.meta.eql(metrics, v.row_metrics)) return; - cl.resize = .{ .resize = .{ .cols = cl.cols, .rows = cl.rows, .cell_pixels = .{ .w = 9, .h = 18 }, .row_metrics = metrics } }; + /// What its view asked of its machine (client.zig `asks`), counted; + /// its clipboard's answer a paste, as a frontend's comes. + pub fn copy(cl: *Client, _: []const u8) void { + cl.asked[0] += 1; } - - /// The window's own pass over its frame, and what it posted applied. - fn within(cl: *Client) void { - if (cl.kind != .window) return; - cl.own(); - if (cl.resize) |ev| { - if (cl.posted == null or !std.meta.eql(cl.posted.?, ev.resize)) { - cl.link.input(ev); - cl.resizes += 1; - const r = cl.r.?; - if (r.core().live == r.view) pardes.draw.facts(r.core(), &cl.facts); - } - cl.posted = ev.resize; - } else cl.posted = null; - cl.resize = null; + pub fn paste(cl: *Client, l: *ClientLoop) void { + cl.asked[1] += 1; + l.input(.{ .paste = "from the client's clipboard" }); + } + pub fn open(cl: *Client, _: []const u8) void { + cl.asked[2] += 1; } }; +const ClientLoop = client_loop.Loop(Client); const Queue = std.PriorityQueue(Msg, void, Msg.order); @@ -596,45 +645,48 @@ fn drain(cl: *Client, c: usize, net: *Net, now: u64) !void { cl.got.shrinkRetainingCapacity(cl.got.items.len - at); } -/// The rest of a pass of the client's loop, after what woke it (an input -/// applied and sent, a message of the stream taken): as the two loops do -/// each time round (tui.zig `runClient`, gui.zig `clientSession`): its -/// inputs settled, a rollback drawn again, then its predicted echo judged, -/// its view drawn if anything changed (the rows it lacks asked after), -/// the copy taken while idle, and the session's digest asked once quiet. -fn pass(cl: *Client, c: usize, net: *Net, now: u64) !void { +/// What woke client `c`'s loop taken (an input applied and sent, a message +/// of the stream, a wake): the rest of its pass and the next up to its wait +/// (`Loop.woken`, the loop the terminal and the window run), what stopped +/// its inputs judged, and what it wrote read off its socket. +fn woke(cl: *Client, c: usize, net: *Net, now: u64, totals: *Totals, run_: Run) !void { + cl.now = now; + cl.loop.link.now = now * 1000; + if (cl.r == null) return; + cl.loop.woken(); + judgeStops(cl, c, totals, run_); + try drain(cl, c, net, now); +} + +/// A client's input that stopped at a name `replica.may_wait` does not +/// list (what a far client may wait a round trip for, with why): the run +/// fails, the input said. +fn judgeStops(cl: *Client, c: usize, totals: *Totals, run_: Run) void { const r = cl.r orelse return; - const link = &cl.link; - r.settle(); - if (r.moved) { - r.moved = false; - link.dirty = true; + defer cl.stops = r.stats.stops; + for (r.stats.stops, cl.stops) |now, was| { + if (now.n == was.n or replica.mayWait(now.name)) continue; + totals.unlisted += now.n - was.n; + var buf: [160]u8 = undefined; + const blocked = r.blocked orelse 0; + const said = for (r.pending.items) |p| { + if (p.seq != blocked) continue; + const in = replica.parseInput(p.msg) orelse break "?"; + break describe(&buf, in.event); + } else "?"; + std.debug.print("seed {d} rtt {d} ms: client {d}'s input {s} stopped at `{s}`, which may_wait does not list\n", .{ run_.seed, run_.rtt_ms, c + 1, said, now.name }); } - if (link.owed or r.echo.changed) link.dirty = true; - if (r.diverged != null) link.quit = true; - if (!link.quit) { - cl.within(); - if (r.echoFrame()) link.dirty = true; - if (link.dirty) cl.draw(); - // Idle, its frame drawn: the window whenever its wait is not 0, - // the terminal unless an event is held already (one pass in four). - if (cl.kind == .window or net.random.uintLessThan(u8, 4) != 0) r.ready(); - // `quietCheck`, on the soak's clock: 300 ms after its last input - // and its last check, changed since and quiet, the digest asked. - if (link.changed and !link.asked and r.quiet()) { - const due = @max(cl.last_input, cl.asked_at) + 300_000; - if (now >= due) { - link.input_ns = 0; - link.asked_ns = 0; - _ = link.quietCheck(); - cl.asked_at = now; - } else if (cl.wake_at < due) { - cl.wake_at = due; - try net.send(.{ .at = due, .n = 0, .kind = .wake, .who = @intCast(c + 1), .bytes = &.{}, .gen = cl.live }); - } - } - } - try drain(cl, c, net, now); +} + +/// An input, in a line. +fn describe(buf: []u8, ev: pardes.Event) []const u8 { + return switch (ev) { + .key => |k| std.fmt.bufPrint(buf, "key {u}{s}{s}", .{ k.cp, if (k.ctrl) " ctrl" else "", if (k.alt) " alt" else "" }), + .command => |t| std.fmt.bufPrint(buf, "`{s}`", .{t[0..@min(t.len, 120)]}), + .mouse => |m| std.fmt.bufPrint(buf, "mouse {t} {t} at {d},{d}", .{ m.button, m.kind, m.col, m.row }), + .paste => |t| std.fmt.bufPrint(buf, "a paste of {d} bytes", .{t.len}), + else => std.fmt.bufPrint(buf, "{t}", .{ev}), + } catch "?"; } /// Its link ended (it diverged, or it quits): its bye, and its join again @@ -642,7 +694,7 @@ fn pass(cl: *Client, c: usize, net: *Net, now: u64) !void { /// held until the dump comes, as `replica.join` holds it. fn ended(cl: *Client, c: usize, net: *Net, now: u64, totals: *Totals, run_: Run, typing: *usize) !void { const r = cl.r.?; - const link = &cl.link; + const link = &cl.loop.link; // Its link ended by the session (a Detach), it says nothing more. if (!link.gone) replica.bye(cl.fds[1], r.diverged != null); try drain(cl, c, net, now); @@ -672,8 +724,6 @@ fn ended(cl: *Client, c: usize, net: *Net, now: u64, totals: *Totals, run_: Run, fn run(r: Run, dir: []const u8, totals: *Totals) !void { if (trace) std.debug.print("seed {d} rtt {d} ms\n", .{ r.seed, r.rtt_ms }); - // Last: the processes' globals were this run's. - defer Proc.current = null; var prng = std.Random.DefaultPrng.init(r.seed *% 0x9e3779b97f4a7c15 +% r.rtt_ms); const random = prng.random(); var host: Host = .{}; @@ -717,15 +767,10 @@ fn run(r: Run, dir: []const u8, totals: *Totals) !void { // The tty's own boot (a raw shell, a text pane under it), then three // files looked at: the session's own frontend shows the first view // and types in it; each client joins from a dump for a view of its own. - var session: Proc = .{}; - session.enter(); host.clocked = true; host.now_ns = std.time.ns_per_s; const a = try replica.Authority.init(gpa, .{ .cols = 100, .rows = 30, .boot = .tty, .addons = kinds }, host.host(), true); - defer { - session.enter(); - a.deinit(); - } + defer a.deinit(); host.core = a.core; var screens: replica.Screens = .init(gpa); defer screens.deinit(a.core); @@ -788,7 +833,6 @@ fn run(r: Run, dir: []const u8, totals: *Totals) !void { try net.send(.{ .at = at, .n = 0, .kind = .dial, .who = @intCast(c + 1), .bytes = &.{} }); } defer for (clients[0..r.clients]) |*cl| { - cl.proc.enter(); if (cl.r) |rp| rp.deinit(); _ = libc.close(cl.fds[0]); _ = libc.close(cl.fds[1]); @@ -799,8 +843,8 @@ fn run(r: Run, dir: []const u8, totals: *Totals) !void { // The link is made at the first join (its replica the dump's). var has_link: [8]bool = @splat(false); defer for (clients[0..r.clients], has_link[0..r.clients]) |*cl, made| if (made) { - cl.link.check = null; - cl.link.deinit(gpa); + cl.loop.link.check = null; + cl.loop.link.deinit(gpa); }; // What the shell's program prints: a full-screen program, a shell's @@ -936,7 +980,6 @@ fn run(r: Run, dir: []const u8, totals: *Totals) !void { switch (m.kind) { // ---- the session ---- .own => { - session.enter(); host.now_ns = std.time.ns_per_s + m.at * 1000; var buf: [64]u8 = undefined; const ev = nextEvent(random, &buf, aim, looks, &own_script); @@ -953,7 +996,6 @@ fn run(r: Run, dir: []const u8, totals: *Totals) !void { if (own_left > 0) try net.send(.{ .at = m.at + typistGap(random), .n = 0, .kind = .own, .who = 0, .bytes = &.{} }) else typing -= 1; }, .to_authority, .echo, .output => { - session.enter(); // A pty's read wakes its loop as an input does; a client's // mail alone leaves the clock where it was. if (m.kind != .to_authority) host.now_ns = std.time.ns_per_s + m.at * 1000; @@ -1001,7 +1043,6 @@ fn run(r: Run, dir: []const u8, totals: *Totals) !void { host.echo.clearRetainingCapacity(); }, .frame => { - session.enter(); // Its own frontend's frame: its loop woken when a frame is // owed or the core's next wake is due, a pump that advances // its clock (what is due ticks: messages, glides, a kind's @@ -1030,7 +1071,6 @@ fn run(r: Run, dir: []const u8, totals: *Totals) !void { .dial => { // Peers.join at the session's next boundary: its view kept // for it, or a new one, or refused when all are taken. - session.enter(); try ses.pending(m.at, flooding); const id = next_id; const j = (try a.join(id, cl.back)) orelse { @@ -1053,7 +1093,6 @@ fn run(r: Run, dir: []const u8, totals: *Totals) !void { try ses.flush(m.at, c); }, .check_up => { - session.enter(); if (!cl.joined or m.gen != cl.gen) continue; try ses.pending(m.at, flooding); const d = try gpa.alloc(u8, 8); @@ -1062,7 +1101,6 @@ fn run(r: Run, dir: []const u8, totals: *Totals) !void { }, .bye_up => { // Peers.leave: its view kept for it (`again`) or closed. - session.enter(); if (!cl.joined or m.gen != cl.gen) continue; try ses.pending(m.at, flooding); cl.joined = false; @@ -1070,7 +1108,6 @@ fn run(r: Run, dir: []const u8, totals: *Totals) !void { try ses.unit(try a.leave(cl.id, m.seq != 0), m.at, false); }, .screen_up => { - session.enter(); if (!cl.joined or m.gen != cl.gen) continue; if (m.bytes[5] == 2) totals.fetched += std.mem.readInt(u64, m.bytes[14..22], .little) - std.mem.readInt(u64, m.bytes[6..14], .little); if (try screens.take(a.core, cl.sid, m.bytes)) |answer| try net.toClient(c, m.at, .screen_down, cl.gen, answer); @@ -1082,7 +1119,6 @@ fn run(r: Run, dir: []const u8, totals: *Totals) !void { // does), while it has keys left to type. cl.back = null; if (cl.r) |old| { - cl.proc.enter(); try totals.add(&old.stats); old.deinit(); cl.r = null; @@ -1096,7 +1132,6 @@ fn run(r: Run, dir: []const u8, totals: *Totals) !void { } }, .dump => { - cl.proc.enter(); cl.dialling = false; cl.tries = 0; // replica.join: the core it left let go once the new one @@ -1105,7 +1140,7 @@ fn run(r: Run, dir: []const u8, totals: *Totals) !void { try totals.add(&old.stats); old.deinit(); } - const rp = try replica.Replica.initDump(gpa, cl.id, cl.view, m.bytes, .{ .cols = cl.cols, .rows = cl.rows, .distrusted = &cl.proc.distrusted }); + const rp = try replica.Replica.initDump(gpa, cl.id, cl.view, m.bytes, .{ .cols = cl.cols, .rows = cl.rows, .distrusted = &cl.distrusted }); cl.r = rp; rp.stats.samples = true; rp.t.local_files = true; @@ -1117,18 +1152,24 @@ fn run(r: Run, dir: []const u8, totals: *Totals) !void { cl.live = m.gen; var j: replica.Joined = .{ .fd = cl.fds[1], .pid = 0, .client = cl.id, .view = cl.view, .gmtoff = 0, .dump = &.{} }; if (!has_link[c]) { - cl.link = .{ .r = rp, .fd = cl.fds[1], .check = cl.check }; + cl.loop = .{ .link = .{ .r = rp, .fd = cl.fds[1], .check = cl.check }, .fe = cl, .frames = &cl.frames }; has_link[c] = true; - if (c == 1) cl.link.test_diverge = 40; + if (c == 1) cl.loop.link.test_diverge = 40; } - cl.link.reset(rp, &j); + cl.c = c; + cl.net = &net; + cl.now = m.at; + cl.wake_at = 0; + cl.stops = rp.stats.stops; + cl.loop.link.now = m.at * 1000; + cl.loop.link.reset(rp, &j); cl.posted = null; - // What it is, then its size, are its view's first inputs - // (the window's size from its own pass over its view). - cl.link.input(.{ .frontend = if (cl.kind == .window) .{ .windowed = true, .native_images = true, .native_image_patches = true } else .{ .windowed = false } }); - if (cl.kind == .tty) cl.link.input(.{ .resize = .{ .cols = cl.cols, .rows = cl.rows } }); - cl.last_input = m.at; - try pass(cl, c, &net, m.at); + // The loop's join (Loop.run): its first inputs, then a pass + // up to its wait. + cl.start(&cl.loop); + _ = cl.loop.pass(); + judgeStops(cl, c, totals, r); + try drain(cl, c, &net, m.at); if (cl.left > 0 and cl.left == r.steps) try net.send(.{ .at = m.at + typistGap(random), .n = 0, .kind = .input, .who = m.who, .bytes = &.{} }); }, .draw => { @@ -1139,15 +1180,13 @@ fn run(r: Run, dir: []const u8, totals: *Totals) !void { j.run(); // A state job's answer: a step of the session's own. if (j.draw == null) { - session.enter(); - host.now_ns = std.time.ns_per_s + m.at * 1000; + host.now_ns = std.time.ns_per_s + m.at * 1000; a.output(.{ .job = .{ .pane = j.pane, .serial = j.serial, .token = j.token, .gen = j.gen, .bytes = j.out } }); j.drop(); continue; } if (j.draw == @as(?*const pardes.Pardes, a.core)) { - session.enter(); - pardes.Kind.landDraw(a.core, j); + pardes.Kind.landDraw(a.core, j); continue; } const k = for (clients[0..r.clients], 0..) |*dc, k| { @@ -1157,14 +1196,12 @@ fn run(r: Run, dir: []const u8, totals: *Totals) !void { continue; }; const dc = &clients[k]; - dc.proc.enter(); pardes.Kind.landDraw(dc.r.?.core(), j); - dc.link.dirty = true; - try pass(dc, k, &net, m.at); - if (dc.link.quit) try ended(dc, k, &net, m.at, totals, r, &typing); + dc.loop.link.dirty = true; + try woke(dc, k, &net, m.at, totals, r); + if (dc.loop.link.quit) try ended(dc, k, &net, m.at, totals, r, &typing); }, .input, .to_replica, .screen_down, .checked, .wake, .quit, .gone => { - cl.proc.enter(); if (m.kind == .input and cl.left == 0) continue; const rp = cl.r orelse if (m.kind == .input and cl.dialling) { try net.send(.{ .at = m.at + 50_000, .n = 0, .kind = .input, .who = m.who, .bytes = &.{} }); @@ -1178,13 +1215,13 @@ fn run(r: Run, dir: []const u8, totals: *Totals) !void { } } else if (m.kind != .quit and m.gen != cl.live) continue; rp.echo.now = m.at * 1000; + cl.now = m.at; + cl.loop.link.now = m.at * 1000; switch (m.kind) { .input => { var buf: [64]u8 = undefined; const ev = nextEvent(random, &buf, aim, looks, &cl.script); - cl.within(); - cl.link.input(ev); - cl.last_input = m.at; + cl.loop.input(ev); cl.left -= 1; if (cl.left > 0) try net.send(.{ .at = m.at + typistGap(random), .n = 0, .kind = .input, .who = m.who, .bytes = &.{} }) else { typing -= 1; @@ -1192,11 +1229,11 @@ fn run(r: Run, dir: []const u8, totals: *Totals) !void { if (c == 0) try net.send(.{ .at = m.at + 300_000, .n = 0, .kind = .quit, .who = m.who, .bytes = &.{} }); } }, - .to_replica => cl.link.take(.{ .unit = try gpa.dupe(u8, m.bytes) }), + .to_replica => cl.loop.take(.{ .unit = try gpa.dupe(u8, m.bytes) }), .screen_down => { const pane = m.bytes[0]; const was = if (rp.screens[pane]) |sc| replicaOf(sc.rep).seq else 0; - cl.link.take(.{ .screen = try gpa.dupe(u8, m.bytes) }); + cl.loop.take(.{ .screen = try gpa.dupe(u8, m.bytes) }); if (m.bytes[5] == 1) if (rp.screens[pane]) |sc| { const now_seq = replicaOf(sc.rep).seq; if (now_seq == was) totals.resets += 1 else { @@ -1213,27 +1250,33 @@ fn run(r: Run, dir: []const u8, totals: *Totals) !void { } }; }, - .checked => cl.link.take(.{ .checked = std.mem.readInt(u64, m.bytes[0..8], .little) }), - .wake => cl.wake_at = 0, - .quit => cl.link.quit = true, + .checked => cl.loop.take(.{ .checked = std.mem.readInt(u64, m.bytes[0..8], .little) }), + .wake => { + // One the next replaced is no wake. + if (m.at != cl.wake_at) continue; + cl.wake_at = 0; + }, + .quit => cl.loop.link.quit = true, .gone => { - cl.link.quit = true; - cl.link.gone = true; + cl.loop.link.quit = true; + cl.loop.link.gone = true; }, else => unreachable, } - try pass(cl, c, &net, m.at); - if (cl.link.quit) try ended(cl, c, &net, m.at, totals, r, &typing); + try woke(cl, c, &net, m.at, totals, r); + if (cl.loop.link.quit) try ended(cl, c, &net, m.at, totals, r, &typing); }, .client_frame => {}, } } totals.flood_us += flood_end -| flood_at; for (flood_deltas[0..r.clients]) |d| totals.flood_deltas += d; - session.enter(); const want = replica.digestOf(a); for (clients[0..r.clients], 1..) |*cl, id| { totals.resizes += cl.resizes; + totals.wakes += cl.wakes; + for (&totals.asked, cl.asked) |*t, n| t.* += n; + if (has_link[id - 1]) totals.draws += cl.loop.link.draws; // Its quiet checks: what the session's digest was against its own. if (readAll(cl.check)) |said| { defer gpa.free(said); @@ -1246,7 +1289,6 @@ fn run(r: Run, dir: []const u8, totals: *Totals) !void { }; } const rp = cl.r orelse continue; - cl.proc.enter(); try totals.add(&rp.stats); if (cl.live == 0) continue; if (rp.diverged) |why| { @@ -1280,7 +1322,6 @@ fn run(r: Run, dir: []const u8, totals: *Totals) !void { } } } - session.enter(); } /// A typist: keys 50-200 ms apart, a pause now and then. @@ -2468,19 +2509,22 @@ pub fn main(init: std.process.Init) !void { } var failed = !try diffCase(dir); if (!try plumbCase(dir)) failed = true; + if (!try corpusCase(dir)) failed = true; std.debug.print("{d} seeds x {d} inputs from the session's own frontend and each of {d} clients (terminals and windows by turns, joined from a dump, at most {d} at once), a TUI then {d} MB of yes in the shell; costs in us (frame {d})\n", .{ seeds, steps, clients, pardes.views.max - 1, flood_mb, frame_us }); - std.debug.print(" rtt inputs at-once stopped view units fast rollback(mis+foreign) rate rebase spec p50/p99 copy p50/p99 (KB) rollback p50/p99 diverged unequal\n", .{}); + std.debug.print(" rtt inputs at-once stopped units fast rollback(mis+foreign) rate rebase spec p50/p99 copy p50/p99 (KB) rollback p50/p99 diverged unequal\n", .{}); var term_lines: std.ArrayList(u8) = .empty; defer term_lines.deinit(gpa); var join_lines: std.ArrayList(u8) = .empty; defer join_lines.deinit(gpa); + var stop_lines: std.ArrayList(u8) = .empty; + defer stop_lines.deinit(gpa); for (rtts) |rtt| { var t: Totals = .{}; for (first..first + seeds) |seed| try run(.{ .seed = seed, .rtt_ms = rtt, .steps = steps, .clients = clients, .flood_mb = flood_mb }, dir, &t); const rollbacks = t.mispredicted + t.foreign; - std.debug.print("{d:>4} {d:>6} {d:>7} {d:>7} {d:>4} {d:>6} {d:>6} {d:>6} ({d}+{d}) {d:>5.1}% {d:>6} {d:>5}/{d:<6} {d:>5}/{d:<5} ({d}) {d:>7}/{d:<7} {d:>8} {d:>7}\n", .{ + std.debug.print("{d:>4} {d:>6} {d:>7} {d:>7} {d:>6} {d:>6} {d:>6} ({d}+{d}) {d:>5.1}% {d:>6} {d:>5}/{d:<6} {d:>5}/{d:<5} ({d}) {d:>7}/{d:<7} {d:>8} {d:>7}\n", .{ rtt, t.inputs, t.speculated, - t.stopped, t.unspeculated, t.units, + t.stopped, t.units, t.fast, rollbacks, t.mispredicted, t.foreign, @as(f64, @floatFromInt(rollbacks)) * 100 / @as(f64, @floatFromInt(@max(t.inputs, 1))), t.rebases, pct(t.spec_ns.items, 50) / 1000, pct(t.spec_ns.items, 99) / 1000, pct(t.copy_ns.items, 50) / 1000, @@ -2504,12 +2548,234 @@ pub fn main(init: std.process.Init) !void { t.screens_checked, t.screens_wrong, }); + try stop_lines.print(gpa, "{d:>4} {d:>8} {d:>6} {d:>6} {d:>3}/{d}/{d} ", .{ rtt, t.unlisted, t.wakes, t.draws, t.asked[0], t.asked[1], t.asked[2] }); + for (t.stops) |st| if (st.n > 0) try stop_lines.print(gpa, "{s}:{d} ", .{ st.name, st.n }); + try stop_lines.append(gpa, '\n'); try join_lines.print(gpa, "{d:>4} {d:>5} {d:>7} {d:>8} {d:>8} {d:>6} {d:>5}/{d:<5} {d:>5}/{d:<6} {d:>7} {d:>5}/{d}/{d}\n", .{ rtt, t.joins, t.refused, t.rejoined, t.detached, t.detach_words, t.agree, t.differ, t.checks, t.units, t.resizes, t.kind_panes[0], t.kind_panes[1], t.kind_panes[2] }); - if (t.divergences > 0 or t.unequal > 0 or t.screens_wrong > 0 or t.differ > 0) failed = true; + if (t.divergences > 0 or t.unequal > 0 or t.screens_wrong > 0 or t.differ > 0 or t.unlisted > 0) failed = true; } std.debug.print("terminals: deltas a replica applied a second under the flood; a peer's bytes a second under the flood (deltas, units); encode a frame of the flood for every peer, apply a delta (us); rows fetched, KB of rows sent before the step that read them; resets; deltas checked/wrong\n", .{}); std.debug.print(" rtt deltas/s delta B/s unit B/s encode p50/p99 apply p50/p99 fetched filled KB resets checked/wrong\n{s}", .{term_lines.items}); std.debug.print("clients: joins from a dump, refused (every view taken), joined again after a divergence put on them, left (of them by a Detach); quiet checks of the session's digest agreed/differed; the digests the clients compared (units and quiet), of the units they took; resizes the windows posted; the kinds' panes the session opened (image/life/pdf)\n", .{}); std.debug.print(" rtt joins refused rejoined detached detach agree/differ checks/units resizes kinds\n{s}", .{join_lines.items}); + std.debug.print("stops: the wakes the clients' loops asked, the frames they drew, the yanks, pastes and links their frontends did (y/p/l), and what stopped their inputs (a stop counted again as its input is applied again), by name; those at a name replica.may_wait does not list fail the run\n", .{}); + std.debug.print(" rtt unlisted wakes draws y/p/l stops\n{s}", .{stop_lines.items}); if (failed) std.process.exit(1); } + +// ---- the frame corpus through a client ---- + +/// A frame as a frontend reads it (10a: the window and the terminal draw +/// from these alone): its cells, cursor, chrome and regions, and the facts +/// beside them. +const Shown = struct { + cells: std.ArrayListUnmanaged(pardes.Cell) = .empty, + regions: std.ArrayListUnmanaged(pardes.Region) = .empty, + cols: u16 = 0, + rows: u16 = 0, + cursor: @FieldType(pardes.Surface, "cursor") = null, + chrome: @FieldType(pardes.Surface, "chrome") = .{}, + facts: pardes.Facts = .{}, + placements: u32 = 0, + frames: u32 = 0, + + fn take(sh: *Shown, s: *const pardes.Surface) void { + sh.cells.clearRetainingCapacity(); + sh.cells.appendSlice(gpa, s.cells) catch {}; + sh.regions.clearRetainingCapacity(); + sh.regions.appendSlice(gpa, s.regions[0..s.nregions]) catch {}; + sh.cols = s.cols; + sh.rows = s.rows; + sh.cursor = s.cursor; + sh.chrome = s.chrome; + sh.facts = s.facts.*; + sh.placements = @intCast(s.placements.items.len); + sh.frames += 1; + } + + fn deinit(sh: *Shown) void { + sh.cells.deinit(gpa); + sh.regions.deinit(gpa); + } + + /// What differs between two frames, or null. + fn differ(a: *const Shown, b: *const Shown, buf: []u8) ?[]const u8 { + if (a.cols != b.cols or a.rows != b.rows) return std.fmt.bufPrint(buf, "the size {d}x{d} against {d}x{d}", .{ a.cols, a.rows, b.cols, b.rows }) catch "the size"; + var cells: usize = 0; + var first: usize = 0; + for (a.cells.items, b.cells.items, 0..) |x, y, i| if (!std.meta.eql(x, y)) { + if (cells == 0) first = i; + cells += 1; + }; + if (cells > 0) return std.fmt.bufPrint(buf, "{d} cells, the first at {d},{d}", .{ cells, first % a.cols, first / a.cols }) catch "cells"; + if (!std.meta.eql(a.cursor, b.cursor)) return "the cursor"; + if (!std.meta.eql(a.chrome, b.chrome)) return "the chrome"; + if (a.regions.items.len != b.regions.items.len) return "the regions"; + for (a.regions.items, b.regions.items) |x, y| if (!std.meta.eql(x, y)) return "a region"; + if (!std.meta.eql(a.facts, b.facts)) return "the facts"; + if (a.placements != b.placements) return "the placements"; + return null; + } +}; + +/// A session's own frontend: what its pump presents, kept. +const ShownHost = struct { + shown: Shown = .{}, + fn watched(_: ?*anyopaque) bool { + return true; + } + fn present(ctx: ?*anyopaque, s: *const pardes.Surface) bool { + const h: *ShownHost = @ptrCast(@alignCast(ctx.?)); + h.shown.take(s); + return true; + } + const vtable = replica.everyEntry(.{ .watched = watched, .present = present }); + fn host(h: *ShownHost) pardes.Host { + return .{ .ctx = h, .vtable = &vtable }; + } +}; + +/// A client's frontend that keeps what it presents, and has nothing of its +/// own: the client loop's frames, as a frontend would be given them. +const Shows = struct { + shown: Shown = .{}, + pub fn start(_: *Shows, l: *client_loop.Loop(Shows)) void { + _ = l; + } + pub fn own(_: *Shows, _: *client_loop.Loop(Shows)) bool { + return true; + } + pub fn again(_: *Shows, _: *client_loop.Loop(Shows)) bool { + return false; + } + pub fn deadline(_: *Shows, _: *client_loop.Loop(Shows)) u32 { + return client_loop.forever; + } + pub fn wait(_: *Shows, _: *client_loop.Loop(Shows), _: u32) void {} + pub fn present(ctx: ?*anyopaque, s: *const pardes.Surface) bool { + const f: *Shows = @ptrCast(@alignCast(ctx.?)); + f.shown.take(s); + return true; + } + pub fn drawn(_: *Shows) client_loop.Drawn { + return .{ .drew = true, .moving = false }; + } + pub fn copy(_: *Shows, _: []const u8) void {} + pub fn paste(_: *Shows, _: *client_loop.Loop(Shows)) void {} + pub fn open(_: *Shows, _: []const u8) void {} +}; + +/// The frame corpus's scenes (test/process/window.zig `corpus`, what a +/// session's core makes of them: its files, a wheel, a click, a jump, the +/// taglines' size, a markdown file, a picture, three columns, a dirty +/// pane, InactiveDim, WindowOpacity, ligatures, a resize) typed twice: +/// into a session's own view, drawn by its own pump as its own frontend's +/// is, and into a client's view of another session of the same files, +/// through the client loop (runtime/client.zig) and the session's units. +/// After each, at rest, the two frames are the same: what a frontend draws +/// from (10a) is the same through a client as its own. GPU pixels are not +/// drawn here; the corpus's own gate (77 frames) proves the window draws +/// these alike. +fn corpusCase(dir: []const u8) !bool { + var path_bufs: [5][300]u8 = undefined; + const shapes = try std.fmt.bufPrintSentinel(&path_bufs[0], "{s}/shapes.zig", .{dir}, 0); + var zig: std.ArrayListUnmanaged(u8) = .empty; + defer zig.deinit(gpa); + try zig.appendSlice(gpa, "const std = @import(\"std\");\n\npub const Shape = union(enum) {\n circle: f32,\n square: f32,\n};\n\npub fn main() void {\n var total: f32 = 0;\n"); + for (0..80) |n| try zig.print(gpa, " total += {d}; // line {d}\n", .{ n, n }); + try zig.appendSlice(gpa, " std.debug.print(\"{d}\\n\", .{total});\n}\n"); + try writeText(shapes, zig.items); + const notes = try std.fmt.bufPrintSentinel(&path_bufs[1], "{s}/notes.md", .{dir}, 0); + try writeText(notes, "# Fallback faces and rules\n\n| name | glyphs |\n|------|--------|\n| cjk | 界面字 |\n| sym | ∮ ≠ ★ |\n\n┌──┬──┐\n│ a│ b│\n└──┴──┘\n"); + const ligatures = try std.fmt.bufPrintSentinel(&path_bufs[2], "{s}/ligatures.zig", .{dir}, 0); + try writeText(ligatures, "const a = b -> c; // => != <= >= == === !== |> <| :: ++ --\nconst fi = \"office flow staff\";\n"); + var looks: [3][320]u8 = undefined; + const Wheel = struct { + fn at(button: @FieldType(@FieldType(pardes.Event, "mouse"), "button"), kind: @FieldType(@FieldType(pardes.Event, "mouse"), "kind"), col: u16, row: u16) pardes.Event { + return .{ .mouse = .{ .button = button, .kind = kind, .col = col, .row = row } }; + } + }; + const k = struct { + fn of(cp: u21) pardes.Event { + return .{ .key = .{ .cp = cp, .text = switch (cp) { + 'g' => "g", + 'j' => "j", + else => "", + } } }; + } + }; + const steps = [_]pardes.Event{ + Wheel.at(.wheel_down, .press, 40, 12), Wheel.at(.wheel_down, .press, 40, 12), Wheel.at(.wheel_down, .press, 40, 12), + Wheel.at(.left, .press, 20, 10), Wheel.at(.left, .release, 20, 10), k.of('g'), + k.of('g'), .{ .command = "TaglineSize 80" }, k.of('j'), + k.of('j'), k.of('j'), .{ .command = try std.fmt.bufPrint(&looks[0], "Look {s}", .{notes}) }, + .{ .command = "Newcol" }, .{ .command = "Newcol" }, .{ .command = "New" }, + .{ .paste = "a dirty pane\n" }, .{ .command = "InactiveDim 40" }, .{ .command = "WindowOpacity 71" }, + .{ .command = try std.fmt.bufPrint(&looks[1], "Look {s}", .{ligatures}) }, .{ .command = "Zerox" }, .{ .key = .{ .cp = Key.escape } }, + .{ .resize = .{ .cols = 70, .rows = 20 } }, + }; + var own_host: ShownHost = .{}; + defer own_host.shown.deinit(); + var noop: Host = .{}; + const options: pardes.Options = .{ .cols = 100, .rows = 22, .file = shapes }; + const a = try replica.Authority.init(gpa, options, own_host.host(), true); + defer a.deinit(); + const b = try replica.Authority.init(gpa, options, noop.host(), true); + defer b.deinit(); + noop.core = b.core; + _ = try b.unit(0, 0); + const j = (try b.join(1, null)) orelse return error.NoView; + defer gpa.free(j.dump); + const rp = try replica.Replica.initDump(gpa, 1, j.view, j.dump, .{ .cols = 100, .rows = 22 }); + defer rp.deinit(); + var fds: [2]c_int = undefined; + if (libc.socketpair(libc.AF.UNIX, libc.SOCK.STREAM | libc.SOCK.CLOEXEC, 0, &fds) != 0) return error.NoSocket; + defer for (fds) |fd| { + _ = libc.close(fd); + }; + _ = libc.fcntl(fds[0], libc.F.SETFL, @as(c_int, @bitCast(libc.O{ .NONBLOCK = true }))); + var shows: Shows = .{}; + defer shows.shown.deinit(); + var frames: pardes.FrameStats = .{}; + var l: client_loop.Loop(Shows) = .{ .link = .{ .r = rp, .fd = fds[1] }, .fe = &shows, .frames = &frames }; + const Both = struct { + a: *replica.Authority, + b: *replica.Authority, + l: *client_loop.Loop(Shows), + fd: c_int, + /// `ev` into the session's own view, and through the client loop + /// into the client's: the session's unit back to it, at once. + fn step(s: @This(), ev: pardes.Event) !void { + _ = try s.a.own(ev); + s.l.input(ev); + const r = s.l.link.r; + if (try s.b.pending()) |batch| s.l.take(.{ .unit = try std.heap.c_allocator.dupe(u8, batch) }); + const msg = try gpa.dupe(u8, r.out.items); + defer gpa.free(msg); + s.l.take(.{ .unit = try std.heap.c_allocator.dupe(u8, try s.b.take(msg)) }); + s.l.woken(); + var sink: [4096]u8 = undefined; + while (libc.read(s.fd, &sink, sink.len) > 0) {} + } + }; + const both: Both = .{ .a = a, .b = b, .l = &l, .fd = fds[0] }; + // What each is, then its size: its view's first inputs. + try both.step(.{ .frontend = .{ .windowed = false } }); + try both.step(.{ .resize = .{ .cols = 100, .rows = 22 } }); + var ok = true; + var why: [120]u8 = undefined; + for (steps, 0..) |ev, n| { + try both.step(ev); + if (!rp.quiet() or rp.diverged != null) { + std.debug.print("corpus through a client: step {d} ({t}): the client is not the session's ({s})\n", .{ n, ev, rp.diverged orelse "inputs pending" }); + ok = false; + continue; + } + if (Shown.differ(&own_host.shown, &shows.shown, &why)) |what| { + std.debug.print("corpus through a client: step {d} ({t}): the client's frame is not the own frontend's: {s}\n", .{ n, ev, what }); + ok = false; + } + } + std.debug.print("corpus through a client: {d} scenes, the own frontend drew {d} frames and the client {d}; {s}\n", .{ steps.len, own_host.shown.frames, shows.shown.frames, if (ok) "every scene's frame the same" else "FAILED" }); + return ok; +} |
