summaryrefslogtreecommitdiff
path: root/src/main.zig
diff options
context:
space:
mode:
authorGabriel Schneider <[email protected]>2026-10-30 17:35:06 -0300
committerGabriel Schneider <[email protected]>2026-10-30 17:35:06 -0300
commit6d8da8721141284cf33bb901168b26135893eb86 (patch)
tree791d63401d4e85fbca1d597a8ce0326e70efd545 /src/main.zig
parentefd43a3a2cf03bb741366331158b368abf9ac583 (diff)
parentbf6810a8f9d6cc82050e7d9c0cfb06358301b574 (diff)
downloadpardes-6d8da8721141284cf33bb901168b26135893eb86.tar.gz
pardes-6d8da8721141284cf33bb901168b26135893eb86.zip
Merge latest upstream into the macOS branch for Zig 0.17
Retain the macOS branch history and local Acme selection color while adopting upstream's current core and platform changes. Pin Zig and ZLS to 0.17.0, and fetch the existing zstbi compatibility commit through upstream after its original fork was removed.
Diffstat (limited to 'src/main.zig')
-rw-r--r--src/main.zig473
1 files changed, 446 insertions, 27 deletions
diff --git a/src/main.zig b/src/main.zig
index 4b1910bd..4e6b49bb 100644
--- a/src/main.zig
+++ b/src/main.zig
@@ -16,7 +16,11 @@ pub const std_options_debug_io: std.Io = if (is_emscripten)
else
std_options_debug_threaded_io.?.io();
-pub const std_options: std.Options = .{ .logFn = logFn };
+// Every thread's alternate signal stack is a threadlocal that libc zeroes as
+// the thread starts, so std's 256 KiB made each 9P connection's thread cost
+// that much resident. A stack-overflow segfault on a thread still printed its
+// whole symbolized trace from 32 KiB up (16 KiB double-faulted): 64 KiB.
+pub const std_options: std.Options = .{ .logFn = logFn, .signal_stack_size = 64 * 1024 };
fn logFn(
comptime level: std.log.Level,
@@ -46,11 +50,14 @@ pub const debug = if (is_emscripten) struct {} else struct {
};
const help_text =
- \\Usage: pardes [options] [file|dir]
+ \\Usage: pardes [options] [file|dir|-]
\\
\\With no arguments the shell pane starts in tty mode. A FILE argument
\\(optionally file:LINE) opens it alone, filling the window; a DIRECTORY
- \\argument becomes the cwd shells spawn in.
+ \\argument becomes the cwd shells spawn in. `-` reads stdin into a +Pager
+ \\pane, its colours kept (PagerColor) and every other escape dropped:
+ \\inside a pardes pane the outer session's, returning at once (a
+ \\terminal's PAGER), else a new editor's.
\\
\\Options:
\\ --tty start as one shell pane already in tty mode
@@ -58,6 +65,12 @@ const help_text =
\\ A FILE argument boots just that file instead.
\\ --tty-toggle <key> use Ctrl-<key> to toggle tty/editor mode
\\ -l <dump.zon> load a dump of another instance (see Dump)
+ \\ -w, --wait inside a pardes pane, hand FILE to the outer
+ \\ session and return only once the pane it opened
+ \\ (or already had) is deleted: 0 then, 1 if the
+ \\ session goes away. For $EDITOR (acme's E):
+ \\ EDITOR='pardes --wait', which GIT_EDITOR follows.
+ \\ Outside pardes a session blocks anyway.
\\ --nested run a full session even inside another pardes.
\\ Without it, a pardes started inside a pardes
\\ hands its FILE argument to the outer one. This
@@ -87,11 +100,179 @@ const help_text =
\\ see the same screen
\\ --attach=<name> ...of the session called <name>, which is what to
\\ use when more than one is running
+ \\ --geometry=WxH[+X+Y] the window's size in points, and where it goes
+ \\ where the display lets a window say (X11)
\\ -h, --help show this help and exit
\\ --version print the version and exit
\\
;
+/// `pardes -` inside a session: `text`, stdin as it came, escapes and all,
+/// into a new +Pager of the directory (/pager):
+/// written after the directory on that one open, the session parses it
+/// (pager.zig) and puts it in as one undo step, left clean. A text the
+/// session would not take is never lost: it goes to stderr, a terminal,
+/// with why, and the exit is 1.
+fn pageInto(io: std.Io, gpa: std.mem.Allocator, dial: []const u8, text: []const u8) void {
+ const Fail = struct {
+ fn with(o: std.Io, t: []const u8, what: []const u8, err: anyerror) noreturn {
+ var words_buf: [128]u8 = undefined;
+ const why = if (err == error.Remote) ninep_io.Client.lastSaid() else forwardWords(err, &words_buf);
+ var buf: [512]u8 = undefined;
+ const head = std.fmt.bufPrint(&buf, "pardes: -: {s}: {s}; the text follows\n", .{ what, why }) catch "pardes: -: refused; the text follows\n";
+ std.Io.File.stderr().writeStreamingAll(o, head) catch {};
+ std.Io.File.stderr().writeStreamingAll(o, t) catch {};
+ std.process.exit(1);
+ }
+ };
+ // The pane's directory: this one, unless its name could not be one line
+ // of a ctl (a newline, a control byte): then the session's.
+ var cwd_buf: [4096]u8 = undefined;
+ const cwd: []const u8 = if (std.c.getcwd(&cwd_buf, cwd_buf.len)) |c| std.mem.span(@as([*:0]u8, @ptrCast(c))) else "";
+ // ...or the session's when this one may not be written (`git log` in
+ // /usr/src), which /pager refuses: the text is paged all the same.
+ const plain = for (cwd) |c| {
+ if (c < ' ' or c == 0x7f) break false;
+ } else !pardes.filesystem.deniedAbove(cwd);
+ var line_buf: [4200]u8 = undefined;
+ const dir_line = std.fmt.bufPrint(&line_buf, "{s}\n", .{if (plain) cwd else ""}) catch "\n";
+ // Its serial read back on the open that asked, once the text is in:
+ // another client's exec meanwhile can never send it into that
+ // client's pane.
+ const answer = ninep_io.Client.ask(gpa, dial, "/pager", dir_line, text) catch |err| Fail.with(io, text, "no +Pager pane", err);
+ _ = std.fmt.parseInt(u32, std.mem.trim(u8, answer, " \n"), 10) catch |err| Fail.with(io, text, "no +Pager pane", err);
+}
+
+/// Stdin to its end, as it came (its escapes are the session's to parse,
+/// pager.zig), at most a file's limit, a longer one cut there and said so
+/// at its end.
+fn readStdinText(io: std.Io, gpa: std.mem.Allocator) ![]u8 {
+ const limit = pardes.memory.limits.max_file_bytes;
+ var raw: std.ArrayList(u8) = .empty;
+ var chunk: [64 * 1024]u8 = undefined;
+ var stdin = std.Io.File.stdin().readerStreaming(io, &chunk);
+ // One byte past the limit says there is more.
+ stdin.interface.appendRemaining(gpa, &raw, .limited(limit + 1)) catch |err| switch (err) {
+ error.StreamTooLong => {
+ raw.shrinkRetainingCapacity(limit);
+ // CAN ends an escape the cut left half sent, and SGR 0 its colour,
+ // so the note is never swallowed or tinted.
+ const said = "\x18\x1b[m\n[pardes: the rest of stdin is cut: a pane holds at most a file's limit]\n";
+ try raw.appendSlice(gpa, said);
+ },
+ else => |e| return e,
+ };
+ return raw.toOwnedSlice(gpa);
+}
+
+/// A forwarding failure in words, never an error's name: the ones this
+/// file raises said outright, any other as its name's words (`NotFound`,
+/// `not found`), a dial's as Messages says it.
+fn forwardWords(err: anyerror, buf: []u8) []const u8 {
+ return switch (err) {
+ error.NotOneLine => "a file name is one line, and this one holds a newline",
+ error.NotAFileName => "names a directory, not a file",
+ error.NoWorkingDirectory => "this shell's working directory is gone",
+ error.DirectoryNotWritable => "permission denied: its directory may not be read or written, so it could never be saved",
+ error.NotAPaneAddress => "not a pane address: @p and a pane's number",
+ error.NoSuchPane => "this session has no such pane",
+ else => if (pardes.Messages.dialReason(err)) |why| why else words: {
+ var n: usize = 0;
+ for (@errorName(err), 0..) |c, i| {
+ if (n + 2 > buf.len) break;
+ if (std.ascii.isUpper(c) and i > 0) {
+ buf[n] = ' ';
+ n += 1;
+ }
+ buf[n] = std.ascii.toLower(c);
+ n += 1;
+ }
+ break :words buf[0..n];
+ },
+ };
+}
+
+/// `--wait` after a forwarded look, as plan9port's E reads acme's log: the
+/// pane `path` landed in (the one it already had, if open), then /log
+/// followed on one connection until that pane's `del` -- exit 0 -- or the
+/// connection ends with the session -- exit 1.
+fn waitForDel(io: std.Io, gpa: std.mem.Allocator, dial: []const u8, path: []const u8, known: ?u32) noreturn {
+ _ = io;
+ // The pane this launch made (a name not there yet), or the one its
+ // look answered, is known by its serial; one the look answered none
+ // for is found by its file. Found by none after the look went there,
+ // it was closed already: that is the end being waited for, not a
+ // failure (a pane closed between the look and this read made `--wait`
+ // exit 1 before).
+ const serial = known orelse found: {
+ const first = ninep_io.Client.read(gpa, dial, "/index", "/index") catch std.process.exit(1);
+ defer gpa.free(first);
+ break :found paneShowing(first, path) orelse std.process.exit(0);
+ };
+ const Wait = struct {
+ gpa: std.mem.Allocator,
+ dial: []const u8,
+ serial: u32,
+ /// Deleted between the look and the follow: /index, read once the
+ /// follow stands, says so, and a `del` after it is followed.
+ fn gone(w: *const @This()) bool {
+ const index = ninep_io.Client.read(w.gpa, w.dial, "/index", "/index") catch return false;
+ defer w.gpa.free(index);
+ return !hasPane(index, w.serial);
+ }
+ fn deleted(w: *const @This(), bytes: []const u8) bool {
+ return isDel(bytes, w.serial);
+ }
+ };
+ const w: Wait = .{ .gpa = gpa, .dial = dial, .serial = serial };
+ ninep_io.Client.follow(gpa, dial, "/log", "follow new", &w, Wait.gone, Wait.deleted) catch std.process.exit(1);
+ std.process.exit(0);
+}
+
+/// Whether log records `bytes` hold `del <serial> ...`.
+fn isDel(bytes: []const u8, serial: u32) bool {
+ var records = std.mem.splitScalar(u8, bytes, '\n');
+ while (records.next()) |rec| {
+ if (!std.mem.startsWith(u8, rec, "del ")) continue;
+ const word = rec[4 .. std.mem.indexOfScalarPos(u8, rec, 4, ' ') orelse rec.len];
+ if ((std.fmt.parseInt(u32, word, 10) catch continue) == serial) return true;
+ }
+ return false;
+}
+
+/// The serial of /index's first row named `path` (`serial kind dirty name col`).
+fn paneShowing(index: []const u8, path: []const u8) ?u32 {
+ var rows = std.mem.splitScalar(u8, index, '\n');
+ while (rows.next()) |row| {
+ var words = std.mem.splitScalar(u8, row, ' ');
+ const serial = std.fmt.parseInt(u32, words.first(), 10) catch continue;
+ _ = words.next() orelse continue; // kind
+ _ = words.next() orelse continue; // dirty
+ const rest = words.rest();
+ const end = std.mem.lastIndexOfScalar(u8, rest, ' ') orelse continue;
+ if (std.mem.eql(u8, rest[0..end], path)) return serial;
+ }
+ return null;
+}
+
+fn hasPane(index: []const u8, serial: u32) bool {
+ var rows = std.mem.splitScalar(u8, index, '\n');
+ while (rows.next()) |row| {
+ const first = row[0 .. std.mem.indexOfScalar(u8, row, ' ') orelse row.len];
+ if ((std.fmt.parseInt(u32, first, 10) catch continue) == serial) return true;
+ }
+ return false;
+}
+
+test "--wait finds the pane /index names a file by, spaces and all, and sees it gone" {
+ const index = "1 term 0 /home/u 1\n4 text 1 /tmp/a b.txt 2\n";
+ try std.testing.expectEqual(@as(?u32, 4), paneShowing(index, "/tmp/a b.txt"));
+ try std.testing.expectEqual(@as(?u32, null), paneShowing(index, "/tmp/a"));
+ try std.testing.expect(hasPane(index, 4) and !hasPane(index, 2));
+ try std.testing.expect(isDel("new 5 /x\ndel 4 /tmp/a b.txt\n", 4));
+ try std.testing.expect(!isDel("del 41 /x\n", 4) and !isDel("undel 4\n", 4));
+}
+
fn badArgs(io: std.Io, comptime fmt: []const u8, args: anytype) noreturn {
var buf: [1024]u8 = undefined;
const line = std.fmt.bufPrint(&buf, "pardes: " ++ fmt ++ "\nTry 'pardes --help'.\n", args) catch
@@ -138,7 +319,13 @@ fn webMain() !void {
try @import("gui/gui.zig").run(.{}, .{}, null);
}
-fn nativeMain(init: std.process.Init) !void {
+// init.gpa, what the tty, gui and detached shells allocate from, is their
+// own fixed arena (memory.host) in a release build, spilling to libc's
+// malloc, and std.start's DebugAllocator in Debug. Zig 0.17's std.start
+// gives a safe build a SafeAllocator over the page allocator instead.
+fn nativeMain(std_init: std.process.Init) !void {
+ var init = std_init;
+ if (builtin.mode != .debug) init.gpa = pardes.memory.host(std.heap.c_allocator);
var stderr_probe: [64]u8 = undefined;
_ = std.debug.lockStderr(&stderr_probe);
std.debug.unlockStderr();
@@ -154,6 +341,7 @@ fn nativeMain(init: std.process.Init) !void {
var detach: ?[]const u8 = null;
var attach: ?[]const u8 = null;
var positional: ?[:0]const u8 = null;
+ var wait = false;
var i: usize = 1;
while (i < args.len) : (i += 1) {
const a = args[i];
@@ -232,8 +420,12 @@ fn nativeMain(init: std.process.Init) !void {
if (mounts_len == mounts.len) badArgs(init.io, "too many mounts (maximum {d})", .{mounts.len});
mounts[mounts_len] = .{ .name = name, .dial = dial };
mounts_len += 1;
+ } else if (std.mem.startsWith(u8, a, "--geometry=")) {
+ opts.geometry = a["--geometry=".len..];
} else if (std.mem.eql(u8, a, "--nested")) {
opts.nested = true;
+ } else if (std.mem.eql(u8, a, "-w") or std.mem.eql(u8, a, "--wait")) {
+ wait = true;
} else if (std.mem.eql(u8, a, "--detach")) {
detach = "";
} else if (std.mem.startsWith(u8, a, "--detach=")) {
@@ -248,7 +440,17 @@ fn nativeMain(init: std.process.Init) !void {
} else if (std.mem.eql(u8, a, "--version")) {
try std.Io.File.stdout().writeStreamingAll(init.io, version_text);
return;
- } else if (a.len > 0 and a[0] != '-' and positional == null) {
+ } else if (std.mem.eql(u8, a, "--")) {
+ // The end of options: what follows is a name, `-dash.txt` too.
+ for (args[i + 1 ..]) |name| {
+ if (name.len == 0) badArgs(init.io, "an empty argument names nothing", .{});
+ if (positional != null) badArgs(init.io, "one file or directory at a time, and '{s}' is the second", .{name});
+ session_only = false;
+ positional = name;
+ }
+ break;
+ } else if (a.len > 0 and (a[0] != '-' or std.mem.eql(u8, a, "-")) and positional == null) {
+ // `-` is stdin, as for cat and vim: a text to show.
session_only = false;
positional = a;
} else if (a.len == 0) {
@@ -261,8 +463,18 @@ fn nativeMain(init: std.process.Init) !void {
}
opts.tty_only = explicit_tty or session_only;
opts.mounts = mounts[0..mounts_len];
+ // `zig build run-isolated` with nothing named: something to look at on
+ // arrival, read out of the binary itself.
+ if (pardes.isolated and positional == null) {
+ session_only = false;
+ positional = "src/pardes.zig";
+ }
if (detach != null and attach != null)
badArgs(init.io, "--detach and --attach are opposites: one runs the session, the other joins one", .{});
+ // --wait waits on the pane a FILE opens: with none there is nothing to
+ // wait for (EDITOR=pardes --wait is given the file).
+ if (wait and positional == null)
+ badArgs(init.io, "--wait needs a FILE: it returns when that file's pane is closed", .{});
if (opts.ninep_name.len != 0 and attach != null)
badArgs(init.io, "--9p names a session's own socket, and --attach has none of its own", .{});
if (opts.ninep_tcp != null and attach != null)
@@ -272,33 +484,194 @@ fn nativeMain(init: std.process.Init) !void {
if (opts.mounts.len != 0 and attach != null)
badArgs(init.io, "--mount configures a session's own core, and --attach has none of its own", .{});
if (!new_session and !opts.nested and detach == null and attach == null) forwarding: {
- const enabled = std.c.getenv("PARDES_FORWARD_LOOK") orelse break :forwarding;
- if (!std.mem.eql(u8, std.mem.span(enabled), "1")) break :forwarding;
- const dial = std.mem.span(std.c.getenv("PARDES_9P") orelse break :forwarding);
- ninep_io.Client.validateDial(dial) catch break :forwarding;
- const pane_text = std.mem.span(std.c.getenv("PARDES_PANE") orelse break :forwarding);
- for (pane_text) |byte| if (!std.ascii.isDigit(byte)) break :forwarding;
- const serial = std.fmt.parseInt(u32, pane_text, 10) catch break :forwarding;
- if (serial == 0) break :forwarding;
- var ctl_buf: [64]u8 = undefined;
- const ctl = try std.fmt.bufPrint(&ctl_buf, "/pane/{d}/ctl", .{serial});
- const word = positional orelse {
+ // Am I inside a pardes at all? That is $PARDES_PID and nothing else —
+ // one variable, exported by every session that means to take its
+ // children's Looks, so a session that could not open a socket is still
+ // recognisably the session this shell is inside. A pid naming no live
+ // process is a shell that outlived its editor (a daemon started from a
+ // pane, a stale environment carried into a new terminal), which is not
+ // nested at all.
+ // `--wait` with only $PARDES_9P (a script or agent that talks to a
+ // session from outside its panes, EDITOR='pardes --wait') is asked
+ // of that session too: what it waits on is a pane there.
+ const outside = wait and std.c.getenv("PARDES_PID") == null and std.c.getenv("PARDES_9P") != null;
+ if (!outside) {
+ const owner = std.mem.span(std.c.getenv("PARDES_PID") orelse break :forwarding);
+ const pid = std.fmt.parseInt(std.c.pid_t, owner, 10) catch break :forwarding;
+ if (pid <= 0 or std.c.kill(pid, @fromBackingInt(@intCast(0))) != 0) break :forwarding;
+ }
+
+ // Can I reach it? That is the other two, and it is a separate answer.
+ const Parent = struct { dial: []const u8, serial: u32 };
+ const found: ?Parent = reaching: {
+ const dial = std.mem.span(std.c.getenv("PARDES_9P") orelse break :reaching null);
+ ninep_io.Client.validateDial(dial) catch break :reaching null;
+ // No pane of its own (`outside`): the session's root look, 0.
+ const pane_text = std.mem.span(std.c.getenv("PARDES_PANE") orelse if (outside) break :reaching .{ .dial = dial, .serial = 0 } else break :reaching null);
+ for (pane_text) |byte| if (!std.ascii.isDigit(byte)) break :reaching null;
+ const serial = std.fmt.parseInt(u32, pane_text, 10) catch break :reaching null;
+ if (serial == 0) break :reaching null;
+ break :reaching .{ .dial = dial, .serial = serial };
+ };
+ // A pid we cannot reach is a session that is not answering: the shell
+ // says it is inside one, but there is nothing there to take the file.
+ // Starting an ordinary editor is what this did before the pid existed
+ // and is the more useful of the two answers -- refusing to start would
+ // leave a stale environment variable able to lock someone out of their
+ // own editor.
+ const parent = found orelse break :forwarding;
+ // Does it answer? One that answers takes the file or says why not,
+ // as acme's B does: from here on never a nested editor, whose
+ // screen would be drawn inside the pane that asked.
+ ninep_io.Client.probe(arena, parent.dial) catch {
+ // `--wait` is someone's EDITOR waiting on that session: a screen
+ // of its own drawn in their terminal is no answer. Said, exit 1.
+ if (wait) {
+ var buf: [4300]u8 = undefined;
+ const text = std.fmt.bufPrint(&buf, "pardes: --wait: the session at {s} does not answer; it is gone\n", .{parent.dial[0..@min(parent.dial.len, 4096)]}) catch "pardes: --wait: the session does not answer\n";
+ std.Io.File.stderr().writeStreamingAll(init.io, text) catch {};
+ std.process.exit(1);
+ }
+ break :forwarding;
+ };
+ const Refuse = struct {
+ fn with(io: std.Io, what: []const u8, err: anyerror) noreturn {
+ var words_buf: [128]u8 = undefined;
+ const why = if (err == error.Remote) ninep_io.Client.lastSaid() else forwardWords(err, &words_buf);
+ var buf: [8192]u8 = undefined;
+ const text = std.fmt.bufPrint(&buf, "pardes: {s}: {s}\n", .{ what[0..@min(what.len, 4096)], why }) catch "pardes: refused\n";
+ std.Io.File.stderr().writeStreamingAll(io, text) catch {};
+ std.process.exit(1);
+ }
+ };
+ // The pane's `look` file: one line, and the line is the clicked text
+ // itself, which is what a right click in that pane would have been.
+ var look_buf: [64]u8 = undefined;
+ const look = if (parent.serial == 0) "/look" else try std.fmt.bufPrint(&look_buf, "/pane/{d}/look", .{parent.serial});
+ // `pardes -`: stdin read to its end, a +Pager pane of the session
+ // made of it (as acme's `B` has no stdin, through pane/new, a name
+ // and the body), and back at once: the PAGER a pane's shell gets.
+ if (positional) |word| if (std.mem.eql(u8, word, "-")) {
+ const text = readStdinText(init.io, arena) catch |err| Refuse.with(init.io, "stdin", err);
+ // Nothing paged: no pane, and done.
+ if (text.len == 0) return;
+ pageInto(init.io, arena, parent.dial, text);
+ return;
+ };
+ // From outside the session's panes there is no pane to say it is
+ // nested in: `--wait` with no file opens nothing there.
+ if (parent.serial == 0 and positional == null) break :forwarding;
+ const typed_word = positional orelse {
var tag_buf: [64]u8 = undefined;
- const tag = try std.fmt.bufPrint(&tag_buf, "/pane/{d}/tag", .{serial});
- const contents = ninep_io.Client.read(arena, dial, tag, tag) catch break :forwarding;
+ const tag = try std.fmt.bufPrint(&tag_buf, "/pane/{d}/tag", .{parent.serial});
+ const contents = ninep_io.Client.read(arena, parent.dial, tag, tag) catch |err| Refuse.with(init.io, tag, err);
arena.free(contents);
try std.Io.File.stderr().writeStreamingAll(init.io, nested_text);
std.process.exit(1);
};
- if (std.mem.indexOfAny(u8, word, "\r\n") != null) break :forwarding;
+ // Named as it was given, its newline shown `\n`, so the refusal says
+ // which name and why once.
+ if (std.mem.indexOfAny(u8, typed_word, "\r\n") != null) {
+ var shown_buf: [4 * 4096]u8 = undefined;
+ Refuse.with(init.io, pardes.ctlfs.events.shown(typed_word[0..@min(typed_word.len, 4096)], &shown_buf), error.NotOneLine);
+ }
+ // `pardes '~/x'`, quoted so the shell left it: home, as a look's.
+ var home_buf: [4096]u8 = undefined;
+ const word = pardes.filesystem.expandHome(typed_word, &home_buf);
const target = @import("look.zig").parsePathLine(word);
+ // `@pN[:addr]` addresses a pane of this session: one it has is
+ // looked at, one it has not is refused, never a file of that name.
+ if (std.mem.startsWith(u8, target.path, pardes.config.pane_addr)) {
+ const digits = word[pardes.config.pane_addr.len .. std.mem.indexOfScalar(u8, word, ':') orelse word.len];
+ const serial = std.fmt.parseInt(u32, digits, 10) catch Refuse.with(init.io, word, error.NotAPaneAddress);
+ var name_buf: [64]u8 = undefined;
+ const name = try std.fmt.bufPrint(&name_buf, "/pane/{d}/name", .{serial});
+ const named = ninep_io.Client.read(arena, parent.dial, name, name) catch Refuse.with(init.io, word, error.NoSuchPane);
+ arena.free(named);
+ var command_buf: [4200]u8 = undefined;
+ const command = std.fmt.bufPrint(&command_buf, "{s}\n", .{word}) catch |err| Refuse.with(init.io, word, err);
+ ninep_io.Client.write(arena, parent.dial, look, command) catch |err| Refuse.with(init.io, word, err);
+ return;
+ }
var realbuf: [4096]u8 = undefined;
- const path = if (pardes.filesystem.isVirtual(target.path)) target.path else (pardes.filesystem.resolveOs(target.path, &realbuf) orelse break :forwarding).path;
- var command_buf: [8192]u8 = undefined;
- const command = std.fmt.bufPrint(&command_buf, "look {s}{s}\n", .{ path, word[target.path.len..] }) catch break :forwarding;
- ninep_io.Client.write(arena, dial, ctl, command) catch break :forwarding;
+ var newbuf: [4096]u8 = undefined;
+ const found_path: ?[]const u8 = if (pardes.filesystem.isVirtual(target.path)) target.path else if (pardes.filesystem.resolveOs(target.path, &realbuf)) |r| r.path else null;
+ const path = found_path orelse named: {
+ // A name not there yet, as acme's B takes one: its directory
+ // resolved and the name kept, a pane made for it that Save
+ // creates the file from.
+ const base = std.fs.path.basename(target.path);
+ if (base.len == 0 or std.mem.eql(u8, base, ".") or std.mem.eql(u8, base, "..")) Refuse.with(init.io, word, error.NotAFileName);
+ const dir = pardes.filesystem.resolveOs(std.fs.path.dirname(target.path) orelse ".", &realbuf) orelse {
+ // Its directory not there either: the name made absolute as
+ // written, and the pane's Save makes the directories.
+ var cwd_buf: [4096]u8 = undefined;
+ if (std.c.getcwd(&cwd_buf, cwd_buf.len) == null) Refuse.with(init.io, word, error.NoWorkingDirectory);
+ const cwd = std.mem.sliceTo(&cwd_buf, 0);
+ const absolute = std.fs.path.resolvePosix(arena, &.{ cwd, target.path }) catch |err| Refuse.with(init.io, word, err);
+ // Missing because one above may not be searched or written:
+ // its Save could never make it, so refused now.
+ if (pardes.filesystem.deniedAbove(std.fs.path.dirname(absolute) orelse "/")) Refuse.with(init.io, word, error.DirectoryNotWritable);
+ break :named absolute;
+ };
+ // A directory that is there but may not be read or written: a
+ // pane for the name could only fail at its Save, so refused now.
+ var dir_z_buf: [4096]u8 = undefined;
+ if (std.fmt.bufPrintSentinel(&dir_z_buf, "{s}", .{dir.path}, 0)) |dir_z| {
+ const R_OK = 4;
+ const W_OK = 2;
+ const X_OK = 1;
+ if (std.c.access(dir_z.ptr, R_OK | W_OK | X_OK) != 0) Refuse.with(init.io, word, error.DirectoryNotWritable);
+ } else |_| {}
+ break :named std.fmt.bufPrint(&newbuf, "{s}/{s}", .{ std.mem.trimEnd(u8, dir.path, "/"), base }) catch |err| Refuse.with(init.io, word, err);
+ };
+ var made_serial: ?u32 = null;
+ if (found_path != null) {
+ var command_buf: [8192]u8 = undefined;
+ const command = std.fmt.bufPrint(&command_buf, "{s}{s}\n", .{ path, word[target.path.len..] }) catch |err| Refuse.with(init.io, word, err);
+ // The pane it went to, read on the open that asked (another
+ // client's look meanwhile is not this one's): what --wait waits on.
+ const went = ninep_io.Client.ask(arena, parent.dial, look, command, "") catch |err| Refuse.with(init.io, word, err);
+ var rows = std.mem.tokenizeAny(u8, went, " \n");
+ if (rows.next()) |row| made_serial = std.fmt.parseInt(u32, row, 10) catch null;
+ } else {
+ const made = ninep_io.Client.read(arena, parent.dial, "/pane/new", "/pane/new") catch |err| Refuse.with(init.io, word, err);
+ const serial = std.fmt.parseInt(u32, std.mem.trim(u8, made, " \n"), 10) catch |err| Refuse.with(init.io, word, err);
+ made_serial = serial;
+ var name_buf: [64]u8 = undefined;
+ const name = try std.fmt.bufPrint(&name_buf, "/pane/{d}/name", .{serial});
+ var line_buf: [4200]u8 = undefined;
+ const line = std.fmt.bufPrint(&line_buf, "{s}\n", .{path}) catch |err| Refuse.with(init.io, word, err);
+ ninep_io.Client.write(arena, parent.dial, name, line) catch |err| {
+ // The name refused: the pane made for it goes too, no
+ // stray +New left behind.
+ var ctl_buf: [64]u8 = undefined;
+ const ctl = std.fmt.bufPrint(&ctl_buf, "/pane/{d}/ctl", .{serial}) catch unreachable;
+ var why_buf: [256]u8 = undefined;
+ const said = ninep_io.Client.lastSaid();
+ const why = why_buf[0..@min(said.len, why_buf.len)];
+ @memcpy(why, said[0..why.len]);
+ ninep_io.Client.write(arena, parent.dial, ctl, "delete\n") catch {};
+ if (err == error.Remote) {
+ var buf: [8192]u8 = undefined;
+ const text = std.fmt.bufPrint(&buf, "pardes: {s}: {s}\n", .{ word[0..@min(word.len, 4096)], why }) catch "pardes: refused\n";
+ std.Io.File.stderr().writeStreamingAll(init.io, text) catch {};
+ std.process.exit(1);
+ }
+ Refuse.with(init.io, word, err);
+ };
+ }
+ if (wait) waitForDel(init.io, arena, parent.dial, path, made_serial);
return;
}
+ // `pardes -` outside a session: an editor whose first pane holds stdin,
+ // as `vim -` does; the terminal is /dev/tty, never stdin.
+ if (positional) |a| if (std.mem.eql(u8, a, "-")) {
+ opts.stdin_text = readStdinText(init.io, arena) catch |err| badArgs(init.io, "stdin: {s}", .{@errorName(err)});
+ // Nothing paged: nothing to show.
+ if (opts.stdin_text.?.len == 0) return;
+ positional = null;
+ };
if (positional) |a| {
const target = @import("look.zig").parsePathLine(a);
if (std.mem.eql(u8, target.path, "/n") or std.mem.startsWith(u8, target.path, "/n/") or
@@ -327,24 +700,51 @@ fn nativeMain(init: std.process.Init) !void {
}
}
}
+ // The real bare-tty startup wants the editor half present from the first
+ // frame, so it names that layout; a core booted for a test names none and
+ // gets the raw shell by itself. This has to come AFTER the positional is
+ // resolved: naming a layout short-circuits `Boot.of`, so choosing it any
+ // earlier threw away a file argument, and the error pane for one that does
+ // not exist, without a word.
+ if (opts.tty_only and opts.file == null and opts.missing == null) opts.boot = .tty;
const found = pardes.config.User.load(init.io, arena, init.environ_map);
opts.startup_config = found.bytes;
opts.startup_config_path = found.path;
opts.config_dir = found.dir;
+ opts.store_path = storePath(init.io, arena, init.environ_map);
if (found.dir) |d| @import("crash.zig").setDir(d);
if (detach) |name| {
const named = if (name.len != 0)
name
else
try std.fmt.allocPrint(arena, "{d}", .{@as(u32, @intCast(std.c.getpid()))});
- return @import("detached/server.zig").run(init, opts, named);
+ // Said plainly, never a Zig error trace: a name another session's
+ // socket holds already (a plain session is named by its pid too).
+ return @import("detached/server.zig").run(init, opts, named) catch |err| {
+ var words: [128]u8 = undefined;
+ var said: [512]u8 = undefined;
+ const why = if (err == error.ListenFailed)
+ "its socket is taken: another session (a plain one is named by its pid) holds that name; choose another"
+ else
+ pardes.Messages.errorWords(err, &words);
+ std.Io.File.stderr().writeStreamingAll(init.io, std.fmt.bufPrint(&said, "pardes: --detach={s}: {s}\n", .{ named, why }) catch "pardes: --detach failed\n") catch {};
+ std.process.exit(1);
+ };
}
if (attach != null and pardes.platform != .tty and pardes.platform != .gui) {
try std.Io.File.stderr().writeStreamingAll(init.io, "pardes: --attach needs the tty or gui shell\n");
std.process.exit(1);
}
switch (pardes.platform) {
- .tty => try @import("tty/tty.zig").run(init, opts, attach),
+ .tty => @import("tty/tty.zig").run(init, opts, attach) catch |err| switch (err) {
+ // No controlling terminal (a detached pty, a daemon): said, not
+ // an error trace.
+ error.NoDevice => {
+ std.Io.File.stderr().writeStreamingAll(init.io, "pardes: no terminal to draw on: /dev/tty will not open; run it in a terminal, or --detach\n") catch {};
+ std.process.exit(1);
+ },
+ else => return err,
+ },
.gui => try @import("gui/gui.zig").run(init, opts, attach),
.web, .macos, .esp32p4 => unreachable,
}
@@ -369,9 +769,11 @@ test {
_ = pardes.config.User;
_ = @import("crash.zig");
_ = @import("memory.zig");
- _ = @import("locations_cache.zig");
+ _ = @import("locations.zig");
_ = @import("fs.zig");
_ = @import("detached/wire.zig");
+ _ = @import("ShaderBuild.zig");
+ _ = @import("vaxis_input.zig");
_ = @import("detached/server.zig");
_ = @import("detached/client.zig");
_ = @import("9p_io.zig");
@@ -379,9 +781,10 @@ test {
_ = @import("host_io.zig");
_ = @import("host_io.zig").Shell;
_ = @import("host_io.zig").Lsp;
+ // Its tests too: imported by the hosts only, it was never collected.
+ _ = @import("file_watch.zig");
_ = @import("lsp/lsp_client.zig");
_ = @import("lsp/lsp.zig");
- if (comptime @import("pardes_config").zls_backend) _ = @import("lsp/lsp_zls.zig");
if (comptime pardes.platform == .tty) {
_ = @import("tty/tty.zig");
_ = @import("tty/panel_compositor.zig");
@@ -389,3 +792,19 @@ test {
if (comptime pardes.platform == .gui) _ = @import("gui/gui.zig");
if (comptime pardes.font_picker) _ = @import("fonts.zig");
}
+
+/// Where the store every window shares is kept (Store.zig):
+/// $XDG_STATE_HOME/pardes/store, else ~/.local/state/pardes/store, the
+/// directory made if need be; null with no home to keep it in (Recent and
+/// the closed panes then last the session).
+fn storePath(io: std.Io, arena: std.mem.Allocator, env: *const std.process.Environ.Map) ?[]const u8 {
+ const dir = dir: {
+ if (env.get("XDG_STATE_HOME")) |base| if (base.len != 0 and std.fs.path.isAbsolute(base))
+ break :dir std.fs.path.join(arena, &.{ base, "pardes" }) catch return null;
+ const home = env.get("HOME") orelse return null;
+ if (home.len == 0) return null;
+ break :dir std.fs.path.join(arena, &.{ home, ".local", "state", "pardes" }) catch return null;
+ };
+ std.Io.Dir.cwd().createDirPath(io, dir) catch return null;
+ return std.fs.path.join(arena, &.{ dir, "store" }) catch null;
+}