diff options
| author | Gabriel Schneider <[email protected]> | 2026-10-29 20:56:03 -0300 |
|---|---|---|
| committer | Gabriel Schneider <[email protected]> | 2026-10-30 03:13:15 -0300 |
| commit | fdf74e199de7d0fc648f912875323f3dc920ffc2 (patch) | |
| tree | 7e175c6fc9cb653200ff2abb7bcc5cf0fda3dc9f /src/tty/tty.zig | |
| parent | 57aa8d2f9ae851fa9806abbd1fd04abf1fd2b57f (diff) | |
| download | pardes-fdf74e199de7d0fc648f912875323f3dc920ffc2.tar.gz pardes-fdf74e199de7d0fc648f912875323f3dc920ffc2.zip | |
replica clients over a socket: the session streams each its dump and every unit after it (replica.zig `Peers`, a writer and a reader thread a client, units at each step boundary, a client's input stepped there in its own view), and `pardes --attach=<socket>:<name>` and `--attach=<host>:<name>` (through `ssh -tt -L`) are a client in the tty host, its keys applied at once by its own replica and drawn by its own process
wire.zig version 15: welcome (the client's id and view, the dump's length, the session's UTC offset and digest), dump pieces, units (with the authority's clocks), terminal messages both ways, a check. A unit carries one digest, at its end (`unit_digests`).
The client: tty.zig `Shell.remote`, `feed` (a terminal's input to the replica and the session); the session's clock guessed from the last unit's (tape.zig `Guess`); a pump woken only by a client's post reads no new time (`mail_only`), and a unit of another's ending where the last ended leaves the speculation as it is (`neutral`); the rollback copy taken while idle (`Replica.ready`); views a frontend here does not draw left undrawn.
A lagging client never holds the session: its queue is cut off past 64 MiB (PARDES_REPLICA_LAG_KB). Detach in a client ends that client; a Restore lets every client go.
daemon.zig: a replica the daemon hands over is the session's loop's (a note), not a stub thread's. A window session refuses one in words.
test/daemon.py `--clients`: two clients (one through the delay relay) type into a detached session and agree with it, one killed outright, one detached, a third typing into a shell.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Diffstat (limited to 'src/tty/tty.zig')
| -rw-r--r-- | src/tty/tty.zig | 425 |
1 files changed, 397 insertions, 28 deletions
diff --git a/src/tty/tty.zig b/src/tty/tty.zig index 14dc8042..43994645 100644 --- a/src/tty/tty.zig +++ b/src/tty/tty.zig @@ -17,6 +17,8 @@ const panel_compositor = @import("panel_compositor.zig"); const daemon = @import("../daemon.zig"); const host_io = @import("../host_io.zig"); const upgrade = @import("../upgrade.zig"); +const replica = @import("../replica.zig"); +const wire = @import("../detached/wire.zig"); extern "c" fn setenv(name: [*:0]const u8, value: [*:0]const u8, overwrite: c_int) c_int; @@ -150,6 +152,15 @@ pub const Command = struct { search_rows: pardes.Stream.Batch, files_changed, fs_ready, + /// A replica's connection, handed over by the daemon (Peers). + replica: posix.fd_t, + /// A replica's reader posted: the step boundary takes it in. + replica_mail, + /// A replica client's: what the session streamed (replica.Client). + unit: []u8, + /// The session's digest, asked by PARDES_REPLICA_CHECK. + checked: u64, + link_gone, } = .nop; }; const Loop = vaxis.Loop(@TypeOf(Command.value)); @@ -838,14 +849,18 @@ fn terminalCellPixels(total_pixels: u16, cells: u16, fallback: u32) u32 { } fn updateCoreTerminalSize(core: *pardes.Pardes, cols: u16, rows: u16, pixel_w: u16, pixel_h: u16) void { - core.update(.{ .resize = .{ + core.update(.{ .resize = terminalSize(cols, rows, pixel_w, pixel_h) }); +} + +fn terminalSize(cols: u16, rows: u16, pixel_w: u16, pixel_h: u16) @FieldType(pardes.Event, "resize") { + return .{ .cols = cols, .rows = rows, .cell_pixels = .{ .w = @intCast(terminalCellPixels(pixel_w, cols, 8)), .h = @intCast(terminalCellPixels(pixel_h, rows, 16)), }, - } }); + }; } /// A terminal pane's image fragment (`native.exact`): its `src` into its @@ -1255,6 +1270,268 @@ pub fn run(init: std.process.Init, opts: pardes.Options, term: Term) !void { try localSession(init, opts, &screen, &loop, &paste_buf); } +/// A replica client's link to its session (`remote`). +const Remote = struct { + r: *replica.Replica, + fd: posix.fd_t, + quit: bool = false, + /// The session hung up. + gone: bool = false, + /// Something to draw: an input applied, a unit taken. + dirty: bool = true, + /// The last frame was held for the terminal's answer (FrameAck). + owed: bool = false, + /// PARDES_REPLICA_CHECK=<file>: once quiet a while after a change, the + /// session's digest is asked, and whether this replica's agrees is + /// written there, a line a check. + check: ?[:0]const u8 = null, + changed: bool = false, + asked: bool = false, + /// How many of its own inputs the session recorded otherwise when it + /// last drew: a frame after one that writes to the terminal is a + /// rollback that may have been seen (counted so: an upper bound, the + /// frame shows the inputs after it too). + mispredicted: u32 = 0, + visible: u32 = 0, + + /// PARDES_REPLICA_STATS=<file>: how its inputs and the session's units + /// went, a line at its end (test/daemon.py, the gates). + fn writeStats(c: *Remote, path: []const u8) void { + const st = &c.r.stats; + var buf: [600]u8 = undefined; + const line = std.fmt.bufPrint(&buf, "inputs {d} at_once {d} stopped {d} units {d} fast {d} neutral {d} mispredicted {d} foreign {d} visible {d} rtt_us {d} spec_us {d}/{d} copy_us {d}/{d} rollback_us {d}/{d}\n", .{ + st.inputs, st.speculated, st.stopped, st.units, st.fast, + c.r.neutral, st.mispredicted, st.foreign, c.visible, c.r.rtt_ns / 1000, pct(st.spec_ns.items, 50) / 1000, + pct(st.spec_ns.items, 99) / 1000, pct(st.copy_ns.items, 50) / 1000, pct(st.copy_ns.items, 99) / 1000, pct(st.rollback_ns.items, 50) / 1000, pct(st.rollback_ns.items, 99) / 1000, + }) catch return; + var z: [4096]u8 = undefined; + const pz = std.fmt.bufPrintSentinel(&z, "{s}", .{path}, 0) catch return; + const fd = libc.open(pz, .{ .ACCMODE = .WRONLY, .CREAT = true, .APPEND = true, .CLOEXEC = true }, @as(libc.mode_t, 0o644)); + if (fd < 0) return; + _ = libc.write(fd, line.ptr, line.len); + _ = libc.close(fd); + } + + fn pct(samples: []u64, p: usize) u64 { + if (samples.len == 0) return 0; + std.mem.sort(u64, samples, {}, std.sort.asc(u64)); + return samples[@min(samples.len - 1, samples.len * p / 100)]; + } + + /// The session's digest against this replica's, if it is quiet still. + fn checked(c: *Remote, theirs: u64) void { + c.asked = false; + const path = c.check orelse return; + if (!c.r.quiet()) return; + const mine = c.r.digest(); + var buf: [96]u8 = undefined; + const line = (if (mine == theirs) std.fmt.bufPrint(&buf, "agree {x:0>16}\n", .{mine}) else std.fmt.bufPrint(&buf, "differ {x:0>16} {x:0>16}\n", .{ mine, theirs })) catch return; + const fd = libc.open(path, .{ .ACCMODE = .WRONLY, .CREAT = true, .APPEND = true, .CLOEXEC = true }, @as(libc.mode_t, 0o644)); + if (fd < 0) return; + _ = libc.write(fd, line.ptr, line.len); + _ = libc.close(fd); + } + + /// The client's own view drawn on its terminal, outside any step: the + /// replica's digest stays the session's (views.drawOne). What the host + /// writes in the core as it presents (a frame skipped, one owed) is put + /// back, as the frame statistics are this process's. + fn draw(c: *Remote, s: *Shell) void { + const core = c.r.core(); + const skipped = core.present_skipped; + const needs = core.needs_frame; + core.frames.mark_start = pardes.FrameStats.nowNs(); + core.frames.mark_update = core.frames.mark_start; + c.r.draw(.{ .ctx = s, .f = Shell.present }); + core.frames.mark_render = core.frames.mark_update; + if (c.r.stats.mispredicted > c.mispredicted) { + c.mispredicted = c.r.stats.mispredicted; + if (core.frames.bytes > 0) c.visible += 1; + } + c.owed = core.present_skipped; + core.frames.record(pardes.FrameStats.nowNs(), false, c.owed); + core.present_skipped = skipped; + core.needs_frame = needs; + c.dirty = false; + } +}; + +/// The session's stream, onto the loop: its units, and its end. +fn linkReader(gpa: std.mem.Allocator, fd: posix.fd_t, rest: *replica.Framer, loop: *Loop, done: *std.atomic.Value(bool)) void { + defer done.store(true, .release); + const Take = struct { + fn take(l: *Loop, tag: u8, payload: []const u8) bool { + const t = std.enums.fromInt(wire.ServerTag, tag) orelse return false; + switch (t) { + .unit => { + const bytes = std.heap.c_allocator.dupe(u8, payload) catch return false; + l.postEvent(.{ .unit = bytes }) catch std.heap.c_allocator.free(bytes); + }, + .check => { + const d = (wire.decodeServer(tag, payload) catch return false).check; + l.postEvent(.{ .checked = d }) catch {}; + }, + .refused => return false, + // ponytail: a terminal's delta (rterm's, src/screen_state.zig) + // applies here once terminals cross as screens. + .screen, .pong, .welcome, .dump => {}, + } + return true; + } + }; + replica.readStream(gpa, fd, rest, loop, Take.take); + loop.postEvent(.link_gone) catch {}; +} + +/// `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 (src/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'. +pub fn remote(init: std.process.Init, opts: pardes.Options, path: []const u8, session: []const u8) !void { + const io = init.io; + const gpa = init.gpa; + var why: [600]u8 = @splat(0); + var joined = replica.dial(gpa, path, session, &why) orelse { + var said: [700]u8 = undefined; + std.Io.File.stderr().writeStreamingAll(io, std.fmt.bufPrint(&said, "pardes: --attach: {s}\n", .{std.mem.sliceTo(&why, 0)}) catch "pardes: --attach failed\n") catch {}; + std.process.exit(1); + }; + defer _ = libc.close(joined.fd); + defer joined.rest.deinit(gpa); + + const allocs = pardes.memory.init(gpa); + defer pardes.memory.deinit(); + pardes.image.start(io, allocs.image); + if (comptime pardes.pdf_enabled) pardes.pdf.start(allocs.pdf); + pardes.syntax.start(allocs.tree_sitter); + defer { + pardes.image.stop(); + if (comptime pardes.pdf_enabled) pardes.pdf.stop(); + pardes.syntax.stop(); + } + var o = opts; + o.image_allocator = allocs.image; + o.pdf_allocator = allocs.pdf; + const r = replica.Replica.initDump(gpa, joined.client, joined.view, joined.dump, o) catch |err| { + gpa.free(joined.dump); + var said: [200]u8 = undefined; + std.Io.File.stderr().writeStreamingAll(io, std.fmt.bufPrint(&said, "pardes: --attach: the session's dump would not load: {t}\n", .{err}) catch "pardes: --attach: the dump would not load\n") catch {}; + std.process.exit(1); + }; + gpa.free(joined.dump); + defer r.deinit(); + r.gmtoff = joined.gmtoff; + if (!r.loaded(joined.digest)) { + std.Io.File.stderr().writeStreamingAll(io, "pardes: --attach: the session's dump loaded as another session (a build's dump is not complete)\n") catch {}; + std.process.exit(1); + } + + var winch_set = posix.sigemptyset(); + posix.sigaddset(&winch_set, posix.SIG.WINCH); + if (comptime builtin.os.tag == .freebsd) + posix.sigaction(.WINCH, &.{ .handler = .{ .handler = keepSignal }, .mask = posix.sigemptyset(), .flags = 0 }, null); + posix.sigprocmask(posix.SIG.BLOCK, &winch_set, null); + var tty_buf: [0x10000]u8 = undefined; + var screen: Screen = .{ .io = io, .gpa = gpa, .env = init.environ_map, .buf = &tty_buf, .kitty = .init(gpa), .primary = true }; + defer screen.kitty.deinit(); + try screen.enter(try vaxis.Tty.init(io, &tty_buf)); + defer screen.leave(); + defer screen.glide.deinit(gpa); + screen.feed.view = joined.view; + 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); + defer frame_arena.deinit(); + var link: Remote = .{ .r = r, .fd = joined.fd }; + if (init.environ_map.get("PARDES_REPLICA_CHECK")) |file| link.check = try gpa.dupeSentinel(u8, file, 0); + defer if (link.check) |file| gpa.free(file); + var sh: Shell = .{ + .io = io, + .gpa = gpa, + .lsp_gpa = allocs.lsp, + .core = r.core(), + .prompt_rcs = undefined, + .loop = &loop, + .frame = &frame_arena, + .paste_buf = &paste_buf, + .inotify_fd = -1, + .from = joined.view, + .remote = &link, + }; + sh.terms[joined.view] = &screen; + + try startInput(&loop, &screen); + defer stopInput(io, &screen.thread); + (try std.Thread.spawn(.{}, winchWatch, .{&loop})).detach(); + var reader_done: std.atomic.Value(bool) = .init(false); + const reader = try std.Thread.spawn(.{}, linkReader, .{ gpa, joined.fd, &joined.rest, &loop, &reader_done }); + if (link.check != null) (try std.Thread.spawn(.{}, wakeWatch, .{ io, &loop })).detach(); + try screen.vx.queryTerminalSend(screen.tty.writer()); + // Its size is its view's first input. + sh.winched(); + while (!link.quit) { + if (link.dirty) link.draw(&sh); + const first = (loop.tryEvent() catch null) orelse idle: { + // Idle, its frame drawn: the next key needs no copy taken. + r.ready(); + break :idle loop.nextEvent() catch break; + }; + var ev = first; + var batch: usize = 1; + while (true) { + _ = sh.apply(ev); + if (link.quit or (!sh.in_paste and batch >= 64)) break; + ev = (loop.tryEvent() catch null) orelse break; + batch += 1; + } + r.settle(); + 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) link.dirty = true; + if (link.check != null) { + // Quiet a while after a change: asked once (a wake, then the + // next quiet one). + if (first == .wake and link.changed and !link.asked and r.quiet()) { + link.changed = false; + link.asked = replica.askCheck(joined.fd); + } else if (link.changed and r.quiet()) requestWake(io, 300); + } + if (r.diverged) |reason| { + screen.leave(); + var said: [700]u8 = undefined; + std.Io.File.stderr().writeStreamingAll(io, std.fmt.bufPrint(&said, "pardes: --attach: this replica diverged from '{s}': {s}\n", .{ session, reason }) catch "pardes: --attach: diverged\n") catch {}; + std.process.exit(1); + } + } + if (init.environ_map.get("PARDES_REPLICA_STATS")) |file| link.writeStats(file); + if (!link.gone) replica.bye(joined.fd); + // The link's reader ends with the link, posting as it goes: what it + // and the terminal posted is let go until it has. + _ = libc.shutdown(joined.fd, 2); + while (true) { + while (loop.tryEvent() catch null) |ev| switch (ev) { + .unit => |b| std.heap.c_allocator.free(b), + .paste => |b| gpa.free(@constCast(b)), + else => {}, + }; + if (reader_done.load(.acquire)) break; + std.Thread.yield() catch {}; + } + reader.join(); + if (link.gone) { + screen.leave(); + var said: [300]u8 = undefined; + std.Io.File.stderr().writeStreamingAll(io, std.fmt.bufPrint(&said, "pardes: --attach: '{s}' let this client go (a Detach in it, or the session's end)\n", .{session}) catch "pardes: --attach: the session let this client go\n") catch {}; + } +} + /// A terminal a session draws on, while it has one: entered (raw, the /// alternate screen, mouse and paste reports) and left (all of it put back, /// the terminal closed) at the session's start and end, and at a detach and @@ -1462,6 +1739,10 @@ fn localSession( .test_clock = host_io.testClock(), }; sh.terms[0] = screen; + sh.peers = .{ .gpa = gpa, .io = io, .name = daemon.name(), .wake_ctx = loop, .wake = wakeForReplica }; + defer sh.peers.deinit(); + // Before the core goes: each client sees its link end. + defer sh.peers.dropAll(sh.core); pardes.lsp.setStatusSink(&sh, lspStatusSink); host_io.setExitWake(loop, wakeForExit); defer screen.glide.deinit(gpa); @@ -1524,7 +1805,7 @@ fn localSession( // An upgraded session's terminals, its own again. if (comptime !builtin.is_test) if (upgrade.resumed) |*rec| sh.resumeTerminals(rec, screen); // Nobody to see it, and nobody to size it: `size` sets it (ctl.zig). - core.unattended = !sh.attached(); + sh.setAttended(sh.attached()); while (core.nextEffect()) |effect| core.perform(effect); // ...and its shells, once a fresh session's own has a directory to // adopt them in. @@ -1564,6 +1845,8 @@ fn localSession( while (!core.quit) { pardes.turn.bump(&pardes.turn.restores); try core.pump(host); + // Its unit to each replica client, and theirs taken in. + sh.peers.boundary(core); upgrade.locate(); // Asked in the step (the word), done between steps: the session whole. if (sh.upgrade_asked) |pane| sh.upgradeNow(pane); @@ -1572,6 +1855,9 @@ fn localSession( // off a startup's way. daemon.watch(loop, deliverNote); if (core.takeRestore()) |rp| blk: { + // ponytail: a Restore replaces the core its clients replicate; + // they are let go, and attach again. + sh.peers.dropAll(core); const bytes = filesystem.readRestore(gpa, rp, core.settings.dump_dir.get()) catch |err| { core.reportError(core.active, "Restore", err); break :blk; @@ -1620,6 +1906,7 @@ fn localSession( if (live.on) clearNativeImages(&live.kitty, &live.vx, &live.tty); nc.native_images = live.on and live.vx.caps.kitty_graphics; nc.unattended = !live.on; + sh.peers.alone_unattended = !live.on; if (fs) |f| f.reset(nc); core.deinit(); core = nc; @@ -1664,9 +1951,21 @@ fn deliverNote(ctx: *anyopaque, note: daemon.Note) void { }; loop.postEvent(.{ .adopted = .{ .pid = 0, .fd = -1 } }) catch {}; }, + .replica => |fd| loop.postEvent(.{ .replica = fd }) catch { + _ = libc.close(fd); + }, } } +/// A replica reader's post: the session's wait ends, and its step +/// boundary takes the post in. +fn wakeForReplica(ctx: ?*anyopaque) void { + const loop: *Loop = @ptrCast(@alignCast(ctx.?)); + // Never waits: a full queue wakes the loop anyway, and a reader the + // loop is joining (a client let go) must not wait on it. + _ = loop.tryPostEvent(.replica_mail) catch {}; +} + const Shell = struct { io: std.Io, gpa: std.mem.Allocator, @@ -1718,9 +2017,42 @@ const Shell = struct { upgrade_asked: ?u8 = null, /// Its pty readers stopped for it: their end of file is not a shell's. upgrading: bool = false, + /// The session's replica clients (src/replica.zig), on sockets. + peers: replica.Peers = .{}, + /// This wait took only a replica's post (its input, its join): the + /// pump after it reads no new time, so it moves nothing the replicas' + /// speculations stand on (a replica takes such a unit as is). + mail_only: bool = false, + waited: bool = false, + /// This process a replica client of a session elsewhere (`remote`): + /// its inputs go to the replica, never straight to the core. + remote: ?*Remote = null, const Leaving = enum { detach, exit }; + /// A terminal's input, to the core, or to a replica client's engine + /// (applied at once there, and sent to the session). + fn feed(s: *Shell, ev: pardes.Event) void { + const c = s.remote orelse return s.core.update(ev); + const msg = c.r.input(ev) catch return; + if (!replica.sendInput(c.fd, msg)) c.quit = true; + c.dirty = true; + } + + /// Whether a terminal of this process's shows the session, or + /// nothing (a test) can. + fn local(s: *const Shell) bool { + for (s.terms) |slot| if (slot != null) return true; + return false; + } + + /// Whether anyone looks at the session: a terminal here, or a replica + /// client (Peers keeps it attended while one is there). + fn setAttended(s: *Shell, on: bool) void { + s.peers.alone_unattended = !on; + s.core.unattended = !on and s.peers.count() == 0; + } + fn of(ctx: ?*anyopaque) *Shell { return @ptrCast(@alignCast(ctx.?)); } @@ -1770,6 +2102,10 @@ const Shell = struct { fn clockNow(ctx: ?*anyopaque) u64 { const s = of(ctx); + if (s.waited) { + s.waited = false; + if (s.mail_only and s.peers.count() > 0 and s.core.clock_started) return s.core.now_ns; + } return s.test_clock orelse @intCast(std.Io.Clock.awake.now(s.io).nanoseconds); } @@ -1783,15 +2119,23 @@ const Shell = struct { return screen.on; } - /// Drawn only while a terminal shows it. + /// Drawn only while a terminal shows it: a replica client's view live + /// (its input the last), whichever terminal here shows another. fn watched(ctx: ?*anyopaque) bool { - return of(ctx).attached(); + const s = of(ctx); + if (s.term() == null and s.local()) { + for (s.terms) |slot| if (slot) |sc| if (sc.on) return true; + return false; + } + return s.attached(); } /// Detach: the terminal put back and let go, the stub told (it ends, /// and the shell has its terminal again), the session left running. fn detach(ctx: ?*anyopaque) void { const s = of(ctx); + // A replica client's: its link ends. + if (s.peers.detach(s.core.view)) return; if (!s.attached()) return s.core.reportFailure(s.core.active, "Detach: no terminal is attached"); // One of several: its view goes, and the session stays on the rest. if (pardes.views.count(s.core) > 1) return s.dropView(s.core.view, .detach); @@ -1835,7 +2179,7 @@ const Shell = struct { stopInput(s.io, &screen.thread); screen.leave(); s.core.native_images = false; - s.core.unattended = true; + s.setAttended(false); // The stub's stdin, stdout and stderr were its terminal too. const null_fd = libc.open("/dev/null", .{ .ACCMODE = .RDWR, .CLOEXEC = true }, @as(libc.mode_t, 0)); if (null_fd >= 0) { @@ -1883,7 +2227,7 @@ const Shell = struct { s.terms[k] = screen; } screen.setStub(stub); - s.core.unattended = false; + s.setAttended(true); startInput(s.loop, screen) catch {}; screen.vx.queryTerminalSend(screen.tty.writer()) catch {}; s.core.needs_frame = true; @@ -2124,6 +2468,8 @@ const Shell = struct { } s.input_seen = false; s.output_seen = false; + s.mail_only = true; + defer s.waited = true; // Paced, what is not an input (a frame's ack, a pty's output) is // taken in and the wait goes on to the tick: the acks alone ran the // loop at the terminal's round trip. @@ -2215,15 +2561,16 @@ const Shell = struct { else => {}, } if (s.input_seen) s.input_ns = @intCast(std.Io.Clock.awake.now(s.io).nanoseconds); + if (event != .replica_mail) s.mail_only = false; // A terminal's input goes into its view; a closed one's last is // dropped. switch (event) { .key_press, .mouse, .paste, .paste_start, .paste_end, .winsize, .focus_in, .focus_out, .quit => { - if (s.terms[s.from] == null and s.term() != null) { + if (s.terms[s.from] == null and s.local()) { if (event == .paste) s.gpa.free(@constCast(event.paste)); return false; } - if (s.term() != null) core.toView(s.from); + if (s.local() and s.remote == null) core.toView(s.from); }, else => {}, } @@ -2242,6 +2589,10 @@ const Shell = struct { virtual.* = @max(virtual.*, s.wake_to); }, .quit => { + if (s.remote) |c| { + c.quit = true; + return true; + } // One of several: its view goes with it. if (pardes.views.count(core) > 1) { s.dropView(core.view, .detach); @@ -2261,15 +2612,37 @@ const Shell = struct { }, .attach => |a| s.attachTerminal(a.tty, a.stub, null), .adopted => |a| s.adoptShell(a.pid, a.fd), + .replica => |fd| { + s.peers.handed(fd); + s.input_seen = true; + }, + .replica_mail => s.input_seen = true, + .unit => |bytes| { + if (s.remote) |c| { + c.r.confirm(bytes); + if (c.r.moved) c.dirty = true; + c.r.moved = false; + c.changed = true; + } + std.heap.c_allocator.free(bytes); + }, + .checked => |d| if (s.remote) |c| c.checked(d), + .link_gone => if (s.remote) |c| { + c.quit = true; + c.gone = true; + return true; + }, .focus_in => { - core.update(.{ .focus = true }); - upgrade.noticeNewer(core); + s.feed(.{ .focus = true }); + // A client's core is the session's: the notice is the session's to give. + // ponytail: not while clients replicate it (set outside a step). + if (s.remote == null and !s.peers.recording) upgrade.noticeNewer(core); }, .focus_out => { - core.update(.pointer_leave); - core.update(.{ .focus = false }); + s.feed(.pointer_leave); + s.feed(.{ .focus = false }); }, - .winsize => |ws| if (s.attached()) s.resized(ws), + .winsize => |ws| if (s.attached()) s.resized(s.terms[s.from], ws), .pty_read => |pr| { tookRead(s.io, pr.id); s.output_seen = true; @@ -2306,10 +2679,10 @@ const Shell = struct { const bytes = pasteBytes(key); const room = max_paste_bytes -| s.paste_buf.written().len; s.paste_buf.writer.writeAll(bytes[0..@min(bytes.len, room)]) catch {}; - } else core.update(vaxis_input.keyEvent(key)), + } else s.feed(vaxis_input.keyEvent(key)), .mouse => |m| { const pdf_before = nativePdfWheelTarget(core, m); - if (mouseEvent(m)) |ev| core.update(ev); + if (mouseEvent(m)) |ev| s.feed(ev); if (pdf_before) |before| { if (core.panes[before.pane]) |pane| { if (pane.pdfPage()) |page| { @@ -2319,7 +2692,7 @@ const Shell = struct { } }, .paste => |bytes| { - core.update(.{ .paste = bytes }); + s.feed(.{ .paste = bytes }); s.gpa.free(@constCast(bytes)); }, .paste_start => { @@ -2329,7 +2702,7 @@ const Shell = struct { .paste_end => { s.in_paste = false; const pasted = s.paste_buf.written(); - if (pasted.len > 0) core.update(.{ .paste = pasted }); + if (pasted.len > 0) s.feed(.{ .paste = pasted }); s.paste_buf.clearRetainingCapacity(); }, .files_changed => s.check_files = true, @@ -2366,17 +2739,13 @@ const Shell = struct { return false; } - /// The live view's terminal is `ws` big. - fn resized(s: *Shell, ws: vaxis.Winsize) void { - const core = s.core; - if (s.term()) |sc| { + /// Terminal `screen` (the live view's) is `ws` big. + fn resized(s: *Shell, screen: ?*Screen, ws: vaxis.Winsize) void { + if (screen) |sc| { sc.size = ws; sc.vx.resize(s.gpa, sc.tty.writer(), ws) catch {}; } - if (comptime pardes.pdf_enabled) - updateCoreTerminalSize(core, ws.cols, ws.rows, ws.x_pixel, ws.y_pixel) - else - core.update(.{ .resize = .{ .cols = ws.cols, .rows = ws.rows } }); + s.feed(.{ .resize = if (comptime pardes.pdf_enabled) terminalSize(ws.cols, ws.rows, ws.x_pixel, ws.y_pixel) else .{ .cols = ws.cols, .rows = ws.rows } }); } /// A SIGWINCH: each terminal whose size it changed is resized, in its @@ -2387,8 +2756,8 @@ const Shell = struct { if (!sc.on or sc.vx.state.in_band_resize) continue; const ws = sc.tty.getWinsize() catch continue; if (sc.size) |was| if (std.meta.eql(was, ws)) continue; - s.core.toView(@intCast(k)); - s.resized(ws); + if (s.remote == null) s.core.toView(@intCast(k)); + s.resized(sc, ws); } } |
