diff options
| author | Gabriel Schneider <[email protected]> | 2026-10-29 17:01:35 -0300 |
|---|---|---|
| committer | Gabriel Schneider <[email protected]> | 2026-10-29 19:38:53 -0300 |
| commit | 2cce341e2c94fb3150dc1f3e7911c26502a70487 (patch) | |
| tree | c637fcfa9a52aa66f6c34600f4cdea4020088e01 /src/tty/tty.zig | |
| parent | c2b4f235e78735102c691677f08bd1b2403168df (diff) | |
| download | pardes-2cce341e2c94fb3150dc1f3e7911c26502a70487.tar.gz pardes-2cce341e2c94fb3150dc1f3e7911c26502a70487.zip | |
views: several clients on one session, each its own layout, focus, cursors and scroll over the panes they share; a second `pardes --attach` draws on its own terminal beside the first, and `pardes-gui --attach` opens another window
The core still sees one view, the live one, in the fields it always had (src/views.zig): a view's share of the session (`views.fields`: its screen, columns, rects, focus, pointer and gestures, jumps, key prefixes, column tags, presentation and animations, windowed and native_images) and of each pane (`PaneView`: its place in the layout, which text has the keyboard, the body's cursor, selections and mode, its scroll, a document's size, what the step measured of it) is copied out when another view goes live and back when it is live again. One view never parks: the single client pays a test of one byte a step. `toView`, `openView` and `closeView` are taped inputs; the pump draws each other view by going into it and back, which leaves every digested field as it was, so the replica that draws nothing skips it. A parked view is in no digest (its slot is written whenever it goes out); what drawing it made of its own (animations, presentation) is kept, whatever its unpark brought inside a changed text is done again when it is next live.
Shared: the panes' text, terminals, tags, prompts, messages, registers (yanked in one view, put in another), the workspace tag and settings. A terminal shown at two sizes takes the size of the view that typed into it last (`Pane.sized_by`), and any view's once that one is gone; the others show it at that size. A text edited in one view moves the other views' cursors and scroll with the splice, as a Zerox twin's (File.ParkedPlaces). A pane closed in one view leaves the others' layouts (by its slot's serial); a pane focused in a view that does not show it is placed in its active column (views.show).
tty: each terminal is a Screen of its own (its vaxis, input reader, frame answer, kitty images and shm probe, glide, trail and flash); its input reaches the loop as its view's (a `from` ahead of it when another terminal posted last, so one terminal posts none). A SIGWINCH asks every terminal its size; a SIGHUP asks each whether it hung up or lost its stub. Detach, or a terminal's end, with other views left closes only that view, its stub told `d`; the session's end tells every stub. daemon.zig: an attach names an attached session too (or the only one there is when none is detached).
gui: the Gui holds the live window's share of itself (window_fields: the SDL window and its presenting, scroll, glide, scene and post chain, pointer, blink, captures); the others wait in Shell.windows, swapped in (`follow`) as the core's live view changes, and each SDL event first takes its window's view live (`route`). Closing a window while others stay closes its view.
Harnesses: `start <rows> <cols> views=N` in a snapshot script gives the app N-1 more terminals (PARDES_TEST_VIEWS, opened as attached ones), `view <k>` types into and captures terminal k, every wait reads them all; `pardes-monkey --views=N` switches among N; `zig build replay` runs its seeds at three views too. views.snap pins two terminals: an edit seen in both, a scroll in one, a line yanked in one and put in the other, Newcol in one, Detach in one. Unit tests: own cursor, scroll, mode, layout and focus; edits shared; registers shared; terminal size by last typist; closing views; drawing the others leaves the digest; a view keeps its place in a text another edits.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Diffstat (limited to 'src/tty/tty.zig')
| -rw-r--r-- | src/tty/tty.zig | 666 |
1 files changed, 429 insertions, 237 deletions
diff --git a/src/tty/tty.zig b/src/tty/tty.zig index 760c0692..f949d571 100644 --- a/src/tty/tty.zig +++ b/src/tty/tty.zig @@ -21,15 +21,45 @@ extern "c" fn setenv(name: [*:0]const u8, value: [*:0]const u8, overwrite: c_int const TIOCSWINSZ: c_int = @bitCast(@as(u32, if (@hasDecl(posix.T, "IOCSWINSZ")) posix.T.IOCSWINSZ else 0x80087467)); -/// The terminal answered the shared-memory probe (`kittyShmProbe`): it can -/// read a raster from a POSIX shm object, so a page costs a name on the wire -/// instead of its whole base64 body. Set by the input reader, which sees the -/// reply before vaxis' parser swallows every graphics APC alike. -var kitty_shm = std.atomic.Value(bool).init(false); -/// Only a reply that arrives while the probe is out counts. The id is one -/// vaxis' own image numbering (1, 2, ...) never reaches, because a terminal -/// answers every transmission `i=<id>;OK` and one of those must not pass. -var kitty_shm_probing = std.atomic.Value(bool).init(false); +/// What a terminal's input reader keeps, one a terminal (views.zig): its +/// graphemes, the frame it waits on the answer to, the shm probe, and the +/// view its input is. +const Feed = struct { + view: u8 = 0, + cache: vaxis.GraphemeCache = .{}, + ack: FrameAck = .{}, + /// The terminal answered the shared-memory probe (`kittyShmProbe`): it + /// can read a raster from a POSIX shm object, so a page costs a name on + /// the wire instead of its whole base64 body. Set by the input reader, + /// which sees the reply before vaxis' parser swallows every graphics APC + /// alike. + shm: std.atomic.Value(bool) = .init(false), + /// Only a reply that arrives while the probe is out counts. The id is + /// one vaxis' own image numbering (1, 2, ...) never reaches, because a + /// terminal answers every transmission `i=<id>;OK` and one of those must + /// not pass. + shm_probing: std.atomic.Value(bool) = .init(false), +}; + +/// A terminal's input onto the loop's queue, as its view's: a `from` goes +/// ahead of it whenever another terminal posted last. With one terminal +/// none ever does. +const Poster = struct { + loop: *Loop, + view: u8, + var lock: std.Io.Mutex = .init; + var last: u8 = 0; + + pub fn postEvent(p: Poster, ev: @TypeOf(Command.value)) !void { + lock.lockUncancelable(p.loop.io); + defer lock.unlock(p.loop.io); + if (last != p.view) { + try p.loop.postEvent(.{ .from = p.view }); + last = p.view; + } + try p.loop.postEvent(ev); + } +}; const kitty_shm_probe_id = 0x7fff_fff1; var kitty_shm_serial: u32 = 0; /// Transmissions an unread shm segment outlives before it is removed. @@ -62,13 +92,13 @@ fn kittyShmWrite(name: [:0]const u8, bytes: []const u8) bool { /// Ask with a 1x1 RGB image in shm whether the terminal reads that medium. A /// remote terminal cannot see our shm and answers an error (or nothing). -fn kittyShmProbe(w: *std.Io.Writer) void { +fn kittyShmProbe(w: *std.Io.Writer, feed: *Feed) void { var buf: [64]u8 = undefined; const name = kittyShmName(&buf, 0) catch return; if (!kittyShmWrite(name, &.{ 0, 0, 0 })) return; var b64: [64]u8 = undefined; const enc = std.base64.standard.Encoder.encode(&b64, name); - kitty_shm_probing.store(true, .release); + feed.shm_probing.store(true, .release); w.print("\x1b_Gi={d},s=1,v=1,a=q,t=s,f=24;{s}\x1b\\", .{ kitty_shm_probe_id, enc }) catch return; w.flush() catch {}; } @@ -86,6 +116,12 @@ pub const Command = struct { adopted: struct { pid: posix.pid_t, fd: posix.fd_t }, /// A timed wait ran out: the core's next wake has come. wake, + /// The input after this is the terminal of this view's (Poster). + from: u8, + /// A SIGWINCH: a terminal changed size (Shell.winched). + winched, + /// A SIGHUP: the session's own terminal hung up. + hangup, key_press: vaxis.Key, pty_read: struct { id: usize, gen: u32, bytes: []u8 }, pty_eof: struct { id: usize, gen: u32 }, @@ -107,36 +143,36 @@ pub const Command = struct { }; const Loop = vaxis.Loop(@TypeOf(Command.value)); -fn startInput(loop: *Loop, cache: *vaxis.GraphemeCache) !void { +fn startInput(loop: *Loop, sc: *Screen) !void { if (comptime builtin.os.tag == .windows) return loop.start(); - if (loop.thread != null) return; - loop.thread = try loop.io.concurrent(inputThread, .{ loop, cache }); + if (sc.thread != null) return; + sc.thread = try loop.io.concurrent(inputThread, .{ loop, sc }); } -fn stopInput(loop: *Loop) void { - if (comptime builtin.os.tag == .windows) return loop.stop(); - if (loop.thread) |*thread| { - thread.cancel(loop.io); - loop.thread = null; +fn stopInput(io: std.Io, thread: *?std.Io.Future(void)) void { + if (thread.*) |*t| { + t.cancel(io); + thread.* = null; } } -fn inputThread(loop: *Loop, cache: *vaxis.GraphemeCache) void { +fn inputThread(loop: *Loop, sc: *Screen) void { // vaxis's test terminal reads nothing off Linux: it has no read at all. if (comptime !@hasDecl(vaxis.Tty, "read")) return; - inputReader(loop, loop.tty, cache); + inputReader(loop, &sc.tty, &sc.vx, &sc.feed); } -fn inputReader(loop: *Loop, tty: anytype, cache: *vaxis.GraphemeCache) void { - readInput(loop, tty, cache) catch |err| { +fn inputReader(loop: *Loop, tty: anytype, vx: *vaxis.Vaxis, feed: *Feed) void { + readInput(loop, tty, vx, feed) catch |err| { if (err == error.Canceled) return; std.log.err("terminal input: {s}", .{@errorName(err)}); }; - loop.postEvent(.quit) catch {}; + (Poster{ .loop = loop, .view = feed.view }).postEvent(.quit) catch {}; } -fn readInput(loop: *Loop, tty: anytype, cache: *vaxis.GraphemeCache) !void { - try loop.postEvent(.{ .winsize = try tty.getWinsize() }); +fn readInput(loop: *Loop, tty: anytype, vx: *vaxis.Vaxis, feed: *Feed) !void { + const post: Poster = .{ .loop = loop, .view = feed.view }; + try post.postEvent(.{ .winsize = try tty.getWinsize() }); var parser: vaxis.Parser = .{}; var buf: [1024]u8 = undefined; var carried: usize = 0; @@ -147,14 +183,14 @@ fn readInput(loop: *Loop, tty: anytype, cache: *vaxis.GraphemeCache) !void { // The terminal's answers to frames (FrameAck) come out first, // wherever they sit: never events, and never glued to a key (an // Escape pressed just before one would read as Alt on it). - const end = FrameAck.take(buf[0 .. carried + received], loop); + const end = feed.ack.take(buf[0 .. carried + received], loop); if (end == 0) { carried = 0; continue; } - if (kitty_shm_probing.load(.acquire)) if (std.mem.indexOf(u8, buf[0..end], std.fmt.comptimePrint("\x1b_Gi={d};", .{kitty_shm_probe_id}))) |at| { - kitty_shm_probing.store(false, .release); - kitty_shm.store(std.mem.startsWith(u8, buf[at..end], std.fmt.comptimePrint("\x1b_Gi={d};OK", .{kitty_shm_probe_id})), .release); + if (feed.shm_probing.load(.acquire)) if (std.mem.indexOf(u8, buf[0..end], std.fmt.comptimePrint("\x1b_Gi={d};", .{kitty_shm_probe_id}))) |at| { + feed.shm_probing.store(false, .release); + feed.shm.store(std.mem.startsWith(u8, buf[at..end], std.fmt.comptimePrint("\x1b_Gi={d};OK", .{kitty_shm_probe_id})), .release); // Answered either way: a terminal that could not read it left it. var name_buf: [64]u8 = undefined; if (kittyShmName(&name_buf, 0)) |name| _ = libc.shm_unlink(name) else |_| {} @@ -187,9 +223,9 @@ fn readInput(loop: *Loop, tty: anytype, cache: *vaxis.GraphemeCache) !void { std.mem.startsWith(u8, FrameAck.answer, rest)) break; if (!waited and parse_end == end and rest[0] == 0x1b and (rest.len == 1 or (rest.len == 2 and rest[1] == 0x1b))) { waited = true; - if (try inputFollows(tty, loop.io, if (loop.vaxis.caps.kitty_keyboard) 1000 else 50)) break; + if (try inputFollows(tty, loop.io, if (vx.caps.kitty_keyboard) 1000 else 50)) break; } - const result = try parser.parse(buf[consumed..parse_end], loop.vaxis.opts.system_clipboard_allocator); + const result = try parser.parse(buf[consumed..parse_end], vx.opts.system_clipboard_allocator); if (result.n == 0) break; consumed += result.n; // A modifier pressed on its own, which the kitty keyboard @@ -197,8 +233,8 @@ fn readInput(loop: *Loop, tty: anytype, cache: *vaxis.GraphemeCache) !void { // chord, and a shell pane was typed its private-use code. if (result.event) |event| if (event == .key_press and event.key_press.isModifier()) continue; if (result.event) |event| - vaxis.loop.handleEventGeneric(loop, loop.vaxis, cache, @TypeOf(Command.value), event, loop.vaxis.opts.system_clipboard_allocator) catch |err| { - if (event == .paste) if (loop.vaxis.opts.system_clipboard_allocator) |gpa| gpa.free(@constCast(event.paste)); + vaxis.loop.handleEventGeneric(post, vx, &feed.cache, @TypeOf(Command.value), event, vx.opts.system_clipboard_allocator) catch |err| { + if (event == .paste) if (vx.opts.system_clipboard_allocator) |gpa| gpa.free(@constCast(event.paste)); return err; }; // The last answer to the startup queries is no event of its @@ -226,14 +262,14 @@ const FrameAck = struct { const request = "\x1b[5n"; const answer = "\x1b[0n"; const timeout_ns: u64 = std.time.ns_per_s; - var waiting = std.atomic.Value(bool).init(false); - var off = std.atomic.Value(bool).init(false); + waiting: std.atomic.Value(bool) = .init(false), + off: std.atomic.Value(bool) = .init(false), /// When the request went out (the loop's thread only). - var sent_ns: u64 = 0; + sent_ns: u64 = 0, /// Take every answer out of `bytes`, closing up the rest; the new /// length. The loop is woken for the frame that waited on one. - fn take(bytes: []u8, loop: *Loop) usize { + fn take(a: *FrameAck, bytes: []u8, loop: *Loop) usize { var len = bytes.len; var found = false; while (std.mem.indexOf(u8, bytes[0..len], answer)) |at| { @@ -241,18 +277,18 @@ const FrameAck = struct { len -= answer.len; found = true; } - if (found and waiting.swap(false, .acq_rel)) loop.postEvent(.nop) catch {}; + if (found and a.waiting.swap(false, .acq_rel)) loop.postEvent(.nop) catch {}; return len; } /// Whether a new frame must wait (and the loop has a wake at the /// timeout); past the timeout the terminal is taken to never answer. - fn holds(now_ns: u64, io: std.Io) bool { - if (off.load(.acquire) or !waiting.load(.acquire)) return false; - const waited_ns = now_ns -| sent_ns; + fn holds(a: *FrameAck, now_ns: u64, io: std.Io) bool { + if (a.off.load(.acquire) or !a.waiting.load(.acquire)) return false; + const waited_ns = now_ns -| a.sent_ns; if (waited_ns >= timeout_ns) { - off.store(true, .release); - waiting.store(false, .release); + a.off.store(true, .release); + a.waiting.store(false, .release); return false; } requestWake(io, @intCast((timeout_ns - waited_ns + std.time.ns_per_ms - 1) / std.time.ns_per_ms)); @@ -260,14 +296,14 @@ const FrameAck = struct { } /// After a frame that wrote something: ask for the answer. - fn ask(w: *std.Io.Writer, now_ns: u64) void { - if (off.load(.acquire)) return; + fn ask(a: *FrameAck, w: *std.Io.Writer, now_ns: u64) void { + if (a.off.load(.acquire)) return; // Waiting before the request goes: a local terminal can answer // before the write returns, and an answer nobody waited for is lost. - sent_ns = now_ns; - waiting.store(true, .release); - w.writeAll(request) catch return waiting.store(false, .release); - w.flush() catch return waiting.store(false, .release); + a.sent_ns = now_ns; + a.waiting.store(true, .release); + w.writeAll(request) catch return a.waiting.store(false, .release); + w.flush() catch return a.waiting.store(false, .release); } }; @@ -299,7 +335,7 @@ test "terminal input preserves fragmented keys queries paste and text after EOF" vx.queries_done.store(false, .unordered); var tty: vaxis.Tty = undefined; var loop: Loop = .init(io, &tty, &vx); - var cache: vaxis.GraphemeCache = .{}; + var feed: Feed = .{}; const Reader = struct { parts: []const []const u8, next: usize = 0, @@ -321,7 +357,7 @@ test "terminal input preserves fragmented keys queries paste and text after EOF" "plain \x1b[?62;", "4c\x1b[", "A\x1b[200", "~caf\xc3", "\xa9 \xe7", "\x95", "\x8c \xf0\x9f", "\x98\x80", "\x1b[201", "~\x1b]52;c;Y2", "xpcA==\x07tail", "\x1b", } }; - try readInput(&loop, &reader, &cache); + try readInput(&loop, &reader, &vx, &feed); try std.testing.expect(vx.queries_done.load(.unordered)); var text: std.ArrayList(u8) = .empty; defer text.deinit(gpa); @@ -384,7 +420,7 @@ test "terminal replies and malformed sequences never become typed text" { vx.queries_done.store(false, .unordered); var tty: vaxis.Tty = undefined; var loop: Loop = .init(io, &tty, &vx); - var cache: vaxis.GraphemeCache = .{}; + var feed: Feed = .{}; const Reader = struct { parts: []const []const u8, next: usize = 0, @@ -427,7 +463,7 @@ test "terminal replies and malformed sequences never become typed text" { "c", }, }; - try readInput(&loop, &reader, &cache); + try readInput(&loop, &reader, &vx, &feed); try std.testing.expect(vx.queries_done.load(.unordered)); try std.testing.expect(vx.caps.kitty_graphics); var text: std.ArrayList(u8) = .empty; @@ -466,7 +502,7 @@ test "terminal input split at every byte with a gap reads as it does whole" { defer vx.deinit(gpa, &output.writer); var tty: vaxis.Tty = undefined; var loop: Loop = .init(io, &tty, &vx); - var cache: vaxis.GraphemeCache = .{}; + var feed: Feed = .{}; // Two reads with `gap_ms` between them, as an ssh link delivers a // sequence cut across two packets. const Reader = struct { @@ -531,7 +567,7 @@ test "terminal input split at every byte with a gap reads as it does whole" { const all = try std.mem.concat(gpa, u8, &.{ "x", case.bytes, "y" }); defer gpa.free(all); var one: Reader = .{ .parts = .{ all, "" }, .gap_ms = 0 }; - try readInput(&loop, &one, &cache); + try readInput(&loop, &one, &vx, &feed); try Reader.events(&loop, &whole); for (1..all.len) |cut| { // A cut just after an ESC is the one that has to wait, and a @@ -539,7 +575,7 @@ test "terminal input split at every byte with a gap reads as it does whole" { // anywhere else is carried however long the gap. const after_esc = all[cut - 1] == 0x1b; var two: Reader = .{ .parts = .{ all[0..cut], all[cut..] }, .gap_ms = if (after_esc and !case.kitty) 40 else 60 }; - try readInput(&loop, &two, &cache); + try readInput(&loop, &two, &vx, &feed); try Reader.events(&loop, &split); std.testing.expectEqualStrings(whole.items, split.items) catch |err| { std.debug.print("case {f} cut at {d}\n", .{ std.ascii.hexEscape(case.bytes, .lower), cut }); @@ -562,7 +598,7 @@ test "an ESC read by itself is the Escape key at once" { defer vx.deinit(gpa, &output.writer); var tty: vaxis.Tty = undefined; var loop: Loop = .init(io, &tty, &vx); - var cache: vaxis.GraphemeCache = .{}; + var feed: Feed = .{}; // More always follows at once: a reader that waited on the ESC would // take `j` for the rest of its sequence (Alt-j). const Reader = struct { @@ -587,7 +623,7 @@ test "an ESC read by itself is the Escape key at once" { for ([_]bool{ false, true }) |kitty| { vx.caps.kitty_keyboard = kitty; var reader: Reader = .{ .parts = &.{ "\x1b", "j" } }; - try readInput(&loop, &reader, &cache); + try readInput(&loop, &reader, &vx, &feed); try std.testing.expect(!reader.asked); try std.testing.expectEqual(.winsize, std.meta.activeTag((try loop.tryEvent()).?)); const escape = (try loop.tryEvent()).?.key_press; @@ -613,7 +649,7 @@ test "a frame's answer is taken wherever the reads cut it, and never typed" { defer vx.deinit(gpa, &output.writer); var tty: vaxis.Tty = undefined; var loop: Loop = .init(io, &tty, &vx); - var cache: vaxis.GraphemeCache = .{}; + var feed: Feed = .{}; const Reader = struct { parts: [2][]const u8, next: usize = 0, @@ -635,12 +671,12 @@ test "a frame's answer is taken wherever the reads cut it, and never typed" { } }; const all = "x" ++ FrameAck.answer ++ "y"; - defer FrameAck.waiting.store(false, .release); + defer feed.ack.waiting.store(false, .release); for (0..all.len) |cut| { - FrameAck.waiting.store(true, .release); + feed.ack.waiting.store(true, .release); var reader: Reader = .{ .parts = .{ all[0..cut], all[cut..] } }; - try readInput(&loop, &reader, &cache); - try std.testing.expect(!FrameAck.waiting.load(.acquire)); + try readInput(&loop, &reader, &vx, &feed); + try std.testing.expect(!feed.ack.waiting.load(.acquire)); var typed: std.ArrayList(u8) = .empty; defer typed.deinit(gpa); var woke = false; @@ -658,9 +694,9 @@ test "a frame's answer is taken wherever the reads cut it, and never typed" { } // An Escape pressed just before an answer, in the same read, is the // Escape key, not Alt on the answer. - FrameAck.waiting.store(true, .release); + feed.ack.waiting.store(true, .release); var glued: Reader = .{ .parts = .{ "\x1b" ++ FrameAck.answer, "j" } }; - try readInput(&loop, &glued, &cache); + try readInput(&loop, &glued, &vx, &feed); try std.testing.expectEqual(.winsize, std.meta.activeTag((try loop.tryEvent()).?)); try std.testing.expectEqual(.nop, std.meta.activeTag((try loop.tryEvent()).?)); const escape = (try loop.tryEvent()).?.key_press; @@ -672,25 +708,21 @@ test "a frame's answer is taken wherever the reads cut it, and never typed" { test "a terminal that never answers a frame stops being asked after one timeout" { const io = std.testing.io; - defer { - FrameAck.off.store(false, .release); - FrameAck.waiting.store(false, .release); - FrameAck.sent_ns = 0; - } + var ack: FrameAck = .{}; var out: std.Io.Writer.Allocating = .init(std.testing.allocator); defer out.deinit(); const t0: u64 = 5 * std.time.ns_per_s; - FrameAck.ask(&out.writer, t0); + ack.ask(&out.writer, t0); try std.testing.expectEqualStrings(FrameAck.request, out.written()); // Unanswered: the next frame waits, until the timeout. - try std.testing.expect(FrameAck.holds(t0 + 10 * std.time.ns_per_ms, io)); - try std.testing.expect(FrameAck.holds(t0 + 999 * std.time.ns_per_ms, io)); - try std.testing.expect(!FrameAck.holds(t0 + FrameAck.timeout_ns, io)); + try std.testing.expect(ack.holds(t0 + 10 * std.time.ns_per_ms, io)); + try std.testing.expect(ack.holds(t0 + 999 * std.time.ns_per_ms, io)); + try std.testing.expect(!ack.holds(t0 + FrameAck.timeout_ns, io)); // Then never again: no request, no wait. out.clearRetainingCapacity(); - FrameAck.ask(&out.writer, t0 + 2 * std.time.ns_per_s); + ack.ask(&out.writer, t0 + 2 * std.time.ns_per_s); try std.testing.expectEqual(@as(usize, 0), out.written().len); - try std.testing.expect(!FrameAck.holds(t0 + 2 * std.time.ns_per_s, io)); + try std.testing.expect(!ack.holds(t0 + 2 * std.time.ns_per_s, io)); } test "terminal input cancellation joins blocked reads and queued EOF" { @@ -724,8 +756,8 @@ test "terminal input cancellation joins blocked reads and queued EOF" { } return self.file.readStreaming(std.testing.io, &.{buf}); } - fn run(loop: *Loop, reader: *@This(), cache: *vaxis.GraphemeCache) void { - inputReader(loop, reader, cache); + fn run(loop: *Loop, reader: *@This(), vx_: *vaxis.Vaxis, feed: *Feed) void { + inputReader(loop, reader, vx_, feed); } }; const Case = enum { blocked_read, cancel_eof, deliver_eof }; @@ -738,9 +770,9 @@ test "terminal input cancellation joins blocked reads and queued EOF" { var reader: Reader = .{ .file = .{ .handle = fds[0], .flags = .{ .nonblocking = false } }, .eof = eof }; var tty: vaxis.Tty = undefined; var loop: Loop = .init(io, &tty, &vx); - var cache: vaxis.GraphemeCache = .{}; - loop.thread = try io.concurrent(Reader.run, .{ &loop, &reader, &cache }); - defer stopInput(&loop); + var feed: Feed = .{}; + var thread: ?std.Io.Future(void) = try io.concurrent(Reader.run, .{ &loop, &reader, &vx, &feed }); + defer stopInput(io, &thread); try std.testing.expectEqual(.winsize, std.meta.activeTag(try loop.nextEvent())); try reader.entered.wait(io); if (eof) { @@ -750,10 +782,10 @@ test "terminal input cancellation joins blocked reads and queued EOF" { } if (case == .deliver_eof) { try std.testing.expectEqual(.nop, std.meta.activeTag(try loop.nextEvent())); - loop.thread.?.await(io); + thread.?.await(io); } - stopInput(&loop); - try std.testing.expect(loop.thread == null); + stopInput(io, &thread); + try std.testing.expect(thread == null); var count: usize = 0; while (try loop.tryEvent()) |event| { const expected: std.meta.Tag(@TypeOf(Command.value)) = if (case == .deliver_eof and count == 511) .quit else .nop; @@ -1194,7 +1226,8 @@ pub fn run(init: std.process.Init, opts: pardes.Options, term: Term) !void { 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 }; + var screen: Screen = .{ .io = io, .gpa = gpa, .env = init.environ_map, .buf = &tty_buf, .kitty = .init(gpa), .primary = true }; + defer screen.kitty.deinit(); switch (term) { .open => try screen.enter(try vaxis.Tty.init(io, &tty_buf)), .fd => |fd| try screen.enter(try Screen.ttyOn(io, &tty_buf, fd)), @@ -1202,27 +1235,19 @@ pub fn run(init: std.process.Init, opts: pardes.Options, term: Term) !void { } defer screen.leave(); - var kitty_handles = std.AutoHashMap(pardes.ImageCacheKey, vaxis.Image).init(gpa); - defer { - if (screen.on) clearNativeImages(&kitty_handles, &screen.vx, &screen.tty); - kitty_handles.deinit(); - } var paste_buf: std.Io.Writer.Allocating = .init(gpa); defer paste_buf.deinit(); var loop: Loop = .init(io, &screen.tty, &screen.vx); - var input_cache: vaxis.GraphemeCache = .{}; - try localSession(init, opts, &screen, &loop, &input_cache, &kitty_handles, &paste_buf); + try localSession(init, opts, &screen, &loop, &paste_buf); } -/// Whether a terminal is there to ask its size (winchWatch): none while -/// detached, when the descriptor it had may be another's. -var terminal_on = std.atomic.Value(bool).init(false); - -/// The terminal a session draws on, while it has one: entered (raw, the +/// 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 -/// a reattach in between (daemon.zig). +/// a reattach in between (daemon.zig). One a view (views.zig): the session's +/// own (`primary`, its stub `daemon.stub`), and one more for each terminal +/// `pardes --attach`ed while it is attached, which keeps its own. const Screen = struct { io: std.Io, gpa: std.mem.Allocator, @@ -1231,6 +1256,24 @@ const Screen = struct { tty: vaxis.Tty = undefined, vx: vaxis.Vaxis = undefined, on: bool = false, + primary: bool = false, + /// The pipe to its stub, an attached one's (the primary's is daemon.stub). + stub: posix.fd_t = -1, + /// Its slot in Killed. + killed: ?usize = null, + feed: Feed = .{}, + thread: ?std.Io.Future(void) = null, + kitty: std.AutoHashMap(pardes.ImageCacheKey, vaxis.Image), + caps_pending: bool = true, + /// Its size as last taken (`Shell.resized`). + size: ?vaxis.Winsize = null, + tracks: []const pardes.animation.Track = &.{}, + /// T2: the cursor's jump trail (JumpTrail). + trail: JumpTrail = .{}, + /// The view's glide, the GUI's motion drawn at whole rows (anim 12). + glide: pardes.glide.Glide = .{}, + /// T7: when each pane's view last moved (ThumbFlash). + flash: ThumbFlash = .{}, /// `fd` made raw, as vaxis.Tty.init makes /dev/tty: the terminal of a /// forked session is no controlling terminal of its, which /dev/tty is. @@ -1250,56 +1293,88 @@ const Screen = struct { try sc.vx.setMouseMode(sc.tty.writer(), true); try sc.vx.setBracketedPaste(sc.tty.writer(), true); if (comptime !builtin.is_test) { - Killed.arm(sc.tty.fd.handle, sc.tty.termios); + sc.killed = Killed.arm(sc.tty.fd.handle, sc.tty.termios); // What a panic puts back (vaxis.recover). - vaxis.tty.global_tty = sc.tty; + if (sc.primary) vaxis.tty.global_tty = sc.tty; } + const view = sc.feed.view; + sc.feed = .{ .view = view }; + sc.caps_pending = true; + sc.size = null; sc.on = true; - terminal_on.store(true, .release); } fn leave(sc: *Screen) void { if (!sc.on) return; sc.on = false; - terminal_on.store(false, .release); - Killed.disarm(); + if (sc.killed) |slot| Killed.disarm(slot); + sc.killed = null; + clearNativeImages(&sc.kitty, &sc.vx, &sc.tty); sc.vx.exitAltScreen(sc.tty.writer()) catch {}; sc.vx.deinit(sc.gpa, sc.tty.writer()); - if (comptime !builtin.is_test) vaxis.tty.global_tty = null; + if (comptime !builtin.is_test) if (sc.primary) { + vaxis.tty.global_tty = null; + }; sc.tty.deinit(); // restore cooked termios LAST, after vx flushed its resets } + + /// Its stub told the terminal is detached (it ends, and its shell has + /// the terminal back). + fn sayDetached(sc: *Screen) void { + if (sc.primary) return daemon.tellStubDetached(); + daemon.tellDetached(sc.stub); + sc.stub = -1; + } + + /// Its terminal hung up, or the stub that waits on it is gone. + fn hungUp(sc: *const Screen) bool { + const stub = if (sc.primary) daemon.stub else sc.stub; + var fds = [_]posix.pollfd{ + .{ .fd = sc.tty.fd.handle, .events = 0, .revents = 0 }, + .{ .fd = stub, .events = 0, .revents = 0 }, + }; + _ = posix.poll(fds[0..if (stub >= 0) 2 else 1], 0) catch return false; + const gone = posix.POLL.HUP | posix.POLL.ERR; + return fds[0].revents & gone != 0 or (stub >= 0 and fds[1].revents & gone != 0); + } + + fn setStub(sc: *Screen, fd: posix.fd_t) void { + if (sc.primary) daemon.stub = fd else sc.stub = fd; + } }; -/// SIGTERM or SIGHUP: the terminal put back as a clean exit leaves it -- +/// SIGTERM or SIGHUP: each terminal put back as a clean exit leaves it -- /// the main screen, no mouse, paste or keyboard modes, the cursor shown, /// cooked termios -- and then the signal's own death. A nested editor /// killed in a pane must not leave that pane's terminal wedged. /// Async-signal-safe: write, tcsetattr, sigaction, raise. const Killed = struct { - var fd: posix.fd_t = -1; - var cooked: posix.termios = undefined; + var fds: [pardes.views.max]posix.fd_t = @splat(-1); + var cooked: [pardes.views.max]posix.termios = undefined; const reset = "\x1b[<u\x1b[?1000l\x1b[?1002l\x1b[?1003l\x1b[?1006l\x1b[?1004l\x1b[?2004l\x1b[0m\x1b[?25h\x1b[?1049l"; - fn arm(tty_fd: posix.fd_t, termios: posix.termios) void { - cooked = termios; - fd = tty_fd; + fn arm(tty_fd: posix.fd_t, termios: posix.termios) ?usize { + const slot = std.mem.findScalar(posix.fd_t, &fds, -1) orelse return null; + cooked[slot] = termios; + fds[slot] = tty_fd; const on: posix.Sigaction = .{ .handler = .{ .handler = handle }, .mask = posix.sigemptyset(), .flags = posix.SA.RESETHAND }; posix.sigaction(.TERM, &on, null); // A hangup a daemon keeps the session through is winchWatch's. if (daemon.link < 0) posix.sigaction(.HUP, &on, null); + return slot; } /// The terminal gone (put back, or detached): a TERM still takes the /// socket, the prompt files and the shells with it, and leaves the /// terminal alone. - fn disarm() void { - fd = -1; + fn disarm(slot: usize) void { + fds[slot] = -1; } fn handle(sig: posix.SIG) callconv(.c) void { - if (fd >= 0) { + for (fds, &cooked) |fd, *termios| if (fd >= 0) { _ = std.c.write(fd, reset, reset.len); - _ = std.c.tcsetattr(fd, .FLUSH, &cooked); - } + _ = std.c.tcsetattr(fd, .FLUSH, termios); + }; // The 9P socket and private prompt files go too: a killed editor // leaves none behind. Its shells too, the daemon's dups let go. ninep_io.unlinkOwnSocket(); @@ -1315,14 +1390,10 @@ fn localSession( opts: pardes.Options, screen: *Screen, loop: *Loop, - input_cache: *vaxis.GraphemeCache, - kitty_handles: *std.AutoHashMap(pardes.ImageCacheKey, vaxis.Image), paste_buf: *std.Io.Writer.Allocating, ) !void { const io = init.io; const gpa = init.gpa; - const vx = &screen.vx; - const tty = &screen.tty; const allocs = pardes.memory.init(gpa); defer pardes.memory.deinit(); @@ -1367,20 +1438,23 @@ fn localSession( .core = core, .prompt_rcs = &prompt_rcs, .loop = loop, - .vx = vx, - .tty = tty, - .screen = screen, - .input_cache = input_cache, - .kitty = kitty_handles, .frame = &frame_arena, .paste_buf = paste_buf, .inotify_fd = file_watch.init(false), .fs = fs, .test_clock = host_io.testClock(), }; + sh.terms[0] = screen; pardes.lsp.setStatusSink(&sh, lspStatusSink); host_io.setExitWake(loop, wakeForExit); - defer sh.glide.deinit(gpa); + defer screen.glide.deinit(gpa); + // The terminals of the other views end with the session: each put back, + // its stub told. + defer for (&sh.terms) |*slot| if (slot.*) |sc| if (!sc.primary) { + stopInput(io, &sc.thread); + sh.dropScreen(sc, .exit); + slot.* = null; + }; defer { host_io.setExitWake(null, null); pardes.lsp.setStatusSink(null, null); @@ -1421,7 +1495,7 @@ fn localSession( .search_rows => |b| b.deinit(gpa), .attach => |a| { _ = libc.close(a.tty); - _ = libc.close(a.stub); + if (a.stub >= 0) _ = libc.close(a.stub); }, .adopted => |a| _ = libc.close(a.fd), else => {}, @@ -1434,14 +1508,26 @@ fn localSession( core.unattended = !screen.on; while (core.nextEffect()) |effect| core.perform(effect); - if (screen.on) try startInput(loop, input_cache); - defer stopInput(loop); - (try std.Thread.spawn(.{}, winchWatch, .{ loop, vx, tty })).detach(); + if (screen.on) try startInput(loop, screen); + defer stopInput(io, &screen.thread); + (try std.Thread.spawn(.{}, winchWatch, .{loop})).detach(); (try std.Thread.spawn(.{}, wakeWatch, .{ io, loop })).detach(); if (fs) |f| try f.watch(loop, wakeFs); - if (screen.on) try vx.queryTerminalSend(tty.writer()); + if (screen.on) try screen.vx.queryTerminalSend(screen.tty.writer()); // Detached from the start, nothing else may wake the first wait. if (!screen.on) daemon.watch(loop, deliverNote); + // PARDES_TEST_VIEWS: the terminals at these paths are views of the + // session too, from its start, as `pardes --attach`ed ones are (the + // snapshot harness's `start ... views=N`). + if (init.environ_map.get("PARDES_TEST_VIEWS")) |paths| { + var it = std.mem.tokenizeScalar(u8, paths, ' '); + while (it.next()) |path| { + var path_buf: [256]u8 = undefined; + const z = std.fmt.bufPrintSentinel(&path_buf, "{s}", .{path}, 0) catch continue; + const fd = libc.open(z, .{ .ACCMODE = .RDWR, .NOCTTY = true, .CLOEXEC = true }, @as(libc.mode_t, 0)); + if (fd >= 0) sh.attachTerminal(fd, -1); + } + } sh.threads_ok = true; for (&sh.ptys, 0..) |*slot, id| if (slot.*) |*pt| { @@ -1497,15 +1583,29 @@ fn localSession( .{ .text = 0 }, ); _ = file_watch.applyThemeEffect(core, gpa, sh.inotify_fd, &sh.watches, 0, false, false); - if (screen.on) clearNativeImages(kitty_handles, vx, tty); - nc.native_images = screen.on and vx.caps.kitty_graphics; - nc.unattended = !screen.on; + // ponytail: a restored session is one view, the live one's + // terminal: the others are let go, as a detach of each. + const live = sh.term().?; + for (&sh.terms) |*slot| if (slot.*) |sc| if (sc != live) { + stopInput(io, &sc.thread); + sh.dropScreen(sc, .detach); + slot.* = null; + }; + sh.terms = @splat(null); + sh.terms[0] = live; + stopInput(io, &live.thread); + live.feed.view = 0; + sh.from = 0; + if (live.on) startInput(loop, live) catch {}; + 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; if (fs) |f| f.reset(nc); core.deinit(); core = nc; sh.core = nc; - if (comptime pardes.pdf_enabled) if (screen.on) { - updateCoreTerminalSize(core, vx.screen.width, vx.screen.height, vx.screen.width_pix, vx.screen.height_pix); + if (comptime pardes.pdf_enabled) if (live.on) { + updateCoreTerminalSize(core, live.vx.screen.width, live.vx.screen.height, live.vx.screen.width_pix, live.vx.screen.height_pix); }; } } @@ -1554,12 +1654,11 @@ const Shell = struct { core: *pardes.Pardes, prompt_rcs: *const host_io.Shell.PromptFiles, loop: *Loop, - vx: *vaxis.Vaxis, - tty: *vaxis.Tty, - /// The terminal, while there is one (Screen.on); null in tests. - screen: ?*Screen = null, - input_cache: ?*vaxis.GraphemeCache = null, - kitty: *std.AutoHashMap(pardes.ImageCacheKey, vaxis.Image), + /// Each view's terminal, by view (views.zig): the session's own first; + /// none in tests. + terms: [pardes.views.max]?*Screen = @splat(null), + /// The view the input taken now is from (`Command.value.from`). + from: u8 = 0, frame: *std.heap.ArenaAllocator, paste_buf: *std.Io.Writer.Allocating, inotify_fd: c_int, @@ -1576,16 +1675,8 @@ const Shell = struct { lsp_task: ?host_io.Lsp.Task = null, pipe_tasks: PipeTasks = .{}, threads_ok: bool = false, - caps_pending: bool = true, check_files: bool = false, in_paste: bool = false, - tracks: []const pardes.animation.Track = &.{}, - /// T2: the cursor's jump trail (JumpTrail). - trail: JumpTrail = .{}, - /// The view's glide, the GUI's motion drawn at whole rows (anim 12). - glide: pardes.glide.Glide = .{}, - /// T7: when each pane's view last moved (ThumbFlash). - flash: ThumbFlash = .{}, /// PARDES_TEST_CLOCK's virtual time (host_io.testClock), and where the /// running-out wait moves it: the core's next wake. test_clock: ?u64 = null, @@ -1602,6 +1693,8 @@ const Shell = struct { input_ns: u64 = 0, focused_ns: u64 = 0, + const Leaving = enum { detach, exit }; + fn of(ctx: ?*anyopaque) *Shell { return @ptrCast(@alignCast(ctx.?)); } @@ -1653,8 +1746,13 @@ const Shell = struct { return s.test_clock orelse @intCast(std.Io.Clock.awake.now(s.io).nanoseconds); } + /// The live view's terminal (null in tests). + fn term(s: *const Shell) ?*Screen { + return s.terms[s.core.view]; + } + fn attached(s: *const Shell) bool { - const screen = s.screen orelse return true; + const screen = s.term() orelse return true; return screen.on; } @@ -1668,14 +1766,46 @@ const Shell = struct { fn detach(ctx: ?*anyopaque) void { const s = of(ctx); 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); if (!daemon.kept()) return s.core.reportFailure(s.core.active, "Detach: no pardes daemon keeps this session (it is its terminal's job)"); s.leaveTerminal(); } + /// View `k`'s terminal let go (detached, or gone) while others stay: the + /// view goes with it. + fn dropView(s: *Shell, k: u8, how: Leaving) void { + const sc = s.terms[k] orelse return; + stopInput(s.io, &sc.thread); + s.terms[k] = null; + s.core.closeView(k); + s.dropScreen(sc, how); + } + + /// A terminal put back and its stub told; an attached one's Screen freed + /// (the session's own stays, a view of none). + fn dropScreen(s: *Shell, sc: *Screen, how: Leaving) void { + if (sc.primary) { + sc.leave(); + return sc.sayDetached(); + } + sc.leave(); + switch (how) { + .detach => sc.sayDetached(), + .exit => { + daemon.tellExit(sc.stub, 0); + sc.stub = -1; + }, + } + sc.glide.deinit(s.gpa); + sc.kitty.deinit(); + s.gpa.free(sc.buf); + s.gpa.destroy(sc); + } + fn leaveTerminal(s: *Shell) void { - const screen = s.screen orelse return; - stopInput(s.loop); - clearNativeImages(s.kitty, s.vx, s.tty); + const screen = s.term() orelse return; + stopInput(s.io, &screen.thread); screen.leave(); s.core.native_images = false; s.core.unattended = true; @@ -1685,39 +1815,65 @@ const Shell = struct { for (0..3) |i| _ = libc.dup2(null_fd, @intCast(i)); if (null_fd > 2) _ = libc.close(null_fd); } - daemon.tellStubDetached(); + screen.sayDetached(); daemon.setState(true); } - /// `pardes --attach`'s terminal, for this detached session: entered as - /// the first one was, sized, asked what it can do, and drawn whole. + /// `pardes --attach`'s terminal: for a detached session its own again, + /// entered as the first one was; for one attached already, a view of + /// its own (views.zig). Sized, asked what it can do, and drawn whole. fn attachTerminal(s: *Shell, fd: posix.fd_t, stub: posix.fd_t) void { - const screen = s.screen orelse return; - if (screen.on) { + const live = s.term() orelse return; + const screen = if (!live.on) live else extra: { + const sc = s.gpa.create(Screen) catch break :extra null; + const buf = s.gpa.alloc(u8, 0x10000) catch { + s.gpa.destroy(sc); + break :extra null; + }; + sc.* = .{ .io = s.io, .gpa = s.gpa, .env = live.env, .buf = buf, .kitty = .init(s.gpa) }; + break :extra sc; + } orelse { _ = libc.close(fd); - return daemon.refuseStub(stub, "that session has a terminal already"); - } + return refuse(stub, "that session has no room for another terminal"); + }; + const extra = screen != live; const tty = Screen.ttyOn(s.io, screen.buf, fd) catch { _ = libc.close(fd); - daemon.setState(true); - return daemon.refuseStub(stub, "that terminal would not go raw"); + if (extra) s.freeScreen(screen) else daemon.setState(true); + return refuse(stub, "that terminal would not go raw"); }; screen.enter(tty) catch { - daemon.setState(true); - return daemon.refuseStub(stub, "that terminal would not take the screen"); + if (extra) s.freeScreen(screen) else daemon.setState(true); + return refuse(stub, "that terminal would not take the screen"); }; - daemon.stub = stub; - FrameAck.waiting.store(false, .release); - FrameAck.off.store(false, .release); - kitty_shm.store(false, .release); - s.caps_pending = true; + if (extra) { + const k = s.core.openView() orelse { + screen.leave(); + s.freeScreen(screen); + return refuse(stub, "that session has as many terminals as it takes"); + }; + screen.feed.view = k; + s.terms[k] = screen; + } + screen.setStub(stub); s.core.unattended = false; - startInput(s.loop, s.input_cache.?) catch {}; - s.vx.queryTerminalSend(s.tty.writer()) catch {}; + startInput(s.loop, screen) catch {}; + screen.vx.queryTerminalSend(screen.tty.writer()) catch {}; s.core.needs_frame = true; daemon.setState(false); } + fn freeScreen(s: *Shell, sc: *Screen) void { + sc.kitty.deinit(); + s.gpa.free(sc.buf); + s.gpa.destroy(sc); + } + + /// A terminal refused: its stub told why (a test's has none). + fn refuse(stub: posix.fd_t, why: []const u8) void { + if (stub >= 0) daemon.refuseStub(stub, why); + } + /// Adopt: the daemon is asked for the shells of sessions that died /// holding them; each comes back (`adopted`) as a terminal pane here. fn adopt(ctx: ?*anyopaque, pane: u8) void { @@ -1880,12 +2036,38 @@ const Shell = struct { else => {}, } if (s.input_seen) s.input_ns = @intCast(std.Io.Clock.awake.now(s.io).nanoseconds); + // 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 (event == .paste) s.gpa.free(@constCast(event.paste)); + return false; + } + if (s.term() != null) core.toView(s.from); + }, + else => {}, + } switch (event) { .nop => {}, + .from => |k| s.from = k, + .winched => s.winched(), + // A terminal hung up (its stub passes the hangup on) or its stub + // died (a forked session's death signal): that one's input has + // ended. A HUP says not whose: each is asked. + .hangup => for (s.terms, 0..) |slot, k| if (slot) |sc| if (sc.on and sc.hungUp()) { + s.from = @intCast(k); + if (s.apply(.quit)) return true; + }, .wake => if (s.test_clock) |*virtual| { virtual.* = @max(virtual.*, s.wake_to); }, .quit => { + // One of several: its view goes with it. + if (pardes.views.count(core) > 1) { + s.dropView(core.view, .detach); + return true; + } // The terminal went: a session the daemon keeps carries on // without it, to be attached again. Gone before the first // frame, the reader that takes the daemon's `ok` (kept @@ -1905,13 +2087,7 @@ const Shell = struct { core.update(.pointer_leave); core.update(.{ .focus = false }); }, - .winsize => |ws| if (s.attached()) { - s.vx.resize(s.gpa, s.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 } }); - }, + .winsize => |ws| if (s.attached()) s.resized(ws), .pty_read => |pr| { tookRead(s.io, pr.id); s.output_seen = true; @@ -2008,6 +2184,32 @@ 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| { + 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 } }); + } + + /// A SIGWINCH: each terminal whose size it changed is resized, in its + /// view (a terminal reporting in band says so as input). + fn winched(s: *Shell) void { + for (s.terms, 0..) |slot, k| { + const sc = slot orelse continue; + 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); + } + } + fn reloadWatched(s: *Shell) void { if (!s.check_files) return; s.check_files = false; @@ -2020,13 +2222,12 @@ const Shell = struct { /// notches are); `wheeled` from the mouse event if it should glide. fn stepGlide(ctx: ?*anyopaque) void { const s = of(ctx); - s.glide.step(s.core, s.gpa, null, null); + if (s.term()) |sc| sc.glide.step(s.core, s.gpa, null, null); } fn pollFrame(ctx: ?*anyopaque) void { const s = of(ctx); stepGlide(ctx); - s.core.native_image_patches = kitty_shm.load(.acquire); if (s.fs) |f| if (f.tick().pending) { _ = s.loop.tryPostEvent(.fs_ready) catch {}; }; @@ -2035,23 +2236,26 @@ const Shell = struct { if (host_io.ttyCwd(pt.pid, pt.file.handle, s.core.settings.shell.effective.get(), &lbuf)) |cwd| s.core.setCwd(id, cwd); }; - if (s.caps_pending and s.attached() and s.vx.queries_done.load(.unordered)) { - s.caps_pending = false; - s.vx.enableDetectedFeatures(s.tty.writer()) catch {}; - s.core.native_images = s.vx.caps.kitty_graphics; - if (s.vx.caps.kitty_graphics) kittyShmProbe(s.tty.writer()); - s.vx.queueRefresh(); + const sc = s.term() orelse return; + s.core.native_image_patches = sc.feed.shm.load(.acquire); + if (sc.caps_pending and sc.on and sc.vx.queries_done.load(.unordered)) { + sc.caps_pending = false; + sc.vx.enableDetectedFeatures(sc.tty.writer()) catch {}; + s.core.native_images = sc.vx.caps.kitty_graphics; + if (sc.vx.caps.kitty_graphics) kittyShmProbe(sc.tty.writer(), &sc.feed); + sc.vx.queueRefresh(); s.core.needs_frame = true; } } fn present(ctx: ?*anyopaque, canonical: *const pardes.Surface) void { const s = of(ctx); - const vx = s.vx; - s.tracks = canonical.panelTracks(); + const sc = s.term() orelse return; + const vx = &sc.vx; + sc.tracks = canonical.panelTracks(); // The last frame is not answered yet: this one stays owed, and the // answer's wake draws the state as it is then. - if (FrameAck.holds(@intCast(std.Io.Clock.awake.now(s.io).nanoseconds), s.io)) { + if (sc.feed.ack.holds(@intCast(std.Io.Clock.awake.now(s.io).nanoseconds), s.io)) { s.core.present_skipped = true; return; } @@ -2059,21 +2263,21 @@ const Shell = struct { const surface = panel_compositor.compose( s.frame.allocator(), @constCast(canonical), - s.tracks, + sc.tracks, s.core.theme().bg, ) catch return; const tz_cells = tracy.zone(@src(), "surface->vaxis"); const win = vx.window(); const truecolor = vx.caps.rgb or colortermTruecolor(); // Each of the shell's own motions below asks for frames while it runs. - if (s.glide.pending) s.glide.measure(s.gpa, canonical); - if (s.glide.moving()) s.glide.advance(s.core.now_ns, s.glide.motion); - s.core.shell_continuous = s.glide.moving(); - s.core.frames.scroll = @round(s.glide.follow.offset); - const glided = pardes.glide.shifted(&s.glide, s.frame.allocator(), surface) catch surface; + if (sc.glide.pending) sc.glide.measure(s.gpa, canonical); + if (sc.glide.moving()) sc.glide.advance(s.core.now_ns, sc.glide.motion); + s.core.shell_continuous = sc.glide.moving(); + s.core.frames.scroll = @round(sc.glide.follow.offset); + const glided = pardes.glide.shifted(&sc.glide, s.frame.allocator(), surface) catch surface; const shadowed = chipShadows(s.frame.allocator(), glided, s.core, truecolor) catch glided; - const flashed = s.flash.apply(s.frame.allocator(), shadowed, s.core, truecolor) catch shadowed; - const trailed = s.trail.apply(s.frame.allocator(), flashed, s.core, truecolor) catch flashed; + const flashed = sc.flash.apply(s.frame.allocator(), shadowed, s.core, truecolor) catch shadowed; + const trailed = sc.trail.apply(s.frame.allocator(), flashed, s.core, truecolor) catch flashed; paintCells(win, trailed.cells, trailed.cols, trailed.rows); tz_cells.end(); for (surface.images[0..surface.nimages]) |maybe| { @@ -2083,7 +2287,7 @@ const Shell = struct { if (!kittyImageRepresentable(place)) continue; } const key = place.cacheKey(); - if (!s.kitty.contains(key) and vx.caps.kitty_graphics and kitty_shm.load(.acquire)) shm: { + if (!sc.kitty.contains(key) and vx.caps.kitty_graphics and sc.feed.shm.load(.acquire)) shm: { var buf: [64]u8 = undefined; kitty_shm_serial +%= 1; // Bounded: a segment this many transmissions old was never @@ -2095,21 +2299,21 @@ const Shell = struct { } const name = kittyShmName(&buf, kitty_shm_serial) catch break :shm; if (!kittyShmWrite(name, place.rgba)) break :shm; - if (vx.transmitLocalImagePath(s.gpa, s.tty.writer(), name, @intCast(place.iw), @intCast(place.ih), .shared_mem, .rgba) catch null) |handle| - s.kitty.put(key, handle) catch vx.freeImage(s.tty.writer(), handle.id) + if (vx.transmitLocalImagePath(s.gpa, sc.tty.writer(), name, @intCast(place.iw), @intCast(place.ih), .shared_mem, .rgba) catch null) |handle| + sc.kitty.put(key, handle) catch vx.freeImage(sc.tty.writer(), handle.id) else _ = libc.shm_unlink(name); } - if (!s.kitty.contains(key) and vx.caps.kitty_graphics) { + if (!sc.kitty.contains(key) and vx.caps.kitty_graphics) { const enc = std.base64.standard.Encoder; if (s.gpa.alloc(u8, enc.calcSize(place.rgba.len))) |b64| { defer s.gpa.free(b64); _ = enc.encode(b64, place.rgba); - if (vx.transmitPreEncodedImage(s.tty.writer(), b64, @intCast(place.iw), @intCast(place.ih), .rgba) catch null) |handle| - s.kitty.put(key, handle) catch vx.freeImage(s.tty.writer(), handle.id); + if (vx.transmitPreEncodedImage(sc.tty.writer(), b64, @intCast(place.iw), @intCast(place.ih), .rgba) catch null) |handle| + sc.kitty.put(key, handle) catch vx.freeImage(sc.tty.writer(), handle.id); } else |_| {} } - if (s.kitty.get(key)) |cached| { + if (sc.kitty.get(key)) |cached| { if (comptime !pardes.pdf_enabled) { const child = win.child(.{ .x_off = place.x, .y_off = place.y, .width = place.w, .height = place.h }); cached.draw(child, .{ .scale = .contain }) catch {}; @@ -2150,32 +2354,32 @@ const Shell = struct { while (true) { var stale: [pardes.MAX_PANES]pardes.ImageCacheKey = undefined; var stale_len: usize = 0; - var image_iterator = s.kitty.iterator(); + var image_iterator = sc.kitty.iterator(); while (image_iterator.next()) |entry| { if (surfaceHasKittyKey(surface, entry.key_ptr.*)) continue; stale[stale_len] = entry.key_ptr.*; stale_len += 1; if (stale_len == stale.len) break; } - for (stale[0..stale_len]) |key| if (s.kitty.fetchRemove(key)) |removed| - vx.freeImage(s.tty.writer(), removed.value.id); + for (stale[0..stale_len]) |key| if (sc.kitty.fetchRemove(key)) |removed| + vx.freeImage(sc.tty.writer(), removed.value.id); if (stale_len < stale.len) break; } if (glided.cursor) |cur| paintCursor(win, cur.x, cur.y, cur.bar); const tz_render = tracy.zone(@src(), "vx.render"); - const before = s.tty.tty_writer.pos + s.tty.writer().end; - vx.render(s.tty.writer()) catch {}; + const before = sc.tty.tty_writer.pos + sc.tty.writer().end; + vx.render(sc.tty.writer()) catch {}; // The frame's cost to the terminal (FrameStats.Frame.bytes): what // vaxis's diff of the cells wrote. - s.core.frames.bytes +|= @intCast(@min(std.math.maxInt(u32), s.tty.tty_writer.pos + s.tty.writer().end -| before)); - if (s.tty.tty_writer.pos + s.tty.writer().end != before) FrameAck.ask(s.tty.writer(), @intCast(std.Io.Clock.awake.now(s.io).nanoseconds)); + s.core.frames.bytes +|= @intCast(@min(std.math.maxInt(u32), sc.tty.tty_writer.pos + sc.tty.writer().end -| before)); + if (sc.tty.tty_writer.pos + sc.tty.writer().end != before) sc.feed.ack.ask(sc.tty.writer(), @intCast(std.Io.Clock.awake.now(s.io).nanoseconds)); s.drawn_ns = @intCast(std.Io.Clock.awake.now(s.io).nanoseconds); tz_render.end(); } fn postPresent(ctx: ?*anyopaque) void { const s = of(ctx); - s.core.acknowledgePanelPresentation(s.tracks); + if (s.term()) |sc| s.core.acknowledgePanelPresentation(sc.tracks); tracy.frameMark(); } @@ -2320,14 +2524,16 @@ const Shell = struct { fn setClipboard(ctx: ?*anyopaque, text: []const u8) void { const s = of(ctx); // Detached, the session keeps it (a 9P read, a paste here). - if (!s.attached()) return s.core.fallback.setClipboard(text); - copyToClipboard(s.vx, s.tty, s.gpa, text); + const sc = s.term() orelse return s.core.fallback.setClipboard(text); + if (!sc.on) return s.core.fallback.setClipboard(text); + copyToClipboard(&sc.vx, &sc.tty, s.gpa, text); } fn readClipboard(ctx: ?*anyopaque) void { const s = of(ctx); - if (!s.attached()) return s.core.update(.{ .paste = s.core.fallback.clipboard.items }); - requestClipboard(s.vx, s.tty); + const sc = s.term() orelse return s.core.update(.{ .paste = s.core.fallback.clipboard.items }); + if (!sc.on) return s.core.update(.{ .paste = s.core.fallback.clipboard.items }); + requestClipboard(&sc.vx, &sc.tty); } fn openLink(_: ?*anyopaque, url: []const u8) void { @@ -2391,9 +2597,6 @@ test "TTY queued results reject old PTY generations and LSP request IDs" { .core = core, .prompt_rcs = undefined, .loop = undefined, - .vx = undefined, - .tty = undefined, - .kitty = undefined, .frame = undefined, .paste_buf = undefined, .inotify_fd = -1, @@ -2439,9 +2642,6 @@ test "TTY worker setup failures finish matching LSP and pipe requests" { .core = core, .prompt_rcs = undefined, .loop = undefined, - .vx = undefined, - .tty = undefined, - .kitty = undefined, .frame = undefined, .paste_buf = undefined, .inotify_fd = -1, @@ -2507,24 +2707,16 @@ fn watchFiles(io: std.Io, fd: c_int, loop: *Loop) anyerror!void { fn keepSignal(_: posix.SIG) callconv(.c) void {} -fn winchWatch(loop: *Loop, vx: *vaxis.Vaxis, tty: *vaxis.Tty) void { +fn winchWatch(loop: *Loop) void { var set = posix.sigemptyset(); posix.sigaddset(&set, posix.SIG.WINCH); if (daemon.link >= 0) posix.sigaddset(&set, posix.SIG.HUP); while (true) { var sig: c_int = 0; if (libc.sigwait(&set, &sig) != 0) continue; - // The terminal hung up (its stub passes the hangup on): as its - // input's end. - if (sig == @backingInt(posix.SIG.HUP)) { - loop.postEvent(.quit) catch {}; - continue; - } - // Detached, the descriptor the terminal had may be another's now. - if (!terminal_on.load(.acquire)) continue; - if (vx.state.in_band_resize) continue; // terminal reports via CSI 48 - const ws = tty.getWinsize() catch continue; - loop.postEvent(.{ .winsize = ws }) catch {}; + // The terminals are the loop's: it asks each its size, and takes a + // hangup as the end of the one that hung up. + loop.postEvent(if (sig == @backingInt(posix.SIG.HUP)) .hangup else .winched) catch {}; } } @@ -2665,7 +2857,7 @@ test "a terminal pane gets function keys as their sequences and lone modifiers n vx.queries_done.store(false, .unordered); var tty: vaxis.Tty = undefined; var loop: Loop = .init(io, &tty, &vx); - var cache: vaxis.GraphemeCache = .{}; + var feed: Feed = .{}; const Reader = struct { parts: []const []const u8, next: usize = 0, @@ -2698,7 +2890,7 @@ test "a terminal pane gets function keys as their sequences and lone modifiers n "\x1b[104;;104u", }, }; - try readInput(&loop, &reader, &cache); + try readInput(&loop, &reader, &vx, &feed); const core = try pardes.Pardes.init(gpa, .{ .tty_only = true }); defer core.deinit(); core.panes[0].?.body.mode = .tty; |
