summaryrefslogtreecommitdiff
path: root/src/main.zig
blob: 6627bece76a04d9b058fddf13b29ebb4b1912f99 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
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. `-` reads stdin, its terminal
    \\escapes stripped, into a +Pager pane: 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
    \\  -n <count>             initial shell panes: 1 (default) or 3 (classic).
    \\                         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
    \\                         session will not serve its own children either.
    \\                         Explicit session configuration starts a new one.
    \\  --9p=<name>            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=<dial>        also serve 9P at tcp!<numeric-ip>!<port>.
    \\  --9p-quic=<dial>       also serve at quic!<numeric-ip>!<port> (-Dquic=true).
    \\  --mount=<name>=<dial>  mount a 9P session or Unix/TCP/QUIC endpoint under /n/<name>.
    \\                         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=<name>        ...named <name> 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=<name>        ...of the session called <name>, which is what to
    \\                         use when more than one is running
    \\  -h, --help             show this help and exit
    \\  --version              print the version and exit
    \\
;

/// `pardes -` inside a session: `text` into the directory's one +Pager
/// (root ctl `pager <dir>`, refilled when it is there), streamed into its
/// body a bounded chunk at a time as one undo step, and left clean. A text
/// the session would not take is never lost: it goes to stderr, 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 "";
    const plain = for (cwd) |c| {
        if (c < ' ' or c == 0x7f) break false;
    } else true;
    var line_buf: [4200]u8 = undefined;
    const ctl_line = std.fmt.bufPrint(&line_buf, "pager {s}\n", .{if (plain) cwd else ""}) catch "pager\n";
    ninep_io.Client.write(gpa, dial, "/ctl", ctl_line) catch |err| Fail.with(io, text, "no +Pager pane", err);
    const answer = ninep_io.Client.read(gpa, dial, "/exec", "/exec") catch |err| Fail.with(io, text, "no +Pager pane", err);
    const serial = std.fmt.parseInt(u32, std.mem.trim(u8, answer, " \n"), 10) catch |err| Fail.with(io, text, "no +Pager pane", err);
    var path_buf: [64]u8 = undefined;
    const mark = std.fmt.bufPrint(&path_buf, "/pane/{d}/mark", .{serial}) catch unreachable;
    // One undo step for the whole text, however many writes carry it.
    ninep_io.Client.write(gpa, dial, mark, "0\n") catch |err| Fail.with(io, text, "the +Pager pane went", err);
    var body_buf: [64]u8 = undefined;
    const body = std.fmt.bufPrint(&body_buf, "/pane/{d}/body", .{serial}) catch unreachable;
    // A chunk ends on a line's end (never inside a character), each its own
    // write with its own deadline, so a large text arrives whole.
    const chunk_max = 8 * 1024 * 1024;
    var at: usize = 0;
    while (at < text.len) {
        var end = @min(text.len, at + chunk_max);
        if (end < text.len) if (std.mem.lastIndexOfScalar(u8, text[at..end], '\n')) |nl| {
            end = at + nl + 1;
        };
        ninep_io.Client.write(gpa, dial, body, text[at..end]) catch |err| Fail.with(io, text[at..], "the +Pager pane would not take it", err);
        at = end;
    }
    ninep_io.Client.write(gpa, dial, mark, "1\n") catch {};
    var ctl_buf: [64]u8 = undefined;
    ninep_io.Client.write(gpa, dial, std.fmt.bufPrint(&ctl_buf, "/pane/{d}/ctl", .{serial}) catch unreachable, "clean\n") catch {};
}

/// Stdin to its end, its terminal escapes stripped (a pager's input is
/// coloured for a terminal; a text pane shows text), at most a file's
/// limit, a longer one cut there and said so at its end.
fn readStdinText(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 cut = false;
    while (true) {
        const n = std.c.read(0, &chunk, chunk.len);
        if (n < 0) {
            if (std.posix.errno(n) == .INTR) continue;
            return error.ReadFailed;
        }
        if (n == 0) break;
        const got: usize = @intCast(n);
        if (raw.items.len + got > limit) {
            try raw.appendSlice(gpa, chunk[0 .. limit - raw.items.len]);
            cut = true;
            break;
        }
        try raw.appendSlice(gpa, chunk[0..got]);
    }
    var text = try stripEscapes(gpa, raw.items);
    if (cut) {
        const said = "\n[pardes: the rest of stdin is cut: a pane holds at most a file's limit]\n";
        text = try std.mem.concat(gpa, u8, &.{ text, said });
    }
    return text;
}

