diff options
| author | Gabriel Schneider <[email protected]> | 2026-10-29 10:48:56 -0300 |
|---|---|---|
| committer | Gabriel Schneider <[email protected]> | 2026-10-29 12:01:27 -0300 |
| commit | 4ffe5c93b3087f245f5b57a822ab0ecf41cc085c (patch) | |
| tree | ede4d5de12fe169838f1f5993a9896bd32f45715 | |
| parent | cb2a6cd79e443d671f5255d262ea79b7e26552a5 (diff) | |
| download | pardes-4ffe5c93b3087f245f5b57a822ab0ecf41cc085c.tar.gz pardes-4ffe5c93b3087f245f5b57a822ab0ecf41cc085c.zip | |
sessions register with the daemon: a terminal's session forked off its stub, Detach and --attach in place for terminals and windows, pty masters kept, Adopt
pardes in a terminal reaches (or starts) the daemon, opens /dev/tty and forks: the child is the session, in a session of its own (setsid), drawing on that terminal (tty.Term.fd, a raw vaxis Tty made from the fd); the parent stays as its stub, the job the shell waits on. Not the daemon spawning it from a passed fd, env and argv: the user's terminals each run in a 9ns user and mount namespace, which a session spawned by a per-user daemon would not share, and a fork costs one small process's page tables where the spawn cost an IPC and an exec. GUI windows and --detach sessions just register.
tty: Detach (and a terminal's end: EOF, EIO, a hangup the stub passes on, taken on the signal thread) puts the terminal back, drops it and the stub's stdio, tells the stub (which ends, exit 0), and leaves the session running with nothing drawn (Host.watched), its messages on the clock and `size` its own. pardes --attach[=name] hands its terminal through the daemon; the session enters it as the first one, sized, queried and drawn whole, and that process is its stub until it leaves. A hangup never ends a kept session; TERM and INT do, telling the daemon so the shells go with it (one async-signal-safe send).
gui: Detach closes the window (its swapchain or renderer) and keeps the device, atlas and pipelines; the loop sleeps on SDL's queue; pardes-gui --attach[=name] opens a window again. Closing a window still quits.
--detach is a session started detached: the tty host with no terminal yet, the GUI with a hidden window closed at once. forkShell sends the daemon a dup of every master and the hosts tell it what they close, so a session killed outright leaves its shells running; the new Adopt word takes them in as terminal panes (the Tty word's pane, its spawn taking the pty, a 1x1 size then the pane's to make it redraw).
The Attach word, which switched a session's own terminal to a detached session through the frames, goes, with its effect and request in the core. PARDES_DAEMON=off (the e2e harness's) runs a session as before. test/daemon.py: 50 detach/attach cycles at a level fd count with no stale socket, kill -9 and Adopt, and nothing left; --gui the same for a window. test/fs.py: a forked session's socket is found by its own pid, and a hangup leaves a kept session running.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
| -rw-r--r-- | docs/typ/builtins-gui.json | 4 | ||||
| -rw-r--r-- | docs/typ/builtins-tty.json | 4 | ||||
| -rw-r--r-- | docs/typ/cheatsheet.typ | 3 | ||||
| -rw-r--r-- | docs/typ/guide.typ | 14 | ||||
| -rw-r--r-- | src/9p_io.zig | 22 | ||||
| -rw-r--r-- | src/builtins.zig | 49 | ||||
| -rw-r--r-- | src/config.zig | 4 | ||||
| -rw-r--r-- | src/file_watch.zig | 2 | ||||
| -rw-r--r-- | src/gui/gui.zig | 487 | ||||
| -rw-r--r-- | src/host_io.zig | 37 | ||||
| -rw-r--r-- | src/macos.zig | 3 | ||||
| -rw-r--r-- | src/main.zig | 137 | ||||
| -rw-r--r-- | src/pardes.zig | 72 | ||||
| -rw-r--r-- | src/tty/tty.zig | 650 | ||||
| -rw-r--r-- | src/tutor.txt | 4 | ||||
| -rw-r--r-- | test/daemon.py | 322 | ||||
| -rw-r--r-- | test/e2e_harness.zig | 4 | ||||
| -rw-r--r-- | test/fs.py | 40 |
18 files changed, 1100 insertions, 758 deletions
diff --git a/docs/typ/builtins-gui.json b/docs/typ/builtins-gui.json index db1031a0..9db9e396 100644 --- a/docs/typ/builtins-gui.json +++ b/docs/typ/builtins-gui.json @@ -1,6 +1,6 @@ [ + {"name": "Adopt", "leader": null, "also": [], "arg": false, "scope": "root", "setting": false, "choices": null, "doc": "Take in the shells of a session that died holding them, each as a terminal pane here: the pardes daemon kept their terminals open."}, {"name": "Ascii", "leader": "SPC t a", "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "add the printable ASCII bitmaps to the matcher's glyph set"}, - {"name": "Attach", "leader": "SPC s a", "also": [], "arg": true, "scope": "root", "setting": false, "choices": null, "doc": "Attach this terminal to a detached pardes session by name."}, {"name": "Back", "leader": "SPC j o", "also": ["C-o"], "arg": false, "scope": "root", "setting": false, "choices": null, "doc": "Ctrl-o: one step back into the history."}, {"name": "Bloom", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": "on, off, 0-3", "doc": "The brightest ink glows a little: a level, 0 (off) through 3."}, {"name": "BootShell", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": "keep, replace", "doc": "A document dropped where a lone untouched shell stands: keep the shell, or replace it."}, @@ -29,7 +29,7 @@ {"name": "DelAbove", "leader": null, "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Close the pane, giving its rows to the pane above it."}, {"name": "DelBelow", "leader": null, "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Close the pane, giving its rows to the pane below it."}, {"name": "Delcol", "leader": "SPC c d", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Close this column and its panes, refusing once over unsaved text."}, - {"name": "Detach", "leader": "SPC s D", "also": [], "arg": false, "scope": "root", "setting": false, "choices": null, "doc": "Detach this pardes from its terminal, leaving the session running."}, + {"name": "Detach", "leader": "SPC s D", "also": [], "arg": false, "scope": "root", "setting": false, "choices": null, "doc": "Detach this pardes from its terminal or window, leaving the session running: `pardes --attach` (or `pardes-gui --attach`) takes it back."}, {"name": "Diagnostics", "leader": "SPC l d", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "List the file's diagnostics from the language server."}, {"name": "Diff", "leader": null, "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Stack a diff's hunks as a diff viewer shows them, each under its place and the declarations around it, in a +Diff; on a +Diff, show the diff itself as text."}, {"name": "DiffLook", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": "hunks, text", "doc": "A .diff or .patch looked at: hunks, a +Diff stacking its hunks, or text, the file itself; Diff goes from one to the other."}, diff --git a/docs/typ/builtins-tty.json b/docs/typ/builtins-tty.json index 6bdca598..151c04a6 100644 --- a/docs/typ/builtins-tty.json +++ b/docs/typ/builtins-tty.json @@ -1,6 +1,6 @@ [ + {"name": "Adopt", "leader": null, "also": [], "arg": false, "scope": "root", "setting": false, "choices": null, "doc": "Take in the shells of a session that died holding them, each as a terminal pane here: the pardes daemon kept their terminals open."}, {"name": "Ascii", "leader": "SPC t a", "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "add the printable ASCII bitmaps to the matcher's glyph set"}, - {"name": "Attach", "leader": "SPC s a", "also": [], "arg": true, "scope": "root", "setting": false, "choices": null, "doc": "Attach this terminal to a detached pardes session by name."}, {"name": "Back", "leader": "SPC j o", "also": ["C-o"], "arg": false, "scope": "root", "setting": false, "choices": null, "doc": "Ctrl-o: one step back into the history."}, {"name": "BootShell", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": "keep, replace", "doc": "A document dropped where a lone untouched shell stands: keep the shell, or replace it."}, {"name": "Callees", "leader": "SPC l C", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "List the functions the function under the cursor calls."}, @@ -26,7 +26,7 @@ {"name": "DelAbove", "leader": null, "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Close the pane, giving its rows to the pane above it."}, {"name": "DelBelow", "leader": null, "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Close the pane, giving its rows to the pane below it."}, {"name": "Delcol", "leader": "SPC c d", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Close this column and its panes, refusing once over unsaved text."}, - {"name": "Detach", "leader": "SPC s D", "also": [], "arg": false, "scope": "root", "setting": false, "choices": null, "doc": "Detach this pardes from its terminal, leaving the session running."}, + {"name": "Detach", "leader": "SPC s D", "also": [], "arg": false, "scope": "root", "setting": false, "choices": null, "doc": "Detach this pardes from its terminal or window, leaving the session running: `pardes --attach` (or `pardes-gui --attach`) takes it back."}, {"name": "Diagnostics", "leader": "SPC l d", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "List the file's diagnostics from the language server."}, {"name": "Diff", "leader": null, "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Stack a diff's hunks as a diff viewer shows them, each under its place and the declarations around it, in a +Diff; on a +Diff, show the diff itself as text."}, {"name": "DiffLook", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": "hunks, text", "doc": "A .diff or .patch looked at: hunks, a +Diff stacking its hunks, or text, the file itself; Diff goes from one to the other."}, diff --git a/docs/typ/cheatsheet.typ b/docs/typ/cheatsheet.typ index 43162f52..11f7c6fc 100644 --- a/docs/typ/cheatsheet.typ +++ b/docs/typ/cheatsheet.typ @@ -105,7 +105,6 @@ Helix-style: motions *select*, then an edit acts on the selection. Mode box: bla key("SPC c p"), word("Placement"), key("SPC s d"), word("Dump"), key("SPC s r"), word("Restore"), - key("SPC s a"), word("Attach"), key("SPC s D"), word("Detach"), key("SPC h t"), word("Tutor"), key("SPC h m"), word("Messages"), @@ -124,7 +123,7 @@ Helix-style: motions *select*, then an edit acts on the selection. Mode box: bla - A query pane under the pane: line 1 the query, its first word the source: `/pat`, `Find name` (fuzzy), `Grep text` (literal), `Recent`, `Panes`, `Symbols`, `All`. #keys("Ctrl-n", "Ctrl-p") step, #key("Enter") lands and keeps the rows, #key("Esc") puts things back. #word("Help"), #word("Tutor"). == Sessions -`pardes --detach=work`; `--attach=work` or #word("Attach") `work`; #word("Detach") leaves it running. #doc("detached") +`pardes --detach=work`; `--attach=work` (`pardes-gui --attach=work`) takes it back; #word("Detach") leaves it running; #word("Adopt") takes in a killed session's shells. #doc("detached") == Config #word("Config") (#key("SPC f c")): `~/.config/pardes/init`, a builtin a line (#word("Theme") `atelier`). #word("DumpConfig"): every setting. #word("Dump") / #word("Restore"): the workspace. #doc("config") diff --git a/docs/typ/guide.typ b/docs/typ/guide.typ index 58e5d907..5dea0522 100644 --- a/docs/typ/guide.typ +++ b/docs/typ/guide.typ @@ -343,12 +343,18 @@ cheatsheet (#doc("cheatsheet")) say so. ``` pardes --detach=work & a session with no screen of its own pardes --attach=work show it here +pardes-gui --attach=work a window session's window again ``` -The session owns the panes, shells and files; frontends come and go, and -all of them see the same screen. #word("Attach") `work` (#key("SPC s a")) -switches this window to it; #word("Detach") (#key("SPC s D")) leaves it -running. +#word("Detach") (#key("SPC s D")) lets the terminal or the window go and +leaves the session running, its panes, shells and files kept; so does a +terminal that closes. `pardes --attach` takes it back in any terminal, +`pardes-gui --attach` a window session's window: a terminal session takes +a terminal, a window session a window. A session is named by `--9p=` or +`--detach=`, else its pid. A session killed outright leaves its shells +running; #word("Adopt") in another takes them in as terminal panes, what +they showed gone. One `pardes --daemon` per user keeps all of it, and +leaves once nothing is kept. = Config <config> diff --git a/src/9p_io.zig b/src/9p_io.zig index a089a7cf..2a0061fd 100644 --- a/src/9p_io.zig +++ b/src/9p_io.zig @@ -975,13 +975,14 @@ pub fn unlinkOwnSocket() void { _ = libc.unlink(own_socket[0..n :0]); } -/// SIGTERM and SIGHUP with no handler of their own (a GUI's): the socket -/// goes, then the signal's own death. A host that handles them itself (the -/// terminal's Killed, the detached server's quit) removes it its own way. +/// SIGTERM, SIGHUP and SIGINT with no handler of their own (a GUI's, a +/// detached session's): the socket goes, then the signal's own death. A +/// host that handles them itself (the terminal's Killed, SDL's quit) +/// removes it its own way. fn armSocketCleanup() void { const sig = std.posix.SIG; const on: std.posix.Sigaction = .{ .handler = .{ .handler = onFatalSignal }, .mask = std.posix.sigemptyset(), .flags = std.posix.SA.RESETHAND }; - for ([_]std.posix.SIG{ sig.TERM, sig.HUP }) |s| { + for ([_]std.posix.SIG{ sig.TERM, sig.HUP, sig.INT }) |s| { var was: std.posix.Sigaction = undefined; std.posix.sigaction(s, null, &was); if (was.handler.handler == sig.DFL) std.posix.sigaction(s, &on, null); @@ -995,6 +996,8 @@ pub var fatal_cleanup: ?*const fn () void = null; fn onFatalSignal(s: std.posix.SIG) callconv(.c) void { unlinkOwnSocket(); if (fatal_cleanup) |cleanup| cleanup(); + // Its shells go with it, the daemon's dups let go. + @import("daemon.zig").hangUp(); // SA_RESETHAND put the default back: the same signal, now fatal. _ = std.c.raise(s); } @@ -1204,6 +1207,17 @@ pub fn listen(io: std.Io, gpa: std.mem.Allocator, core: *pardes.Pardes, named: [ const alive = transport.isListening; +/// Whether a live session listens under `name` already: a second +/// `--detach=<name>` is refused before anything is made. +pub fn taken(name: []const u8) bool { + if (comptime !supported) return false; + var dir_buf: [sun_path_len:0]u8 = undefined; + const dir = socketDir(&dir_buf) orelse return false; + var buf: [sun_path_len]u8 = undefined; + const p = socketPath(&buf, dir, name) orelse return false; + return statNoFollow(p) != null and alive(p); +} + /// What is at a socket path, in cloud9's three answers (`post.Probe`). /// Asked here with libc rather than through `cloud9.post.probe`, whose /// raw Linux syscalls darwin cannot compile, but the classification is diff --git a/src/builtins.zig b/src/builtins.zig index 1f1e674e..3a66a316 100644 --- a/src/builtins.zig +++ b/src/builtins.zig @@ -737,51 +737,28 @@ pub const Restore = struct { } }; -/// Attach this terminal to a detached pardes session by name. -pub const Attach = struct { +/// Detach this pardes from its terminal or window, leaving the session +/// running: `pardes --attach` (or `pardes-gui --attach`) takes it back. +pub const Detach = struct { pub const scope: Scope = .session; - pub const takes_arg = true; pub const enabled = pardes.can_attach; pub fn run(c: Ctx) void { - if (comptime enabled) ask(c) else unreachable; - } - fn ask(c: Ctx) void { - const name = std.mem.trim(u8, c.arg orelse "", " \t\r\n"); - if (name.len > pardes.attach_name_max) - return c.p.reportError(c.id, comptime word(@This()), error.NameTooLong); - // A detached session has no terminal to move: bare, there is no - // "the one session there" but itself; a name is said for what it is. - if (c.p.opts.detached_session) { - if (name.len == 0) return c.p.reportFailure(c.id, "wrong #args in control message \"Attach\": a detached session names the session"); - // A session is its socket, `pardes-detached-<name>.sock` beside - // the 9P ones (detached/server.zig socketPath); not imported, as - // the core links no frontend's code. - const ninep_io = @import("9p_io.zig"); - var dir_buf: [ninep_io.sun_path_len:0]u8 = undefined; - var path_buf: [ninep_io.sun_path_len + 64:0]u8 = undefined; - const exists = if (ninep_io.socketDir(&dir_buf)) |dir| - (if (std.fmt.bufPrintSentinel(&path_buf, "{s}/pardes-detached-{s}.sock", .{ dir, name }, 0)) |path| ninep_io.statNoFollow(path) != null else |_| false) - else - false; - var said: [pardes.attach_name_max + 96]u8 = undefined; - return c.p.reportFailure(c.id, if (exists) - std.fmt.bufPrint(&said, "Attach: {s}: a detached session has no terminal to attach; Attach from a frontend", .{name}) catch "Attach: a detached session has no terminal to attach" - else - std.fmt.bufPrint(&said, "Attach: {s}: no such session", .{name}) catch "Attach: no such session"); - } - c.p.emit(.{ .attach = .{ .pane = @intCast(c.id), .name = .from(name) } }); + if (comptime enabled) + c.p.emit(.{ .detach = .{ .pane = @intCast(c.id) } }) + else + unreachable; } }; -/// Detach this pardes from its terminal, leaving the session running. -pub const Detach = struct { +/// Take in the shells of a session that died holding them, each as a +/// terminal pane here: the pardes daemon kept their terminals open. +pub const Adopt = struct { pub const scope: Scope = .session; pub const enabled = pardes.can_attach; pub fn run(c: Ctx) void { - if (comptime enabled) - c.p.emit(.{ .detach = .{ .pane = @intCast(c.id) } }) - else - unreachable; + if (comptime !enabled) unreachable; + const adopt = c.p.host.vtable.adopt orelse return c.p.reportFailure(c.id, "Adopt: no pardes daemon is keeping shells for this session"); + adopt(c.p.host.ctx, @intCast(c.id)); } }; diff --git a/src/config.zig b/src/config.zig index 988f634d..66b11c72 100644 --- a/src/config.zig +++ b/src/config.zig @@ -217,8 +217,8 @@ pub const leader_path = paths: { table.set(.Unmount, null); } if (pardes.can_attach) { - table.set(.Attach, "sa"); table.set(.Detach, "sD"); + table.set(.Adopt, null); } if (builtins.Peek.enabled) { table.set(.Peek, null); @@ -2306,6 +2306,8 @@ test "docs/typ names only words, keys and default tags that exist" { var dir = try std.Io.Dir.cwd().openDir(io, @import("doc_typ").dir, .{ .iterate = true }); defer dir.close(io); var found: [3]std.ArrayList([]const u8) = @splat(.empty); + // The arena's: gone with this test, so no later test reads it. + defer doc_typ.other_build = ""; for ([_][]const u8{ "builtins-tty.json", "builtins-gui.json" }) |f| { const text = dir.readFileAlloc(io, f, gpa, .limited(1 << 20)) catch continue; doc_typ.other_build = try std.mem.concat(gpa, u8, &.{ doc_typ.other_build, text }); diff --git a/src/file_watch.zig b/src/file_watch.zig index ab902e5b..e3fe9963 100644 --- a/src/file_watch.zig +++ b/src/file_watch.zig @@ -98,7 +98,7 @@ const wake_ident: usize = std.math.maxInt(usize); /// /// `polled` is the only flag that survives the port. On linux it adds /// IN_NONBLOCK, because a host that finds this descriptor ready in its own -/// `poll(2)` (detached/server.zig) must be able to stop draining it, while a +/// `poll(2)` must be able to stop draining it, while a /// host that parks a thread in `wait` (tty.zig, gui.zig) wants the blocking /// read. On macos neither host needs either flag: a kqueue is not inherited /// across `fork(2)`, so there is no CLOEXEC to ask for, and whether a wait diff --git a/src/gui/gui.zig b/src/gui/gui.zig index 01272b41..a1590b48 100644 --- a/src/gui/gui.zig +++ b/src/gui/gui.zig @@ -22,7 +22,7 @@ const c_heap = @import("c_heap"); const ninep_io = @import("../9p_io.zig"); -const detached_client = @import("../detached/client.zig"); +const daemon = @import("../daemon.zig"); const tracy = @import("../tracy.zig"); pub const c = @import("gui_c"); // SDL3 and font.h, translated by build.zig @@ -1434,8 +1434,6 @@ const Gui = struct { tagline_percent: u8, tagline_width: u32, tagline_height: u32, - attached_layers: ?*const [pardes.MAX_PANES]pardes.Layer = null, - attached_tag_layers: ?*const [pardes.MAX_TAG_LAYERS]pardes.Layer = null, cell_w: u32, cell_h: u32, ascent: i32, @@ -1533,6 +1531,14 @@ const Gui = struct { applied_window_opacity: u8 = 100, soft_renderer: ?*c.SDL_Renderer = null, soft_texture: ?*c.SDL_Texture = null, + /// What a window is opened again with (reopenWindow): the flags (not + /// hidden), the present mode, its size when it was closed. + win_flags: c.SDL_WindowFlags = 0, + present_mode: c.SDL_GPUPresentMode = c.SDL_GPU_PRESENTMODE_VSYNC, + window_w: c_int = 1120, + window_h: c_int = 720, + /// The window runNative destroys at the end: the one open then, if any. + window_slot: ?*?*c.SDL_Window = null, soft_tex_w: u32 = 0, soft_tex_h: u32 = 0, @@ -1895,16 +1901,10 @@ fn setTransitionFields( pub const run = runNative; -fn runNative(init: std.process.Init, opts_in: pardes.Options, attach: ?[]const u8) !void { +fn runNative(init: std.process.Init, opts_in: pardes.Options, headless: bool) !void { const gpa = init.gpa; const env = init.environ_map; - if (env.get("PARDES_TEST_GRID") != null) { - if (attach != null) { - log.err("--attach needs a window; PARDES_TEST_GRID is headless", .{}); - return error.AttachNeedsWindow; - } - return runGrid(init, opts_in); - } + if (env.get("PARDES_TEST_GRID") != null) return runGrid(init, opts_in); const test_mode = env.get("PARDES_TEST") != null; const capture_dir = env.get("PARDES_TEST_CAPTURE_DIR"); @@ -1950,6 +1950,9 @@ fn runNative(init: std.process.Init, opts_in: pardes.Options, attach: ?[]const u // opacity would dim the text as well. SDL requires this flag at creation. const surface_opacity = native_wayland; if (surface_opacity) win_flags |= c.SDL_WINDOW_TRANSPARENT; + const reopen_flags = win_flags; + // `--detach`: a window never shown, closed once the session is up. + if (headless) win_flags |= c.SDL_WINDOW_HIDDEN; // `--geometry=WxH[+X+Y]`, as X11 programs take it. var want_w: c_int = 1120; var want_h: c_int = 720; @@ -1969,7 +1972,8 @@ fn runNative(init: std.process.Init, opts_in: pardes.Options, attach: ?[]const u log.err("SDL_CreateWindow: {s}", .{c.SDL_GetError()}); return error.SdlInit; }; - defer c.SDL_DestroyWindow(window); + var window_slot: ?*c.SDL_Window = window; + defer if (window_slot) |open| c.SDL_DestroyWindow(open); if (want_at) |at| _ = c.SDL_SetWindowPosition(window, at[0], at[1]); updateDisplayScale(window); if (native_wayland) log.info("Wayland opacity: background-only transparent surface", .{}); @@ -2173,6 +2177,11 @@ fn runNative(init: std.process.Init, opts_in: pardes.Options, attach: ?[]const u .demo_next = if (env.get("PARDES_FRAMES_DEMO")) |name| (if (pardes.FrameStats.named(name) != null) @as(?usize, 0) else null) else null, .surface_opacity = surface_opacity, .soft_renderer = soft_renderer, + .win_flags = reopen_flags, + .present_mode = present_mode, + .window_w = want_w, + .window_h = want_h, + .window_slot = &window_slot, }; // The pipelines, textures and buffers the Gui holds, whatever they were // regrown to; the image ones are released below. @@ -2221,10 +2230,48 @@ fn runNative(init: std.process.Init, opts_in: pardes.Options, attach: ?[]const u // compositor moves it, as it does a title bar. if (!test_mode and !c.SDL_SetWindowHitTest(window, hitTest, &g)) log.warn("SDL_SetWindowHitTest: {s}", .{c.SDL_GetError()}); - if (attach) |requested| return attachRequested(gpa, &g, requested); - var attached: ?detached_client.Client = null; - try localSession(init, &g, opts_in, test_mode, &attached); - if (attached) |*client| return attachedLoop(gpa, &g, client); + try localSession(init, &g, opts_in, test_mode, headless); +} + +/// Detach: the window closed (and with it its swapchain or renderer); the +/// device, the atlas and the pipelines stay for the next one. +fn closeWindow(g: *Gui) void { + _ = c.SDL_GetWindowSize(g.window, &g.window_w, &g.window_h); + _ = c.SDL_StopTextInput(g.window); + if (g.soft_renderer) |renderer| { + if (g.soft_texture) |texture| c.SDL_DestroyTexture(texture); + g.soft_texture = null; + g.soft_tex_w = 0; + g.soft_tex_h = 0; + c.SDL_DestroyRenderer(renderer); + g.soft_renderer = null; + } else c.SDL_ReleaseWindowFromGPUDevice(g.device, g.window); + c.SDL_DestroyWindow(g.window); + if (g.window_slot) |slot| slot.* = null; +} + +/// `pardes-gui --attach`: a window again, as the first was made, at the +/// size the last one had. False when the display will not give one. +fn reopenWindow(g: *Gui) bool { + const window = c.SDL_CreateWindow("pardes", g.window_w, g.window_h, g.win_flags) orelse return false; + if (g.soft_present) { + g.soft_renderer = c.SDL_CreateRenderer(window, null) orelse { + c.SDL_DestroyWindow(window); + return false; + }; + } else { + if (!c.SDL_ClaimWindowForGPUDevice(g.device, window)) { + c.SDL_DestroyWindow(window); + return false; + } + _ = c.SDL_SetGPUSwapchainParameters(g.device, window, c.SDL_GPU_SWAPCHAINCOMPOSITION_SDR, g.present_mode); + } + g.window = window; + if (g.window_slot) |slot| slot.* = window; + updateDisplayScale(window); + if (!g.capture) _ = c.SDL_SetWindowHitTest(window, hitTest, g); + _ = c.SDL_StartTextInput(window); + return true; } fn localSession( @@ -2232,7 +2279,7 @@ fn localSession( g: *Gui, opts_in: pardes.Options, test_mode: bool, - attached: *?detached_client.Client, + headless: bool, ) !void { const io = init.io; const gpa = init.gpa; @@ -2359,25 +2406,19 @@ fn localSession( defer pardes.lsp.setStatusSink(null, null); host_io.setExitWake(&queue, Queue.wakeForExit); defer host_io.setExitWake(null, null); + if (headless) { + shell.closeTheWindow(); + // Nothing else may wake the first wait. + daemon.watch(&queue, deliverNote); + } while (!core.quit) { pardes.turn.bump(&pardes.turn.restores); try core.pump(host); + // A window asked for again, or an adopted shell, from the daemon's + // thread through the queue; started after the first frame. + daemon.watch(&queue, deliverNote); if (core.quit) break; // a session that ended does not restore into one - if (core.takeAttach()) |req| { - const geom = windowCells(g); - const outcome = detached_client.attempt(gpa, req.name, geom.cols, geom.rows); - switch (outcome) { - .greeted => |client| { - attached.* = client; - break; - }, - else => { - var mbuf: [256]u8 = undefined; - core.setMessage(req.pane, attachFailure(&mbuf, outcome, req.name)); - }, - } - } if (core.takeRestore()) |rp| blk: { const bytes = filesystem.readRestore(gpa, rp, core.settings.dump_dir.get()) catch |err| { core.reportError(core.active, "Restore", err); @@ -2426,198 +2467,6 @@ fn localSession( } } -fn attachFailure(buf: []u8, outcome: detached_client.Attempt, requested: []const u8) []const u8 { - return switch (outcome) { - .greeted => unreachable, - .no_session => if (requested.len != 0) - std.fmt.bufPrint(buf, "Attach: no detached session called '{s}'", .{requested}) catch - "Attach: no detached session under that name" - else - "Attach: nothing is detached (start one with `pardes --detach`)", - .ambiguous => |n| std.fmt.bufPrint(buf, "Attach: {d} detached sessions; say which one", .{n}) catch - "Attach: several detached sessions; say which one", - .refused => |why| switch (why) { - .version => "Attach: that session speaks a different wire version — it is another build of pardes", - .full => "Attach: that session already has every frontend slot taken", - .quitting => "Attach: that session is ending", - }, - .silent => "Attach: that session took the connection and never greeted us", - .lost => |err| std.fmt.bufPrint(buf, "Attach: lost the connection ({t})", .{err}) catch - "Attach: lost the connection", - }; -} - -fn attachRequested(gpa: std.mem.Allocator, g: *Gui, requested: []const u8) !void { - const geom = windowCells(g); - const outcome = detached_client.attempt(gpa, requested, geom.cols, geom.rows); - switch (outcome) { - .greeted => |greeted| { - var client = greeted; - return attachedLoop(gpa, g, &client); - }, - else => { - var mbuf: [256]u8 = undefined; - log.err("{s}", .{attachFailure(&mbuf, outcome, requested)}); - return switch (outcome) { - .no_session => error.NoSession, - .ambiguous => error.AmbiguousSession, - .refused => error.Refused, - .silent => error.NoGreeting, - .lost => |err| err, - .greeted => unreachable, - }; - }, - } -} - -fn attachedResize(client: *detached_client.Client, g: *const Gui, cols: u16, rows: u16) !void { - try client.send(.{ .event = .{ .resize = .{ .cols = cols, .rows = rows, .row_metrics = .{ - .body_w = @intCast(g.cell_w), - .body_h = @intCast(g.cell_h), - .tagline_w = @intCast(g.tagline_width), - .tagline_h = @intCast(g.tagline_height), - } } } }); -} - -fn attachedLoop(gpa: std.mem.Allocator, g: *Gui, client: *detached_client.Client) !void { - defer client.detach(); - _ = c.SDL_StartTextInput(g.window); - - var in: Input = .{ .client = client }; - g.attached_layers = &client.body_layers; - g.attached_tag_layers = &client.tag_layers; - var dirty = false; - var geom = windowCells(g); - try attachedResize(client, g, geom.cols, geom.rows); - while (true) { - const link = client.wait(detached_client.poll_ms); - while (true) { - const msg = (try client.next()) orelse break; - switch (msg) { - .welcome => {}, - .refuse => |why| { - log.err("session refused an already-greeted frontend: {t}", .{why}); - return error.Refused; - }, - .frame => dirty = true, - .quit => return, - .detach => return, - .set_clipboard => |text| putClipboard(gpa, text), - .read_clipboard => if (takeClipboard()) |text| { - defer c.SDL_free(text.ptr); - in.post(.{ .paste = text }); - }, - .open_link => |url| look.openLink(url), - .post => dirty = true, - } - } - try link; - - var sev = std.mem.zeroes(c.SDL_Event); - while (c.SDL_PollEvent(&sev)) dispatch(g, &in, &sev); - pollGamepad(g, &in); - if (in.lost) |err| return err; - if (in.quit) return; - - const now = windowCells(g); - if (now.cols != geom.cols or now.rows != geom.rows) { - geom = now; - try attachedResize(client, g, now.cols, now.rows); - } - // The session's chain, its files compiled there. - g.post.sync(gpa, g.device, g.swapchain_format, client.post.list(), client.post_key, null); - if (!dirty) { - // As a local window does: a chain that moves on its own redraws - // alone, once a refresh. - if (g.post.animating(client.post.animation) and g.scene_tex != null and - c.SDL_GetTicksNS() -| g.post.last_ns + std.time.ns_per_ms >= refreshNs(g)) redrawPost(g, gpa); - continue; - } - dirty = false; - paintAttached(g, gpa, client); - } -} - -fn paintAttached(g: *Gui, gpa: std.mem.Allocator, client: *detached_client.Client) void { - var surface = attachedSurface(client); - _ = renderFrame( - g, - gpa, - null, - &surface, - false, - ) catch |err| blk: { - log.err("render: {t}", .{err}); - break :blk false; - }; -} - -/// The session's frame as a surface: its cells, layers, regions and palette, -/// so its chrome is drawn from them as a local one's is. -fn attachedSurface(client: *const detached_client.Client) pardes.Surface { - var surface: pardes.Surface = .{ - .cols = client.cols, - .rows = client.rows, - .cells = client.grid.items, - .cursor = if (client.cursor) |cu| .{ .x = cu.x, .y = cu.y, .bar = cu.bar } else null, - .pointer_shape = client.pointer_shape, - .body_layers = client.body_layers, - .tag_layers = client.tag_layers, - .chrome = client.chrome, - }; - const placed = client.regions.items[0..@min(client.regions.items.len, surface.regions.len)]; - @memcpy(surface.regions[0..placed.len], placed); - surface.nregions = @intCast(placed.len); - return surface; -} - -test "an attached frontend draws the session's chrome from its frame alone" { - const gpa = std.testing.allocator; - const core = try pardes.Pardes.init(gpa, .{ .cols = 80, .rows = 24 }); - defer core.deinit(); - // A gui-shaped core, whose tags and notices are layers. - core.update(.{ .resize = .{ .cols = 80, .rows = 24, .row_metrics = .{ .body_w = 10, .body_h = 20, .tagline_w = 6, .tagline_h = 12 } } }); - _ = try core.newShell(1, ""); - try std.testing.expect(pardes.layout.splitColumn(core, 0, 1, false)); - core.settings.focus_tint = true; - try std.testing.expect(core.executeBuiltinLine(0, "Msg a notice with a rule under it")); - core.sync(); - // Past its slide into place, where its rule shows. - for (0..30) |_| core.update(.tick); - const s = try core.render(core.scratch.allocator()); - - const wire = @import("../detached/wire.zig"); - var client: detached_client.Client = .{ .gpa = gpa }; - defer client.deinit(); - var welcome: [64]u8 = undefined; - try client.in.appendSlice(gpa, try wire.encodeServer(&welcome, .{ .welcome = .{ .slot = 0, .cols = s.cols, .rows = s.rows } })); - const out = try gpa.alloc(u8, wire.frameBound(s.cols, s.rows) + wire.layersBound(&s.body_layers, &s.tag_layers, s.regionList())); - defer gpa.free(out); - try client.in.appendSlice(gpa, try wire.encodeFrameLayers(out, s.cols, s.rows, null, s.pointer_shape, s.cells, &.{}, &s.body_layers, &s.tag_layers, s.regionList(), s.chrome)); - _ = try client.next(); - _ = try client.next(); - const attached = attachedSurface(&client); - - var g: Gui = undefined; - g.cell_w = 10; - g.cell_h = 20; - g.tagline_width = 6; - g.tagline_height = 12; - g.decor = .empty; - g.glide = .{}; - g.scroll_pane = null; - g.scroll_lag = 0; - defer g.decor.deinit(gpa); - var groups = makeGroups(&.{}, false); - try buildDecor(&g, gpa, s, &groups, fixedCellLayout(&g), 800, 480, true); - const local = try gpa.dupe(CellInstance, g.decor.items); - defer gpa.free(local); - try std.testing.expect(local.len > 8); - try std.testing.expect(groups.items[groups.notices].decor_count != 0); - try buildDecor(&g, gpa, &attached, &groups, fixedCellLayout(&g), 800, 480, true); - try std.testing.expectEqualSlices(u8, std.mem.sliceAsBytes(local), std.mem.sliceAsBytes(g.decor.items)); -} - fn runGrid(init: std.process.Init, opts_in: pardes.Options) !void { const io = init.io; const gpa = init.gpa; @@ -2691,6 +2540,7 @@ fn runGrid(init: std.process.Init, opts_in: pardes.Options) !void { .inotify_fd = -1, .watches = &watches, .fs = fs, + .grid = true, }; defer shell.shutdownPtys(); const host = shell.host(); @@ -3125,18 +2975,10 @@ test "the window's function and editing keys reach a terminal as its cursor keys const Input = struct { core: ?*pardes.Pardes = null, - client: ?*detached_client.Client = null, quit: bool = false, - lost: ?anyerror = null, fn post(in: *Input, ev: pardes.Event) void { if (in.core) |core| return core.update(ev); - const client = in.client orelse return; - if (in.lost != null) return; - client.send(.{ .event = ev }) catch |err| switch (err) { - error.Overlong, error.WriteFailed => {}, - else => in.lost = err, - }; } fn close(in: *Input) void { @@ -3526,18 +3368,6 @@ fn gridCellAtPixels(g: *const Gui, core: ?*const pardes.Pardes, x: f32, y: f32) break; } }; - if (core == null) if (g.attached_layers) |layers| for (layers) |*layer| { - if (layer.bodyHit(x, y, @floatFromInt(g.cell_w), @floatFromInt(g.cell_h), @floatFromInt(g.tagline_width), @floatFromInt(g.tagline_height))) |body_hit| { - point.body_hit = body_hit; - break; - } - }; - if (core == null) if (g.attached_tag_layers) |layers| for (layers) |*layer| { - if (layer.tagHit(x, y, @floatFromInt(g.cell_w), @floatFromInt(g.cell_h), @floatFromInt(g.tagline_width), @floatFromInt(g.tagline_height))) |hit| { - point.tag_hit = hit; - break; - } - }; return point; } @@ -3805,7 +3635,17 @@ fn pollGamepad(g: *Gui, in: *Input) void { const Shell = struct { core: *pardes.Pardes, + /// The window's, while one is open; null while detached (`parked` has + /// it) and in the headless test grid. gui: ?*Gui = null, + parked: ?*Gui = null, + /// The headless test grid (runGrid): its own loop, no window ever. + grid: bool = false, + /// 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, io: std.Io, gpa: std.mem.Allocator, fs: ?*ninep_io.Listener = null, @@ -3863,6 +3703,7 @@ const Shell = struct { } _ = libc.close(pt.fd); pt.fd = -1; + daemon.closed(pt.pid); const now = std.Io.Clock.awake.now(s.queue.io).toMilliseconds(); host_io.reapRetired(&pt.pid, &pt.kill_at, now); if (pt.pid == 0) { @@ -3917,7 +3758,83 @@ const Shell = struct { } fn host(s: *Shell) pardes.Host { - return .{ .ctx = s, .vtable = if (s.gui == null) &grid_vtable else &vtable }; + return .{ .ctx = s, .vtable = if (s.grid) &grid_vtable else &vtable }; + } + + /// Detach: the window closed, the session left running with no + /// window, for `pardes-gui --attach` to open one again. + fn detachWindow(ctx: ?*anyopaque) void { + const s = shellOf(ctx); + if (s.gui == null) return s.core.reportFailure(s.core.active, "Detach: no window is open"); + if (!daemon.kept()) return s.core.reportFailure(s.core.active, "Detach: no pardes daemon keeps this session; closing its window ends it"); + s.closeTheWindow(); + } + + fn closeTheWindow(s: *Shell) void { + const g = s.gui orelse return; + closeWindow(g); + s.parked = g; + s.gui = null; + s.presented = false; + s.surface = null; + s.core.unattended = true; + daemon.setState(true); + } + + fn openTheWindow(s: *Shell) void { + const g = s.parked orelse return; + if (!reopenWindow(g)) { + log.err("--attach: no window: {s}", .{c.SDL_GetError()}); + return daemon.setState(true); + } + s.gui = g; + s.parked = null; + s.core.unattended = false; + s.core.needs_frame = true; + resetScroll(g); + daemon.setState(false); + } + + fn watched(ctx: ?*anyopaque) bool { + return shellOf(ctx).gui != null; + } + + fn adopt(ctx: ?*anyopaque, pane: u8) void { + const s = shellOf(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): + /// a terminal pane made for it, as the Tty word makes one, whose spawn + /// takes this pty (spawnPane). + fn adoptShell(s: *Shell, pid: libc.pid_t, fd: c_int) 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) { + 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; + } + _ = 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"); } const vtable: pardes.Host.VTable = .{ @@ -3926,6 +3843,9 @@ const Shell = struct { .present = present, .post_present = postPresent, .poll_frame = pollFrame, + .watched = watched, + .detach = detachWindow, + .adopt = adopt, .spawn = spawnPane, .pty_write = ptyWrite, .pty_resize = ptyResize, @@ -3957,6 +3877,9 @@ const Shell = struct { v.post_present = gridPostPresent; v.set_clipboard = null; v.read_clipboard = null; + v.watched = null; + v.detach = null; + v.adopt = null; break :vt v; }; @@ -4051,6 +3974,14 @@ const Shell = struct { }, .files_changed => check_files = true, .fs_ready => {}, + .window => { + s.openTheWindow(); + s.saw_event = true; + }, + .adopted => |a| { + s.adoptShell(a.pid, a.fd); + s.saw_event = true; + }, }; if (check_files) s.shaders.recheck(); if (check_files and file_watch.reloadChanged(s.core, s.io, s.gpa, s.watches)) @@ -4214,7 +4145,7 @@ fn waitInput(ctx: ?*anyopaque, timeout_ms: u32) void { } s.paced_ns = if (paced) tick else null; if (paced) g.pace_ns = tick; - } + } else waitDetached(core, timeout_ms); if (s.test_mode) { const r = s.feed.pump(s.gpa, &in, s.gui) catch { core.quit = true; @@ -4229,6 +4160,26 @@ fn waitInput(ctx: ?*anyopaque, timeout_ms: u32) void { if (s.gui) |g| pollGamepad(g, &in); } +/// Detached: no window, asleep until the queue's wake (an SDL user event: +/// a pty's output, the daemon's window request), the core's next wake, or a +/// quit (SDL makes SIGTERM and SIGINT one). With nobody to dismiss them, +/// messages go on the clock. +fn waitDetached(core: *pardes.Pardes, timeout_ms: u32) void { + pardes.Messages.expireUnattended(core); + var ms: c_int = if (timeout_ms != 0) @intCast(@min(timeout_ms, std.math.maxInt(c_int))) else -1; + for (core.panes) |slot| if (slot) |pane| if (pane.msg_len > 0) { + ms = if (ms < 0) 100 else @min(ms, 100); + break; + }; + var sev = std.mem.zeroes(c.SDL_Event); + pardes.turn.rest(); + var got = c.SDL_WaitEventTimeout(&sev, ms); + pardes.turn.wake(); + while (got) : (got = c.SDL_PollEvent(&sev)) { + if (sev.type == c.SDL_EVENT_QUIT) core.quit = true; + } +} + fn pollFrame(ctx: ?*anyopaque) void { const s = shellOf(ctx); s.reconcilePtys(); @@ -4545,6 +4496,11 @@ fn gridPostPresent(ctx: ?*anyopaque) void { fn spawnPane(ctx: ?*anyopaque, pane: u8, cwd: []const u8) void { const s = shellOf(ctx); s.reap(); + 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 takeShell(s, 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; @@ -4571,6 +4527,46 @@ fn spawnPane(ctx: ?*anyopaque, pane: u8, cwd: []const u8) void { }; } +const Adoption = struct { pid: libc.pid_t, fd: c_int, pane: ?u8 }; + +/// An adopted shell, running already, as pane `pane`'s: told the size twice +/// (one it never had, then the pane's), which makes it redraw. +fn takeShell(s: *Shell, pane: u8, a: Adoption) void { + s.closePty(pane); + s.gens[pane] +%= 1; + s.ptys[pane] = .{ .fd = a.fd, .pid = a.pid, .serial = s.core.panes[pane].?.serial, .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) return; + s.ptys[pane].?.reader = s.queue.startReader(.{ .handle = a.fd, .flags = .{ .nonblocking = false } }, pane, s.gens[pane]) catch |err| { + s.closePty(pane); + return s.core.reportError(pane, "terminal reader", err); + }; +} + +/// The daemon's thread: what it says, onto the queue (drainQueue). +fn deliverNote(ctx: *anyopaque, note: daemon.Note) void { + const q: *Queue = @ptrCast(@alignCast(ctx)); + switch (note) { + .attach => |a| { + // A terminal for a window session: the daemon refuses that kind + // before it is sent, so only an old one's would be here. + if (a.tty >= 0) _ = libc.close(a.tty); + if (a.stub >= 0) daemon.refuseStub(a.stub, "a window session takes no terminal"); + if (a.tty < 0) q.push(.window); + }, + .adopted => |a| { + for (a.pids[0..a.n], a.fds[0..a.n]) |pid, fd| q.push(.{ .adopted = .{ .pid = pid, .fd = fd } }); + q.push(.{ .adopted = .{ .pid = 0, .fd = -1 } }); + }, + } +} + fn ptyWrite(ctx: ?*anyopaque, pane: u8, bytes: []const u8) void { const s = shellOf(ctx); if (s.ptys[pane]) |pt| if (pt.fd >= 0) { @@ -4704,6 +4700,7 @@ test "the headless grid host round-trips a yank back as a paste" { .pipe_tasks = &pipe_tasks, .inotify_fd = -1, .watches = &watches, + .grid = true, }; core.host = shell.host(); try std.testing.expect(core.host.vtable == &Shell.grid_vtable); diff --git a/src/host_io.zig b/src/host_io.zig index af284e84..96c790d7 100644 --- a/src/host_io.zig +++ b/src/host_io.zig @@ -24,7 +24,11 @@ pub const Host = struct { /// client attached draws none (a /screen read draws its own), and /// the frame owed is drawn when one attaches. Absent: always. watched: ?*const fn (ctx: ?*anyopaque) bool = null, + /// Detach: the terminal or window let go, the session left running + /// for the daemon to attach again (daemon.zig). detach: ?*const fn (ctx: ?*anyopaque) void = null, + /// Adopt: the shells a dead session left, asked of the daemon. + adopt: ?*const fn (ctx: ?*anyopaque, pane: u8) void = null, spawn: ?*const fn (ctx: ?*anyopaque, pane: u8, cwd: []const u8) void = null, pty_write: ?*const fn (ctx: ?*anyopaque, pane: u8, bytes: []const u8) void = null, pty_resize: ?*const fn (ctx: ?*anyopaque, pane: u8, cols: u16, rows: u16) void = null, @@ -143,6 +147,11 @@ pub const Inbox = struct { handed: struct { seq: u32, ok: bool, words: []u8 }, files_changed, fs_ready, + /// The daemon asks for the window again (`pardes-gui --attach`). + window, + /// A shell a dead session left, its pty's master (Adopt); pid 0 is + /// the last of them told. + adopted: struct { pid: libc.pid_t, fd: c_int }, pub fn deinit(m: Msg, gpa: std.mem.Allocator, lsp_allocator: std.mem.Allocator) void { switch (m) { @@ -155,7 +164,10 @@ pub const Inbox = struct { }, .search => |b| b.deinit(gpa), .handed => |h| gpa.free(h.words), - .eof, .files_changed, .fs_ready => {}, + .adopted => |a| if (a.fd >= 0) { + _ = libc.close(a.fd); + }, + .eof, .files_changed, .fs_ready, .window => {}, } } }; @@ -2097,6 +2109,9 @@ pub fn forkShell( }; } ninep_io.setCloexec(master); + // The daemon keeps a dup: this session killed outright never hangs the + // shell up (daemon.zig). + @import("daemon.zig").pty(pid, master); if (core) |c| c.acknowledgeShell(pane, std.mem.span(spawn.path), one_line == null and spawn.argv[1] != null); return .{ .file = .{ .handle = master, .flags = .{ .nonblocking = false } }, .pid = pid }; } @@ -2208,6 +2223,26 @@ const proc_vnodepathinfo = extern struct { const PROC_PIDVNODEPATHINFO: c_int = 9; extern "c" fn proc_pidinfo(pid: c_int, flavor: c_int, arg: u64, buffer: *anyopaque, buffersize: c_int) c_int; +/// Whether an adopted shell marks its prompts: one pardes started with its +/// prompt files (bash, zsh, fish), which a pane's runs wait on. +pub fn marksPrompts(pid: libc.pid_t) bool { + var buf: [pardes.memory.limits.host_path_cap + 1]u8 = undefined; + const exe = std.fs.path.basename(processExe(pid, &buf) orelse return false); + for ([_][]const u8{ "bash", "zsh", "fish" }) |shell| if (std.mem.eql(u8, exe, shell)) return true; + return false; +} + +/// The program `pid` runs, where the system says (an adopted shell's, for +/// its pane's Tty word); null elsewhere. +pub fn processExe(pid: libc.pid_t, buf: []u8) ?[]const u8 { + if (comptime builtin.os.tag != .linux) return null; + var pbuf: [64]u8 = undefined; + const path = std.fmt.bufPrintSentinel(&pbuf, "/proc/{d}/exe", .{pid}, 0) catch return null; + const n = libc.readlink(path, buf.ptr, buf.len); + if (n <= 0 or n >= buf.len) return null; + return buf[0..@intCast(n)]; +} + pub fn shellCwd(pid: libc.pid_t, buf: []u8) ?[]const u8 { switch (builtin.os.tag) { .linux => { diff --git a/src/macos.zig b/src/macos.zig index 8d372432..e07955a1 100644 --- a/src/macos.zig +++ b/src/macos.zig @@ -1105,7 +1105,8 @@ fn drainInbox(st: *State) bool { .search => |b| st.core.update(.{ .search = b }), // The SDL shell's: this one's file watches and 9P are its own. // ponytail: no hand_over host entry on macOS yet, so none comes. - .files_changed, .fs_ready, .handed => {}, + // No daemon on macOS (daemon.supported): neither ever comes. + .files_changed, .fs_ready, .handed, .window, .adopted => {}, } } for (0..pardes.MAX_PANES) |pane| { diff --git a/src/main.zig b/src/main.zig index 4e6b49bb..803ff4da 100644 --- a/src/main.zig +++ b/src/main.zig @@ -2,6 +2,7 @@ const std = @import("std"); const builtin = @import("builtin"); const pardes = @import("pardes.zig"); const ninep_io = @import("9p_io.zig"); +const daemon = @import("daemon.zig"); const is_emscripten = builtin.os.tag == .emscripten; @@ -84,22 +85,20 @@ const help_text = \\ --9p-quic=<dial> also serve at quic!<numeric-ip>!<port> (-Dquic=true). \\ --mount=<name>=<dial> mount a 9P session or Unix/TCP/QUIC endpoint under /n/<name>. \\ Repeat for more mounts; os and self are reserved. - \\ --detach run this session with NO terminal of its own, - \\ serving frontends over a unix socket beside its - \\ 9P socket. The core, the panes and the - \\ undo history outlive every frontend that attaches - \\ --detach=<name> ...named <name> rather than this process's pid, so - \\ a frontend can say which session it wants. One - \\ path component: no '/' and nothing empty - \\ --attach become a frontend of the one detached session - \\ that is running: draw its screen and send it - \\ input, and nothing else — the session owns its - \\ pane shells, its files and its watches. Works in - \\ both the terminal and the SDL window build. - \\ Several frontends may be attached at once and all - \\ see the same screen - \\ --attach=<name> ...of the session called <name>, which is what to - \\ use when more than one is running + \\ --detach run this session with no terminal (no window) + \\ until one attaches; its panes, shells and files + \\ stay. Detach, or a terminal that closes, leaves + \\ any session so. One `pardes --daemon` per user + \\ keeps them (PARDES_DAEMON=off: none) + \\ --detach=<name> ...named <name> rather than this process's pid, + \\ as --9p names it. One path component: no '/' + \\ and nothing empty + \\ --attach show the one detached session here: this + \\ terminal for `pardes`, a window again for + \\ `pardes-gui`, each of its own kind. Returns when + \\ the session detaches or ends + \\ --attach=<name> ...the session called <name> (its --9p or + \\ --detach name, else its pid) \\ --geometry=WxH[+X+Y] the window's size in points, and where it goes \\ where the display lets a window say (X11) \\ -h, --help show this help and exit @@ -316,7 +315,7 @@ fn emscriptenMain(argc: c_int, argv: [*]?[*:0]u8) callconv(.c) c_int { // no argv in the browser: options stay default, state comes from the dump, and // there is no session to attach to — a browser tab has no unix socket. fn webMain() !void { - try @import("gui/gui.zig").run(.{}, .{}, null); + try @import("gui/gui.zig").run(.{}, .{}, false); } // init.gpa, what the tty, gui and detached shells allocate from, is their @@ -335,6 +334,8 @@ fn nativeMain(std_init: std.process.Init) !void { var mounts_len: usize = 0; const arena = init.arena.allocator(); const args = try init.minimal.args.toSlice(arena); + // The per-user daemon a session started (daemon.zig): nothing else. + if (comptime daemon.supported) if (args.len == 2 and std.mem.eql(u8, args[1], "--daemon")) daemon.serve(); var session_only = true; var new_session = false; var explicit_tty = false; @@ -713,30 +714,57 @@ fn nativeMain(std_init: std.process.Init) !void { opts.config_dir = found.dir; opts.store_path = storePath(init.io, arena, init.environ_map); if (found.dir) |d| @import("crash.zig").setDir(d); + if (attach) |name| attachTo(init.io, name); if (detach) |name| { - const named = if (name.len != 0) - name - else - try std.fmt.allocPrint(arena, "{d}", .{@as(u32, @intCast(std.c.getpid()))}); - // Said plainly, never a Zig error trace: a name another session's + // Said plainly, never a Zig error trace: a name a live session's // socket holds already (a plain session is named by its pid too). - return @import("detached/server.zig").run(init, opts, named) catch |err| { - var words: [128]u8 = undefined; + if (name.len != 0 and ninep_io.taken(name)) { var said: [512]u8 = undefined; - const why = if (err == error.ListenFailed) - "its socket is taken: another session (a plain one is named by its pid) holds that name; choose another" - else - pardes.Messages.errorWords(err, &words); - std.Io.File.stderr().writeStreamingAll(init.io, std.fmt.bufPrint(&said, "pardes: --detach={s}: {s}\n", .{ named, why }) catch "pardes: --detach failed\n") catch {}; + std.Io.File.stderr().writeStreamingAll(init.io, std.fmt.bufPrint(&said, "pardes: a session named {s} is already running\n", .{name}) catch "pardes: a session of that name is already running\n") catch {}; std.process.exit(1); - }; + } + if (opts.ninep_name.len == 0) opts.ninep_name = name; + // Nobody's size yet: one roomy enough for a script's panes; `size` + // sets another, and an attached terminal or window its own. + opts.cols = 160; + opts.rows = 50; } - if (attach != null and pardes.platform != .tty and pardes.platform != .gui) { - try std.Io.File.stderr().writeStreamingAll(init.io, "pardes: --attach needs the tty or gui shell\n"); - std.process.exit(1); + const kind: daemon.Kind = if (pardes.platform == .gui) .gui else .tty; + var term: @import("tty/tty.zig").Term = if (detach != null) .none else .open; + if (daemon.wanted()) { + if (detach != null or pardes.platform == .gui) { + _ = daemon.register(null, kind, opts.ninep_name, detach != null); + } else if (pardes.platform == .tty) fork: { + // A terminal's session is forked off its stub, which stays the + // job the shell waits on: Detach (or the terminal's end) ends + // the job and leaves the session running (daemon.forkSession). + // The daemon is reached or started first, from this small + // process, and the terminal opened while it is this one's. + const conn = daemon.connect(true) orelse break :fork; + const fd = std.c.open("/dev/tty", .{ .ACCMODE = .RDWR, .CLOEXEC = true, .NOCTTY = true }, @as(std.c.mode_t, 0)); + if (fd < 0) { + daemon.startPending(true); + _ = std.c.close(conn); + break :fork; + } + // Started in the background, the job stops here until it is + // brought to the foreground, as one making its terminal raw does. + // std.posix's termios, not std.c's: glibc's is the bigger struct. + if (std.posix.tcgetattr(fd)) |tio| std.posix.tcsetattr(fd, .NOW, tio) catch {} else |_| {} + daemon.forkSession(conn) orelse { + daemon.startPending(true); + _ = std.c.close(fd); + _ = std.c.close(conn); + break :fork; + }; + _ = daemon.register(conn, .tty, opts.ninep_name, false); + term = .{ .fd = fd }; + } } + defer daemon.quit(); + errdefer daemon.tellStubExit(1); switch (pardes.platform) { - .tty => @import("tty/tty.zig").run(init, opts, attach) catch |err| switch (err) { + .tty => @import("tty/tty.zig").run(init, opts, term) catch |err| switch (err) { // No controlling terminal (a detached pty, a daemon): said, not // an error trace. error.NoDevice => { @@ -745,9 +773,45 @@ fn nativeMain(std_init: std.process.Init) !void { }, else => return err, }, - .gui => try @import("gui/gui.zig").run(init, opts, attach), + .gui => try @import("gui/gui.zig").run(init, opts, detach != null), .web, .macos, .esp32p4 => unreachable, } + daemon.tellStubExit(0); +} + +/// `pardes --attach[=name]` in a terminal: this terminal handed (through +/// the daemon) to the detached session of that name, or the only one, and +/// this process its stub until the session leaves it. `pardes-gui +/// --attach`: the session asked to open its window again, and done. +fn attachTo(io: std.Io, name: []const u8) noreturn { + var words: [600]u8 = undefined; + const Say = struct { + fn no(o: std.Io, why: []const u8) noreturn { + var buf: [700]u8 = undefined; + std.Io.File.stderr().writeStreamingAll(o, std.fmt.bufPrint(&buf, "pardes: --attach: {s}\n", .{why}) catch "pardes: --attach failed\n") catch {}; + std.process.exit(1); + } + }; + if (comptime !daemon.supported) Say.no(io, "this system has no pardes daemon to attach through"); + if (pardes.platform == .gui) switch (daemon.attach(.gui, name, &.{}, &words)) { + .ok => std.process.exit(0), + .no => |why| Say.no(io, why), + }; + const fd = std.c.open("/dev/tty", .{ .ACCMODE = .RDWR, .CLOEXEC = true, .NOCTTY = true }, @as(std.c.mode_t, 0)); + if (fd < 0) Say.no(io, "no terminal to attach: /dev/tty will not open"); + if (std.posix.tcgetattr(fd)) |tio| std.posix.tcsetattr(fd, .NOW, tio) catch {} else |_| {} + var pipe: [2]std.c.fd_t = undefined; + if (std.c.pipe(&pipe) != 0) Say.no(io, "no pipe for the session to say when it leaves"); + ninep_io.setCloexec(pipe[0]); + ninep_io.setCloexec(pipe[1]); + switch (daemon.attach(.tty, name, &.{ fd, pipe[1] }, &words)) { + .ok => |pid| { + _ = std.c.close(fd); + _ = std.c.close(pipe[1]); + daemon.stubWait(pid, false, pipe[0]); + }, + .no => |why| Say.no(io, why), + } } fn parseCtrlKey(raw: []const u8) ?u21 { @@ -774,8 +838,7 @@ test { _ = @import("detached/wire.zig"); _ = @import("ShaderBuild.zig"); _ = @import("vaxis_input.zig"); - _ = @import("detached/server.zig"); - _ = @import("detached/client.zig"); + _ = @import("daemon.zig"); _ = @import("9p_io.zig"); _ = @import("9p_io.zig").Client; _ = @import("host_io.zig"); diff --git a/src/pardes.zig b/src/pardes.zig index c7ae6704..2bee1f98 100644 --- a/src/pardes.zig +++ b/src/pardes.zig @@ -538,53 +538,8 @@ fn drainForSavePath(p: *Pardes, buf: []u8) ?[]const u8 { return if (len) |n| buf[0..n] else null; } -fn drainForAttach(p: *Pardes) ?AttachRequest { - while (p.nextEffect()) |effect| p.perform(effect); - return p.takeAttach(); -} - -test "Attach asks for a session and tears nothing down" { - if (comptime !can_attach) return; - const gpa = std.testing.allocator; - const p = try Pardes.init(gpa, .{ .tty_only = true }); - defer p.deinit(); - while (p.nextEffect()) |_| {} - - // Bare means whichever session is there, and that is an EMPTY name rather - // than an absent request: the frontend still has to go and look. - try std.testing.expect(p.executeBuiltinLine(0, "Attach")); - const bare = drainForAttach(p) orelse return error.NoAttachAsked; - try std.testing.expectEqualStrings("", bare.name); - try std.testing.expectEqual(@as(u8, 0), bare.pane); - - // ...and the named form carries its tail, the way `Theme <name>` does. - try std.testing.expect(p.executeBuiltinLine(0, "Attach work")); - const named = drainForAttach(p) orelse return error.NoAttachAsked; - try std.testing.expectEqualStrings("work", named.name); - try std.testing.expect(p.takeAttach() == null); // taken once, then gone - - // The word only ASKS. A core that tore itself down here could not be handed - // back intact when the connect fails, and that is the entire guarantee. - try std.testing.expect(!p.quit); - try std.testing.expect(p.panes[0] != null); -} - -test "Attach in a detached session: bare is wrong #args, a name no session has says so, and nothing is asked" { - if (comptime !can_attach) return; - const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .detached_session = true }); - defer p.deinit(); - while (p.nextEffect()) |_| {} - const pane = p.panes[0].?; - try std.testing.expect(p.executeBuiltinLine(0, "Attach")); - try std.testing.expect(drainForAttach(p) == null); - try std.testing.expectStringStartsWith(pane.msg[0..pane.msg_len], "wrong #args"); - try std.testing.expect(p.executeBuiltinLine(0, "Attach zz-no-such-session-qq")); - try std.testing.expect(drainForAttach(p) == null); - try std.testing.expectEqualStrings("Attach: zz-no-such-session-qq: no such session", pane.msg[0..pane.msg_len]); -} - -test "Detach asks the frontend to leave, and says so when there is nothing to leave" { - if (comptime !can_attach) return; // compiled out where nothing polls `takeAttach` — see `can_attach` +test "Detach asks the host to let its terminal go, and says so when there is nothing to leave" { + if (comptime !can_attach) return; // the word is compiled out elsewhere: see `can_attach` const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .tty_only = true }); defer p.deinit(); @@ -3753,10 +3708,6 @@ pub const Event = union(enum) { tick, }; -pub const attach_name_max = 256; - -pub const AttachRequest = struct { pane: u8, name: []const u8 }; - pub const PendingWrite = struct { bytes: []u8, off: usize = 0 }; /// `command` is Kill's: SIGTERM to the terminal's foreground job, and never @@ -3807,7 +3758,6 @@ pub const Effect = union(enum) { /// Write the build-time theme ring below the per-user config directory. /// The pane receives the completion/error message from the native host. dump_themes: struct { pane: u8 }, - attach: struct { pane: u8, name: Buf(attach_name_max) }, detach: struct { pane: u8 }, quit, @@ -4387,9 +4337,6 @@ pub const Options = struct { /// window opens one as big as that, Handover.zig). geometry: ?[]const u8 = null, nested: bool = false, - /// The core of a `--detach` session (detached/server.zig): it has no - /// terminal of its own, so Attach there is refused with why. - detached_session: bool = false, startup_config: ?[]const u8 = null, ninep_name: []const u8 = "", ninep_tcp: ?[]const u8 = null, @@ -4738,8 +4685,6 @@ pub const Pardes = struct { /// shell consumes it via takeRestore each frame (restore contents stay host-fed) restore_req: ?[]const u8 = null, restore_buf: [1024]u8 = undefined, - attach_req: ?AttachRequest = null, - attach_buf: [attach_name_max]u8 = undefined, surface: Surface = .{}, /// per-update scratch (paneCursorLines, selection text); reset each update @@ -5088,14 +5033,6 @@ pub const Pardes = struct { return r; } - /// the shell polls this each frame beside takeRestore: a pending Attach's - /// session and reporting pane, or null - pub fn takeAttach(p: *Pardes) ?AttachRequest { - const a = p.attach_req; - p.attach_req = null; - return a; - } - /// The workspace tag's height: one row while the setting keeps it, as /// acme's row tag is, zero once a native shell takes its commands over. /// Layout and hit testing read this rather than the constant, the way @@ -5981,11 +5918,6 @@ pub const Pardes = struct { }, .theme_file => |t| if (v.watch_theme) |f| f(p.host.ctx, t.generation, t.on), .dump_themes => |d| if (v.dump_themes) |f| f(p.host.ctx, d.pane), - .attach => |a| { - const name = a.name.slice(); - @memcpy(p.attach_buf[0..name.len], name); - p.attach_req = .{ .pane = a.pane, .name = p.attach_buf[0..name.len] }; - }, .detach => |d| if (v.detach) |f| f(p.host.ctx) else 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 }); diff --git a/src/tutor.txt b/src/tutor.txt index 3f153ebd..5cfb245b 100644 --- a/src/tutor.txt +++ b/src/tutor.txt @@ -144,7 +144,7 @@ run at start. 2. In a shell, pardes --detach=work starts a session with no screen; pardes --attach=work shows it; `Detach` (SPC s D) leaves it - running. + running, as a terminal that closes does. -> Guide: Sessions, Config @@ -292,7 +292,7 @@ typed SPC y yank to the clipboard SPC p paste from it SPC w window mode: h/j/k/l, Enter; d Del, c Collapse SPC j j `Last` SPC j o / SPC j i back / forward - SPC s a `Attach` SPC s D `Detach` + SPC s D `Detach` SPC t ... the toggles SPC l ... the language SPC h t this tutor diff --git a/test/daemon.py b/test/daemon.py new file mode 100644 index 00000000..bf3d237c --- /dev/null +++ b/test/daemon.py @@ -0,0 +1,322 @@ +#!/usr/bin/env python3 +"""The per-user daemon end to end (docs/next-daemon.md, phase 3), under a +private HOME and runtime directory: + +- a terminal's session detached (the stub ends, exit 0) and attached again + from another terminal, N times; +- a session killed outright: its shells live on, held by the daemon, and + another session adopts them as terminal panes; +- nothing left behind: no session, shell, daemon or socket. + + python3 -B test/daemon.py <pardes> [cycles] + python3 -B test/daemon.py --gui <pardes-gui> [cycles] (a hidden window; + needs a Wayland display, and a pardes beside it for the refusal) +""" +import fcntl +import os +import shutil +import signal +import struct +import subprocess +import sys +import tempfile +import termios +import threading +import time +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).parent)) +from ninep import Client # noqa: E402 + + +def wait_for(what, check, timeout=10): + deadline = time.monotonic() + timeout + while True: + got = check() + if got: + return got + if time.monotonic() > deadline: + raise TimeoutError(what) + time.sleep(.01) + + +class Term: + """A terminal: a pty whose other end is read and kept, its frame + requests answered (CSI 5 n), as a terminal emulator does.""" + + def __init__(self, rows=24, cols=80): + self.master, self.slave = os.openpty() + fcntl.ioctl(self.slave, termios.TIOCSWINSZ, struct.pack('HHHH', rows, cols, 0, 0)) + self.out = bytearray() + self.lock = threading.Lock() + self.reader = threading.Thread(target=self.drain, daemon=True) + self.reader.start() + + def drain(self): + while True: + try: + got = os.read(self.master, 65536) + except OSError: + return + if not got: + return + with self.lock: + self.out += got + if b'\x1b[5n' in got: + try: + os.write(self.master, b'\x1b[0n') + except OSError: + return + + def spawn(self, argv, env): + slave = self.slave + return subprocess.Popen(argv, env=env, stdin=slave, stdout=slave, stderr=slave, + start_new_session=True, + preexec_fn=lambda: fcntl.ioctl(0, termios.TIOCSCTTY, 0)) + + def text(self): + with self.lock: + return bytes(self.out) + + def close(self): + os.close(self.slave) + os.close(self.master) + self.reader.join(timeout=2) + + +def run(client, serial, line): + """pty/run: a line in, `exit N` and its output out.""" + fid = client.open(f'/pane/{serial}/pty/run', 2) + try: + client.rpc(118, struct.pack('<IQI', fid, 0, len(line)) + line) + return client.read_fid(fid) + finally: + client.close(fid) + + +def processes(root): + """The pids whose environment is this run's (its runtime directory).""" + found = [] + mark = f'XDG_RUNTIME_DIR={root}'.encode() + for entry in os.listdir('/proc'): + if not entry.isdigit(): + continue + try: + environ = open(f'/proc/{entry}/environ', 'rb').read().split(b'\0') + except OSError: + continue + if mark in environ: + found.append(int(entry)) + return found + + +def cmdline(pid): + try: + return open(f'/proc/{pid}/cmdline', 'rb').read().split(b'\0') + except OSError: + return [] + + +def alive(pid): + try: + os.kill(pid, 0) + except ProcessLookupError: + return False + try: + state = open(f'/proc/{pid}/stat').read().rsplit(')', 1)[1].split()[0] + except OSError: + return False + return state != 'Z' + + +def fds(pid): + try: + return len(os.listdir(f'/proc/{pid}/fd')) + except OSError: + return -1 + + +def terminals(client): + return [int(row.split()[0]) for row in client.read('/index').splitlines() if row.split()[1] == b'term'] + + +def main(binary, cycles): + scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn' + scratch.mkdir(parents=True, exist_ok=True) + root = Path(tempfile.mkdtemp(prefix='rt-', dir=scratch)) + env = {k: v for k, v in os.environ.items() if not k.startswith('PARDES_') and 'PAGER' not in k} + env.update(HOME=str(root), XDG_RUNTIME_DIR=str(root), XDG_CONFIG_HOME=str(root / 'config'), + TERM='xterm-256color', SHELL='/bin/bash', PARDES_NOTIME='1') + (root / 'config' / 'pardes').mkdir(parents=True) + (root / 'config' / 'pardes' / 'init').write_text('Shell bash\nMessageLinger 0\n') + daemon_sock = root / 'pardes-daemon.sock' + started = [] + try: + term = Term() + stub = term.spawn([binary, '--tty', '--9p=work'], env) + started.append(stub.pid) + sock = root / 'pardes-9p-work.sock' + wait_for('the session\'s 9P socket', sock.exists) + client = Client(sock) + status = dict(line.split(maxsplit=1) for line in client.read('/status').decode().splitlines()) + session = int(status['pid']) + started.append(session) + assert session != stub.pid, 'the session is forked off its stub' + assert daemon_sock.exists(), list(root.iterdir()) + daemons = [p for p in processes(root) if cmdline(p)[1:2] == [b'--daemon']] + assert len(daemons) == 1, [cmdline(p) for p in processes(root)] + daemon = daemons[0] + started.append(daemon) + shell = terminals(client)[0] + shell_pid = int(run(client, shell, b'echo $$\n').split(b'\n')[1]) + started.append(shell_pid) + baseline = None + for cycle in range(cycles): + client.write(f'/pane/{shell}/exec', b'Detach\n') + assert stub.wait(timeout=10) == 0, stub.returncode + said = term.text() + assert b'detached from \'work\'' in said, said[-400:] + assert b'\x1b[?1049l' in said, 'the terminal is put back' + term.close() + assert alive(session) and alive(shell_pid) + assert run(client, shell, b'echo still\n').startswith(b'exit 0\nstill'), 'the shell runs on, detached' + term = Term(30, 100) + stub = term.spawn([binary, '--attach=work'], env) + wait_for('the attached terminal\'s first frame', lambda: b'\x1b[?1049h' in term.text()) + wait_for('the session sized to its new terminal', + lambda: client.screen()['cols'] == 100 and client.screen()['rows'] == 30) + now = (fds(session), fds(daemon), len(list(root.iterdir())), len(processes(root))) + if baseline is None: + baseline = now + assert now == baseline, (cycle, now, baseline) + print(f'daemon: {cycles} detach/attach cycles, fds/sockets/processes level: {baseline}') + + # Killed outright: its shells live on, their masters the daemon's. + os.kill(session, signal.SIGKILL) + stub.wait(timeout=10) + client.socket.close() + term.close() + wait_for('the killed session gone', lambda: not alive(session)) + time.sleep(.3) + assert alive(shell_pid), 'a killed session\'s shell is not hung up' + assert alive(daemon) + term = Term() + stub = term.spawn([binary, '--tty', '--9p=fresh'], env) + started.append(stub.pid) + sock = root / 'pardes-9p-fresh.sock' + wait_for('the second session', sock.exists) + client = Client(sock) + status = dict(line.split(maxsplit=1) for line in client.read('/status').decode().splitlines()) + session = int(status['pid']) + started.append(session) + before = set(terminals(client)) + client.write(f'/pane/{min(before)}/exec', b'Adopt\n') + adopted = wait_for('the adopted pane', lambda: set(terminals(client)) - before) + pane = adopted.pop() + said = run(client, pane, b'echo $$\n') + assert said.split(b'\n')[1] == str(shell_pid).encode(), said + print(f'daemon: shell {shell_pid} outlived kill -9 of its session and was adopted') + + # The end: the session quits, its shells hang up, the daemon goes. + client.write(f'/pane/{pane}/exec', b'Exit\n') + stub.wait(timeout=10) + client.socket.close() + term.close() + wait_for('the adopted shell hung up', lambda: not alive(shell_pid)) + wait_for('the daemon gone once idle', lambda: not alive(daemon), timeout=5) + left = [p for p in processes(root) if alive(p)] + assert not left, [cmdline(p) for p in left] + sockets = [p.name for p in root.iterdir() if p.is_socket()] + assert not sockets, sockets + print('daemon: nothing left behind') + finally: + for pid in started + processes(root): + try: + os.kill(pid, signal.SIGKILL) + except OSError: + pass + shutil.rmtree(root, ignore_errors=True) + + +def sized(client): + """Whether the session takes a `size`: only with no window or terminal.""" + try: + client.write('/ctl', b'size 100 30\n') + return True + except OSError: + return False + + +def gui(binary, cycles): + """A window's Detach closes it and keeps the process; `pardes-gui + --attach` opens it again. Test mode: a hidden window, its stdin the + test feed.""" + scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn' + root = Path(tempfile.mkdtemp(prefix='rtg-', dir=scratch)) + env = {k: v for k, v in os.environ.items() if not k.startswith('PARDES_') and 'PAGER' not in k} + display = Path(os.environ.get('WAYLAND_DISPLAY', 'wayland-0')) + if not display.is_absolute(): + display = Path(os.environ.get('XDG_RUNTIME_DIR', f'/run/user/{os.getuid()}')) / display + (root / 'caps').mkdir() + env.update(HOME=str(root), XDG_RUNTIME_DIR=str(root), XDG_CONFIG_HOME=str(root / 'config'), + SHELL='/bin/bash', PARDES_NOTIME='1', PARDES_TEST='1', PARDES_TEST_CAPTURE_DIR=str(root / 'caps'), + SDL_VIDEODRIVER='wayland', WAYLAND_DISPLAY=str(display), PARDES_DAEMON='on') + (root / 'config' / 'pardes').mkdir(parents=True) + (root / 'config' / 'pardes' / 'init').write_text('Shell bash\nMessageLinger 0\n') + feed_r, feed_w = os.pipe() + proc = subprocess.Popen([binary, '--9p=win'], env=env, cwd=root, stdin=feed_r, + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True) + os.close(feed_r) + try: + sock = root / 'pardes-9p-win.sock' + wait_for('the window session', sock.exists, timeout=20) + client = Client(sock) + shell = terminals(client)[0] + assert not sized(client), 'a window owns the size' + baseline = None + for cycle in range(cycles): + client.write(f'/pane/{shell}/exec', b'Detach\n') + wait_for('the window closed', lambda: sized(client)) + assert proc.poll() is None, 'the process carries on with no window' + attach = subprocess.run([binary, '--attach=win'], env=env, cwd=root, timeout=10, + stdout=subprocess.PIPE, stderr=subprocess.PIPE) + assert attach.returncode == 0, attach.stderr + wait_for('the window open again', lambda: not sized(client)) + now = (fds(proc.pid), len(processes(root))) + baseline = baseline or now + assert now == baseline, (cycle, now, baseline) + print(f'daemon: {cycles} window detach/attach cycles, fds/processes level: {baseline}') + # Another kind is refused in words, and so is a name nobody has. + client.write(f'/pane/{shell}/exec', b'Detach\n') + wait_for('the window closed', lambda: sized(client)) + term = Term() + tty_attach = term.spawn([binary.replace('pardes-gui', 'pardes'), '--attach=win'], env) + assert tty_attach.wait(timeout=10) == 1 + said = term.text() + term.close() + assert b'is a window' in said, said + nobody = subprocess.run([binary, '--attach=nobody'], env=env, cwd=root, timeout=10, + stdout=subprocess.PIPE, stderr=subprocess.PIPE) + assert nobody.returncode == 1 and b"no session called 'nobody'" in nobody.stderr, nobody.stderr + # Detached and told to end: it ends. + client.write(f'/pane/{shell}/exec', b'Exit\n') + proc.wait(timeout=10) + client.socket.close() + wait_for('the daemon gone once idle', lambda: not [p for p in processes(root) if alive(p)], timeout=5) + print('daemon: window session ended, nothing left behind') + finally: + os.close(feed_w) + for pid in [proc.pid] + processes(root): + try: + os.kill(pid, signal.SIGKILL) + except OSError: + pass + shutil.rmtree(root, ignore_errors=True) + + +if __name__ == '__main__': + if '--gui' in sys.argv: + args = [a for a in sys.argv[1:] if a != '--gui'] + gui(args[0], int(args[1]) if len(args) > 1 else 50) + else: + main(sys.argv[1], int(sys.argv[2]) if len(sys.argv) > 2 else 50) diff --git a/test/e2e_harness.zig b/test/e2e_harness.zig index a2010c19..7e29476b 100644 --- a/test/e2e_harness.zig +++ b/test/e2e_harness.zig @@ -15,6 +15,7 @@ extern "c" fn forkpty( extern "c" fn execvp(file: [*:0]const u8, argv: [*:null]const ?[*:0]const u8) c_int; extern "c" fn _exit(status: c_int) noreturn; extern "c" fn unsetenv(name: [*:0]const u8) c_int; +extern "c" fn setenv(name: [*:0]const u8, value: [*:0]const u8, overwrite: c_int) c_int; /// Monotonic milliseconds; the harness's only clock (std.time lost /// milliTimestamp in 0.16). @@ -96,6 +97,9 @@ pub const Harness = struct { if (pid == 0) { for ([_][*:0]const u8{ "PARDES_PID", "PARDES_9P", "PARDES_PANE" }) |name| if (unsetenv(name) != 0) _exit(126); + // The app is the process this kills and the terminal it hangs + // up (deinit): no daemon to fork it off and keep it (daemon.zig). + if (setenv("PARDES_DAEMON", "off", 1) != 0) _exit(126); _ = execvp(exe, argv.ptr); _exit(127); } @@ -47,6 +47,7 @@ def session(binary, root, name, *options, socket_name=None, file=None, tty=False preexec = lambda: fcntl.ioctl(0, termios.TIOCSCTTY, 0) if launch is not None: args = [binary, *launch] + existing = set(root.glob('pardes-9p-*.sock')) child = subprocess.Popen(args, cwd=root, env=env, stdin=slave, stdout=slave if tty else subprocess.DEVNULL, stderr=subprocess.PIPE, start_new_session=True, @@ -55,7 +56,9 @@ def session(binary, root, name, *options, socket_name=None, file=None, tty=False # Borrowed handles for input-driving probes, valid inside this context. terminal.update(pid=child.pid, input_fd=master) if launch is not None and socket_name is None: - address = root / f'pardes-9p-{child.pid}.sock' + # Named by the session's pid: a terminal's session is forked + # off the process launched, which stays as its stub. + address = None if slave is not None: os.close(slave) slave = None @@ -68,7 +71,11 @@ def session(binary, root, name, *options, socket_name=None, file=None, tty=False reader = threading.Thread(target=drain, daemon=True) reader.start() deadline = time.monotonic() + 10 - while not address.exists(): + while address is None or not address.exists(): + if address is None: + address = next(iter(set(root.glob('pardes-9p-*.sock')) - existing), None) + if address is not None: + continue if child.poll() is not None: raise AssertionError((args, child.returncode, child.stderr.read().decode())) if time.monotonic() > deadline: @@ -984,19 +991,24 @@ def python_repl_runs_one_line(binary): def signal_cleans_up(binary): - """A detached session told to stop by a signal unlinks its sockets.""" + """A detached session told to stop by a signal unlinks its sockets. A + hangup is a terminal's end, not a session's: the daemon keeps it.""" for sig in [signal.SIGTERM, signal.SIGINT, signal.SIGHUP]: with tempfile.TemporaryDirectory(prefix='pardes-sig-') as directory: root = Path(directory) seen = {} with session(binary, root, 'sig', terminal=seen) as (client, address): - detached = root / 'pardes-detached-sig.sock' - assert address.exists() and detached.exists() + assert address.exists() + if sig == signal.SIGHUP: + os.kill(seen['pid'], sig) + time.sleep(.3) + assert address.exists() and client.read('/index'), 'a hangup ended a kept session' + sig = signal.SIGTERM os.kill(seen['pid'], sig) deadline = time.monotonic() + 5 - while (address.exists() or detached.exists()) and time.monotonic() < deadline: + while address.exists() and time.monotonic() < deadline: time.sleep(.01) - assert not address.exists() and not detached.exists(), (sig, list(root.iterdir())) + assert not address.exists(), (sig, list(root.iterdir())) def odd_paths(binary): @@ -1885,6 +1897,7 @@ def test(binary, quic=False): cooked = termios.tcgetattr(slave) env = {k: v for k, v in os.environ.items() if not k.startswith('PARDES_')} env.update(HOME=str(root), XDG_RUNTIME_DIR=str(root), TERM='xterm-256color', PARDES_NOTIME='1') + existing = set(root.glob('pardes-9p-*.sock')) killed = subprocess.Popen([binary, '--tty', 'x.txt'], cwd=root, env=env, stdin=slave, stdout=slave, stderr=subprocess.DEVNULL, start_new_session=True, @@ -1897,12 +1910,21 @@ def test(binary, quic=False): if select.select([master], [], [], .1)[0]: seen += os.read(master, 65536) time.sleep(.3) - own_socket = root / f'pardes-9p-{killed.pid}.sock' - assert own_socket.exists() + # The session's own, named by its pid: forked off the + # launched process, which stays as its stub. + own_socket, = set(root.glob('pardes-9p-*.sock')) - existing assert not dead_socket.exists() assert live_socket.exists() killed.send_signal(sig) assert killed.wait(timeout=5) == -sig + if sig == signal.SIGHUP: + # A hangup is the terminal's end: the session carries on + # detached (the daemon keeps it) until told to end. + assert own_socket.exists(), own_socket + os.kill(int(own_socket.name[len('pardes-9p-'):-len('.sock')]), signal.SIGTERM) + deadline = time.monotonic() + 5 + while own_socket.exists() and time.monotonic() < deadline: + time.sleep(.01) assert not own_socket.exists(), own_socket while select.select([master], [], [], .2)[0]: try: |
