summaryrefslogtreecommitdiff
path: root/src/tty/tty.zig
diff options
context:
space:
mode:
authorGabriel Schneider <[email protected]>2026-10-31 06:28:48 -0300
committerGabriel Schneider <[email protected]>2026-10-31 06:28:48 -0300
commita479792a1ab2b593642d7f648194bfa23ce01dba (patch)
tree96ddee7d879a9084daa07db43b0b7910b072a785 /src/tty/tty.zig
parente179cc44fe5060c76a5b00c41e53f11209f5acd9 (diff)
parent4c761893e5b3fdae422622cfa02104ab36633045 (diff)
downloadpardes-a479792a1ab2b593642d7f648194bfa23ce01dba.tar.gz
pardes-a479792a1ab2b593642d7f648194bfa23ce01dba.zip
Merge the upstream daemon and replicated client/server refactor
Diffstat (limited to 'src/tty/tty.zig')
-rw-r--r--src/tty/tty.zig1881
1 files changed, 1339 insertions, 542 deletions
diff --git a/src/tty/tty.zig b/src/tty/tty.zig
index a358051e..4c054021 100644
--- a/src/tty/tty.zig
+++ b/src/tty/tty.zig
@@ -14,24 +14,55 @@ const file_watch = @import("../file_watch.zig");
const selection_pipe = @import("../selection_pipe.zig");
const ninep_io = @import("../9p_io.zig");
const panel_compositor = @import("panel_compositor.zig");
-const detached_client = @import("../detached/client.zig");
-const detached_server = @import("../detached/server.zig");
-const wire = @import("../detached/wire.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;
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.
@@ -41,6 +72,16 @@ fn kittyShmName(buf: []u8, n: u32) ![:0]const u8 {
return std.fmt.bufPrintSentinel(buf, "/pardes-{d}-{d}", .{ libc.getpid(), n }, 0);
}
+/// A terminal unlinks what it reads; whatever it never read (the probe
+/// unanswered, a transmission lost with the terminal) is ours to remove.
+fn unlinkKittyShm() void {
+ var name_buf: [64]u8 = undefined;
+ var n: u32 = 0;
+ while (n <= kitty_shm_serial) : (n += 1) {
+ if (kittyShmName(&name_buf, n)) |name| _ = libc.shm_unlink(name) else |_| {}
+ }
+}
+
/// Write `bytes` to a fresh shm object; the terminal unlinks it after reading.
fn kittyShmWrite(name: [:0]const u8, bytes: []const u8) bool {
const fd = libc.shm_open(name, @bitCast(libc.O{ .ACCMODE = .RDWR, .CREAT = true, .EXCL = true }), @as(c_uint, 0o600));
@@ -64,13 +105,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 {};
}
@@ -78,9 +119,22 @@ fn kittyShmProbe(w: *std.Io.Writer) void {
pub const Command = struct {
pub var value: union(enum) {
nop,
+ /// The terminal's input ended: its end of file, a hangup. A session
+ /// a daemon keeps carries on detached; any other ends.
quit,
+ /// A terminal for this detached session, and its stub's pipe
+ /// (daemon.Note.attach).
+ attach: struct { tty: posix.fd_t, stub: posix.fd_t },
+ /// A shell a dead session left, its pty's master (daemon.Note.adopted).
+ 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 },
@@ -98,38 +152,47 @@ pub const Command = struct {
search_rows: pardes.Stream.Batch,
files_changed,
fs_ready,
+ /// A replica's connection, handed over by the daemon (Peers).
+ replica: daemon.Joining,
+ /// A replica's reader posted: the step boundary takes it in.
+ replica_mail,
+ /// A replica client's: what the session streamed (replica.Link).
+ said: replica.Said,
+ link_gone,
} = .nop;
};
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 {
- inputReader(loop, loop.tty, cache);
+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, &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;
@@ -140,14 +203,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 |_| {}
@@ -180,9 +243,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
@@ -190,8 +253,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
@@ -219,14 +282,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| {
@@ -234,18 +297,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));
@@ -253,14 +316,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);
}
};
@@ -292,7 +355,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,
@@ -314,7 +377,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);
@@ -377,7 +440,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,
@@ -420,7 +483,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;
@@ -459,7 +522,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 {
@@ -524,7 +587,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
@@ -532,7 +595,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 });
@@ -555,7 +618,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 {
@@ -580,7 +643,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;
@@ -606,7 +669,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,
@@ -628,12 +691,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;
@@ -651,9 +714,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;
@@ -665,25 +728,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" {
@@ -717,8 +776,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 };
@@ -731,9 +790,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) {
@@ -743,10 +802,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;
@@ -788,14 +847,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
@@ -1166,111 +1229,414 @@ fn nativePdfWheelTarget(core: *const pardes.Pardes, mouse: vaxis.Mouse) ?PdfWhee
return null;
}
-pub fn run(init: std.process.Init, opts: pardes.Options, attach: ?[]const u8) !void {
+/// Where a session's terminal comes from: /dev/tty, as a plain `pardes`
+/// opens it; one open already (a session forked off its stub,
+/// daemon.forkSession); or none, until one is attached (`--detach`).
+/// The terminal a session starts on: /dev/tty, one its stub opened (an
+/// upgraded session's is raw already, `termios` the cooked one), or none.
+pub const Term = union(enum) { open, fd: struct { fd: posix.fd_t, termios: ?posix.termios = null }, none };
+
+pub fn run(init: std.process.Init, opts: pardes.Options, term: Term) !void {
const io = init.io;
const gpa = init.gpa;
- var attach_end: AttachEnd = .none;
- defer attach_end.report(io);
-
- var name_buf: [detached_server.path_max]u8 = undefined;
- var attach_name: []const u8 = &.{};
- if (attach) |requested| switch (detached_client.resolve(&name_buf, requested)) {
- .name => |resolved| attach_name = resolved,
- .none => {
- attach_end = if (requested.len != 0) .{ .no_session = requested } else .nothing_detached;
- return;
- },
- .ambiguous => |found| {
- attach_end = .{ .ambiguous = found };
- return;
- },
- };
-
var winch_set = posix.sigemptyset();
posix.sigaddset(&winch_set, posix.SIG.WINCH);
+ // Kept by a daemon, a hangup is the terminal's end, not the session's:
+ // winchWatch takes it, and the session carries on detached.
+ if (daemon.link >= 0) posix.sigaddset(&winch_set, posix.SIG.HUP);
+ // FreeBSD drops a signal whose action is to be ignored (WINCH's
+ // default) as it is sent, sigwait or not: a handler keeps it.
+ 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 tty = try vaxis.Tty.init(io, &tty_buf);
- defer tty.deinit(); // restore cooked termios LAST, after vx flushed its resets
- var vx = try vaxis.init(io, gpa, init.environ_map, .{ .system_clipboard_allocator = gpa });
- defer vx.deinit(gpa, tty.writer());
- try vx.enterAltScreen(tty.writer());
- defer vx.exitAltScreen(tty.writer()) catch {};
- try vx.setMouseMode(tty.writer(), true);
- try vx.setBracketedPaste(tty.writer(), true);
- Killed.arm(tty.fd.handle, tty.termios);
- defer Killed.disarm();
+ 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 => |t| try screen.enter(try Screen.ttyOn(io, &tty_buf, t.fd, t.termios)),
+ .none => {},
+ }
+ defer screen.leave();
- if (attach != null) {
- attach_end = attachSession(init, attach_name, &tty, &vx);
- return;
+ var paste_buf: std.Io.Writer.Allocating = .init(gpa);
+ defer paste_buf.deinit();
+ var loop: Loop = .init(io, &screen.tty, &screen.vx);
+
+ try localSession(init, opts, &screen, &loop, &paste_buf);
+}
+
+/// A replica client's link to its session (`remote`), drawn here.
+const Remote = struct {
+ link: replica.Link,
+
+ /// 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 r = c.link.r;
+ const core = 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;
+ r.draw(.{ .ctx = s, .f = Shell.present });
+ core.frames.mark_render = core.frames.mark_update;
+ const drew = core.frames.bytes > 0;
+ c.link.owed = core.present_skipped;
+ core.frames.record(pardes.FrameStats.nowNs(), false, c.link.owed);
+ core.present_skipped = skipped;
+ core.needs_frame = needs;
+ c.link.drawn(drew);
}
+};
+
+/// 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;
+ }
+ };
+ replica.readLink(gpa, fd, rest, loop, Post.post);
+ 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, far_link: bool) !void {
+ const io = init.io;
+ const gpa = init.gpa;
+ const Said = struct {
+ fn no(o: std.Io, comptime fmt: []const u8, args: anytype) noreturn {
+ var said: [800]u8 = undefined;
+ std.Io.File.stderr().writeStreamingAll(o, std.fmt.bufPrint(&said, "pardes: --attach: " ++ fmt ++ "\n", args) catch "pardes: --attach failed\n") catch {};
+ 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;
+ var dial_t0 = std.Io.Clock.awake.now(io).nanoseconds;
+ var joined = replica.dial(gpa, path, session, &why, have, null) orelse Said.no(io, "{s}", .{std.mem.sliceTo(&why, 0)});
+ if (joined.semantics != wire.semantics) Said.no(io, "{s}", .{replica.Link.upgrade_words});
- var kitty_handles = std.AutoHashMap(pardes.ImageCacheKey, vaxis.Image).init(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 {
- clearNativeImages(&kitty_handles, &vx, &tty);
- kitty_handles.deinit();
+ 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;
+ var r = replica.Link.load(gpa, &joined, o, &why, have) orelse Said.no(io, "{s}", .{std.mem.sliceTo(&why, 0)});
+ // Its join's time, the dial and the load (PARDES_REPLICA_STATS).
+ var dial_ms: u64 = @intCast(@divTrunc(std.Io.Clock.awake.now(io).nanoseconds - dial_t0, std.time.ns_per_ms));
+
+ var winch_set = posix.sigemptyset();
+ posix.sigaddset(&winch_set, posix.SIG.WINCH);
+ // A hangup ends it the normal way (`quit`), what it made kept on disk
+ // (`Have.keep`) and its ssh forward's socket unlinked (main.zig).
+ posix.sigaddset(&winch_set, posix.SIG.HUP);
+ hangup_quits = true;
+ 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);
var paste_buf: std.Io.Writer.Allocating = .init(gpa);
defer paste_buf.deinit();
- var loop: Loop = .init(io, &tty, &vx);
- var input_cache: vaxis.GraphemeCache = .{};
-
- var attached: ?detached_client.Client = null;
- defer if (attached != null) {
- stopInput(&loop);
- drainAttachedQueue(&loop, gpa);
+ var loop: Loop = .init(io, &screen.tty, &screen.vx);
+ var frame_arena: std.heap.ArenaAllocator = .init(allocs.frame);
+ defer frame_arena.deinit();
+ var remote_link: Remote = .{ .link = .{ .r = r, .fd = joined.fd } };
+ const link = &remote_link.link;
+ try link.fromEnv(gpa, init.environ_map);
+ defer link.deinit(gpa);
+ 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 = &remote_link,
};
- try localSession(init, opts, &tty, &vx, &loop, &input_cache, &kitty_handles, &paste_buf, &attached);
- if (attached) |*client| {
- defer client.detach();
- var a: Attach = .{
- .gpa = gpa,
- .client = client,
- .loop = &loop,
- .vx = &vx,
- .tty = &tty,
- .paste_buf = &paste_buf,
+
+ try startInput(&loop, &screen);
+ defer stopInput(io, &screen.thread);
+ (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) {
+ r.gmtoff = joined.gmtoff;
+ sh.core = r.core();
+ sh.from = joined.view;
+ sh.terms = @splat(null);
+ sh.terms[joined.view] = &screen;
+ screen.feed.view = joined.view;
+ link.reset(r, joined.fd);
+ link.joinedAs(&joined, dial_ms);
+ 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) remote_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 or r.echo.changed) link.dirty = true;
+ // Predictions out: judged a frame at a time while they are.
+ if (r.echo.n > 0 or r.echo.cursor != null or r.echo.nd > 0) requestWake(io, @intCast(pardes.animation.frame_ns / std.time.ns_per_ms));
+ if (link.quietCheck()) |ms| requestWake(io, ms);
+ 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 => |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.
+ if (have) |h| h.leaving(r.core());
+ dial_t0 = std.Io.Clock.awake.now(io).nanoseconds;
+ joined = replica.Link.redial(gpa, path, session, &why, have, r.diverged == null, joined.view) orelse {
+ screen.leave();
+ Said.no(io, "could not join again: {s}", .{std.mem.sliceTo(&why, 0)});
};
- attach_end = attachLoop(&a);
+ if (have) |h| h.left();
+ r.deinit();
+ r = replica.Link.load(gpa, &joined, o, &why, have) orelse {
+ screen.leave();
+ Said.no(io, "{s}", .{std.mem.sliceTo(&why, 0)});
+ };
+ dial_ms = @intCast(@divTrunc(std.Io.Clock.awake.now(io).nanoseconds - dial_t0, std.time.ns_per_ms));
}
}
-/// SIGTERM or SIGHUP: the terminal put back as a clean exit leaves it --
+
+/// 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). 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,
+ env: *std.process.Environ.Map,
+ buf: []u8,
+ 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.
+ /// An upgraded session's is raw already, `cooked` what it goes back to.
+ fn ttyOn(io: std.Io, buf: []u8, fd: posix.fd_t, cooked: ?posix.termios) !vaxis.Tty {
+ if (comptime builtin.is_test) unreachable; // vaxis.Tty is its TestTty
+ const termios = cooked orelse try vaxis.Tty.makeRaw(fd);
+ const file: std.Io.File = .{ .handle = fd, .flags = .{ .nonblocking = false } };
+ return .{ .io = io, .fd = file, .termios = termios, .tty_writer = file.writerStreaming(io, buf) };
+ }
+
+ fn enter(sc: *Screen, tty: vaxis.Tty) !void {
+ sc.tty = tty;
+ errdefer sc.tty.deinit();
+ sc.vx = try vaxis.init(sc.io, sc.gpa, sc.env, .{ .system_clipboard_allocator = sc.gpa });
+ errdefer sc.vx.deinit(sc.gpa, sc.tty.writer());
+ try sc.vx.enterAltScreen(sc.tty.writer());
+ try sc.vx.setMouseMode(sc.tty.writer(), true);
+ try sc.vx.setBracketedPaste(sc.tty.writer(), true);
+ if (comptime !builtin.is_test) {
+ sc.killed = Killed.arm(sc.tty.fd.handle, sc.tty.termios);
+ // What a panic puts back (vaxis.recover).
+ 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;
+ }
+
+ fn leave(sc: *Screen) void {
+ if (!sc.on) return;
+ sc.on = false;
+ 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) 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;
+ const handle = if (@TypeOf(sc.tty.fd) == std.Io.File) sc.tty.fd.handle else sc.tty.fd;
+ var fds = [_]posix.pollfd{
+ .{ .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: 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";
- const signals = [_]posix.SIG{ .TERM, .HUP };
-
- 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 };
- for (signals) |sig| posix.sigaction(sig, &on, null);
+ 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;
}
- fn disarm() void {
- fd = -1;
- const default: posix.Sigaction = .{ .handler = .{ .handler = posix.SIG.DFL }, .mask = posix.sigemptyset(), .flags = 0 };
- for (signals) |sig| posix.sigaction(sig, &default, null);
+ /// 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(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.
+ // leaves none behind. Its shells too, the daemon's dups let go.
ninep_io.unlinkOwnSocket();
host_io.Shell.unlinkOwnedRcs();
+ daemon.hangUp();
// SA_RESETHAND put the default back: the same signal, now fatal.
_ = std.c.raise(sig);
}
@@ -1279,13 +1645,9 @@ const Killed = struct {
fn localSession(
init: std.process.Init,
opts: pardes.Options,
- tty: *vaxis.Tty,
- vx: *vaxis.Vaxis,
+ screen: *Screen,
loop: *Loop,
- input_cache: *vaxis.GraphemeCache,
- kitty_handles: *std.AutoHashMap(pardes.ImageCacheKey, vaxis.Image),
paste_buf: *std.Io.Writer.Allocating,
- attached: *?detached_client.Client,
) !void {
const io = init.io;
const gpa = init.gpa;
@@ -1310,7 +1672,9 @@ fn localSession(
pardes.syntax.stop();
}
- var core = if (options.load_path) |lp| blk: {
+ var core = if (upgrade.resumed) |*rec|
+ try upgrade.load(gpa, allocs.pardes, options, rec)
+ else if (options.load_path) |lp| blk: {
const bytes = try filesystem.readFile(gpa, lp);
defer gpa.free(bytes);
break :blk try pardes.dump.initFromDump(allocs.pardes, options, bytes);
@@ -1333,30 +1697,36 @@ fn localSession(
.core = core,
.prompt_rcs = &prompt_rcs,
.loop = loop,
- .vx = vx,
- .tty = tty,
- .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;
+ 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 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);
for (&sh.ptys) |*slot| if (slot.*) |*pt| {
pt.reader.cancel(io) catch {};
_ = libc.close(pt.file.handle);
- if (attached.* != null) {
- _ = libc.kill(pt.pid, posix.SIG.KILL);
- _ = libc.waitpid(pt.pid, null, 0);
- }
slot.* = null;
};
+ for (sh.adoptions[0..sh.adoptions_len]) |a| _ = libc.close(a.fd);
if (sh.lsp_task) |*t| {
t.future.cancel(io);
sh.lsp_task = null;
@@ -1374,7 +1744,10 @@ fn localSession(
sh.inotify_fd = -1;
}
while (loop.tryEvent() catch null) |ev| switch (ev) {
- .pty_read => |pr| gpa.free(pr.bytes),
+ .pty_read => |pr| {
+ tookRead(io, pr.id);
+ gpa.free(pr.bytes);
+ },
.paste => |b| gpa.free(@constCast(b)),
.lsp_done => |d| if (d.rows) |rows| allocs.lsp.free(rows),
.lsp_status => |text| allocs.lsp.free(text),
@@ -1383,20 +1756,49 @@ fn localSession(
response.deinit(gpa);
},
.search_rows => |b| b.deinit(gpa),
+ .attach => |a| {
+ _ = libc.close(a.tty);
+ if (a.stub >= 0) _ = libc.close(a.stub);
+ },
+ .adopted => |a| _ = libc.close(a.fd),
else => {},
};
}
const host = sh.host();
core.host = host;
+ // 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).
+ 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.
+ if (upgrade.resumed) |*rec| {
+ sh.resumePtys(rec);
+ while (core.nextEffect()) |effect| core.perform(effect);
+ }
- try startInput(loop, input_cache);
- defer if (attached.* == null) 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);
- 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 (upgrade.resumed == null) 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, null);
+ }
+ };
sh.threads_ok = true;
for (&sh.ptys, 0..) |*slot, id| if (slot.*) |*pt| {
@@ -1404,19 +1806,23 @@ fn localSession(
};
if (sh.inotify_fd >= 0) sh.watch_task = io.concurrent(watchFiles, .{ io, sh.inotify_fd, loop }) catch null;
- // A terminal unlinks what it reads; whatever it never read (the probe
- // unanswered, a transmission lost with the terminal) is ours to remove.
- defer {
- var name_buf: [64]u8 = undefined;
- var n: u32 = 0;
- while (n <= kitty_shm_serial) : (n += 1) {
- if (kittyShmName(&name_buf, n)) |name| _ = libc.shm_unlink(name) else |_| {}
- }
- }
- frames: while (!core.quit) {
+ defer unlinkKittyShm();
+ 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);
+ // A terminal (`pardes --attach`) or an adopted shell, handed on by
+ // the daemon's thread to this loop; started after the first frame,
+ // 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;
@@ -1435,6 +1841,7 @@ fn localSession(
for (&sh.ptys) |*slot| if (slot.*) |*pt| {
pt.reader.cancel(io) catch {};
_ = libc.close(pt.file.handle);
+ daemon.closed(pt.pid);
host_io.retireShell(pt.pid);
slot.* = null;
};
@@ -1447,28 +1854,31 @@ fn localSession(
.{ .text = 0 },
);
_ = file_watch.applyThemeEffect(core, gpa, sh.inotify_fd, &sh.watches, 0, false, false);
- clearNativeImages(kitty_handles, vx, tty);
- nc.native_images = vx.caps.kitty_graphics;
+ // 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;
+ sh.peers.alone_unattended = !live.on;
if (fs) |f| f.reset(nc);
core.deinit();
core = nc;
sh.core = nc;
- if (comptime pardes.pdf_enabled) {
- updateCoreTerminalSize(core, vx.screen.width, vx.screen.height, vx.screen.width_pix, vx.screen.height_pix);
- }
- }
- if (core.takeAttach()) |req| {
- var attempt = detached_client.attempt(gpa, req.name, core.screen_w, core.screen_h);
- switch (attempt) {
- .greeted => |client| {
- attached.* = client;
- break :frames;
- },
- else => {
- var mbuf: [256]u8 = undefined;
- core.setMessage(req.pane, attemptEnd(&attempt, req.name).row(&mbuf));
- },
- }
+ 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);
+ };
}
}
if (fs) |f| {
@@ -1488,11 +1898,37 @@ fn clearNativeImages(
kitty_handles.clearRetainingCapacity();
}
-fn drainAttachedQueue(loop: *Loop, gpa: std.mem.Allocator) void {
- while (loop.tryEvent() catch null) |ev| switch (ev) {
- .paste => |b| gpa.free(@constCast(b)),
- else => {},
- };
+const Adoption = struct { pid: posix.pid_t, fd: posix.fd_t, pane: ?u8 };
+
+/// The daemon's thread: what it says, onto the loop's queue.
+fn deliverNote(ctx: *anyopaque, note: daemon.Note) void {
+ const loop: *Loop = @ptrCast(@alignCast(ctx));
+ switch (note) {
+ .attach => |a| if (a.tty < 0) {
+ if (a.stub >= 0) daemon.refuseStub(a.stub, "a terminal session takes a terminal");
+ } else loop.postEvent(.{ .attach = .{ .tty = a.tty, .stub = a.stub } }) catch {
+ _ = libc.close(a.tty);
+ _ = libc.close(a.stub);
+ },
+ .adopted => |a| {
+ for (a.pids[0..a.n], a.fds[0..a.n]) |pid, fd| loop.postEvent(.{ .adopted = .{ .pid = pid, .fd = fd } }) catch {
+ _ = libc.close(fd);
+ };
+ loop.postEvent(.{ .adopted = .{ .pid = 0, .fd = -1 } }) catch {};
+ },
+ .replica => |j| loop.postEvent(.{ .replica = j }) catch {
+ _ = libc.close(j.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 {
@@ -1502,12 +1938,19 @@ const Shell = struct {
core: *pardes.Pardes,
prompt_rcs: *const host_io.Shell.PromptFiles,
loop: *Loop,
- vx: *vaxis.Vaxis,
- tty: *vaxis.Tty,
- 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,
+ /// Shells a dead session left (Adopt), each waiting for the spawn of
+ /// the terminal pane made for it.
+ adoptions: [pardes.MAX_PANES]Adoption = undefined,
+ adoptions_len: usize = 0,
+ adopted: usize = 0,
fs: ?*ninep_io.Listener = null,
ptys: [pardes.MAX_PANES]?Pty = @splat(null),
gens: [pardes.MAX_PANES]u32 = @splat(0),
@@ -1516,16 +1959,10 @@ 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,
+ // ponytail: one bracketed paste at a time for every terminal: keys
+ // another terminal sends while one pastes join its paste.
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,
@@ -1534,6 +1971,54 @@ const Shell = struct {
pace_ns: u64 = 0,
input_seen: bool = false,
wake_to: u64 = 0,
+ /// waitInput's pacing of output: whether this wait read a pane's output,
+ /// and when the last frame was written, the last input was read and the
+ /// focused pane's output last was.
+ output_seen: bool = false,
+ drawn_ns: u64 = 0,
+ input_ns: u64 = 0,
+ focused_ns: u64 = 0,
+ /// Upgrade was asked from this pane, to be done between steps (`upgradeNow`).
+ 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 wait's steps so far, and the input held for the next (`split`).
+ took_input: bool = false,
+ took_output: bool = false,
+ held: ?@TypeOf(Command.value) = null,
+ /// 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);
+ c.link.input(ev);
+ }
+
+ /// 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.?));
@@ -1557,6 +2042,11 @@ const Shell = struct {
.present = present,
.post_present = postPresent,
.poll_frame = pollFrame,
+ .watched = watched,
+ .detach = detach,
+ .adopt = adopt,
+ .upgrade = upgradeAsked,
+ .newer_build = newerBuild,
.spawn = spawn,
.pty_write = ptyWrite,
.pty_resize = ptyResize,
@@ -1580,9 +2070,354 @@ 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);
}
+ /// 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.term() orelse return true;
+ return screen.on;
+ }
+
+ /// 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 {
+ 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);
+ 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.term() orelse return;
+ stopInput(s.io, &screen.thread);
+ screen.leave();
+ s.core.native_images = false;
+ 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) {
+ for (0..3) |i| _ = libc.dup2(null_fd, @intCast(i));
+ if (null_fd > 2) _ = libc.close(null_fd);
+ }
+ screen.sayDetached();
+ daemon.setState(true);
+ }
+
+ /// `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, cooked: ?posix.termios) void {
+ // A replica client's view live (its input the last) has no terminal
+ // here: the session's own is the one a terminal takes, or joins.
+ const live = s.term() orelse for (s.terms) |slot| {
+ if (slot) |sc| if (sc.primary) break sc;
+ } else {
+ _ = libc.close(fd);
+ return refuse(stub, "that session has no terminal of its own to attach to");
+ };
+ 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 refuse(stub, "that session has no room for another terminal");
+ };
+ const extra = screen != live;
+ const tty = Screen.ttyOn(s.io, screen.buf, fd, cooked) catch {
+ _ = libc.close(fd);
+ if (extra) s.freeScreen(screen) else daemon.setState(true);
+ return refuse(stub, "that terminal would not go raw");
+ };
+ screen.enter(tty) catch {
+ if (extra) s.freeScreen(screen) else daemon.setState(true);
+ return refuse(stub, "that terminal would not take the screen");
+ };
+ 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.setAttended(true);
+ 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 {
+ const s = of(ctx);
+ if (!daemon.kept()) return s.core.reportFailure(pane, "Adopt: no pardes daemon is keeping shells for this session");
+ s.adopted = 0;
+ daemon.adopt();
+ }
+
+ /// A client's own build is not the session's to say (its core's host
+ /// is the session's, through the tape).
+ fn newerBuild(ctx: ?*anyopaque) bool {
+ return of(ctx).remote == null and upgrade.newer();
+ }
+
+ fn upgradeAsked(ctx: ?*anyopaque, pane: u8) void {
+ const s = of(ctx);
+ if (comptime !upgrade.supported) return s.core.reportFailure(pane, "Upgrade: this system cannot move a session to another build in place");
+ s.upgrade_asked = pane;
+ }
+
+ /// Upgrade, between steps: this process exec'd as the pardes now at the
+ /// path it was started from, the session in its dump, and its ptys,
+ /// terminals, stubs and daemon link kept open across (upgrade.zig).
+ /// Returns only when it could not be, the session going on as it was.
+ fn upgradeNow(s: *Shell, pane: u8) void {
+ if (comptime builtin.is_test) unreachable; // vaxis.Tty is its TestTty
+ s.upgrade_asked = null;
+ const core = s.core;
+ var why: [800]u8 = undefined;
+ const path = upgrade.exe() orelse return core.reportFailure(pane, "Upgrade: this process does not know the path it was started from");
+ // 9P is served while the new binary is asked (its clients' clunks
+ // and reads after the word are answered), and not after.
+ pardes.turn.rest();
+ const checked = upgrade.check(path, &why);
+ pardes.turn.wake();
+ switch (checked) {
+ .no => |w| return core.reportFailure(pane, w),
+ .ok => {},
+ }
+ // Nothing more read from a pty or a terminal, and what was read
+ // goes in; a reader's cancel posts an end of file, passed over.
+ s.upgrading = true;
+ defer s.upgrading = false;
+ for (&s.ptys) |*slot| if (slot.*) |*pt| pt.reader.cancel(s.io) catch {};
+ for (s.terms) |slot| if (slot) |sc| stopInput(s.io, &sc.thread);
+ while (s.loop.tryEvent() catch null) |ev| _ = s.apply(ev);
+ core.settle();
+ // Its replica clients told, their views gone before the dump: each
+ // dials the session again once it is back.
+ s.peers.refuseAll(core, "the session is upgrading to another build of pardes");
+ var rec: upgrade.Record = .{ .link = daemon.link, .stub = daemon.stub, .exe = path };
+ for (s.ptys, 0..) |slot, id| if (slot) |pt| rec.addPty(id, pt.pid, pt.file.handle);
+ for (s.terms, 0..) |slot, k| if (slot) |sc| if (sc.on) rec.addTty(.{
+ .view = @intCast(k),
+ .fd = sc.tty.fd.handle,
+ .stub = if (sc.primary) daemon.stub else sc.stub,
+ .primary = sc.primary,
+ .termios = sc.tty.termios,
+ });
+ var popped = false;
+ var at_buf: [1024:0]u8 = undefined;
+ const failed: []const u8 = failed: {
+ const at = pardes.dump.upgradePath(&at_buf, core.settings.dump_dir.get()) orelse break :failed "Upgrade: no directory for the session's dump; this session stays as it is";
+ const bytes = pardes.dump.dumpBytes(core) catch |err| {
+ var words: [128]u8 = undefined;
+ break :failed std.fmt.bufPrint(&why, "Upgrade: the session would not dump: {s}; it stays as it is", .{pardes.Messages.errorWords(err, &words)}) catch "Upgrade: the session would not dump";
+ };
+ defer s.gpa.free(bytes);
+ if (!upgrade.writeDump(at, bytes)) break :failed std.fmt.bufPrint(&why, "Upgrade: the session's dump could not be written to {s}; it stays as it is", .{at[0..@min(at.len, 600)]}) catch "Upgrade: its dump could not be written";
+ rec.dump = at;
+ rec.old = upgrade.openSelf();
+ // What this process put in its terminals that the next puts in
+ // again: its images, and its keyboard mode, a stack.
+ for (s.terms) |slot| if (slot) |sc| if (sc.on) {
+ clearNativeImages(&sc.kitty, &sc.vx, &sc.tty);
+ if (sc.vx.state.kitty_keyboard) sc.tty.writer().writeAll("\x1b[<u") catch {};
+ sc.vx.state.kitty_keyboard = false;
+ sc.tty.writer().flush() catch {};
+ };
+ popped = true;
+ unlinkKittyShm();
+ daemon.upgraded();
+ if (s.fs) |f| f.flushOut();
+ const err_words = upgrade.exec(s.gpa, path, -1, &rec);
+ // Still here: the exec failed.
+ _ = libc.unlink(at);
+ if (rec.old >= 0) _ = libc.close(rec.old);
+ break :failed std.fmt.bufPrint(&why, "Upgrade: {s} would not start: {s}; this session stays as it is", .{ path[0..@min(path.len, 600)], err_words }) catch "Upgrade: the new pardes would not start";
+ };
+ // As it was: its ptys read on, its terminals' keys as they were.
+ for (&s.ptys, 0..) |*slot, id| if (slot.*) |*pt| {
+ pt.reader = s.io.concurrent(readPty, .{ s.io, s.gpa, pt.file, id, s.gens[id], s.loop }) catch pt.reader;
+ };
+ for (s.terms) |slot| if (slot) |sc| if (sc.on) {
+ if (popped) sc.vx.enableDetectedFeatures(sc.tty.writer()) catch {};
+ startInput(s.loop, sc) catch {};
+ };
+ core.reportFailure(pane, failed);
+ }
+
+ /// An upgraded session's shells, running on: each its pane's pty again,
+ /// or, when its dump would not load (`fresh`), adopted as new panes.
+ fn resumePtys(s: *Shell, rec: *const upgrade.Record) void {
+ for (rec.ptys[0..rec.nptys]) |k| {
+ const pane = if (rec.fresh) null else s.core.panes[k.pane];
+ if (pane == null or !pane.?.isTerminal()) {
+ s.adoptShell(k.pid, k.fd);
+ continue;
+ }
+ const file: std.Io.File = .{ .handle = k.fd, .flags = .{ .nonblocking = false } };
+ s.ptys[k.pane] = .{ .file = file, .pid = k.pid, .reader = .{ .any_future = null, .result = {} }, .cmd = .{ .watched = pane.?.command != null and host_io.watchExit(k.pid), .fd = k.fd } };
+ }
+ }
+
+ /// An upgraded session's terminals, each its view's again (`primary`,
+ /// run's, entered already); in a fresh session each but the primary a
+ /// view of its own, as `--attach` makes one. A view left with none
+ /// closes, but a replica client's, kept for its rejoin (views.away).
+ fn resumeTerminals(s: *Shell, rec: *const upgrade.Record, primary: *Screen) void {
+ if (comptime builtin.is_test) unreachable;
+ const core = s.core;
+ if (rec.fresh) {
+ for (rec.ttys[0..rec.nttys]) |t| if (!t.primary) s.attachTerminal(t.fd, t.stub, t.termios);
+ return;
+ }
+ s.terms = @splat(null);
+ if (rec.nttys == 0) {
+ // The live view alone (never one kept for a rejoin) is the
+ // session's own.
+ for (0..pardes.views.max) |k| if (k != core.view and pardes.views.isOpen(core, @intCast(k)) and !pardes.views.isAway(core, @intCast(k))) core.closeView(@intCast(k));
+ s.terms[core.view] = primary;
+ primary.feed.view = core.view;
+ return;
+ }
+ for (rec.ttys[0..rec.nttys]) |t| {
+ if (!pardes.views.isOpen(core, t.view) or s.terms[t.view] != null) {
+ if (t.primary) continue;
+ _ = libc.close(t.fd);
+ if (t.stub >= 0) daemon.tellDetached(t.stub);
+ continue;
+ }
+ const sc = if (t.primary) primary 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 = primary.env, .buf = buf, .kitty = .init(s.gpa) };
+ const tty = Screen.ttyOn(s.io, sc.buf, t.fd, t.termios) catch {
+ s.freeScreen(sc);
+ break :extra null;
+ };
+ sc.enter(tty) catch {
+ s.freeScreen(sc);
+ break :extra null;
+ };
+ sc.setStub(t.stub);
+ startInput(s.loop, sc) catch {};
+ sc.vx.queryTerminalSend(sc.tty.writer()) catch {};
+ break :extra sc;
+ } orelse {
+ _ = libc.close(t.fd);
+ if (t.stub >= 0) daemon.tellDetached(t.stub);
+ continue;
+ };
+ sc.feed.view = t.view;
+ s.terms[t.view] = sc;
+ }
+ for (0..pardes.views.max) |k| if (pardes.views.isOpen(core, @intCast(k)) and s.terms[k] == null and !pardes.views.isAway(core, @intCast(k))) core.closeView(@intCast(k));
+ if (s.terms[core.view] == null) s.terms[core.view] = primary;
+ }
+
+ /// One shell of a dead session (`pid` 0: the last of them was told).
+ fn adoptShell(s: *Shell, pid: posix.pid_t, fd: posix.fd_t) void {
+ const core = s.core;
+ if (pid == 0) {
+ var buf: [96]u8 = undefined;
+ return core.setMessage(core.active, if (s.adopted == 0) "Adopt: no shell of a session that died is waiting" else std.fmt.bufPrint(&buf, "Adopt: {d} shell{s} taken in; what they showed is gone", .{ s.adopted, if (s.adopted == 1) "" else "s" }) catch "Adopt: shells taken in");
+ }
+ if (s.adoptions_len < s.adoptions.len) {
+ // A terminal pane, as the Tty word makes one; its spawn takes
+ // this pty instead of forking a shell (`spawn`).
+ s.adoptions[s.adoptions_len] = .{ .pid = pid, .fd = fd, .pane = null };
+ s.adoptions_len += 1;
+ if (core.adoptShell()) |id| {
+ s.adoptions[s.adoptions_len - 1].pane = id;
+ s.adopted += 1;
+ return;
+ }
+ s.adoptions_len -= 1;
+ }
+ // No room for it: its master goes, and the shell with this session.
+ _ = libc.close(fd);
+ var buf: [96]u8 = undefined;
+ core.setMessage(core.active, std.fmt.bufPrint(&buf, "Adopt: no room for shell {d}; it ends with this session", .{pid}) catch "Adopt: no room for a shell");
+ }
+
fn waitInput(ctx: ?*anyopaque, timeout_ms: u32) void {
const s = of(ctx);
// The wait is the 9P connections' turn with the core. A timeout (the
@@ -1593,6 +2428,14 @@ const Shell = struct {
// ends the wait at once and its frame is drawn then; the ticks after
// it run from it.
var wait = timeout_ms;
+ // Detached, nobody's key dismisses a message: they go on the clock
+ // (the pump's, after this wait), which wakes it.
+ if (!s.attached()) {
+ for (s.core.panes) |slot| if (slot) |pane| if (pane.msg_len > 0) {
+ wait = if (wait == 0) 100 else @min(wait, 100);
+ break;
+ };
+ }
const paced = s.test_clock == null and s.core.continuous();
var tick: u64 = 0;
if (paced) {
@@ -1604,6 +2447,11 @@ const Shell = struct {
wait = @intCast(@max(1, (tick -| now) / std.time.ns_per_ms));
}
s.input_seen = false;
+ s.output_seen = false;
+ s.took_input = false;
+ s.took_output = 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.
@@ -1615,29 +2463,51 @@ const Shell = struct {
wait = @intCast((tick - now) / std.time.ns_per_ms);
}
if (paced and s.input_seen) s.pace_ns = @intCast(std.Io.Clock.awake.now(s.io).nanoseconds);
+ // Output alone is drawn a frame a tick at most, what came in till
+ // then in one: a flood (`yes`, 4 KB a read) was drawn a read at a
+ // time, nearly all of its frames written over before they were
+ // seen. Never while what someone waits on is undrawn: an input
+ // (its frame held for the terminal's answer, FrameAck), or the
+ // focused pane's output soon after one, its echo (a remote shell's
+ // an RTT later).
+ while (!paced and s.output_seen and !s.input_seen and !s.core.quit and s.test_clock == null) {
+ if (s.input_ns > s.drawn_ns) break;
+ if (s.focused_ns > s.drawn_ns and s.focused_ns -| s.input_ns < std.time.ns_per_s) break;
+ const due = s.drawn_ns + pardes.animation.frame_ns;
+ const now: u64 = @intCast(std.Io.Clock.awake.now(s.io).nanoseconds);
+ if (now + std.time.ns_per_ms > due) break;
+ s.waitOnce(@intCast((due - now) / std.time.ns_per_ms));
+ }
}
fn waitOnce(s: *Shell, wait: u32) void {
var batch: usize = 0;
- if (wait != 0) {
- // A virtual clock moves a frame a wake while anything moves
- // continuously (the glide), as the real one would.
- s.wake_to = s.core.nextWake() orelse if (s.core.continuous()) s.core.now_ns + pardes.animation.frame_ns else 0;
- requestWake(s.io, wait);
- }
- pardes.turn.rest();
- const first = s.loop.nextEvent() catch {
+ const first = if (s.held) |held| held: {
+ s.held = null;
+ break :held held;
+ } else next: {
+ if (wait != 0) {
+ // A virtual clock moves a frame a wake while anything moves
+ // continuously (the glide), as the real one would.
+ s.wake_to = s.core.nextWake() orelse if (s.core.continuous()) s.core.now_ns + pardes.animation.frame_ns else 0;
+ requestWake(s.io, wait);
+ }
+ pardes.turn.rest();
+ const got = s.loop.nextEvent() catch {
+ pardes.turn.wake();
+ s.core.quit = true;
+ return s.reloadWatched();
+ };
pardes.turn.wake();
- s.core.quit = true;
- return s.reloadWatched();
+ break :next got;
};
- pardes.turn.wake();
batch = 1;
// A run of queued motions is one move to its last cell: each would
// otherwise redo hover and selection work the next one undoes.
var motion: ?@TypeOf(Command.value) = null;
var ev = first;
while (true) {
+ if (s.split(ev)) break;
if (ev == .mouse and (ev.mouse.type == .motion or ev.mouse.type == .drag)) {
if (motion) |m| if (m.mouse.button != ev.mouse.button or m.mouse.type != ev.mouse.type or
@as(u3, @bitCast(m.mouse.mods)) != @as(u3, @bitCast(ev.mouse.mods)))
@@ -1661,6 +2531,31 @@ const Shell = struct {
s.reloadWatched();
}
+ /// With replica clients, a wait (one pump, one unit) takes one step of
+ /// a person's input, and none after a pty's output: a step reads the
+ /// terminals as the clients' deltas bring them, sent after each unit
+ /// (docs/next-daemon.md, part B terminal notes). One that must wait is
+ /// held for the next. Whether `ev` is.
+ fn split(s: *Shell, ev: @TypeOf(Command.value)) bool {
+ if (!s.peers.recording) return false;
+ switch (ev) {
+ .pty_read => {
+ s.took_output = true;
+ return false;
+ },
+ .key_press => if (s.in_paste) return false,
+ .mouse, .paste, .paste_end, .winsize, .focus_in, .focus_out => {},
+ else => return false,
+ }
+ if (s.took_output or s.took_input) {
+ s.held = ev;
+ s.input_seen = true;
+ return true;
+ }
+ s.took_input = true;
+ return false;
+ }
+
fn apply(s: *Shell, event: @TypeOf(Command.value)) bool {
const core = s.core;
const tz_event = tracy.zone(@src(), "event");
@@ -1679,28 +2574,85 @@ const Shell = struct {
.paste, .paste_start, .winsize => s.input_seen = true,
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.local()) {
+ if (event == .paste) s.gpa.free(@constCast(event.paste));
+ return false;
+ }
+ if (s.local() and s.remote == 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 => {
+ if (s.remote) |c| {
+ c.link.quit = true;
+ return true;
+ }
+ // 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
+ // waits on it) is not started yet: started here.
+ daemon.watch(s.loop, deliverNote);
+ if (daemon.kept()) {
+ if (s.attached()) s.leaveTerminal();
+ return true;
+ }
core.quit = true;
return true;
},
- .focus_in => core.update(.{ .focus = true }),
- .focus_out => {
- core.update(.pointer_leave);
- core.update(.{ .focus = false });
+ .attach => |a| s.attachTerminal(a.tty, a.stub, null),
+ .adopted => |a| s.adoptShell(a.pid, a.fd),
+ .replica => |j| {
+ s.peers.handed(j.fd, j.view);
+ s.input_seen = true;
},
- .winsize => |ws| {
- 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 } });
+ .replica_mail => s.input_seen = true,
+ .said => |said| if (s.remote) |c| {
+ c.link.take(said);
+ if (said == .refused) return true;
+ } else switch (said) {
+ .unit, .screen, .refused => |b| std.heap.c_allocator.free(b),
+ .checked => {},
},
+ .link_gone => if (s.remote) |c| {
+ c.link.quit = true;
+ c.link.gone = true;
+ return true;
+ },
+ .focus_in => s.feed(.{ .focus = true }),
+ .focus_out => {
+ s.feed(.pointer_leave);
+ s.feed(.{ .focus = false });
+ },
+ .winsize => |ws| if (s.attached()) s.resized(s.terms[s.from], ws),
.pty_read => |pr| {
+ tookRead(s.io, pr.id);
+ s.output_seen = true;
+ if (pr.id == core.active) s.focused_ns = @intCast(std.Io.Clock.awake.now(s.io).nanoseconds);
if (s.gens[pr.id] == pr.gen)
core.update(.{ .output = .{ .pane = @intCast(pr.id), .bytes = pr.bytes } });
s.gpa.free(pr.bytes);
@@ -1708,7 +2660,7 @@ const Shell = struct {
s.takeExits();
return true;
},
- .pty_eof => |e| if (s.gens[e.id] == e.gen) {
+ .pty_eof => |e| if (s.gens[e.id] == e.gen and !s.upgrading) {
if (s.ptys[e.id]) |*pt| {
pt.reader.await(s.io) catch {}; // reader just finished; join it or its future leaks
// A command's pty stays open until its child has exited:
@@ -1733,10 +2685,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| {
@@ -1746,7 +2698,7 @@ const Shell = struct {
}
},
.paste => |bytes| {
- core.update(.{ .paste = bytes });
+ s.feed(.{ .paste = bytes });
s.gpa.free(@constCast(bytes));
},
.paste_start => {
@@ -1756,7 +2708,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,
@@ -1793,6 +2745,28 @@ const Shell = struct {
return false;
}
+ /// 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 {};
+ }
+ 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
+ /// 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;
+ if (s.remote == null) s.core.toView(@intCast(k));
+ s.resized(sc, ws);
+ }
+ }
+
fn reloadWatched(s: *Shell) void {
if (!s.check_files) return;
s.check_files = false;
@@ -1805,13 +2779,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 {};
};
@@ -1820,23 +2793,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.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;
}
@@ -1844,22 +2820,23 @@ 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);
+ if (s.remote) |c| if (c.link.notice_len > 0) noticeLine(win, c.link.notice(), trailed.cols, trailed.rows);
tz_cells.end();
for (surface.images[0..surface.nimages]) |maybe| {
const place = maybe orelse continue;
@@ -1868,7 +2845,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
@@ -1880,21 +2857,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 {};
@@ -1935,36 +2912,42 @@ 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();
}
fn spawn(ctx: ?*anyopaque, pane: u8, cwd: []const u8) void {
const s = of(ctx);
+ for (s.adoptions[0..s.adoptions_len], 0..) |a, i| if (a.pane == pane) {
+ std.mem.copyForwards(Adoption, s.adoptions[i .. s.adoptions_len - 1], s.adoptions[i + 1 .. s.adoptions_len]);
+ s.adoptions_len -= 1;
+ return s.takeShell(pane, a);
+ };
// The new shell starts before a running one goes: one that cannot
// start leaves the running one be (pty/ctl's exec).
const running = s.ptys[pane] != null;
@@ -1988,6 +2971,25 @@ const Shell = struct {
}
}
+ /// An adopted shell, running already, as pane `pane`'s: told the size
+ /// twice (a size it never had, then the pane's), which makes it redraw.
+ fn takeShell(s: *Shell, pane: u8, a: Adoption) void {
+ closePty(s, pane);
+ s.gens[pane] +%= 1;
+ const file: std.Io.File = .{ .handle = a.fd, .flags = .{ .nonblocking = false } };
+ s.ptys[pane] = .{ .file = file, .pid = a.pid, .reader = .{ .any_future = null, .result = {} }, .cmd = .{} };
+ var exe_buf: [pardes.memory.limits.host_path_cap + 1]u8 = undefined;
+ s.core.acknowledgeShell(pane, host_io.processExe(a.pid, &exe_buf) orelse "sh", host_io.marksPrompts(a.pid));
+ var lbuf: [pardes.memory.limits.host_path_cap + 1]u8 = undefined;
+ if (host_io.shellCwd(a.pid, &lbuf)) |wd| s.core.setCwd(pane, wd);
+ const tiny: posix.winsize = .{ .row = 1, .col = 1, .xpixel = 0, .ypixel = 0 };
+ _ = posix.system.ioctl(a.fd, TIOCSWINSZ, @intFromPtr(&tiny));
+ if (s.core.panes[pane]) |pn| ptyResize(s, pane, @max(pn.cols, 1), @max(pn.rows, 1));
+ if (s.threads_ok) if (s.ptys[pane]) |*pt| {
+ pt.reader = s.io.concurrent(readPty, .{ s.io, s.gpa, pt.file, @as(usize, pane), s.gens[pane], s.loop }) catch pt.reader;
+ };
+ }
+
fn ptyWrite(ctx: ?*anyopaque, pane: u8, bytes: []const u8) void {
const s = of(ctx);
if (s.ptys[pane]) |pt| _ = host_io.writeFd(pt.file.handle, bytes);
@@ -2018,6 +3020,7 @@ const Shell = struct {
s.gens[pane] +%= 1;
pt.reader.cancel(s.io) catch {};
_ = libc.close(pt.file.handle);
+ daemon.closed(pt.pid);
host_io.retireShell(pt.pid);
}
@@ -2078,12 +3081,17 @@ const Shell = struct {
fn setClipboard(ctx: ?*anyopaque, text: []const u8) void {
const s = of(ctx);
- copyToClipboard(s.vx, s.tty, s.gpa, text);
+ // Detached, the session keeps it (a 9P read, a paste here).
+ 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);
- 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 {
@@ -2147,9 +3155,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,
@@ -2195,9 +3200,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,
@@ -2246,7 +3248,7 @@ fn lspStatusSink(ctx: ?*anyopaque, text: []const u8) void {
}
fn watchFiles(io: std.Io, fd: c_int, loop: *Loop) anyerror!void {
- if (comptime builtin.os.tag != .linux) {
+ if (comptime builtin.os.tag != .linux and builtin.os.tag != .freebsd) {
while (file_watch.wait(fd)) loop.postEvent(.files_changed) catch break;
return;
}
@@ -2261,23 +3263,22 @@ fn watchFiles(io: std.Io, fd: c_int, loop: *Loop) anyerror!void {
}
}
-fn winchWatch(loop: *Loop, vx: *vaxis.Vaxis, tty: *vaxis.Tty) void {
- winchWatchUntil(loop, vx, tty, null);
-}
+fn keepSignal(_: posix.SIG) callconv(.c) void {}
-/// A SIGWINCH watcher that ends: `stop` set, then a SIGWINCH sent to its
-/// thread, wakes its sigwait and it returns, so whoever owns `loop` can join
-/// it before the loop goes (attachSession's loop is on its stack).
-fn winchWatchUntil(loop: *Loop, vx: *vaxis.Vaxis, tty: *vaxis.Tty, stop: ?*const std.atomic.Value(bool)) void {
+/// A replica client's (`remote`): a hangup is its end, whoever sent it.
+var hangup_quits = false;
+
+fn winchWatch(loop: *Loop) void {
var set = posix.sigemptyset();
posix.sigaddset(&set, posix.SIG.WINCH);
+ if (daemon.link >= 0 or hangup_quits) posix.sigaddset(&set, posix.SIG.HUP);
while (true) {
var sig: c_int = 0;
if (libc.sigwait(&set, &sig) != 0) continue;
- if (stop) |flag| if (flag.load(.acquire)) return;
- 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.
+ const ev: @TypeOf(Command.value) = if (sig != @backingInt(posix.SIG.HUP)) .winched else if (hangup_quits) .quit else .hangup;
+ loop.postEvent(ev) catch {};
}
}
@@ -2356,15 +3357,37 @@ fn wakeFs(ctx: ?*anyopaque) void {
_ = loop.tryPostEvent(.fs_ready) catch {};
}
+/// Each pane's reads posted and not yet taken in. Two at most: a flood the
+/// loop cannot keep up with waits in its pty, not in the queue ahead of a
+/// key and its echo (hundreds of 4 KB reads queued were half a second).
+var reads_queued: [pardes.MAX_PANES]std.atomic.Value(u32) = @splat(.init(0));
+
+/// A read of pane `id` taken in (or dropped): its reader may read on. Never
+/// below zero, for an event no reader posted (a test's).
+fn tookRead(io: std.Io, id: usize) void {
+ var queued = reads_queued[id].load(.acquire);
+ while (queued > 0) queued = reads_queued[id].cmpxchgWeak(queued, queued - 1, .acq_rel, .acquire) orelse {
+ if (queued == 2) io.futexWake(u32, &reads_queued[id].raw, 1);
+ return;
+ };
+}
+
fn readPty(io: std.Io, gpa: std.mem.Allocator, pty: std.Io.File, id: usize, gen: u32, loop: *Loop) anyerror!void {
// One buffer, read into directly: a Reader around it only added a second
// (and in a safe build, filled both as `undefined` on every start).
var buf: [0x10000]u8 = undefined;
- while (true) {
+ read: while (true) {
+ while (true) {
+ const queued = reads_queued[id].load(.acquire);
+ if (queued < 2) break;
+ io.futexWait(u32, &reads_queued[id].raw, queued) catch break :read;
+ }
const n = pty.readStreaming(io, &.{&buf}) catch break;
if (n == 0) break;
const bytes = try gpa.dupe(u8, buf[0..n]);
+ _ = reads_queued[id].fetchAdd(1, .acq_rel);
loop.postEvent(.{ .pty_read = .{ .id = id, .gen = gen, .bytes = bytes } }) catch {
+ tookRead(io, id);
gpa.free(bytes);
break;
};
@@ -2396,7 +3419,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,
@@ -2429,7 +3452,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;
@@ -2572,6 +3595,17 @@ test "a mouse's side buttons, xterm's 8 and 9, are Back and Forward, as SDL's X1
}
}
+/// A replica client's own line over its frame's last row (`Remote.notify`),
+/// reversed. `text` is printable ASCII and outlives the render (vaxis keeps
+/// the slices).
+fn noticeLine(win: vaxis.Window, text: []const u8, cols: u16, rows: u16) void {
+ if (rows == 0) return;
+ for (0..cols) |x| win.writeCell(@intCast(x), rows - 1, .{
+ .char = .{ .grapheme = if (x < text.len) text[x..][0..1] else " " },
+ .style = .{ .reverse = true },
+ });
+}
+
/// A blank whose ink alone changed is not sent: vaxis's render skips it
/// (pardes's patch to Vaxis.zig in build.zig), since a blank's ink shows
/// nowhere. Deciding that here cost every cell of every frame a look at the
@@ -2869,243 +3903,6 @@ fn vaxisColor(c: pardes.Color) vaxis.Color {
};
}
-const AttachEnd = union(enum) {
- none,
- no_session: []const u8,
- nothing_detached,
- ambiguous: usize,
- refused: wire.Refusal,
- lost: anyerror,
- rejected,
- silent,
- detached: []const u8,
-
- fn report(e: AttachEnd, io: std.Io) void {
- var buf: [512]u8 = undefined;
- var ok = false;
- const text: []const u8 = switch (e) {
- .none => return,
- .detached => |name| blk: {
- ok = true;
- break :blk if (name.len != 0) std.fmt.bufPrint(
- &buf,
- "pardes: detached from '{s}', which is still running — come back with `pardes --attach={s}`\n",
- .{ name, name },
- ) catch "pardes: detached; that session is still running\n" else "pardes: detached; that session is still running — come back with `pardes --attach`\n";
- },
- .no_session => |name| std.fmt.bufPrint(
- &buf,
- "pardes: no detached session called '{s}' (start one with `pardes --detach={s}`)\n",
- .{ name, name },
- ) catch "pardes: no detached session under that name\n",
- .nothing_detached => "pardes: no detached session is running (start one with `pardes --detach`)\n",
- .ambiguous => |n| std.fmt.bufPrint(
- &buf,
- "pardes: {d} detached sessions are running; say which with --attach=<name>\n",
- .{n},
- ) catch "pardes: several detached sessions are running; say which with --attach=<name>\n",
- .refused => |why| switch (why) {
- .version => "pardes: that session speaks a different wire version — it is another build of pardes\n",
- .full => "pardes: that session already has every frontend slot taken\n",
- .quitting => "pardes: that session is ending\n",
- },
- .lost => |err| std.fmt.bufPrint(&buf, "pardes: detached session lost: {t}\n", .{err}) catch
- "pardes: detached session lost\n",
- .rejected => "pardes: that session hung up on the connect — every frontend slot is taken (32), or it is shutting down. `PARDES_LOG=1` on the session names which\n",
- .silent => "pardes: that session accepted the connection and then never greeted it — it is wedged inside its own loop, or something else is listening at that path. `PARDES_LOG=1` on the session says which\n",
- };
- const out = if (ok) std.Io.File.stdout() else std.Io.File.stderr();
- out.writeStreamingAll(io, text) catch {};
- if (!ok) std.process.exit(1);
- }
-
- fn row(e: AttachEnd, buf: []u8) []const u8 {
- return switch (e) {
- .none => "attach: that session ended",
- .no_session => |name| std.fmt.bufPrint(buf, "attach: no session '{s}'", .{name}) catch
- "attach: no session under that name",
- .nothing_detached => "attach: no detached session is running",
- .ambiguous => |n| std.fmt.bufPrint(buf, "attach: {d} sessions running, name one", .{n}) catch
- "attach: several sessions running, name one",
- .refused => |why| switch (why) {
- .version => "attach: that session is another build of pardes",
- .full => "attach: that session has every frontend slot taken",
- .quitting => "attach: that session is ending",
- },
- .lost => |err| std.fmt.bufPrint(buf, "attach: {t}", .{err}) catch "attach: link lost",
- .rejected => "attach: that session hung up on the connect",
- .silent => "attach: that session accepted and never greeted",
- .detached => "attach: detached from that session",
- };
- }
-};
-
-const Attach = struct {
- gpa: std.mem.Allocator,
- client: *detached_client.Client,
- loop: *Loop,
- vx: *vaxis.Vaxis,
- tty: *vaxis.Tty,
- paste_buf: *std.Io.Writer.Allocating,
- session: []const u8 = &.{},
- caps_pending: bool = true,
- in_paste: bool = false,
- dirty: bool = false,
-
- fn send(a: *Attach, ev: pardes.Event) ?AttachEnd {
- a.client.send(.{ .event = ev }) catch |err| switch (err) {
- error.Overlong, error.WriteFailed => return null,
- else => return .{ .lost = err },
- };
- return null;
- }
-
- fn handle(a: *Attach, msg: wire.ServerMsg) ?AttachEnd {
- switch (msg) {
- .welcome => {},
- .refuse => |why| return .{ .refused = why },
- .frame => a.dirty = true,
- .quit => return .none,
- .detach => return .{ .detached = a.session },
- .set_clipboard => |text| copyToClipboard(a.vx, a.tty, a.gpa, text),
- .read_clipboard => requestClipboard(a.vx, a.tty),
- .open_link => |url| look.openLink(url),
- // A terminal has no post chain to draw through.
- .post => {},
- }
- return null;
- }
-
- fn apply(a: *Attach, event: @TypeOf(Command.value)) ?AttachEnd {
- switch (event) {
- .nop, .wake, .fs_ready, .lsp_done, .lsp_status, .pipe_done, .search_rows, .pty_read, .pty_eof, .files_changed => {},
- .quit => return .none,
- .focus_in => return a.send(.{ .focus = true }),
- .focus_out => {
- if (a.send(.pointer_leave)) |end| return end;
- return a.send(.{ .focus = false });
- },
- .winsize => |ws| {
- a.vx.resize(a.gpa, a.tty.writer(), ws) catch {};
- a.dirty = true;
- a.client.resize(ws.cols, ws.rows) catch |err| return .{ .lost = err };
- },
- .key_press => |key| if (a.in_paste) {
- const bytes = pasteBytes(key);
- const room = max_paste_bytes -| a.paste_buf.written().len;
- a.paste_buf.writer.writeAll(bytes[0..@min(bytes.len, room)]) catch {};
- } else return a.send(vaxis_input.keyEvent(key)),
- .mouse => |m| if (mouseEvent(m)) |ev| return a.send(ev),
- .paste => |bytes| {
- defer a.gpa.free(@constCast(bytes));
- return a.send(.{ .paste = bytes });
- },
- .paste_start => {
- a.in_paste = true;
- a.paste_buf.clearRetainingCapacity();
- },
- .paste_end => {
- a.in_paste = false;
- defer a.paste_buf.clearRetainingCapacity();
- const pasted = a.paste_buf.written();
- if (pasted.len > 0) return a.send(.{ .paste = pasted });
- },
- }
- return null;
- }
-
- fn enableCaps(a: *Attach) void {
- if (!a.caps_pending or !a.vx.queries_done.load(.unordered)) return;
- a.caps_pending = false;
- a.vx.enableDetectedFeatures(a.tty.writer()) catch {};
- a.vx.queueRefresh();
- a.dirty = true;
- }
-
- fn paint(a: *Attach) void {
- a.dirty = false;
- const win = a.vx.window();
- paintCells(win, a.client.grid.items, a.client.cols, a.client.rows);
- if (a.client.cursor) |cur| paintCursor(win, cur.x, cur.y, cur.bar);
- a.vx.render(a.tty.writer()) catch {};
- }
-};
-
-fn attemptEnd(a: *const detached_client.Attempt, requested: []const u8) AttachEnd {
- return switch (a.*) {
- .greeted => .none,
- .no_session => if (requested.len != 0) .{ .no_session = requested } else .nothing_detached,
- .ambiguous => |found| .{ .ambiguous = found },
- .refused => |why| .{ .refused = why },
- .silent => .silent,
- .lost => |err| if (err == error.Closed) .rejected else .{ .lost = err },
- };
-}
-
-fn attachLoop(a: *Attach) AttachEnd {
- while (true) {
- const link = a.client.wait(detached_client.poll_ms);
- while (true) {
- const msg = (a.client.next() catch |err| return .{ .lost = err }) orelse break;
- if (a.handle(msg)) |end| return end;
- }
- link catch |err| return .{ .lost = err };
- var batch: usize = 0;
- while (a.in_paste or batch < 64) {
- const ev = (a.loop.tryEvent() catch |err| return .{ .lost = err }) orelse break;
- batch += 1;
- if (a.apply(ev)) |end| return end;
- }
- a.enableCaps();
- if (a.dirty) a.paint();
- }
-}
-
-fn attachSession(init: std.process.Init, name: []const u8, tty: *vaxis.Tty, vx: *vaxis.Vaxis) AttachEnd {
- const io = init.io;
- const gpa = init.gpa;
-
- const ws = tty.getWinsize() catch |err| return .{ .lost = err };
- if (ws.cols == 0 or ws.rows == 0) return .{ .lost = error.NoWinsize };
- vx.resize(gpa, tty.writer(), ws) catch |err| return .{ .lost = err };
-
- var attempt = detached_client.attempt(gpa, name, ws.cols, ws.rows);
- var client = switch (attempt) {
- .greeted => |c| c,
- else => return attemptEnd(&attempt, name),
- };
- defer client.detach();
-
- var loop: Loop = .init(io, tty, vx);
- var input_cache: vaxis.GraphemeCache = .{};
- var paste_buf: std.Io.Writer.Allocating = .init(gpa);
- defer paste_buf.deinit();
-
- var a: Attach = .{
- .gpa = gpa,
- .client = &client,
- .loop = &loop,
- .vx = vx,
- .tty = tty,
- .paste_buf = &paste_buf,
- .session = name,
- };
- defer drainAttachedQueue(&loop, gpa);
-
- startInput(&loop, &input_cache) catch |err| return .{ .lost = err };
- defer stopInput(&loop);
- var winch_stop: std.atomic.Value(bool) = .init(false);
- const winch = std.Thread.spawn(.{}, winchWatchUntil, .{ &loop, vx, tty, &winch_stop }) catch |err| return .{ .lost = err };
- defer {
- winch_stop.store(true, .release);
- _ = libc.pthread_kill(winch.getHandle(), posix.SIG.WINCH);
- winch.join();
- }
- vx.queryTerminalSend(tty.writer()) catch {};
-
- return attachLoop(&a);
-}
-
test "a jump leaves a trail of a few cells behind the cursor that fades in 120 ms" {
const gpa = std.testing.allocator;
const core = try pardes.Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24 });