diff options
Diffstat (limited to 'src/tty/tty.zig')
| -rw-r--r-- | src/tty/tty.zig | 650 |
1 files changed, 309 insertions, 341 deletions
diff --git a/src/tty/tty.zig b/src/tty/tty.zig index a358051e..37f66456 100644 --- a/src/tty/tty.zig +++ b/src/tty/tty.zig @@ -14,9 +14,7 @@ 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"); extern "c" fn setenv(name: [*:0]const u8, value: [*:0]const u8, overwrite: c_int) c_int; @@ -78,7 +76,14 @@ 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, key_press: vaxis.Key, @@ -1166,78 +1171,99 @@ 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`). +pub const Term = union(enum) { open, fd: posix.fd_t, 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); 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(); - - if (attach != null) { - attach_end = attachSession(init, attach_name, &tty, &vx); - return; + var screen: Screen = .{ .io = io, .gpa = gpa, .env = init.environ_map, .buf = &tty_buf }; + switch (term) { + .open => try screen.enter(try vaxis.Tty.init(io, &tty_buf)), + .fd => |fd| try screen.enter(try Screen.ttyOn(io, &tty_buf, fd)), + .none => {}, } + defer screen.leave(); var kitty_handles = std.AutoHashMap(pardes.ImageCacheKey, vaxis.Image).init(gpa); defer { - clearNativeImages(&kitty_handles, &vx, &tty); + if (screen.on) clearNativeImages(&kitty_handles, &screen.vx, &screen.tty); kitty_handles.deinit(); } var paste_buf: std.Io.Writer.Allocating = .init(gpa); defer paste_buf.deinit(); - var loop: Loop = .init(io, &tty, &vx); + var loop: Loop = .init(io, &screen.tty, &screen.vx); var input_cache: vaxis.GraphemeCache = .{}; - var attached: ?detached_client.Client = null; - defer if (attached != null) { - stopInput(&loop); - drainAttachedQueue(&loop, gpa); - }; - 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, - }; - attach_end = attachLoop(&a); - } + try localSession(init, opts, &screen, &loop, &input_cache, &kitty_handles, &paste_buf); } +/// Whether a terminal is there to ask its size (winchWatch): none while +/// detached, when the descriptor it had may be another's. +var terminal_on = std.atomic.Value(bool).init(false); + +/// The terminal a session draws on, while it has one: entered (raw, the +/// 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). +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, + + /// `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. + fn ttyOn(io: std.Io, buf: []u8, fd: posix.fd_t) !vaxis.Tty { + if (comptime builtin.is_test) unreachable; // vaxis.Tty is its TestTty + const termios = 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) { + Killed.arm(sc.tty.fd.handle, sc.tty.termios); + // What a panic puts back (vaxis.recover). + vaxis.tty.global_tty = sc.tty; + } + sc.on = true; + terminal_on.store(true, .release); + } + + fn leave(sc: *Screen) void { + if (!sc.on) return; + sc.on = false; + terminal_on.store(false, .release); + Killed.disarm(); + sc.vx.exitAltScreen(sc.tty.writer()) catch {}; + sc.vx.deinit(sc.gpa, sc.tty.writer()); + if (comptime !builtin.is_test) vaxis.tty.global_tty = null; + sc.tty.deinit(); // restore cooked termios LAST, after vx flushed its resets + } +}; + /// SIGTERM or SIGHUP: the 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 @@ -1247,19 +1273,20 @@ const Killed = struct { var fd: posix.fd_t = -1; var cooked: 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; 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); } + /// The terminal gone (put back, or detached): a TERM still takes the + /// socket, the prompt files and the shells with it, and leaves the + /// terminal alone. fn disarm() void { fd = -1; - const default: posix.Sigaction = .{ .handler = .{ .handler = posix.SIG.DFL }, .mask = posix.sigemptyset(), .flags = 0 }; - for (signals) |sig| posix.sigaction(sig, &default, null); } fn handle(sig: posix.SIG) callconv(.c) void { @@ -1268,9 +1295,10 @@ const Killed = struct { _ = std.c.tcsetattr(fd, .FLUSH, &cooked); } // 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,16 +1307,16 @@ 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; + const vx = &screen.vx; + const tty = &screen.tty; const allocs = pardes.memory.init(gpa); defer pardes.memory.deinit(); @@ -1335,6 +1363,8 @@ fn localSession( .loop = loop, .vx = vx, .tty = tty, + .screen = screen, + .input_cache = input_cache, .kitty = kitty_handles, .frame = &frame_arena, .paste_buf = paste_buf, @@ -1351,12 +1381,9 @@ fn localSession( 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; @@ -1383,20 +1410,29 @@ fn localSession( response.deinit(gpa); }, .search_rows => |b| b.deinit(gpa), + .attach => |a| { + _ = libc.close(a.tty); + _ = libc.close(a.stub); + }, + .adopted => |a| _ = libc.close(a.fd), else => {}, }; } const host = sh.host(); core.host = host; + // Nobody to see it, and nobody to size it: `size` sets it (ctl.zig). + core.unattended = !screen.on; while (core.nextEffect()) |effect| core.perform(effect); - try startInput(loop, input_cache); - defer if (attached.* == null) stopInput(loop); + if (screen.on) try startInput(loop, input_cache); + defer stopInput(loop); (try std.Thread.spawn(.{}, winchWatch, .{ loop, vx, tty })).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 vx.queryTerminalSend(tty.writer()); + // Detached from the start, nothing else may wake the first wait. + if (!screen.on) daemon.watch(loop, deliverNote); sh.threads_ok = true; for (&sh.ptys, 0..) |*slot, id| if (slot.*) |*pt| { @@ -1413,9 +1449,13 @@ fn localSession( if (kittyShmName(&name_buf, n)) |name| _ = libc.shm_unlink(name) else |_| {} } } - frames: while (!core.quit) { + while (!core.quit) { pardes.turn.bump(&pardes.turn.restores); try core.pump(host); + // 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: { const bytes = filesystem.readRestore(gpa, rp, core.settings.dump_dir.get()) catch |err| { core.reportError(core.active, "Restore", err); @@ -1435,6 +1475,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 +1488,16 @@ 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; + if (screen.on) clearNativeImages(kitty_handles, vx, tty); + nc.native_images = screen.on and vx.caps.kitty_graphics; + nc.unattended = !screen.on; if (fs) |f| f.reset(nc); core.deinit(); core = nc; sh.core = nc; - if (comptime pardes.pdf_enabled) { + if (comptime pardes.pdf_enabled) if (screen.on) { updateCoreTerminalSize(core, vx.screen.width, vx.screen.height, vx.screen.width_pix, vx.screen.height_pix); - } - } - if (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 (fs) |f| { @@ -1488,11 +1517,25 @@ 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 {}; + }, + } } const Shell = struct { @@ -1504,10 +1547,18 @@ const Shell = struct { loop: *Loop, vx: *vaxis.Vaxis, tty: *vaxis.Tty, + /// The terminal, while there is one (Screen.on); null in tests. + screen: ?*Screen = null, + input_cache: ?*vaxis.GraphemeCache = null, kitty: *std.AutoHashMap(pardes.ImageCacheKey, vaxis.Image), 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), @@ -1557,6 +1608,9 @@ const Shell = struct { .present = present, .post_present = postPresent, .poll_frame = pollFrame, + .watched = watched, + .detach = detach, + .adopt = adopt, .spawn = spawn, .pty_write = ptyWrite, .pty_resize = ptyResize, @@ -1583,6 +1637,112 @@ const Shell = struct { return s.test_clock orelse @intCast(std.Io.Clock.awake.now(s.io).nanoseconds); } + fn attached(s: *const Shell) bool { + const screen = s.screen orelse return true; + return screen.on; + } + + /// Drawn only while a terminal shows it. + fn watched(ctx: ?*anyopaque) bool { + return of(ctx).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); + if (!s.attached()) return s.core.reportFailure(s.core.active, "Detach: no terminal is attached"); + 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(); + } + + fn leaveTerminal(s: *Shell) void { + const screen = s.screen orelse return; + stopInput(s.loop); + clearNativeImages(s.kitty, s.vx, s.tty); + screen.leave(); + s.core.native_images = false; + s.core.unattended = true; + // 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); + } + daemon.tellStubDetached(); + daemon.setState(true); + } + + /// `pardes --attach`'s terminal, for this detached session: entered as + /// the first one was, sized, asked what it can do, and drawn whole. + fn attachTerminal(s: *Shell, fd: posix.fd_t, stub: posix.fd_t) void { + const screen = s.screen orelse return; + if (screen.on) { + _ = libc.close(fd); + return daemon.refuseStub(stub, "that session has a terminal already"); + } + const tty = Screen.ttyOn(s.io, screen.buf, fd) catch { + _ = libc.close(fd); + daemon.setState(true); + return daemon.refuseStub(stub, "that terminal would not go raw"); + }; + screen.enter(tty) catch { + daemon.setState(true); + return daemon.refuseStub(stub, "that terminal would not take the screen"); + }; + daemon.stub = stub; + FrameAck.waiting.store(false, .release); + FrameAck.off.store(false, .release); + kitty_shm.store(false, .release); + s.caps_pending = true; + s.core.unattended = false; + startInput(s.loop, s.input_cache.?) catch {}; + s.vx.queryTerminalSend(s.tty.writer()) catch {}; + s.core.needs_frame = true; + daemon.setState(false); + } + + /// 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(); + } + + /// 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"); + } + var newest: u32 = 0; + for (core.panes) |slot| if (slot) |pn| { + newest = @max(newest, pn.serial); + }; + 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; + _ = core.executeBuiltinLine(core.active, "Tty"); + for (core.panes, 0..) |slot, id| if (slot) |pn| if (pn.serial > newest and pn.isTerminal()) { + // Its shell is up already: nothing to greet with `ls`. + pn.greet = false; + s.adoptions[s.adoptions_len - 1].pane = @intCast(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 +1753,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. + if (!s.attached()) { + pardes.Messages.expireUnattended(s.core); + 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) { @@ -1685,15 +1853,23 @@ const Shell = struct { virtual.* = @max(virtual.*, s.wake_to); }, .quit => { + // The terminal went: a session the daemon keeps carries on + // without it, to be attached again. + if (daemon.kept()) { + if (s.attached()) s.leaveTerminal(); + return true; + } core.quit = true; return true; }, + .attach => |a| s.attachTerminal(a.tty, a.stub), + .adopted => |a| s.adoptShell(a.pid, a.fd), .focus_in => core.update(.{ .focus = true }), .focus_out => { core.update(.pointer_leave); core.update(.{ .focus = false }); }, - .winsize => |ws| { + .winsize => |ws| if (s.attached()) { s.vx.resize(s.gpa, s.tty.writer(), ws) catch {}; if (comptime pardes.pdf_enabled) updateCoreTerminalSize(core, ws.cols, ws.rows, ws.x_pixel, ws.y_pixel) @@ -1820,7 +1996,7 @@ 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)) { + if (s.caps_pending and s.attached() and s.vx.queries_done.load(.unordered)) { s.caps_pending = false; s.vx.enableDetectedFeatures(s.tty.writer()) catch {}; s.core.native_images = s.vx.caps.kitty_graphics; @@ -1965,6 +2141,11 @@ const Shell = struct { 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 +2169,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 +2218,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,11 +2279,14 @@ const Shell = struct { fn setClipboard(ctx: ?*anyopaque, text: []const u8) void { const s = of(ctx); + // Detached, the session keeps it (a 9P read, a paste here). + if (!s.attached()) return s.core.fallback.setClipboard(text); copyToClipboard(s.vx, s.tty, s.gpa, text); } fn readClipboard(ctx: ?*anyopaque) void { const s = of(ctx); + if (!s.attached()) return s.core.update(.{ .paste = s.core.fallback.clipboard.items }); requestClipboard(s.vx, s.tty); } @@ -2262,19 +2466,20 @@ 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); -} - -/// 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 { var set = posix.sigemptyset(); posix.sigaddset(&set, posix.SIG.WINCH); + if (daemon.link >= 0) posix.sigaddset(&set, posix.SIG.HUP); while (true) { var sig: c_int = 0; if (libc.sigwait(&set, &sig) != 0) continue; - if (stop) |flag| if (flag.load(.acquire)) return; + // The terminal hung up (its stub passes the hangup on): as its + // input's end. + if (sig == @backingInt(posix.SIG.HUP)) { + loop.postEvent(.quit) catch {}; + continue; + } + // Detached, the descriptor the terminal had may be another's now. + if (!terminal_on.load(.acquire)) continue; if (vx.state.in_band_resize) continue; // terminal reports via CSI 48 const ws = tty.getWinsize() catch continue; loop.postEvent(.{ .winsize = ws }) catch {}; @@ -2869,243 +3074,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 }); |
