const std = @import("std"); const builtin = @import("builtin"); const pardes = @import("pardes.zig"); const ninep_io = @import("9p_io.zig"); const is_emscripten = builtin.os.tag == .emscripten; extern "c" fn emscripten_console_error(utf8: [*:0]const u8) void; pub const std_options_debug_threaded_io: ?*std.Io.Threaded = if (is_emscripten) null else std.Io.Threaded.global_single_threaded; pub const std_options_debug_io: std.Io = if (is_emscripten) std.Io.failing else std_options_debug_threaded_io.?.io(); pub const std_options: std.Options = .{ .logFn = logFn }; fn logFn( comptime level: std.log.Level, comptime scope: @EnumLiteral(), comptime format: []const u8, args: anytype, ) void { if (scope != .gui and scope != .dump and std.c.getenv("PARDES_LOG") == null) return; std.log.defaultLog(level, scope, format, args); } pub const panic = if (is_emscripten) std.debug.FullPanic(std.debug.defaultPanic) else std.debug.FullPanic(struct { fn call(msg: []const u8, ret_addr: ?usize) noreturn { if (!recovering.swap(true, .seq_cst)) @import("vaxis").recover(); @import("crash.zig").record(msg); std.debug.defaultPanic(msg, ret_addr); } }.call); var recovering: std.atomic.Value(bool) = .init(false); pub const debug = if (is_emscripten) struct {} else struct { pub fn handleSegfault(addr: ?usize, name: []const u8, opt_ctx: anytype) noreturn { if (!recovering.swap(true, .seq_cst)) @import("vaxis").recover(); return std.debug.defaultHandleSegfault(addr, name, opt_ctx); } }; const help_text = \\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. \\ \\Options: \\ --tty start as one shell pane already in tty mode \\ -n initial shell panes: 1 (default) or 3 (classic). \\ A FILE argument boots just that file instead. \\ --tty-toggle use Ctrl- to toggle tty/editor mode \\ -l load a dump of another instance (see Dump) \\ --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 \\ session will not serve its own children either. \\ Explicit session configuration starts a new one. \\ --9p= name the default 9P socket. Without this flag, \\ the name is the detached session name or pid. \\ The socket is under $XDG_RUNTIME_DIR, falling \\ back to ~/.local/state/pardes. \\ --9p-tcp= also serve 9P at tcp!!. \\ --9p-quic= also serve at quic!! (-Dquic=true). \\ --mount== mount a 9P session or Unix/TCP/QUIC endpoint under /n/. \\ Repeat for more mounts; os and self are reserved. \\ --detach run this session with NO terminal of its own, \\ serving frontends over a unix socket beside its \\ 9P socket. The core, the panes and the \\ undo history outlive every frontend that attaches \\ --detach= ...named rather than this process's pid, so \\ a frontend can say which session it wants. One \\ path component: no '/' and nothing empty \\ --attach become a frontend of the one detached session \\ that is running: draw its screen and send it \\ input, and nothing else — the session owns its \\ pane shells, its files and its watches. Works in \\ both the terminal and the SDL window build. \\ Several frontends may be attached at once and all \\ see the same screen \\ --attach= ...of the session called , which is what to \\ use when more than one is running \\ -h, --help show this help and exit \\ --version print the version and exit \\ ; 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 "pardes: bad arguments\nTry 'pardes --help'.\n"; std.Io.File.stderr().writeStreamingAll(io, line) catch {}; std.process.exit(1); } const version_text = if (pardes.commit) |c| "pardes " ++ pardes.version ++ " (" ++ c ++ ")\n" else "pardes " ++ pardes.version ++ "\n"; const nested_text = \\pardes: this shell is already inside pardes, and a pardes inside a pardes \\is spicy. Name a file or a directory and the outer session opens it, or \\pass --nested if you really want a second one in here. \\ ; // The browser runtime calls a C main (exported below); everything else keeps // the std.process.Init entry. pub const main = if (is_emscripten) webMain else nativeMain; comptime { if (is_emscripten) @export(&emscriptenMain, .{ .name = "main" }); } fn emscriptenMain(argc: c_int, argv: [*]?[*:0]u8) callconv(.c) c_int { _ = argc; _ = argv; webMain() catch |err| { var buf: [128]u8 = undefined; const msg = std.fmt.bufPrintSentinel(&buf, "pardes web init failed: {t}", .{err}, 0) catch "pardes web init failed"; emscripten_console_error(msg.ptr); return 1; }; return 0; } // no argv in the browser: options stay default, state comes from the dump, and // there is no session to attach to — a browser tab has no unix socket. fn webMain() !void { try @import("gui/gui.zig").run(.{}, .{}, null); } fn nativeMain(init: std.process.Init) !void { var stderr_probe: [64]u8 = undefined; _ = std.debug.lockStderr(&stderr_probe); std.debug.unlockStderr(); var opts: pardes.Options = .{}; var mounts: [pardes.filesystem.max_mounts]pardes.filesystem.Mount = undefined; var mounts_len: usize = 0; const arena = init.arena.allocator(); const args = try init.minimal.args.toSlice(arena); var session_only = true; var new_session = false; var explicit_tty = false; var detach: ?[]const u8 = null; var attach: ?[]const u8 = null; var positional: ?[:0]const u8 = null; var i: usize = 1; while (i < args.len) : (i += 1) { const a = args[i]; if (std.mem.eql(u8, a, "--tty")) { explicit_tty = true; } else if (std.mem.startsWith(u8, a, "--tty-toggle=")) { session_only = false; new_session = true; opts.tty_toggle = parseCtrlKey(a["--tty-toggle=".len..]) orelse badArgs(init.io, "--tty-toggle wants one letter, not '{s}'", .{a["--tty-toggle=".len..]}); } else if (std.mem.eql(u8, a, "--tty-toggle")) { session_only = false; new_session = true; i += 1; if (i >= args.len) badArgs(init.io, "--tty-toggle needs a letter after it", .{}); opts.tty_toggle = parseCtrlKey(args[i]) orelse badArgs(init.io, "--tty-toggle wants one letter, not '{s}'", .{args[i]}); } else if (std.mem.eql(u8, a, "-n")) { session_only = false; new_session = true; i += 1; if (i >= args.len) badArgs(init.io, "-n needs a count after it: 1 or 3", .{}); opts.shells = std.fmt.parseInt(u8, args[i], 10) catch badArgs(init.io, "-n takes 1 or 3, not '{s}'", .{args[i]}); } else if (std.mem.eql(u8, a, "-l")) { session_only = false; new_session = true; i += 1; if (i >= args.len) badArgs(init.io, "-l needs the path of a dump to load", .{}); opts.load_path = args[i]; } else if (std.mem.eql(u8, a, "--9p")) { badArgs(init.io, "--9p needs a socket name: --9p=", .{}); } else if (std.mem.startsWith(u8, a, "--9p=")) { new_session = true; const name = a["--9p=".len..]; if (name.len == 0 or std.mem.indexOfAny(u8, name, "/\x00") != null) badArgs(init.io, "invalid 9P socket name: '{s}'", .{name}); opts.ninep_name = name; } else if (std.mem.startsWith(u8, a, "--9p-tcp=")) { new_session = true; const dial = a["--9p-tcp=".len..]; if (!std.mem.startsWith(u8, dial, "tcp!")) badArgs(init.io, "--9p-tcp needs tcp!!", .{}); _ = @import("9p_io.zig").networkAddress(dial, true) catch badArgs(init.io, "--9p-tcp needs tcp!!", .{}); if (opts.ninep_tcp != null) badArgs(init.io, "--9p-tcp was specified twice", .{}); opts.ninep_tcp = dial; } else if (std.mem.eql(u8, a, "--9p-tcp")) { badArgs(init.io, "--9p-tcp needs tcp!!", .{}); } else if (std.mem.startsWith(u8, a, "--9p-quic=")) { new_session = true; const dial = a["--9p-quic=".len..]; if (!std.mem.startsWith(u8, dial, "quic!")) badArgs(init.io, "--9p-quic needs quic!!", .{}); _ = @import("9p_io.zig").networkAddress(dial, true) catch badArgs(init.io, "--9p-quic needs quic!!", .{}); if (opts.ninep_quic != null) badArgs(init.io, "--9p-quic was specified twice", .{}); if (!@import("9p_io.zig").quic_enabled) badArgs(init.io, "QUIC is not included; rebuild with -Dquic=true", .{}); opts.ninep_quic = dial; } else if (std.mem.eql(u8, a, "--9p-quic")) { badArgs(init.io, "--9p-quic needs quic!!", .{}); } else if (std.mem.startsWith(u8, a, "--mount=")) { new_session = true; const mount = a["--mount=".len..]; const split = std.mem.indexOfScalar(u8, mount, '=') orelse badArgs(init.io, "--mount needs name=dial", .{}); const name = mount[0..split]; const dial = mount[split + 1 ..]; if (dial.len == 0 or !@import("fs.zig").validMountName(name)) badArgs(init.io, "invalid mount name or dial: '{s}'", .{mount}); @import("9p_io.zig").Client.validateDial(dial) catch badArgs(init.io, "invalid mount dial: '{s}'", .{dial}); for (mounts[0..mounts_len]) |existing| if (std.mem.eql(u8, existing.name, name)) badArgs(init.io, "duplicate mount name: '{s}'", .{name}); 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.eql(u8, a, "--nested")) { opts.nested = true; } else if (std.mem.eql(u8, a, "--detach")) { detach = ""; } else if (std.mem.startsWith(u8, a, "--detach=")) { detach = a["--detach=".len..]; } else if (std.mem.eql(u8, a, "--attach")) { attach = ""; } else if (std.mem.startsWith(u8, a, "--attach=")) { attach = a["--attach=".len..]; } else if (std.mem.eql(u8, a, "-h") or std.mem.eql(u8, a, "--help")) { try std.Io.File.stdout().writeStreamingAll(init.io, help_text); return; } 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) { session_only = false; positional = a; } else if (a.len == 0) { badArgs(init.io, "an empty argument names nothing", .{}); } else if (a[0] == '-') { badArgs(init.io, "no such option: {s}", .{a}); } else { badArgs(init.io, "one file or directory at a time, and '{s}' is the second", .{a}); } } opts.tty_only = explicit_tty or session_only; opts.mounts = mounts[0..mounts_len]; if (detach != null and attach != null) badArgs(init.io, "--detach and --attach are opposites: one runs the session, the other joins one", .{}); 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) badArgs(init.io, "--9p-tcp opens a session's own listener, and --attach has none of its own", .{}); if (opts.ninep_quic != null and attach != null) badArgs(init.io, "--9p-quic opens a session's own listener, and --attach has none of its own", .{}); 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 { 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; 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; const target = @import("look.zig").parsePathLine(word); 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; return; } 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 std.mem.eql(u8, target.path, "/virtual") or std.mem.startsWith(u8, target.path, "/virtual/")) { opts.file = try arena.dupe(u8, target.path); opts.file_line = target.at.line; } else if (std.c.chdir(a.ptr) != 0) { var cwdbuf: [4096]u8 = undefined; const cwd = std.c.getcwd(&cwdbuf, cwdbuf.len) orelse badArgs(init.io, "this shell's working directory is gone; cd somewhere that exists", .{}); var realbuf: [4096]u8 = undefined; switch (@import("look.zig").resolve(null, a, std.mem.span(@as([*:0]u8, @ptrCast(cwd))), &realbuf)) { .file => |t| { opts.file = try arena.dupe(u8, t.path); opts.file_line = t.at.line; }, .image => |t| opts.file = try arena.dupe(u8, t.path), .none => opts.missing = .{ .word = try arena.dupe(u8, a), .dir = try arena.dupe(u8, std.mem.span(@as([*:0]u8, @ptrCast(cwd)))), }, .url => badArgs(init.io, "a URL is not something a launch can open; start pardes and click it", .{}), .pane => badArgs(init.io, "@pN addresses a pane of a running pardes, so there is none yet", .{}), else => badArgs(init.io, "cannot enter that directory: {s}", .{a}), } } } 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; 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); } 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), .gui => try @import("gui/gui.zig").run(init, opts, attach), .web, .macos, .esp32p4 => unreachable, } } fn parseCtrlKey(raw: []const u8) ?u21 { var value = std.mem.trim(u8, raw, " \t\r\n"); if (value.len >= 5 and std.ascii.eqlIgnoreCase(value[0..5], "ctrl-")) { value = value[5..]; } else if (value.len >= 5 and std.ascii.eqlIgnoreCase(value[0..5], "ctrl+")) { value = value[5..]; } else if (value.len == 2 and value[0] == '^') { value = value[1..]; } if (value.len != 1) return null; const c = std.ascii.toLower(value[0]); if (c < 'a' or c > 'z' or c == 'c') return null; return c; } test { _ = pardes.config.User; _ = @import("crash.zig"); _ = @import("memory.zig"); _ = @import("locations_cache.zig"); _ = @import("fs.zig"); _ = @import("detached/wire.zig"); _ = @import("detached/server.zig"); _ = @import("detached/client.zig"); _ = @import("9p_io.zig"); _ = @import("9p_io.zig").Client; _ = @import("host_io.zig"); _ = @import("host_io.zig").Shell; _ = @import("host_io.zig").Lsp; _ = @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"); } if (comptime pardes.platform == .gui) _ = @import("gui/gui.zig"); if (comptime pardes.font_picker) _ = @import("fonts.zig"); }