summaryrefslogtreecommitdiff
path: root/src/detached/server.zig
diff options
context:
space:
mode:
Diffstat (limited to 'src/detached/server.zig')
-rw-r--r--src/detached/server.zig645
1 files changed, 387 insertions, 258 deletions
diff --git a/src/detached/server.zig b/src/detached/server.zig
index ac9af2ee..d7dda6ba 100644
--- a/src/detached/server.zig
+++ b/src/detached/server.zig
@@ -4,18 +4,20 @@ const builtin = @import("builtin");
const libc = std.c;
const posix = std.posix;
const pardes = @import("../pardes.zig");
+const dump = @import("../dump.zig");
const wire = @import("wire.zig");
const host_io = @import("../host_io.zig");
const selection_pipe = @import("../selection_pipe.zig");
const file_watch = @import("../file_watch.zig");
+const ShaderBuild = @import("../ShaderBuild.zig");
const ninep_io = @import("../9p_io.zig");
const look = @import("../look.zig");
-const message = pardes.Pardes.Message;
+const message = pardes.Messages.Message;
const TIOCSWINSZ: c_int = @bitCast(@as(u32, if (@hasDecl(posix.T, "IOCSWINSZ")) posix.T.IOCSWINSZ else 0x80087467));
@@ -62,6 +64,8 @@ const Client = struct {
mirror: std.ArrayListUnmanaged(pardes.Cell) = .empty,
need_full: bool = true,
accepted_ms: i64 = 0,
+ /// The post chain last sent (Session.sendPost); null: none yet.
+ post_sent: ?u64 = null,
};
const Pty = struct {
@@ -69,61 +73,18 @@ const Pty = struct {
pid: posix.pid_t = 0,
kill_at: i64 = 0,
out: std.ArrayListUnmanaged(u8) = .empty,
+ /// A command pane's child, watched to its exit (host_io.watchExit);
+ /// the pty stays open, unpolled after its end of file, until both its
+ /// end of file and its exit.
+ cmd: host_io.CommandWatch = .{},
};
-const RetiredShell = struct { pid: posix.pid_t = 0, kill_at: i64 = 0 };
-
-const Completion = union(enum) {
- lsp: struct { id: u32, rows: ?[]u8 },
- pipe: selection_pipe.Response,
-
- fn deinit(completion: *Completion, gpa: std.mem.Allocator) void {
- switch (completion.*) {
- .lsp => |result| if (result.rows) |rows| gpa.free(rows),
- .pipe => |*result| result.deinit(gpa),
- }
- }
-};
-
-const Mailbox = struct {
- const capacity = selection_pipe.Tasks.capacity + 1;
- const Batch = struct {
- items: [capacity]Completion = undefined,
- len: usize = 0,
- status: ?[]u8 = null,
- };
-
- mutex: std.atomic.Mutex = .unlocked,
- batch: Batch = .{},
- wake: [2]c_int = .{ -1, -1 },
-
- fn post(box: *Mailbox, completion: Completion) void {
- while (!box.mutex.tryLock()) std.atomic.spinLoopHint();
- // Tasks retain their slot until the owner consumes their one completion.
- std.debug.assert(box.batch.len < capacity);
- box.batch.items[box.batch.len] = completion;
- box.batch.len += 1;
- box.mutex.unlock();
- box.signal();
- }
-
- fn signal(box: *Mailbox) void {
- while (libc.send(box.wake[1], "w", 1, nosignal) < 0) {
- if (libc.errno(-1) != .INTR) break;
- }
- }
+/// A watched child exited, or a worker finished: wake the loop.
+fn wakeForExit(ctx: ?*anyopaque) void {
+ Session.signal(@ptrCast(@alignCast(ctx.?)));
+}
- fn take(box: *Mailbox) Batch {
- var bytes: [128]u8 = undefined;
- while (libc.recv(box.wake[0], &bytes, bytes.len, 0) > 0) {}
- while (!box.mutex.tryLock()) std.atomic.spinLoopHint();
- defer box.mutex.unlock();
- const batch = box.batch;
- box.batch.len = 0;
- box.batch.status = null;
- return batch;
- }
-};
+const RetiredShell = struct { pid: posix.pid_t = 0, kill_at: i64 = 0 };
const Source = union(enum) {
listener,
@@ -139,6 +100,8 @@ pub const Session = struct {
worker_gpa: std.mem.Allocator,
io: std.Io,
core: *pardes.Pardes,
+ /// PARDES_TEST_CLOCK's virtual time (host_io.testClock).
+ test_clock: ?u64 = null,
listener: c_int = -1,
path_buf: [sun_path_len]u8 = undefined,
path_len: usize = 0,
@@ -149,16 +112,21 @@ pub const Session = struct {
scratch: std.ArrayListUnmanaged(u8) = .empty,
ptys: [pardes.MAX_PANES]Pty = @splat(.{}),
retired_shells: [pardes.MAX_PANES]RetiredShell = @splat(.{}),
- mailbox: Mailbox = .{},
- lsp_task: ?host_io.Lsp.Task = null,
+ /// The workers' answers (initAsync sets it up); `wake` is what wakes
+ /// the loop's poll for them, and for a watched child's exit.
+ inbox: host_io.Inbox = undefined,
+ wake: [2]c_int = .{ -1, -1 },
pipe_tasks: selection_pipe.Tasks = .{},
prompt_rcs: host_io.Shell.PromptFiles = .{},
inotify_fd: c_int = -1,
ninep: ?*ninep_io.Listener = null,
ninep_pending: bool = false,
- /// Set by the 9P runner's tasks: a request waits for `tick`.
+ /// A 9P request changed the core since the wake byte was last drained:
+ /// the next poll returns at once, to draw it.
ninep_wake: std.atomic.Value(bool) = .init(false),
watches: file_watch.Table = @splat(null),
+ /// The post chain's files, compiled here for the GUIs attached.
+ shaders: ShaderBuild = .{},
check_files: bool = false,
in_loop: bool = false,
greet_deadline_ms: u32 = greet_deadline_default_ms,
@@ -172,42 +140,50 @@ pub const Session = struct {
};
for (pair) |fd| {
if (libc.fcntl(fd, libc.F.SETFD, @as(c_int, 1)) < 0) return error.SocketOptionFailed;
- const flags = libc.fcntl(fd, libc.F.GETFL, @as(c_int, 0));
- if (flags < 0) return error.SocketOptionFailed;
- var options: libc.O = @bitCast(@as(u32, @bitCast(flags)));
- options.NONBLOCK = true;
- if (libc.fcntl(fd, libc.F.SETFL, @as(c_int, @bitCast(@as(u32, @bitCast(options))))) < 0)
- return error.SocketOptionFailed;
+ if (!setNonblock(fd)) return error.SocketOptionFailed;
if (comptime darwin) {
const on: c_int = 1;
if (libc.setsockopt(fd, libc.SOL.SOCKET, libc.SO.NOSIGPIPE, &on, @sizeOf(c_int)) != 0)
return error.SocketOptionFailed;
}
}
- s.mailbox.wake = pair;
- pardes.lsp.setStatusSink(s, lspStatus);
+ s.wake = pair;
+ s.inbox = .{ .gpa = s.worker_gpa, .lsp_allocator = s.worker_gpa, .io = s.io, .wake_fn = wakeForExit, .wake_ctx = s };
+ pardes.lsp.setStatusSink(&s.inbox, host_io.Inbox.lspStatus);
+ host_io.setExitWake(s, wakeForExit);
+ }
+
+ fn signal(s: *Session) void {
+ while (libc.send(s.wake[1], "w", 1, nosignal) < 0) {
+ if (libc.errno(-1) != .INTR) break;
+ }
}
fn cancelWorkers(s: *Session) void {
- if (s.lsp_task) |*task| {
- task.future.cancel(s.io) catch {};
- s.lsp_task = null;
+ if (s.wake[0] < 0) return; // no initAsync: no workers
+ if (s.inbox.lsp_task) |*task| {
+ task.future.cancel(s.io);
+ s.inbox.lsp_task = null;
}
s.pipe_tasks.cancelAll(s.io);
+ // Its worker may be waiting on the inbox for room.
+ s.core.stream.cancelTask();
_ = s.drainCompletions(false);
}
fn drainCompletions(s: *Session, apply_results: bool) bool {
- var batch = s.mailbox.take();
- for (batch.items[0..batch.len]) |*completion| {
- defer completion.deinit(s.worker_gpa);
+ var bytes: [128]u8 = undefined;
+ while (libc.recv(s.wake[0], &bytes, bytes.len, 0) > 0) {}
+ var batch = s.inbox.take();
+ for (batch.slice()) |msg| {
+ defer msg.deinit(s.worker_gpa, s.worker_gpa);
if (!apply_results) continue;
- switch (completion.*) {
+ switch (msg) {
.lsp => |result| {
s.core.update(.{ .lsp_resp = .{ .id = result.id, .rows = result.rows } });
- if (s.lsp_task) |*task| if (task.id == result.id) {
- task.future.await(s.io) catch {};
- s.lsp_task = null;
+ if (s.inbox.lsp_task) |*task| if (task.id == result.id) {
+ task.future.await(s.io);
+ s.inbox.lsp_task = null;
};
},
.pipe => |result| {
@@ -219,28 +195,31 @@ pub const Session = struct {
} });
s.pipe_tasks.finish(s.io, result.id);
},
+ .lsp_status => |status| {
+ var buf: [256]u8 = undefined;
+ s.core.setStatus(s.core.active, message.stamp(&buf, "lsp", status));
+ },
+ .search => |b| s.core.update(.{ .search = b }),
+ // Ptys are read in the loop's own poll, not through the inbox.
+ // No hand_over host entry here (a session with no window): none comes.
+ .output, .eof, .files_changed, .fs_ready, .handed => {},
}
}
- if (batch.status) |status| {
- defer s.worker_gpa.free(status);
- if (apply_results) {
- var buf: [256]u8 = undefined;
- s.core.setStatus(s.core.active, message.stamp(&buf, "lsp", status));
- }
- }
- return batch.len != 0 or batch.status != null;
+ return batch.len != 0;
}
- pub fn restore(s: *Session, bytes: []const u8) !void {
- const replacement = try s.core.restore(bytes);
+ pub fn restore(s: *Session, bytes: []const u8, from: []const u8) !void {
+ const replacement = try dump.restore(s.core, bytes, from);
s.cancelWorkers();
for (0..s.ptys.len) |pane| s.closePty(@intCast(pane));
s.harvest();
for (0..pardes.MAX_PANES) |pane|
file_watch.watchPane(s.inotify_fd, &s.watches, @intCast(pane), null, 0, .{ .text = 0 });
_ = file_watch.applyThemeEffect(s.core, s.gpa, s.inotify_fd, &s.watches, 0, false, false);
+ // The new core's chain generations are its own.
+ s.shaders.generation = null;
s.check_files = false;
- if (s.ninep) |listener| listener.reset(s.core);
+ if (s.ninep) |listener| listener.reset(replacement);
s.ninep_pending = false;
replacement.host = s.host();
s.core.deinit();
@@ -248,16 +227,20 @@ pub const Session = struct {
for (&s.clients) |*client| if (client.attached) {
client.need_full = true;
};
- s.mailbox.signal();
+ s.signal();
}
pub fn deinit(s: *Session) void {
- if (s.mailbox.wake[0] >= 0) pardes.lsp.setStatusSink(null, null);
+ // First: its compile thread wakes the loop, whose socket closes below.
+ s.shaders.deinit(s.gpa, s.inotify_fd, &s.watches);
+ if (s.wake[0] >= 0) pardes.lsp.setStatusSink(null, null);
+ if (s.wake[0] >= 0) host_io.setExitWake(null, null);
s.cancelWorkers();
- for (s.mailbox.wake) |fd| if (fd >= 0) {
+ if (s.wake[0] >= 0) s.inbox.close();
+ for (s.wake) |fd| if (fd >= 0) {
_ = libc.close(fd);
};
- s.mailbox.wake = .{ -1, -1 };
+ s.wake = .{ -1, -1 };
if (s.ninep) |l| {
l.deinit(s.gpa);
s.ninep = null;
@@ -317,7 +300,7 @@ pub const Session = struct {
_ = libc.close(fd);
return false;
}
- setNonblock(fd);
+ _ = setNonblock(fd);
s.listener = fd;
s.path_len = path.len;
return true;
@@ -341,15 +324,25 @@ pub const Session = struct {
return @ptrCast(@alignCast(ctx.?));
}
+ fn clockNow(ctx: ?*anyopaque) u64 {
+ const s = of(ctx);
+ return s.test_clock orelse @intCast(std.Io.Clock.awake.now(s.io).nanoseconds);
+ }
+
const vtable: host_io.Host.VTable = .{
.wait_input = waitInput,
+ .now = clockNow,
.present = present,
.poll_frame = pollFrame,
+ .watched = watched,
.spawn = spawn,
.pty_write = ptyWrite,
.pty_resize = ptyResize,
.pty_signal = ptySignal,
+ .close_pty = closePaneShell,
.tty_taken = ttyTaken,
+ .fg_name = fgName,
+ .kill_job = killJob,
.write_file = writeFile,
.write_dump = writeDump,
.watch_file = watchFile,
@@ -361,70 +354,25 @@ pub const Session = struct {
.detach = detach,
.lsp = lspRequest,
.pipe = pipeRequest,
+ .search = searchRequest,
};
- fn lspRequest(ctx: ?*anyopaque, request: host_io.Lsp.Request) void {
+ fn searchRequest(ctx: ?*anyopaque, gen: u32) void {
const s = of(ctx);
- _ = s.drainCompletions(true);
- if (s.lsp_task) |*task| {
- task.future.cancel(s.io) catch {};
- s.lsp_task = null;
- _ = s.drainCompletions(true);
- }
- const job = host_io.Lsp.snapshot(s.worker_gpa, s.core, request) catch |err| {
- s.core.update(.{ .lsp_resp = .{ .id = request.id, .rows = null } });
- return s.core.reportError(request.pane, "lsp", err);
- };
- const future = s.io.concurrent(lspWorker, .{ s.worker_gpa, job, &s.mailbox }) catch |err| {
- job.free(s.worker_gpa);
- s.core.update(.{ .lsp_resp = .{ .id = request.id, .rows = null } });
- return s.core.reportError(request.pane, "lsp", err);
- };
- s.lsp_task = .{ .id = request.id, .future = future };
- }
-
- fn lspWorker(gpa: std.mem.Allocator, job: *host_io.Lsp.Job, box: *Mailbox) anyerror!void {
- host_io.Lsp.work(gpa, job, box, deliverLspRows);
+ if (s.wake[0] < 0) return pardes.Stream.runHere(s.core, gen);
+ pardes.Stream.start(s.io, s.worker_gpa, s.core, gen, &s.inbox, host_io.Inbox.pushSearch);
}
- fn deliverLspRows(ctx: ?*anyopaque, id: u32, rows: ?[]u8) void {
- const box: *Mailbox = @ptrCast(@alignCast(ctx.?));
- box.post(.{ .lsp = .{ .id = id, .rows = rows } });
- }
-
- fn lspStatus(ctx: ?*anyopaque, text: []const u8) void {
+ fn lspRequest(ctx: ?*anyopaque, request: host_io.Lsp.Request) void {
const s = of(ctx);
- const copy = s.worker_gpa.dupe(u8, text) catch return;
- while (!s.mailbox.mutex.tryLock()) std.atomic.spinLoopHint();
- if (s.mailbox.batch.status) |old| s.worker_gpa.free(old);
- s.mailbox.batch.status = copy;
- s.mailbox.mutex.unlock();
- s.mailbox.signal();
+ _ = s.drainCompletions(true);
+ s.inbox.startLsp(s.core, request);
}
fn pipeRequest(ctx: ?*anyopaque, id: u32) void {
const s = of(ctx);
_ = s.drainCompletions(true);
- if (s.pipe_tasks.full()) {
- s.core.update(.{ .pipe_resp = .{ .id = id, .success = false, .outputs = &.{} } });
- return;
- }
- const request = s.core.pipeRequest(id) orelse return;
- const job = selection_pipe.Job.copy(s.worker_gpa, request) catch |err| {
- s.core.update(.{ .pipe_resp = .{ .id = id, .success = false, .outputs = &.{} } });
- return s.core.reportError(s.core.active, "pipe", err);
- };
- const future = s.io.concurrent(pipeWorker, .{ s.io, s.worker_gpa, job, &s.mailbox }) catch |err| {
- job.deinit(s.worker_gpa);
- s.core.update(.{ .pipe_resp = .{ .id = id, .success = false, .outputs = &.{} } });
- return s.core.reportError(s.core.active, "pipe", err);
- };
- std.debug.assert(s.pipe_tasks.add(.{ .id = id, .future = future }));
- }
-
- fn pipeWorker(io: std.Io, gpa: std.mem.Allocator, job: *selection_pipe.Job, box: *Mailbox) anyerror!void {
- defer job.deinit(gpa);
- box.post(.{ .pipe = selection_pipe.runJob(gpa, io, job) });
+ selection_pipe.start(s.io, s.worker_gpa, s.core, &s.pipe_tasks, id, &s.inbox, host_io.Inbox.pushPipe);
}
fn primary(s: *Session) ?*Client {
@@ -451,9 +399,11 @@ pub const Session = struct {
fn spawn(ctx: ?*anyopaque, pane: u8, cwd: []const u8) void {
const s = of(ctx);
if (pane >= s.ptys.len) return; // the core indexes its own panes
- s.closePty(pane);
s.harvest();
- if (s.ptys[pane].pid != 0) return s.core.reportError(pane, "shell", error.ShellClosing);
+ // 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].fd >= 0;
+ if (!running and s.ptys[pane].pid != 0) return s.core.reportError(pane, "shell", error.ShellClosing);
for (s.retired_shells) |shell| {
if (shell.pid == 0) break;
} else return s.core.reportError(pane, "shell", error.ShellClosing);
@@ -466,11 +416,25 @@ pub const Session = struct {
s.core.screen_h,
s.core.screen_w,
s.ninep,
- ) catch |err| return s.core.reportError(pane, "shell", err);
- s.ptys[pane] = .{ .fd = child.file.handle, .pid = child.pid };
- setNonblock(child.file.handle);
+ ) catch |err| {
+ if (running) return s.core.restartFailed(pane, err);
+ return s.core.shellFailed(pane, err);
+ };
+ s.closePty(pane);
+ s.harvest();
+ if (s.ptys[pane].pid != 0) {
+ _ = libc.close(child.file.handle);
+ host_io.retireShell(child.pid);
+ return s.core.reportError(pane, "shell", error.ShellClosing);
+ }
+ const command = if (s.core.panes[pane]) |pn| pn.command != null else false;
+ s.ptys[pane] = .{ .fd = child.file.handle, .pid = child.pid, .cmd = .{ .watched = command and host_io.watchExit(child.pid), .fd = child.file.handle } };
+ _ = setNonblock(child.file.handle);
var lbuf: [pardes.memory.limits.host_path_cap + 1]u8 = undefined;
- if (host_io.shellCwd(child.pid, &lbuf)) |wd| s.core.setCwd(pane, wd);
+ // 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(pane, wd);
}
fn ptyWrite(ctx: ?*anyopaque, pane: u8, bytes: []const u8) void {
@@ -478,7 +442,8 @@ pub const Session = struct {
if (pane >= s.ptys.len) return;
const pt = &s.ptys[pane];
if (pt.fd < 0) return;
- if (pt.out.items.len > pty_backlog) {
+ // The bound holds with this write in: queued and new together.
+ if (pt.out.items.len + bytes.len > pty_backlog) {
var mbuf: [256]u8 = undefined;
const text = std.fmt.bufPrint(
&mbuf,
@@ -498,7 +463,9 @@ pub const Session = struct {
if (pane >= s.ptys.len) return;
const fd = s.ptys[pane].fd;
if (fd < 0) return;
- const ws: posix.winsize = .{ .row = rows, .col = cols, .xpixel = 0, .ypixel = 0 };
+ // In pixels too, at the last frontend's cell size (8x16 before
+ // one attached): a program sizes its kitty graphics by them.
+ const ws = host_io.ptyWinsize(s.core, cols, rows);
_ = posix.system.ioctl(fd, TIOCSWINSZ, @intFromPtr(&ws));
}
@@ -506,8 +473,9 @@ pub const Session = struct {
const s = of(ctx);
if (pane >= s.ptys.len) return;
const pt = s.ptys[pane];
- if (pt.fd < 0) return;
- host_io.signalTty(pt.pid, pt.fd, sig);
+ // A command whose exit is recorded is reaped: its group may be another's.
+ if (pt.fd < 0 or pt.cmd.exited) return;
+ host_io.signalTty(pt.pid, pt.fd, sig, pt.cmd.watched);
}
fn ttyTaken(ctx: ?*anyopaque, pane: u8) bool {
@@ -518,26 +486,29 @@ pub const Session = struct {
return host_io.ttyTaken(pt.pid, pt.fd);
}
+ fn fgName(ctx: ?*anyopaque, pane: u8, buf: []u8) ?[]const u8 {
+ const s = of(ctx);
+ if (pane >= s.ptys.len) return null;
+ const pt = s.ptys[pane];
+ if (pt.fd < 0) return null;
+ return host_io.foregroundName(pt.pid, pt.fd, buf);
+ }
+
+ fn killJob(ctx: ?*anyopaque, pane: u8) bool {
+ const s = of(ctx);
+ if (pane >= s.ptys.len) return false;
+ const pt = s.ptys[pane];
+ if (pt.fd < 0) return false;
+ return host_io.killJob(pt.pid, pt.fd);
+ }
+
fn writeFile(ctx: ?*anyopaque, pane: u8, path: []const u8, bytes: []const u8) void {
const s = of(ctx);
- filesystem.write(s.core, path, bytes) catch |err|
- return s.core.saveFailed(pane, "save", err);
- if (s.core.panes[pane]) |pn| if (pn.file) |f| if (std.mem.eql(u8, f.path, path)) {
- if (s.watches[pane]) |*w| if (w.serial == pn.serial) switch (w.generation) {
- .text => w.generation = .{ .text = std.hash.Wyhash.hash(0, bytes) },
- .pdf => {},
- };
- };
- var mbuf: [256]u8 = undefined;
- s.core.setMessage(pane, message.stamp(&mbuf, "saved", path));
+ host_io.writeFile(s.core, &s.watches, pane, path, bytes);
}
fn writeDump(ctx: ?*anyopaque, bytes: []const u8) void {
- const s = of(ctx);
- var pbuf: [1024:0]u8 = undefined;
- const path = pardes.dump.outPath(&pbuf) orelse return;
- filesystem.write(s.core, path, bytes) catch |err| return s.core.reportError(0, "dump", err);
- s.core.setLastDump(path);
+ host_io.writeDump(of(ctx).core, bytes);
}
fn watchFile(ctx: ?*anyopaque, pane: u8, _: []const u8, on: bool, mode: pardes.WatchMode) void {
@@ -554,14 +525,7 @@ pub const Session = struct {
fn dumpThemes(ctx: ?*anyopaque, pane: u8) void {
const s = of(ctx);
- const config_dir = s.core.opts.config_dir orelse return;
- const out_dir = pardes.config.User.dumpThemes(s.io, s.gpa, config_dir, pardes.themes) catch |err| {
- s.core.reportError(pane, "dump themes", err);
- return;
- };
- defer s.gpa.free(out_dir);
- var mbuf: [256]u8 = undefined;
- s.core.setMessage(pane, message.stamp(&mbuf, "dumped themes", out_dir));
+ host_io.dumpThemes(s.core, s.io, s.gpa, pane);
}
fn setClipboard(ctx: ?*anyopaque, text: []const u8) void {
@@ -579,7 +543,11 @@ pub const Session = struct {
fn openLink(ctx: ?*anyopaque, url: []const u8) void {
const s = of(ctx);
if (s.origins()) |c| return s.send(c, .{ .open_link = url });
+ // No frontend: the session's own desktop is nobody's to open a
+ // browser on. Kept, and said, so a script sees the look land.
s.core.fallback.setLink(url);
+ var said: [320]u8 = undefined;
+ s.core.setMessage(s.core.active, std.fmt.bufPrint(&said, "look: {s}: no frontend attached to open it in a browser", .{url}) catch "look: no frontend attached to open a link");
}
fn detach(ctx: ?*anyopaque) void {
@@ -587,23 +555,34 @@ pub const Session = struct {
if (s.origins()) |c| s.send(c, .detach);
}
- /// The 9P runner has a request for `tick`: wake the poll loop.
+ /// A 9P request changed the core: wake the poll loop to draw it.
fn wakeNinep(ctx: ?*anyopaque) void {
const s = of(ctx);
s.ninep_wake.store(true, .release);
- s.mailbox.signal();
+ s.signal();
+ }
+
+ fn watched(ctx: ?*anyopaque) bool {
+ const s = of(ctx);
+ for (&s.clients) |*c| if (c.attached) return true;
+ return false;
}
fn pollFrame(ctx: ?*anyopaque) void {
const s = of(ctx);
- if (s.ninep) |l| s.ninep_pending = l.tick(s.core).pending;
+ if (s.ninep) |l| s.ninep_pending = l.tick().pending;
for (&s.ptys, 0..) |*pt, pane| {
if (pt.fd < 0) continue;
var lbuf: [pardes.memory.limits.host_path_cap + 1]u8 = undefined;
- if (host_io.shellCwd(pt.pid, &lbuf)) |cwd| s.core.setCwd(pane, cwd);
+ if (host_io.ttyCwd(pt.pid, pt.fd, s.core.settings.shell.effective.get(), &lbuf)) |cwd| s.core.setCwd(pane, cwd);
}
}
+ fn closePaneShell(ctx: ?*anyopaque, pane: u8) void {
+ const s = of(ctx);
+ if (pane < s.ptys.len) s.closePty(pane);
+ }
+
fn closePty(s: *Session, pane: u8) void {
const pt = &s.ptys[pane];
if (pt.fd < 0) return;
@@ -613,7 +592,7 @@ pub const Session = struct {
pt.out = .empty;
if (pt.pid == 0) return;
_ = libc.kill(pt.pid, libc.SIG.HUP);
- pt.kill_at = monotonicMs() + 100;
+ pt.kill_at = std.Io.Clock.awake.now(s.io).toMilliseconds() + 100;
s.harvest();
if (pt.pid == 0) return;
for (&s.retired_shells) |*shell| if (shell.pid == 0) {
@@ -662,27 +641,35 @@ pub const Session = struct {
}
fn paneEof(s: *Session, pane: u8) void {
+ const pt = &s.ptys[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(s.core, &s.ptys, pane, s, 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 unwatched = if (s.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
s.closePty(pane);
s.harvest();
+ if (unwatched or status != null) s.core.update(.{ .exited = .{ .pane = pane, .status = status } });
s.core.update(.{ .eof = .{ .pane = pane } });
}
- fn harvest(s: *Session) void {
- const now = monotonicMs();
- for (&s.retired_shells) |*shell| reapShell(&shell.pid, &shell.kill_at, now);
- for (&s.ptys) |*pty| if (pty.fd < 0) reapShell(&pty.pid, &pty.kill_at, now);
+ /// The command panes' exits, told once their output is in (host_io).
+ fn takeExits(s: *Session) void {
+ host_io.takeExits(s.core, &s.ptys, s, closeWatched);
}
- fn reapShell(pid: *posix.pid_t, kill_at: *i64, now: i64) void {
- if (pid.* == 0) return;
- const result = libc.waitpid(pid.*, null, libc.W.NOHANG);
- if (result > 0 or (result < 0 and libc.errno(result) == .CHILD)) {
- pid.* = 0;
- kill_at.* = 0;
- } else if (kill_at.* != 0 and now >= kill_at.*) {
- _ = libc.kill(pid.*, libc.SIG.KILL);
- kill_at.* = 0;
- }
+ fn closeWatched(s: *Session, id: usize) void {
+ s.closePty(@intCast(id));
+ }
+
+ fn harvest(s: *Session) void {
+ const now = std.Io.Clock.awake.now(s.io).toMilliseconds();
+ for (&s.retired_shells) |*shell| host_io.reapRetired(&shell.pid, &shell.kill_at, now);
+ for (&s.ptys) |*pty| if (pty.fd < 0) host_io.reapRetired(&pty.pid, &pty.kill_at, now);
}
fn inotify(s: *Session) c_int {
@@ -698,6 +685,7 @@ pub const Session = struct {
fn reloadWatched(s: *Session) void {
if (!s.check_files) return;
s.check_files = false;
+ s.shaders.recheck();
for (0..reload_retries) |_| {
if (!file_watch.reloadChanged(s.core, s.io, s.gpa, &s.watches)) return;
}
@@ -714,7 +702,7 @@ pub const Session = struct {
fn sendFrame(s: *Session, c: *Client, surface: *const pardes.Surface) void {
const cells = surface.cells;
- const want = wire.frameBound(surface.cols, surface.rows) + wire.layersBound(&surface.body_layers, &surface.tag_layers);
+ const want = wire.frameBound(surface.cols, surface.rows) + wire.layersBound(&surface.body_layers, &surface.tag_layers, surface.regionList());
s.scratch.ensureTotalCapacity(s.gpa, want) catch return s.close(c, .oom);
const prev: []const pardes.Cell = if (c.need_full or c.mirror.items.len != cells.len)
&.{}
@@ -734,6 +722,8 @@ pub const Session = struct {
prev,
&surface.body_layers,
&surface.tag_layers,
+ surface.regionList(),
+ surface.chrome,
) catch |err| {
log.debug("frame {d}x{d} not encodable: {t}", .{ surface.cols, surface.rows, err });
return;
@@ -753,13 +743,19 @@ pub const Session = struct {
const completed = s.ninep_wake.swap(false, .acq_rel) or drained;
for (&s.clients) |*c| if (c.fd >= 0) s.flush(c);
const regridded = s.reconcile();
+ // After the greeting reconcile sends: a chain before it is refused.
+ const compiled = s.sendPost();
+ // Nobody attached, nobody to dismiss a message: the loop expires
+ // them itself, between the editor's steps (expireUnattended).
+ s.core.unattended = s.primary() == null;
+ pardes.Messages.expireUnattended(s.core);
- const now = monotonicMs();
+ const now = std.Io.Clock.awake.now(s.io).toMilliseconds();
var fds: [poll_slots]libc.pollfd = undefined;
var src: [poll_slots]Source = undefined;
var n: usize = 0;
- if (s.mailbox.wake[0] >= 0) {
- fds[n] = .{ .fd = s.mailbox.wake[0], .events = poll_in, .revents = 0 };
+ if (s.wake[0] >= 0) {
+ fds[n] = .{ .fd = s.wake[0], .events = poll_in, .revents = 0 };
src[n] = .completion;
n += 1;
}
@@ -780,7 +776,7 @@ pub const Session = struct {
n += 1;
}
for (&s.ptys, 0..) |*pt, pane| {
- if (pt.fd < 0) continue;
+ if (pt.fd < 0 or pt.cmd.eof) continue;
fds[n] = .{
.fd = pt.fd,
.events = if (pt.out.items.len != 0) poll_in | poll_out else poll_in,
@@ -796,7 +792,7 @@ pub const Session = struct {
}
if (s.ninep) |l| {
// Unix and TCP connections run on cloud9's runner, which wakes
- // this loop through the mailbox; only QUIC is polled here.
+ // this loop through `wake`; only QUIC is polled here.
if (comptime ninep_io.quic_enabled) {
if (l.quic) |*listener| {
fds[n] = listener.poll();
@@ -805,14 +801,30 @@ pub const Session = struct {
}
}
}
- if (n == 0) return nap(if (timeout_ms == 0) 16 else timeout_ms);
+ // The wait is the 9P connections' turn with the core.
+ if (n == 0) {
+ pardes.turn.rest();
+ s.io.sleep(.fromMilliseconds(if (timeout_ms == 0) 16 else timeout_ms), .awake) catch {};
+ pardes.turn.wake();
+ if (timeout_ms != 0) if (s.test_clock) |*virtual| {
+ virtual.* = @max(virtual.*, s.core.nextWake() orelse virtual.*);
+ };
+ return;
+ }
var timeout: c_int = if (timeout_ms == 0) -1 else @intCast(@min(timeout_ms, std.math.maxInt(c_int)));
if (s.nextWake(now)) |due| timeout = if (timeout < 0) due else @min(timeout, due);
- if (completed or s.check_files or regridded or s.ninep_pending) timeout = 0;
+ if (completed or compiled or s.check_files or regridded or s.ninep_pending) timeout = 0;
+ pardes.turn.rest();
const ready = libc.poll(&fds, @intCast(n), timeout);
+ pardes.turn.wake();
if (ready > 0) s.dispatch(fds[0..n], src[0..n]);
+ // The core's wake ran out; the pump advances it from `now`.
+ if (timeout_ms != 0 and std.Io.Clock.awake.now(s.io).toMilliseconds() -| now >= timeout_ms) if (s.test_clock) |*virtual| {
+ virtual.* = @max(virtual.*, s.core.nextWake() orelse virtual.*);
+ };
_ = s.drainCompletions(true);
- s.expire(monotonicMs());
+ s.takeExits();
+ s.expire(std.Io.Clock.awake.now(s.io).toMilliseconds());
s.harvest();
s.reloadWatched();
_ = s.reconcile();
@@ -849,7 +861,6 @@ pub const Session = struct {
}
fn nextWake(s: *const Session, now: i64) ?c_int {
- if (now == 0) return null; // no clock; see `monotonicMs`
var due: ?i64 = null;
for (s.retired_shells) |shell| if (shell.pid != 0) {
due = now + 10;
@@ -872,6 +883,11 @@ pub const Session = struct {
due = if (due) |d| @min(d, at9) else at9;
}
}
+ // Unattended messages go on the clock: look again in a while.
+ if (s.core.unattended) for (s.core.panes) |slot| if (slot) |pane| if (pane.msg_len > 0) {
+ due = if (due) |d| @min(d, now + 100) else now + 100;
+ break;
+ };
const at = due orelse return null;
return @intCast(@max(0, @min(at - now, std.math.maxInt(c_int))));
}
@@ -891,13 +907,13 @@ pub const Session = struct {
switch (libc.errno(fd)) {
.AGAIN, .INTR, .CONNABORTED => return,
else => {
- s.accept_paused_ms = monotonicMs() + accept_pause_ms;
+ s.accept_paused_ms = std.Io.Clock.awake.now(s.io).toMilliseconds() + accept_pause_ms;
return;
},
}
}
ninep_io.setCloexec(fd);
- setNonblock(fd);
+ _ = setNonblock(fd);
if (comptime darwin) {
const on: c_int = 1;
_ = libc.setsockopt(fd, libc.SOL.SOCKET, libc.SO.NOSIGPIPE, &on, @sizeOf(c_int));
@@ -909,7 +925,7 @@ pub const Session = struct {
_ = libc.close(fd);
continue;
};
- s.clients[slot] = .{ .fd = fd, .accepted_ms = monotonicMs() };
+ s.clients[slot] = .{ .fd = fd, .accepted_ms = std.Io.Clock.awake.now(s.io).toMilliseconds() };
}
}
@@ -946,7 +962,7 @@ pub const Session = struct {
}
fn apply(s: *Session, c: *Client, slot: u8, tag: u8, payload: []const u8) wire.Error!void {
- if (tag == @intFromEnum(wire.ClientTag.hello)) {
+ if (tag == @backingInt(wire.ClientTag.hello)) {
if (c.attached) return error.BadValue;
const claimed = try wire.helloVersion(payload);
if (claimed != wire.version) {
@@ -962,6 +978,9 @@ pub const Session = struct {
c.attached = true;
c.need_full = true;
c.greet = true;
+ // Unwatched until now, it may have drawn nothing: a frame
+ // for the one attaching (watched).
+ s.core.needs_frame = true;
},
.bye => s.close(c, .bye),
.event => |ev| {
@@ -990,7 +1009,9 @@ pub const Session = struct {
rows = if (rows == 0) c.rows else @min(rows, c.rows);
}
var regridded = false;
- if (cols != 0 and (cols != s.cols or rows != s.rows)) {
+ // Against the core's size too: a root ctl `size` may have set it
+ // while nobody was attached.
+ if (cols != 0 and (cols != s.cols or rows != s.rows or cols != s.core.screen_w or rows != s.core.screen_h)) {
s.cols = cols;
s.rows = rows;
for (&s.clients) |*c| c.need_full = true;
@@ -1005,6 +1026,28 @@ pub const Session = struct {
return regridded;
}
+ /// Compiles the post chain's files (a finished compile wakes the loop
+ /// through `wake`) and sends each attached frontend the chain it
+ /// has not seen: on attach, and when it or a file's SPIR-V changes. True
+ /// when a compile was taken in, so the loop draws what it said.
+ /// ponytail: a terminal frontend is sent it too and drops it; a hello
+ /// saying which frontend it is would spare those bytes.
+ fn sendPost(s: *Session) bool {
+ const files = for (s.core.settings.post.list()) |entry| {
+ if (entry.scene == null) break true;
+ } else false;
+ const compiled = s.shaders.sync(s.gpa, s.io, s.core, if (files) s.inotify() else s.inotify_fd, &s.watches, .{ .ctx = s, .call = wakeForExit });
+ const key = @as(u64, s.shaders.revision) << 8 | @backingInt(s.core.settings.shader_animation);
+ var chain: wire.Post = .{ .animation = s.core.settings.shader_animation, .len = s.core.settings.post.len };
+ _ = s.shaders.view(&s.core.settings.post, &chain.passes);
+ for (&s.clients) |*c| {
+ if (!c.attached or c.greet or c.post_sent == key) continue;
+ c.post_sent = key;
+ s.send(c, .{ .post = chain });
+ }
+ return compiled;
+ }
+
fn send(s: *Session, c: *Client, msg: wire.ServerMsg) void {
const want = wire.serverBound(msg);
s.scratch.ensureTotalCapacity(s.gpa, want) catch return s.close(c, .oom);
@@ -1015,6 +1058,9 @@ pub const Session = struct {
s.queue(c, bytes);
}
+ /// A client's queued output is at most `out_backlog + wire.max_payload`:
+ /// past the backlog it is closed, and one frame lands on top of it first
+ /// (a frame bigger than the backlog must still go out whole).
fn queue(s: *Session, c: *Client, bytes: []const u8) void {
if (c.out.items.len > out_backlog) return s.close(c, .backlog);
s.account();
@@ -1068,6 +1114,7 @@ pub const Session = struct {
fn refuseFd(_: *Session, fd: c_int, why: wire.Refusal) void {
var buf: [wire.header_len + 1]u8 = undefined;
+ // unreachable: a refusal is a header and one byte, which buf is sized to
const bytes = wire.encodeServer(&buf, .{ .refuse = why }) catch unreachable;
var off: usize = 0;
while (off < bytes.len) {
@@ -1093,11 +1140,43 @@ pub const Session = struct {
}
};
+/// SIGTERM, SIGINT or SIGHUP: quit as Exit does, through the loop, so its
+/// sockets are unlinked on the way out rather than left for the next
+/// session to trip on. The handler only sets the flag and wakes the loop.
+var quit_signalled = std.atomic.Value(bool).init(false);
+var quit_wake: c_int = -1;
+
+fn onQuitSignal(_: std.posix.SIG) callconv(.c) void {
+ quit_signalled.store(true, .release);
+ if (quit_wake >= 0) _ = libc.send(quit_wake, "q", 1, nosignal);
+}
+
+/// The screen of a detached session no frontend has sized.
+pub const detached_cols = 160;
+pub const detached_rows = 50;
+
pub fn run(init: std.process.Init, opts: pardes.Options, name: []const u8) !void {
+ // A name a live session holds: said, exit 1, before anything is made
+ // (no error trace, no second session racing the first for the socket).
+ if (comptime supported) {
+ var path_buf: [path_max]u8 = undefined;
+ if (sessionPath(&path_buf, name)) |path| if (ninep_io.statNoFollow(path) != null and alive(path)) {
+ var said: [path_max + 64]u8 = undefined;
+ const text = std.fmt.bufPrint(&said, "pardes: a session named {s} is already running\n", .{name}) catch "pardes: a session of that name is already running\n";
+ std.Io.File.stderr().writeStreamingAll(init.io, text) catch {};
+ std.process.exit(1);
+ };
+ }
const gpa = init.gpa;
const allocs = pardes.memory.init(gpa);
defer pardes.memory.deinit();
var options = opts;
+ // No frontend yet, so no size to take: one roomy enough for a script's
+ // panes (80x24 left pane/new refused after a few); `size` sets another,
+ // and an attaching frontend its own.
+ options.cols = detached_cols;
+ options.rows = detached_rows;
+ options.detached_session = true;
options.image_allocator = allocs.image;
options.pdf_allocator = allocs.pdf;
options.tree_sitter_allocator = allocs.tree_sitter;
@@ -1115,7 +1194,7 @@ pub fn run(init: std.process.Init, opts: pardes.Options, name: []const u8) !void
const core = if (options.load_path) |lp| blk: {
const bytes = try filesystem.readFile(gpa, lp);
defer gpa.free(bytes);
- break :blk try pardes.Pardes.initFromDump(allocs.pardes, options, bytes);
+ break :blk try pardes.dump.initFromDump(allocs.pardes, options, bytes);
} else try pardes.Pardes.init(allocs.pardes, options);
var session: Session = .{
.gpa = gpa,
@@ -1125,40 +1204,62 @@ pub fn run(init: std.process.Init, opts: pardes.Options, name: []const u8) !void
.cols = options.cols,
.rows = options.rows,
.prompt_rcs = host_io.Shell.prepare(),
+ .test_clock = host_io.testClock(),
};
defer session.core.deinit();
defer session.deinit();
try session.initAsync();
if (!session.listen(name)) {
try std.Io.File.stderr().writeStreamingAll(init.io, "pardes: could not bind a detached session socket\n");
- return error.NoSocket;
+ std.process.exit(1);
}
- session.ninep = ninep_io.listen(init.io, gpa, opts.ninep_name, name, opts.ninep_tcp, opts.ninep_quic);
+ session.ninep = ninep_io.listen(init.io, gpa, core, opts.ninep_name, name, opts.ninep_tcp, opts.ninep_quic);
if (session.ninep == null) return error.ListenFailed;
- session.ninep.?.setWake(&session, Session.wakeNinep);
- core.fs.socket_path = session.ninep.?.path();
- core.fs.tcp_address = session.ninep.?.tcp_address;
- core.fs.quic_address = session.ninep.?.quic_address;
+ session.ninep.?.wake_ctx = &session;
+ session.ninep.?.wake = Session.wakeNinep;
const h = session.host();
core.host = h;
while (core.nextEffect()) |effect| core.perform(effect);
session.in_loop = true;
- while (!session.core.quit) {
+ quit_wake = session.wake[1];
+ const on_quit: std.posix.Sigaction = .{ .handler = .{ .handler = onQuitSignal }, .mask = std.posix.sigemptyset(), .flags = 0 };
+ for ([_]std.posix.SIG{ .HUP, .INT, .TERM }) |sig| std.posix.sigaction(sig, &on_quit, null);
+ defer quit_wake = -1;
+ while (!session.core.quit and !quit_signalled.load(.acquire)) {
+ pardes.turn.bump(&pardes.turn.restores);
try session.core.pump(h);
if (session.core.quit) break;
if (session.core.takeRestore()) |path| restore: {
- const bytes = filesystem.readRestore(gpa, path) catch |err| {
+ const bytes = filesystem.readRestore(gpa, path, session.core.settings.dump_dir.get()) catch |err| {
session.core.reportError(session.core.active, "Restore", err);
break :restore;
};
defer gpa.free(bytes);
- session.restore(bytes) catch |err| session.core.reportError(session.core.active, "Restore", err);
+ session.restore(bytes, path) catch |err| session.core.reportError(session.core.active, "Restore", err);
}
}
}
+test "a link looked at with no frontend attached opens no browser, and says so" {
+ const gpa = std.testing.allocator;
+ var s: Session = .{
+ .gpa = gpa,
+ .worker_gpa = gpa,
+ .io = std.testing.io,
+ .core = try pardes.Pardes.init(gpa, .{ .tty_only = true, .cols = 40, .rows = 12 }),
+ .cols = 40,
+ .rows = 12,
+ };
+ defer s.core.deinit();
+ defer s.deinit();
+ Session.openLink(&s, "https://example.com/x");
+ try std.testing.expectEqualStrings("https://example.com/x", s.core.fallback.link.items);
+ const pane = s.core.panes[s.core.active].?;
+ try std.testing.expectEqualStrings("look: https://example.com/x: no frontend attached to open it in a browser", pane.msg[0..pane.msg_len]);
+}
+
test "detached queued results preserve current requests and are discarded before Restore" {
const gpa = std.testing.allocator;
var s: Session = .{
@@ -1178,24 +1279,27 @@ test "detached queued results preserve current requests and are discarded before
const old_id = s.core.lsp_wait.?.id;
s.core.lspRequest(0, .status, "");
const current_id = s.core.lsp_wait.?.id;
- s.lsp_task = .{ .id = current_id, .future = .{ .any_future = null, .result = {} } };
- s.mailbox.post(.{ .lsp = .{ .id = old_id, .rows = try gpa.dupe(u8, "old result\n") } });
- try std.testing.expect(s.drainCompletions(true));
- try std.testing.expectEqual(current_id, s.lsp_task.?.id);
+ s.inbox.lsp_id = current_id;
+ s.inbox.lsp_task = .{ .id = current_id, .future = .{ .any_future = null, .result = {} } };
+ // The inbox turns the superseded answer away.
+ s.inbox.push(.{ .lsp = .{ .id = old_id, .rows = try gpa.dupe(u8, "old result\n") } });
+ try std.testing.expectEqual(@as(usize, 0), s.inbox.completion_len);
+ _ = s.drainCompletions(true);
+ try std.testing.expectEqual(current_id, s.inbox.lsp_task.?.id);
try std.testing.expectEqual(current_id, s.core.lsp_wait.?.id);
- try s.core.dumpState();
+ try dump.dumpState(s.core);
const saved = try gpa.dupe(u8, s.core.dump_out.?);
defer gpa.free(saved);
while (s.core.nextEffect()) |_| {}
- s.mailbox.post(.{ .lsp = .{ .id = current_id, .rows = try gpa.dupe(u8, "queued before restore\n") } });
+ s.inbox.push(.{ .lsp = .{ .id = current_id, .rows = try gpa.dupe(u8, "queued before restore\n") } });
const outputs = try gpa.alloc([]u8, 1);
outputs[0] = try gpa.dupe(u8, "old filter output\n");
try std.testing.expect(s.pipe_tasks.add(.{ .id = 77, .future = .{ .any_future = null, .result = {} } }));
- s.mailbox.post(.{ .pipe = .{ .id = 77, .success = true, .outputs = outputs } });
- Session.lspStatus(&s, "old status");
- try s.restore(saved);
- try std.testing.expect(s.lsp_task == null);
+ s.inbox.push(.{ .pipe = .{ .id = 77, .success = true, .outputs = outputs } });
+ host_io.Inbox.lspStatus(&s.inbox, "old status");
+ try s.restore(saved, "test");
+ try std.testing.expect(s.inbox.lsp_task == null);
try std.testing.expectEqual(@as(usize, 0), s.pipe_tasks.len);
try std.testing.expect(!s.drainCompletions(true));
try std.testing.expectEqualStrings("saved body\n", s.core.panes[0].?.file.?.content);
@@ -1203,18 +1307,57 @@ test "detached queued results preserve current requests and are discarded before
s.core.lspRequest(0, .status, "");
const restored_id = s.core.lsp_wait.?.id;
try std.testing.expect(restored_id > current_id);
- s.lsp_task = .{ .id = restored_id, .future = .{ .any_future = null, .result = {} } };
- s.mailbox.post(.{ .lsp = .{ .id = current_id, .rows = try gpa.dupe(u8, "late old result\n") } });
+ s.inbox.lsp_id = restored_id;
+ s.inbox.lsp_task = .{ .id = restored_id, .future = .{ .any_future = null, .result = {} } };
+ s.inbox.push(.{ .lsp = .{ .id = current_id, .rows = try gpa.dupe(u8, "late old result\n") } });
_ = s.drainCompletions(true);
- try std.testing.expectEqual(restored_id, s.lsp_task.?.id);
+ try std.testing.expectEqual(restored_id, s.inbox.lsp_task.?.id);
try std.testing.expectEqual(restored_id, s.core.lsp_wait.?.id);
- s.mailbox.post(.{ .lsp = .{ .id = restored_id, .rows = &.{} } });
+ s.inbox.push(.{ .lsp = .{ .id = restored_id, .rows = &.{} } });
const host = s.host();
host.vtable.wait_input.?(host.ctx, 1);
- try std.testing.expect(s.lsp_task == null);
+ try std.testing.expect(s.inbox.lsp_task == null);
try std.testing.expect(s.core.lsp_wait == null);
}
+test "a detached session's terminal pane takes its shell with it when it closes" {
+ const gpa = std.testing.allocator;
+ var s: Session = .{
+ .gpa = gpa,
+ .worker_gpa = gpa,
+ .io = std.testing.io,
+ .core = try pardes.Pardes.init(gpa, .{ .tty_only = true, .cols = 40, .rows = 12 }),
+ .cols = 40,
+ .rows = 12,
+ };
+ defer s.core.deinit();
+ defer s.deinit();
+ // A stand-in shell: it waits for a signal, and a hangup ends it.
+ const pid = libc.fork();
+ if (pid == 0) while (true) {
+ _ = libc.poll(&[0]libc.pollfd{}, 0, -1);
+ };
+ try std.testing.expect(pid > 0);
+ var fds: [2]c_int = undefined;
+ try std.testing.expectEqual(@as(c_int, 0), libc.pipe(&fds));
+ defer _ = libc.close(fds[1]);
+ s.ptys[3] = .{ .fd = fds[0], .pid = pid };
+ const host = s.host();
+ host.vtable.close_pty.?(host.ctx, 3);
+ try std.testing.expect(s.ptys[3].fd < 0);
+ const deadline = std.Io.Clock.awake.now(std.testing.io).toMilliseconds() + 2000;
+ while (std.Io.Clock.awake.now(std.testing.io).toMilliseconds() < deadline) {
+ s.harvest();
+ const running = s.ptys[3].pid != 0 or for (s.retired_shells) |shell| {
+ if (shell.pid == pid) break true;
+ } else false;
+ if (!running) break;
+ _ = libc.poll(&[0]libc.pollfd{}, 0, 5);
+ }
+ try std.testing.expect(s.ptys[3].pid == 0);
+ for (s.retired_shells) |shell| try std.testing.expect(shell.pid != pid);
+}
+
test "detached worker setup failure completes requests without changing document bytes" {
const gpa = std.testing.allocator;
var failing = std.testing.FailingAllocator.init(gpa, .{ .fail_index = 0 });
@@ -1235,16 +1378,16 @@ test "detached worker setup failure completes requests without changing document
s.core.lspRequest(0, .status, "");
while (s.core.nextEffect()) |effect| s.core.perform(effect);
try std.testing.expect(s.core.lsp_wait == null);
- try std.testing.expect(s.lsp_task == null);
+ try std.testing.expect(s.inbox.lsp_task == null);
- pane.cur_col = 2;
- pane.vsel = .{ .active = true, .row = 0, .col = 0, .explicit = true };
+ pane.body.cur_col = 2;
+ pane.body.vsel = .{ .active = true, .row = 0, .col = 0, .explicit = true };
s.core.update(.{ .key = .{ .cp = '|' } });
s.core.update(.{ .key = .{ .cp = 't', .text = "tr a-z A-Z" } });
s.core.update(.{ .key = .{ .cp = pardes.Key.enter } });
- try std.testing.expect(s.core.pipe_wait != null);
+ try std.testing.expect(s.core.pipe.wait != null);
while (s.core.nextEffect()) |effect| s.core.perform(effect);
- try std.testing.expect(s.core.pipe_wait == null);
+ try std.testing.expect(s.core.pipe.wait == null);
try std.testing.expectEqual(@as(usize, 0), s.pipe_tasks.len);
try std.testing.expectEqualStrings("one\n", pane.file.?.content);
try std.testing.expect(failing.has_induced_failure);
@@ -1252,12 +1395,12 @@ test "detached worker setup failure completes requests without changing document
pub const setCloexec = ninep_io.setCloexec;
-pub fn setNonblock(fd: c_int) void {
+pub fn setNonblock(fd: c_int) bool {
const flags = libc.fcntl(fd, libc.F.GETFL, @as(c_int, 0));
- if (flags < 0) return;
+ if (flags < 0) return false;
var o: libc.O = @bitCast(@as(u32, @bitCast(flags)));
o.NONBLOCK = true;
- _ = libc.fcntl(fd, libc.F.SETFL, @as(c_int, @bitCast(@as(u32, @bitCast(o)))));
+ return libc.fcntl(fd, libc.F.SETFL, @as(c_int, @bitCast(@as(u32, @bitCast(o))))) >= 0;
}
pub const nosignal: u32 = if (darwin) 0 else libc.MSG.NOSIGNAL;
@@ -1273,20 +1416,6 @@ fn retire(gpa: std.mem.Allocator, list: *std.ArrayListUnmanaged(u8)) void {
list.clearAndFree(gpa);
}
-pub fn monotonicMs() i64 {
- var ts: libc.timespec = undefined;
- if (libc.clock_gettime(.MONOTONIC, &ts) != 0) return 0;
- return @as(i64, ts.sec) * std.time.ms_per_s + @divTrunc(ts.nsec, std.time.ns_per_ms);
-}
-
-fn nap(ms: u32) void {
- var ts: libc.timespec = .{
- .sec = @intCast(ms / 1000),
- .nsec = @intCast((ms % 1000) * std.time.ns_per_ms),
- };
- _ = libc.nanosleep(&ts, null);
-}
-
pub fn socketPath(buf: *[sun_path_len]u8, dir: []const u8, name: []const u8) ?[:0]const u8 {
if (name.len == 0) return null;
if (std.mem.indexOfAny(u8, name, "/\x00") != null) return null;
@@ -1330,7 +1459,7 @@ fn alive(path: [:0]const u8) bool {
if (fd < 0) return true;
defer _ = libc.close(fd);
ninep_io.setCloexec(fd);
- setNonblock(fd);
+ _ = setNonblock(fd);
const rc = libc.connect(fd, @ptrCast(&addr), @sizeOf(@TypeOf(addr)));
if (rc == 0) return true;
return libc.errno(rc) != .CONNREFUSED;