summaryrefslogtreecommitdiff
path: root/dev
diff options
context:
space:
mode:
Diffstat (limited to 'dev')
-rw-r--r--dev/Inbox.zig24
-rw-r--r--dev/Ptys.zig403
-rw-r--r--dev/file_watch.zig122
-rw-r--r--dev/gui/gui.zig598
-rw-r--r--dev/host_io.zig2
-rw-r--r--dev/root.zig7
-rw-r--r--dev/tui/tui.zig587
7 files changed, 724 insertions, 1019 deletions
diff --git a/dev/Inbox.zig b/dev/Inbox.zig
index ed3a9835..aac1f7a1 100644
--- a/dev/Inbox.zig
+++ b/dev/Inbox.zig
@@ -23,8 +23,6 @@ pub const Msg = union(enum) {
kind_job: *KindJob,
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 },
@@ -44,7 +42,7 @@ pub const Msg = union(enum) {
.adopted => |a| if (a.fd >= 0) {
_ = libc.close(a.fd);
},
- .eof, .files_changed, .fs_ready, .window => {},
+ .eof, .files_changed, .fs_ready => {},
}
}
};
@@ -264,6 +262,9 @@ pub fn close(q: *Inbox) void {
}
pub fn deinit(q: *Inbox) void {
+ // The query in flight ends first: what it still delivers is dropped.
+ if (q.lsp_task) |*t| t.future.cancel(q.io);
+ q.lsp_task = null;
q.close();
std.debug.assert(q.waiting == 0);
}
@@ -310,6 +311,23 @@ pub fn startLsp(q: *Inbox, core: *pardes.Pardes, e: Lsp.Request) void {
Lsp.start(q.io, q.lsp_allocator, core, &q.lsp_task, e, q, pushLspRows);
}
+/// A language server's answer or status line taken off the queue, to the
+/// core (whichever frontend took it).
+pub fn landLsp(q: *Inbox, core: *pardes.Pardes, m: Msg) void {
+ switch (m) {
+ .lsp => |l| {
+ core.update(.{ .lsp_resp = .{ .id = l.id, .rows = l.rows } });
+ if (l.rows) |rows| q.lsp_allocator.free(rows);
+ },
+ .lsp_status => |text| {
+ var mbuf: [256]u8 = undefined;
+ core.setStatus(.at(core.view().active), pardes.Messages.Message.stamp(&mbuf, "lsp", text));
+ q.lsp_allocator.free(text);
+ },
+ else => unreachable,
+ }
+}
+
fn pushLspRows(ctx: ?*anyopaque, id: u32, rows: ?[]u8) void {
const q: *Inbox = @ptrCast(@alignCast(ctx orelse return));
q.push(.{ .lsp = .{ .id = id, .rows = rows } });
diff --git a/dev/Ptys.zig b/dev/Ptys.zig
new file mode 100644
index 00000000..16a31939
--- /dev/null
+++ b/dev/Ptys.zig
@@ -0,0 +1,403 @@
+//! A session's ptys: each terminal pane's shell (forked here, or adopted
+//! from a session that died), its master and pid, and the reader that
+//! posts what it says to the session's queue (Inbox). One table a session,
+//! the session loop's (runtime/session.zig): the Host's pty calls are
+//! answered here whatever the frontend (`Calls`), and a frontend draining
+//! the queue hands the readers' posts back (`output`, `eof`).
+const std = @import("std");
+const posix = std.posix;
+const libc = std.c;
+const pardes = @import("core");
+const daemon = @import("runtime").daemon;
+const upgrade = @import("runtime").upgrade;
+const host_io = @import("host_io.zig");
+const Inbox = host_io.Inbox;
+const Ptys = @This();
+
+const TIOCSWINSZ: c_int = @bitCast(@as(u32, if (@hasDecl(posix.T, "IOCSWINSZ")) posix.T.IOCSWINSZ else 0x80087467));
+
+pub const Pty = struct {
+ fd: c_int,
+ pid: libc.pid_t,
+ /// Its reader, blocked in an Io read: `close` cancels it.
+ reader: ?std.Io.Future(void) = null,
+ /// 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 = .{},
+};
+
+slots: [pardes.MAX_PANES]?Pty = @splat(null),
+/// Each slot's generation: a post of an older one is passed over.
+gens: [pardes.MAX_PANES]u32 = @splat(0),
+queue: *Inbox,
+prompt_rcs: *const host_io.Shell.PromptFiles,
+/// Shells a dead session left (Adopt), each waiting for the spawn of the
+/// terminal pane made for it.
+adoptions: host_io.Adoptions = .{},
+/// Readers run from the loop's start on (`start`): a shell spawned in the
+/// first effects is read from then.
+reading: bool = false,
+
+/// The Host's pty calls, for a host whose `ctx` is a `*Ctx` with the
+/// fields `ptys: *Ptys` and `core: *Pardes`.
+pub fn Calls(comptime Ctx: type) type {
+ return struct {
+ fn of(ctx: ?*anyopaque) *Ctx {
+ return @ptrCast(@alignCast(ctx.?));
+ }
+ pub fn spawn(ctx: ?*anyopaque, id: pardes.Pane.Id, cwd: []const u8) void {
+ const s = of(ctx);
+ s.ptys.spawn(s.core, id, cwd);
+ }
+ pub fn write(ctx: ?*anyopaque, id: pardes.Pane.Id, bytes: []const u8) void {
+ of(ctx).ptys.write(id, bytes);
+ }
+ pub fn resize(ctx: ?*anyopaque, id: pardes.Pane.Id, cols: u16, rows: u16) void {
+ const s = of(ctx);
+ s.ptys.resize(s.core, id, cols, rows);
+ }
+ pub fn signal(ctx: ?*anyopaque, id: pardes.Pane.Id, sig: pardes.PtySignal) void {
+ of(ctx).ptys.signal(id, sig);
+ }
+ pub fn close(ctx: ?*anyopaque, id: pardes.Pane.Id) void {
+ of(ctx).ptys.close(id);
+ }
+ pub fn ttyTaken(ctx: ?*anyopaque, id: pardes.Pane.Id) bool {
+ const pt = of(ctx).ptys.slots[id.index()] orelse return false;
+ return host_io.ttyTaken(pt.pid, pt.fd);
+ }
+ pub fn fgName(ctx: ?*anyopaque, id: pardes.Pane.Id, buf: []u8) ?[]const u8 {
+ const pt = of(ctx).ptys.slots[id.index()] orelse return null;
+ return host_io.foregroundName(pt.pid, pt.fd, buf);
+ }
+ pub fn killJob(ctx: ?*anyopaque, id: pardes.Pane.Id) bool {
+ const pt = of(ctx).ptys.slots[id.index()] orelse return false;
+ return host_io.killJob(pt.pid, pt.fd);
+ }
+ pub fn adopt(ctx: ?*anyopaque, id: pardes.Pane.Id) void {
+ const s = of(ctx);
+ s.ptys.adoptions.ask(s.core, id.index());
+ }
+ };
+}
+
+/// Pane `id`'s shell, in `cwd` (empty: where its pane's directory says),
+/// or the adopted one waiting for it.
+pub fn spawn(p: *Ptys, core: *pardes.Pardes, id: pardes.Pane.Id, cwd: []const u8) void {
+ const pane = id.index();
+ if (p.adoptions.take(id)) |a| return p.take(core, 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 = p.slots[pane] != null;
+ const child = host_io.forkShell(core, pane, p.prompt_rcs, core.shellBin(), cwd, core.view().screen_h, core.view().screen_w) catch |err| {
+ if (running) return core.restartFailed(id, err);
+ return core.shellFailed(id, err);
+ };
+ p.close(id);
+ p.gens[pane] +%= 1;
+ const command = if (core.panes[pane]) |pn| pn.command != null else false;
+ p.slots[pane] = .{ .fd = child.file.handle, .pid = child.pid, .cmd = .{ .watched = command and host_io.watchExit(child.pid), .fd = child.file.handle } };
+ // Only a shell given no directory is asked where it is: one given a
+ // directory is named by it already (newShell), and the frame's poll
+ // (`pollCwds`) says where it went from there.
+ var lbuf: [pardes.memory.limits.host_path_cap + 1]u8 = undefined;
+ if (cwd.len == 0) if (host_io.shellCwd(child.pid, &lbuf)) |wd| core.setCwd(id, wd);
+ p.read(core, pane);
+}
+
+/// 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 take(p: *Ptys, core: *pardes.Pardes, pane: u8, a: host_io.Adoption) void {
+ p.close(.at(pane));
+ p.gens[pane] +%= 1;
+ p.slots[pane] = .{ .fd = a.fd, .pid = a.pid };
+ var exe_buf: [pardes.memory.limits.host_path_cap + 1]u8 = undefined;
+ 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| 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 (core.panes[pane]) |pn| p.resize(core, .at(pane), @max(pn.cols, 1), @max(pn.rows, 1));
+ p.read(core, pane);
+}
+
+/// Pane `pane`'s reader, once readers run: the place of one stopped for
+/// an Upgrade let go first. One that cannot start closes the pty and says
+/// why in the pane.
+fn read(p: *Ptys, core: *pardes.Pardes, pane: u8) void {
+ if (!p.reading) return;
+ const pt = &(p.slots[pane] orelse return);
+ p.queue.cancelReader(.at(pane), p.gens[pane]);
+ pt.reader = p.queue.startReader(.{ .handle = pt.fd, .flags = .{ .nonblocking = false } }, .at(pane), p.gens[pane]) catch |err| {
+ p.close(.at(pane));
+ return core.reportError(.at(pane), "terminal reader", err);
+ };
+}
+
+/// The loop's start: every shell read from now on.
+pub fn start(p: *Ptys, core: *pardes.Pardes) void {
+ p.reading = true;
+ for (0..p.slots.len) |pane| p.read(core, @intCast(pane));
+}
+
+pub fn write(p: *Ptys, id: pardes.Pane.Id, bytes: []const u8) void {
+ if (p.slots[id.index()]) |pt| _ = host_io.writeFd(pt.fd, bytes);
+}
+
+pub fn resize(p: *Ptys, core: *const pardes.Pardes, id: pardes.Pane.Id, cols: u16, rows: u16) void {
+ const pt = p.slots[id.index()] orelse return;
+ const ws = host_io.ptyWinsize(core, cols, rows);
+ _ = posix.system.ioctl(pt.fd, TIOCSWINSZ, @intFromPtr(&ws));
+}
+
+pub fn signal(p: *Ptys, id: pardes.Pane.Id, sig: pardes.PtySignal) void {
+ // A command whose exit is recorded is reaped: its group may be
+ // another's by now.
+ if (p.slots[id.index()]) |pt| if (!pt.cmd.exited) host_io.signalTty(pt.pid, pt.fd, sig, pt.cmd.watched);
+}
+
+/// A daemon started since the last one died: every master told it again,
+/// as `spawn` tells the first (host_io.forkShell).
+pub fn tellDaemon(p: *const Ptys) void {
+ for (p.slots) |slot| if (slot) |pt| daemon.pty(pt.pid, pt.fd);
+}
+
+/// The pane is gone, or its shell is: its reader out of the queue first
+/// (which lets go one waiting for room there) and canceled; its pty hung
+/// up, which the kernel passes on to the shell as SIGHUP; the daemon's
+/// copy let go; the shell retired.
+pub fn close(p: *Ptys, id: pardes.Pane.Id) void {
+ const pane = id.index();
+ var pt = p.slots[pane] orelse return;
+ p.slots[pane] = null;
+ p.queue.cancelReader(id, p.gens[pane]);
+ if (pt.reader) |*r| r.cancel(p.queue.io);
+ _ = libc.close(pt.fd);
+ daemon.closed(pt.pid);
+ host_io.retireShell(pt.pid);
+}
+
+/// A reader's read, off the queue (freed here).
+pub fn output(p: *Ptys, core: *pardes.Pardes, o: @FieldType(Inbox.Msg, "output")) void {
+ defer p.queue.gpa.free(o.bytes);
+ if (p.gens[o.pane.index()] == o.gen) core.update(.{ .output = .{ .pane = o.pane, .bytes = o.bytes } });
+}
+
+/// A reader's end, off the queue: its pty's end of file, or a read that
+/// failed.
+pub fn eof(p: *Ptys, core: *pardes.Pardes, e: @FieldType(Inbox.Msg, "eof")) void {
+ const pane = e.pane.index();
+ if (p.gens[pane] != e.gen) return;
+ if (e.failure) |err| {
+ p.close(e.pane);
+ return core.readerFailed(e.pane, err);
+ }
+ const pt = &(p.slots[pane] orelse return core.update(.{ .eof = .{ .pane = e.pane } }));
+ // 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) return host_io.commandEof(core, &p.slots, pane, p, closeWatched);
+ // 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[pane]) |pn| pn.command != null else false;
+ const status = host_io.exitStatus(pt.pid, 100);
+ if (status != null) pt.pid = 0; // reaped: no shell to retire
+ p.close(e.pane);
+ if (command or status != null) core.update(.{ .exited = .{ .pane = e.pane, .status = status } });
+ core.update(.{ .eof = .{ .pane = e.pane } });
+}
+
+/// The command panes' exits, told once their output is in (host_io):
+/// after an exit's wake and after each batch of output.
+pub fn takeExits(p: *Ptys, core: *pardes.Pardes) void {
+ host_io.takeExits(core, &p.slots, p, closeWatched);
+}
+
+fn closeWatched(p: *Ptys, id: usize) void {
+ p.close(.at(id));
+}
+
+/// Where each shell is now: its pane's directory (a frame's poll).
+pub fn pollCwds(p: *Ptys, core: *pardes.Pardes) void {
+ for (p.slots, 0..) |slot, id| if (slot) |pt| {
+ var lbuf: [pardes.memory.limits.host_path_cap + 1]u8 = undefined;
+ if (host_io.ttyCwd(pt.pid, pt.fd, core.settings.shell.effective.get(), &lbuf)) |cwd| core.setCwd(.at(id), cwd);
+ };
+}
+
+/// An Upgrade's: the readers stopped, the ptys left open. What a reader
+/// posted before its cancel is in the queue still, the frontend's to
+/// take; one waiting for room has it once the queue is drained.
+pub fn pause(p: *Ptys) void {
+ for (&p.slots) |*slot| if (slot.*) |*pt| if (pt.reader) |*r| {
+ r.cancel(p.queue.io);
+ pt.reader = null;
+ };
+}
+
+/// After an Upgrade that did not happen: read on.
+pub fn readOn(p: *Ptys, core: *pardes.Pardes) void {
+ for (p.slots, 0..) |slot, pane| if (slot) |pt| if (pt.reader == null) p.read(core, @intCast(pane));
+}
+
+/// The ptys an Upgrade hands to the next build.
+pub fn record(p: *const Ptys, rec: *upgrade.Record) void {
+ for (p.slots, 0..) |slot, id| if (slot) |pt| rec.addPty(id, pt.pid, pt.fd);
+}
+
+/// 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.
+pub fn resumeFrom(p: *Ptys, core: *pardes.Pardes, rec: *const upgrade.Record) void {
+ for (rec.ptys[0..rec.nptys]) |k| {
+ const pane = if (rec.fresh) null else core.panes[k.pane];
+ if (pane == null or !pane.?.isTerminal()) {
+ p.adoptions.adoptShell(core, k.pid, k.fd);
+ continue;
+ }
+ p.slots[k.pane] = .{ .fd = k.fd, .pid = k.pid, .cmd = .{ .watched = pane.?.command != null and host_io.watchExit(k.pid), .fd = k.fd } };
+ }
+}
+
+/// Every pty closed and every generation moved on: a Restore's (the new
+/// core's panes start shells of their own) and the session's end.
+pub fn stop(p: *Ptys) void {
+ for (0..p.slots.len) |pane| p.close(.at(pane));
+ for (&p.gens) |*gen| gen.* +%= 1;
+}
+
+/// The session's end: every shell hung up and seen out (waitRetired), the
+/// adopted ones no pane took let go.
+pub fn deinit(p: *Ptys) void {
+ p.stop();
+ for (p.adoptions.list[0..p.adoptions.len]) |a| _ = libc.close(a.fd);
+ p.adoptions.len = 0;
+ host_io.waitRetired();
+}
+
+/// A table over `queue` with shells of its own, readers running: the
+/// tests' (each slot's generation 1).
+fn testing(queue: *Inbox) Ptys {
+ const none = struct {
+ const rcs: host_io.Shell.PromptFiles = .{};
+ };
+ return .{ .queue = queue, .prompt_rcs = &none.rcs, .gens = @splat(1), .reading = true };
+}
+
+fn testShell(p: *Ptys, pane: u8) !libc.pid_t {
+ const child = try host_io.forkShell(null, pane, p.prompt_rcs, "/bin/sh", "", 24, 80);
+ p.slots[pane] = .{ .fd = child.file.handle, .pid = child.pid };
+ p.slots[pane].?.reader = try p.queue.startReader(.{ .handle = child.file.handle, .flags = .{ .nonblocking = false } }, .at(pane), p.gens[pane]);
+ return child.pid;
+}
+
+test "a reader delivers a real shell's tail before its end of file, and closing joins it" {
+ const gpa = std.testing.allocator;
+ var queue: Inbox = .{ .io = std.testing.io, .gpa = gpa, .lsp_allocator = gpa };
+ defer queue.deinit();
+ var p = testing(&queue);
+ defer p.deinit();
+ _ = try p.testShell(0);
+ const fd = p.slots[0].?.fd;
+ try std.testing.expect(host_io.writeFd(fd, "printf '\\120\\101\\122\\104\\105\\123\\055\\124\\101\\111\\114'; exit\n"));
+ var bytes: std.ArrayList(u8) = .empty;
+ defer bytes.deinit(gpa);
+ var ended = false;
+ const until = std.Io.Clock.awake.now(std.testing.io).toMilliseconds() + 2_000;
+ while (!ended and std.Io.Clock.awake.now(std.testing.io).toMilliseconds() < until) {
+ var batch = queue.take();
+ defer for (batch.slice()) |msg| msg.deinit(gpa, gpa);
+ for (batch.slice()) |msg| switch (msg) {
+ .output => |o| {
+ try std.testing.expect(!ended);
+ try bytes.appendSlice(gpa, o.bytes);
+ },
+ .eof => |e| {
+ try std.testing.expect(e.failure == null);
+ ended = true;
+ },
+ else => return error.UnexpectedMessage,
+ };
+ if (!ended) try std.testing.io.sleep(.fromMilliseconds(1), .awake);
+ }
+ try std.testing.expect(ended);
+ try std.testing.expect(std.mem.indexOf(u8, bytes.items, "PARDES-TAIL") != null);
+ p.close(.at(0));
+ try std.testing.expect(queue.readers[0] == null);
+ try std.testing.expect(p.slots[0] == null);
+ try std.testing.expectEqual(@as(c_int, -1), libc.fcntl(fd, libc.F.GETFD));
+}
+
+test "a Restore's stop joins a real reader waiting for room in the queue" {
+ const gpa = std.testing.allocator;
+ var core = try pardes.Pardes.init(gpa, .{ .tty_only = true });
+ defer core.deinit();
+ try pardes.dump.dumpState(core);
+ var queue: Inbox = .{ .io = std.testing.io, .gpa = gpa, .lsp_allocator = gpa };
+ defer queue.deinit();
+ queue.acceptReader(.at(1), 1);
+ for (0..Inbox.output_capacity) |_| queue.push(.{ .output = .{ .pane = .at(1), .gen = 1, .bytes = try gpa.dupe(u8, "other pane") } });
+ var p = testing(&queue);
+ defer p.deinit();
+ _ = try p.testShell(0);
+ const fd = p.slots[0].?.fd;
+ try std.testing.expect(host_io.writeFd(fd, "printf 'after-full'; exit\n"));
+ try host_io.PtyTests.waitBlocked(&queue);
+ const old_serial = core.panes[0].?.serial;
+ const replacement = try pardes.dump.restore(core, core.dump_out.?, "test");
+ p.stop();
+ core.deinit();
+ core = replacement;
+ // The dump's pane, its serial too; its old shell stopped all the same.
+ try std.testing.expectEqual(old_serial, core.panes[0].?.serial);
+ try std.testing.expectEqual(@as(usize, 0), queue.waiting);
+ try std.testing.expect(queue.readers[0] == null);
+ try std.testing.expectEqual(@as(c_int, -1), libc.fcntl(fd, libc.F.GETFD));
+ queue.cancelReader(.at(1), 1);
+ queue.acceptReader(.at(0), p.gens[0]);
+ queue.push(.{ .eof = .{ .pane = .at(0), .gen = 1 } });
+ try std.testing.expect(queue.pushOutput(.at(0), p.gens[0], try gpa.dupe(u8, "fresh")));
+ var batch = queue.take();
+ defer for (batch.slice()) |msg| msg.deinit(gpa, gpa);
+ try std.testing.expectEqual(@as(usize, 1), batch.len);
+ try std.testing.expectEqualStrings("fresh", batch.items[0].output.bytes);
+}
+
+test "a pane's removal closes its pty, joins its idle reader, and its shell is reaped by the end" {
+ const gpa = std.testing.allocator;
+ const core = try pardes.Pardes.init(gpa, .{ .tty_only = true });
+ defer core.deinit();
+ var queue: Inbox = .{ .io = std.testing.io, .gpa = gpa, .lsp_allocator = gpa };
+ defer queue.deinit();
+ var p = testing(&queue);
+ defer p.deinit();
+ while (core.nextEffect()) |_| {}
+ const pid = try p.testShell(0);
+ const fd = p.slots[0].?.fd;
+ try core.removePane(0, null);
+ // The core asks it closed (panes.retirePane): no pane outlives its pty.
+ while (core.nextEffect()) |e| if (e == .close_pty) p.close(e.close_pty.pane);
+ try std.testing.expect(p.slots[0] == null);
+ try std.testing.expect(queue.readers[0] == null);
+ try std.testing.expectEqual(@as(usize, 0), queue.waiting);
+ try std.testing.expectEqual(@as(usize, 0), queue.take().len);
+ try std.testing.expectEqual(@as(c_int, -1), libc.fcntl(fd, libc.F.GETFD));
+ p.deinit();
+ try std.testing.expectEqual(@as(libc.pid_t, -1), libc.waitpid(pid, null, libc.W.NOHANG));
+ try std.testing.expectEqual(libc.E.CHILD, libc.errno(-1));
+}
+
+test "a post of an older generation is passed over" {
+ const gpa = std.testing.allocator;
+ const core = try pardes.Pardes.init(gpa, .{ .tty_only = true, .cols = 40, .rows = 12 });
+ defer core.deinit();
+ var queue: Inbox = .{ .io = std.testing.io, .gpa = gpa, .lsp_allocator = gpa };
+ defer queue.deinit();
+ var p: Ptys = .{ .queue = &queue, .prompt_rcs = undefined };
+ p.gens[0] = 2;
+ p.output(core, .{ .pane = .at(0), .gen = 1, .bytes = try gpa.dupe(u8, "old session\n") });
+ p.output(core, .{ .pane = .at(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);
+}
diff --git a/dev/file_watch.zig b/dev/file_watch.zig
index 84f37c81..58229d90 100644
--- a/dev/file_watch.zig
+++ b/dev/file_watch.zig
@@ -664,6 +664,88 @@ pub fn reloadTheme(
return false;
}
+/// A session's file watches: the kernel's descriptor, the table (each
+/// pane's mark and the theme's slot) and the reader that posts a change
+/// to the session's queue (Inbox) as `files_changed`. One a session, the
+/// session loop's (runtime/session.zig): the Host's three file calls are
+/// answered here whatever the frontend (`Calls`), and a frontend taking
+/// `files_changed` off the queue hands it back (`reload`).
+pub const Watches = struct {
+ fd: c_int = -1,
+ table: Table = @splat(null),
+ io: std.Io,
+ gpa: std.mem.Allocator,
+ queue: *Inbox,
+ reader: ?std.Io.Future(void) = null,
+
+ const Inbox = @import("Inbox.zig");
+
+ pub fn open(io: std.Io, gpa: std.mem.Allocator, queue: *Inbox) Watches {
+ return .{ .fd = init(false), .io = io, .gpa = gpa, .queue = queue };
+ }
+
+ /// The reader, from the loop's start on (none: nothing is watched for
+ /// a change, the marks still made).
+ pub fn start(w: *Watches) void {
+ if (w.fd >= 0) w.reader = w.io.concurrent(read, .{ w.io, w.fd, w.queue }) catch null;
+ }
+
+ pub fn deinit(w: *Watches) void {
+ stop(w.fd);
+ if (w.reader) |*r| r.cancel(w.io);
+ w.reader = null;
+ if (w.fd >= 0) _ = libc.close(w.fd);
+ w.fd = -1;
+ }
+
+ /// The marks reconciled after a wake; a second pass asked of the
+ /// queue when one wants it (`reloadPane`).
+ pub fn reload(w: *Watches, core: *pardes.Pardes) void {
+ if (reloadChanged(core, w.io, w.gpa, &w.table)) w.queue.push(.files_changed);
+ }
+
+ /// Blocked in a read of the descriptor (a kqueue's `wait`, where there
+ /// is nothing to read): a change posted, whatever it was (`reload`
+ /// reads every mark); canceled (`deinit`), it ends.
+ fn read(io: std.Io, fd: c_int, queue: *Inbox) void {
+ if (comptime builtin.os.tag != .linux and builtin.os.tag != .freebsd) {
+ while (wait(fd)) queue.push(.files_changed);
+ return;
+ }
+ const file: std.Io.File = .{ .handle = fd, .flags = .{ .nonblocking = false } };
+ var buf: [4096]u8 = undefined;
+ while (true) {
+ const n = file.readStreaming(io, &.{&buf}) catch return;
+ if (n == 0) return;
+ queue.push(.files_changed);
+ }
+ }
+
+ /// The Host's file calls, for a host whose `ctx` is a `*Ctx` with the
+ /// fields `watches: *Watches` and `core: *Pardes`.
+ pub fn Calls(comptime Ctx: type) type {
+ return struct {
+ fn of(ctx: ?*anyopaque) *Ctx {
+ return @ptrCast(@alignCast(ctx.?));
+ }
+ pub fn writeFile(ctx: ?*anyopaque, id: pardes.Pane.Id, path: []const u8, bytes: []const u8) void {
+ const s = of(ctx);
+ @import("host_io.zig").writeFile(s.core, &s.watches.table, id.index(), path, bytes);
+ }
+ pub fn watchFile(ctx: ?*anyopaque, id: pardes.Pane.Id, _: []const u8, on: bool, mode: pardes.WatchMode) void {
+ const s = of(ctx);
+ const w = s.watches;
+ if (applyEffect(s.core, w.io, w.fd, &w.table, id.index(), on, mode)) w.queue.push(.files_changed);
+ }
+ pub fn watchTheme(ctx: ?*anyopaque, generation: u32, on: bool) void {
+ const s = of(ctx);
+ const w = s.watches;
+ if (applyThemeEffect(s.core, w.gpa, w.fd, &w.table, generation, on)) w.queue.push(.files_changed);
+ }
+ };
+ }
+};
+
pub fn identify(io: std.Io, path: []const u8) !Identity {
const native = filesystem.localPath(path) orelse return error.NonLocalPath;
pardes.turn.yield();
@@ -961,3 +1043,43 @@ test "a watched file deleted wakes the watch at once, and its pane says so" {
_ = reloadChanged(core, io, gpa, &watches);
try std.testing.expect(pane.file.?.disk_gone);
}
+
+test "a session's watches: a marked file's change posted to the queue, the reader ended at the end" {
+ if (comptime !supported or !filesystem.platform_has_fs) return;
+ const io = std.testing.io;
+ const gpa = std.testing.allocator;
+ var tmp = std.testing.tmpDir(.{});
+ defer tmp.cleanup();
+ try tmp.dir.writeFile(io, .{ .sub_path = "watched", .data = "before\n" });
+ var path_buf: [256]u8 = undefined;
+ const path = try std.fmt.bufPrint(&path_buf, ".zig-cache/tmp/{s}/watched", .{tmp.sub_path});
+ const core = try pardes.Pardes.init(gpa, .{ .tty_only = true });
+ defer core.deinit();
+ while (core.nextEffect()) |_| {}
+ const id: u8 = @intCast(core.freeSlot().?);
+ const pane = try pardes.panes.File.open(core, id, path, 0);
+ var queue: Watches.Inbox = .{ .io = io, .gpa = gpa, .lsp_allocator = gpa };
+ defer queue.deinit();
+ var w: Watches = .open(io, gpa, &queue);
+ defer w.deinit();
+ if (w.fd < 0) return error.NoWatcher;
+ defer unwatchAll(w.fd, &w.table);
+ while (core.nextEffect()) |effect| switch (effect) {
+ .watch => |watch| if (watch.pane.index() == id and watch.on) {
+ _ = applyEffect(core, io, w.fd, &w.table, id, watch.on, watch.mode);
+ },
+ else => {},
+ };
+ w.start();
+ try tmp.dir.writeFile(io, .{ .sub_path = "watched", .data = "after\n" });
+ var batch: Watches.Inbox.Batch = .{};
+ for (0..500) |_| {
+ queue.takeInto(&batch);
+ if (batch.len > 0) break;
+ try io.sleep(.fromMilliseconds(10), .awake);
+ }
+ try std.testing.expectEqual(@as(usize, 1), batch.len);
+ try std.testing.expect(batch.items[0] == .files_changed);
+ w.reload(core);
+ try std.testing.expectEqualStrings("after\n", pane.file.?.content);
+}
diff --git a/dev/gui/gui.zig b/dev/gui/gui.zig
index 9695bf83..ab33abe9 100644
--- a/dev/gui/gui.zig
+++ b/dev/gui/gui.zig
@@ -370,17 +370,6 @@ fn emitTouchClick(g: *const Gui, in: *Input, point: TouchNormPoint, button: pard
in.post(.{ .mouse = .{ .button = button, .kind = .release, .col = cell.col, .row = cell.row, .tag_hit = cell.tag_hit, .body_hit = cell.body_hit } });
}
-const Pty = struct {
- fd: c_int,
- pid: libc.pid_t,
- serial: u32,
- /// Its reader, blocked in an Io read: `closePty` cancels it.
- reader: ?std.Io.Future(void) = null,
- /// 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 = .{},
-};
-
const Queue = host_io.Inbox;
/// Wakes a blocking SDL_WaitEventTimeout from another thread: a push to
@@ -393,32 +382,6 @@ fn sdlWake(_: ?*anyopaque) void {
const PipeTasks = selection_pipe.Tasks;
const output_capacity = Queue.output_capacity;
-fn stopPipe() ![2]c_int {
- var fds: [2]c_int = undefined;
- if (libc.pipe(&fds) != 0) return error.PipeFailed;
- errdefer for (fds) |fd| {
- _ = libc.close(fd);
- };
- for (fds) |fd| if (libc.fcntl(fd, libc.F.SETFD, @as(c_int, 1)) < 0) return error.PipeFailed;
- return fds;
-}
-
-fn watchThread(fd: c_int, stop: c_int, q: *Queue) void {
- while (true) {
- var fds = [_]libc.pollfd{
- .{ .fd = stop, .events = libc.POLL.IN, .revents = 0 },
- .{ .fd = fd, .events = libc.POLL.IN, .revents = 0 },
- };
- if (libc.poll(&fds, fds.len, -1) < 0) {
- if (libc.errno(-1) == .INTR) continue;
- return;
- }
- if (fds[0].revents != 0) return;
- if ((fds[1].revents & (libc.POLL.ERR | libc.POLL.HUP | libc.POLL.NVAL)) != 0) return;
- if (fds[1].revents != 0 and file_watch.drain(fd)) q.push(.files_changed);
- }
-}
-
const Gui = struct {
addon_gpu: ?SketchGpu = null,
addon_hash: [pardes.MAX_PANES]u64 = @splat(0),
@@ -1001,8 +964,9 @@ fn closeWindow(g: *Gui) void {
};
}
-/// `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.
+/// A window again, as the first was made, at the size the last one had
+/// (a transparent one: syncWindowOpacity). 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 (comptime builtin.os.tag == .macos) c.ui_macos_trackpad_attach(window);
@@ -1027,14 +991,7 @@ const Own = struct {
g: *Gui,
test_mode: bool,
detached: bool,
- ptys: [pardes.MAX_PANES]?Pty = @splat(null),
- gens: [pardes.MAX_PANES]u32 = @splat(0),
- queue: Queue = undefined,
pipe_tasks: PipeTasks = .{},
- inotify_fd: c_int = -1,
- watch_reader: ?std.Thread = null,
- watch_stop: [2]c_int = .{ -1, -1 },
- watches: file_watch.Table = @splat(null),
shell: Shell = undefined,
const Session = session_loop.Loop(Own);
@@ -1058,26 +1015,17 @@ const Own = struct {
core.view().frontend.native_image_patches = true;
observeGuiFont(g, core);
syncTaglineFont(g, core);
- o.queue = .{
- .io = l.io,
- .gpa = l.gpa,
- .lsp_allocator = l.allocs.lsp,
- .wake_fn = sdlWake,
- };
- o.inotify_fd = file_watch.init(true);
+ l.inbox.wake_fn = sdlWake;
o.shell = .{
.core = core,
.gui = g,
.io = l.io,
.gpa = l.gpa,
.lsp_allocator = l.allocs.lsp,
- .prompt_rcs = &l.prompt_rcs,
- .ptys = &o.ptys,
- .gens = &o.gens,
- .queue = &o.queue,
+ .ptys = &l.ptys,
+ .queue = &l.inbox,
.pipe_tasks = &o.pipe_tasks,
- .inotify_fd = o.inotify_fd,
- .watches = &o.watches,
+ .watches = &l.watches,
.fs = l.fs,
.test_mode = o.test_mode,
.test_clock = if (o.test_mode) host_io.testClock() else null,
@@ -1100,43 +1048,16 @@ const Own = struct {
const io = l.io;
o.shell.fs = null;
host_io.setExitWake(null, null);
- pardes.lsp.setStatusSink(null, null);
pardes.Kind.drawer = null;
- o.shell.shutdownPtys();
o.shell.job_tasks.cancelAll(io);
- if (o.inotify_fd >= 0) {
- if (o.watch_reader) |thread| {
- _ = host_io.writeFd(o.watch_stop[1], "x");
- thread.join();
- }
- for (o.watch_stop) |fd| if (fd >= 0) {
- _ = libc.close(fd);
- };
- file_watch.stop(o.inotify_fd);
- _ = libc.close(o.inotify_fd);
- o.inotify_fd = -1;
- }
o.pipe_tasks.cancelAll(io);
- if (o.queue.lsp_task) |*task| task.future.cancel(io);
// Its worker may be waiting on the queue for room.
l.core.stream.cancelTask();
- o.queue.deinit();
o.g.hit_core = null;
}
- pub fn resumePtys(o: *Own, rec: *const upgrade.Record) void {
- o.shell.resumePtys(rec);
- }
-
pub fn start(o: *Own, l: *Session) !void {
- for (&o.ptys, 0..) |*slot, id| if (slot.*) |*pt| {
- pt.reader = try o.queue.startReader(.{ .handle = pt.fd, .flags = .{ .nonblocking = false } }, .at(id), o.gens[id]);
- };
- if (o.inotify_fd >= 0) {
- o.watch_stop = try stopPipe();
- o.watch_reader = try std.Thread.spawn(.{}, watchThread, .{ o.inotify_fd, o.watch_stop[0], &o.queue });
- }
- if (l.fs) |f| try f.watch(&o.queue, wakeFs);
+ if (l.fs) |f| try f.watch(&l.inbox, wakeFs);
_ = c.SDL_StartTextInput(o.g.window);
// An upgraded session's window, its view's again.
@@ -1144,8 +1065,7 @@ const Own = struct {
if (o.test_mode) setStdinRaw() catch {};
o.shell.threads_ok = true;
- pardes.lsp.setStatusSink(&o.queue, Queue.lspStatus);
- host_io.setExitWake(&o.queue, Queue.wakeForExit);
+ host_io.setExitWake(&l.inbox, Queue.wakeForExit);
if (o.detached) {
o.shell.closeTheWindow();
// Nothing else may wake the first wait.
@@ -1163,16 +1083,10 @@ const Own = struct {
deliverNote(&o.shell, n);
}
- pub fn watched(o: *Own) session_loop.Watched {
- return .{ .fd = o.inotify_fd, .table = &o.watches };
- }
-
pub fn restoring(o: *Own, nc: *pardes.Pardes) void {
o.pipe_tasks.cancelAll(o.shell.io);
- o.queue.discardCompletions();
// One view, the window's (host_io.restoreCore).
o.shell.gview = 0;
- o.shell.stopPtys();
o.g.cells.clearImages();
o.g.prepared_images.clearRetainingCapacity();
nc.view().frontend.native_images = true;
@@ -1498,13 +1412,11 @@ fn clientSession(init: std.process.Init, g: *Gui, opts_in: pardes.Options, test_
window.loop = &loop;
// A client spawns, watches and serves nothing: the Shell's tables are
// empty ones, there for what draws.
- var ptys: [pardes.MAX_PANES]?Pty = @splat(null);
- var gens: [pardes.MAX_PANES]u32 = @splat(0);
var queue: Queue = .{ .io = io, .gpa = gpa, .lsp_allocator = start.allocs.lsp, .wake_fn = sdlWake };
defer queue.deinit();
+ var ptys: host_io.Ptys = .{ .queue = &queue, .prompt_rcs = undefined };
var pipe_tasks: PipeTasks = .{};
- var watches: file_watch.Table = @splat(null);
- const prompt_rcs: host_io.Shell.PromptFiles = .{};
+ var no_watches: file_watch.Watches = .{ .io = io, .gpa = gpa, .queue = &queue };
var no_peers: replica.Peers = .{};
var shell: Shell = .{
.core = start.r.core(),
@@ -1512,13 +1424,10 @@ fn clientSession(init: std.process.Init, g: *Gui, opts_in: pardes.Options, test_
.io = io,
.gpa = gpa,
.lsp_allocator = start.allocs.lsp,
- .prompt_rcs = &prompt_rcs,
.ptys = &ptys,
- .gens = &gens,
.queue = &queue,
.pipe_tasks = &pipe_tasks,
- .inotify_fd = -1,
- .watches = &watches,
+ .watches = &no_watches,
.test_mode = test_mode,
.client = &window,
.peers = &no_peers,
@@ -2430,27 +2339,23 @@ fn pollGamepad(g: *Gui, in: *Input) void {
const Shell = struct {
core: *pardes.Pardes,
- /// The window's, while one is open; null while detached (`detached` has
- /// it).
+ /// The window's, while one is open; null once detached.
gui: ?*Gui = null,
- detached: ?*Gui = null,
- /// Shells a dead session left (Adopt), each waiting for the spawn of
- /// the terminal pane made for it.
- adoptions: host_io.Adoptions = .{},
io: std.Io,
gpa: std.mem.Allocator,
fs: ?*ninep_io.Listener = null,
lsp_allocator: std.mem.Allocator,
- prompt_rcs: *const host_io.Shell.PromptFiles,
- ptys: *[pardes.MAX_PANES]?Pty,
- gens: *[pardes.MAX_PANES]u32,
+ /// The session's ptys (runtime/session.zig's), reading into `queue`;
+ /// a client's, an empty table.
+ ptys: *host_io.Ptys,
queue: *Queue,
/// What drainQueue takes each wakeup, kept rather than rebuilt.
batch: Queue.Batch = .{},
pipe_tasks: *PipeTasks,
job_tasks: PipeTasks = .{},
- inotify_fd: c_int,
- watches: *file_watch.Table,
+ /// The session's file watches (runtime/session.zig's); a client's,
+ /// none.
+ watches: *file_watch.Watches,
threads_ok: bool = false,
test_mode: bool = false,
feed: StdinFeed = .{},
@@ -2485,50 +2390,12 @@ const Shell = struct {
took_input: bool = false,
held: ?c.SDL_Event = null,
- fn closePaneShell(ctx: ?*anyopaque, id: pardes.Pane.Id) void {
- const pane = id.index();
- shellOf(ctx).closePty(pane);
- }
-
- fn closePty(s: *Shell, pane: u8) void {
- const pt = if (s.ptys[pane]) |*pt| pt else return;
- // Out of the queue first, which lets go a reader waiting for room
- // in it; then its read is canceled (or, at its end, it is joined).
- s.queue.cancelReader(.at(pane), s.gens[pane]);
- if (pt.reader) |*reader| {
- reader.cancel(s.queue.io); // the Io it was started on (startReader)
- pt.reader = null;
- }
- _ = libc.close(pt.fd);
- daemon.closed(pt.pid);
- host_io.retireShell(pt.pid);
- s.ptys[pane] = null;
- }
-
- fn stopPtys(s: *Shell) void {
- for (0..s.ptys.len) |pane| s.closePty(@intCast(pane));
- for (s.gens) |*gen| gen.* +%= 1;
- }
-
- fn shutdownPtys(s: *Shell) void {
- s.stopPtys();
- host_io.waitRetired();
- }
-
- fn reconcilePtys(s: *Shell) void {
- for (s.ptys, 0..) |slot, pane| if (slot) |pt| {
- const current = s.core.panes[pane];
- if (current == null or current.?.serial != pt.serial or !current.?.isTerminal())
- s.closePty(@intCast(pane));
- };
- }
-
fn host(s: *Shell) pardes.Host {
return .{ .ctx = s, .vtable = &vtable };
}
/// Detach: the window closed, the session left running with no
- /// window, for `pardes-gui --attach` to open one again.
+ /// window, detached for good: an attach shows it as a client.
fn detachWindow(ctx: ?*anyopaque) void {
const s = shellOf(ctx);
// A replica client's: its link ends.
@@ -2575,41 +2442,19 @@ const Shell = struct {
fn closeTheWindow(s: *Shell) void {
const g = s.gui orelse return;
closeWindow(g);
- s.detached = g;
s.gui = null;
s.presented = false;
s.surface = null;
// Its clients look at it still (Peers keeps it attended).
s.peers.detached = true;
s.core.unattended = s.peers.count() == 0;
- daemon.setState(true);
- }
-
- fn openTheWindow(s: *Shell) void {
- const g = s.detached orelse return;
- if (!reopenWindow(g)) {
- log.err("--attach: no window: {s}", .{c.SDL_GetError()});
- return daemon.setState(true);
- }
- s.gui = g;
- s.detached = null;
- s.peers.detached = false;
- s.core.unattended = false;
- s.core.needs_frame = true;
- resetScroll(g);
- daemon.setState(false);
+ daemon.setDetached();
}
fn watched(ctx: ?*anyopaque) bool {
return shellOf(ctx).gui != null;
}
- fn adopt(ctx: ?*anyopaque, id: pardes.Pane.Id) void {
- const pane = id.index();
- const s = shellOf(ctx);
- s.adoptions.ask(s.core, pane);
- }
-
fn upgradeAsked(ctx: ?*anyopaque, id: pardes.Pane.Id) void {
const pane = id.index();
const s = shellOf(ctx);
@@ -2644,39 +2489,21 @@ const Shell = struct {
// the readers stopped (a reader waiting for room has it then), and
// what they pushed meanwhile drained.
s.drainQueue();
- for (s.ptys) |*slot| if (slot.*) |*pt| if (pt.reader) |*r| {
- r.cancel(s.queue.io);
- pt.reader = null;
- };
+ s.ptys.pause();
s.drainQueue();
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, .window = s.gui != null, .exe = path };
- for (s.ptys, 0..) |slot, id| if (slot) |pt| if (pt.fd >= 0) rec.addPty(id, pt.pid, pt.fd);
+ s.ptys.record(&rec);
var at_buf: [1024:0]u8 = undefined;
const failed = upgrade.dumpInto(core, &rec, &at_buf, &why) orelse upgrade.execAs(s.gpa, path, &rec, &at_buf, s.fs, &why);
// As it was: its ptys read on.
- for (s.ptys, 0..) |*slot, id| if (slot.*) |*pt| if (pt.fd >= 0 and pt.reader == null) {
- pt.reader = s.queue.startReader(.{ .handle = pt.fd, .flags = .{ .nonblocking = false } }, .at(id), s.gens[id]) catch null;
- };
+ s.ptys.readOn(core);
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;
- }
- s.ptys[k.pane] = .{ .fd = k.fd, .pid = k.pid, .serial = pane.?.serial, .cmd = .{ .watched = pane.?.command != null and host_io.watchExit(k.pid), .fd = k.fd } };
- }
- }
-
/// An upgraded session's window, its view's again; every other view
/// but a replica client's, kept for its rejoin (views.away), closes.
fn resumeWindow(s: *Shell) void {
@@ -2695,20 +2522,20 @@ const Shell = struct {
.poll_frame = pollFrame,
.watched = watched,
.detach = detachWindow,
- .adopt = adopt,
+ .adopt = PtyCalls.adopt,
.upgrade = upgradeAsked,
- .spawn = spawnPane,
- .pty_write = ptyWrite,
- .pty_resize = ptyResize,
- .pty_signal = ptySignal,
- .close_pty = closePaneShell,
- .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,
@@ -2721,13 +2548,12 @@ const Shell = struct {
.job = kindJob,
};
+ const PtyCalls = host_io.Ptys.Calls(Shell);
+ const WatchCalls = file_watch.Watches.Calls(Shell);
+
/// The command panes' exits, told once their output is in (host_io).
fn takeExits(s: *Shell) void {
- host_io.takeExits(s.core, s.ptys, s, closeWatched);
- }
-
- fn closeWatched(s: *Shell, id: usize) void {
- s.closePty(@intCast(id));
+ s.ptys.takeExits(s.core);
}
/// A client's queue holds its draws alone: each landed for its pane's
@@ -2745,7 +2571,6 @@ const Shell = struct {
}
fn drainQueue(s: *Shell) void {
- s.reconcilePtys();
// After this batch's output, which an exit is told behind.
defer s.takeExits();
s.queue.takeInto(&s.batch);
@@ -2753,48 +2578,9 @@ const Shell = struct {
if (msgs.len > 0) s.mail_only = false;
var check_files = false;
for (msgs.slice()) |m| switch (m) {
- .output => |o| {
- if (s.gens[o.pane.index()] == o.gen)
- s.core.update(.{ .output = .{ .pane = o.pane, .bytes = o.bytes } });
- s.gpa.free(o.bytes);
- },
- .eof => |e| {
- if (s.gens[e.pane.index()] == e.gen) eof: {
- if (e.failure) |err| {
- s.closePty(e.pane.index());
- s.core.readerFailed(e.pane, err);
- break :eof;
- }
- const pt = if (s.ptys[e.pane.index()]) |*pt| pt else {
- s.core.update(.{ .eof = .{ .pane = e.pane } });
- break :eof;
- };
- // 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(s.core, s.ptys, e.pane.index(), s, closeWatched);
- break :eof;
- }
- // 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 unwatched = if (s.core.panes[e.pane.index()]) |pane| pane.command != null else false;
- const status = host_io.exitStatus(pt.pid, 100);
- if (status != null) pt.pid = 0; // reaped: no shell to retire
- s.closePty(e.pane.index());
- if (unwatched or status != null) s.core.update(.{ .exited = .{ .pane = e.pane, .status = status } });
- s.core.update(.{ .eof = .{ .pane = e.pane } });
- }
- },
- .lsp => |l| {
- s.core.update(.{ .lsp_resp = .{ .id = l.id, .rows = l.rows } });
- if (l.rows) |rows| s.lsp_allocator.free(rows);
- },
- .lsp_status => |text| {
- var mbuf: [256]u8 = undefined;
- s.core.setStatus(.at(s.core.view().active), message.stamp(&mbuf, "lsp", text));
- s.lsp_allocator.free(text);
- },
+ .output => |o| s.ptys.output(s.core, o),
+ .eof => |e| s.ptys.eof(s.core, e),
+ .lsp, .lsp_status => s.queue.landLsp(s.core, m),
.pipe => |response_value| {
var response = response_value;
s.core.update(.{ .pipe_resp = .{
@@ -2820,11 +2606,9 @@ const Shell = struct {
},
.files_changed => check_files = true,
.fs_ready => {},
- .window => if (s.gui == null) s.openTheWindow(),
- .adopted => |a| s.adoptions.adoptShell(s.core, a.pid, a.fd),
+ .adopted => |a| s.ptys.adoptions.adoptShell(s.core, a.pid, a.fd),
};
- if (check_files and file_watch.reloadChanged(s.core, s.io, s.gpa, s.watches))
- s.queue.push(.files_changed);
+ if (check_files) s.watches.reload(s.core);
}
};
@@ -3026,11 +2810,10 @@ fn waitDetached(core: *pardes.Pardes, timeout_ms: u32) void {
fn pollFrame(ctx: ?*anyopaque) void {
const s = shellOf(ctx);
- s.reconcilePtys();
const core = s.core;
if (s.fs) |f| if (f.tick().pending) s.queue.push(.fs_ready);
// The authority owns its terminals even with its window closed.
- pollCwds(core, s.ptys);
+ s.ptys.pollCwds(core);
const g = s.gui orelse {
if (core.settings.window_opacity_pending) {
var unchanged_opacity: u8 = 100;
@@ -3330,68 +3113,12 @@ fn guiNow(ctx: ?*anyopaque) u64 {
return s.test_clock orelse s.paced_ns orelse c.SDL_GetTicksNS();
}
-fn spawnPane(ctx: ?*anyopaque, id: pardes.Pane.Id, cwd: []const u8) void {
- const pane = id.index();
- const s = shellOf(ctx);
- if (s.adoptions.take(id)) |a| 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;
- 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);
- };
- s.closePty(pane);
- if (s.ptys[pane] != null) {
- _ = libc.close(child.file.handle);
- host_io.retireShell(child.pid);
- return s.core.reportError(id, "shell", error.WorkersBusy);
- }
- s.gens[pane] +%= 1;
- const command = s.core.panes[pane].?.command != null;
- const pt: Pty = .{ .fd = child.file.handle, .pid = child.pid, .serial = s.core.panes[pane].?.serial, .cmd = .{ .watched = command and host_io.watchExit(child.pid), .fd = child.file.handle } };
- s.ptys[pane] = pt;
- var lbuf: [pardes.memory.limits.host_path_cap + 1]u8 = undefined;
- if (host_io.shellCwd(pt.pid, &lbuf)) |wd| s.core.setCwd(id, wd);
- if (!s.threads_ok) return;
- s.ptys[pane].?.reader = s.queue.startReader(.{ .handle = pt.fd, .flags = .{ .nonblocking = false } }, id, s.gens[pane]) catch |err| {
- s.closePty(pane);
- return s.core.reportError(id, "terminal reader", err);
- };
-}
-
-/// 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: host_io.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(.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) return;
- s.ptys[pane].?.reader = s.queue.startReader(.{ .handle = a.fd, .flags = .{ .nonblocking = false } }, .at(pane), s.gens[pane]) catch |err| {
- s.closePty(pane);
- return s.core.reportError(.at(pane), "terminal reader", err);
- };
-}
-
/// The daemon's thread: what it says, onto the queue (drainQueue).
fn deliverNote(ctx: *anyopaque, note: daemon.Note) void {
const s: *Shell = @ptrCast(@alignCast(ctx));
const q = s.queue;
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.tellStub(a.stub, "r{s}", .{"a window session takes no terminal"});
- if (a.tty < 0) q.push(.window);
- },
+ .relinked => q.wake(),
.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 } });
@@ -3401,78 +3128,10 @@ fn deliverNote(ctx: *anyopaque, note: daemon.Note) void {
}
}
-fn ptyWrite(ctx: ?*anyopaque, id: pardes.Pane.Id, bytes: []const u8) void {
- const pane = id.index();
- const s = shellOf(ctx);
- if (s.ptys[pane]) |pt| _ = host_io.writeFd(pt.fd, bytes);
-}
-
-fn ptyResize(ctx: ?*anyopaque, id: pardes.Pane.Id, cols: u16, rows: u16) void {
- const pane = id.index();
- const s = shellOf(ctx);
- if (s.ptys[pane]) |pt| {
- const ws = host_io.ptyWinsize(s.core, cols, rows);
- _ = posix.system.ioctl(pt.fd, TIOCSWINSZ, @intFromPtr(&ws));
- }
-}
-
-fn ptySignal(ctx: ?*anyopaque, id: pardes.Pane.Id, sig: pardes.PtySignal) void {
- const pane = id.index();
- const s = shellOf(ctx);
- // A command whose exit is recorded is reaped: its group may be another's.
- if (s.ptys[pane]) |pt| if (!pt.cmd.exited) host_io.signalTty(pt.pid, pt.fd, sig, pt.cmd.watched);
-}
-
-fn ttyTaken(ctx: ?*anyopaque, id: pardes.Pane.Id) bool {
- const pane = id.index();
- const s = shellOf(ctx);
- const pt = s.ptys[pane] orelse return false;
- return host_io.ttyTaken(pt.pid, pt.fd);
-}
-
-fn fgName(ctx: ?*anyopaque, id: pardes.Pane.Id, buf: []u8) ?[]const u8 {
- const pane = id.index();
- const s = shellOf(ctx);
- const pt = s.ptys[pane] orelse return null;
- return host_io.foregroundName(pt.pid, pt.fd, buf);
-}
-
-fn killJob(ctx: ?*anyopaque, id: pardes.Pane.Id) bool {
- const pane = id.index();
- const s = shellOf(ctx);
- const pt = s.ptys[pane] orelse return false;
- return host_io.killJob(pt.pid, pt.fd);
-}
-
-fn writeFile(ctx: ?*anyopaque, id: pardes.Pane.Id, path: []const u8, bytes: []const u8) void {
- const pane = id.index();
- const s = shellOf(ctx);
- host_io.writeFile(s.core, s.watches, pane, path, bytes);
-}
-
fn writeDump(ctx: ?*anyopaque, bytes: []const u8) void {
host_io.writeDump(shellOf(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 = shellOf(ctx);
- if (file_watch.applyEffect(s.core, s.io, s.inotify_fd, s.watches, pane, on, mode))
- s.queue.push(.files_changed);
-}
-
-fn watchTheme(ctx: ?*anyopaque, generation: u32, on: bool) void {
- const s = shellOf(ctx);
- if (file_watch.applyThemeEffect(
- s.core,
- s.gpa,
- s.inotify_fd,
- s.watches,
- generation,
- on,
- )) s.queue.push(.files_changed);
-}
-
fn dumpThemes(ctx: ?*anyopaque, id: pardes.Pane.Id) void {
const pane = id.index();
const s = shellOf(ctx);
@@ -3590,13 +3249,6 @@ fn handOver(ctx: ?*anyopaque, seq: u32, bytes: []const u8) void {
};
}
-fn pollCwds(core: *pardes.Pardes, ptys: *[pardes.MAX_PANES]?Pty) void {
- for (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.fd, core.settings.shell.effective.get(), &lbuf)) |cwd| core.setCwd(.at(id), cwd);
- };
-}
-
fn accumulateWheelDelta(pending: f32, raw_y: f32) f32 {
if (!std.math.isFinite(raw_y)) return pending;
const next = pending - raw_y;
@@ -6276,148 +5928,6 @@ test "installed Nerd Symbols fallback covers Yazi directory icons" {
try std.testing.expect(atlas.glyphForCodepoint(0xe5ff).glyph != 0);
}
-test "GUI PTY reader delivers a real shell tail before EOF and joins on close" {
- const gpa = std.testing.allocator;
- const core = try pardes.Pardes.init(gpa, .{ .tty_only = true });
- defer core.deinit();
- var queue: Queue = .{ .io = std.testing.io, .gpa = gpa, .lsp_allocator = gpa };
- defer queue.deinit();
- var ptys: [pardes.MAX_PANES]?Pty = @splat(null);
- var gens: [pardes.MAX_PANES]u32 = @splat(1);
- var shell: Shell = undefined;
- shell.core = core;
- shell.gpa = gpa;
- shell.ptys = &ptys;
- shell.gens = &gens;
- shell.queue = &queue;
- defer shell.shutdownPtys();
- const rcs: host_io.Shell.PromptFiles = .{};
- const child = try host_io.forkShell(null, 0, &rcs, "/bin/sh", "", 24, 80);
- ptys[0] = .{ .fd = child.file.handle, .pid = child.pid, .serial = core.panes[0].?.serial };
- ptys[0].?.reader = try queue.startReader(.{ .handle = ptys[0].?.fd, .flags = .{ .nonblocking = false } }, .at(0), 1);
- try std.testing.expect(host_io.writeFd(child.file.handle, "printf '\\120\\101\\122\\104\\105\\123\\055\\124\\101\\111\\114'; exit\n"));
- var bytes: std.ArrayList(u8) = .empty;
- defer bytes.deinit(gpa);
- var eof = false;
- const until = std.Io.Clock.awake.now(std.testing.io).toMilliseconds() + 2_000;
- while (!eof and std.Io.Clock.awake.now(std.testing.io).toMilliseconds() < until) {
- var batch = queue.take();
- defer for (batch.slice()) |msg| msg.deinit(gpa, gpa);
- for (batch.slice()) |msg| switch (msg) {
- .output => |o| {
- try std.testing.expect(!eof);
- try bytes.appendSlice(gpa, o.bytes);
- },
- .eof => |e| {
- try std.testing.expect(e.failure == null);
- eof = true;
- },
- else => return error.UnexpectedMessage,
- };
- if (!eof) try std.testing.io.sleep(.fromMilliseconds(1), .awake);
- }
- try std.testing.expect(eof);
- try std.testing.expect(std.mem.indexOf(u8, bytes.items, "PARDES-TAIL") != null);
- shell.closePty(0);
- try std.testing.expect(queue.readers[0] == null);
- try std.testing.expect(ptys[0] == null or ptys[0].?.reader == null);
- try std.testing.expectEqual(@as(c_int, -1), libc.fcntl(child.file.handle, libc.F.GETFD));
-}
-
-test "GUI PTY Restore joins a real reader waiting for queue space" {
- const gpa = std.testing.allocator;
- var core = try pardes.Pardes.init(gpa, .{ .tty_only = true });
- defer core.deinit();
- try dump.dumpState(core);
- var queue: Queue = .{ .io = std.testing.io, .gpa = gpa, .lsp_allocator = gpa };
- defer queue.deinit();
- queue.acceptReader(.at(1), 1);
- for (0..output_capacity) |_| queue.push(.{ .output = .{ .pane = .at(1), .gen = 1, .bytes = try gpa.dupe(u8, "other pane") } });
- var ptys: [pardes.MAX_PANES]?Pty = @splat(null);
- var gens: [pardes.MAX_PANES]u32 = @splat(1);
- var shell: Shell = undefined;
- shell.core = core;
- shell.gpa = gpa;
- shell.ptys = &ptys;
- shell.gens = &gens;
- shell.queue = &queue;
- defer shell.shutdownPtys();
- const rcs: host_io.Shell.PromptFiles = .{};
- const child = try host_io.forkShell(null, 0, &rcs, "/bin/sh", "", 24, 80);
- ptys[0] = .{ .fd = child.file.handle, .pid = child.pid, .serial = core.panes[0].?.serial };
- ptys[0].?.reader = try queue.startReader(.{ .handle = ptys[0].?.fd, .flags = .{ .nonblocking = false } }, .at(0), 1);
- try std.testing.expect(host_io.writeFd(child.file.handle, "printf 'after-full'; exit\n"));
- try host_io.PtyTests.waitBlocked(&queue);
- const old_serial = core.panes[0].?.serial;
- const replacement = try dump.restore(core, core.dump_out.?, "test");
- shell.stopPtys();
- core.deinit();
- core = replacement;
- shell.core = replacement;
- // The dump's pane, its serial too; its old shell stopped all the same.
- try std.testing.expectEqual(old_serial, core.panes[0].?.serial);
- try std.testing.expectEqual(@as(usize, 0), queue.waiting);
- try std.testing.expect(queue.readers[0] == null);
- try std.testing.expectEqual(@as(c_int, -1), libc.fcntl(child.file.handle, libc.F.GETFD));
- queue.cancelReader(.at(1), 1);
- queue.acceptReader(.at(0), gens[0]);
- queue.push(.{ .eof = .{ .pane = .at(0), .gen = 1 } });
- try std.testing.expect(queue.pushOutput(.at(0), gens[0], try gpa.dupe(u8, "fresh")));
- var batch = queue.take();
- defer for (batch.slice()) |msg| msg.deinit(gpa, gpa);
- try std.testing.expectEqual(@as(usize, 1), batch.len);
- try std.testing.expectEqualStrings("fresh", batch.items[0].output.bytes);
-}
-
-test "GUI PTY deletion joins an idle reader and its shell is reaped by exit" {
- const gpa = std.testing.allocator;
- const core = try pardes.Pardes.init(gpa, .{ .tty_only = true });
- defer core.deinit();
- var queue: Queue = .{ .io = std.testing.io, .gpa = gpa, .lsp_allocator = gpa };
- defer queue.deinit();
- var ptys: [pardes.MAX_PANES]?Pty = @splat(null);
- var gens: [pardes.MAX_PANES]u32 = @splat(1);
- var shell: Shell = undefined;
- shell.core = core;
- shell.gpa = gpa;
- shell.ptys = &ptys;
- shell.gens = &gens;
- shell.queue = &queue;
- defer shell.shutdownPtys();
- const rcs: host_io.Shell.PromptFiles = .{};
- const child = try host_io.forkShell(null, 0, &rcs, "/bin/sh", "", 24, 80);
- ptys[0] = .{ .fd = child.file.handle, .pid = child.pid, .serial = core.panes[0].?.serial };
- ptys[0].?.reader = try queue.startReader(.{ .handle = ptys[0].?.fd, .flags = .{ .nonblocking = false } }, .at(0), 1);
- try core.removePane(0, null);
- shell.reconcilePtys();
- try std.testing.expect(queue.readers[0] == null);
- try std.testing.expectEqual(@as(usize, 0), queue.waiting);
- try std.testing.expectEqual(@as(usize, 0), queue.take().len);
- try std.testing.expectEqual(@as(c_int, -1), libc.fcntl(child.file.handle, libc.F.GETFD));
- shell.shutdownPtys();
- try std.testing.expectEqual(@as(libc.pid_t, -1), libc.waitpid(child.pid, null, libc.W.NOHANG));
- try std.testing.expectEqual(libc.E.CHILD, libc.errno(-1));
-}
-
-test "GUI PTY file watcher stops and joins without closing its watched descriptor" {
- if (!file_watch.supported) return error.SkipZigTest;
- const gpa = std.testing.allocator;
- var queue: Queue = .{ .io = std.testing.io, .gpa = gpa, .lsp_allocator = gpa };
- defer queue.deinit();
- const fd = file_watch.init(true);
- if (fd < 0) return error.WatchInitFailed;
- defer _ = libc.close(fd);
- const stop = try stopPipe();
- defer for (stop) |pipe_fd| {
- _ = libc.close(pipe_fd);
- };
- const thread = try std.Thread.spawn(.{}, watchThread, .{ fd, stop[0], &queue });
- _ = host_io.writeFd(stop[1], "x");
- thread.join();
- try std.testing.expect(libc.fcntl(fd, libc.F.GETFD) >= 0);
- try std.testing.expectEqual(@as(usize, 0), queue.take().len);
-}
-
test "GUI completion failure survives backlog and leaves the document unchanged" {
const gpa = std.testing.allocator;
const core = try pardes.Pardes.init(gpa, .{ .tty_only = true });
@@ -6435,14 +5945,12 @@ test "GUI completion failure survives backlog and leaves the document unchanged"
.bytes = try gpa.dupe(u8, "output"),
} });
queue.push(.{ .lsp = .{ .id = id, .rows = null } });
- var gens: [pardes.MAX_PANES]u32 = @splat(1);
- var ptys: [pardes.MAX_PANES]?Pty = @splat(null);
+ var ptys: host_io.Ptys = .{ .queue = &queue, .prompt_rcs = undefined, .gens = @splat(1) };
var shell: Shell = undefined;
shell.core = core;
shell.queue = &queue;
shell.gpa = gpa;
shell.lsp_allocator = gpa;
- shell.gens = &gens;
shell.ptys = &ptys;
shell.drainQueue();
try std.testing.expect(core.lsp_ask.wait == null);
@@ -8165,16 +7673,14 @@ test "a detached GUI authority follows terminal directory changes with no window
_ = core.settings.shell.effective.set("/bin/sh");
var queue: Queue = .{ .io = io, .gpa = gpa, .lsp_allocator = gpa };
defer queue.deinit();
- var ptys: [pardes.MAX_PANES]?Pty = @splat(null);
- var gens: [pardes.MAX_PANES]u32 = @splat(1);
const rcs: host_io.Shell.PromptFiles = .{};
+ var ptys: host_io.Ptys = .{ .queue = &queue, .prompt_rcs = &rcs, .gens = @splat(1) };
+ defer ptys.deinit();
var pipes: PipeTasks = .{};
- var watches: file_watch.Table = @splat(null);
var no_peers: replica.Peers = .{};
- var shell: Shell = .{ .core = core, .io = io, .gpa = gpa, .lsp_allocator = gpa, .prompt_rcs = &rcs, .ptys = &ptys, .gens = &gens, .queue = &queue, .pipe_tasks = &pipes, .inotify_fd = -1, .watches = &watches, .peers = &no_peers };
- defer shell.shutdownPtys();
+ var shell: Shell = .{ .core = core, .io = io, .gpa = gpa, .lsp_allocator = gpa, .ptys = &ptys, .queue = &queue, .pipe_tasks = &pipes, .watches = undefined, .peers = &no_peers };
const child = try host_io.forkShell(null, 0, &rcs, "/bin/sh", start, 24, 80);
- ptys[0] = .{ .fd = child.file.handle, .pid = child.pid, .serial = core.panes[0].?.serial };
+ ptys.slots[0] = .{ .fd = child.file.handle, .pid = child.pid };
try std.testing.expect(host_io.writeFd(child.file.handle, "cd child\n"));
const until = std.Io.Clock.awake.now(io).toMilliseconds() + 2_000;
var actual: [4096]u8 = undefined;
diff --git a/dev/host_io.zig b/dev/host_io.zig
index f86c3250..5465fc7a 100644
--- a/dev/host_io.zig
+++ b/dev/host_io.zig
@@ -197,6 +197,8 @@ pub const Fallback = struct {
/// a language query since superseded, are dropped here.
pub const Inbox = @import("Inbox.zig");
+pub const Ptys = @import("Ptys.zig");
+
pub const Lsp = @import("Lsp.zig");
pub const Shell = @import("Shell.zig");
diff --git a/dev/root.zig b/dev/root.zig
index 2c70783f..fb1d1ad9 100644
--- a/dev/root.zig
+++ b/dev/root.zig
@@ -26,9 +26,10 @@ test {
_ = glide;
// The frontends', which main.zig's test block collected: a shell's
// build (shell-test); the core without a terminal never compiled them.
- if (comptime @import("term_options").terminal) {
- if (comptime @import("pardes_config").platform == .tui) _ = tui;
- if (comptime @import("pardes_config").platform == .gui) _ = gui;
+ if (comptime @import("pardes_options").terminal) {
+ if (comptime @import("pardes_options").platform == .tui) _ = tui;
+ if (comptime @import("pardes_options").platform == .gui) _ = gui;
_ = vaxis_input;
+ _ = host_io.Ptys;
}
}
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);
}
}