diff options
Diffstat (limited to 'dev/tui')
| -rw-r--r-- | dev/tui/tui.zig | 587 |
1 files changed, 120 insertions, 467 deletions
diff --git a/dev/tui/tui.zig b/dev/tui/tui.zig index d7ea8ed6..543be3aa 100644 --- a/dev/tui/tui.zig +++ b/dev/tui/tui.zig @@ -104,9 +104,6 @@ const Msg = union(enum) { /// 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. @@ -116,8 +113,6 @@ const Msg = union(enum) { /// A SIGHUP: the session's own terminal hung up. hangup, key_press: vaxis.Key, - pty_read: struct { id: usize, gen: u32, bytes: []u8 }, - pty_eof: struct { id: usize, gen: u32 }, winsize: vaxis.Winsize, mouse: vaxis.Mouse, focus_in, @@ -125,14 +120,11 @@ const Msg = union(enum) { paste: []const u8, paste_start, paste_end, - lsp_done: struct { id: u32, rows: ?[]u8 }, - lsp_status: []u8, pipe_done: selection_pipe.Response, /// A streaming search's rows (pardes.Stream). search_rows: pardes.Stream.Batch, /// A kind's job done on a worker (host_io.KindJob). kind_job: *host_io.KindJob, - files_changed, fs_ready, /// A replica's connection, handed over by the daemon (Peers). replica: daemon.Joining, @@ -379,15 +371,6 @@ const TestReader = struct { const PipeTasks = selection_pipe.Tasks; -const Pty = struct { - file: std.Io.File, - pid: posix.pid_t, - reader: std.Io.Future(error{OutOfMemory}!void), - /// A command pane's child, watched to its exit (host_io.watchExit); - /// the pty stays open until both its end of file and its exit. - cmd: host_io.CommandWatch = .{}, -}; - /// A watched child exited: wake the loop, which takes it (`takeExits`). fn wakeForExit(ctx: ?*anyopaque) void { const loop: *Loop = @ptrCast(@alignCast(ctx.?)); @@ -584,7 +567,7 @@ fn surfaceHasKittyKey(surface: *const pardes.Surface, key: u64) bool { /// 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, detached until one is attached (`--detach`). +/// daemon.forkSession); or none, detached from the start (`--detach`). /// The terminal a session starts on: /dev/tty, one its stub opened (an /// upgraded session's is raw already, `termios` the cooked one), or none. pub const Term = union(enum) { open, fd: struct { fd: posix.fd_t, termios: ?posix.termios = null }, detached }; @@ -776,23 +759,28 @@ pub fn runClient(init: std.process.Init, opts: pardes.Options, path: []const u8, var tty: Tty = undefined; var c = try Client.init(&tty, &start); defer c.link.deinit(gpa); - // A client has no clients of its own. + // A client has no clients of its own, and spawns nothing: its pty + // table an empty one over an empty queue. var no_peers: replica.Peers = .{}; + var no_inbox: host_io.Inbox = .{ .io = io, .gpa = gpa, .lsp_allocator = start.allocs.lsp }; + defer no_inbox.deinit(); + var no_ptys: host_io.Ptys = .{ .queue = &no_inbox, .prompt_rcs = undefined }; + var no_watches: file_watch.Watches = .{ .io = io, .gpa = gpa, .queue = &no_inbox }; var sh: Shell = .{ .io = io, .gpa = gpa, .lsp_gpa = start.allocs.lsp, .core = start.r.core(), .frames = &start.frames, - .prompt_rcs = undefined, .loop = &loop, .frame = &frame_arena, .paste_buf = &paste_buf, - .inotify_fd = -1, + .watches = &no_watches, .own = start.joined.view, .screen = &screen, .client = &c, .peers = &no_peers, + .ptys = &no_ptys, }; tty = .{ .sh = &sh, .screen = &screen, .loop = &loop, .joins = &start }; @@ -818,9 +806,9 @@ pub fn runClient(init: std.process.Init, opts: pardes.Options, path: []const u8, /// A terminal a session draws on, while it has one: entered (raw, the /// alternate screen, mouse and paste reports) and left (all of it put back, -/// the terminal closed) at the session's start and end, and at a detach and -/// a reattach in between (daemon.zig), its stub `daemon.stub`. One a -/// process: a second terminal on a session is a replica client of it. +/// the terminal closed) at the session's start and end, or at a detach +/// (daemon.zig), its stub `daemon.stub`. One a process, the one the session +/// was born with: an attach is a replica client of it. const Screen = struct { io: std.Io, gpa: std.mem.Allocator, @@ -961,20 +949,21 @@ const Own = struct { .lsp_gpa = l.allocs.lsp, .core = l.core, .frames = &l.frames, - .prompt_rcs = &l.prompt_rcs, .loop = o.loop, .frame = &o.frame_arena, .paste_buf = o.paste_buf, - .inotify_fd = file_watch.init(false), + .watches = &l.watches, .fs = l.fs, .test_clock = host_io.testClock(), .peers = &l.peers, + .ptys = &l.ptys, }; const sh = &o.sh; sh.screen = o.screen; + l.inbox.wake_fn = Shell.wakeForQueue; + l.inbox.wake_ctx = sh; l.peers.wake_ctx = o.loop; l.peers.wake = wakeForReplica; - pardes.lsp.setStatusSink(sh, lspStatusSink); host_io.setExitWake(o.loop, wakeForExit); const host = sh.host(); l.core.host = host; @@ -996,48 +985,18 @@ const Own = struct { stopInput(io, &o.screen.thread); pardes.Kind.drawer = null; host_io.setExitWake(null, null); - pardes.lsp.setStatusSink(null, null); - for (&sh.ptys) |*slot| if (slot.*) |*pt| { - pt.reader.cancel(io) catch {}; - _ = libc.close(pt.file.handle); - slot.* = null; - }; - for (sh.adoptions.list[0..sh.adoptions.len]) |a| _ = libc.close(a.fd); - if (sh.lsp_task) |*t| { - t.future.cancel(io); - sh.lsp_task = null; - } sh.pipe_tasks.cancelAll(io); sh.job_tasks.cancelAll(io); // Its worker may be waiting on the loop's queue for room. sh.core.stream.cancelTask(); - file_watch.stop(sh.inotify_fd); - if (sh.watch_task) |*t| { - t.cancel(io); - sh.watch_task = null; - } - if (sh.inotify_fd >= 0) { - _ = libc.close(sh.inotify_fd); - sh.inotify_fd = -1; - } while (loop.tryEvent() catch null) |ev| switch (ev) { - .pty_read => |pr| { - tookRead(io, pr.id); - gpa.free(pr.bytes); - }, .paste => |b| gpa.free(@constCast(b)), - .lsp_done => |d| if (d.rows) |rows| sh.lsp_gpa.free(rows), - .lsp_status => |text| sh.lsp_gpa.free(text), .pipe_done => |response_value| { var response = response_value; response.deinit(gpa); }, .search_rows => |b| b.deinit(gpa), .kind_job => |j| j.drop(), - .attach => |a| { - _ = libc.close(a.tty); - if (a.stub >= 0) _ = libc.close(a.stub); - }, .adopted => |a| _ = libc.close(a.fd), else => {}, }; @@ -1046,10 +1005,6 @@ const Own = struct { o.frame_arena.deinit(); } - pub fn resumePtys(o: *Own, rec: *const upgrade.Record) void { - o.sh.resumePtys(rec); - } - pub fn start(o: *Own, l: *Session) !void { const io = l.io; const sh = &o.sh; @@ -1064,10 +1019,6 @@ const Own = struct { if (!screen.on) l.watch(); sh.threads_ok = true; - for (&sh.ptys, 0..) |*slot, id| if (slot.*) |*pt| { - pt.reader = try io.concurrent(readPty, .{ io, l.gpa, pt.file, id, sh.gens[id], loop }); - }; - if (sh.inotify_fd >= 0) sh.watch_task = io.concurrent(watchFiles, .{ io, sh.inotify_fd, loop }) catch null; } /// Detached, the unit is its clients' frame: its output is paced to it @@ -1086,20 +1037,10 @@ const Own = struct { deliverNote(o.loop, n); } - pub fn watched(o: *Own) session_loop.Watched { - return .{ .fd = o.sh.inotify_fd, .table = &o.sh.watches }; - } - pub fn restoring(o: *Own, nc: *pardes.Pardes) void { const sh = &o.sh; const io = sh.io; - if (sh.lsp_task) |*task| { - task.future.cancel(io); - sh.lsp_task = null; - } sh.pipe_tasks.cancelAll(io); - for (&sh.gens) |*generation| generation.* +%= 1; - for (0..pardes.MAX_PANES) |pane| Shell.closePty(sh, .at(pane)); // One view, the terminal's (host_io.restoreCore). const live = o.screen; stopInput(io, &live.thread); @@ -1132,12 +1073,8 @@ fn clearNativeImages( 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.tellStub(a.stub, "r{s}", .{"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); - }, + // A full queue wakes it anyway. + .relinked => _ = loop.tryPostEvent(.nop) catch false, .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); @@ -1167,7 +1104,6 @@ const Shell = struct { /// Its runner's frame timings (Pardes.frames): written as it draws and /// takes input, never through the core. frames: *pardes.FrameStats, - prompt_rcs: *const host_io.Shell.PromptFiles, loop: *Loop, /// The terminal (none in tests), and the view it shows: a second /// terminal on the session is a replica client (`pardes --attach`). @@ -1175,16 +1111,19 @@ const Shell = struct { own: u8 = 0, frame: *std.heap.ArenaAllocator, paste_buf: *std.Io.Writer.Allocating, - inotify_fd: c_int, - /// Shells a dead session left (Adopt), each waiting for the spawn of - /// the terminal pane made for it. - adoptions: host_io.Adoptions = .{}, + /// The session's file watches (runtime/session.zig's); a client's, + /// none. + watches: *file_watch.Watches, fs: ?*ninep_io.Listener = null, - ptys: [pardes.MAX_PANES]?Pty = @splat(null), - gens: [pardes.MAX_PANES]u32 = @splat(0), - watches: file_watch.Table = @splat(null), - watch_task: ?std.Io.Future(void) = null, - lsp_task: ?host_io.Lsp.Task = null, + /// The session's ptys (runtime/session.zig's); a client's, an empty + /// table over an empty queue. + ptys: *host_io.Ptys, + /// What `takeQueue` takes off the ptys' queue, and whether the loop + /// was woken for it since it last did (one wake, not one a read ahead + /// of the terminal's keys in the loop's queue). + batch: host_io.Inbox.Batch = .{}, + batch_at: usize = 0, + queue_woken: std.atomic.Value(bool) = .init(false), pipe_tasks: PipeTasks = .{}, job_tasks: PipeTasks = .{}, threads_ok: bool = false, @@ -1207,8 +1146,6 @@ const Shell = struct { focused_ns: u64 = 0, /// Upgrade was asked from this pane, to be done between steps (`upgradeNow`). upgrade_asked: ?u8 = null, - /// Its pty readers stopped for it: their end of file is not a shell's. - upgrading: bool = false, /// The session's replica clients (core/replica.zig), on sockets: the /// session loop's (runtime/session.zig); a client's, none. peers: *replica.Peers, @@ -1272,20 +1209,20 @@ const Shell = struct { .poll_frame = pollFrame, .watched = watched, .detach = detach, - .adopt = adopt, + .adopt = PtyCalls.adopt, .upgrade = upgradeAsked, - .spawn = spawn, - .pty_write = ptyWrite, - .pty_resize = ptyResize, - .pty_signal = ptySignal, - .close_pty = closePty, - .tty_taken = ttyTaken, - .fg_name = fgName, - .kill_job = killJob, - .write_file = writeFile, + .spawn = PtyCalls.spawn, + .pty_write = PtyCalls.write, + .pty_resize = PtyCalls.resize, + .pty_signal = PtyCalls.signal, + .close_pty = PtyCalls.close, + .tty_taken = PtyCalls.ttyTaken, + .fg_name = PtyCalls.fgName, + .kill_job = PtyCalls.killJob, + .write_file = WatchCalls.writeFile, .write_dump = writeDump, - .watch_file = watchFile, - .watch_theme = watchTheme, + .watch_file = WatchCalls.watchFile, + .watch_theme = WatchCalls.watchTheme, .dump_themes = dumpThemes, .set_clipboard = setClipboard, .read_clipboard = readClipboard, @@ -1347,49 +1284,11 @@ const Shell = struct { if (null_fd > 2) _ = libc.close(null_fd); } daemon.tellStubDetached(); - daemon.setState(true); - } - - /// `pardes --attach`'s terminal, for a detached session: its own again, - /// entered as the first one was, sized, asked what it can do, and drawn - /// whole. One attached already takes no other (the daemon makes a second - /// a replica client). - fn attachTerminal(s: *Shell, fd: posix.fd_t, stub: posix.fd_t, cooked: ?posix.termios) void { - const screen = s.screen orelse { - _ = libc.close(fd); - return refuse(stub, "that session has no terminal of its own to attach to"); - }; - if (screen.on) { - _ = libc.close(fd); - return refuse(stub, "that session has a terminal: join it as a client, `pardes --attach=<socket>:<name>`"); - } - const tty = Screen.ttyOn(s.io, screen.buf, fd, cooked) catch { - _ = libc.close(fd); - daemon.setState(true); - return refuse(stub, "that terminal would not go raw"); - }; - screen.enter(tty) catch { - daemon.setState(true); - return refuse(stub, "that terminal would not take the screen"); - }; - daemon.stub = stub; - s.setAttended(true); - startInput(s.loop, screen) catch {}; - screen.vx.queryTerminalSend(screen.tty.writer()) catch {}; - s.core.needs_frame = true; - daemon.setState(false); - } - - /// A terminal refused: its stub told why (a test's has none). - fn refuse(stub: posix.fd_t, why: []const u8) void { - if (stub >= 0) daemon.tellStub(stub, "r{s}", .{why}); + daemon.setDetached(); } - fn adopt(ctx: ?*anyopaque, id: pardes.Pane.Id) void { - const pane = id.index(); - const s = of(ctx); - s.adoptions.ask(s.core, pane); - } + const PtyCalls = host_io.Ptys.Calls(Shell); + const WatchCalls = file_watch.Watches.Calls(Shell); fn upgradeAsked(ctx: ?*anyopaque, id: pardes.Pane.Id) void { const pane = id.index(); @@ -1418,18 +1317,19 @@ const Shell = struct { .ok => {}, } // Nothing more read from a pty or a terminal, and what was read - // goes in; a reader's cancel posts an end of file, passed over. - s.upgrading = true; - defer s.upgrading = false; - for (&s.ptys) |*slot| if (slot.*) |*pt| pt.reader.cancel(s.io) catch {}; + // goes in: taken, the readers stopped (one waiting for room has it + // then), and what they posted meanwhile taken. + s.takeAll(); + s.ptys.pause(); if (s.screen) |sc| stopInput(s.io, &sc.thread); while (s.loop.tryEvent() catch null) |ev| _ = s.apply(ev); + s.takeAll(); core.settle(); // Its replica clients told, their views gone before the dump: each // dials the session again once it is back. s.peers.refuseAll(core, "the session is upgrading to another build of pardes"); var rec: upgrade.Record = .{ .link = daemon.link, .stub = daemon.stub, .exe = path }; - for (s.ptys, 0..) |slot, id| if (slot) |pt| rec.addPty(id, pt.pid, pt.file.handle); + s.ptys.record(&rec); if (s.screen) |sc| if (sc.on) rec.addTty(.{ .view = s.own, .fd = sc.tty.fd.handle, @@ -1453,9 +1353,7 @@ const Shell = struct { break :failed upgrade.execAs(s.gpa, path, &rec, &at_buf, s.fs, &why); }; // As it was: its ptys read on, its terminals' keys as they were. - for (&s.ptys, 0..) |*slot, id| if (slot.*) |*pt| { - pt.reader = s.io.concurrent(readPty, .{ s.io, s.gpa, pt.file, id, s.gens[id], s.loop }) catch pt.reader; - }; + s.ptys.readOn(core); if (s.screen) |sc| if (sc.on) { if (popped) sc.vx.enableDetectedFeatures(sc.tty.writer()) catch {}; startInput(s.loop, sc) catch {}; @@ -1463,20 +1361,6 @@ const Shell = struct { core.reportFailure(pane, failed); } - /// An upgraded session's shells, running on: each its pane's pty again, - /// or, when its dump would not load (`fresh`), adopted as new panes. - fn resumePtys(s: *Shell, rec: *const upgrade.Record) void { - for (rec.ptys[0..rec.nptys]) |k| { - const pane = if (rec.fresh) null else s.core.panes[k.pane]; - if (pane == null or !pane.?.isTerminal()) { - s.adoptions.adoptShell(s.core, k.pid, k.fd); - continue; - } - const file: std.Io.File = .{ .handle = k.fd, .flags = .{ .nonblocking = false } }; - s.ptys[k.pane] = .{ .file = file, .pid = k.pid, .reader = .{ .any_future = null, .result = {} }, .cmd = .{ .watched = pane.?.command != null and host_io.watchExit(k.pid), .fd = k.fd } }; - } - } - /// An upgraded session's terminal, its view's again (`primary`, run's, /// entered already); every other view but a replica client's, kept for /// its rejoin (views.away), closes. A terminal another build kept for a @@ -1614,9 +1498,16 @@ const Shell = struct { batch += 1; } if (motion) |m| _ = s.apply(m); + // The ptys' output, after the terminal's input of this wait (which + // is never queued behind it; with clients, an input after output + // is held for the next wait: `split`). + s.takeQueue(); // An exit's wake (a .nop) or output an exit waited behind: told - // here, inside the step, so the frame after it shows it. - s.takeExits(); + // here, inside the step, so the frame after it shows it; not while + // reads taken off the queue wait their steps (`takeQueue`): one of + // them may be the command's own last output, which its exit would + // be drawn above (CommandWatch.due cannot see it). + if (s.batch_at == s.batch.len) s.takeExits(); s.reloadWatched(); } @@ -1628,10 +1519,6 @@ const Shell = struct { fn split(s: *Shell, ev: Msg) bool { if (!s.peers.recording) return false; switch (ev) { - .pty_read => { - s.took_output = true; - return false; - }, .key_press => if (s.in_paste) return false, .mouse, .paste, .paste_end, .winsize, .focus_in, .focus_out => {}, else => return false, @@ -1701,8 +1588,7 @@ const Shell = struct { core.quit = true; return true; }, - .attach => |a| s.attachTerminal(a.tty, a.stub, null), - .adopted => |a| s.adoptions.adoptShell(s.core, a.pid, a.fd), + .adopted => |a| s.ptys.adoptions.adoptShell(s.core, a.pid, a.fd), .replica => |j| { s.peers.handed(j.fd, j.view); s.input_seen = true; @@ -1741,38 +1627,6 @@ const Shell = struct { s.feed(.{ .focus = false }); }, .winsize => |ws| if (!s.detached()) s.resized(s.screen, ws), - .pty_read => |pr| { - tookRead(s.io, pr.id); - s.output_seen = true; - if (pr.id == core.view().active) s.focused_ns = @intCast(std.Io.Clock.awake.now(s.io).nanoseconds); - if (s.gens[pr.id] == pr.gen) - core.update(.{ .output = .{ .pane = .at(pr.id), .bytes = pr.bytes } }); - s.gpa.free(pr.bytes); - // An exit waiting behind this output may be told now. - s.takeExits(); - return true; - }, - .pty_eof => |e| if (s.gens[e.id] == e.gen and !s.upgrading) { - if (s.ptys[e.id]) |*pt| { - pt.reader.await(s.io) catch {}; // reader just finished; join it or its future leaks - // A command's pty stays open until its child has exited: - // closing it would hang up one that runs on without it. - // Its exit, if it came first, is told now its output is in. - if (pt.cmd.watched) { - host_io.commandEof(core, &s.ptys, e.id, s, closeWatched); - return true; - } - _ = libc.close(pt.file.handle); - // Unwatched, a command's exit is read here, as its end, - // and a shell's, for a run waiting on it and the log. - const command = if (core.panes[e.id]) |pn| pn.command != null else false; - const status = host_io.exitStatus(pt.pid, 100); - if (status == null) host_io.retireShell(pt.pid); - s.ptys[e.id] = null; - if (command or status != null) core.update(.{ .exited = .{ .pane = .at(e.id), .status = status } }); - } - core.update(.{ .eof = .{ .pane = .at(e.id) } }); - }, .key_press => |key| if (s.in_paste) { const bytes = vaxis_input.pasteBytes(key); const room = max_paste_bytes -| s.paste_buf.written().len; @@ -1793,21 +1647,7 @@ const Shell = struct { if (pasted.len > 0) s.feed(.{ .paste = pasted }); s.paste_buf.clearRetainingCapacity(); }, - .files_changed => s.check_files = true, .fs_ready => {}, - .lsp_done => |d| { - core.update(.{ .lsp_resp = .{ .id = d.id, .rows = d.rows } }); - if (d.rows) |rows| s.lsp_gpa.free(rows); - if (s.lsp_task) |*t| if (t.id == d.id) { - t.future.await(s.io); - s.lsp_task = null; - }; - }, - .lsp_status => |text| { - var mbuf: [256]u8 = undefined; - core.setStatus(.at(core.view().active), message.stamp(&mbuf, "lsp", text)); - s.lsp_gpa.free(text); - }, .pipe_done => |response_value| { var response = response_value; core.update(.{ .pipe_resp = .{ @@ -1856,8 +1696,7 @@ const Shell = struct { fn reloadWatched(s: *Shell) void { if (!s.check_files) return; s.check_files = false; - if (file_watch.reloadChanged(s.core, s.io, s.gpa, &s.watches)) - s.loop.postEvent(.files_changed) catch {}; + s.watches.reload(s.core); } /// The tty's own motions (its glide, a jump's trail) are under way. @@ -1881,10 +1720,7 @@ const Shell = struct { if (s.fs) |f| if (f.tick().pending) { _ = s.loop.tryPostEvent(.fs_ready) catch {}; }; - for (&s.ptys, 0..) |*slot, id| if (slot.*) |pt| { - var lbuf: [pardes.memory.limits.host_path_cap + 1]u8 = undefined; - if (host_io.ttyCwd(pt.pid, pt.file.handle, s.core.settings.shell.effective.get(), &lbuf)) |cwd| s.core.setCwd(.at(id), cwd); - }; + s.ptys.pollCwds(s.core); const sc = s.term() orelse return; s.core.view().frontend.native_image_patches = sc.feed.shm.load(.acquire); @@ -2026,145 +1862,67 @@ const Shell = struct { tracy.frameMark(); } - fn spawn(ctx: ?*anyopaque, id: pardes.Pane.Id, cwd: []const u8) void { - const pane = id.index(); - const s = of(ctx); - if (s.adoptions.take(id)) |a| 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; - const child = host_io.forkShell(s.core, pane, s.prompt_rcs, s.core.shellBin(), cwd, s.core.view().screen_h, s.core.view().screen_w) catch |err| { - if (running) return s.core.restartFailed(id, err); - return s.core.shellFailed(id, err); - }; - closePty(ctx, id); // a shell still in the slot goes, reaped - s.gens[pane] +%= 1; - const command = if (s.core.panes[pane]) |pn| pn.command != null else false; - s.ptys[pane] = .{ .file = child.file, .pid = child.pid, .reader = .{ .any_future = null, .result = {} }, .cmd = .{ .watched = command and host_io.watchExit(child.pid), .fd = child.file.handle } }; - var lbuf: [pardes.memory.limits.host_path_cap + 1]u8 = undefined; - // Only a shell given no directory is asked where it is: one given a - // directory is named by it already (newShell), and asked now, before - // its chdir, it would answer this process's, a rename to undo. - if (cwd.len == 0) if (host_io.shellCwd(child.pid, &lbuf)) |wd| s.core.setCwd(id, wd); - 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; - } - } - } - - /// 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: host_io.Adoption) void { - closePty(s, .at(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(.at(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(.at(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, .at(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; - }; + /// The command panes' exits, told once their output is in (host_io). + fn takeExits(s: *Shell) void { + s.ptys.takeExits(s.core); } - fn ptyWrite(ctx: ?*anyopaque, id: pardes.Pane.Id, bytes: []const u8) void { - const pane = id.index(); + /// A post to the session's queue (Inbox.wake, any thread): the loop + /// woken, once until it takes them. + fn wakeForQueue(ctx: ?*anyopaque) void { const s = of(ctx); - if (s.ptys[pane]) |pt| _ = host_io.writeFd(pt.file.handle, bytes); + if (s.queue_woken.swap(true, .acq_rel)) return; + // A full queue is taken soon anyway, and the post with it. + if (!(s.loop.tryPostEvent(.nop) catch false)) s.queue_woken.store(false, .release); } - fn ptyResize(ctx: ?*anyopaque, id: pardes.Pane.Id, cols: u16, rows: u16) void { - const pane = id.index(); - const s = of(ctx); - if (s.ptys[pane]) |pt| { - const ws = host_io.ptyWinsize(s.core, cols, rows); - _ = posix.system.ioctl(pt.file.handle, TIOCSWINSZ, @intFromPtr(&ws)); + /// What the session's queue holds: its ptys' output (`waitInput` + /// paces it; the focused pane's is its echo) and their ends of file. + /// A read a step, as the terminal's own queue gave them: the frame + /// after one shows it before what came after it (a command's last line + /// before its exit scrolls it away), the rest kept for the next wait. + fn takeQueue(s: *Shell) void { + while (true) { + if (s.batch_at == s.batch.len) { + s.queue_woken.store(false, .release); + s.ptys.queue.takeInto(&s.batch); + s.batch_at = 0; + if (s.batch.len == 0) return; + } + const m = s.batch.items[s.batch_at]; + s.batch_at += 1; + switch (m) { + .output => |o| { + s.output_seen = true; + s.mail_only = false; + if (s.peers.recording) s.took_output = true; + if (o.pane.index() == s.core.view().active) s.focused_ns = @intCast(std.Io.Clock.awake.now(s.io).nanoseconds); + s.ptys.output(s.core, o); + // The next wait takes the rest (a wake its own: the + // one a post made may be taken already). + _ = s.loop.tryPostEvent(.nop) catch {}; + return; + }, + .eof => |e| s.ptys.eof(s.core, e), + .files_changed => s.check_files = true, + .lsp, .lsp_status => s.ptys.queue.landLsp(s.core, m), + else => m.deinit(s.gpa, s.lsp_gpa), + } } } - fn ptySignal(ctx: ?*anyopaque, id: pardes.Pane.Id, sig: pardes.PtySignal) void { - const pane = id.index(); - const s = of(ctx); - // A command whose exit is recorded is reaped: its group may be - // another's by now. - if (s.ptys[pane]) |pt| if (!pt.cmd.exited) host_io.signalTty(pt.pid, pt.file.handle, sig, pt.cmd.watched); - } - - /// The pane is gone: hang its pty up, which the kernel passes on to the - /// shell as SIGHUP, and retire the shell. Output still in flight - /// carries the old generation and is dropped. - fn closePty(ctx: ?*anyopaque, id: pardes.Pane.Id) void { - const pane = id.index(); - const s = of(ctx); - var pt = s.ptys[pane] orelse return; - s.ptys[pane] = null; - s.gens[pane] +%= 1; - pt.reader.cancel(s.io) catch {}; - _ = libc.close(pt.file.handle); - daemon.closed(pt.pid); - host_io.retireShell(pt.pid); - } - - fn ttyTaken(ctx: ?*anyopaque, id: pardes.Pane.Id) bool { - const pane = id.index(); - const s = of(ctx); - const pt = s.ptys[pane] orelse return false; - return host_io.ttyTaken(pt.pid, pt.file.handle); - } - - fn fgName(ctx: ?*anyopaque, id: pardes.Pane.Id, buf: []u8) ?[]const u8 { - const pane = id.index(); - const s = of(ctx); - const pt = s.ptys[pane] orelse return null; - return host_io.foregroundName(pt.pid, pt.file.handle, buf); - } - - /// The command panes' exits, told once their output is in (host_io). - fn takeExits(s: *@This()) void { - host_io.takeExits(s.core, &s.ptys, s, closeWatched); - } - - fn closeWatched(s: *@This(), id: usize) void { - const pt = &(s.ptys[id] orelse return); - _ = libc.close(pt.file.handle); - s.ptys[id] = null; - } - - fn killJob(ctx: ?*anyopaque, id: pardes.Pane.Id) bool { - const pane = id.index(); - const s = of(ctx); - const pt = s.ptys[pane] orelse return false; - return host_io.killJob(pt.pid, pt.file.handle); - } - - fn writeFile(ctx: ?*anyopaque, id: pardes.Pane.Id, path: []const u8, bytes: []const u8) void { - const pane = id.index(); - const s = of(ctx); - host_io.writeFile(s.core, &s.watches, pane, path, bytes); + /// Everything queued taken (an Upgrade's). + fn takeAll(s: *Shell) void { + while (true) { + s.takeQueue(); + if (s.batch.len == 0) return; + } } fn writeDump(ctx: ?*anyopaque, bytes: []const u8) void { host_io.writeDump(of(ctx).core, bytes); } - fn watchFile(ctx: ?*anyopaque, id: pardes.Pane.Id, _: []const u8, on: bool, mode: pardes.WatchMode) void { - const pane = id.index(); - const s = of(ctx); - if (file_watch.applyEffect(s.core, s.io, s.inotify_fd, &s.watches, pane, on, mode)) - s.loop.postEvent(.files_changed) catch {}; - } - - fn watchTheme(ctx: ?*anyopaque, generation: u32, on: bool) void { - const s = of(ctx); - if (file_watch.applyThemeEffect(s.core, s.gpa, s.inotify_fd, &s.watches, generation, on)) - s.loop.postEvent(.files_changed) catch {}; - } - fn dumpThemes(ctx: ?*anyopaque, id: pardes.Pane.Id) void { const pane = id.index(); const s = of(ctx); @@ -2192,16 +1950,9 @@ const Shell = struct { fn lsp(ctx: ?*anyopaque, req: host_io.Lsp.Request) void { const s = of(ctx); - if (!s.threads_ok) { - s.core.update(.{ .lsp_resp = .{ .id = req.id, .rows = null } }); - return s.core.reportError(req.pane, "lsp", error.WorkersUnavailable); - } - host_io.Lsp.start(s.io, s.lsp_gpa, s.core, &s.lsp_task, req, s, deliverLspRows); - } - - fn deliverLspRows(ctx: ?*anyopaque, id: u32, rows: ?[]u8) void { - const s = of(ctx); - s.loop.postEvent(.{ .lsp_done = .{ .id = id, .rows = rows } }) catch if (rows) |owned| s.lsp_gpa.free(owned); + if (s.threads_ok) return s.ptys.queue.startLsp(s.core, req); + s.core.update(.{ .lsp_resp = .{ .id = req.id, .rows = null } }); + s.core.reportError(req.pane, "lsp", error.WorkersUnavailable); } fn pipe(ctx: ?*anyopaque, id: u32) void { @@ -2257,29 +2008,6 @@ const Shell = struct { } }; -fn lspStatusSink(ctx: ?*anyopaque, text: []const u8) void { - const s: *Shell = @ptrCast(@alignCast(ctx orelse return)); - const copy = s.lsp_gpa.dupe(u8, text) catch return; - const posted = s.loop.tryPostEvent(.{ .lsp_status = copy }) catch false; - if (!posted) s.lsp_gpa.free(copy); -} - -fn watchFiles(io: std.Io, fd: c_int, loop: *Loop) void { - if (comptime builtin.os.tag != .linux and builtin.os.tag != .freebsd) { - while (file_watch.wait(fd)) loop.postEvent(.files_changed) catch break; - return; - } - const file: std.Io.File = .{ .handle = fd, .flags = .{ .nonblocking = false } }; - // One buffer, read into directly: a Reader around it only added a second - // (and in a safe build, filled both as `undefined` on every start). - var buf: [4096]u8 = undefined; - while (true) { - const n = file.readStreaming(io, &.{&buf}) catch break; - if (n == 0) break; - loop.postEvent(.files_changed) catch break; - } -} - fn keepSignal(_: posix.SIG) callconv(.c) void {} /// A replica client's (`runClient`): a hangup is its end, whoever sent it. @@ -2351,44 +2079,6 @@ fn wakeFs(ctx: ?*anyopaque) void { _ = loop.tryPostEvent(.fs_ready) catch {}; } -/// Each pane's reads posted and not yet taken in. Two at most: a flood the -/// loop cannot keep up with waits in its pty, not in the queue ahead of a -/// key and its echo (hundreds of 4 KB reads queued were half a second). -var reads_queued: [pardes.MAX_PANES]std.atomic.Value(u32) = @splat(.init(0)); - -/// A read of pane `id` taken in (or dropped): its reader may read on. Never -/// below zero, for an event no reader posted (a test's). -fn tookRead(io: std.Io, id: usize) void { - var queued = reads_queued[id].load(.acquire); - while (queued > 0) queued = reads_queued[id].cmpxchgWeak(queued, queued - 1, .acq_rel, .acquire) orelse { - if (queued == 2) io.futexWake(u32, &reads_queued[id].raw, 1); - return; - }; -} - -fn readPty(io: std.Io, gpa: std.mem.Allocator, pty: std.Io.File, id: usize, gen: u32, loop: *Loop) error{OutOfMemory}!void { - // One buffer, read into directly: a Reader around it only added a second - // (and in a safe build, filled both as `undefined` on every start). - var buf: [0x10000]u8 = undefined; - read: while (true) { - while (true) { - const queued = reads_queued[id].load(.acquire); - if (queued < 2) break; - io.futexWait(u32, &reads_queued[id].raw, queued) catch break :read; - } - const n = pty.readStreaming(io, &.{&buf}) catch break; - if (n == 0) break; - const bytes = try gpa.dupe(u8, buf[0..n]); - _ = reads_queued[id].fetchAdd(1, .acq_rel); - loop.postEvent(.{ .pty_read = .{ .id = id, .gen = gen, .bytes = bytes } }) catch { - tookRead(io, id); - gpa.free(bytes); - break; - }; - } - _ = loop.tryPostEvent(.{ .pty_eof = .{ .id = id, .gen = gen } }) catch {}; -} - const max_paste_bytes: usize = pardes.memory.limits.max_paste_bytes; fn mouseEvent(m: vaxis.Mouse) ?pardes.Event { @@ -2995,46 +2685,6 @@ test "on a terminal with no kitty graphics a program's 64x64 image over 8x4 cell try std.testing.expectEqual(@as(usize, 32), painted); } -test "TTY queued results reject old PTY generations and LSP request IDs" { - const gpa = std.testing.allocator; - const core = try pardes.Pardes.init(gpa, .{ .tty_only = true, .cols = 40, .rows = 12 }); - defer core.deinit(); - var no_peers: replica.Peers = .{}; - var shell: Shell = .{ - .io = std.testing.io, - .gpa = gpa, - .lsp_gpa = gpa, - .core = core, - .frames = core.frames, - .prompt_rcs = undefined, - .loop = undefined, - .frame = undefined, - .paste_buf = undefined, - .inotify_fd = -1, - .peers = &no_peers, - }; - shell.gens[0] = 2; - _ = shell.apply(.{ .pty_read = .{ .id = 0, .gen = 1, .bytes = try gpa.dupe(u8, "old session\n") } }); - _ = shell.apply(.{ .pty_read = .{ .id = 0, .gen = 2, .bytes = try gpa.dupe(u8, "current session\n") } }); - const text = try pardes.Term.scrollback(core.panes[0].?.terminal, gpa); - defer gpa.free(text); - try std.testing.expect(std.mem.indexOf(u8, text, "old session") == null); - try std.testing.expect(std.mem.indexOf(u8, text, "current session") != null); - - core.lspRequest(0, .status, ""); - const old_id = core.lsp_ask.wait.?.id; - core.lspRequest(0, .status, ""); - const current_id = core.lsp_ask.wait.?.id; - shell.lsp_task = .{ .id = current_id, .future = .{ .any_future = null, .result = {} } }; - _ = shell.apply(.{ .lsp_done = .{ .id = old_id, .rows = try gpa.dupe(u8, "stale result\n") } }); - try std.testing.expect(shell.lsp_task != null); - try std.testing.expectEqual(current_id, shell.lsp_task.?.id); - try std.testing.expectEqual(current_id, core.lsp_ask.wait.?.id); - _ = shell.apply(.{ .lsp_done = .{ .id = current_id, .rows = try gpa.dupe(u8, "") } }); - try std.testing.expect(shell.lsp_task == null); - try std.testing.expect(core.lsp_ask.wait == null); -} - test "TTY worker setup failures finish matching LSP and pipe requests" { const gpa = std.testing.allocator; var failing_vtable = std.testing.io.vtable.*; @@ -3048,19 +2698,22 @@ test "TTY worker setup failures finish matching LSP and pipe requests" { .fail_index = if (failure == 0) 0 else std.math.maxInt(usize), }); var no_peers: replica.Peers = .{}; + var queue: host_io.Inbox = .{ .io = failing_io, .gpa = gpa, .lsp_allocator = failing.allocator() }; + defer queue.deinit(); + var ptys: host_io.Ptys = .{ .queue = &queue, .prompt_rcs = undefined }; var shell: Shell = .{ .io = failing_io, .gpa = failing.allocator(), .lsp_gpa = failing.allocator(), .core = core, .frames = core.frames, - .prompt_rcs = undefined, .loop = undefined, .frame = undefined, .paste_buf = undefined, - .inotify_fd = -1, + .watches = undefined, .threads_ok = true, .peers = &no_peers, + .ptys = &ptys, }; core.lspRequest(core.view().active, .status, ""); const req: host_io.Lsp.Request = .{ @@ -3083,7 +2736,7 @@ test "TTY worker setup failures finish matching LSP and pipe requests" { Shell.pipe(&shell, pipe_id); try std.testing.expect(core.pipe.wait == null); try std.testing.expectEqualStrings("abc", pane.file.?.content); - try std.testing.expect(shell.lsp_task == null); + try std.testing.expect(queue.lsp_task == null); try std.testing.expectEqual(@as(usize, 0), shell.pipe_tasks.len); } } |