/// `bytes` without terminal escapes: CSI (`ESC [` ... a final byte, SGR
/// colour among them), OSC (`ESC ]` ... BEL or `ESC \`), any other
/// two-byte `ESC x`, and a man page's overstrike (`x BS x`, `_ BS x`).
pub fn stripEscapes(gpa: std.mem.Allocator, bytes: []const u8) ![]u8 {
    var out = try std.ArrayList(u8).initCapacity(gpa, bytes.len);
    var i: usize = 0;
    while (i < bytes.len) {
        const c = bytes[i];
        if (c == 0x1b and i + 1 < bytes.len) {
            const kind = bytes[i + 1];
            i += 2;
            if (kind == '[') {
                while (i < bytes.len and !(bytes[i] >= 0x40 and bytes[i] <= 0x7e)) i += 1;
                i += 1;
            } else if (std.mem.indexOfScalar(u8, "()*+", kind) != null) {
                i += 1; // a charset's name after it
            } else if (kind == ']') {
                while (i < bytes.len) : (i += 1) {
                    if (bytes[i] == 0x07) {
                        i += 1;
                        break;
                    }
                    if (bytes[i] == 0x1b and i + 1 < bytes.len and bytes[i + 1] == '\\') {
                        i += 2;
                        break;
                    }
                }
            }
            continue;
        }
        // Overstrike: the byte before a backspace is struck over.
        if (c == 0x08) {
            if (out.items.len > 0) _ = out.pop();
            i += 1;
            continue;
        }
        // A carriage return: CRLF is a newline; alone, the line starts
        // over, as on a terminal, so a progress line keeps its last state.
        if (c == '\r') {
            if (i + 1 < bytes.len and bytes[i + 1] == '\n') {
                i += 1;
                continue;
            }
            const line_start = if (std.mem.lastIndexOfScalar(u8, out.items, '\n')) |nl| nl + 1 else 0;
            out.shrinkRetainingCapacity(line_start);
            i += 1;
            continue;
        }
        // Bytes a terminal acts on and never shows: NUL, BEL, SO, SI.
        if (c == 0 or c == 0x07 or c == 0x0e or c == 0x0f) {
            i += 1;
            continue;
        }
        out.appendAssumeCapacity(c);
        i += 1;
    }
    return out.toOwnedSlice(gpa);
}

test "stripEscapes takes out colour, other escapes and overstrike, and keeps the text" {
    const gpa = std.testing.allocator;
    const cases = [_][2][]const u8{
        .{ "\x1b[33mcommit abc\x1b[m\n", "commit abc\n" },
        .{ "a\x1b]8;;http://x\x1b\\link\x1b]8;;\x07b", "alinkb" },
        .{ "N\x08NA\x08AM\x08ME\x08E _\x08u", "NAME u" },
        .{ "plain\ttext\n", "plain\ttext\n" },
        .{ "\x1b(Bdone", "done" },
        .{ "a\r\nb\r\n", "a\nb\n" },
        .{ "10%\r50%\r100%\ndone\n", "100%\ndone\n" },
        .{ "x\x00y\x07z\x0e\x0f\n", "xyz\n" },
    };
    for (cases) |c| {
        const got = try stripEscapes(gpa, c[0]);
        defer gpa.free(got);
        try std.testing.expectEqualStrings(c[1], got);
    }
}

/// 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 => "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) is known by its
    // serial; one a look opened or went to 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
        "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);
}

// init.gpa, what the tty, gui and detached shells allocate from, is
// std.start's: a DebugAllocator in Debug and, since we link libc, libc's
// malloc otherwise. Kept on purpose: glibc's malloc was measured at least as
// fast as std.heap.smp_allocator on every scenario and faster on MuPDF's
// page-sized rasters. macos.zig makes the same choice for itself.
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 wait = false;
    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=<name>", .{});
        } 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!<numeric-ip>!<port>", .{});
            _ = @import("9p_io.zig").networkAddress(dial, true) catch
                badArgs(init.io, "--9p-tcp needs tcp!<numeric-ip>!<port>", .{});
            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!<numeric-ip>!<port>", .{});
        } 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!<numeric-ip>!<port>", .{});
            _ = @import("9p_io.zig").networkAddress(dial, true) catch
                badArgs(init.io, "--9p-quic needs quic!<numeric-ip>!<port>", .{});
            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!<numeric-ip>!<port>", .{});
        } 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, "-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=")) {
            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] != '-' 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) {
            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: {
        // 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.
        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, @enumFromInt(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;
            const pane_text = std.mem.span(std.c.getenv("PARDES_PANE") orelse 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 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 = 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(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;
        };
        const typed_word = positional orelse {
            var tag_buf: [64]u8 = undefined;
            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, typed_word, "\r\n") != null) Refuse.with(init.io, "a file name", 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;
        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);
                break :named std.fs.path.resolvePosix(arena, &.{ cwd, target.path }) catch |err| Refuse.with(init.io, word, err);
            };
            // 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);
            ninep_io.Client.write(arena, parent.dial, look, command) catch |err| Refuse.with(init.io, word, err);
        } 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(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
            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}),
            }
        }
    }
    // 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.recent_path = recentPath(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);
    }
    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 => @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,
    }
}

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.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");
    _ = @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 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");
}

/// Where the list of files opened lately is kept: $XDG_STATE_HOME/pardes
/// /recent, else ~/.local/state/pardes/recent, the directory made if need
/// be; null with no home to keep it in (the list then lasts the session).
fn recentPath(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, "recent" }) catch null;
}