summaryrefslogtreecommitdiff
path: root/core/ninep
diff options
context:
space:
mode:
authorGabriel Schneider <[email protected]>2026-11-18 22:03:14 -0300
committerGabriel Schneider <[email protected]>2026-11-18 22:23:51 -0300
commit99f5b10eccd95aa0066ea6fe6bb75f367ab56a47 (patch)
tree813596ea84318a7bae4fd7416ba463de8e3b7107 /core/ninep
parent92d553123673376adf6126ab90d49a22c5b833d2 (diff)
downloadpardes-99f5b10eccd95aa0066ea6fe6bb75f367ab56a47.tar.gz
pardes-99f5b10eccd95aa0066ea6fe6bb75f367ab56a47.zip
core: src/ becomes core/, pardes.zig its root.zig (the reorganisation's tree, step 2d), and every mention of a src/ path follows: the build's paths, the core's imports of its root, the tests that read the repository's files by path (lspbench's, look.zig's spans over core/look.zig), the comments that cite files, the documents and the manual (the typst corpus reads core/tutor.txt and core/plumbing); left as they were: the /src tree's served names (src/pardes.zig and the rest are the 9P tree's, not the repository's), the CHANGELOG's history, fixtures that are only strings; fs-unit-test runs from the core's root (a module of the core rooted at fs.zig had the runtime's and the devices' `core` be fs.zig); nothing else changes: the ledger (pardes.test.* now root.test.*), frames byte-identical, replicas and process-test the base's
Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T
Diffstat (limited to 'core/ninep')
-rw-r--r--core/ninep/addr.zig680
-rw-r--r--core/ninep/cols.zig727
-rw-r--r--core/ninep/ctl.zig2909
-rw-r--r--core/ninep/events.zig1497
-rw-r--r--core/ninep/pane.zig1342
-rw-r--r--core/ninep/pty.zig1198
-rw-r--r--core/ninep/screen.zig307
-rw-r--r--core/ninep/sources.zig148
-rw-r--r--core/ninep/testing.zig168
-rw-r--r--core/ninep/tree.zig2273
10 files changed, 11249 insertions, 0 deletions
diff --git a/core/ninep/addr.zig b/core/ninep/addr.zig
new file mode 100644
index 00000000..72a2d815
--- /dev/null
+++ b/core/ninep/addr.zig
@@ -0,0 +1,680 @@
+//! The address language of a pane's `addr` file, acme's (editors/acme/
+//! addr.c), its regular expressions searched as sam searches (regexp.zig).
+const std = @import("std");
+const regexp_ = @import("../regexp.zig");
+const modal = @import("../modal.zig");
+const pane_files = @import("pane.zig");
+
+pub const Range = pane_files.State.Range;
+
+const clip = pane_files.clip;
+
+pub const e_no_match = "no match for regexp";
+pub const e_range = "address out of range";
+pub const e_col_zero = "address out of range: a column counts from 1";
+pub const e_regexp = "bad regular expression";
+/// Not "took too long": 9ns reads errors by their words, and that would be
+/// ENAMETOOLONG.
+pub const e_slow = "regular expression search took too much time, gave up";
+pub const e_syntax = "bad address syntax";
+pub const e_order = "addresses out of order";
+
+pub const Addr = struct {
+ text: []const u8,
+ lim: ?Range,
+ expr: []const u8,
+ i: usize = 0,
+ depth: u8 = 0,
+ /// Why `address` answered null.
+ err: []const u8 = e_syntax,
+
+ const max_depth = 32;
+ const Size = enum { char, line };
+
+ pub fn address(a: *Addr, ar_in: Range) ?Range {
+ const start = a.i;
+ var ar = ar_in;
+ var r = ar_in;
+ var dir: u8 = 0;
+ var size: Size = .line;
+ var c: u8 = 0;
+ while (a.i < a.expr.len) {
+ const prevc = c;
+ c = a.expr[a.i];
+ a.i += 1;
+ switch (c) {
+ ',', ';' => {
+ if (c == ';') ar = r;
+ if (prevc == 0) r.q0 = 0; // lhs defaults to 0
+ if (a.i >= a.expr.len) {
+ r.q1 = clip(a.text.len); // rhs defaults to $
+ } else {
+ if (a.depth >= max_depth) return null;
+ a.depth += 1;
+ const nr = a.address(ar) orelse return null;
+ a.depth -= 1;
+ r.q1 = nr.q1;
+ }
+ return r;
+ },
+ '+', '-' => {
+ if (prevc == '+' or prevc == '-') {
+ const nc = if (a.i < a.expr.len) a.expr[a.i] else 0;
+ if (nc != '#' and nc != '/' and nc != '?')
+ r = a.number(r, 1, prevc, .line) orelse return null;
+ }
+ dir = c;
+ },
+ '.', '$' => {
+ if (a.i != start + 1) {
+ a.i -= 1;
+ return r;
+ }
+ r = if (c == '.') ar else .{ .q0 = clip(a.text.len), .q1 = clip(a.text.len) };
+ dir = if (a.i < a.expr.len) '+' else 0;
+ },
+ '#', '0'...'9' => {
+ var digit = c;
+ if (c == '#') {
+ if (a.i >= a.expr.len or a.expr[a.i] < '0' or a.expr[a.i] > '9') {
+ a.i -= 1;
+ return r;
+ }
+ digit = a.expr[a.i];
+ a.i += 1;
+ size = .char;
+ }
+ var n: u64 = digit - '0';
+ while (a.i < a.expr.len) : (a.i += 1) {
+ const d = a.expr[a.i];
+ if (d < '0' or d > '9') break;
+ n = @min(n * 10 + (d - '0'), std.math.maxInt(u32));
+ }
+ // pardes's `line:col`, Look's `file:12:5` spelling (look.zig
+ // parsePathLine): the point at that column of that line, the
+ // column in bytes from 1, clamped to the line's end and snapped
+ // to a rune's start, as every address is. Not sam's.
+ if (size == .line and dir == 0 and a.i + 1 < a.expr.len and a.expr[a.i] == ':' and
+ a.expr[a.i + 1] >= '0' and a.expr[a.i + 1] <= '9')
+ {
+ a.i += 1;
+ var col: u64 = 0;
+ while (a.i < a.expr.len and a.expr[a.i] >= '0' and a.expr[a.i] <= '9') : (a.i += 1)
+ col = @min(col * 10 + (a.expr[a.i] - '0'), std.math.maxInt(u32));
+ const lines = modal.cursorLineCount(a.text);
+ if (n == 0 or n > lines or col == 0) {
+ a.err = if (col == 0) e_col_zero else e_range;
+ return null;
+ }
+ const q = clip(modal.runeOffsetAt(a.text, .{ .row = @intCast(n - 1), .col = @intCast(col - 1) }));
+ r = .{ .q0 = q, .q1 = q };
+ // The rows' range, `L:C-L2:C2` or `L:C-C2` (Recent,
+ // +Search, Jumplist): through its last character,
+ // inclusive, as the rows mean it -- so a row pastes in.
+ if (a.i + 1 < a.expr.len and a.expr[a.i] == '-' and a.expr[a.i + 1] >= '1' and a.expr[a.i + 1] <= '9') {
+ a.i += 1;
+ var n2: u64 = 0;
+ while (a.i < a.expr.len and a.expr[a.i] >= '0' and a.expr[a.i] <= '9') : (a.i += 1)
+ n2 = @min(n2 * 10 + (a.expr[a.i] - '0'), std.math.maxInt(u32));
+ var end_line = n;
+ var end_col = n2;
+ if (a.i + 1 < a.expr.len and a.expr[a.i] == ':' and a.expr[a.i + 1] >= '0' and a.expr[a.i + 1] <= '9') {
+ a.i += 1;
+ end_line = n2;
+ end_col = 0;
+ while (a.i < a.expr.len and a.expr[a.i] >= '0' and a.expr[a.i] <= '9') : (a.i += 1)
+ end_col = @min(end_col * 10 + (a.expr[a.i] - '0'), std.math.maxInt(u32));
+ }
+ if (end_line == 0 or end_line > lines or end_col == 0) {
+ a.err = if (end_col == 0) e_col_zero else e_range;
+ return null;
+ }
+ const last = modal.runeOffsetAt(a.text, .{ .row = @intCast(end_line - 1), .col = @intCast(end_col - 1) });
+ const e = clip(@min(a.text.len, last + (std.unicode.utf8ByteSequenceLength(if (last < a.text.len) a.text[last] else 'x') catch 1)));
+ if (e < q) {
+ a.err = e_order;
+ return null;
+ }
+ r.q1 = e;
+ }
+ continue;
+ }
+ r = a.number(r, @intCast(n), dir, size) orelse return null;
+ dir = 0;
+ size = .line;
+ },
+ '/', '?' => {
+ // `-/re/` searches back as `?re?` does (acme's address()
+ // takes the direction a `-` set, addr.c).
+ const back = c == '?' or dir == '-';
+ r = (a.regexp(r, a.pattern(c), back) catch {
+ a.err = e_slow;
+ return null;
+ }) orelse return null;
+ dir = 0;
+ size = .line;
+ },
+ else => {
+ a.i -= 1;
+ return r;
+ },
+ }
+ }
+ if (dir != 0) r = a.number(r, 1, dir, .line) orelse return null;
+ return r;
+ }
+
+ fn pattern(a: *Addr, delim: u8) []const u8 {
+ const s = a.i;
+ while (a.i < a.expr.len) {
+ const c = a.expr[a.i];
+ if (c == '\n') break;
+ a.i += 1;
+ if (c == '\\') {
+ if (a.i < a.expr.len) a.i += 1;
+ continue;
+ }
+ if (c == delim) return a.expr[s .. a.i - 1];
+ }
+ return a.expr[s..a.i];
+ }
+
+ fn number(a: *Addr, r_in: Range, n: u32, dir: u8, size: Size) ?Range {
+ var r = r_in;
+ if (size == .char) {
+ var off: i64 = n;
+ if (dir == '+') {
+ off = @as(i64, r.q1) + n;
+ } else if (dir == '-') {
+ if (r.q0 == 0 and n > 0) r.q0 = clip(a.text.len);
+ off = @as(i64, r.q0) - n;
+ }
+ if (off < 0 or off > @as(i64, @intCast(a.text.len))) {
+ a.err = e_range;
+ return null;
+ }
+ const g = clip(modal.runeStart(a.text, @intCast(off)));
+ return .{ .q0 = g, .q1 = g };
+ }
+ var line: i64 = n;
+ var q0: usize = r.q0;
+ var q1: usize = r.q1;
+ switch (dir) {
+ '-' => {
+ if (q0 < a.text.len) while (q0 > 0 and a.text[q0 - 1] != '\n') {
+ q0 -= 1;
+ };
+ q1 = q0;
+ while (line > 0 and q0 > 0) {
+ if (a.text[q0 - 1] == '\n') {
+ line -= 1;
+ q1 = q0;
+ }
+ q0 -= 1;
+ }
+ if (line > 1) {
+ a.err = e_range;
+ return null;
+ }
+ while (q0 > 0 and a.text[q0 - 1] != '\n') q0 -= 1;
+ return .{ .q0 = clip(q0), .q1 = clip(q1) };
+ },
+ else => {},
+ }
+ // Forward, sam's lineaddr (editors/sam/address.c:180-215), not acme's
+ // number(): line n is found by counting newlines, and a line just
+ // past the last newline is an empty one there, so `1` of an empty
+ // text is #0,#0 and `2` of "a\n" is #2,#2; only past that is it out
+ // of range.
+ const nc = a.text.len;
+ var p: usize = 0;
+ var p1: usize = 0;
+ if (n == 0) {
+ if (dir == 0 or q1 == 0) return .{ .q0 = 0, .q1 = 0 };
+ p1 = q1;
+ p = q1 - 1;
+ } else {
+ var k: u32 = 1;
+ if (dir != 0 and q1 > 0) {
+ p = q1 - 1;
+ k = @intFromBool(a.text[p] == '\n');
+ p += 1;
+ }
+ // Counted a block at a time (modal.lineStartExact), where a byte
+ // at a time made `echo 7000 > addr` walk every byte above it.
+ if (k < n) p += modal.lineStartExact(a.text[p..], n - k) orelse {
+ a.err = e_range;
+ return null;
+ };
+ p1 = p;
+ }
+ p = if (std.mem.indexOfScalarPos(u8, a.text, p, '\n')) |nl| nl + 1 else nc;
+ return .{ .q0 = clip(p1), .q1 = clip(p) };
+ }
+
+ /// acme's regexp(): forward from the end of `r` to the limit, wrapping
+ /// to the start of the text when there is none; backward, the last
+ /// match ending by the start of `r`, else the last one in the text.
+ /// The first match at or after `from`, else, with no limit, the first
+ /// from the top (a search wraps).
+ fn forward(a: *Addr, rx: *regexp_.Regex, from: usize, hi: usize) error{Slow}!?Range {
+ const ahead = rx.find(a.text, from, hi, hi) catch return error.Slow;
+ const m = ahead orelse (if (a.lim != null or from == 0) null else rx.find(a.text, 0, from - 1, hi) catch return error.Slow) orelse return null;
+ return .{ .q0 = clip(m.start), .q1 = clip(m.end) };
+ }
+
+ /// The last match ending at or before `limit`, else the last of all
+ /// (a search wraps).
+ fn backward(a: *Addr, rx: *regexp_.Regex, limit: u32) error{Slow}!?Range {
+ var last: ?Range = null;
+ var before: ?Range = null;
+ var at: usize = 0;
+ while (at <= a.text.len) {
+ const m = (rx.find(a.text, at, a.text.len, a.text.len) catch return error.Slow) orelse break;
+ const found_range: Range = .{ .q0 = clip(m.start), .q1 = clip(m.end) };
+ if (found_range.q1 <= limit) before = found_range;
+ last = found_range;
+ at = if (m.end > m.start) m.end else m.end + 1;
+ }
+ return before orelse last;
+ }
+
+ fn regexp(a: *Addr, r: Range, pat: []const u8, back: bool) error{Slow}!?Range {
+ if (pat.len == 0) {
+ a.err = "no previous regular expression";
+ return null;
+ }
+ var rx = regexp_.Regex.compile(pat) catch |err| {
+ a.err = if (err == error.Bad) e_regexp else regexp_.Regex.message(err);
+ return null;
+ };
+ // sam's nextmatch (editors/sam/address.c:97-119): an empty match
+ // right at the search's start is no progress, so the search is made
+ // again a character on (back: a character before), wrapping, and
+ // repeated `/^/` or `/$/` walks the lines.
+ const found = if (back) found: {
+ var f = try a.backward(&rx, r.q0);
+ if (f) |m| if (m.q0 == m.q1 and m.q1 == r.q0) {
+ f = try a.backward(&rx, if (r.q0 == 0) clip(a.text.len) else r.q0 - 1);
+ };
+ break :found f;
+ } else found: {
+ const hi = if (a.lim) |l| @min(@as(usize, l.q1), a.text.len) else a.text.len;
+ const from = @min(@as(usize, r.q1), hi);
+ var f = try a.forward(&rx, from, hi);
+ if (f) |m| if (m.q0 == m.q1 and m.q0 == from) {
+ const next = if (from + 1 > hi) (if (a.lim != null) break :found null else 0) else from + 1;
+ f = try a.forward(&rx, next, hi);
+ };
+ break :found f;
+ };
+ // A byte pattern may match inside a rune: the match covers the
+ // runes it touches.
+ if (found) |f| return .{ .q0 = clip(modal.runeStart(a.text, f.q0)), .q1 = clip(modal.runeEnd(a.text, f.q1)) };
+ return found orelse {
+ a.err = e_no_match;
+ return null;
+ };
+ }
+};
+
+const testing = std.testing;
+const th = @import("testing.zig");
+const tree = @import("tree.zig");
+const Node = tree.Node;
+const E = tree.E;
+const Status = tree.Status;
+
+test "an address is evaluated from the current one, as acme's are" {
+ const p = try th.withFile(testing.allocator, "a foo b foo c foo\n");
+ defer p.deinit();
+ const addr = Node.of(th.serialOf(p), .addr);
+ const Step = struct { expr: []const u8, q0: u32, q1: u32 };
+ _ = th.wr(p, addr, "#0");
+ for ([_]Step{
+ // each search starts where the last address ended
+ .{ .expr = "/foo/", .q0 = 2, .q1 = 5 },
+ .{ .expr = "/foo/", .q0 = 8, .q1 = 11 },
+ // `.` is that address, and `-` before a pattern searches back
+ .{ .expr = ".", .q0 = 8, .q1 = 11 },
+ .{ .expr = "-/foo/", .q0 = 2, .q1 = 5 },
+ .{ .expr = "./foo/", .q0 = 8, .q1 = 11 },
+ .{ .expr = "+/foo/", .q0 = 14, .q1 = 17 },
+ // a number then a pattern: the search starts at the number
+ .{ .expr = "#9/foo/", .q0 = 14, .q1 = 17 },
+ }) |c| {
+ try testing.expectEqual(Status.ok, th.wr(p, addr, c.expr).reply.status);
+ try testing.expectEqual(c.q0, p.panes[0].?.fs.addr.q0);
+ try testing.expectEqual(c.q1, p.panes[0].?.fs.addr.q1);
+ }
+ // A range whose end comes before its start is sam's error.
+ try testing.expectEqualStrings(e_order, th.wr(p, addr, "#10,#5").reply.ename);
+
+ // `;` evaluates its right side from its left (acme's addr.c:170-171,
+ // `ar = r`), `,` from the address the whole started at.
+ const q = try th.withFile(testing.allocator, "b a b\n");
+ defer q.deinit();
+ const qaddr = Node.of(th.serialOf(q), .addr);
+ _ = th.wr(q, qaddr, "#0");
+ try testing.expectEqual(Status.ok, th.wr(q, qaddr, "/a/;/b/").reply.status);
+ try testing.expectEqual(@as(u32, 2), q.panes[0].?.fs.addr.q0);
+ try testing.expectEqual(@as(u32, 5), q.panes[0].?.fs.addr.q1);
+ _ = th.wr(q, qaddr, "#0");
+ try testing.expectEqualStrings(e_order, th.wr(q, qaddr, "/a/,/b/").reply.ename);
+}
+
+test "a backward search along one long line takes time in its length, not its square" {
+ const gpa = testing.allocator;
+ const line = try gpa.alloc(u8, 7 * 16800);
+ defer gpa.free(line);
+ for (0..16800) |i| @memcpy(line[i * 7 ..][0..7], "answer ");
+ const p = try th.withFile(gpa, line);
+ defer p.deinit();
+ const t0 = std.Io.Timestamp.now(testing.io, .awake);
+ try testing.expectEqual(Status.ok, th.wr(p, Node.of(th.serialOf(p), .addr), "?a?").reply.status);
+ // Quadratic, it took seconds (6.4 s through 9P in Debug); linear, a
+ // few milliseconds.
+ const took = t0.durationTo(std.Io.Timestamp.now(testing.io, .awake)).toNanoseconds();
+ try testing.expect(took < std.time.ns_per_s);
+}
+
+test "an alternation anchoring some branches and not others is refused with why, a $ not counting" {
+ const p = try th.withFile(testing.allocator, "def\nfoo\n");
+ defer p.deinit();
+ const node = Node.of(th.serialOf(p), .addr);
+ for ([_][]const u8{ "/^def|x/", "/foo$|^zèbre/" }) |pat| {
+ const r = th.wr(p, node, pat);
+ try testing.expectEqual(E.INVAL, r.errno());
+ try testing.expectEqualStrings(regexp_.Regex.message(error.Mixed), r.reply.ename);
+ }
+ try testing.expectEqual(Status.ok, th.wr(p, node, "/foo$|def/").reply.status);
+}
+
+test "a pattern with a newline and an anchor mvzr would misread is refused EINVAL, by addr and by Edit" {
+ const p = try th.withFile(testing.allocator, "a\nfoo\n");
+ defer p.deinit();
+ const r = th.wr(p, Node.of(th.serialOf(p), .addr), "/(^|\\n)foo/");
+ try testing.expectEqual(E.INVAL, r.errno());
+ try testing.expectEqualStrings(regexp_.Regex.message(error.Anchor), r.reply.ename);
+ const e = th.wr(p, Node.of(th.serialOf(p), .ctl), "Edit ,x/(^|\\n)foo/d\n");
+ try testing.expectEqual(E.INVAL, e.errno());
+}
+
+test "a row's range, L:C-L2:C2 or L:C-C2, is an address through its last character" {
+ const p = try th.withFile(testing.allocator, "one\ntwo three\nfour\n");
+ defer p.deinit();
+ const addr = Node.of(th.serialOf(p), .addr);
+ const data = Node.of(th.serialOf(p), .xdata);
+ try testing.expectEqual(Status.ok, th.wr(p, addr, "2:5-2:9").reply.status);
+ try testing.expectEqualStrings("three", th.rd(p, data, 0, 64).bytes);
+ try testing.expectEqual(Status.ok, th.wr(p, addr, "2:1-3").reply.status);
+ try testing.expectEqualStrings("two", th.rd(p, data, 0, 64).bytes);
+ try testing.expectEqual(Status.ok, th.wr(p, addr, "1:2-3:2").reply.status);
+ try testing.expectEqualStrings("ne\ntwo three\nfo", th.rd(p, data, 0, 64).bytes);
+ try testing.expectEqualStrings(e_order, th.wr(p, addr, "2:5-1:1").reply.ename);
+ try testing.expectEqualStrings(e_range, th.wr(p, addr, "2:1-9:1").reply.ename);
+}
+
+test "an empty match at the search's start is passed over, as sam's nextmatch does" {
+ const p = try th.withFile(testing.allocator, "ab\ncd\nef\n");
+ defer p.deinit();
+ const addr = Node.of(th.serialOf(p), .addr);
+ const Case = struct { start: []const u8, expr: []const u8, want: []const u32 };
+ for ([_]Case{
+ // From #3 (the start of line 2), /^/ goes on to line 3.
+ .{ .start = "#3", .expr = "/^/", .want = &.{6} },
+ .{ .start = "#2", .expr = "/$/", .want = &.{ 5, 8 } },
+ .{ .start = "#3", .expr = "/x*/", .want = &.{ 4, 5, 6 } },
+ .{ .start = "#3", .expr = "?^?", .want = &.{0} },
+ }) |c| {
+ _ = th.wr(p, addr, c.start);
+ for (c.want) |q| {
+ try testing.expectEqual(Status.ok, th.wr(p, addr, c.expr).reply.status);
+ try testing.expectEqual(q, p.panes[0].?.fs.addr.q0);
+ try testing.expectEqual(q, p.panes[0].?.fs.addr.q1);
+ }
+ }
+}
+
+test "regular expressions search lines as sam's do, and a search wraps" {
+ const p = try th.withFile(testing.allocator, "alpha beta\nbeta gamma\ngamma\n");
+ defer p.deinit();
+ const serial = th.serialOf(p);
+ const addr = Node.of(serial, .addr);
+ const Case = struct { from: []const u8, expr: []const u8, q0: u32, q1: u32 };
+ for ([_]Case{
+ // ^ and $ at every line's start and end, not only the text's
+ .{ .from = "#0", .expr = "/^beta/", .q0 = 11, .q1 = 15 },
+ .{ .from = "#0", .expr = "/beta$/", .q0 = 6, .q1 = 10 },
+ .{ .from = "#0", .expr = "/^gamma$/", .q0 = 22, .q1 = 27 },
+ // . and [^...] stop at a newline; \n names one
+ .{ .from = "#0", .expr = "/a.*/", .q0 = 0, .q1 = 10 },
+ .{ .from = "#0", .expr = "/a[^x]*/", .q0 = 0, .q1 = 10 },
+ .{ .from = "#0", .expr = "/a\\nbeta/", .q0 = 9, .q1 = 15 },
+ // leftmost; of the alternatives there, mvzr's first
+ .{ .from = "#0", .expr = "/be|beta b/", .q0 = 6, .q1 = 8 },
+ .{ .from = "#0", .expr = "/gam|gamma/", .q0 = 16, .q1 = 19 },
+ .{ .from = "#0", .expr = "/(al)+pha?/", .q0 = 0, .q1 = 5 },
+ // `^` does not match where a search starts in the middle of a line
+ .{ .from = "#1", .expr = "/^/", .q0 = 11, .q1 = 11 },
+ // a search past the last match wraps to the text's start
+ .{ .from = "$", .expr = "/alpha/", .q0 = 0, .q1 = 5 },
+ // backward: the last match that ends by the start of dot
+ .{ .from = "#16", .expr = "?beta?", .q0 = 11, .q1 = 15 },
+ .{ .from = "#0", .expr = "?gamma?", .q0 = 22, .q1 = 27 },
+ }) |c| {
+ _ = th.wr(p, addr, c.from);
+ const w = th.wr(p, addr, c.expr);
+ try testing.expectEqual(Status.ok, w.reply.status);
+ try testing.expectEqual(c.q0, p.panes[0].?.fs.addr.q0);
+ try testing.expectEqual(c.q1, p.panes[0].?.fs.addr.q1);
+ }
+ // $ also matches at the end of text with no newline to end it
+ const q = try th.withFile(testing.allocator, "last line");
+ defer q.deinit();
+ _ = th.wr(q, Node.of(th.serialOf(q), .addr), "#0");
+ try testing.expectEqual(Status.ok, th.wr(q, Node.of(th.serialOf(q), .addr), "/line$/").reply.status);
+ try testing.expectEqual(@as(u32, 5), q.panes[0].?.fs.addr.q0);
+}
+
+test "a refused write to dot after a truncation changes nothing; a truncation with no write empties it at close" {
+ const p = try th.withFile(testing.allocator, "one\ntwo\nthree\n");
+ defer p.deinit();
+ const serial = th.serialOf(p);
+ const dot = Node.of(serial, .dot);
+ try testing.expectEqual(Status.ok, th.wr(p, dot, "2").reply.status);
+ const was = th.rd(p, dot, 0, 64).bytes;
+ var kept: [64]u8 = undefined;
+ @memcpy(kept[0..was.len], was);
+ // A shell's `echo /nomatch/ > dot`: truncate, then the refused write.
+ const h = th.call(p, .{ .tag = 1, .op = .open, .node = dot, .omode = 1 }).reply.handle;
+ _ = th.call(p, .{ .tag = 2, .op = .setattr, .node = dot, .truncate = true });
+ try testing.expectEqual(Status.err, th.call(p, .{ .tag = 3, .op = .write, .node = dot, .handle = h, .data = "/nomatch/" }).reply.status);
+ _ = th.call(p, .{ .tag = 4, .op = .release, .node = dot, .handle = h, .opened = true });
+ try testing.expectEqualStrings(kept[0..was.len], th.rd(p, dot, 0, 64).bytes);
+ // `: > dot`: the truncation alone empties it once its open goes.
+ const h2 = th.call(p, .{ .tag = 5, .op = .open, .node = dot, .omode = 1 }).reply.handle;
+ _ = th.call(p, .{ .tag = 6, .op = .setattr, .node = dot, .truncate = true });
+ _ = th.call(p, .{ .tag = 7, .op = .release, .node = dot, .handle = h2, .opened = true });
+ try testing.expectEqualStrings(" 0 0 ", th.rd(p, dot, 0, 64).bytes);
+}
+
+test "a failed address leaves none, so data refuses rather than act at the last one" {
+ const p = try th.withFile(testing.allocator, "one\ntwo\n");
+ defer p.deinit();
+ const serial = th.serialOf(p);
+ const addr = Node.of(serial, .addr);
+ const data = Node.of(serial, .data);
+ _ = th.wr(p, addr, "#0,#3");
+ try testing.expectEqualStrings(e_no_match, th.wr(p, addr, "/zzz/").reply.ename);
+ try testing.expectEqualStrings(pane_files.e_addr_failed, th.wr(p, data, "ONE").reply.ename);
+ try testing.expectEqualStrings(pane_files.e_addr_failed, th.rd(p, data, 0, 64).reply.ename);
+ try testing.expectEqual(Status.ok, th.rd(p, addr, 0, 64).reply.status);
+ try testing.expectEqualStrings("", th.rd(p, addr, 0, 64).bytes);
+ try testing.expectEqual(E.INVAL, th.call(p, .{ .tag = 1, .op = .setattr, .node = Node.of(serial, .xdata), .truncate = true }).errno());
+ try testing.expectEqualStrings("one\ntwo\n", p.panes[0].?.file.?.content);
+ // A good address gives it one again; truncating addr does not.
+ _ = th.wr(p, addr, "#0,#3");
+ try testing.expectEqual(Status.ok, th.wr(p, data, "ONE").reply.status);
+ try testing.expectEqualStrings("ONE\ntwo\n", p.panes[0].?.file.?.content);
+ _ = th.wr(p, addr, "99");
+ _ = th.call(p, .{ .tag = 1, .op = .setattr, .node = addr, .truncate = true });
+ try testing.expectEqualStrings(pane_files.e_addr_failed, th.wr(p, data, "0").reply.ename);
+}
+
+test "a shell's > on addr searches on from the last address, and 0 starts over" {
+ const p = try th.withFile(testing.allocator, "foo x foo y foo\n");
+ defer p.deinit();
+ const serial = th.serialOf(p);
+ const addr = Node.of(serial, .addr);
+ const data = Node.of(serial, .data);
+ // echo /foo/ > addr; printf foobar > data -- twice over, as a loop does.
+ for (0..3) |_| {
+ _ = th.call(p, .{ .tag = 1, .op = .setattr, .node = addr, .truncate = true });
+ try testing.expectEqual(Status.ok, th.wr(p, addr, "/foo/").reply.status);
+ _ = th.call(p, .{ .tag = 1, .op = .setattr, .node = data, .truncate = true });
+ try testing.expectEqual(Status.ok, th.wr(p, data, "foobar").reply.status);
+ }
+ try testing.expectEqualStrings("foobar x foobar y foobar\n", p.panes[0].?.file.?.content);
+ // .+#1 moves on from where the last write left the address.
+ _ = th.wr(p, addr, "0");
+ _ = th.call(p, .{ .tag = 1, .op = .setattr, .node = addr, .truncate = true });
+ try testing.expectEqual(Status.ok, th.wr(p, addr, ".+#1").reply.status);
+ try testing.expectEqualStrings(" 1 1 ", th.rd(p, addr, 0, 64).bytes);
+}
+
+test "the address language, form by form" {
+ const gpa = testing.allocator;
+ const p = try th.withFile(gpa, "one\ntwo\nthree\n");
+ defer p.deinit();
+ const serial = th.serialOf(p);
+ const addr = Node.of(serial, .addr);
+
+ const Case = struct { expr: []const u8, q0: u32, q1: u32 };
+ for ([_]Case{
+ .{ .expr = "#0", .q0 = 0, .q1 = 0 },
+ .{ .expr = "#5", .q0 = 5, .q1 = 5 },
+ .{ .expr = "0", .q0 = 0, .q1 = 0 },
+ .{ .expr = "1", .q0 = 0, .q1 = 4 },
+ .{ .expr = "2", .q0 = 4, .q1 = 8 },
+ .{ .expr = "$", .q0 = 14, .q1 = 14 },
+ .{ .expr = ",", .q0 = 0, .q1 = 14 },
+ .{ .expr = "1,2", .q0 = 0, .q1 = 8 },
+ .{ .expr = "#1,#4", .q0 = 1, .q1 = 4 },
+ .{ .expr = "2+1", .q0 = 8, .q1 = 14 },
+ .{ .expr = "$-1", .q0 = 8, .q1 = 14 },
+ .{ .expr = "/two/", .q0 = 4, .q1 = 7 },
+ .{ .expr = "/t.o/", .q0 = 4, .q1 = 7 },
+ .{ .expr = "1\n", .q0 = 0, .q1 = 4 },
+ // pardes's line:col, composing like any simple address.
+ .{ .expr = "2:2", .q0 = 5, .q1 = 5 },
+ .{ .expr = "2:99", .q0 = 7, .q1 = 7 },
+ .{ .expr = "2:2,3:1", .q0 = 5, .q1 = 8 },
+ .{ .expr = "2:2+#3", .q0 = 8, .q1 = 8 },
+ }) |c| {
+ _ = th.wr(p, addr, "#0");
+ const w = th.wr(p, addr, c.expr);
+ try testing.expectEqual(Status.ok, w.reply.status);
+ const got = th.rd(p, addr, 0, 64);
+ var want: [32]u8 = undefined;
+ try testing.expectEqualStrings(
+ try std.fmt.bufPrint(&want, "{d:>11} {d:>11} ", .{ c.q0, c.q1 }),
+ got.bytes,
+ );
+ }
+
+ _ = th.wr(p, addr, "1");
+ _ = th.wr(p, addr, ".");
+ try testing.expectEqual(@as(u32, 0), p.panes[0].?.fs.addr.q0);
+ try testing.expectEqual(@as(u32, 4), p.panes[0].?.fs.addr.q1);
+
+ _ = th.wr(p, addr, "$");
+ _ = th.wr(p, addr, "?o?");
+ try testing.expectEqual(@as(u32, 6), p.panes[0].?.fs.addr.q0); // the `o` in "two"
+ try testing.expectEqual(@as(u32, 7), p.panes[0].?.fs.addr.q1);
+
+ // limit is its own file: copying addr onto it bounds the search, and
+ // truncating it lifts the bound again.
+ const limit = Node.of(serial, .limit);
+ _ = th.wr(p, addr, "1");
+ try testing.expectEqualStrings("", th.rd(p, limit, 0, 64).bytes);
+ var copied: [64]u8 = undefined;
+ const pair = th.rd(p, addr, 0, 64).bytes;
+ @memcpy(copied[0..pair.len], pair);
+ _ = th.wr(p, limit, copied[0..pair.len]);
+ try testing.expectEqual(@as(u32, 4), p.panes[0].?.fs.limit.?.q1);
+ try testing.expectEqualStrings(" 0 4 ", th.rd(p, limit, 0, 64).bytes);
+ _ = th.wr(p, addr, "#0");
+ try testing.expectEqual(E.INVAL, th.wr(p, addr, "/three/").errno());
+ _ = th.call(p, .{ .tag = 6, .op = .setattr, .node = limit, .truncate = true });
+ try testing.expect(p.panes[0].?.fs.limit == null);
+ _ = th.wr(p, addr, "#0");
+ try testing.expectEqual(Status.ok, th.wr(p, addr, "/three/").reply.status);
+
+ for ([_][]const u8{ "zzz", "#", "//", "/nomatch/", "1 2 3", "99", "/a\\" }) |bad| {
+ _ = th.wr(p, addr, "#0");
+ try testing.expectEqual(E.INVAL, th.wr(p, addr, bad).errno());
+ }
+ // Each failure says which it is.
+ for ([_][2][]const u8{
+ .{ "zzz", e_syntax }, .{ "/nomatch/", e_no_match }, .{ "99", e_range },
+ .{ "#999", e_range }, .{ "/a[/", e_regexp }, .{ "/(a/", e_regexp },
+ .{ "/*a/", e_regexp }, .{ "99:1", e_range }, .{ "2:0", e_col_zero },
+ }) |c| {
+ _ = th.wr(p, addr, "#0");
+ try testing.expectEqualStrings(c[1], th.wr(p, addr, c[0]).reply.ename);
+ }
+
+ const nested = &@as([4096]u8, @splat(','));
+ _ = th.wr(p, addr, "#0");
+ try testing.expectEqual(E.INVAL, th.wr(p, addr, nested).errno());
+}
+
+test "a line just past the last newline is an empty one there, as sam's lineaddr has it" {
+ const Case = struct { text: []const u8, expr: []const u8, q0: u32, q1: u32 };
+ for ([_]Case{
+ .{ .text = "", .expr = "1", .q0 = 0, .q1 = 0 },
+ .{ .text = "a\n", .expr = "2", .q0 = 2, .q1 = 2 },
+ .{ .text = "a\nb", .expr = "2", .q0 = 2, .q1 = 3 },
+ .{ .text = "a\nb\n", .expr = "1", .q0 = 0, .q1 = 2 },
+ .{ .text = "a\nb\n", .expr = "0", .q0 = 0, .q1 = 0 },
+ .{ .text = "a\nb\n", .expr = "1+1", .q0 = 2, .q1 = 4 },
+ .{ .text = "a\nb\n", .expr = "$", .q0 = 4, .q1 = 4 },
+ }) |c| {
+ var a: Addr = .{ .text = c.text, .lim = null, .expr = c.expr };
+ const r = a.address(.{ .q0 = 0, .q1 = 0 }).?;
+ try testing.expectEqual(c.q0, r.q0);
+ try testing.expectEqual(c.q1, r.q1);
+ }
+ for ([_][2][]const u8{ .{ "", "2" }, .{ "a\n", "3" } }) |c| {
+ var a: Addr = .{ .text = c[0], .lim = null, .expr = c[1] };
+ try testing.expectEqual(null, a.address(.{ .q0 = 0, .q1 = 0 }));
+ try testing.expectEqualStrings(e_range, a.err);
+ }
+ // Edit's addresses are these: 1i on an empty file inserts.
+ const p = try th.withFile(testing.allocator, "");
+ defer p.deinit();
+ try testing.expectEqual(Status.ok, th.wr(p, Node.of(th.serialOf(p), .ctl), "Edit 1i/header/\n").reply.status);
+ try testing.expectEqualStrings("header", p.panes[0].?.file.?.content);
+}
+
+test "lineStartExact past an offset finds what a byte at a time finds" {
+ var prng: std.Random.DefaultPrng = .init(0x51ab);
+ const random = prng.random();
+ var buf: [200]u8 = undefined;
+ for (0..3000) |_| {
+ const len = random.uintLessThan(usize, buf.len);
+ for (buf[0..len]) |*b| b.* = if (random.uintLessThan(u8, 3) == 0) '\n' else 'x';
+ const text = buf[0..len];
+ const from = random.uintLessThan(usize, len + 1);
+ const count = 1 + random.uintLessThan(usize, 40);
+ var p = from;
+ var k: usize = 0;
+ const want: ?usize = while (k < count) {
+ if (p >= text.len) break null;
+ if (text[p] == '\n') k += 1;
+ p += 1;
+ } else p;
+ try std.testing.expectEqual(want, if (modal.lineStartExact(text[from..], count)) |at| from + at else null);
+ }
+}
diff --git a/core/ninep/cols.zig b/core/ninep/cols.zig
new file mode 100644
index 00000000..561a5ffa
--- /dev/null
+++ b/core/ninep/cols.zig
@@ -0,0 +1,727 @@
+//! The layout and the header tags: /layout, /tag (the workspace's) and
+//! /col/<serial>/tag (each column's; a column's serial stays while it lives,
+//! as a pane's does). acme serves no column files -- its columns
+//! are only a window's place -- so these go past it: a script can see where
+//! the panes are and edit the tags a person clicks in.
+const std = @import("std");
+const pardes = @import("../root.zig");
+const Pardes = pardes.Pardes;
+const tree = @import("tree.zig");
+const limits = @import("../memory.zig").limits;
+const panes = @import("../panes.zig");
+const tagline = pardes.tagline;
+const layout = pardes.layout;
+const Text = pardes.panes.Text;
+const Req = tree.Req;
+const Reply = tree.Reply;
+const E = tree.E;
+
+/// The column with the keyboard: the header's, when a column tag has it,
+/// else the active pane's. Null when the workspace tag has it and no pane
+/// is active.
+pub fn activeColumn(p: *const Pardes) ?usize {
+ if (p.headerColumn()) |c| return if (c < p.view().ncol) c else null;
+ const at = layout.findPane(p, p.view().active) orelse return null;
+ return at.col;
+}
+
+/// One line a column: its serial (the name /col/<serial> and the log give
+/// it, which stays while it lives), its index left to right, x and width in
+/// cells, `current` or `notcurrent` (rio's words, for the column with the
+/// keyboard), `empty` or `full`, and its panes' serials, top to bottom;
+/// then `active <serial>`: the active column, where pane/new and a look
+/// place a pane next (acme's activecol), not always the keyboard's.
+pub fn writeLayout(p: *Pardes, w: *std.Io.Writer) std.Io.Writer.Error!void {
+ const v = p.view();
+ const active = activeColumn(p);
+ for (0..p.view().ncol) |c| {
+ try w.print("{d} {d} {d} {d} {s} {s}", .{
+ layout.columnSerial(p, c), c, v.col_x[c], v.col_w[c],
+ if (active == c) "current" else "notcurrent", if (v.cols[c].n == 0) "empty" else "full",
+ });
+ for (v.cols[c].panes[0..p.view().cols[c].n]) |id| if (p.panes[id]) |pane| try w.print(" {d}", .{pane.serial});
+ try w.writeByte('\n');
+ }
+ if (layout.activeColumn(p) orelse active) |c| try w.print("active {d}\n", .{layout.columnSerial(p, c)}) else try w.writeAll("active -\n");
+}
+
+/// A header by its node: the workspace's (`serial` null) or the column's
+/// with that serial; null when that column has closed.
+const Header = struct { text: *Text, col: ?usize };
+
+fn header(p: *Pardes, serial: ?u32) ?Header {
+ const s = serial orelse return .{ .text = &p.global_tag, .col = null };
+ const c = layout.columnBySerial(p, s) orelse return null;
+ return .{ .text = &p.view().col_tags[c], .col = c };
+}
+
+pub fn headerText(p: *Pardes, serial: ?u32) ?[]const u8 {
+ const h = header(p, serial) orelse return null;
+ return if (h.col) |c| tagline.columnTag(p, c) else tagline.topbar(p);
+}
+
+pub fn read(p: *Pardes, req: Req, serial: ?u32) Reply {
+ applyTruncation(p, serial);
+ // As a pane tag reads: the text alone, no newline after it.
+ return tree.window(p, req, headerText(p, serial) orelse return Reply.fail(req.tag, E.NOENT));
+}
+
+/// A write appends, as a pane tag's does; the tag is one line, so a newline
+/// in it becomes a space (tagline.flattenHeaders), but after a truncation
+/// the newline that ends the write is dropped, as a pane tag drops it.
+pub fn write(p: *Pardes, req: Req, serial: ?u32) Reply {
+ const t = (header(p, serial) orelse return Reply.fail(req.tag, E.NOENT)).text;
+ if (req.data.len == 0) return .{ .tag = req.tag, .written = 0 };
+ const pending = p.fs.header_trunc_pending == rewriteKey(serial);
+ // The same checks as a pane tag's, whole or not at all; a refused
+ // write drops the truncation it would have come with.
+ if (pardes.ctlfs.pane.tagFault(req.data)) |why| {
+ if (pending) p.fs.header_trunc_pending = null;
+ return tree.failText(req.tag, E.INVAL, why);
+ }
+ const had = if (pending) 0 else headerText(p, serial).?.len;
+ // A rewrite drops its one trailing newline: `echo <4096 bytes> > tag`
+ // is 4096 bytes of tag, and fits.
+ const rewrite = pending or p.fs.header_rewrite == rewriteKey(serial);
+ const counted = req.data.len - @intFromBool(rewrite and req.data[req.data.len - 1] == '\n');
+ if (counted > limits.max_tag_tail -| had) {
+ if (pending) p.fs.header_trunc_pending = null;
+ return tree.failText(req.tag, E.NOSPC, pardes.ctlfs.pane.e_tag_over);
+ }
+ applyTruncation(p, serial);
+ const was = headerText(p, serial).?;
+ var data = req.data;
+ const rewriting = p.fs.header_rewrite == rewriteKey(serial);
+ // A newline held from the write before goes in once more text follows.
+ const held: []const u8 = if (rewriting and p.fs.header_held) " " else "";
+ p.fs.header_held = false;
+ if (rewriting and data[data.len - 1] == '\n') {
+ data = data[0 .. data.len - 1];
+ p.fs.header_held = true;
+ }
+ const next = std.mem.concat(p.gpa, u8, &.{ was, held, data }) catch return Reply.fail(req.tag, E.NOMEM);
+ std.mem.replaceScalar(u8, next, '\n', ' ');
+ if (t.own) |own| p.gpa.free(own);
+ t.own = next;
+ return .{ .tag = req.tag, .written = @intCast(req.data.len) };
+}
+
+/// Truncating clears it, as a pane tag's `cleartag`: its default words go
+/// too, and `u` in it brings them back.
+pub fn truncate(p: *Pardes, serial: ?u32) tree.Status {
+ if (header(p, serial) == null) return .err;
+ // Done with the write after it, which may yet be refused.
+ p.fs.header_trunc_pending = rewriteKey(serial);
+ return .ok;
+}
+
+/// A pending truncation of this header, done.
+pub fn applyTruncation(p: *Pardes, serial: ?u32) void {
+ if (p.fs.header_trunc_pending != rewriteKey(serial)) return;
+ p.fs.header_trunc_pending = null;
+ _ = clear(p, serial);
+}
+
+fn clear(p: *Pardes, serial: ?u32) tree.Status {
+ const t = (header(p, serial) orelse return .err).text;
+ t.remember(p.gpa, if (t.own) |own| .{ .text = own } else null) catch return .err;
+ const empty = p.gpa.alloc(u8, 0) catch unreachable; // no byte: the allocator is not asked
+ if (t.own) |own| p.gpa.free(own);
+ t.own = empty;
+ t.cur_row = 0;
+ t.cur_col = 0;
+ p.fs.header_rewrite = rewriteKey(serial);
+ p.fs.header_held = false;
+ return .ok;
+}
+
+/// Which header a truncation was of: the workspace's is 0 (no column's
+/// serial is), a column's its serial.
+fn rewriteKey(serial: ?u32) u32 {
+ return serial orelse 0;
+}
+
+pub fn released(p: *Pardes, serial: ?u32) void {
+ applyTruncation(p, serial);
+ if (p.fs.header_rewrite != rewriteKey(serial)) return;
+ p.fs.header_rewrite = null;
+ p.fs.header_held = false;
+}
+
+/// A column's ctl: the words that act on a column, as its tag's clicks do --
+/// Delcol, Joincol, New, Term -- one a line, each run as from that tag. What
+/// they say is the session's in the log (`msg -`), not the focused pane's.
+pub fn writeCtl(p: *Pardes, req: Req, serial: u32) Reply {
+ // What this write touched, alone, reads back (runBuiltin notes it).
+ p.fs.results_len = 0;
+ p.fs.session_write = true;
+ defer p.fs.session_write = false;
+ var lines = std.mem.splitScalar(u8, req.data, '\n');
+ while (lines.next()) |raw| {
+ const line = std.mem.trim(u8, raw, " \t\r");
+ if (line.len == 0 or pardes.exec.isComment(line)) continue;
+ const word = line[0 .. std.mem.indexOfAny(u8, line, " \t") orelse line.len];
+ const takes = for ([_][]const u8{ "Delcol", "Joincol", "New", "Term" }) |w| {
+ if (std.mem.eql(u8, w, word)) break true;
+ } else false;
+ // Plan 9's words for it, so a mount's errno is EINVAL as the root's
+ // and a pane's ctl give (9ns reads "control message").
+ if (!takes) return pardes.ctlfs.ctl.refuseQuoting(p, req, "unknown control message", word, ": a column's ctl takes Delcol, Joincol, New or Term");
+ // Only Term takes a word (its shell); `New extra` is no New.
+ if (!std.mem.eql(u8, word, "Term") and word.len != line.len)
+ return pardes.ctlfs.ctl.refuseQuoting(p, req, "wrong #args in control message", word, "");
+ const col = layout.columnBySerial(p, serial) orelse return Reply.fail(req.tag, E.NOENT);
+ p.exec_column = col;
+ defer p.exec_column = null;
+ p.exec_header = true;
+ defer p.exec_header = false;
+ if (pardes.ctlfs.ctl.runBuiltin(p, req, p.view().active, line)) |refusal| return refusal;
+ }
+ return .{ .tag = req.tag, .written = @intCast(req.data.len) };
+}
+
+/// A column's exec (`serial`), or the workspace tag's (/tagexec, null):
+/// each line run as a middle click on it in that tag, a column's acting on
+/// that column. A read answers the panes the last write touched, as /exec's
+/// does; what the words say is the session's in the log (`msg -`).
+pub fn writeExec(p: *Pardes, req: Req, serial: ?u32) Reply {
+ p.fs.results_len = 0;
+ p.fs.session_write = true;
+ defer p.fs.session_write = false;
+ var lines = std.mem.splitScalar(u8, req.data, '\n');
+ while (lines.next()) |raw| {
+ const line = std.mem.trim(u8, raw, " \t\r");
+ if (line.len == 0) continue;
+ for (line) |c| if ((c < ' ' and c != '\t') or c == 0x7f) return tree.failText(req.tag, E.INVAL, pardes.ctlfs.ctl.e_control);
+ if (pardes.ctlfs.ctl.tooLong(req, line)) |refusal| return refusal;
+ // A pane's word (Undo, Msg, Save) is no word of a tag no pane owns:
+ // refused as the root's ctl refuses it, never done at whichever
+ // pane has the keyboard. The tag's own words (New, Term, Find, Grep
+ // in a column's) are its to run.
+ if (paneWord(line, if (serial == null) pardes.config.topbar_str else tagline.column_tag_default))
+ return pardes.ctlfs.ctl.refuseQuoting(p, req, "not a session control message", pardes.ctlfs.ctl.firstWord(line), ": write it to pane/<n>/ctl");
+ const col = if (serial) |s| layout.columnBySerial(p, s) orelse return Reply.fail(req.tag, E.NOENT) else null;
+ // With no pane at all, a word runs at the stand-in, as a click in
+ // the empty window's tag does (runBuiltinFrom).
+ p.exec_column = col;
+ defer p.exec_column = null;
+ p.exec_header = true;
+ defer p.exec_header = false;
+ if (pardes.ctlfs.ctl.captured(p, req, p.view().active, true, line, true)) |refusal| return refusal;
+ }
+ return .{ .tag = req.tag, .written = @intCast(req.data.len) };
+}
+
+/// Whether `line` names a builtin that acts on a pane (every one of pane
+/// scope, Edit too, which the root's ctl takes at the active pane) and is
+/// not one of `own`, the words its tag holds by default: those a tag no
+/// pane owns refuses, never doing them at the pane with the keyboard.
+fn paneWord(line: []const u8, own: []const u8) bool {
+ const cmd = pardes.exec.commandText(line);
+ const word = cmd[0 .. std.mem.indexOfAny(u8, cmd, " \t+") orelse cmd.len];
+ const b = std.meta.stringToEnum(pardes.builtins.registry.Builtin(), word) orelse return false;
+ if (pardes.builtins.registry.scope(b) == .session) return false;
+ // A new pane is every tag's to make, in the session's directory.
+ if (b == .New or b == .Term) return false;
+ var words = std.mem.tokenizeScalar(u8, own, ' ');
+ while (words.next()) |w| if (std.mem.eql(u8, w, word)) return false;
+ return true;
+}
+
+/// rmdir of a column closes it when it is empty; one with panes is
+/// refused, saying so (close them, or Delcol on its ctl, which asks first).
+pub fn remove(p: *Pardes, req: Req, serial: u32, file: tree.ColFile) Reply {
+ if (file != .dir) return Reply.fail(req.tag, E.PERM);
+ const col = layout.columnBySerial(p, serial) orelse return Reply.fail(req.tag, E.NOENT);
+ if (p.view().cols[col].n > 0) return tree.failText(req.tag, E.NOTEMPTY, "column not empty: close its panes, or write Delcol to its ctl");
+ layout.removeColumn(p, col) catch return Reply.fail(req.tag, E.IO);
+ return .{ .tag = req.tag };
+}
+
+// ---- tests ----
+
+const testing = std.testing;
+const th = @import("testing.zig");
+const Node = tree.Node;
+
+test "New written to a column's exec makes its scratch in the session's directory, as tagexec's does" {
+ const p = try th.withFile(testing.allocator, "x\n");
+ defer p.deinit();
+ const session = "/project/src";
+ @memcpy(p.session_dir[0..session.len], session);
+ p.session_dir_len = session.len;
+ const serial = layout.columnSerial(p, 0);
+ const exec_node = tree.Node.ofCol(serial, .exec);
+ try testing.expectEqual(tree.Status.ok, th.wr(p, exec_node, "New\n").reply.status);
+ try testing.expectEqualStrings("/project/src/+New", p.panes[p.view().active].?.file.?.path);
+}
+
+test "Joincol is refused when the joined column cannot give each pane its tag and 2 rows" {
+ const p = try pardes.Pardes.init(testing.allocator, .{ .tty_only = true, .cols = 160, .rows = 12 });
+ defer p.deinit();
+ while (p.nextEffect()) |_| {}
+ const ctl = @backingInt(tree.TopFile.ctl);
+ const focus = @backingInt(tree.TopFile.focus);
+ // Two panes in the first column, then a second column of two.
+ const a = try th.newPane(p);
+ _ = a;
+ try testing.expectEqual(tree.Status.ok, th.wr(p, ctl, "Newcol\n").reply.status);
+ const b = try th.newPane(p);
+ var digits: [16]u8 = undefined;
+ _ = th.wr(p, focus, try std.fmt.bufPrint(&digits, "{d}\n", .{b}));
+ _ = try th.newPane(p);
+ try testing.expectEqual(@as(usize, 2), p.view().ncol);
+ try testing.expect(p.view().cols[0].n >= 2 and p.view().cols[1].n >= 2);
+ // Focus in the left column: joined, four panes want 12 rows of 10.
+ const left = p.panes[p.view().cols[0].panes[0]].?.serial;
+ _ = th.wr(p, focus, try std.fmt.bufPrint(&digits, "{d}\n", .{left}));
+ const r = th.wr(p, ctl, "Joincol\n");
+ try testing.expectEqual(tree.Status.err, r.reply.status);
+ try testing.expect(std.mem.indexOf(u8, r.reply.ename, "tag and 2 rows") != null);
+ try testing.expectEqual(@as(usize, 2), p.view().ncol);
+ try testing.expect(pardes.layout.minimaFit(p));
+}
+
+test "pane/new takes rows from a pane in another column before refusing ENOSPC" {
+ const p = try pardes.Pardes.init(testing.allocator, .{ .tty_only = true, .cols = 160, .rows = 16 });
+ defer p.deinit();
+ while (p.nextEffect()) |_| {}
+ const first = p.panes[p.view().active].?.serial;
+ // A second column holding one tall pane.
+ try testing.expectEqual(tree.Status.ok, th.wr(p, @backingInt(tree.TopFile.ctl), "Newcol\n").reply.status);
+ const tall = try th.newPane(p);
+ const tall_col = layout.findPane(p, p.paneBySerial(tall).?).?.col;
+ const focus = @backingInt(tree.TopFile.focus);
+ var digits: [16]u8 = undefined;
+ // From the first column, until pane/new is refused.
+ var moved = false;
+ for (0..pardes.MAX_PANES) |_| {
+ _ = th.wr(p, focus, try std.fmt.bufPrint(&digits, "{d}\n", .{first}));
+ const made = th.newPane(p) catch break;
+ if (layout.findPane(p, p.paneBySerial(made).?).?.col == tall_col) moved = true;
+ }
+ try testing.expect(moved);
+}
+
+test "in a > cut into several tag writes, those taken before a refused one stand" {
+ const p = try th.withFile(testing.allocator, "x\n");
+ defer p.deinit();
+ const node = tree.Node.of(th.serialOf(p), .tag);
+ _ = th.call(p, .{ .tag = 1, .op = .setattr, .node = node, .truncate = true });
+ const h = th.call(p, .{ .tag = 2, .op = .open, .node = node, .omode = 1 }).reply.handle;
+ try testing.expectEqual(tree.Status.ok, th.call(p, .{ .tag = 3, .op = .write, .node = node, .handle = h, .data = "Make" }).reply.status);
+ try testing.expectEqual(E.INVAL, th.call(p, .{ .tag = 4, .op = .write, .node = node, .handle = h, .data = " \x01" }).errno());
+ _ = th.call(p, .{ .tag = 5, .op = .release, .node = node, .handle = h, .opened = true });
+ try testing.expect(std.mem.endsWith(u8, th.rd(p, node, 0, 4096).bytes, "Make"));
+}
+
+test "exactly 4096 bytes written with echo's newline after a truncation fit every kind of tag" {
+ const p = try th.withFile(testing.allocator, "x\n");
+ defer p.deinit();
+ const serial = th.serialOf(p);
+ const text = &@as([4096]u8, @splat('w')) ++ "\n";
+ for ([_]u64{ tree.Node.of(serial, .tag), tree.Node.ofCol(layout.columnSerial(p, 0), .tag), @backingInt(tree.TopFile.tag) }) |node| {
+ _ = th.call(p, .{ .tag = 1, .op = .setattr, .node = node, .truncate = true });
+ const h = th.call(p, .{ .tag = 2, .op = .open, .node = node, .omode = 1 }).reply.handle;
+ const r = th.call(p, .{ .tag = 3, .op = .write, .node = node, .handle = h, .data = text });
+ try testing.expectEqual(tree.Status.ok, r.reply.status);
+ _ = th.call(p, .{ .tag = 4, .op = .release, .node = node, .handle = h, .opened = true });
+ try testing.expect(std.mem.endsWith(u8, th.rd(p, node, 0, 1 << 16).bytes, &@as([4096]u8, @splat('w'))));
+ // One more byte is over.
+ _ = th.call(p, .{ .tag = 5, .op = .setattr, .node = node, .truncate = true });
+ const h2 = th.call(p, .{ .tag = 6, .op = .open, .node = node, .omode = 1 }).reply.handle;
+ try testing.expectEqual(E.NOSPC, th.call(p, .{ .tag = 7, .op = .write, .node = node, .handle = h2, .data = &@as([4097]u8, @splat('w')) ++ "\n" }).errno());
+ _ = th.call(p, .{ .tag = 8, .op = .release, .node = node, .handle = h2, .opened = true });
+ }
+}
+
+test "a Newcol refused because the tags would not fit logs its err alone and spends no column serial" {
+ const p = try pardes.Pardes.init(testing.allocator, .{ .tty_only = true, .cols = 160, .rows = 14 });
+ defer p.deinit();
+ while (p.nextEffect()) |_| {}
+ // Long tags wrap onto more rows as their column narrows: the boot's
+ // two panes share one, and each keeps its tag and two rows.
+ const made = try th.newPane(p);
+ const pane = p.panes[p.paneBySerial(made).?].?;
+ const col = layout.findPane(p, p.paneBySerial(made).?).?.col;
+ for (p.view().cols[col].panes[0..p.view().cols[col].n]) |k| {
+ const each = p.panes[k].?;
+ if (each.tag.own) |old| p.gpa.free(old);
+ each.tag.own = try p.gpa.dupe(u8, std.mem.asBytes(&@as([60][5]u8, @splat("word ".*))));
+ }
+ try testing.expect(p.view().cols[col].n >= 2);
+ p.sync();
+ const ctl = @backingInt(tree.TopFile.ctl);
+ const focus = @backingInt(tree.TopFile.focus);
+ var digits: [16]u8 = undefined;
+ const own = try std.fmt.bufPrint(&digits, "{d}\n", .{pane.serial});
+ var refused = false;
+ for (0..pardes.MAX_COLS) |_| {
+ // From the long tag's column, so it is the one split narrower.
+ _ = th.wr(p, focus, own);
+ const serial_before = p.next_column_serial;
+ const log_before = try pardes.ctlfs.events.freezeLog(p);
+ defer p.gpa.free(log_before.bytes);
+ const r = th.wr(p, ctl, "Newcol\n");
+ if (r.reply.status == .ok) continue;
+ if (std.mem.indexOf(u8, r.reply.ename, "tags would not fit") == null) continue;
+ refused = true;
+ try testing.expectEqual(serial_before, p.next_column_serial);
+ const log_after = try pardes.ctlfs.events.freezeLog(p);
+ defer p.gpa.free(log_after.bytes);
+ const added = log_after.bytes[log_before.bytes.len..];
+ try testing.expect(std.mem.startsWith(u8, added, "err "));
+ try testing.expectEqual(@as(usize, 1), std.mem.count(u8, added, "\n"));
+ break;
+ }
+ try testing.expect(refused);
+}
+
+test "a tagexec word that makes, acts on and focuses no pane reads back nothing" {
+ const p = try th.withFile(testing.allocator, "x\n");
+ defer p.deinit();
+ const tagexec = @backingInt(tree.TopFile.tagexec);
+ try testing.expectEqual(tree.Status.ok, th.wr(p, tagexec, "Newcol\n").reply.status);
+ try testing.expectEqualStrings("", th.rd(p, tagexec, 0, 64).bytes);
+ // A column's New makes one, and answers it.
+ const col_exec = tree.Node.ofCol(layout.columnSerial(p, 0), .exec);
+ try testing.expectEqual(tree.Status.ok, th.wr(p, col_exec, "New\n").reply.status);
+ var want: [16]u8 = undefined;
+ try testing.expectEqualStrings(try std.fmt.bufPrint(&want, "{d}\n", .{p.panes[p.view().active].?.serial}), th.rd(p, col_exec, 0, 64).bytes);
+}
+
+test "New written to a column's ctl reads back the new pane alone, as its exec does" {
+ const p = try th.withFile(testing.allocator, "x\n");
+ defer p.deinit();
+ const root_exec = @backingInt(tree.TopFile.exec);
+ _ = th.wr(p, root_exec, "Msg before\n");
+ const ctl_node = tree.Node.ofCol(layout.columnSerial(p, 0), .ctl);
+ try testing.expectEqual(tree.Status.ok, th.wr(p, ctl_node, "New\n").reply.status);
+ var want: [16]u8 = undefined;
+ try testing.expectEqualStrings(try std.fmt.bufPrint(&want, "{d}\n", .{p.panes[p.view().active].?.serial}), th.rd(p, root_exec, 0, 64).bytes);
+}
+
+test "a pane's word written to /tagexec or a column's exec is refused, and acts on no pane" {
+ const p = try th.withFile(testing.allocator, "x\n");
+ defer p.deinit();
+ const col_exec = tree.Node.ofCol(layout.columnSerial(p, 0), .exec);
+ for ([_]u64{ @backingInt(tree.TopFile.tagexec), col_exec }) |node| {
+ for ([_][]const u8{ "Undo\n", "Msg hi\n", "Redo\n" }) |line| {
+ const refused = th.wr(p, node, line);
+ try testing.expectEqual(E.INVAL, refused.errno());
+ try testing.expectStringStartsWith(refused.reply.ename, "not a session control message");
+ }
+ }
+ // The column tag's own words still run there.
+ try testing.expectEqual(tree.Status.ok, th.wr(p, col_exec, "New\n").reply.status);
+}
+
+test "Help and Find at /tagexec act in the session's directory, not the keyboard pane's" {
+ const p = try th.withFile(testing.allocator, "x\n");
+ defer p.deinit();
+ var tmp = testing.tmpDir(.{});
+ defer tmp.cleanup();
+ try tmp.dir.writeFile(testing.io, .{ .sub_path = "needle.txt", .data = "n\n" });
+ var buf: [4096]u8 = undefined;
+ const session = buf[0..try tmp.dir.realPath(testing.io, &buf)];
+ @memcpy(p.session_dir[0..session.len], session);
+ p.session_dir_len = @intCast(session.len);
+ const tagexec = @backingInt(tree.TopFile.tagexec);
+ for ([_][]const u8{ "Help\n", "Find needle\n" }) |line| {
+ try testing.expectEqual(tree.Status.ok, th.wr(p, tagexec, line).reply.status);
+ const made = p.panes[p.view().active].?.file.?.path;
+ try testing.expectEqualStrings(session, std.Io.Dir.path.dirname(made).?);
+ }
+}
+
+test "a shell command at /tagexec or a column's exec is a command pane in the session's directory, never typed into the keyboard's terminal" {
+ if (pardes.Term.ops == null) return error.SkipZigTest; // a command pane
+ const p = try Pardes.init(testing.allocator, .{ .tty_only = true, .cols = 80, .rows = 30 });
+ defer p.deinit();
+ while (p.nextEffect()) |_| {}
+ const term = p.panes[p.view().active].?;
+ try testing.expect(pardes.exec.takesCommandLine(p, p.view().active));
+ const col_exec = tree.Node.ofCol(layout.columnSerial(p, 0), .exec);
+ for ([_]u64{ @backingInt(tree.TopFile.tagexec), col_exec }) |node| {
+ p.view().active = p.paneBySerial(term.serial).?;
+ const before = p.next_serial;
+ const r = th.wr(p, node, "echo from-the-tag\n");
+ try testing.expectEqual(tree.Status.ok, r.reply.status);
+ try testing.expectEqualStrings("", r.pty());
+ try testing.expectEqual(before + 1, p.next_serial);
+ const made = p.panes[p.paneBySerial(p.next_serial).?].?; // the newest
+ try testing.expectEqualStrings("echo from-the-tag", made.command.?);
+ try testing.expectEqualStrings(p.sessionDir(), made.cwdSlice());
+ }
+}
+
+test "New and Term run at /tagexec and a column's exec, with no pane at all too" {
+ if (pardes.Term.ops == null) return error.SkipZigTest; // a shell
+ const p = try th.withFile(testing.allocator, "x\n");
+ defer p.deinit();
+ const tagexec = @backingInt(tree.TopFile.tagexec);
+ const col_exec = tree.Node.ofCol(layout.columnSerial(p, 0), .exec);
+ for ([_]u64{ tagexec, col_exec }) |node| for ([_][]const u8{ "New\n", "Term\n" }) |line| {
+ const before = p.next_serial;
+ try testing.expectEqual(tree.Status.ok, th.wr(p, node, line).reply.status);
+ try testing.expectEqual(before + 1, p.next_serial);
+ };
+ // Every pane gone: the workspace tag makes one all the same.
+ for ([_][]const u8{ "New\n", "Term\n" }) |line| {
+ while (p.view().ncol > 0) {
+ const first = p.panes[p.view().cols[0].panes[0]].?.serial;
+ _ = th.wr(p, tree.Node.of(first, .ctl), "delete\n");
+ if (panes.anyPane(p) == null) break;
+ }
+ try testing.expect(panes.anyPane(p) == null);
+ try testing.expectEqual(tree.Status.ok, th.wr(p, tagexec, line).reply.status);
+ try testing.expect(panes.anyPane(p) != null);
+ }
+}
+
+test "every pane word a tag no pane owns does not hold is refused there, Edit included, and the pane is untouched" {
+ const p = try th.withFile(testing.allocator, "keep me\n");
+ defer p.deinit();
+ const Builtin = pardes.builtins.registry.Builtin();
+ const col_exec = tree.Node.ofCol(layout.columnSerial(p, 0), .exec);
+ for ([_]struct { node: u64, own: []const u8 }{
+ .{ .node = @backingInt(tree.TopFile.tagexec), .own = pardes.config.topbar_str },
+ .{ .node = col_exec, .own = tagline.column_tag_default },
+ }) |tag_file| {
+ var checked: usize = 0;
+ for (std.enums.values(Builtin)) |b| {
+ if (pardes.builtins.registry.scope(b) == .session) continue;
+ if (b == .New or b == .Term) continue; // every tag's
+ var owned = false;
+ var words = std.mem.tokenizeScalar(u8, tag_file.own, ' ');
+ while (words.next()) |w| owned = owned or std.mem.eql(u8, w, @tagName(b));
+ if (owned) continue;
+ var line: [64]u8 = undefined;
+ const text = try std.fmt.bufPrint(&line, "{s}{s}\n", .{ @tagName(b), if (b == .Edit) " ,d" else if (pardes.builtins.registry.requiresArg(b)) " x" else "" });
+ const refused = th.wr(p, tag_file.node, text);
+ try testing.expectEqual(E.INVAL, refused.errno());
+ try testing.expectStringStartsWith(refused.reply.ename, "not a session control message");
+ checked += 1;
+ }
+ try testing.expect(checked > 20);
+ }
+ // `Edit ,d` wiped the pane with the keyboard: nothing touched it.
+ try testing.expectEqualStrings("keep me\n", p.panes[0].?.file.?.content);
+}
+
+test "layout lists each column's place, panes and state, and the active one" {
+ const p = try th.withFile(testing.allocator, "x\n");
+ defer p.deinit();
+ layout.newColumn(p, p.view().active);
+ p.sync();
+ const first_serial = layout.columnSerial(p, 0);
+ const new_serial = layout.columnSerial(p, 1);
+ try testing.expect(first_serial != new_serial);
+ const layout_node = @backingInt(tree.TopFile.layout);
+ const text = th.rd(p, layout_node, 0, 4096).bytes;
+ var want: [256]u8 = undefined;
+ const first = try std.fmt.bufPrint(&want, "{d} 0 {d} {d} notcurrent full {d}\n", .{ first_serial, p.view().col_x[0], p.view().col_w[0], p.panes[0].?.serial });
+ try testing.expect(std.mem.startsWith(u8, text, first));
+ // Newcol gives the new, empty column's tag the keyboard.
+ try testing.expect(std.mem.indexOf(u8, text, "current empty\n") != null);
+ try testing.expect(std.mem.endsWith(u8, text, try std.fmt.bufPrint(&want, "active {d}\n", .{new_serial})));
+ try testing.expect(text.len > 0);
+ try testing.expectEqual(@as(u64, 0), th.call(p, .{ .tag = 1, .op = .getattr, .node = layout_node }).reply.attr.size); // generated by each read
+ // /index says which column each pane is in, by its serial, last.
+ try testing.expect(std.mem.endsWith(u8, th.rd(p, @backingInt(tree.TopFile.index), 0, 4096).bytes, try std.fmt.bufPrint(&want, " {d}\n", .{first_serial})));
+ try testing.expect(th.logHas(p, try std.fmt.bufPrint(&want, "newcol {d}\n", .{new_serial})));
+ // A column that closes takes its name with it; the others keep theirs.
+ try layout.removeColumn(p, 1);
+ try testing.expect(th.logHas(p, try std.fmt.bufPrint(&want, "delcol {d}\n", .{new_serial})));
+ try testing.expectEqual(E.NOENT, th.look_up(p, @backingInt(tree.TopFile.col), try std.fmt.bufPrint(&want, "{d}", .{new_serial})).errno());
+ try testing.expectEqual(first_serial, layout.columnSerial(p, 0));
+}
+
+test "a column's tag and the workspace's read, replace and append as a pane tag does, on one line" {
+ const p = try th.withFile(testing.allocator, "x\n");
+ defer p.deinit();
+ const col_dir = @backingInt(tree.TopFile.col);
+ const serial = layout.columnSerial(p, 0);
+ var name: [16]u8 = undefined;
+ try testing.expectEqual(tree.Status.ok, th.look_up(p, col_dir, try std.fmt.bufPrint(&name, "{d}", .{serial})).reply.status);
+ try testing.expectEqual(E.NOENT, th.look_up(p, col_dir, "0").errno());
+ try testing.expectEqual(E.NOENT, th.look_up(p, col_dir, "777").errno());
+ const tag = Node.ofCol(serial, .tag);
+ try testing.expectEqual(tree.Status.ok, th.look_up(p, Node.ofCol(serial, .dir), "tag").reply.status);
+ try testing.expectEqualStrings("New Term Find Grep Joincol Delcol", th.rd(p, tag, 0, 4096).bytes);
+ // `echo Make > tag`: cleared, then the newline ending the write dropped.
+ _ = th.call(p, .{ .tag = 1, .op = .setattr, .node = tag, .truncate = true });
+ _ = th.wr(p, tag, "Make\n");
+ try testing.expectEqualStrings("Make", th.rd(p, tag, 0, 4096).bytes);
+ _ = th.call(p, .{ .tag = 2, .op = .release, .node = tag });
+ // `>>` appends; a newline in a one-line tag is a space.
+ _ = th.wr(p, tag, " Lint\nNow");
+ try testing.expectEqualStrings("Make Lint Now", th.rd(p, tag, 0, 4096).bytes);
+ const top = @backingInt(tree.TopFile.tag);
+ _ = th.call(p, .{ .tag = 3, .op = .setattr, .node = top, .truncate = true });
+ _ = th.wr(p, top, "Newcol Exit\n");
+ try testing.expectEqualStrings("Newcol Exit", tagline.topbar(p));
+}
+
+test "a focus write makes its pane's column the active one: layout says so and pane/new goes there" {
+ const p = try th.withFile(testing.allocator, "x\n");
+ defer p.deinit();
+ const left = p.panes[0].?.serial;
+ layout.newColumn(p, p.view().active);
+ panes.newScratchFor(p, p.view().active, .fs); // fills the new, right column
+ p.sync();
+ try testing.expectEqual(@as(usize, 1), layout.findPane(p, p.view().active).?.col);
+ var digits: [16]u8 = undefined;
+ _ = th.wr(p, @backingInt(tree.TopFile.focus), try std.fmt.bufPrint(&digits, "{d}\n", .{left}));
+ var want: [32]u8 = undefined;
+ const text = th.rd(p, @backingInt(tree.TopFile.layout), 0, 4096).bytes;
+ try testing.expect(std.mem.endsWith(u8, text, try std.fmt.bufPrint(&want, "active {d}\n", .{layout.columnSerial(p, 0)})));
+ const made = th.call(p, .{ .tag = 1, .op = .open, .node = @backingInt(tree.TopFile.new) }).reply.handle;
+ try testing.expectEqual(@as(usize, 0), layout.findPane(p, p.paneBySerial(made).?).?.col);
+}
+
+test "a refused write after a truncation leaves every kind of tag as it was, and Dump still works" {
+ const p = try th.withFile(testing.allocator, "x\n");
+ defer p.deinit();
+ const serial = th.serialOf(p);
+ const col = layout.columnSerial(p, 0);
+ const big = &@as([limits.max_tag_tail + 1]u8, @splat('w'));
+ // Each tag: a truncating open, then a write too long: nothing changes.
+ for ([_]u64{ Node.of(serial, .tag), Node.ofCol(col, .tag), @backingInt(tree.TopFile.tag) }) |node| {
+ _ = th.wr(p, node, " Mine");
+ const before = try testing.allocator.dupe(u8, th.rd(p, node, 0, 1 << 16).bytes);
+ defer testing.allocator.free(before);
+ _ = th.call(p, .{ .tag = 1, .op = .setattr, .node = node, .truncate = true });
+ const h = th.call(p, .{ .tag = 2, .op = .open, .node = node, .omode = 1 }).reply.handle;
+ const r = th.call(p, .{ .tag = 3, .op = .write, .node = node, .handle = h, .data = big });
+ try testing.expectEqual(E.NOSPC, r.errno());
+ try testing.expectEqualStrings("no space: over 4096 bytes", r.reply.ename);
+ // Its err record names the file once: `tag: no space`, never `tag: tag:`.
+ try testing.expect(th.logHas(p, "tag: no space: over 4096 bytes"));
+ try testing.expect(!th.logHas(p, "tag: tag:"));
+ _ = th.call(p, .{ .tag = 4, .op = .release, .node = node, .handle = h, .opened = true });
+ try testing.expectEqualStrings(before, th.rd(p, node, 0, 1 << 16).bytes);
+ // A control character is refused the same way on every kind.
+ try testing.expectEqual(E.INVAL, th.wr(p, node, "a\x01b").errno());
+ // A truncation with no write after it clears at the close.
+ _ = th.call(p, .{ .tag = 5, .op = .setattr, .node = node, .truncate = true });
+ const e = th.call(p, .{ .tag = 6, .op = .open, .node = node, .omode = 1 }).reply.handle;
+ _ = th.call(p, .{ .tag = 7, .op = .release, .node = node, .handle = e, .opened = true });
+ try testing.expect(std.mem.indexOf(u8, th.rd(p, node, 0, 1 << 16).bytes, "Mine") == null);
+ }
+ try pardes.dump.dumpState(p);
+}
+
+test "a column's ctl and exec act on it as its tag would, and rmdir closes it only empty" {
+ const p = try th.withFile(testing.allocator, "x\n");
+ defer p.deinit();
+ const first = layout.columnSerial(p, 0);
+ layout.newColumn(p, p.view().active);
+ const empty = layout.columnSerial(p, 1);
+ // New on the empty column's ctl fills it, wherever the keyboard is.
+ try testing.expectEqual(tree.Status.ok, th.wr(p, Node.ofCol(empty, .ctl), "New\n").reply.status);
+ try testing.expectEqual(@as(usize, 1), p.view().cols[1].n);
+ try testing.expectEqual(E.INVAL, th.wr(p, Node.ofCol(empty, .ctl), "Exit\n").errno());
+ var rec: [64]u8 = undefined;
+ try testing.expect(th.logHas(p, try std.fmt.bufPrint(&rec, "err - col/{d}/ctl: unknown control message \"Exit\"", .{empty})));
+ // rmdir refuses a column with a pane, and says why, in its error alone.
+ const full = th.call(p, .{ .tag = 1, .op = .release, .node = Node.ofCol(empty, .dir), .remove = true });
+ try testing.expectEqual(E.NOTEMPTY, full.errno());
+ try testing.expect(std.mem.startsWith(u8, full.reply.ename, "column not empty"));
+ try testing.expect(!th.logHas(p, try std.fmt.bufPrint(&rec, "err - col/{d}: column not empty", .{empty})));
+ // exec runs a word as a click in that column's tag: Delcol closes it.
+ try testing.expectEqual(tree.Status.ok, th.wr(p, Node.ofCol(empty, .exec), "Delcol\n").reply.status);
+ try testing.expectEqual(@as(?usize, null), layout.columnBySerial(p, empty));
+ // An empty column goes on rmdir.
+ layout.newColumn(p, p.view().active);
+ const made = layout.columnSerial(p, 1);
+ try testing.expectEqual(tree.Status.ok, th.call(p, .{ .tag = 2, .op = .release, .node = Node.ofCol(made, .dir), .remove = true }).reply.status);
+ try testing.expectEqual(@as(?usize, null), layout.columnBySerial(p, made));
+ try testing.expectEqual(first, layout.columnSerial(p, 0));
+ // Joincol folds a column into the one on its right, which keeps its own
+ // serial and tag.
+ layout.newColumn(p, p.view().active);
+ const right = layout.columnSerial(p, 1);
+ _ = th.wr(p, Node.ofCol(right, .tag), " Mine");
+ try testing.expectEqual(tree.Status.ok, th.wr(p, Node.ofCol(first, .ctl), "Joincol\n").reply.status);
+ try testing.expectEqual(@as(?usize, null), layout.columnBySerial(p, first));
+ try testing.expectEqual(@as(?usize, 0), layout.columnBySerial(p, right));
+ try testing.expect(std.mem.endsWith(u8, headerText(p, right).?, " Mine"));
+ // The root's ctl points a column word at the column's own.
+ try testing.expect(std.mem.endsWith(u8, th.wr(p, @backingInt(tree.TopFile.ctl), "Delcol\n").reply.ename, "write it to col/<serial>/ctl"));
+}
+
+test "tagexec runs a word as a click in the workspace tag; exec files read back what they touched; their messages are the session's" {
+ const p = try th.withFile(testing.allocator, "x\n");
+ defer p.deinit();
+ const tagexec = @backingInt(tree.TopFile.tagexec);
+ try testing.expectEqual(tree.Status.ok, th.look_up(p, tree.root, "tagexec").reply.status);
+ try testing.expectEqual(tree.Status.ok, th.wr(p, tagexec, "Newcol\n").reply.status);
+ try testing.expectEqual(@as(usize, 2), p.view().ncol);
+ // Its announcement is the message row's, never logged; a pane's word
+ // such as Msg is refused there.
+ try testing.expect(!th.logHas(p, "msg - Newcol\n"));
+ try testing.expectEqual(E.INVAL, th.wr(p, tagexec, "Msg from the top\n").errno());
+ // A column's exec makes a pane there and reads it back.
+ const right = layout.columnSerial(p, 1);
+ try testing.expectEqual(tree.Status.ok, th.wr(p, Node.ofCol(right, .exec), "New\n").reply.status);
+ const made = p.panes[p.view().cols[1].panes[0]].?.serial;
+ var want: [16]u8 = undefined;
+ try testing.expectEqualStrings(try std.fmt.bufPrint(&want, "{d}\n", .{made}), th.rd(p, Node.ofCol(right, .exec), 0, 64).bytes);
+ try testing.expectEqualStrings(try std.fmt.bufPrint(&want, "{d}\n", .{made}), th.rd(p, tagexec, 0, 64).bytes);
+ try testing.expect(!th.logHas(p, "msg - New\n")); // announced on the message row only
+}
+
+test "a word run from the workspace's or a column's tag runs in the session's directory, a pane's in its own" {
+ if (pardes.Term.ops == null) return error.SkipZigTest; // a command pane
+ const p = try th.withFile(testing.allocator, "x\n");
+ defer p.deinit();
+ const session = p.sessionDir();
+ try testing.expect(!std.mem.eql(u8, session, pardes.Pardes.paneDir(p.panes[0].?))); // the file is elsewhere
+ const dirs = [_]u64{ @backingInt(tree.TopFile.tagexec), Node.ofCol(layout.columnSerial(p, 0), .exec) };
+ for (dirs) |node| {
+ try testing.expectEqual(tree.Status.ok, th.wr(p, node, "true\n").reply.status);
+ const made = p.paneBySerial(p.fs.results[0]).?;
+ try testing.expectEqualStrings(session, pardes.Pardes.paneDir(p.panes[made].?));
+ try p.removePane(made, null);
+ }
+ const from_pane = p.panes[0].?.serial;
+ _ = th.wr(p, Node.of(from_pane, .exec), "true\n");
+ const made = p.paneBySerial(p.fs.results[0]).?;
+ try testing.expectEqualStrings(pardes.Pardes.paneDir(p.panes[0].?), pardes.Pardes.paneDir(p.panes[made].?));
+}
+
+test "a command run from a column's tag gets its pane in that column, not the last" {
+ if (pardes.Term.ops == null) return error.SkipZigTest; // a command pane
+ const p = try th.withFile(testing.allocator, "x\n");
+ defer p.deinit();
+ layout.newColumn(p, p.view().active);
+ panes.newScratchFor(p, p.view().active, .fs); // fills the new, right column
+ p.sync();
+ const left = layout.columnSerial(p, 0);
+ try testing.expectEqual(tree.Status.ok, th.wr(p, Node.ofCol(left, .exec), "true\n").reply.status);
+ const made = p.paneBySerial(p.fs.results[0]).?;
+ try testing.expectEqual(@as(usize, 0), layout.findPane(p, made).?.col);
+ // Finished, it is reused only by its own column's commands.
+ p.panes[made].?.command_done = true;
+ p.panes[made].?.command_pty = false;
+ try testing.expectEqual(tree.Status.ok, th.wr(p, Node.ofCol(layout.columnSerial(p, 1), .exec), "true\n").reply.status);
+ const other = p.paneBySerial(p.fs.results[0]).?;
+ try testing.expect(other != made);
+ try testing.expectEqual(@as(usize, 1), layout.findPane(p, other).?.col);
+}
+
+test "a column's ctl refuses an unknown word and an argument as the other ctls do" {
+ const p = try th.withFile(testing.allocator, "x\n");
+ defer p.deinit();
+ const ctl_node = Node.ofCol(layout.columnSerial(p, 0), .ctl);
+ const unknown = th.wr(p, ctl_node, "Bogus\n");
+ try testing.expectEqual(E.INVAL, unknown.errno());
+ try testing.expect(std.mem.startsWith(u8, unknown.reply.ename, "unknown control message \"Bogus\""));
+ const extra = th.wr(p, ctl_node, "New extra\n");
+ try testing.expectEqual(E.INVAL, extra.errno());
+ try testing.expect(std.mem.startsWith(u8, extra.reply.ename, "wrong #args"));
+ try testing.expectEqual(@as(usize, 1), p.view().cols[0].n);
+ // A pane's bare answer and a winsize of no size say what they take.
+ try testing.expectEqualStrings("answer takes a choice or -", th.wr(p, Node.of(p.panes[0].?.serial, .ctl), "answer\n").reply.ename);
+}
diff --git a/core/ninep/ctl.zig b/core/ninep/ctl.zig
new file mode 100644
index 00000000..0077f095
--- /dev/null
+++ b/core/ninep/ctl.zig
@@ -0,0 +1,2909 @@
+//! The command files and the status they answer. Writing a line to `look` is
+//! a right click on it and writing one to `exec` a middle click, at the
+//! active pane from the root and at that pane from /pane/<n>/; reading either
+//! answers the serials the last command made or touched. /status reports the
+//! editor. The root ctl reads the settings and takes the session's builtins;
+//! a pane's ctl reads its acme status line and takes acme's verbs `get`,
+//! `lock` and `unlock` and the builtins that act on a pane.
+const std = @import("std");
+const pardes = @import("../root.zig");
+const look = @import("../look.zig");
+const panes = @import("../panes.zig");
+const config = @import("../config.zig");
+const fs = @import("../fs.zig");
+const tagline = @import("../tagline.zig");
+const layout = @import("../layout.zig");
+const builtins = @import("../builtins.zig");
+const exec_line = @import("../exec.zig");
+const tree = @import("tree.zig");
+const pane_files = @import("pane.zig");
+const keys = @import("../keys.zig");
+const Ask = @import("../lsp/Ask.zig");
+
+const Pardes = pardes.Pardes;
+const Pane = pardes.Pane;
+const MAX_PANES = pardes.MAX_PANES;
+const Req = tree.Req;
+const Reply = tree.Reply;
+const E = tree.E;
+
+// ---- which panes a command made or touched ----
+
+const Serials = struct {
+ list: [MAX_PANES]u32 = undefined,
+ len: usize = 0,
+
+ fn snapshot(p: *Pardes) Serials {
+ var s: Serials = .{};
+ for (p.panes) |slot| if (slot) |pane| {
+ s.list[s.len] = pane.serial;
+ s.len += 1;
+ };
+ return s;
+ }
+};
+
+fn noteResult(p: *Pardes, serial: u32) void {
+ for (p.fs.results[0..p.fs.results_len]) |known| if (known == serial) return;
+ if (p.fs.results_len == p.fs.results.len) return;
+ p.fs.results[p.fs.results_len] = serial;
+ p.fs.results_len += 1;
+}
+
+/// Runs one look or exec from the pane `id`, then records the panes it
+/// created; failing that, a look records the pane it focused and an exec
+/// the pane it acted on (even one it closed).
+pub fn run(p: *Pardes, id: usize, exec: bool, text: []const u8, in_tag: bool) void {
+ const v = p.view();
+ const context = if (p.panes[id]) |pane| pane.serial else 0;
+ // A pane an event reader holds hears its clicks instead of acting on
+ // them (editors/acme/look.c:53 and exec.c:173 send them to winevent),
+ // and a line written to a look or exec is a click: on that pane, or for
+ // the root's, on the pane with the keyboard. The reader writes the
+ // record back to have it done.
+ // A click in a column's or the workspace's tag is not the pane's; one
+ // in the pane's own tag (its tagexec) is, an `x` or `l` record as
+ // acme's tag clicks are.
+ if (!p.exec_header and p.panes[id].?.fs.readers > 0) {
+ const named = exec_line.namesBuiltin(text);
+ // No flag 2: a written line was never expanded from a click, and no
+ // expansion record follows (editors/acme/look.c:42-43, exec.c:154-157).
+ var flag: u32 = 0;
+ if (named) flag |= pardes.ctlfs.events.flag_builtin;
+ if (!exec and !named and std.mem.indexOfAny(u8, text, "/.:") != null) flag |= pardes.ctlfs.events.flag_filename;
+ const action: pardes.ctlfs.events.Action = if (in_tag)
+ (if (exec) .tag_exec else .tag_look)
+ else
+ (if (exec) .body_exec else .body_look);
+ pardes.ctlfs.events.noteAction(p, id, action, 0, 0, flag, text);
+ return noteResult(p, context);
+ }
+ const before = Serials.snapshot(p);
+ // An exec answers the pane it went to: a command pane it reused, or
+ // the terminal it typed into.
+ p.look_missed = false;
+ p.fs.refilled = null;
+ const went: ?usize = if (exec) pardes.exec.execute(p, id, text) else blk: {
+ look.lookAt(p, id, text);
+ break :blk null;
+ };
+ // A look that found nothing answers nothing, not the pane before it.
+ if (!exec and p.look_missed) return;
+ const after = Serials.snapshot(p);
+ var created = false;
+ for (after.list[0..after.len]) |serial| if (std.mem.indexOfScalar(u32, before.list[0..before.len], serial) == null) {
+ // A query pane's +Preview is its query pane's: that answers.
+ if (p.paneBySerial(serial)) |made| if (p.panes[made].?.file) |f| if (f.output) |o| if (o.from == .preview) continue;
+ // A look that made a +Search pane (a terminal's word)
+ // answers it: that is where the places it found are.
+ noteResult(p, serial);
+ created = true;
+ };
+ if (created) return;
+ // A +Search it filled again (Find and Grep reuse one): that is what it
+ // touched.
+ if (p.fs.refilled) |serial| if (p.paneBySerial(serial) != null) return noteResult(p, serial);
+ if (went) |dst| if (p.panes[dst]) |pane| return noteResult(p, pane.serial);
+ // A word in a column's or the workspace's tag ran at no pane: it
+ // answers one only if it focused one (Newcol answers nothing).
+ if (p.exec_header) {
+ if (v.active != id) if (p.panes[v.active]) |pane| noteResult(p, pane.serial);
+ return;
+ }
+ noteResult(p, if (exec) context else (p.panes[v.active] orelse return).serial);
+}
+
+/// A write's messages, a line each, except that an `Edit` line takes the
+/// lines after it while its `{` group or `a`/`c`/`i` text block is open
+/// (sam_edit.waitsFor): a block written whole reaches Edit whole, never
+/// as lines of their own.
+const Messages = struct {
+ p: *Pardes,
+ data: []const u8,
+ at: usize = 0,
+ /// A look's line is its text, leading blanks and all (` return x`,
+ /// a diff's context line ` ` alone): only its `\r` goes.
+ keep_blanks: bool = false,
+
+ fn next(m: *Messages) ?[]const u8 {
+ if (m.at >= m.data.len) return null;
+ const start = m.at;
+ var end = std.mem.indexOfScalarPos(u8, m.data, start, '\n') orelse m.data.len;
+ m.at = end + 1;
+ if (m.keep_blanks) return std.mem.trimEnd(u8, m.data[start..end], "\r");
+ const first = std.mem.trim(u8, m.data[start..end], " \t\r");
+ const edit = "Edit";
+ if (!std.mem.startsWith(u8, first, edit) or (first.len > edit.len and first[edit.len] != ' ' and first[edit.len] != '\t'))
+ return first;
+ end = editEnd(m.p, m.data, start, end, true).?;
+ m.at = end + 1;
+ return std.mem.trim(u8, m.data[start..end], " \t\r");
+ }
+};
+
+/// Where the Edit block whose first line is `data[start..first_end]` ends:
+/// the end of its last line, taking the lines after it while its `{`
+/// group or a/c/i text block is open. Out of lines, the end of `data` when
+/// `to_end` (a write run whole), else null (wait for more). Only a line
+/// that could end what is open is parsed again with all before it: within
+/// a text block, just a `.` line. The arena copy of each parse is freed.
+fn editEnd(p: *Pardes, data: []const u8, start: usize, first_end: usize, to_end: bool) ?usize {
+ const sam = @import("../sam_edit.zig");
+ const edit = "Edit";
+ const arena = p.scratch.allocator();
+ var end = first_end;
+ var wait = sam.waitsFor(arena, std.mem.trim(u8, data[start..end], " \t\r")[edit.len..]);
+ while (wait != .none) {
+ if (end >= data.len) return if (to_end) data.len else null;
+ const next = std.mem.indexOfScalarPos(u8, data, end + 1, '\n') orelse
+ (if (to_end) data.len else return null);
+ const line = std.mem.trim(u8, data[end + 1 .. next], " \t\r");
+ end = next;
+ if (wait == .text and !std.mem.eql(u8, line, ".")) continue;
+ wait = sam.waitsFor(arena, std.mem.trim(u8, data[start..end], " \t\r")[edit.len..]);
+ }
+ return end;
+}
+
+/// How much of `data` is whole messages, as `Messages` reads them: lines
+/// ended by a newline, an Edit block only once it closes. The rest waits
+/// for more (tree.Open.pending).
+pub fn completeEnd(p: *Pardes, data: []const u8) usize {
+ const edit = "Edit";
+ var whole: usize = 0;
+ var at: usize = 0;
+ while (std.mem.indexOfScalarPos(u8, data, at, '\n')) |nl| {
+ const start = at;
+ var end = nl;
+ const first = std.mem.trim(u8, data[start..end], " \t\r");
+ if (std.mem.startsWith(u8, first, edit) and (first.len == edit.len or first[edit.len] == ' ' or first[edit.len] == '\t'))
+ end = editEnd(p, data, start, end, false) orelse return whole;
+ at = end + 1;
+ whole = at;
+ }
+ return whole;
+}
+
+// ---- look and exec ----
+
+/// One command per line, checked whole before any line runs: a line is the
+/// clicked text itself, so it may not be empty or carry control characters.
+/// A null `serial` clicks at whichever pane is active as each line runs,
+/// which is what the root's own look and exec mean; a serial stays put.
+pub fn command(p: *Pardes, req: Req, serial: ?u32, exec: bool, in_tag: bool) Reply {
+ const v = p.view();
+ // The root's lines run at the keyboard's pane: a refusal before any runs
+ // is that pane's too, in its err record.
+ p.fs.ran_at = if (serial == null) (if (p.panes[v.active]) |pane| pane.serial else 0) else 0;
+ if (editNotAlone(p, req.data)) return tree.failText(req.tag, E.INVAL, e_after_edit);
+ for ([2]bool{ false, true }) |apply| {
+ if (apply) p.fs.results_len = 0;
+ var it: Messages = .{ .p = p, .data = req.data };
+ it.keep_blanks = !exec;
+ while (it.next()) |text| {
+ if (text.len == 0) continue;
+ // Only an Edit block holds newlines (Messages).
+ for (text) |c| if ((c < ' ' and c != '\t' and c != '\n') or c == 0x7f) return tree.failText(req.tag, E.INVAL, e_control);
+ if (exec) if (tooLong(req, text)) |refusal| return refusal;
+ if (!apply) continue;
+ var id = if (serial) |s| p.paneBySerial(s) orelse break else v.active;
+ // No pane at all: the root's look and exec act in the session's
+ // directory. An exec runs as the workspace tag's; a look from a
+ // scratch made as New makes one (and its column), dropped
+ // unannounced when the look went elsewhere.
+ var scratch: ?usize = null;
+ if (p.panes[id] == null and serial == null and panes.anyPane(p) == null) {
+ if (exec) {
+ p.exec_header = true;
+ defer p.exec_header = false;
+ if (captured(p, req, id, exec, text, true)) |refusal| return refusal;
+ continue;
+ }
+ const free = p.freeSlot() orelse return Reply.fail(req.tag, E.NOSPC);
+ panes.newScratchFor(p, id, .scratch);
+ if (p.panes[free] == null) return Reply.fail(req.tag, E.NOSPC);
+ v.active = free;
+ id = free;
+ scratch = free;
+ }
+ if (p.panes[id] == null) return Reply.fail(req.tag, E.NOENT);
+ defer if (scratch) |s| if (v.active != s) if (p.panes[s]) |sp| if (sp.file) |f| {
+ if (f.content.len == 0) p.removePane(s, null) catch |err| p.reportError(s, "exec", err);
+ };
+ p.fs.ran_at = p.panes[id].?.serial;
+ p.fs.no_pane_slot = false;
+ if (captured(p, req, id, exec, text, in_tag)) |refusal| return refusal;
+ // A pane it would have opened had no slot: the write fails, and
+ // a look reads back nothing.
+ if (p.fs.no_pane_slot) {
+ p.fs.results_len = 0;
+ return tree.failText(req.tag, E.IO, p.fs.ename[0..p.fs.no_pane_slot_len]);
+ }
+ }
+ }
+ return .{ .tag = req.tag, .written = @intCast(req.data.len) };
+}
+
+// "invalid" is the word 9ns reads as EINVAL (enameToErrno): through a
+// mount the refusal is EINVAL, as the reply's errno is.
+pub const e_too_long = std.fmt.comptimePrint("invalid command line: a command line is at most {d} bytes", .{pardes.exec.command_max});
+
+/// A line an exec would run as a command, over the most a command line may
+/// be: refused whole, before anything runs, rather than said on the message
+/// row after the write succeeded. A builtin's line (Msg, an Edit block) may
+/// be longer.
+pub fn tooLong(req: Req, line: []const u8) ?Reply {
+ if (line.len <= pardes.exec.command_max) return null;
+ const cmd = exec_line.commandText(line);
+ const word = cmd[0 .. std.mem.indexOfAny(u8, cmd, " \t+") orelse cmd.len];
+ if (std.meta.stringToEnum(Builtin, word) != null) return null;
+ return tree.failText(req.tag, E.INVAL, e_too_long);
+}
+
+pub const e_control = "invalid command line: it holds a control character (or DEL) other than a tab";
+
+/// An Edit whose `<`, `|` or `>` commands run answers its write when they
+/// are done (edit_cmd.zig); a line after it in the same write would run
+/// before them, on the text they are about to change. Refused up front,
+/// before any line runs.
+pub const e_after_edit = "invalid command line: an Edit that runs commands is a write of its own";
+
+/// Whether `data` holds an Edit that runs commands and any other line.
+fn editNotAlone(p: *Pardes, data: []const u8) bool {
+ const sam = @import("../sam_edit.zig");
+ var lines: usize = 0;
+ var runs = false;
+ var it: Messages = .{ .p = p, .data = data };
+ while (it.next()) |line| {
+ if (line.len == 0 or exec_line.isComment(line)) continue;
+ lines += 1;
+ if (std.mem.startsWith(u8, line, "Edit") and sam.runsCommands(p.scratch.allocator(), line["Edit".len..])) runs = true;
+ }
+ return runs and lines > 1;
+}
+
+/// Runs one click (`run`) as a 9P write's: a builtin that fails there fails
+/// the write, with its words and an err record, and no msg, as a ctl line
+/// does (runBuiltin). The refusal, or null.
+pub fn captured(p: *Pardes, req: Req, id: usize, exec: bool, text: []const u8, in_tag: bool) ?Reply {
+ // A builtin that means nothing without its argument, written bare: the
+ // write is refused, EINVAL, as a ctl's is (checkBuiltin), not run to
+ // fail or to ask.
+ if (exec) {
+ const cmd = exec_line.commandText(text);
+ if (std.meta.stringToEnum(Builtin, cmd)) |b| if (builtins.registry.requiresArg(b)) {
+ p.fs.results_len = 0;
+ return refuse(p, req, "wrong #args in control message", cmd);
+ };
+ // ...and one that takes none, written with one (`Config extra`):
+ // refused as a ctl's is, not run as a shell command of that name.
+ if (std.mem.indexOfAny(u8, cmd, " \t")) |sp| if (std.meta.stringToEnum(Builtin, cmd[0..sp])) |b| {
+ if (!builtins.registry.takesArg(b) and config.Runtime.find(cmd[0..sp]) == null) {
+ p.fs.results_len = 0;
+ return refuse(p, req, "wrong #args in control message", cmd);
+ }
+ };
+ }
+ p.fs.capturing = true;
+ p.fs.failure_len = 0;
+ defer p.fs.capturing = false;
+ run(p, id, exec, text, in_tag);
+ const refusal = failedWrite(p, req.tag) orelse return null;
+ // A failed click answers nothing: look reads back empty.
+ p.fs.results_len = 0;
+ return refusal;
+}
+
+/// The failure a run said while it was captured, as the refusal of the
+/// write that ran it: its words, and the errno 9ns reads in them (a slot or
+/// a place refused keeps its, no space: ENOSPC); null when it said none.
+pub fn failedWrite(p: *Pardes, tag: u64) ?Reply {
+ if (p.fs.failure_len == 0) return null;
+ const failure = p.fs.failure[0..p.fs.failure_len];
+ return tree.failText(tag, failureErrno(failure), std.fmt.bufPrint(&p.fs.ename, "{s}", .{failure}) catch unreachable); // failure is a slice of fs.failure, a [256]u8, into ename's 320
+}
+
+/// The errno a builtin's failure answers with: ENOENT for what is not
+/// there (`no such`, `not found`, the words 9ns reads as ENOENT too), else
+/// EIO.
+pub fn failureErrno(failure: []const u8) u16 {
+ // Refused while something else runs (an Edit's commands): EBUSY, the
+ // word 9ns reads as it.
+ if (std.mem.indexOf(u8, failure, "busy: ") != null) return E.BUSY;
+ if (std.mem.indexOf(u8, failure, "no such") != null or std.mem.indexOf(u8, failure, "not found") != null) return E.NOENT;
+ // As 9ns reads the same words (cloud9.fs.enameErrno).
+ if (std.mem.indexOf(u8, failure, "not a dir") != null) return E.NOTDIR;
+ if (std.mem.indexOf(u8, failure, "is a dir") != null) return E.ISDIR;
+ if (std.mem.indexOf(u8, failure, "permission denied") != null) return 13; // EACCES
+ // A pattern refused (Edit's too) is malformed input, as 9ns reads it;
+ // so is a word this build has not (`invalid: acme's Put ...`).
+ if (std.mem.indexOf(u8, failure, "bad regular expression") != null or std.mem.indexOf(u8, failure, "invalid") != null or
+ std.mem.startsWith(u8, failure, "address out of range")) return E.INVAL;
+ // A word's arguments wrong, or a dial that is no address: what 9ns
+ // reads as EINVAL from the same words (`control message`, `bad `).
+ if (std.mem.indexOf(u8, failure, "control message") != null or std.mem.indexOf(u8, failure, "bad dial address") != null) return E.INVAL;
+ return E.IO;
+}
+
+pub fn resultsLen(p: *Pardes) u64 {
+ var n: u64 = 0;
+ for (p.fs.results[0..p.fs.results_len]) |serial| {
+ var digits: [16]u8 = undefined;
+ // unreachable: a u32 serial and a newline fit 16
+ n += (std.fmt.bufPrint(&digits, "{d}\n", .{serial}) catch unreachable).len;
+ }
+ return n;
+}
+
+/// The panes the open's last write touched (tree.Open.results); with no
+/// open, the session's last.
+pub fn readResults(p: *Pardes, req: Req) Reply {
+ const out = p.fs.stage(p.gpa);
+ const o = tree.openOf(p, req);
+ const kept = if (o) |open| open.results.list[0..open.results.len] else p.fs.results[0..p.fs.results_len];
+ // A look answers panes to go to: never one closed since (an exec may
+ // answer the pane it closed, which is what it acted on).
+ const looking = if (tree.Node.target(req.node)) |t| switch (t) {
+ .top => |f| f == .look,
+ .pane => |pt| pt.file == .look,
+ .col, .port => false,
+ } else false;
+ for (kept) |serial| if (!looking or p.paneBySerial(serial) != null)
+ out.print(p.gpa, "{d}\n", .{serial}) catch return Reply.fail(req.tag, E.NOMEM);
+ const open = o orelse return tree.stagedReply(p, req);
+ if (!open.results.wrote) return tree.stagedReply(p, req);
+ var at = req;
+ at.off = open.results.read;
+ const reply = tree.stagedReply(p, at);
+ open.results.read += reply.payload.staged;
+ return reply;
+}
+
+// ---- /status ----
+
+/// /status's text, in the step's scratch.
+pub fn statusText(p: *Pardes) std.Io.Writer.Error![]const u8 {
+ var w: std.Io.Writer.Allocating = .init(p.scratch.allocator());
+ var count: usize = 0;
+ for (p.panes) |slot| count += @intFromBool(slot != null);
+ const pid: u32 = @intCast(std.c.getpid());
+ try w.writer.print("pid {d}\nversion {s}\npanes {d}\n", .{ pid, pardes.version, count });
+ // Whether the pointer is over this window: what a grip let go past
+ // another window's edge asks of every window, to find the one it was
+ // let go over (Handover.zig), where no window may know another's place.
+ if (p.view().frontend.windowed) try w.writer.print("pointer {s}\n", .{if (p.view().pointer_inside) "in" else "out"});
+ return w.written();
+}
+
+// ---- /pane/<n>/ctl ----
+
+fn writeQuoted(w: *std.Io.Writer, s: []const u8) !void {
+ const plain = s.len > 0 and for (s) |c| {
+ if (c <= ' ' or c == '\'') break false;
+ } else true;
+ if (plain) return w.writeAll(s);
+ try w.writeByte('\'');
+ for (s) |c| {
+ if (c == '\'') try w.writeByte('\'');
+ try w.writeByte(c);
+ }
+ try w.writeByte('\'');
+}
+
+pub const pane_text_cap = 9 * 12 + 2 * 256 + 4 + "notcurrent ".len + 48 + "collapsed fit:height tint:filtered mode:insert ".len + 129;
+
+/// acme's winctlprint (plan9port wind.c), field for field: serial, tag
+/// length, body length, isdir (1 for a directory pane), the dirty flag,
+/// the width in cells, the font, the tab width, whether Undo has a step,
+/// whether Redo has one. Then pardes's own: rio's word for whether the
+/// window has the keyboard, `current` or `notcurrent` (rio(4), wctl), and
+/// a REPL's id.
+pub fn paneText(p: *Pardes, pane: *Pane, buf: *[pane_text_cap]u8) []const u8 {
+ var w = std.Io.Writer.fixed(buf);
+ // A buffer that fills cuts the line there.
+ fill: {
+ w.print("{d:>11} {d:>11} {d:>11} {d:>11} {d:>11} {d:>11} ", .{
+ pane.serial,
+ if (pane_files.tagOf(p, pane)) |tag| tag.len else |_| 0, // a length, as a stat's: none when the tag cannot be made
+ // A terminal's body is its history, read whole on an open's first read.
+ if (pane.isTerminal()) pardes.Term.scrollbackLen(pane.terminal) else pane_files.bodyOf(pane).len,
+ // A directory pane is one, as acme's isdir says.
+ @intFromBool(if (pane.file) |f| f.listing != null else false),
+ @intFromBool(pane_files.dirtyOf(pane)),
+ pane.cols,
+ }) catch break :fill;
+ const font = p.settings.font.effective_name.get();
+ writeQuoted(&w, if (font.len == 0) "default" else font) catch break :fill;
+ // While a column's or the workspace's tag has the keyboard, no pane does.
+ const current = p.panes[p.view().active] == pane and p.view().header == null;
+ const f = pane_files.fileOf(pane);
+ const undo = if (f) |file| file.history.journal.done > 0 else false;
+ const redo = if (f) |file| file.history.journal.done < file.history.journal.steps.items.len else false;
+ w.print(" {d:>11} {d:>11} {d:>11} {s} ", .{ config.tab_now, @intFromBool(undo), @intFromBool(redo), if (current) "current" else "notcurrent" }) catch break :fill;
+ // A terminal bound as a REPL ends with its id, `python-a`.
+ var idbuf: [48]u8 = undefined;
+ const id = exec_line.replId(&idbuf, pane);
+ if (id.len > 0) w.print("{s} ", .{id}) catch break :fill;
+ // Then what its tag does not say: Collapse, and a kind's own fields (a
+ // PDF's PdfFit and PdfTint, in the words they take).
+ if (pane.collapsed) w.writeAll("collapsed ") catch break :fill;
+ if (pane.addon != null) {
+ var fields: [128]u8 = undefined;
+ const kind_fields = pardes.Kind.ctlRead(pane, &fields);
+ if (kind_fields.len > 0) w.print("{s} ", .{kind_fields}) catch break :fill;
+ }
+ // Last, the body's mode, which the tag shows as a box: helix's select
+ // is normal mode extending.
+ w.print("mode:{s} ", .{if (pane.body.mode == .normal and pane.body.select) "select" else @tagName(pane.body.mode)}) catch break :fill;
+ }
+ return w.buffered();
+}
+
+// ---- control messages: the builtins, by scope ----
+
+const Builtin = builtins.registry.Builtin();
+
+/// Refuses a control message, quoting it the way Plan 9's cmderror does
+/// (kernel/misc/parse.c:82): `unknown control message "Bogus 3"`.
+fn refuse(p: *Pardes, req: Req, why: []const u8, line: []const u8) Reply {
+ return refuseQuoting(p, req, why, firstWord(line), "");
+}
+
+/// `refuse` quoting `word` as given (a setting's bad value, blanks and
+/// all), then `tail`: which ctl takes the message instead, or what this one
+/// takes.
+pub fn refuseQuoting(p: *Pardes, req: Req, why: []const u8, word: []const u8, tail: []const u8) Reply {
+ // A word too long to quote whole gives up its middle (fitErr), so the
+ // refusal keeps both its ends.
+ var shown: [4096]u8 = undefined;
+ var whole: [4096 + 320]u8 = undefined;
+ const full = std.fmt.bufPrint(&whole, "{s} \"{s}\"{s}", .{ why, blanked(word[0..@min(word.len, shown.len)], &shown), tail }) catch why;
+ // Into the session's own buffer: `whole` is this frame's.
+ if (full.len <= p.fs.ename.len) {
+ @memcpy(p.fs.ename[0..full.len], full);
+ return tree.failText(req.tag, E.INVAL, p.fs.ename[0..full.len]);
+ }
+ return tree.failText(req.tag, E.INVAL, tree.fitErr(full, &p.fs.ename));
+}
+
+/// The word a refusal quotes: a control message's first, its offending
+/// word, never the line with its arguments (one rule everywhere: `wrong
+/// #args in control message "Newcol"`).
+pub fn firstWord(line: []const u8) []const u8 {
+ const trimmed = std.mem.trim(u8, line, " \t\r\n");
+ return trimmed[0 .. std.mem.indexOfAny(u8, trimmed, " \t") orelse trimmed.len];
+}
+
+/// A quoted line as a refusal shows it: a control byte (a tab, the one a
+/// line may hold) is a blank, so the reason reads as one line of words.
+fn blanked(line: []const u8, buf: []u8) []const u8 {
+ const n = @min(line.len, buf.len);
+ for (line[0..n], buf[0..n]) |c, *o| o.* = if (c < ' ' or c == 0x7f) ' ' else c;
+ return buf[0..n];
+}
+
+/// Checks one line written to a ctl as a builtin of `scope` before any line
+/// of the write runs: a word the registry knows, of this ctl's scope, given
+/// an argument if and only if it takes or requires one, and for a setting a
+/// value it takes.
+/// Answers the refusal, or null. Words are the builtins' own, capitalised
+/// as on a tag; acme's lowercase verbs are the pane ctl's and alias none.
+fn checkBuiltin(p: *Pardes, req: Req, line: []const u8, scope: builtins.Scope) ?Reply {
+ var sp = std.mem.indexOfAny(u8, line, " \t");
+ // `Word+arg` for a word that takes one so (`Term+bash`), as exec does;
+ // an old name's too (`Tty+bash`).
+ if (sp == null) if (std.mem.indexOfScalar(u8, line, '+')) |at| {
+ const head = for (pardes.exec.acme_words) |w| {
+ if (std.mem.eql(u8, line[0..at], w.acme)) break w.pardes orelse "";
+ } else line[0..at];
+ if (std.meta.stringToEnum(Builtin, head)) |b| if (builtins.registry.plusArg(b)) {
+ sp = at;
+ };
+ };
+ const typed = line[0 .. sp orelse line.len];
+ // acme's words: checked as the pardes word they run as, or refused.
+ const word = for (pardes.exec.acme_words) |w| {
+ if (!std.mem.eql(u8, typed, w.acme)) continue;
+ const now = w.pardes orelse return tree.failText(req.tag, E.INVAL, std.fmt.bufPrint(&p.fs.ename, "invalid: acme's {s} is not a pardes builtin{s}", .{ w.acme, w.hint }) catch &p.fs.ename); // cut to ename's 320
+ break now;
+ } else typed;
+ const arg = if (sp) |s| std.mem.trim(u8, line[s + 1 ..], " \t") else "";
+ const here = if (std.meta.stringToEnum(Builtin, word)) |b| builtins.registry.here(p, b) else false;
+ const b = (if (here) std.meta.stringToEnum(Builtin, word) else null) orelse {
+ // An addon's word: its kind's to take or refuse as it runs.
+ if (p.kinds.word(word) != null) return null;
+ // A setting this build's frontend cannot show (Lift, GripWidth on a
+ // terminal, the window's own words in a terminal's view) is known,
+ // and says so rather than sound misspelt.
+ if (builtins.absentWhy(word) orelse if (config.Runtime.find(word) != null or std.meta.stringToEnum(Builtin, word) != null) @as([]const u8, "GUI-only") else null) |absent| {
+ var why: pardes.Kind.Buf(64) = .{};
+ // EINVAL, a request this build cannot take, in words 9ns reads
+ // as that: `invalid`.
+ return refuse(p, req, why.print("{s} is {s}, invalid here", .{ word, absent }), line);
+ }
+ return refuse(p, req, "unknown control message", line);
+ };
+ // Edit is the one pane word the root takes too: at the active pane.
+ if (builtins.registry.scope(b) != scope and b != .Edit)
+ return refuseQuoting(p, req, if (scope == .pane) "not a window control message" else "not a session control message", firstWord(line), if (scope == .pane)
+ ": write it to /ctl"
+ else if (b == .Delcol or b == .Joincol)
+ ": write it to col/<serial>/ctl" // a column's own ctl, the one /layout names
+ else
+ ": write it to pane/<n>/ctl");
+ if (arg.len > 0 and !builtins.registry.takesArg(b)) return refuse(p, req, "wrong #args in control message", line);
+ if (arg.len == 0 and builtins.registry.requiresArg(b)) return refuse(p, req, "wrong #args in control message", line);
+ const setting = config.Runtime.find(word) orelse return null;
+ const takes = switch (setting.action) {
+ .theme => if (pardes.colors.themeIndex(arg) != null) true else {
+ // `refuse` quotes the line after it, all in the 128 bytes an
+ // Rerror carries: the names get what is left.
+ const head = "bad value in control message; like it: ";
+ const tail = "; Themes lists all";
+ var near: [128]u8 = undefined;
+ const room = @import("cloud9").fs.errmax -| (head.len + tail.len + line.len + 3);
+ var why: pardes.Kind.Buf(256) = .{};
+ return refuse(p, req, why.print(head ++ "{s}" ++ tail, .{pardes.colors.themesNear(near[0..@min(room, near.len)], arg)}), arg);
+ },
+ .font => config.Runtime.FontSpec.parse(arg) != null,
+ // Bare, it says the width, as from a pane's exec.
+ .tab => arg.len == 0 or (std.fmt.parseInt(u16, arg, 10) catch 0) -% 1 < 16,
+ .callstack_depth => arg.len == 0 or (std.fmt.parseInt(u8, arg, 10) catch 0) -% 1 < pardes.lsp.callstack_max_depth,
+ else => probe: {
+ var probe = p.settings;
+ break :probe probe.apply(setting, if (arg.len > 0) arg else null);
+ },
+ };
+ if (takes) return null;
+ var why: pardes.Kind.Buf(160) = .{};
+ // The offending word is the value: quoted, so two bad values read,
+ // and log, as two.
+ return refuseQuoting(p, req, if (config.Runtime.takes(setting.action)) |values|
+ why.print("bad value in control message; takes {s}", .{values})
+ else
+ "bad value in control message", arg, "");
+}
+
+/// Runs a checked control message at pane `id`, as a click on its word
+/// would. Answers the refusal when it would have opened a prompt for an
+/// argument, which nobody writing to a file is there to type, or when it
+/// reported an error: `Mount: AlreadyMounted "Mount peer /tmp/s"`.
+pub fn runBuiltin(p: *Pardes, req: Req, id: usize, line: []const u8) ?Reply {
+ p.fs.no_prompt = true;
+ p.fs.refused = false;
+ p.fs.failure_len = 0;
+ defer p.fs.no_prompt = false;
+ // What a ctl write touched reads back from /look and /exec as a click's
+ // does (`run`), so a script that made a pane with `Term` finds it there.
+ const context = if (p.panes[id]) |pane| pane.serial else 0;
+ const before = Serials.snapshot(p);
+ _ = exec_line.executeBuiltinLine(p, id, line);
+ const after = Serials.snapshot(p);
+ var created = false;
+ for (after.list[0..after.len]) |serial| if (std.mem.indexOfScalar(u32, before.list[0..before.len], serial) == null) {
+ noteResult(p, serial);
+ created = true;
+ };
+ if (!created) noteResult(p, context);
+ if (p.fs.refused) return refuse(p, req, e_prompt, line);
+ // A line that ran and failed says why in the builtin's own words, which
+ // name what failed (`Mount peer /tmp/s: dial failed: ...`): the line is
+ // not quoted after them, as an exec's is not. Only a line refused before
+ // it runs, as no message at all, quotes it (`unknown control message
+ // "X"`).
+ return failedWrite(p, req.tag);
+}
+
+const e_prompt = "control message needs its argument";
+
+// ---- the root ctl ----
+
+/// Every setting, one a line, in the words a write of it takes, so that the
+/// file read back is the configuration, as webfs's ctl reads (webfs(4)).
+/// What is not a setting -- platform, themes, where the config came from --
+/// is /status's or the DumpConfig window's.
+fn writeSettings(p: *Pardes, w: *std.Io.Writer) !void {
+ try writeSettingsFor(p, &p.settings, w, builtins.viewCapabilities(p));
+}
+
+/// The setting words of `s`, one a line, those a frontend of `caps` takes
+/// (the root ctl's: the live view's), and the session's LocationsConfig.
+fn writeSettingsFor(p: *Pardes, s: *const config.Runtime, w: *std.Io.Writer, caps: config.Runtime.Capabilities) !void {
+ // DumpConfig's words: a `# Word unsupported` comment for what `caps` lacks.
+ var dump_dir: [1024]u8 = undefined;
+ var located_buf: [256]u8 = undefined;
+ var located: std.Io.Writer = .fixed(&located_buf);
+ try p.locations_config.write(&located);
+ try config.Runtime.writeSettings(w, .{
+ .locations = located.buffered(),
+ .theme_name = p.theme().name,
+ .theme_file = pardes.colors.loadedThemeFile(p),
+ .compiled_default_shell = config.defaultShell(),
+ .default_dump_dir = pardes.dump.defaultDirectory(&dump_dir) orelse "",
+ .capabilities = caps,
+ .state = s,
+ });
+}
+
+/// The root ctl's text (`writeSettings`), in the step's scratch.
+pub fn settingsText(p: *Pardes) std.Io.Writer.Error![]const u8 {
+ var text: std.Io.Writer.Allocating = .init(p.scratch.allocator());
+ try writeSettings(p, &text.writer);
+ return text.written();
+}
+
+/// /pager, `pardes -`'s: the directory written (empty, or not absolute: the
+/// session's) gets a new +Pager; the serial is what a
+/// read of this same open answers, never another client's. What the open
+/// writes after that line is the text, held by tree.zig for `fillPager`.
+pub fn writePager(p: *Pardes, req: Req) Reply {
+ // A refused write leaves its open no answer, not the last one's.
+ p.fs.results_len = 0;
+ var it: Messages = .{ .p = p, .data = req.data };
+ const line = it.next() orelse "";
+ // Words 9ns maps back to EINVAL (`invalid`), as every refusal here. One
+ // directory an open, as pty/run takes one line: through a mount
+ // `printf 'a\nb\n'` comes a line a write, and the second is refused.
+ const asked_before = if (tree.openOf(p, req)) |o| o.results.wrote else false;
+ if (it.next() != null or asked_before) return tree.failText(req.tag, E.INVAL, "pager: invalid write: one directory an open");
+ // `~` is home, and `/tmp/../etc` is `/etc`: the +Pager is named in the
+ // directory it is, as any other pane's name is.
+ var home_buf: [4096]u8 = undefined;
+ const typed = pardes.filesystem.expandHome(std.mem.trim(u8, line, " \t"), &home_buf);
+ const dir = if (typed.len > 0 and typed[0] == '/') std.Io.Dir.path.resolvePosix(p.scratch.allocator(), &.{typed}) catch typed else typed;
+ // A directory that is there, or none (the session's): never a +Pager
+ // named into one missing, nor a relative one quietly taken for none.
+ if (dir.len > 0 and dir[0] != '/') {
+ var shown: [256]u8 = undefined;
+ return tree.failText(req.tag, E.INVAL, std.fmt.bufPrint(&p.fs.ename, "pager: invalid directory \"{s}\": must be absolute", .{blanked(dir[0..@min(dir.len, shown.len)], &shown)}) catch &p.fs.ename); // cut to ename's 320
+ }
+ if (dir.len > 0) if (pardes.filesystem.localPath(dir)) |local| {
+ // A file there is no directory, ENOTDIR; nothing there, ENOENT.
+ if (exec_line.kindOf(local) != .directory) {
+ if (exec_line.kindOf(local) != null)
+ return tree.failText(req.tag, E.NOTDIR, std.fmt.bufPrint(&p.fs.ename, "pager: {s}: not a directory", .{dir[0..@min(dir.len, 256)]}) catch &p.fs.ename); // cut to ename's 320
+ return tree.failText(req.tag, E.NOENT, std.fmt.bufPrint(&p.fs.ename, "pager: {s}: no such directory", .{dir[0..@min(dir.len, 256)]}) catch &p.fs.ename); // cut to ename's 320
+ }
+ // Nor one that may not be written, as a file's name there is refused.
+ if (pardes.filesystem.deniedAbove(local))
+ return tree.failText(req.tag, E.PERM, std.fmt.bufPrint(&p.fs.ename, "pager: {s}: permission denied", .{dir[0..@min(dir.len, 256)]}) catch &p.fs.ename); // cut to ename's 320
+ };
+ const id = pardes.panes.Output.openPager(p, p.view().active, dir) catch |err|
+ return tree.failText(req.tag, if (err == error.NoPaneRoom or err == error.NoPaneSlots) E.NOSPC else E.IO, switch (err) {
+ error.NoPaneRoom, error.NoPaneSlots => "pager: no space for a +Pager pane",
+ else => "pager: could not make a +Pager pane",
+ });
+ noteResult(p, p.panes[id].?.serial);
+ return .{ .tag = req.tag, .written = @intCast(req.data.len) };
+}
+
+/// The text a /pager open wrote after its directory (`held`), a program's
+/// output for a terminal, put in the +Pager `serial` as `pardes -` once
+/// wrote it to the body: through the terminal's parse (Term.page), its colours kept
+/// as the pane's spans, one undo step, and left
+/// clean. Reads of the pane are its plain text. The held bytes go either way.
+pub fn fillPager(p: *Pardes, serial: u32, held: *std.ArrayList(u8)) error{OutOfMemory}!void {
+ if (held.items.len == 0) return;
+ defer held.clearAndFree(p.gpa);
+ const id = p.paneBySerial(serial) orelse return;
+ const pane = p.panes[id].?;
+ const f = if (pane.file) |*file| file else return;
+ const page = try pardes.Term.page(p.gpa, held.items);
+ held.clearAndFree(p.gpa);
+ if (page.text.len == 0 and f.content.len == 0) return page.deinit(p.gpa);
+ if (!pane.fs.nomark) panes.File.pushUndo(p, pane) catch |err| {
+ page.deinit(p.gpa);
+ return err;
+ };
+ panes.File.setContent(p, f, page.text);
+ f.pager_spans = page.spans;
+ f.saved_revision = f.revision;
+ pardes.Plumb.paged(p, id);
+}
+
+/// The editor's step: the text of /pager opens closed unread goes in.
+pub fn fillClosedPagers(p: *Pardes) void {
+ for (p.fs.pages.items) |*page| {
+ fillPager(p, page.serial, &page.bytes) catch |err| if (p.paneBySerial(page.serial)) |id| p.reportError(id, "pager", err);
+ page.bytes.deinit(p.gpa);
+ }
+ p.fs.pages.clearRetainingCapacity();
+}
+
+/// One session builtin a line, at whichever pane has the keyboard as each
+/// runs, as the root's look and exec click there; all are checked first.
+pub fn writeRoot(p: *Pardes, req: Req) Reply {
+ const v = p.view();
+ for ([2]bool{ false, true }) |apply| {
+ if (apply) p.fs.results_len = 0;
+ var it: Messages = .{ .p = p, .data = req.data };
+ while (it.next()) |line| {
+ if (line.len == 0 or exec_line.isComment(line)) continue;
+ if (std.mem.startsWith(u8, line, "size ") or std.mem.eql(u8, line, "size")) {
+ // The offending word is the value: `size 5 5` quotes "5 5".
+ const value = std.mem.trim(u8, line["size".len..], " \t");
+ const size = sizeOf(line) orelse return refuseQuoting(p, req, e_size, value, "");
+ // A frontend's window is the size; only a session none is
+ // attached to (--detach, unattended) takes one written.
+ if (!p.unattended) return refuseQuoting(p, req, "size: a frontend is attached and owns the size", value, "");
+ if (apply) {
+ const was: [2]u16 = .{ v.screen_w, v.screen_h };
+ const before = v.rects;
+ p.update(.{ .resize = .{ .cols = size[0], .rows = size[1] } });
+ p.sync();
+ // Every pane keeps its tag and two rows, as placement
+ // leaves them (layout.minRows, the one minimum): a size
+ // too small for the panes' minima is refused, and one
+ // they fit gives back rows the resize took under them.
+ if (!pardes.layout.minimaFit(p)) {
+ p.update(.{ .resize = .{ .cols = was[0], .rows = was[1] } });
+ p.sync();
+ return refuseQuoting(p, req, "size: too small for the panes, each its tag and 2 rows", value, "");
+ }
+ pardes.layout.restoreMinimaFrom(p, &before, null);
+ p.sync();
+ }
+ continue;
+ }
+ // `adopt <dump>`: a pane or column another window's grip carried
+ // here (Handover.zig), taken in where the pointer is. A window's
+ // word to a window, as `size` is a frontend's: no builtin.
+ if (std.mem.startsWith(u8, line, "adopt ")) {
+ const path = std.mem.trim(u8, line["adopt".len..], " \t");
+ if (!apply) continue;
+ // ponytail: read on the 9P task, a small local file; a big
+ // one would want pardes.turn's yield.
+ const bytes = fs.readFile(p.gpa, path) catch |err| return refuseQuoting(p, req, @errorName(err), path, "");
+ defer p.gpa.free(bytes);
+ _ = pardes.Handover.adopt(p, bytes) catch |err| return refuseQuoting(p, req, @errorName(err), path, "");
+ continue;
+ }
+ if (!apply) {
+ if (checkBuiltin(p, req, line, .session)) |refusal| return refusal;
+ continue;
+ }
+ // An empty window (no pane at all) still takes its session words.
+ if (p.panes[v.active] == null and panes.anyPane(p) != null) return Reply.fail(req.tag, E.NOENT);
+ p.fs.session_write = true;
+ defer p.fs.session_write = false;
+ if (runBuiltin(p, req, v.active, line)) |refusal| return refusal;
+ }
+ }
+ return .{ .tag = req.tag, .written = @intCast(req.data.len) };
+}
+
+const size_min = [2]u16{ 20, 6 };
+const size_max = [2]u16{ 4096, 4096 };
+// "invalid": the word 9ns reads as EINVAL (enameToErrno), as winsize's.
+const e_size = std.fmt.comptimePrint("invalid size: takes <cols> <rows>, at least {d}x{d}, at most {d}x{d}", .{ size_min[0], size_min[1], size_max[0], size_max[1] });
+
+/// `size <cols> <rows>`, within size_min and size_max.
+fn sizeOf(line: []const u8) ?[2]u16 {
+ var it = std.mem.tokenizeAny(u8, line["size".len..], " \t");
+ const cols = std.fmt.parseInt(u16, it.next() orelse return null, 10) catch return null;
+ const rows = std.fmt.parseInt(u16, it.next() orelse return null, 10) catch return null;
+ if (it.next() != null or cols < size_min[0] or rows < size_min[1] or cols > size_max[0] or rows > size_max[1]) return null;
+ return .{ cols, rows };
+}
+
+// ---- /commands ----
+
+/// Every builtin the registry holds, one a line: its word, `arg` when it
+/// takes one, and which ctl takes it, `root` or `pane` -- the registry
+/// itself, so a new builtin is listed the moment it exists.
+/// A builtin's doc comment, its first sentence, from the source itself: a
+/// line of /commands says what each word does without a second copy of it.
+pub fn summaryOf(word: []const u8, buf: []u8) []const u8 {
+ const source = @embedFile("../builtins.zig");
+ var needle_buf: [64]u8 = undefined;
+ const needle = std.fmt.bufPrint(&needle_buf, "\npub const {s} = struct", .{word}) catch return "";
+ const at = std.mem.indexOf(u8, source, needle) orelse return "";
+ // Back over the `///` lines just above it.
+ var start = at + 1;
+ while (start > 0) {
+ const prev_end = start - 1;
+ const prev_start = if (std.mem.lastIndexOfScalar(u8, source[0..prev_end], '\n')) |nl| nl + 1 else 0;
+ if (!std.mem.startsWith(u8, std.mem.trimStart(u8, source[prev_start..prev_end], " "), "///")) break;
+ start = prev_start;
+ }
+ var w = std.Io.Writer.fixed(buf);
+ var lines = std.mem.splitScalar(u8, source[start .. at + 1], '\n');
+ while (lines.next()) |line| {
+ const text = std.mem.trim(u8, std.mem.trimStart(u8, std.mem.trimStart(u8, line, " "), "/"), " ");
+ if (text.len == 0) continue;
+ if (w.buffered().len > 0) w.writeByte(' ') catch break;
+ w.writeAll(text) catch break;
+ }
+ const all = stripCitations(w.buffered());
+ // The first sentence, whole: to a `.` that ends one.
+ var i: usize = 0;
+ while (std.mem.indexOfScalarPos(u8, all, i, '.')) |dot| : (i = dot + 1) {
+ if (dot + 1 == all.len or all[dot + 1] == ' ') return all[0 .. dot + 1];
+ }
+ return all;
+}
+
+/// Drops a parenthesis that cites source (`(editors/acme/exec.c:892)`,
+/// `(exec.c, \`kill\`; acme.c's WKill)`): a reader of /commands wants what
+/// the word does, not where acme has it. In place; answers the rest.
+fn stripCitations(text: []u8) []u8 {
+ var out: usize = 0;
+ var i: usize = 0;
+ while (i < text.len) {
+ if (text[i] == '(') if (std.mem.indexOfScalarPos(u8, text, i, ')')) |close| {
+ const inside = text[i + 1 .. close];
+ if (std.mem.indexOf(u8, inside, ".c") != null or std.mem.indexOf(u8, inside, ".zig") != null) {
+ // With the space before it, and a colon after it kept.
+ if (out > 0 and text[out - 1] == ' ') out -= 1;
+ i = close + 1;
+ continue;
+ }
+ };
+ text[out] = text[i];
+ out += 1;
+ i += 1;
+ }
+ return text[0..out];
+}
+
+fn writeCommands(p: *const Pardes, w: *std.Io.Writer) !void {
+ for (std.enums.values(Builtin)) |b| {
+ // A window's own word is none in a terminal's view.
+ if (!builtins.registry.here(p, b)) continue;
+ // Edit is a pane's word the root's ctl takes too, at the active pane.
+ const scope: []const u8 = if (b == .Edit) "both" else if (builtins.registry.scope(b) == .session) "root" else "pane";
+ try w.print("{s}{s} {s}", .{
+ @tagName(b),
+ if (builtins.registry.takesArg(b)) " arg" else "",
+ scope,
+ });
+ // A setting that chooses among words: the words, comma-joined. Bare,
+ // it steps to the next of them (a two-valued one flips).
+ if (config.Runtime.find(@tagName(b))) |setting| if (config.Runtime.choices(setting.action)) |values| {
+ try w.writeByte(' ');
+ var parts = std.mem.splitSequence(u8, values, ", ");
+ var first = true;
+ while (parts.next()) |v| : (first = false) try w.print("{s}{s}", .{ if (first) "" else ",", v });
+ };
+ // Then ` -- ` and what it does: a setting's doc, else its source's.
+ var summary_buf: [2048]u8 = undefined;
+ const summary = if (config.Runtime.find(@tagName(b))) |setting| setting.doc else summaryOf(@tagName(b), &summary_buf);
+ if (summary.len > 0) {
+ // The sentence whole unless it is long, then cut between words.
+ const kept = @import("../Messages.zig").clip(summary, 240);
+ try w.print(" -- {s}{s}", .{ kept, if (kept.len < summary.len) "…" else "" });
+ }
+ try w.writeByte('\n');
+ }
+ // The addons' words, after the core's: `(addon <name>)` says whose.
+ for (p.kinds.words[0..p.kinds.nwords]) |*kw| try w.print("{s}{s} {s} -- {s} (addon {s})\n", .{
+ kw.name.slice(),
+ if (kw.arg != pardes.Kind.c.PA_ARG_NONE) " arg" else "",
+ if (kw.opens != 0) "both" else "pane",
+ kw.doc.slice(),
+ p.kinds.kinds[kw.kind].nameOf(),
+ });
+}
+
+/// /commands' text (`writeCommands`), in the step's scratch.
+pub fn commandsText(p: *Pardes) std.Io.Writer.Error![]const u8 {
+ var text: std.Io.Writer.Allocating = .init(p.scratch.allocator());
+ try writeCommands(p, &text.writer);
+ return text.written();
+}
+
+// ---- /focus ----
+
+/// The pane with the keyboard, which a write of a serial moves, the way
+/// writing `current` to rio's wctl does (rio(4)). While a column's or the
+/// workspace's tag has it, no pane does, and this reads empty. A write
+/// gives the keyboard and nothing else: a folded pane stays folded, as
+/// rio keeps `current` apart from `unhide`.
+pub fn readFocus(p: *Pardes, req: Req) Reply {
+ const out = p.fs.stage(p.gpa);
+ if (p.view().header != null) return tree.stagedReply(p, req);
+ const pane = p.panes[p.view().active] orelse return tree.stagedReply(p, req);
+ out.print(p.gpa, "{d}\n", .{pane.serial}) catch return Reply.fail(req.tag, E.NOMEM);
+ return tree.stagedReply(p, req);
+}
+
+pub fn writeFocus(p: *Pardes, req: Req) Reply {
+ const text = std.mem.trim(u8, req.data, " \t\r\n");
+ const serial = std.fmt.parseInt(u32, text, 10) catch return tree.failText(req.tag, E.INVAL, tree.e_bad_ctl);
+ const id = p.paneBySerial(serial) orelse return tree.failText(req.tag, E.NOENT, e_no_pane);
+ // The keyboard goes to the pane itself, off any header that had it, and
+ // its column becomes the active one, as the user's click there would
+ // make it: pane/new and a look place there next.
+ tagline.exitHeader(p);
+ p.view().active = id;
+ if (pardes.layout.findPane(p, id)) |at| p.setActiveColumn(at.col);
+ return .{ .tag = req.tag, .written = @intCast(req.data.len) };
+}
+
+const e_no_pane = "no such pane";
+
+/// rio's kbdin (windows/rio/xfid.c:515): each rune written is a key typed
+/// at the pane with the keyboard, the user's own, each done before the next
+/// and all before the write is answered. Control runes are Ctrl and a
+/// letter, but for Plan 9's keys (include/ALL/keyboard.h): \n or \r Enter,
+/// \t Tab, \b Backspace, 0x7f Delete, 0x1b Esc, and the arrows, Home, End,
+/// Page Up and Down, Insert and F1-F12 at its private-use runes. Its
+/// Kalt, Kshift and Kctl runes, which Plan 9 sends alone, add Alt, Shift
+/// or Ctrl to the key after them.
+pub fn writeKbdin(p: *Pardes, req: Req) Reply {
+ const view = std.unicode.Utf8View.init(req.data) catch return tree.failText(req.tag, E.INVAL, "invalid UTF-8");
+ var it = view.iterator();
+ var mods: pardes.Key = .{ .cp = 0 };
+ while (it.nextCodepointSlice()) |rune| {
+ switch (std.unicode.utf8Decode(rune) catch unreachable) {
+ 0xF015 => mods.alt = true,
+ 0xF016 => mods.shift = true,
+ 0xF017 => mods.ctrl = true,
+ else => {
+ var key = kbdKey(rune);
+ key.alt = key.alt or mods.alt;
+ key.shift = key.shift or mods.shift;
+ key.ctrl = key.ctrl or mods.ctrl;
+ // A modified key types no text, as a terminal's report has none.
+ if (mods.alt or mods.ctrl) key.text = "";
+ p.update(.{ .key = key });
+ mods = .{ .cp = 0 };
+ },
+ }
+ }
+ return .{ .tag = req.tag, .written = @intCast(req.data.len) };
+}
+
+fn kbdKey(rune: []const u8) pardes.Key {
+ const K = pardes.Key;
+ const c = std.unicode.utf8Decode(rune) catch unreachable;
+ const KF: u21 = 0xF000;
+ return switch (c) {
+ '\n', '\r' => .{ .cp = K.enter },
+ '\t' => .{ .cp = K.tab },
+ 0x08 => .{ .cp = K.backspace },
+ 0x7f => .{ .cp = K.delete },
+ 0x1b => .{ .cp = K.escape },
+ 0x00 => .{ .cp = ' ', .ctrl = true },
+ 0x01...0x07, 0x0b, 0x0c, 0x0e...0x1a => .{ .cp = 'a' + c - 1, .ctrl = true },
+ KF | 0x0D => .{ .cp = K.home },
+ KF | 0x0E => .{ .cp = K.up },
+ 0xF800 => .{ .cp = K.down },
+ KF | 0x0F => .{ .cp = K.page_up },
+ KF | 0x11 => .{ .cp = K.left },
+ KF | 0x12 => .{ .cp = K.right },
+ KF | 0x13 => .{ .cp = K.page_down },
+ KF | 0x14 => .{ .cp = K.insert },
+ KF | 0x18 => .{ .cp = K.end },
+ KF | 0x01...KF | 0x0C => .{ .cp = K.f1 + (c - (KF | 0x01)) },
+ else => .{ .cp = c, .text = rune },
+ };
+}
+
+/// devmouse's mousein (kernel/devices/mouse/devmouse.c:445), in cells: a
+/// line `m col row buttons` is the mouse as it now is, Plan 9's bits (1
+/// left, 2 middle, 4 right; 8 and 16 a wheel notch up and down). What
+/// changed since the last line is pressed or released there, in that order
+/// of buttons; a move with one held drags, with none moves.
+pub fn writeMousein(p: *Pardes, req: Req) Reply {
+ var lines = std.mem.tokenizeScalar(u8, req.data, '\n');
+ while (lines.next()) |line| {
+ var words = std.mem.tokenizeAny(u8, line, " \t\r");
+ const m = words.next() orelse continue;
+ if (!std.mem.eql(u8, m, "m")) return tree.failText(req.tag, E.INVAL, "invalid mousein: m col row buttons");
+ var n: [3]u16 = undefined;
+ for (&n) |*v| v.* = std.fmt.parseInt(u16, words.next() orelse "", 10) catch
+ return tree.failText(req.tag, E.INVAL, "invalid mousein: m col row buttons");
+ const col, const row, const b = n;
+ if (b > 31) return tree.failText(req.tag, E.INVAL, "invalid mousein: buttons are 1 2 4 8 16");
+ const was = p.mousein_buttons;
+ const now: u8 = @intCast(b & 7);
+ const Button = pardes.Mouse.Button;
+ const buttons = [_]Button{ .left, .middle, .right };
+ for (buttons, 0..) |button, i| {
+ const bit = @as(u8, 1) << @intCast(i);
+ if (was & bit != 0 and now & bit == 0) p.update(.{ .mouse = .{ .button = button, .kind = .release, .col = col, .row = row } });
+ }
+ if (was == now and b & 24 == 0) {
+ const held = for (buttons, 0..) |button, i| {
+ if (now & (@as(u8, 1) << @intCast(i)) != 0) break button;
+ } else Button.none;
+ p.update(.{ .mouse = .{ .button = held, .kind = if (held == .none) .motion else .drag, .col = col, .row = row } });
+ }
+ for (buttons, 0..) |button, i| {
+ const bit = @as(u8, 1) << @intCast(i);
+ if (was & bit == 0 and now & bit != 0) p.update(.{ .mouse = .{ .button = button, .kind = .press, .col = col, .row = row } });
+ }
+ p.mousein_buttons = now;
+ if (b & 8 != 0) p.update(.{ .mouse = .{ .button = .wheel_up, .kind = .press, .col = col, .row = row } });
+ if (b & 16 != 0) p.update(.{ .mouse = .{ .button = .wheel_down, .kind = .press, .col = col, .row = row } });
+ }
+ return .{ .tag = req.tag, .written = @intCast(req.data.len) };
+}
+
+/// `get` reloads the buffer from the name it carries, wherever that name
+/// resolves. Any other line is a builtin that acts on a pane (`Del`,
+/// `Save f`), run at this one; a session's builtin is the root ctl's.
+///
+/// `lock` and `unlock` are acme's (editors/acme/xfid.c:603-611), so that a
+/// client can make an edit of several writes to addr and data without
+/// another's landing in between. As in acme the lock binds only the clients
+/// that ask for it; a write to any other file is never refused for it, nor
+/// is the person at the keyboard. It belongs to the open that wrote it,
+/// which alone may `unlock`, and closing that open or the pane gives it up.
+/// Where acme's qlock blocks a second locker, this refuses it at once with
+/// `file in use`, and the client tries again: through a kernel or FUSE
+/// mount a blocked write holds the file's writes, the holder's own `unlock`
+/// and close among them, so a waiting lock would never be let in.
+pub fn writePane(p: *Pardes, req: Req, pane: *Pane) Reply {
+ // This open's handle is what holds the lock; a write that came on no
+ // writable open (the editor's own) has none.
+ const mine: ?u32 = if (tree.openOf(p, req)) |o| (if (o.what == .ctl) req.handle else null) else null;
+ // The pane keeps the holder's handle, which names that open only on
+ // this pane's ctl node; one that no longer does holds nothing.
+ if (pane.fs.lock) |h| {
+ const o = tree.openOf(p, .{ .tag = 0, .op = .write, .node = tree.Node.of(pane.serial, .ctl), .handle = h });
+ if (o == null or o.?.what != .ctl) pane.fs.lock = null;
+ }
+ const other = pane.fs.lock != null and pane.fs.lock != mine;
+ const serial = pane.serial;
+ // Checked whole before anything applies, so a write that must wait for
+ // the lock has done nothing yet when it goes again.
+ if (editNotAlone(p, req.data)) return tree.failText(req.tag, E.INVAL, e_after_edit);
+ for ([2]bool{ false, true }) |apply| {
+ if (apply) p.fs.results_len = 0;
+ var held = !other and pane.fs.lock != null;
+ var it: Messages = .{ .p = p, .data = req.data };
+ while (it.next()) |line_in| {
+ if (line_in.len == 0 or exec_line.isComment(line_in)) continue;
+ // A line before this one may have closed the pane (`Del`).
+ if (apply and p.paneBySerial(serial) == null) return Reply.fail(req.tag, E.NOENT);
+ // acme's ctl words: done by the file that replaces each, or the
+ // builtin that does it, checked with the rest before any runs.
+ var line = line_in;
+ switch (acmeCtl(p, req, serial, line_in, apply)) {
+ .no => {},
+ .done => continue,
+ .refused => |r| return r,
+ .builtin => |word| line = word,
+ }
+ if (std.meta.stringToEnum(enum { get, lock, unlock, answer }, line)) |word| switch (word) {
+ .get => {
+ if (!apply) continue;
+ if (@import("../edit_cmd.zig").busyOn(p, p.paneBySerial(serial).?)) return tree.failText(req.tag, E.BUSY, "get: " ++ @import("../edit_cmd.zig").e_busy);
+ // It ran and was refused: its words (in ename), not the line
+ // quoted, as a builtin's refusal (Save's) says it.
+ if (getRefused(p, pane, "get")) |said| return tree.failText(req.tag, E.IO, said);
+ // Naming the path, in words 9ns reads as the errno; a peer
+ // out of reach as a look or a Save says it.
+ get(p, pane) catch |err| {
+ const path = if (pane_files.fileOf(pane)) |f| f.path else "";
+ var why_buf: pardes.Kind.Buf(48) = .{};
+ const why = if (pardes.Messages.dialReason(err)) |r|
+ why_buf.print("dial failed: {s}", .{r})
+ else if (err == error.FileNotFound) "no such file" else "cannot be read";
+ return tree.failText(req.tag, if (err == error.FileNotFound) E.NOENT else E.IO, std.fmt.bufPrint(&p.fs.ename, "get: {s}: {s}", .{ path[0..@min(path.len, 256)], why[0..@min(why.len, 48)] }) catch &p.fs.ename); // cut to ename's 320
+ };
+ },
+ .lock => {
+ if (mine == null) return tree.failText(req.tag, E.INVAL, tree.e_bad_ctl);
+ if (other) return tree.failText(req.tag, E.BUSY, e_locked);
+ held = true;
+ if (apply) pane.fs.lock = mine;
+ },
+ .unlock => {
+ if (!held) return tree.failText(req.tag, E.INVAL, e_not_locked);
+ held = false;
+ if (apply) pane.fs.lock = null;
+ },
+ .answer => {
+ // With a question up, what it offers.
+ var offered: [64]u8 = undefined;
+ if (keys.questionChoices(p, p.paneBySerial(serial).?, &offered)) |choices|
+ return tree.failText(req.tag, E.INVAL, std.fmt.bufPrint(&p.fs.ename, "answer takes {s} or -", .{choices[0..@min(choices.len, 64)]}) catch &p.fs.ename); // cut to ename's 320
+ return tree.failText(req.tag, E.INVAL, "answer takes a choice or -");
+ },
+ } else if (std.mem.startsWith(u8, line, "answer ") and p.panes[p.paneBySerial(serial).?].?.prompt == .save) {
+ // Save's path, asked over 9P (`ask <serial> save path`).
+ if (!apply) continue;
+ const id = p.paneBySerial(serial).?;
+ const asked = p.panes[id].?;
+ const path = std.mem.trim(u8, line["answer ".len..], " ");
+ var rec: pardes.Kind.Buf(300) = .{};
+ pardes.ctlfs.events.notePath(p, "answer", rec.print("{d} {s}", .{ serial, path }));
+ if (!std.mem.eql(u8, path, "-")) exec_line.saveTo(p, id, path);
+ asked.closePrompt();
+ } else if (std.mem.startsWith(u8, line, "answer ")) {
+ // The pane's question (its `ask` in the log), answered.
+ const choice = std.mem.trim(u8, line["answer ".len..], " ");
+ const id = p.paneBySerial(serial).?;
+ var offered: [64]u8 = undefined;
+ const choices = keys.questionChoices(p, id, &offered) orelse return refuse(p, req, "no question asked", line);
+ // Only a choice the question offers answers it; anything
+ // else leaves it standing, and says what it takes.
+ if (!std.mem.eql(u8, choice, "-") and (choice.len != 1 or std.mem.indexOfScalar(u8, choices, choice[0]) == null)) {
+ var why: pardes.Kind.Buf(96) = .{};
+ // The choice refused is what is quoted: `answer takes a b or - "z"`.
+ return refuseQuoting(p, req, why.print("answer takes {s} or -", .{choices}), choice, "");
+ }
+ if (apply) _ = keys.answerQuestion(p, id, if (choice[0] == '-') null else choice[0]);
+ } else if (!apply) {
+ if (checkBuiltin(p, req, line, .pane)) |refusal| return refusal;
+ // Edit on a pane with no text is the refusal a data write
+ // there gets, EINVAL, before anything runs.
+ if (std.mem.startsWith(u8, line, "Edit") and pane_files.fileOf(p.panes[p.paneBySerial(serial).?].?) == null)
+ return tree.failText(req.tag, E.INVAL, pane_files.e_no_text);
+ } else if (runBuiltin(p, req, p.paneBySerial(serial).?, line)) |refusal| {
+ return refusal;
+ }
+ }
+ }
+ return .{ .tag = req.tag, .written = @intCast(req.data.len) };
+}
+
+/// acme's pane ctl vocabulary (editors/acme/xfid.c xfidctlwrite): each word
+/// done here by the file that replaces it, or run as the builtin that does
+/// it; those with no place here refused with why.
+const AcmeCtl = union(enum) { no, done, refused: Reply, builtin: []const u8 };
+
+fn acmeCtl(p: *Pardes, req: Req, serial: u32, line: []const u8, apply: bool) AcmeCtl {
+ const id = p.paneBySerial(serial) orelse return .no;
+ const pane = p.panes[id].?;
+ const word = line[0 .. std.mem.indexOfScalar(u8, line, ' ') orelse line.len];
+ const rest = std.mem.trim(u8, line[word.len..], " ");
+ const File = tree.PaneFile;
+ // A word written to one of the pane's own files, as acme's is to its.
+ const Into = struct { file: File, data: []const u8 };
+ const Word = enum { name, clean, dirty, mark, nomark, put, del, delete, @"dot=addr", @"addr=dot", @"limit=addr", show, cleartag, dump, dumpdir, font, menu, nomenu };
+ const w = std.meta.stringToEnum(Word, word) orelse return .no;
+ // name, dump, dumpdir and font take what follows them; the rest are a line alone.
+ switch (w) {
+ .name, .dump, .dumpdir, .font => {},
+ else => if (word.len != line.len) return .no,
+ }
+ const pf = &pane.fs;
+ const into: Into = switch (w) {
+ // `name` takes all after its one blank, as the name file takes what
+ // is written; with nothing after it, it names nothing (said so, not
+ // an unknown word), and a second blank is refused, not taken as the
+ // name's first byte: a line's words are split at blanks.
+ .name => if (rest.len == 0)
+ return .{ .refused = tree.failText(req.tag, E.INVAL, "invalid file name: name takes the name, and there is none") }
+ else if (line[word.len + 1] == ' ')
+ return .{ .refused = tree.failText(req.tag, E.INVAL, "bad character in file name: a blank at its start") }
+ else
+ .{ .file = .name, .data = line[word.len + 1 ..] },
+ .clean => .{ .file = .dirty, .data = "0" },
+ .dirty => .{ .file = .dirty, .data = "1" },
+ .mark => .{ .file = .mark, .data = "1" },
+ .nomark => .{ .file = .mark, .data = "0" },
+ .put => return .{ .builtin = "Save" },
+ .del => return .{ .builtin = "Del" },
+ .delete => return .{ .builtin = "Delete" },
+ .@"dot=addr", .@"addr=dot", .@"limit=addr", .show, .cleartag => {
+ if (apply) switch (w) {
+ .@"dot=addr" => pane_files.setDot(pane, pf.addr),
+ .@"addr=dot" => pf.addr = pane_files.dotOf(pane),
+ .@"limit=addr" => pf.limit = pf.addr,
+ .show => pane_files.showOffset(pane, pane_files.dotOf(pane).q0),
+ else => _ = pane_files.truncate(p, pane, .tag),
+ };
+ return .done;
+ },
+ .dump, .dumpdir, .font, .menu, .nomenu => {
+ const why = switch (w) {
+ .font => "the font is the session's: Font on /ctl",
+ .menu, .nomenu => "pardes has no menu",
+ else => "a pane is dumped with the session: Dump and DumpDir on /ctl",
+ };
+ return .{ .refused = tree.failText(req.tag, E.INVAL, std.fmt.bufPrint(&p.fs.ename, "invalid: acme's {s}: {s}", .{ @tagName(w), why }) catch &p.fs.ename) }; // cut to ename's 320
+ },
+ };
+ if (!apply) return .done;
+ const r = pane_files.write(p, .{ .tag = req.tag, .op = .write, .node = tree.Node.of(serial, into.file), .data = into.data }, id, pane, into.file);
+ return if (r.status == .err) .{ .refused = r } else .done;
+}
+
+const e_not_locked = "pane not locked by this open";
+/// Who holds it is another open of this ctl, whose client pardes cannot name.
+const e_locked = tree.e_in_use ++ ": another open of this ctl holds the lock";
+
+/// acme's get asks winclean first (exec.c:513): unsaved text is warned
+/// about once, and the same get again, nothing edited since, discards it.
+/// Asked once over unsaved edits, by `word` (ctl's `get`, the Get builtin):
+/// the words of the refusal, in ename; null to go ahead.
+pub fn getRefused(p: *Pardes, pane: *Pane, word: []const u8) ?[]const u8 {
+ const f = pane_files.fileOf(pane) orelse return null;
+ if (!panes.Output.fileTraits(f.output).saves or f.revision == f.saved_revision) return null;
+ // A scratch under 100 bytes is not asked about, as Del and Exit do not
+ // ask (builtins.warnModifiedIn): nothing worth a question to lose.
+ if (f.output != null and f.content.len < 100) return null;
+ // Dirty by a rename alone is no text to lose: only edits are asked about.
+ const saved = f.saved_hash orelse return null;
+ if (std.hash.Wyhash.hash(0, f.content) == saved) return null;
+ if (pane.discard_warned) |w| if (w.revision == f.revision and w.by == .get) return null;
+ pane.discard_warned = .{ .revision = f.revision, .by = .get };
+ const id = p.paneBySerial(pane.serial).?;
+ // Kept in +Unsaved, as Exit's refusal is; the notice is short. The
+ // write's err record logs it, not a msg too.
+ // And logged `unsaved <serial> <name>`, as the other refusals are.
+ tree.events.noteLog(p, .unsaved, pane);
+ const listed = std.fmt.allocPrint(p.gpa, "{s}: Modified\n\n{s} again to discard\n", .{ f.path, word }) catch null;
+ if (listed) |content| panes.Output.openUnsaved(p, id, content);
+ var notice: pardes.Kind.Buf(64) = .{};
+ p.fs.unlogged = true;
+ p.setMessage(id, notice.print("1 unsaved pane \u{2014} {s} again to discard", .{word}));
+ p.fs.unlogged = false;
+ return std.fmt.bufPrint(&p.fs.ename, "{s}: Modified ({s} again to discard)", .{ f.path[0..@min(f.path.len, 256)], word[0..@min(word.len, 16)] }) catch &p.fs.ename; // cut to ename's 320
+}
+
+/// acme's `Get file`, and Edit's `e file`: the file at `path` (absolute)
+/// loaded into the pane, which takes its name, in one undo step that puts
+/// the old name back with the old text. Read first, so one that cannot be
+/// read changes nothing; loaded, the pane is clean. Asking about unsaved
+/// edits is the caller's (getRefused).
+pub fn getFile(p: *Pardes, pane: *Pane, path: []const u8) GetError!void {
+ const f = pane_files.fileOf(pane) orelse return error.NotAFile;
+ const id = p.paneBySerial(pane.serial) orelse return error.FileNotFound;
+ const bytes = try fs.read(p, path);
+ panes.File.pushUndo(p, pane) catch |err| {
+ p.gpa.free(bytes);
+ return err;
+ };
+ pane_files.nameBuffer(p, id, path, false) catch |err| {
+ p.gpa.free(bytes);
+ return if (err == error.OutOfMemory) error.OutOfMemory else error.InvalidName;
+ };
+ panes.File.setContent(p, f, bytes);
+ f.saved_revision = f.revision;
+ f.saved_hash = std.hash.Wyhash.hash(0, f.content);
+ f.saved_len = f.content.len;
+ f.disk_newer = null;
+ f.disk_newer_warned = false;
+ f.disk_gone = false;
+ if (fs.localPath(path) != null) p.emit(.{ .watch = .{ .pane = @intCast(id), .on = true } });
+}
+
+/// What Get and Edit's `e` fail with, as their callers say it (the 9P
+/// reply's errno, FileNotFound ENOENT and the rest EIO; a peer's dial,
+/// Messages.dialReason; Get's words, Messages.errorWords): a read's, and a
+/// name the pane cannot take.
+pub const GetError = fs.ReadError || error{InvalidName};
+
+pub fn get(p: *Pardes, pane: *Pane) GetError!void {
+ const f = pane_files.fileOf(pane) orelse return;
+ // A directory pane: the directory read again (Dir.zig).
+ if (f.listing != null) return panes.Dir.refresh(p, p.paneBySerial(pane.serial).?) catch |err| switch (err) {
+ error.FileNotFound, error.OutOfMemory => |e| e,
+ else => error.ReadFailed,
+ };
+ if (!panes.Output.fileTraits(f.output).saves) return;
+ const bytes = try fs.read(p, f.path);
+ // Throwing unsaved edits away for it is a reload the log hears of, as a
+ // clean one from the watch is.
+ const discarded = f.revision != f.saved_revision;
+ panes.File.pushUndo(p, pane) catch |err| {
+ p.gpa.free(bytes);
+ return err;
+ };
+ panes.File.setContent(p, f, bytes);
+ f.saved_revision = f.revision;
+ f.saved_hash = std.hash.Wyhash.hash(0, f.content);
+ f.saved_len = f.content.len;
+ f.disk_newer = null;
+ f.disk_gone = false;
+ if (discarded) {
+ var rec: [32]u8 = undefined;
+ pardes.ctlfs.events.notePath(p, "changed", std.fmt.bufPrint(&rec, "{d} reloaded", .{pane.serial}) catch unreachable); // a u32 fits 32
+ }
+}
+
+// ---- tests ----
+
+const testing = std.testing;
+const th = @import("testing.zig");
+const call = th.call;
+const rd = th.rd;
+const wr = th.wr;
+const withFile = th.withFile;
+const serialOf = th.serialOf;
+const Node = tree.Node;
+const Status = tree.Status;
+const root_status = @backingInt(tree.TopFile.status);
+const root_look = @backingInt(tree.TopFile.look);
+const root_exec = @backingInt(tree.TopFile.exec);
+
+test "pane ctl read is acme's fields -- index's five, width in cells, font, tab width, undo, redo -- then whether it is current" {
+ const gpa = testing.allocator;
+ const p = try withFile(gpa, "x\n");
+ defer p.deinit();
+ const pane = p.panes[0].?;
+
+ const a = rd(p, Node.of(pane.serial, .ctl), 0, 4096);
+ try testing.expectEqual(Status.ok, a.reply.status);
+ var want: std.ArrayList(u8) = .empty;
+ defer want.deinit(gpa);
+ try want.print(gpa, "{d:>11} {d:>11} {d:>11} {d:>11} {d:>11} {d:>11} {s} {d:>11} {d:>11} {d:>11} current mode:normal ", .{
+ pane.serial, (try pane_files.tagOf(p, pane)).len, @as(usize, 2), 0, 0, pane.cols, "default", config.tab_now, 0, 0,
+ });
+ try testing.expectEqualStrings(want.items, a.bytes);
+ try testing.expectEqual(@as(u64, a.bytes.len), call(p, .{ .tag = 1, .op = .getattr, .node = Node.of(pane.serial, .ctl) }).reply.attr.size);
+
+ var quoted: [64]u8 = undefined;
+ var w = std.Io.Writer.fixed(&quoted);
+ try writeQuoted(&w, "DejaVu Sans Mono");
+ try testing.expectEqualStrings("'DejaVu Sans Mono'", w.buffered());
+ w = std.Io.Writer.fixed(&quoted);
+ try writeQuoted(&w, "it's");
+ try testing.expectEqualStrings("'it''s'", w.buffered());
+}
+
+test "commands lists every builtin with its argument and the ctl that takes it" {
+ const p = try withFile(testing.allocator, "x\n");
+ defer p.deinit();
+ const node = @backingInt(tree.TopFile.commands);
+ const listed = rd(p, node, 0, 1 << 16);
+ try testing.expectEqual(@as(u64, listed.bytes.len), call(p, .{ .tag = 1, .op = .getattr, .node = node }).reply.attr.size);
+ try testing.expectEqual(E.PERM, wr(p, node, "Del\n").errno());
+ var lines: usize = 0;
+ var it = std.mem.tokenizeScalar(u8, listed.bytes, '\n');
+ while (it.next()) |line| : (lines += 1) {
+ var words = std.mem.tokenizeScalar(u8, line, ' ');
+ const b = std.meta.stringToEnum(Builtin, words.next().?).?;
+ if (builtins.registry.takesArg(b)) try testing.expectEqualStrings("arg", words.next().?);
+ try testing.expectEqualStrings(if (b == .Edit) "both" else if (builtins.registry.scope(b) == .session) "root" else "pane", words.next().?);
+ if (config.Runtime.find(@tagName(b))) |s| if (config.Runtime.choices(s.action) != null) try testing.expect(words.next() != null);
+ // Then, where the source has one, ` -- ` and what it does.
+ if (words.next()) |dashes| try testing.expectEqualStrings("--", dashes);
+ }
+ var here: usize = 0;
+ for (std.enums.values(Builtin)) |b| here += @intFromBool(builtins.registry.here(p, b));
+ try testing.expectEqual(here, lines);
+ for ([_][]const u8{ "\nDel arg pane -- ", "\nNewcol root -- ", "\nSave arg pane", "\nVerbose arg root on,off", "\nUndo pane -- ", "\nEdit arg both -- acme's Edit" }) |row|
+ try testing.expect(std.mem.indexOf(u8, listed.bytes, row) != null);
+}
+
+
+test "status in a window says whether the pointer is over it" {
+ // The rest of status is test/behaviour/look_and_exec.zig's: a session
+ // there is a terminal's view.
+ const p = try withFile(testing.allocator, "x\n");
+ defer p.deinit();
+ p.view().frontend.windowed = true;
+ var lines = std.mem.tokenizeScalar(u8, rd(p, root_status, 0, 4096).bytes, '\n');
+ for (0..3) |_| _ = lines.next();
+ try testing.expectEqualStrings("pointer out", lines.next().?);
+ p.view().frontend.windowed = false;
+}
+
+
+test "Zerox twins: a Save from one, performed, cleans both" {
+ // The rest of Zerox is test/behaviour/panes.zig's; this needs the save done.
+ var tmp = testing.tmpDir(.{});
+ defer tmp.cleanup();
+ var dir_buf: [4096]u8 = undefined;
+ const dir = dir_buf[0..try tmp.dir.realPath(testing.io, &dir_buf)];
+ const p = try withFile(testing.allocator, "one\n");
+ defer p.deinit();
+ var name: [std.Io.Dir.max_path_bytes + 8]u8 = undefined;
+ _ = wr(p, Node.of(serialOf(p), .name), try std.fmt.bufPrint(&name, "{s}/z.txt\n", .{dir}));
+ try testing.expect(p.executeBuiltinLine(0, "Zerox"));
+ const twin_id = for (p.panes, 0..) |slot, id| {
+ if (id != 0) if (slot) |pane| if (pane.file != null) break id;
+ } else return error.NoTwin;
+ const a = p.panes[0].?;
+ const b = p.panes[twin_id].?;
+ try testing.expectEqual(Status.ok, wr(p, Node.of(b.serial, .body), "two\n").reply.status);
+ try testing.expect(p.executeBuiltinLine(twin_id, "Save"));
+ while (p.nextEffect()) |e| p.perform(e);
+ try testing.expect(!pane_files.dirtyOf(a) and !pane_files.dirtyOf(b));
+ try testing.expectEqualStrings("one\ntwo\n", p.fallback.get(b.file.?.path).?);
+}
+
+test "Zerox twins dump their text once and come back on one buffer from a Restore" {
+ const p = try withFile(testing.allocator, "one\ntwo\n");
+ defer p.deinit();
+ const first = serialOf(p);
+ _ = wr(p, Node.of(first, .name), "/tmp/pardes-zerox-dump.txt\n");
+ _ = wr(p, Node.of(first, .body), std.mem.asBytes(&@as([64][8]u8, @splat("unsaved ".*))) ++ "\n");
+ try testing.expect(p.executeBuiltinLine(0, "Zerox"));
+ try testing.expect(p.executeBuiltinLine(0, "Zerox"));
+ try pardes.dump.dumpState(p);
+ const text = p.dump_out.?;
+ // The text is kept once though three panes show it.
+ try testing.expectEqual(@as(usize, 1), std.mem.count(u8, text, p.panes[0].?.file.?.content));
+ const restored = try pardes.dump.restore(p, text, "/tmp/pardes.dump.zon");
+ defer restored.deinit();
+ var files: [3]*pardes.panes.File.State = undefined;
+ var n: usize = 0;
+ for (restored.panes) |slot| if (slot) |pane| if (pane.file) |*f| if (std.mem.eql(u8, f.path, "/tmp/pardes-zerox-dump.txt")) {
+ files[n] = f;
+ n += 1;
+ };
+ try testing.expectEqual(@as(usize, 3), n);
+ for (files[1..]) |f| {
+ try testing.expectEqual(files[0].content.ptr, f.content.ptr);
+ try testing.expectEqual(files[0].history, f.history);
+ try testing.expect(f.twin != 0 and f.twin == files[0].twin);
+ }
+ try testing.expect(std.mem.startsWith(u8, files[0].content, "one\ntwo\nunsaved "));
+}
+
+test "Undo to unsaved text under its old name says nothing changed on disk when nothing did, and Save then writes" {
+ var tmp = testing.tmpDir(.{});
+ defer tmp.cleanup();
+ try tmp.dir.writeFile(testing.io, .{ .sub_path = "e.txt", .data = "e\n" });
+ try tmp.dir.writeFile(testing.io, .{ .sub_path = "b.txt", .data = "b\n" });
+ var dir_buf: [4096]u8 = undefined;
+ const dir = dir_buf[0..try tmp.dir.realPath(testing.io, &dir_buf)];
+ for ([_][]const u8{ "Get b.txt", "Edit e b.txt" }) |load| {
+ const p = try withFile(testing.allocator, "x\n");
+ defer p.deinit();
+ const serial = serialOf(p);
+ const pane = p.panes[0].?;
+ var name: [4300]u8 = undefined;
+ _ = wr(p, Node.of(serial, .name), try std.fmt.bufPrint(&name, "{s}/e.txt\n", .{dir}));
+ try testing.expect(p.executeBuiltinLine(0, "Get"));
+ _ = wr(p, Node.of(serial, .body), "appended\n");
+ // Asked once, then loaded.
+ try testing.expect(p.executeBuiltinLine(0, load));
+ try testing.expect(p.executeBuiltinLine(0, load));
+ try testing.expectEqualStrings("b\n", pane.file.?.content);
+ try testing.expect(p.executeBuiltinLine(0, "Undo"));
+ try testing.expectEqualStrings("e\nappended\n", pane.file.?.content);
+ try testing.expect(pane_files.dirtyOf(pane));
+ // The watch looks again at e.txt, as it was all along.
+ pardes.panes.File.changed(p, 0, "e\n");
+ try testing.expectEqual(@as(?u64, null), pane.file.?.disk_newer);
+ try testing.expect(!th.logHas(p, "changed on disk"));
+ // A change there is still news.
+ pardes.panes.File.changed(p, 0, "someone else\n");
+ try testing.expect(pane.file.?.disk_newer != null);
+ }
+}
+
+test "the init file saved says a bad line as startup does" {
+ // Get of a file not there is test/behaviour/panes.zig's.
+ const p = try Pardes.init(testing.allocator, .{ .tty_only = true, .startup_config = "Theme dusk\n", .startup_config_path = "/tmp/pardes-init-test/init" });
+ defer p.deinit();
+ pardes.exec.reapplyInitFile(p, "/tmp/pardes-init-test/init", "Theme acme\nnosuchword 1\nNewcol\n");
+ try testing.expect(th.logHas(p, "err - init file line 2: unknown word \"nosuchword 1\""));
+ try testing.expect(!th.logHas(p, "init file line 3"));
+}
+
+test "a body write to a terminal is typed input, not a paste, even to a program that asked for bracketed paste" {
+ const p = try Pardes.init(testing.allocator, .{ .cols = 90, .rows = 30 });
+ defer p.deinit();
+ while (p.nextEffect()) |_| {}
+ const term = for (p.panes, 0..) |slot, id| {
+ if (slot) |pane| if (pane.isTerminal()) break id;
+ } else return error.SkipZigTest;
+ p.update(.{ .output = .{ .pane = @intCast(term), .bytes = "\x1b[?2004h" } });
+ while (p.nextEffect()) |_| {}
+ const w = wr(p, Node.of(p.panes[term].?.serial, .body), "ls\n");
+ try testing.expectEqual(Status.ok, w.reply.status);
+ try testing.expectEqualStrings("ls\n", w.pty_buf[0..w.pty_len]);
+}
+
+test "Save path of a file pane logs a save record naming that path" {
+ const p = try withFile(testing.allocator, "one\n");
+ defer p.deinit();
+ const serial = serialOf(p);
+ const saved = wr(p, Node.of(serial, .ctl), "Save /tmp/pardes-save-copy.txt\n");
+ try testing.expectEqual(Status.ok, saved.reply.status);
+ p.perform(.{ .save_text = .{ .pane = 0, .serial = serial, .path = Pardes.SavePath.from("/tmp/pardes-save-copy.txt") } });
+ var want: [64]u8 = undefined;
+ try testing.expect(th.logHas(p, try std.fmt.bufPrint(&want, "save {d} /tmp/pardes-save-copy.txt\n", .{serial})));
+}
+
+test "an address looked at in an image pane names the image, never an empty subject" {
+ const p = try withFile(testing.allocator, "x\n");
+ defer p.deinit();
+ const id = p.freeSlot().?;
+ const doc = try pardes.Kind.open(p, id, pardes.Kind.test_kind.of(p), "/tmp/pardes-pic.ppm", null);
+ _ = wr(p, Node.of(doc.serial, .look), ":/x/\n");
+ try testing.expect(th.logHas(p, "look: /tmp/pardes-pic.ppm is no text to address"));
+}
+
+test "Save and Save path on a kind's pane (a picture) are refused with why, never a silent success" {
+ const p = try withFile(testing.allocator, "x\n");
+ defer p.deinit();
+ const id = p.freeSlot().?;
+ const doc = try pardes.Kind.open(p, id, pardes.Kind.test_kind.of(p), "/tmp/pardes-pic.ppm", null);
+ for ([_][]const u8{ "Save\n", "Save /tmp/pardes-copy.ppm\n" }) |line| {
+ const r = wr(p, Node.of(doc.serial, .ctl), line);
+ try testing.expectEqual(Status.err, r.reply.status);
+ try testing.expectEqualStrings("Save: a test pane has no text to save", r.reply.ename);
+ }
+}
+
+test "a builtin for one kind of pane is refused on another, and still acts on its own kind" {
+ const gpa = testing.allocator;
+ const p = try withFile(gpa, "text\n");
+ defer p.deinit();
+ const serial = serialOf(p);
+ const cases = [_]struct { []const u8, []const u8 }{
+ .{ "Petscii\n", "Petscii: only an image or a terminal pane takes it" },
+ .{ "Palette\n", "Palette: only an image pane takes it" },
+ .{ "Ascii\n", "Ascii: only an image pane takes it" },
+ .{ "Filter\n", "Filter: only a terminal or a +Pager pane takes it" },
+ .{ "Diff\n", "Diff: only a diff or a +Diff pane takes it" },
+ .{ "Togglettymode\n", "Togglettymode: only a terminal pane takes it" },
+ };
+ for (cases) |case| {
+ const r = wr(p, Node.of(serial, .ctl), case[0]);
+ try testing.expectEqual(Status.err, r.reply.status);
+ try testing.expectEqualStrings(case[1], r.reply.ename);
+ }
+ const id = p.freeSlot().?;
+ // A picture shown: the core's art words follow the kind's prefix.
+ const doc = try pardes.Kind.open(p, id, pardes.Kind.test_kind.of(p), "/tmp/pardes-pic.ppm", "P6\n1 1\n255\n\x01\x02\x03");
+ while (p.nextEffect()) |e| p.perform(e);
+ pardes.layout.placeNew(p, 0, 0, id, .doc);
+ _ = try p.render(p.scratch.allocator());
+ const r = wr(p, Node.of(doc.serial, .ctl), "Mode\n");
+ try testing.expectEqualStrings("Mode: only a text or terminal pane has modes", r.reply.ename);
+ const glyphs = doc.addon.?.art.glyph;
+ try testing.expectEqual(Status.ok, wr(p, Node.of(doc.serial, .ctl), "Petscii\n").reply.status);
+ try testing.expect(doc.addon.?.art.glyph != glyphs);
+ // Its tag says what is drawn: with no graphics, glyph art whatever
+ // Petscii chose; with them, what it chose.
+ for ([_]bool{ false, true }) |art| {
+ doc.addon.?.art.glyph = art;
+ p.view().frontend.native_images = false;
+ try testing.expect(std.mem.indexOf(u8, try pardes.tagline.tagPrefix(p, doc), " petscii:on ") != null);
+ p.view().frontend.native_images = true;
+ try testing.expect(std.mem.indexOf(u8, try pardes.tagline.tagPrefix(p, doc), if (art) " petscii:on " else " petscii:off ") != null);
+ }
+}
+
+test "exec Save writes the named file through the host" {
+ const gpa = testing.allocator;
+ const p = try withFile(gpa, "one\ntwo\n");
+ defer p.deinit();
+ const serial = serialOf(p);
+ const pane = p.panes[0].?;
+ try testing.expectEqual(Status.ok, wr(p, Node.of(serial, .name), "/tmp/renamed.txt\n").reply.status);
+ try testing.expect(!pane_files.dirtyOf(pane)); // a name alone is no edit; Save writes all the same
+ const saved = wr(p, Node.of(serial, .exec), "Save\n");
+ try testing.expectEqual(Status.ok, saved.reply.status);
+ try testing.expect(saved.saved);
+ p.perform(.{ .save_file = .{ .pane = 0 } });
+ try testing.expect(!pane_files.dirtyOf(pane));
+ try testing.expectEqualStrings(pane.file.?.content, p.fallback.get("/tmp/renamed.txt").?);
+}
+
+test "a refusal's +Unsaved goes in the session's directory when the active pane's directory is not there" {
+ const p = try withFile(testing.allocator, "x\n");
+ defer p.deinit();
+ const serial = serialOf(p);
+ try testing.expectEqual(Status.ok, wr(p, Node.of(serial, .name), "/tmp/pardes-no-such-dir-zz/x.txt\n").reply.status);
+ try testing.expectEqual(Status.ok, wr(p, Node.of(serial, .body), "edited\n").reply.status);
+ try testing.expectEqual(Status.err, wr(p, @backingInt(tree.TopFile.ctl), "Exit\n").reply.status);
+ const unsaved = for (p.panes) |slot| {
+ const pane = slot orelse continue;
+ const f = pane.file orelse continue;
+ if (f.output) |o| if (o.from == .unsaved) break f.path;
+ } else return error.NoUnsavedPane;
+ try testing.expectEqualStrings(p.sessionDir(), std.Io.Dir.path.dirname(unsaved).?);
+}
+
+
+test "a builtin's Verbose announcement is logged only when it succeeds, its failure said now or by the host later" {
+ const gpa = testing.allocator;
+ const p = try withFile(gpa, "x\n");
+ defer p.deinit();
+ const serial = serialOf(p);
+ var want: [64]u8 = undefined;
+ const said_exit = try std.fmt.bufPrint(&want, "msg {d} Exit\n", .{serial});
+ // A Save a ctl write gives no name to, on a scratch: refused, no Save.
+ const scratch = try th.newPane(p);
+ var said_save_buf: [64]u8 = undefined;
+ try testing.expectEqual(E.INVAL, wr(p, Node.of(scratch, .ctl), "Save\n").errno());
+ try testing.expect(!th.logHas(p, try std.fmt.bufPrint(&said_save_buf, "msg {d} Save\n", .{scratch})));
+ // Refused as it runs, through a click: the write fails, and no Exit.
+ const f = &p.panes[0].?.file.?;
+ f.saved_revision = f.revision -% 1;
+ f.saved_hash = 0;
+ try testing.expect(wr(p, Node.of(serial, .exec), "Exit\n").errno() != 0);
+ try testing.expect(!th.logHas(p, said_exit));
+ // Refused at the keyboard (no write to fail), edited since: the same.
+ f.revision +%= 1;
+ _ = p.executeBuiltinLine(p.view().active, "Exit");
+ try testing.expect(!th.logHas(p, said_exit));
+ try testing.expect(!p.quit);
+ // A Save the host could not do, told a step later: the Save goes too.
+ var save_buf: [64]u8 = undefined;
+ const said_save = try std.fmt.bufPrint(&save_buf, "msg {d} Save\n", .{serial});
+ _ = wr(p, Node.of(serial, .exec), "Save\n");
+ p.saveFailed(@intCast(p.paneBySerial(serial).?), "/test.txt", error.AccessDenied);
+ try testing.expect(!th.logHas(p, said_save));
+ // One that does what it says keeps its announcement.
+ _ = wr(p, Node.of(serial, .exec), "Undo\n");
+ var undo_buf: [64]u8 = undefined;
+ try testing.expect(th.logHas(p, try std.fmt.bufPrint(&undo_buf, "msg {d} Undo", .{serial})));
+}
+
+test "an error's words give the errno a mount reads: EINVAL for what is malformed, EIO for what failed" {
+ // 9ns (cloud9's 9ns/src/nine.zig) maps an error to an errno by its
+ // words, and EIO when none of them match: these words must not.
+ const addressing = @import("addr.zig");
+ const einval = [_][]const u8{ "control message", "invalid", "bad " };
+ const other = [_][]const u8{ "interrupt", "shut down", "not exist", "not found", "no such", "exists", "not empty", "not a dir", "is a dir", "permission", "denied", "read-only", "read only", "no space", "not allowed", "not permitted", "cannot", "fid", "busy", "in use", "too long", "not supported", "unsupported" };
+ const Case = struct { text: []const u8, malformed: bool };
+ for ([_]Case{
+ .{ .text = addressing.e_syntax, .malformed = true },
+ .{ .text = addressing.e_regexp, .malformed = true },
+ .{ .text = e_prompt, .malformed = true },
+ .{ .text = addressing.e_no_match, .malformed = false },
+ .{ .text = addressing.e_range, .malformed = false },
+ .{ .text = addressing.e_order, .malformed = false },
+ .{ .text = addressing.e_slow, .malformed = false },
+ .{ .text = "/tmp/x.txt: Modified (Exit again to discard)", .malformed = false },
+ .{ .text = "Edit: w is a sam command pardes's Edit leaves out (it has no file or shell commands)", .malformed = false },
+ }) |c| {
+ const says_einval = for (einval) |w| {
+ if (std.ascii.findIgnoreCase(c.text, w) != null) break true;
+ } else false;
+ try testing.expectEqual(c.malformed, says_einval);
+ for (other) |w| try testing.expect(std.ascii.findIgnoreCase(c.text, w) == null);
+ }
+}
+
+test "DumpConfig's whole report writes back to the root ctl, line by line, with no error" {
+ const p = try withFile(testing.allocator, "x\n");
+ defer p.deinit();
+ const root_ctl = @backingInt(tree.TopFile.ctl);
+ try testing.expectEqual(Status.ok, wr(p, root_ctl, "DumpConfig\n").reply.status);
+ const report = for (p.panes) |slot| {
+ const pane = slot orelse continue;
+ const f = pane.file orelse continue;
+ const o = f.output orelse continue;
+ if (std.meta.eql(o.from, panes.Output.Origin{ .cmd = .DumpConfig })) break try testing.allocator.dupe(u8, f.content);
+ } else return error.NoDumpConfigPane;
+ defer testing.allocator.free(report);
+ // What this shell cannot show is a comment, never a value it refuses.
+ if (pardes.platform == .tui) try testing.expect(std.mem.indexOf(u8, report, "# GripWidth unsupported\n") != null);
+ var lines = std.mem.splitScalar(u8, report, '\n');
+ while (lines.next()) |line| {
+ if (line.len == 0) continue;
+ const r = wr(p, root_ctl, line);
+ if (r.reply.status != .ok) std.debug.print("refused: {s}: {s}\n", .{ line, r.reply.ename });
+ try testing.expectEqual(Status.ok, r.reply.status);
+ }
+}
+
+test "a Restore asks again for the ThemeFile the dump names, as a /ctl write of it does" {
+ const gpa = testing.allocator;
+ const p = try withFile(gpa, "x\n");
+ defer p.deinit();
+ const good = "/tmp/pardes-restored-theme.zon";
+ _ = wr(p, @backingInt(tree.TopFile.ctl), "ThemeFile " ++ good ++ "\n");
+ var custom = pardes.themes[0];
+ custom.name = "restored";
+ var encoded: std.Io.Writer.Allocating = .init(gpa);
+ defer encoded.deinit();
+ try std.zon.stringify.serialize(custom, .{}, &encoded.writer);
+ try testing.expect(pardes.colors.loadThemeFile(p, p.theme_file_generation, encoded.written()));
+ try pardes.dump.dumpState(p);
+ const restored = try pardes.dump.restore(p, p.dump_out.?, "/tmp/pardes.dump.zon");
+ defer restored.deinit();
+ const asked = while (restored.nextEffect()) |effect| switch (effect) {
+ .theme_file => |t| if (t.on) break t,
+ else => {},
+ } else return error.NoThemeFileAsked;
+ try testing.expectEqualStrings(good, pardes.colors.themeFileRequest(restored, asked.generation).?.path);
+ // The file broken since, the load fails: the restored session still
+ // shows the theme the old one did, and names the file it loaded.
+ try testing.expectEqualStrings("restored", restored.theme().name);
+ pardes.colors.failThemeFile(restored, asked.generation, error.ParseZon);
+ try testing.expectEqualStrings("restored", restored.theme().name);
+ try testing.expectEqualStrings(good, restored.theme_file_path.get());
+}
+
+test "a ThemeFile that fails to load changes nothing: the root ctl still names the one loaded, or none" {
+ const gpa = testing.allocator;
+ const p = try withFile(gpa, "x\n");
+ defer p.deinit();
+ const root_ctl = @backingInt(tree.TopFile.ctl);
+ // None loaded: a failed one leaves Theme as it was.
+ _ = wr(p, root_ctl, "ThemeFile /tmp/pardes-no-such-theme.zon\n");
+ pardes.colors.failThemeFile(p, p.theme_file_generation, error.FileNotFound);
+ try testing.expect(std.mem.indexOf(u8, rd(p, root_ctl, 0, 1 << 16).bytes, "ThemeFile") == null);
+ try testing.expectEqualStrings("", p.theme_file_path.get());
+ // One loaded, then another that fails: still the first, on every read.
+ const good = "/tmp/pardes-good-theme.zon";
+ _ = wr(p, root_ctl, "ThemeFile " ++ good ++ "\n");
+ var custom = pardes.themes[0];
+ custom.name = "good";
+ var encoded: std.Io.Writer.Allocating = .init(gpa);
+ defer encoded.deinit();
+ try std.zon.stringify.serialize(custom, .{}, &encoded.writer);
+ try testing.expect(pardes.colors.loadThemeFile(p, p.theme_file_generation, encoded.written()));
+ _ = wr(p, root_ctl, "ThemeFile /tmp/pardes-bad-theme.zon\n");
+ try testing.expect(!pardes.colors.loadThemeFile(p, p.theme_file_generation, ".{ .name = "));
+ try testing.expect(std.mem.indexOf(u8, rd(p, root_ctl, 0, 1 << 16).bytes, "ThemeFile " ++ good ++ "\n") != null);
+ try testing.expectEqualStrings(good, p.theme_file_path.get());
+}
+
+test "after a ThemeFile the root ctl and DumpConfig say ThemeFile and its path, which writes back" {
+ const gpa = testing.allocator;
+ const p = try withFile(gpa, "x\n");
+ defer p.deinit();
+ const root_ctl = @backingInt(tree.TopFile.ctl);
+ const path = "/tmp/pardes-mine-theme.zon";
+ try testing.expectEqual(Status.ok, wr(p, root_ctl, "ThemeFile " ++ path ++ "\n").reply.status);
+ var custom = pardes.themes[0];
+ custom.name = "mine";
+ var encoded: std.Io.Writer.Allocating = .init(gpa);
+ defer encoded.deinit();
+ try std.zon.stringify.serialize(custom, .{}, &encoded.writer);
+ try testing.expect(pardes.colors.loadThemeFile(p, p.theme_file_generation, encoded.written()));
+ const settings = rd(p, root_ctl, 0, 1 << 16).bytes;
+ try testing.expect(std.mem.indexOf(u8, settings, "ThemeFile " ++ path ++ "\n") != null);
+ try testing.expect(std.mem.indexOf(u8, settings, "Theme mine") == null);
+ var storage: [16384]u8 = undefined;
+ var out: std.Io.Writer = .fixed(&storage);
+ try config.Runtime.writeReport(&out, .{
+ .startup_config_path = null,
+ .platform = @tagName(pardes.platform),
+ .theme_name = p.theme().name,
+ .theme_file = pardes.colors.loadedThemeFile(p),
+ .compiled_default_shell = config.defaultShell(),
+ .hover_delay_frames = config.look_preview_delay_frames,
+ .native_images = false,
+ .capabilities = builtins.capabilities,
+ .state = &p.settings,
+ });
+ try testing.expect(std.mem.indexOf(u8, out.buffered(), "ThemeFile " ++ path ++ "\n") != null);
+ // Written back, it is the same request again, not "no theme mine".
+ try testing.expectEqual(Status.ok, wr(p, root_ctl, "ThemeFile " ++ path ++ "\n").reply.status);
+}
+
+test "themesNear finds a misspelling's like far from any first letter, and every theme sharing the first letter when they fit" {
+ // Joincol and Theme's refusals are test/behaviour/root_ctl.zig's.
+ var near: [170]u8 = undefined;
+ try testing.expect(std.mem.indexOf(u8, pardes.colors.themesNear(&near, "9dracula"), "dracula") != null);
+ var tested = false;
+ for ("abcdefghijklmnopqrstuvwxyz") |letter| {
+ var count: usize = 0;
+ var len: usize = 0;
+ for (pardes.themes) |t| if (t.name[0] == letter) {
+ count += 1;
+ len += t.name.len + 1;
+ };
+ if (count < 2 or len > near.len) continue;
+ try testing.expectEqual(count, std.mem.count(u8, pardes.colors.themesNear(&near, &.{letter}), " ") + 1);
+ tested = true;
+ }
+ try testing.expect(tested);
+}
+
+
+test "a look whose pane is refused a place fails with that alone, not a missing line too" {
+ const gpa = testing.allocator;
+ // A screen with rows for one pane only.
+ const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 5 });
+ defer p.deinit();
+ while (p.nextEffect()) |_| {}
+ _ = try p.setTestFile("x\n");
+ while (p.nextEffect()) |_| {}
+ var tmp = testing.tmpDir(.{});
+ defer tmp.cleanup();
+ try tmp.dir.writeFile(testing.io, .{ .sub_path = "f.txt", .data = "one\ntwo\n" });
+ var dir: [4096]u8 = undefined;
+ const at = dir[0..try tmp.dir.realPath(testing.io, &dir)];
+ var line: [4200]u8 = undefined;
+ const r = wr(p, root_look, try std.fmt.bufPrint(&line, "{s}/f.txt:2\n", .{at}));
+ try testing.expectEqual(Status.err, r.reply.status);
+ try testing.expect(std.mem.indexOf(u8, r.reply.ename, "no space for a pane") != null);
+ try testing.expectEqual(@as(usize, 1), th.logCount(p, "\nerr "));
+}
+
+test "a Restore of a file that is no dump fails the write before any warning, and a failed Dump fails its write" {
+ const p = try withFile(testing.allocator, "x\n");
+ defer p.deinit();
+ const f = pane_files.fileOf(p.panes[0].?).?;
+ f.content = try p.gpa.realloc(f.content, 3);
+ @memcpy(f.content, "yy\n");
+ f.revision +%= 1; // unsaved: a Restore would warn about it first
+ var tmp = testing.tmpDir(.{});
+ defer tmp.cleanup();
+ try tmp.dir.writeFile(testing.io, .{ .sub_path = "notes.txt", .data = "just notes\n" });
+ var dir_buf: [4096]u8 = undefined;
+ const dir = dir_buf[0..try tmp.dir.realPath(testing.io, &dir_buf)];
+ var line_buf: [4200]u8 = undefined;
+ const line = try std.fmt.bufPrint(&line_buf, "Restore {s}/notes.txt\n", .{dir});
+ const root_ctl = @backingInt(tree.TopFile.ctl);
+ const refused = wr(p, root_ctl, line);
+ try testing.expectEqual(E.IO, refused.errno());
+ try testing.expect(std.mem.indexOf(u8, refused.reply.ename, "not a pardes dump: it does not begin as one") != null);
+ try testing.expect(p.restore_req == null);
+ try testing.expect(p.panes[0].?.discard_warned == null);
+
+ p.fs.late_failure_len = 0;
+ // (Under /tmp: under / a user's Dump is refused permission, not missing.)
+ p.dumpFailed("/tmp/pardes-nowhere-zz/pardes.dump.zon", error.FileNotFound);
+ try testing.expectEqualStrings("Dump /tmp/pardes-nowhere-zz/pardes.dump.zon: no such directory", p.fs.late_failure[0..p.fs.late_failure_len]);
+ // A DumpDir that is there but no directory says that.
+ p.fs.late_failure_len = 0;
+ p.dumpFailed("/dev/null/pardes.dump.zon", error.NotDir);
+ try testing.expectEqualStrings("Dump /dev/null/pardes.dump.zon: /dev/null is not a directory", p.fs.late_failure[0..p.fs.late_failure_len]);
+}
+
+
+test "Mount dials its peer and fails, mounting nothing, when none answers; a look through a peer gone says dial failed" {
+ const p = try withFile(testing.allocator, "x\n");
+ defer p.deinit();
+ const root_ctl = @backingInt(tree.TopFile.ctl);
+ const dead = "/tmp/pardes-test-no-such-peer.sock";
+ // A socket path not there is said so; one there that does not answer
+ // (a directory here) is a dial that failed.
+ const missing = wr(p, root_ctl, "Mount dead " ++ dead ++ "\n");
+ try testing.expectEqual(E.NOENT, missing.errno());
+ try testing.expectEqualStrings("Mount dead: " ++ dead ++ ": no such socket", missing.reply.ename);
+ const refused = wr(p, root_ctl, "Mount dead /tmp\n");
+ try testing.expectEqual(E.IO, refused.errno());
+ try testing.expectEqualStrings("Mount dead /tmp: dial failed: no answer", refused.reply.ename);
+ try testing.expectEqual(@as(usize, 0), p.fs.mounts.items.len);
+ // A pane of a peer gone since: get says so too.
+ try p.fs.mounts.append(p.gpa, .{ .name = try p.gpa.dupe(u8, "away"), .dial = try p.gpa.dupe(u8, dead) });
+ _ = wr(p, Node.of(serialOf(p), .name), "/n/away/f.txt\n");
+ const got = wr(p, Node.of(serialOf(p), .ctl), "get\n");
+ try testing.expectEqualStrings("get: /n/away/f.txt: dial failed: no answer", got.reply.ename);
+ // Mounted when it answered, gone since: a look through it says so.
+ try p.fs.mounts.append(p.gpa, .{ .name = try p.gpa.dupe(u8, "gone"), .dial = try p.gpa.dupe(u8, dead) });
+ const looked = wr(p, @backingInt(tree.TopFile.look), "/n/gone/f.txt\n");
+ try testing.expect(looked.errno() != 0);
+ try testing.expect(th.logHas(p, "look: /n/gone/f.txt: dial failed: no answer"));
+}
+
+test "Term in a directory that is not there fails and makes no pane; a shell that never started answers a run" {
+ if (pardes.Term.ops == null) return error.SkipZigTest; // a shell
+ const p = try withFile(testing.allocator, "x\n");
+ defer p.deinit();
+ const serial = serialOf(p);
+ _ = wr(p, Node.of(serial, .name), "/tmp/pardes-no-such-dir-zz/f.txt\n");
+ // A host that starts shells (the core alone starts none, and asks
+ // nothing of a directory).
+ p.host = .{ .vtable = &th.starting };
+ defer p.host = .{};
+ var count: usize = 0;
+ for (p.panes) |slot| count += @intFromBool(slot != null);
+ const refused = wr(p, Node.of(serial, .ctl), "Term\n");
+ try testing.expectEqual(E.NOENT, refused.errno());
+ try testing.expectStringStartsWith(refused.reply.ename, "Term: /tmp/pardes-no-such-dir-zz: no such directory");
+ var after: usize = 0;
+ for (p.panes) |slot| after += @intFromBool(slot != null);
+ try testing.expectEqual(count, after);
+ // A terminal whose shell the host could not start.
+ _ = wr(p, Node.of(serial, .name), "/tmp/f.txt\n");
+ try testing.expectEqual(Status.ok, wr(p, Node.of(serial, .ctl), "Term\n").reply.status);
+ const term = p.view().active;
+ p.shellFailed(@intCast(term), error.FileNotFound);
+ const run_node = Node.of(p.panes[term].?.serial, .pty_run);
+ const h = call(p, .{ .tag = 1, .op = .open, .node = run_node, .omode = 2 }).reply.handle;
+ _ = call(p, .{ .tag = 2, .op = .write, .node = run_node, .handle = h, .data = "true\n" });
+ try testing.expectEqualStrings("error shell gone\n", call(p, .{ .tag = 3, .op = .read, .node = run_node, .handle = h, .size = 64 }).bytes);
+}
+
+test "a script's Grep and Find fill the pane's one query pane, a row a line under its file; a miss says not found and opens nothing" {
+ const p = try withFile(testing.allocator, "x\n");
+ defer p.deinit();
+ var tmp = testing.tmpDir(.{});
+ defer tmp.cleanup();
+ try tmp.dir.writeFile(testing.io, .{ .sub_path = "a.txt", .data = "alpha\n" });
+ try tmp.dir.writeFile(testing.io, .{ .sub_path = "other.txt", .data = "one\nbravo here\nthree bravo\n" });
+ var dir_buf: [4096]u8 = undefined;
+ const dir = dir_buf[0..try tmp.dir.realPath(testing.io, &dir_buf)];
+ var line: [4200]u8 = undefined;
+ _ = wr(p, Node.of(serialOf(p), .name), try std.fmt.bufPrint(&line, "{s}/a.txt\n", .{dir}));
+ // A hit fills the pane's query pane, line 1 the command, its rows under
+ // the file they are in: exec reads it back. Find and Grep share it, the
+ // pane's one query pane, each run replacing it.
+ try testing.expectEqual(Status.ok, wr(p, Node.of(serialOf(p), .exec), "Grep bravo\n").reply.status);
+ const grepped = p.panes[p.paneBySerial(try std.fmt.parseInt(u32, std.mem.trimEnd(u8, rd(p, root_exec, 0, 64).bytes, "\n"), 10)).?].?;
+ const rows = grepped.file.?.content;
+ try testing.expect(std.mem.startsWith(u8, rows, "Grep bravo\n"));
+ try testing.expect(std.mem.indexOf(u8, rows, "\nother.txt\n") != null);
+ // each row its place as text, `path:line:col`, the code in one column
+ try testing.expect(std.mem.indexOf(u8, rows, "\nother.txt:2:1 bravo here\n") != null);
+ try testing.expect(std.mem.indexOf(u8, rows, "\nother.txt:3:7 three bravo\n") != null);
+ try testing.expectEqual(@as(usize, 2), grepped.query.?.total);
+ try testing.expectEqual(Status.ok, wr(p, Node.of(serialOf(p), .exec), "Find other\n").reply.status);
+ const found = p.panes[p.paneBySerial(try std.fmt.parseInt(u32, std.mem.trimEnd(u8, rd(p, root_exec, 0, 64).bytes, "\n"), 10)).?].?;
+ try testing.expectEqual(grepped.serial, found.serial);
+ try testing.expect(std.mem.indexOf(u8, found.file.?.content, "\nother.txt\n") != null);
+ try testing.expect(std.mem.indexOf(u8, found.file.?.content, "bravo here") == null);
+ // The same Find again reads back the query pane, not the pane it ran in.
+ try testing.expectEqual(Status.ok, wr(p, Node.of(serialOf(p), .exec), "Find other\n").reply.status);
+ try testing.expectEqualStrings(try std.fmt.bufPrint(&line, "{d}\n", .{found.serial}), rd(p, root_exec, 0, 64).bytes);
+ // A Grep run from the query pane itself fills that one, never a second.
+ try testing.expectEqual(Status.ok, wr(p, Node.of(found.serial, .exec), "Grep bravo\n").reply.status);
+ try testing.expectEqualStrings(try std.fmt.bufPrint(&line, "{d}\n", .{found.serial}), rd(p, root_exec, 0, 64).bytes);
+ var searches: usize = 0;
+ for (p.panes) |slot| if (slot) |q| if (q.file) |f| if (f.output != null) {
+ searches += @intFromBool(std.mem.endsWith(u8, f.path, "/+Search"));
+ };
+ try testing.expectEqual(@as(usize, 1), searches);
+ try testing.expect(std.mem.indexOf(u8, found.file.?.content, "bravo here") != null);
+ var count: usize = 0;
+ for (p.panes) |slot| count += @intFromBool(slot != null);
+ // A miss: said to the script, the query pane's count 0, nothing opened.
+ const missed = wr(p, Node.of(serialOf(p), .exec), "Grep zzqqnomatchzz\n");
+ try testing.expectEqual(E.NOENT, missed.errno());
+ try testing.expectEqualStrings("Grep: text not found", missed.reply.ename);
+ try testing.expectEqual(@as(usize, 0), found.query.?.total);
+ const unfound = wr(p, Node.of(serialOf(p), .exec), "Find zzqqnomatchzz\n");
+ try testing.expectEqual(E.NOENT, unfound.errno());
+ try testing.expectEqualStrings("Find: name not found", unfound.reply.ename);
+ var after: usize = 0;
+ for (p.panes) |slot| after += @intFromBool(slot != null);
+ try testing.expectEqual(count, after);
+ // With no query pane under it, a miss leaves none: the one it made goes.
+ _ = wr(p, Node.of(found.serial, .ctl), "Del\n");
+ var closed: usize = 0;
+ for (p.panes) |slot| closed += @intFromBool(slot != null);
+ try testing.expectEqual(E.NOENT, wr(p, Node.of(serialOf(p), .exec), "Find zzqqnomatchzz\n").errno());
+ var left: usize = 0;
+ for (p.panes) |slot| left += @intFromBool(slot != null);
+ try testing.expectEqual(closed, left);
+ try testing.expect(panes.Query.ofOwner(p, serialOf(p)) == null);
+}
+
+test "a terminal told the directory it already goes by logs no rename" {
+ if (pardes.Term.ops == null) return error.SkipZigTest; // a shell
+ const p = try withFile(testing.allocator, "x\n");
+ defer p.deinit();
+ _ = wr(p, Node.of(serialOf(p), .name), "/tmp/f.txt\n");
+ try testing.expectEqual(Status.ok, wr(p, Node.of(serialOf(p), .ctl), "Term\n").reply.status);
+ p.update(.tick); // announced
+ const term = p.view().active;
+ // The host says where its shell started: where it was already named.
+ p.setCwd(term, "/tmp");
+ var rec: [32]u8 = undefined;
+ try testing.expect(!th.logHas(p, try std.fmt.bufPrint(&rec, "rename {d} ", .{p.panes[term].?.serial})));
+ // This process's directory, asked before the shell has said anything
+ // (so before its chdir): not taken.
+ const session = p.sessionDir();
+ p.setCwd(term, session);
+ try testing.expect(!th.logHas(p, try std.fmt.bufPrint(&rec, "rename {d} ", .{p.panes[term].?.serial})));
+ p.update(.{ .output = .{ .pane = @intCast(term), .bytes = "$ " } });
+ // Somewhere else is a rename.
+ p.setCwd(term, "/usr");
+ try testing.expect(th.logHas(p, try std.fmt.bufPrint(&rec, "rename {d} /usr", .{p.panes[term].?.serial})));
+}
+
+test "a terminal with text typed at its prompt is never typed into: a look at its directory or an exec at it opens a pane of its own" {
+ const p = try th.withTerm(testing.allocator);
+ defer p.deinit();
+ const term = p.paneBySerial(serialOf(p)).?;
+ p.setCwd(term, "/tmp");
+ p.update(.{ .output = .{ .pane = @intCast(term), .bytes = "\x1b]133;A;aid=pardes\x07$ \x1b]133;B;aid=pardes\x07TYPED" } });
+ while (p.nextEffect()) |_| {}
+ var count: usize = 0;
+ for (p.panes) |slot| count += @intFromBool(slot != null);
+ try testing.expectEqual(Status.ok, wr(p, @backingInt(tree.TopFile.look), "/tmp\n").reply.status);
+ var typed_into = false;
+ while (p.nextEffect()) |effect| if (effect == .write and effect.write.pane == term) {
+ typed_into = true;
+ };
+ try testing.expect(!typed_into);
+ var after: usize = 0;
+ for (p.panes) |slot| after += @intFromBool(slot != null);
+ try testing.expectEqual(count + 1, after);
+ // An exec at it runs in a pane of its own, not typed after TYPED.
+ _ = wr(p, Node.of(serialOf(p), .exec), "echo hi\n");
+ while (p.nextEffect()) |effect| if (effect == .write and effect.write.pane == term) {
+ typed_into = true;
+ };
+ try testing.expect(!typed_into);
+}
+
+test "a command line from a missing directory fails ENOENT and makes no pane; a command whose shell never started ends 127" {
+ if (pardes.Term.ops == null) return error.SkipZigTest; // a command pane
+ const p = try withFile(testing.allocator, "x\n");
+ defer p.deinit();
+ p.host = .{ .vtable = &th.starting };
+ defer p.host = .{};
+ const serial = serialOf(p);
+ _ = wr(p, Node.of(serial, .name), "/tmp/pardes-no-such-dir-zz/f.txt\n");
+ var count: usize = 0;
+ for (p.panes) |slot| count += @intFromBool(slot != null);
+ const refused = wr(p, Node.of(serial, .exec), "echo hi\n");
+ try testing.expectEqual(E.NOENT, refused.errno());
+ try testing.expectStringStartsWith(refused.reply.ename, "exec: /tmp/pardes-no-such-dir-zz: no such directory");
+ var after: usize = 0;
+ for (p.panes) |slot| after += @intFromBool(slot != null);
+ try testing.expectEqual(count, after);
+ // A command pane whose shell the host could not start.
+ _ = wr(p, Node.of(serial, .name), "/tmp/f.txt\n");
+ try testing.expectEqual(Status.ok, wr(p, Node.of(serial, .exec), "echo hi\n").reply.status);
+ const cmd = p.paneBySerial(try std.fmt.parseInt(u32, std.mem.trimEnd(u8, rd(p, Node.of(serial, .exec), 0, 64).bytes, "\n"), 10)).?;
+ p.shellFailed(@intCast(cmd), error.FileNotFound);
+ const pane = p.panes[cmd].?;
+ try testing.expect(pane.command_done);
+ try testing.expectEqual(@as(?u8, 127), pane.command_status);
+ var rec: [32]u8 = undefined;
+ try testing.expect(th.logHas(p, try std.fmt.bufPrint(&rec, "exit {d} 127\n", .{pane.serial})));
+ try testing.expect(th.logHas(p, "shell: directory missing"));
+}
+
+test "pty/ctl exec in a directory that is gone fails ENOENT; a shell that cannot start fails the write" {
+ const p = try th.withTerm(testing.allocator);
+ defer p.deinit();
+ p.host = .{ .vtable = &th.starting };
+ defer p.host = .{};
+ const serial = serialOf(p);
+ p.setCwd(p.paneBySerial(serial).?, "/tmp/pardes-no-such-dir-zz");
+ const refused = wr(p, Node.of(serial, .pty_ctl), "exec\n");
+ try testing.expectEqual(E.NOENT, refused.errno());
+ try testing.expectStringStartsWith(refused.reply.ename, "exec: /tmp/pardes-no-such-dir-zz: no such directory");
+ // The host's own failure is the waiting write's (late_failure).
+ p.fs.late_failure_len = 0;
+ p.shellFailed(@intCast(p.paneBySerial(serial).?), error.AccessDenied);
+ try testing.expectEqualStrings("shell: permission denied", p.fs.late_failure[0..p.fs.late_failure_len]);
+}
+
+test "a script whose interpreter is not there: Term refuses it up front, only an err logged, and pty/ctl exec keeps the running shell" {
+ const p = try th.withTerm(testing.allocator);
+ defer p.deinit();
+ p.host = .{ .vtable = &th.starting };
+ defer p.host = .{};
+ var tmp = testing.tmpDir(.{});
+ defer tmp.cleanup();
+ try tmp.dir.writeFile(testing.io, .{ .sub_path = "bad", .data = "#!/no/such/interp\n", .flags = .{ .permissions = .executable_file } });
+ var dir_buf: [4096]u8 = undefined;
+ const dir = dir_buf[0..try tmp.dir.realPath(testing.io, &dir_buf)];
+ var line: [4200]u8 = undefined;
+ const serial = serialOf(p);
+ var count: usize = 0;
+ for (p.panes) |slot| count += @intFromBool(slot != null);
+ const refused = wr(p, Node.of(serial, .ctl), try std.fmt.bufPrint(&line, "Term {s}/bad\n", .{dir}));
+ try testing.expectEqual(E.NOENT, refused.errno());
+ try testing.expectEqualStrings("Term: interpreter /no/such/interp not found", refused.reply.ename);
+ var after: usize = 0;
+ for (p.panes) |slot| after += @intFromBool(slot != null);
+ try testing.expectEqual(count, after);
+ // The log gained the err and nothing else: no new, msg or del.
+ try testing.expect(th.logHas(p, "Term: interpreter /no/such/interp not found\n"));
+ try testing.expect(!th.logHas(p, "\nmsg "));
+ try testing.expect(!th.logHas(p, "\ndel "));
+ // The shell to start again is that script: refused before the running
+ // one goes.
+ const id = p.paneBySerial(serial).?;
+ p.panes[id].?.shell = try p.gpa.dupe(u8, try std.fmt.bufPrint(&line, "{s}/bad", .{dir}));
+ p.setCwd(id, dir);
+ const exec_refused = wr(p, Node.of(serial, .pty_ctl), "exec\n");
+ try testing.expectEqual(E.NOENT, exec_refused.errno());
+ try testing.expectEqualStrings("exec: interpreter /no/such/interp not found", exec_refused.reply.ename);
+ // One the host found could not start (the script changed after): said
+ // with the interpreter's name, and the running shell is not gone.
+ p.fs.late_failure_len = 0;
+ p.restartFailed(@intCast(id), error.InterpreterNotFound);
+ try testing.expectEqualStrings("shell: interpreter /no/such/interp not found", p.fs.late_failure[0..p.fs.late_failure_len]);
+ try testing.expect(!p.panes[id].?.shell_failed);
+}
+
+test "a language server question that finds nothing, cannot be answered, or is asked of no file fails, and a write to an image's body is refused" {
+ const p = try withFile(testing.allocator, "x\n");
+ defer p.deinit();
+ const id = p.view().active;
+ // Asked of a pane that is no file's: at once.
+ _ = wr(p, root_exec, "Recent\n");
+ const listed = p.paneBySerial(try std.fmt.parseInt(u32, std.mem.trimEnd(u8, rd(p, root_exec, 0, 64).bytes, "\n"), 10)).?;
+ p.lspRequest(listed, .incoming_calls, "");
+ try testing.expect(std.mem.indexOf(u8, p.panes[listed].?.msg[0..p.panes[listed].?.msg_len], "Callers: only a file's pane asks") != null);
+ // Nothing found: Callers says so, and the waiting write hears it.
+ p.fs.late_failure_len = 0;
+ p.lspRequest(id, .incoming_calls, "");
+ try testing.expect(p.lsp_ask.wait != null);
+ Ask.lspResponse(p, p.lsp_ask.wait.?.id, "");
+ try testing.expectEqualStrings("Callers: callers not found", p.fs.late_failure[0..p.fs.late_failure_len]);
+ // A backend that cannot answer says why.
+ p.fs.late_failure_len = 0;
+ p.lspRequest(id, .outgoing_calls, "");
+ Ask.lspResponse(p, p.lsp_ask.wait.?.id, "@none zls does not answer call hierarchy\n");
+ try testing.expectEqualStrings("Callees: zls does not answer call hierarchy", p.fs.late_failure[0..p.fs.late_failure_len]);
+ // No answer at all.
+ p.fs.late_failure_len = 0;
+ p.lspRequest(id, .hover, "");
+ Ask.lspResponse(p, p.lsp_ask.wait.?.id, null);
+ try testing.expectEqualStrings("Hover: the language server did not answer", p.fs.late_failure[0..p.fs.late_failure_len]);
+ // No diagnostics is no failure.
+ p.fs.late_failure_len = 0;
+ p.lspRequest(id, .diagnostics, "");
+ Ask.lspResponse(p, p.lsp_ask.wait.?.id, "");
+ try testing.expectEqual(@as(u16, 0), p.fs.late_failure_len);
+ // An image's body takes no write.
+ const slot = p.freeSlot().?;
+ const img = try pardes.Kind.open(p, slot, pardes.Kind.test_kind.of(p), "/tmp/pardes-no-such.png", "not a png");
+ try testing.expectEqual(E.INVAL, wr(p, Node.of(img.serial, .body), "text\n").errno());
+}
+
+test "workspace symbols, Symbols and Diagnostics share their directory's one +Search" {
+ const p = try withFile(testing.allocator, "x\n");
+ defer p.deinit();
+ const id = p.view().active;
+ const Output = pardes.panes.Output;
+ try Output.fillResults(p, id, "/tmp", .{ .query = .workspace_symbols }, "x", try p.gpa.dupe(u8, "a.txt:1:1 x\n"), null);
+ try Output.fillResults(p, id, "/tmp", .{ .query = .document_symbols }, "", try p.gpa.dupe(u8, "a.txt:2:1 fn f\n"), null);
+ try Output.fillResults(p, id, "/tmp", .{ .query = .diagnostics }, "", try p.gpa.dupe(u8, "a.txt:3:1 error\n"), null);
+ var searches: usize = 0;
+ for (p.panes) |slot| if (slot) |q| if (q.file) |f| if (f.output != null) {
+ searches += @intFromBool(std.mem.eql(u8, f.path, "/tmp/+Search"));
+ };
+ try testing.expectEqual(@as(usize, 1), searches);
+}
+
+test "a buffer whose file was deleted on disk is dirty, and Del asks first" {
+ const p = try withFile(testing.allocator, "x\n");
+ defer p.deinit();
+ const serial = serialOf(p);
+ try testing.expectEqualStrings("0", std.mem.trimEnd(u8, rd(p, Node.of(serial, .dirty), 0, 8).bytes, "\n"));
+ pardes.panes.File.deleted(p, @intCast(p.paneBySerial(serial).?));
+ try testing.expectEqualStrings("1", std.mem.trimEnd(u8, rd(p, Node.of(serial, .dirty), 0, 8).bytes, "\n"));
+ try testing.expectEqual(Status.err, wr(p, Node.of(serial, .ctl), "Del\n").reply.status);
+ try testing.expect(p.paneBySerial(serial) != null);
+ _ = wr(p, Node.of(serial, .ctl), "Del\n");
+ p.sync();
+ try testing.expect(p.paneBySerial(serial) == null);
+}
+
+test "a failure said while a 9P write waits on it posts no msg, only the write's err" {
+ const p = try withFile(testing.allocator, "x\n");
+ defer p.deinit();
+ p.fs.write_waits = true;
+ p.saveFailed(@intCast(p.view().active), "/nowhere/zz.txt", error.FileNotFound);
+ p.fs.write_waits = false;
+ try testing.expect(!th.logHas(p, "msg "));
+ try testing.expect(p.fs.late_failure_len > 0);
+}
+
+test "with no pane at all, the root look opens its file and the root exec runs in the session's directory" {
+ if (pardes.Term.ops == null) return error.SkipZigTest; // a command pane
+ const p = try withFile(testing.allocator, "x\n");
+ defer p.deinit();
+ var tmp = testing.tmpDir(.{});
+ defer tmp.cleanup();
+ try tmp.dir.writeFile(testing.io, .{ .sub_path = "f.txt", .data = "file\n" });
+ var buf: [4096]u8 = undefined;
+ const session = buf[0..try tmp.dir.realPath(testing.io, &buf)];
+ @memcpy(p.session_dir[0..session.len], session);
+ p.session_dir_len = @intCast(session.len);
+ const Empty = struct {
+ fn all(q: *Pardes) !void {
+ while (panes.anyPane(q)) |k| _ = wr(q, Node.of(q.panes[k].?.serial, .ctl), "delete\n");
+ }
+ };
+ try Empty.all(p);
+ const look_node = @backingInt(tree.TopFile.look);
+ try testing.expectEqual(Status.ok, wr(p, look_node, "f.txt\n").reply.status);
+ var want: [4200]u8 = undefined;
+ const path = try std.fmt.bufPrint(&want, "{s}/f.txt", .{session});
+ var opened: usize = 0;
+ var scratches: usize = 0;
+ for (p.panes) |slot| {
+ const f = (slot orelse continue).file orelse continue;
+ opened += @intFromBool(std.mem.eql(u8, f.path, path));
+ scratches += @intFromBool(std.mem.endsWith(u8, f.path, "/+New"));
+ }
+ try testing.expectEqual(@as(usize, 1), opened);
+ try testing.expectEqual(@as(usize, 0), scratches);
+
+ try Empty.all(p);
+ try testing.expectEqual(Status.ok, wr(p, @backingInt(tree.TopFile.exec), "echo hi\n").reply.status);
+ const made = p.panes[panes.anyPane(p).?].?;
+ try testing.expect(made.command != null);
+ try testing.expectEqualStrings(session, made.cwdSlice());
+}
+
+test "a restored pane whose file is gone from disk comes back dirty, and Del asks first" {
+ const p = try withFile(testing.allocator, "kept text\n");
+ defer p.deinit();
+ // On disk when dumped, gone by the Restore.
+ var tmp = testing.tmpDir(.{});
+ defer tmp.cleanup();
+ try tmp.dir.writeFile(testing.io, .{ .sub_path = "f.txt", .data = "kept text\n" });
+ var dir_buf: [4096]u8 = undefined;
+ const dir = dir_buf[0..try tmp.dir.realPath(testing.io, &dir_buf)];
+ var path_buf: [4200]u8 = undefined;
+ try pane_files.nameBuffer(p, 0, try std.fmt.bufPrint(&path_buf, "{s}/f.txt", .{dir}), false);
+ try pardes.dump.dumpState(p);
+ try tmp.dir.deleteFile(testing.io, "f.txt");
+ const restored = try pardes.dump.restore(p, p.dump_out.?, "/tmp/pardes.dump.zon");
+ defer restored.deinit();
+ const again = restored.panes[restored.paneBySerial(restored.panes[0].?.serial).?].?;
+ try testing.expect(again.file.?.disk_gone);
+ const r = wr(restored, Node.of(again.serial, .ctl), "Del\n");
+ try testing.expectEqual(Status.err, r.reply.status);
+ try testing.expect(std.mem.indexOf(u8, r.reply.ename, "Modified") != null);
+}
+
+
+test "a focus moved over 9P tells the programs that asked for focus reports, as a click does" {
+ if (pardes.Term.ops == null) return error.SkipZigTest; // a shell
+ const p = try Pardes.init(testing.allocator, .{ .cols = 90, .rows = 30, .shells = 2 });
+ defer p.deinit();
+ while (p.nextEffect()) |_| {}
+ const first = for (p.panes) |slot| {
+ if (slot) |pane| if (pane.isTerminal()) break pane.serial;
+ } else return error.NoShell;
+ try testing.expectEqual(Status.ok, wr(p, Node.of(first, .exec), "Term\n").reply.status);
+ var shells: [2]usize = undefined;
+ var n: usize = 0;
+ for (p.panes, 0..) |slot, id| if (slot) |pane| if (pane.isTerminal() and n < 2) {
+ shells[n] = id;
+ n += 1;
+ };
+ try testing.expectEqual(@as(usize, 2), n);
+ p.view().active = shells[0];
+ p.update(.{ .output = .{ .pane = @intCast(shells[0]), .bytes = "\x1b[?1004h" } });
+ p.update(.{ .output = .{ .pane = @intCast(shells[1]), .bytes = "\x1b[?1004h" } });
+ while (p.nextEffect()) |_| {}
+ var digits: [16]u8 = undefined;
+ const moved = wr(p, @backingInt(tree.TopFile.focus), try std.fmt.bufPrint(&digits, "{d}\n", .{p.panes[shells[1]].?.serial}));
+ try testing.expectEqual(Status.ok, moved.reply.status);
+ try testing.expectEqual(shells[1], p.view().active);
+ try testing.expectEqualStrings("\x1b[O\x1b[I", moved.pty_buf[0..moved.pty_len]);
+}
+
+test "a Restore of a name in the DumpDir asks for, and logs, the whole path it reads" {
+ const p = try withFile(testing.allocator, "x\n");
+ defer p.deinit();
+ try pardes.dump.dumpState(p);
+ var tmp = testing.tmpDir(.{});
+ defer tmp.cleanup();
+ try tmp.dir.writeFile(testing.io, .{ .sub_path = "x.dump.zon", .data = p.dump_out.? });
+ var buf: [4096]u8 = undefined;
+ const dir = buf[0..try tmp.dir.realPath(testing.io, &buf)];
+ try testing.expect(p.settings.dump_dir.set(dir));
+ try testing.expectEqual(Status.ok, wr(p, @backingInt(tree.TopFile.ctl), "Restore x.dump.zon\n").reply.status);
+ var want: [4200]u8 = undefined;
+ try testing.expectEqualStrings(try std.fmt.bufPrint(&want, "{s}/x.dump.zon", .{dir}), p.restore_req.?);
+}
+
+
+test "a write to addr, limit or mark asks for no frame; one to body does" {
+ const p = try withFile(testing.allocator, "one\n");
+ defer p.deinit();
+ const serial = serialOf(p);
+ for ([_]tree.PaneFile{ .addr, .limit, .mark }) |file| {
+ p.needs_frame = false;
+ _ = p.serveFs(.{ .tag = 1, .op = .write, .node = Node.of(serial, file), .data = if (file == .mark) "1" else "#0" });
+ try testing.expect(!p.needs_frame);
+ }
+ p.needs_frame = false;
+ _ = p.serveFs(.{ .tag = 1, .op = .write, .node = Node.of(serial, .body), .data = "two\n" });
+ try testing.expect(p.needs_frame);
+}
+
+test "/index shows a name as the log does: a newline in it is \\n, a control byte, C1 or byte not UTF-8 \\xNN" {
+ const p = try th.withTerm(testing.allocator);
+ defer p.deinit();
+ const term = p.paneBySerial(serialOf(p)).?;
+ p.setCwd(term, "/tmp/two\nlines\x07\x7f\xc2\x85\xff");
+ const index = rd(p, @backingInt(tree.TopFile.index), 0, 4096).bytes;
+ // Each byte as itself, so the name decodes to what it is.
+ try testing.expect(std.mem.indexOf(u8, index, "/tmp/two\\nlines\\x07\\x7f\\xc2\\x85\\xff ") != null);
+ try testing.expectEqual(@as(usize, 1), std.mem.count(u8, index, "\n"));
+ try testing.expect(index.len > 0);
+ try testing.expectEqual(@as(u64, 0), call(p, .{ .tag = 1, .op = .getattr, .node = @backingInt(tree.TopFile.index) }).reply.attr.size);
+ // Its tag never carries the raw newline either.
+ const tag = rd(p, Node.of(serialOf(p), .tag), 0, 4096).bytes;
+ try testing.expect(std.mem.indexOf(u8, tag, "/tmp/two\\nlines") != null);
+ // A name's own backslash doubled is test/behaviour/other_files.zig's.
+}
+
+test "a column takes panes until their documented minimums fill it, not until none can be halved" {
+ const p = try Pardes.init(testing.allocator, .{ .tty_only = true, .cols = 160, .rows = 50 });
+ defer p.deinit();
+ while (p.nextEffect()) |_| {}
+ const new = @backingInt(tree.TopFile.new);
+ while (call(p, .{ .tag = 1, .op = .open, .node = new }).reply.status == .ok) p.sync();
+ p.sync();
+ const avail = p.view().screen_h - (p.topBarHeight() + layout.columnBarHeight(p));
+ for (0..p.view().ncol) |c| {
+ var need: u32 = 0;
+ for (p.view().cols[c].panes[0..p.view().cols[c].n]) |k| need += layout.minRows(p, k);
+ // Refused only when one more pane's tag and two rows would not fit.
+ if (p.view().cols[c].n > 1) try testing.expect(avail - need < 3);
+ // Every pane keeps its minimum.
+ for (p.view().cols[c].panes[0..p.view().cols[c].n]) |k| try testing.expect(p.view().rects[k].h >= layout.minRows(p, k));
+ }
+}
+
+test "a new file saved shows in /recent, open, while it is" {
+ const p = try withFile(testing.allocator, "x\n");
+ defer p.deinit();
+ var tmp = testing.tmpDir(.{});
+ defer tmp.cleanup();
+ var dir_buf: [4096]u8 = undefined;
+ const dir = dir_buf[0..try tmp.dir.realPath(testing.io, &dir_buf)];
+ // A host that writes files, as the real ones do.
+ const Writing = struct {
+ fn write(_: ?*anyopaque, _: u8, path: []const u8, bytes: []const u8) void {
+ std.Io.Dir.cwd().writeFile(testing.io, .{ .sub_path = path, .data = bytes }) catch {};
+ }
+ };
+ p.host = .{ .vtable = &.{ .write_file = Writing.write } };
+ defer p.host = .{};
+ const made = try th.newPane(p);
+ var line: [4200]u8 = undefined;
+ const path = try std.fmt.bufPrint(&line, "{s}/new.txt", .{dir});
+ var name: [4200]u8 = undefined;
+ _ = wr(p, Node.of(made, .name), try std.fmt.bufPrint(&name, "{s}\n", .{path}));
+ _ = wr(p, Node.of(made, .body), "fresh\n");
+ try testing.expectEqual(Status.ok, wr(p, Node.of(made, .ctl), "Save\n").reply.status);
+ p.perform(.{ .save_file = .{ .pane = @intCast(p.paneBySerial(made).?) } });
+ var want: [4300]u8 = undefined;
+ try testing.expect(std.mem.indexOf(u8, rd(p, @backingInt(tree.TopFile.recent), 0, 8192).bytes, try std.fmt.bufPrint(&want, "open {s}\n", .{path})) != null);
+}
+
+test "/recent shows a name as /index does, a newline in it escaped" {
+ const p = try withFile(testing.allocator, "x\n");
+ defer p.deinit();
+ // A backslash doubled is test/behaviour/other_files.zig's; a 9P name
+ // write cannot hold a newline.
+ p.recent.opened(p.recentGpa(), "/tmp/a\nb");
+ const text = rd(p, @backingInt(tree.TopFile.recent), 0, 8192).bytes;
+ try testing.expect(std.mem.indexOf(u8, text, "closed /tmp/a\\nb\n") != null);
+}
+
+test "size is monotonic: growing is never refused, and a size once taken is taken again" {
+ if (pardes.Term.ops == null) return error.SkipZigTest; // a shell
+ const p = try Pardes.init(testing.allocator, .{ .tty_only = true, .cols = 160, .rows = 60 });
+ defer p.deinit();
+ while (p.nextEffect()) |_| {}
+ p.unattended = true;
+ const root_ctl = @backingInt(tree.TopFile.ctl);
+ const new = @backingInt(tree.TopFile.new);
+ // The dogfood's repro: Newcol, three pane/new, a Term, then pane/new
+ // until a column has no room (ENOSPC).
+ try testing.expectEqual(Status.ok, wr(p, root_ctl, "Newcol\n").reply.status);
+ for (0..3) |_| try testing.expectEqual(Status.ok, call(p, .{ .tag = 1, .op = .open, .node = new }).reply.status);
+ try testing.expectEqual(Status.ok, wr(p, Node.of(p.panes[p.view().active].?.serial, .ctl), "Term\n").reply.status);
+ p.sync();
+ while (call(p, .{ .tag = 1, .op = .open, .node = new }).reply.status == .ok) p.sync();
+ p.sync();
+ var line: [32]u8 = undefined;
+ // Down a row at a time (59, 58, 57, 56 and on) until one is refused:
+ // once refused, every smaller one is too.
+ var taken: [60]bool = @splat(false);
+ var rows: u16 = 59;
+ var refused = false;
+ while (rows >= 20) : (rows -= 1) {
+ taken[rows] = wr(p, root_ctl, try std.fmt.bufPrint(&line, "size 160 {d}\n", .{rows})).reply.status == .ok;
+ if (refused) try testing.expect(!taken[rows]);
+ if (!taken[rows]) refused = true;
+ }
+ try testing.expect(refused); // the columns are full: some size is too small
+ // Back up: each size is taken again exactly when it was on the way down.
+ rows = 20;
+ while (rows <= 59) : (rows += 1) {
+ const ok = wr(p, root_ctl, try std.fmt.bufPrint(&line, "size 160 {d}\n", .{rows})).reply.status == .ok;
+ try testing.expectEqual(taken[rows], ok);
+ }
+ for ([_]u16{ 60, 61, 64, 70, 100 }) |grown| {
+ try testing.expectEqual(Status.ok, wr(p, root_ctl, try std.fmt.bufPrint(&line, "size 160 {d}\n", .{grown})).reply.status);
+ try testing.expectEqual(grown, p.view().screen_h);
+ }
+ // Out of range is EINVAL, in words 9ns reads as that.
+ const bad = wr(p, root_ctl, "size 5 2\n");
+ try testing.expectEqual(E.INVAL, bad.errno());
+ try testing.expectStringStartsWith(bad.reply.ename, "invalid size");
+}
+
+test "a 10k-line Edit text block is taken in linear time and memory" {
+ const gpa = testing.allocator;
+ const p = try withFile(gpa, "x\n");
+ defer p.deinit();
+ var block: std.ArrayList(u8) = .empty;
+ defer block.deinit(gpa);
+ try block.appendSlice(gpa, "Edit $a\n");
+ for (0..10_000) |i| try block.print(gpa, "line {d} of the block {{ with a brace }}\n", .{i});
+ try block.appendSlice(gpa, ".\n");
+ const started = std.Io.Clock.awake.now(std.testing.io);
+ try testing.expectEqual(Status.ok, wr(p, Node.of(serialOf(p), .ctl), block.items).reply.status);
+ const took = started.durationTo(std.Io.Clock.awake.now(std.testing.io)).toNanoseconds();
+ try testing.expect(took < std.time.ns_per_s);
+ try testing.expect(p.scratch.queryCapacity() < 50 * 1024 * 1024);
+ try testing.expectEqual(@as(usize, 10_001), std.mem.count(u8, p.panes[0].?.file.?.content, "\n"));
+}
+
+test "a file changed on disk under unsaved edits is not reloaded: it says so, get asks, Save warns once" {
+ const p = try withFile(testing.allocator, "one\n");
+ defer p.deinit();
+ const serial = serialOf(p);
+ const f = &p.panes[0].?.file.?;
+ // Clean, it takes the new text.
+ pardes.panes.File.changed(p, 0, "two\n");
+ try testing.expectEqualStrings("two\n", f.content);
+ var reloaded: [32]u8 = undefined;
+ try testing.expect(th.logHas(p, try std.fmt.bufPrint(&reloaded, "changed {d} reloaded\n", .{serial})));
+ // Edited, it keeps its text and stays dirty.
+ _ = wr(p, Node.of(serial, .body), "mine\n");
+ pardes.panes.File.changed(p, 0, "three\n");
+ try testing.expectEqualStrings("two\nmine\n", f.content);
+ try testing.expect(f.revision != f.saved_revision);
+ try testing.expect(th.logHas(p, "changed on disk (get reloads it, Save overwrites it)"));
+ var want: [32]u8 = undefined;
+ try testing.expect(th.logHas(p, try std.fmt.bufPrint(&want, "changed {d}\n", .{serial})));
+ // Exit and get still ask about the edits.
+ try testing.expectEqual(Status.err, wr(p, @backingInt(tree.TopFile.ctl), "Exit\n").reply.status);
+ try testing.expect(std.mem.indexOf(u8, wr(p, Node.of(serial, .ctl), "get\n").reply.ename, "Modified") != null);
+ // Save warns once before overwriting the newer file, then writes.
+ const first = wr(p, Node.of(serial, .ctl), "Save\n");
+ try testing.expectEqual(Status.err, first.reply.status);
+ try testing.expect(std.mem.indexOf(u8, first.reply.ename, "modified on disk since read") != null);
+ try testing.expect(wr(p, Node.of(serial, .ctl), "Save\n").saved);
+}
+
+test "every word's /commands description is its own doc comment's first sentence, no citation" {
+ const p = try withFile(testing.allocator, "x\n");
+ defer p.deinit();
+ const listed = rd(p, @backingInt(tree.TopFile.commands), 0, 1 << 16).bytes;
+ for ([_][]const u8{
+ "\nRepl arg pane -- Binds this terminal as a language's REPL, so an exec on that language's files is typed into it instead of run.\n",
+ "\nJoincol root -- Fold the active pane's column into the one on its right, keeping its panes.\n",
+ "\nExit root -- Quit the editor, refusing once while a pane holds unsaved text: an Exit with nothing edited since discards it.\n",
+ "\nWrap arg root on,off -- Long lines wrap onto the next row, on or off.\n",
+ // the reference's examples, as they read.
+ "\nNewcol root -- An empty column right of the keyboard's, its tag taking the keyboard.\n",
+ "\nSave arg pane -- Write the pane's text to its file, or to the file its argument names.\n",
+ "\nVerbose arg root on,off -- A builtin says its own name on the message row as it runs, on or off.\n",
+ "\nKill arg root -- acme's Kill: stop the commands pardes started",
+ }) |row| try testing.expect(std.mem.indexOf(u8, listed, row) != null);
+ try testing.expect(std.mem.indexOf(u8, listed, ".c:") == null);
+ // Every description is the first sentence of the doc comment just
+ // above its word's declaration in builtins.zig.
+ const source = @embedFile("../builtins.zig");
+ var it = std.mem.tokenizeScalar(u8, listed, '\n');
+ var undescribed: usize = 0;
+ while (it.next()) |line| {
+ // Every builtin has one: a word nobody can look up is no use.
+ const dashes = std.mem.indexOf(u8, line, " -- ") orelse {
+ std.debug.print("no doc comment: {s}\n", .{line});
+ undescribed += 1;
+ continue;
+ };
+ const word = line[0..std.mem.indexOfScalar(u8, line, ' ').?];
+ if (config.Runtime.find(word)) |setting| {
+ try testing.expect(std.mem.endsWith(u8, line, setting.doc));
+ continue;
+ }
+ var needle: [64]u8 = undefined;
+ const at = std.mem.indexOf(u8, source, try std.fmt.bufPrint(&needle, "\npub const {s} = struct", .{word})).?;
+ const said = std.mem.trimEnd(u8, line[dashes + 4 ..], "…");
+ // Its opening words are in the comment block right above.
+ const head = said[0..@min(said.len, 10)];
+ const block_start = std.mem.lastIndexOf(u8, source[0..at], "\n\n") orelse 0;
+ try testing.expect(std.mem.indexOf(u8, source[block_start..at], head) != null);
+ }
+ try testing.expectEqual(0, undescribed);
+}
+
+test "Newcol at the column cap fails the write and says the cap" {
+ const p = try withFile(testing.allocator, "x\n");
+ defer p.deinit();
+ p.update(.{ .resize = .{ .cols = 4000, .rows = 30 } });
+ const root_ctl = @backingInt(tree.TopFile.ctl);
+ while (p.view().ncol < pardes.MAX_COLS) {
+ // From the widest column's tag, so no column gets too narrow first.
+ p.sync();
+ var widest: usize = 0;
+ for (0..p.view().ncol) |c| if (p.view().col_w[c] > p.view().col_w[widest]) {
+ widest = c;
+ };
+ pardes.tagline.enterHeader(p, widest);
+ try testing.expectEqual(Status.ok, wr(p, root_ctl, "Newcol\n").reply.status);
+ }
+ const refused = wr(p, root_ctl, "Newcol\n");
+ try testing.expectEqual(Status.err, refused.reply.status);
+ var want: [64]u8 = undefined;
+ try testing.expect(std.mem.indexOf(u8, refused.reply.ename, try std.fmt.bufPrint(&want, "no space for a column: {d} max", .{pardes.MAX_COLS})) != null);
+ try testing.expect(th.logHas(p, "no space for a column"));
+}
+
+test "Save on a terminal asked over 9P is an ask in the log, answered with a path, and not asked twice" {
+ const p = try th.withTerm(testing.allocator);
+ defer p.deinit();
+ const serial = serialOf(p);
+ const id = p.paneBySerial(serial).?;
+ try testing.expectEqual(Status.ok, wr(p, Node.of(serial, .tagexec), "Save\n").reply.status);
+ var want: [48]u8 = undefined;
+ try testing.expect(th.logHas(p, try std.fmt.bufPrint(&want, "ask {d} save path\n", .{serial})));
+ try testing.expect(p.panes[id].?.prompt == .save);
+ // Again: the one open stands, one ask in the log.
+ _ = wr(p, Node.of(serial, .tagexec), "Save\n");
+ const log = @backingInt(tree.TopFile.log);
+ const h = call(p, .{ .tag = 1, .op = .open, .node = log }).reply.handle;
+ try testing.expectEqual(@as(usize, 1), std.mem.count(u8, call(p, .{ .tag = 2, .op = .read, .node = log, .handle = h, .size = 1 << 16 }).bytes, "save path\n"));
+ _ = call(p, .{ .tag = 3, .op = .release, .node = log, .handle = h });
+ // Answered: the path is written to, the prompt goes.
+ const answered = wr(p, Node.of(serial, .ctl), "answer /tmp/pardes-ask-save.txt\n");
+ try testing.expectEqual(Status.ok, answered.reply.status);
+ try testing.expect(p.panes[id].?.prompt == .none);
+ try testing.expect(th.logHas(p, try std.fmt.bufPrint(&want, "answer {d} /tmp/pardes-ask-save.txt\n", .{serial})));
+}
+
+test "get names the path it could not read, logs the edits it threw away, and a deleted file is said once" {
+ const p = try withFile(testing.allocator, "x\n");
+ defer p.deinit();
+ const serial = serialOf(p);
+ const f = &p.panes[0].?.file.?;
+ const path = f.path;
+ // Its file is not on disk: get names it.
+ const missing = wr(p, Node.of(serial, .ctl), "get\n");
+ try testing.expectEqual(E.NOENT, missing.errno());
+ var want: [512]u8 = undefined;
+ try testing.expectEqualStrings(try std.fmt.bufPrint(&want, "get: {s}: no such file", .{path}), missing.reply.ename);
+ // Deleted on disk: said once.
+ pardes.panes.File.deleted(p, 0);
+ pardes.panes.File.deleted(p, 0);
+ var rec: [32]u8 = undefined;
+ const log = @backingInt(tree.TopFile.log);
+ const h = call(p, .{ .tag = 1, .op = .open, .node = log }).reply.handle;
+ try testing.expectEqual(@as(usize, 1), std.mem.count(u8, call(p, .{ .tag = 2, .op = .read, .node = log, .handle = h, .size = 1 << 16 }).bytes, try std.fmt.bufPrint(&rec, "changed {d} deleted\n", .{serial})));
+ _ = call(p, .{ .tag = 3, .op = .release, .node = log, .handle = h });
+}
+
+test "a word written to a raw terminal's look is listed as in normal mode" {
+ const p = try th.withTerm(testing.allocator);
+ defer p.deinit();
+ const serial = serialOf(p);
+ const id = p.paneBySerial(serial).?;
+ p.update(.{ .output = .{ .pane = @intCast(id), .bytes = "one MARK two\r\n" } });
+ p.panes[id].?.body.mode = .tty;
+ try testing.expectEqual(Status.ok, wr(p, Node.of(serial, .look), "MARK\n").reply.status);
+ const said = std.mem.trimEnd(u8, rd(p, Node.of(serial, .look), 0, 64).bytes, "\n");
+ const made = p.panes[p.paneBySerial(try std.fmt.parseInt(u32, said, 10)).?].?;
+ try testing.expect(made.file.?.output.?.from == .search);
+}
+
+test "@p<terminal>:<address> takes any address over the terminal's lines, selecting the match" {
+ const p = try th.withTerm(testing.allocator);
+ defer p.deinit();
+ const serial = serialOf(p);
+ const id = p.paneBySerial(serial).?;
+ p.update(.{ .output = .{ .pane = @intCast(id), .bytes = "one\r\ntwo MARK three\r\n" } });
+ const pane = p.panes[id].?;
+ const root = @backingInt(tree.TopFile.look);
+ var line: [64]u8 = undefined;
+ try testing.expectEqual(Status.ok, wr(p, root, try std.fmt.bufPrint(&line, "@p{d}:0/MARK/\n", .{serial})).reply.status);
+ try testing.expectEqual(@as(i32, 1), pane.body.cur_row);
+ try testing.expect(pane.body.vsel.active);
+ // #n lands on that byte: #5 is the `w` of `two`.
+ try testing.expectEqual(Status.ok, wr(p, root, try std.fmt.bufPrint(&line, "@p{d}:#5\n", .{serial})).reply.status);
+ try testing.expectEqual(@as(i32, 1), pane.body.cur_row);
+ try testing.expectEqual(@as(i32, 1), pane.body.cur_col);
+ _ = wr(p, root, try std.fmt.bufPrint(&line, "@p{d}:/zzqq/\n", .{serial}));
+ try testing.expect(th.logHas(p, "look: no match for regexp"));
+ // A line past its last is a miss, as in a file.
+ const row_before = pane.body.cur_row;
+ _ = wr(p, root, try std.fmt.bufPrint(&line, "@p{d}:999\n", .{serial}));
+ try testing.expect(th.logHas(p, "has no line 999"));
+ try testing.expectEqual(row_before, pane.body.cur_row);
+ try testing.expectEqualStrings("", rd(p, root, 0, 64).bytes);
+}
+
+test "what a /pager open writes after its directory is the text: plain in the body, its colours the pane's, clean, in by the read" {
+ if (pardes.Term.ops == null) return error.SkipZigTest; // the emulator's parse of colours
+ const p = try withFile(testing.allocator, "x\n");
+ defer p.deinit();
+ const pager = @backingInt(tree.TopFile.pager);
+ const asked = call(p, .{ .tag = 1, .op = .open, .node = pager, .omode = 2 }).reply.handle;
+ // The directory and the text's start in one write, escapes and all, a
+ // second line no directory; the rest in writes after it.
+ try testing.expectEqual(Status.ok, call(p, .{ .tag = 2, .op = .write, .node = pager, .handle = asked, .data = "/tmp\n\x1b[31mred\x1b[m /a\n" }).reply.status);
+ try testing.expectEqual(Status.ok, call(p, .{ .tag = 3, .op = .write, .node = pager, .handle = asked, .data = "\x1b]0;title\x07N\x08Next\r\n" }).reply.status);
+ const id = for (p.panes, 0..) |slot, i| {
+ const pn = slot orelse continue;
+ if (pn.file) |f| if (std.mem.eql(u8, f.path, "/tmp/+Pager")) break i;
+ } else return error.NoPager;
+ const pn = p.panes[id].?;
+ try testing.expectEqualStrings("", pn.file.?.content);
+ // The read that answers the pane finds the text in.
+ var line: [16]u8 = undefined;
+ try testing.expectEqualStrings(try std.fmt.bufPrint(&line, "{d}\n", .{pn.serial}), call(p, .{ .tag = 4, .op = .read, .node = pager, .handle = asked, .size = 64 }).bytes);
+ _ = call(p, .{ .tag = 5, .op = .release, .node = pager, .handle = asked, .opened = true });
+ const f = &pn.file.?;
+ try testing.expectEqualStrings("red /a\nNext\n", f.content);
+ try testing.expectEqualStrings("red /a\nNext\n", rd(p, Node.of(pn.serial, .body), 0, 64).bytes);
+ try testing.expectEqual(f.revision, f.saved_revision);
+ try testing.expectEqual(@as(usize, 2), f.pager_spans.len);
+ try testing.expectEqualStrings("red", f.content[f.pager_spans[0].start..f.pager_spans[0].end]);
+ try testing.expectEqual(pardes.Color{ .index = 1 }, f.pager_spans[0].style.fg);
+ try testing.expect(f.pager_spans[1].style.bold);
+ // One undo step back to the empty pane.
+ const j = &f.history.journal;
+ try testing.expect(j.done > 0);
+ const top = j.steps.items[j.done - 1];
+ try testing.expectEqual(@as(usize, 1), top.n);
+ // Its one entry took out the nothing the pane held and put the page in.
+ const e = j.entries.items[top.first];
+ try testing.expectEqual(@as(usize, 0), e.off);
+ try testing.expectEqual(@as(usize, 0), e.removed.len);
+ try testing.expectEqual(f.content.len, e.ins);
+ // An edit drops the colours (Term.page's ponytail).
+ try testing.expectEqual(Status.ok, call(p, .{ .tag = 6, .op = .write, .node = Node.of(pn.serial, .body), .data = "more\n" }).reply.status);
+ try testing.expectEqual(@as(usize, 0), f.pager_spans.len);
+ // Undone back to the paged text: the text comes back, its colours
+ // stay dropped (they were the program's, for the text it printed).
+ try panes.File.undoStep(p, pn, true);
+ try testing.expectEqualStrings("red /a\nNext\n", f.content);
+ try testing.expectEqual(@as(usize, 0), f.pager_spans.len);
+
+ // An open closed with no read: the text in at the editor's next step
+ // (a close through a mount never waits), its colours kept.
+ const kept = try testing.allocator.dupe(u8, f.content);
+ defer testing.allocator.free(kept);
+ const shut = call(p, .{ .tag = 7, .op = .open, .node = pager, .omode = 1 }).reply.handle;
+ try testing.expectEqual(Status.ok, call(p, .{ .tag = 8, .op = .write, .node = pager, .handle = shut, .data = "/tmp\n" }).reply.status);
+ try testing.expectEqual(Status.ok, call(p, .{ .tag = 9, .op = .write, .node = pager, .handle = shut, .data = "\x1b[1;32mgreen\x1b[m\n" }).reply.status);
+ _ = call(p, .{ .tag = 10, .op = .release, .node = pager, .handle = shut, .opened = true });
+ // A new +Pager: the first keeps its page.
+ try testing.expectEqualStrings(kept, f.content);
+ const next = for (p.panes) |slot| {
+ const other = slot orelse continue;
+ if (other == pn) continue;
+ if (other.file) |*of| if (std.mem.eql(u8, of.path, "/tmp/+Pager")) break of;
+ } else return error.NoPager;
+ try testing.expectEqualStrings("", next.content);
+ fillClosedPagers(p);
+ try testing.expectEqualStrings("green\n", next.content);
+ try testing.expectEqual(@as(usize, 1), next.pager_spans.len);
+ try testing.expectEqual(next.revision, next.saved_revision);
+}
+
+test "a command pane an exec open was answered is leased to it while it stays open: another client's command gets a pane of its own" {
+ if (pardes.Term.ops == null) return error.SkipZigTest; // a command pane
+ const p = try withFile(testing.allocator, "x\n");
+ defer p.deinit();
+ const exec = Node.of(serialOf(p), .exec);
+ const Client = struct {
+ fn run(pp: *Pardes, node: u64, h: u32, line: []const u8) !usize {
+ try testing.expectEqual(Status.ok, call(pp, .{ .tag = 2, .op = .write, .node = node, .handle = h, .data = line }).reply.status);
+ const id = pp.paneBySerial(pp.fs.results[0]).?;
+ // Its command finishes and its output ends.
+ pp.panes[id].?.command_done = true;
+ pp.panes[id].?.command_pty = false;
+ return id;
+ }
+ };
+ const a = call(p, .{ .tag = 1, .op = .open, .node = exec, .omode = 2 }).reply.handle;
+ const b = call(p, .{ .tag = 1, .op = .open, .node = exec, .omode = 2 }).reply.handle;
+ const a_pane = try Client.run(p, exec, a, "echo a\n");
+ const b_pane = try Client.run(p, exec, b, "echo b\n");
+ try testing.expect(a_pane != b_pane);
+ // Each one's next command runs in its own pane again.
+ try testing.expectEqual(a_pane, try Client.run(p, exec, a, "echo a2\n"));
+ try testing.expectEqual(b_pane, try Client.run(p, exec, b, "echo b2\n"));
+ // Closed, a lease ends: the directory's one command pane is reused.
+ _ = call(p, .{ .tag = 3, .op = .release, .node = exec, .handle = a, .opened = true });
+ try testing.expectEqual(Status.ok, wr(p, exec, "echo c\n").reply.status);
+ try testing.expectEqual(a_pane, p.paneBySerial(p.fs.results[0]).?);
+}
+
+test "a Save whose directory is missing because one above refuses says permission denied, not no such directory" {
+ const p = try withFile(testing.allocator, "x\n");
+ defer p.deinit();
+ // The refusing directory is Linux's /proc/1/root.
+ if (comptime @import("builtin").os.tag == .linux) {
+ p.saveFailed(0, "/proc/1/root/x/f.txt", error.FileNotFound);
+ try testing.expect(th.logHas(p, "Save /proc/1/root/x/f.txt: permission denied"));
+ }
+ p.saveFailed(0, "/tmp/pardes-surely-missing-dir/f.txt", error.FileNotFound);
+ try testing.expect(th.logHas(p, "no such directory"));
+}
+
+test "a body write to an image pane says its body takes none, not that terminals have no text" {
+ const p = try withFile(testing.allocator, "x\n");
+ defer p.deinit();
+ const doc = try pardes.Kind.open(p, p.freeSlot().?, pardes.Kind.test_kind.of(p), "/tmp/pardes-pic.ppm", null);
+ try testing.expectEqualStrings(pane_files.e_no_body, wr(p, Node.of(doc.serial, .body), "x").reply.ename);
+}
+
+test "Term+bash on a pane ctl is Term with its argument, as exec and the tag take it" {
+ if (pardes.Term.ops == null) return error.SkipZigTest; // a shell
+ const p = try withFile(testing.allocator, "x\n");
+ defer p.deinit();
+ // Tty+sh too: Term's old name, as a saved tag holds it.
+ for ([_][]const u8{ "Term+sh\n", "Tty+sh\n" }) |data| {
+ const r = call(p, .{ .tag = 1, .op = .write, .node = Node.of(serialOf(p), .ctl), .data = data });
+ try testing.expectEqual(Status.ok, r.reply.status);
+ try testing.expect(r.spawned);
+ }
+}
+
+test "a Rename that reaches other files previews them, says so, and is the pane a waiting write answers" {
+ const p = try withFile(testing.allocator, "x\n");
+ defer p.deinit();
+ const id = p.view().active;
+ p.fs.lsp_result = null;
+ p.lspRequest(id, .rename, "sum");
+ Ask.lspResponse(p, p.lsp_ask.wait.?.id, "lib.rs:2:8 sum\nmain.rs:4:13-15 sum\n");
+ const preview = p.panes[p.panes[id].?.search_pane.?].?;
+ try testing.expectEqual(preview.serial, p.fs.lsp_result.?);
+ try testing.expect(th.logHas(p, "Rename: 2 edit(s) across files, previewed, not applied"));
+}
+
+test "Edit on an image pane is refused as a data write there is, EINVAL, before it runs" {
+ const p = try withFile(testing.allocator, "x\n");
+ defer p.deinit();
+ const doc = try pardes.Kind.open(p, p.freeSlot().?, pardes.Kind.test_kind.of(p), "/tmp/pardes-pic.ppm", null);
+ const edit = wr(p, Node.of(doc.serial, .ctl), "Edit ,d\n");
+ const data = wr(p, Node.of(doc.serial, .data), "x");
+ try testing.expectEqual(E.INVAL, edit.errno());
+ try testing.expectEqualStrings(data.reply.ename, edit.reply.ename);
+ try testing.expectEqual(E.INVAL, wr(p, Node.of(doc.serial, .name), "/tmp/other.ppm\n").errno());
+}
+
+test "Petscii, Palette and Ascii take the state their tag word names, set rather than flipped" {
+ const p = try withFile(testing.allocator, "x\n");
+ defer p.deinit();
+ const doc = try pardes.Kind.open(p, p.freeSlot().?, pardes.Kind.test_kind.of(p), "/tmp/pardes-pic.ppm", null);
+ const ctl_node = Node.of(doc.serial, .ctl);
+ for ([_][]const u8{ "Petscii on\n", "Petscii on\n" }) |line| {
+ try testing.expectEqual(Status.ok, wr(p, ctl_node, line).reply.status);
+ try testing.expect(doc.addon.?.art.glyph);
+ }
+ _ = wr(p, ctl_node, "Petscii off\n");
+ try testing.expect(!doc.addon.?.art.glyph);
+ _ = wr(p, ctl_node, "Palette terminal\n");
+ _ = wr(p, ctl_node, "Palette terminal\n");
+ try testing.expectEqual(pardes.Placement.Art.Palette.terminal, doc.addon.?.art.palette);
+ _ = wr(p, ctl_node, "Ascii off\n");
+ _ = wr(p, ctl_node, "Ascii off\n");
+ try testing.expect(!doc.addon.?.art.ascii);
+ // Bare, each still flips.
+ _ = wr(p, ctl_node, "Ascii\n");
+ try testing.expect(doc.addon.?.art.ascii);
+ _ = wr(p, ctl_node, "Petscii maybe\n");
+ try testing.expect(th.logHas(p, "Petscii takes on or off"));
+}
+
+test "a Rename the server answered for this file alone, with other open files saying the name, is previewed and says so" {
+ const p = try withFile(testing.allocator, "x\n");
+ defer p.deinit();
+ p.lspRequest(p.view().active, .rename, "sum");
+ Ask.lspResponse(p, p.lsp_ask.wait.?.id, "util.zig:1:8 sum\nmain.zig: also says add, which the server did not rename\n");
+ try testing.expect(th.logHas(p, "Rename: previewed, not applied: the server renamed in this file only, and 1 other open file(s) say the name"));
+}
+
+test "Find says what it skipped under its names, and a script's Find that finds nothing is told so" {
+ const gpa = testing.allocator;
+ var tmp = testing.tmpDir(.{});
+ defer tmp.cleanup();
+ try tmp.dir.writeFile(testing.io, .{ .sub_path = "zz-needle.txt", .data = "needle\n" });
+ try tmp.dir.createDirPath(testing.io, "locked");
+ var dir_buf: [4096]u8 = undefined;
+ const dir = dir_buf[0..try tmp.dir.realPath(testing.io, &dir_buf)];
+ var locked_buf: [4200]u8 = undefined;
+ const locked = try std.fmt.bufPrintSentinel(&locked_buf, "{s}/locked", .{dir}, 0);
+ if (std.c.chmod(locked, 0) != 0) return;
+ defer _ = std.c.chmod(locked, 0o755);
+ var path_buf: [4200]u8 = undefined;
+ const path = try std.fmt.bufPrint(&path_buf, "{s}/zz-needle.txt", .{dir});
+ const p = try Pardes.init(gpa, .{ .file = path, .tty_only = true, .cols = 80, .rows = 30 });
+ defer p.deinit();
+ // the walk's own skips are what is said (rg would pass over in silence)
+ p.stream.engine = .walk;
+ try testing.expectEqual(Status.ok, wr(p, Node.of(serialOf(p), .exec), "Find needle\n").reply.status);
+ const search = p.panes[pardes.panes.Query.ofOwner(p, p.panes[0].?.serial).?].?;
+ const listed = search.file.?.content;
+ try testing.expect(std.mem.endsWith(u8, listed, "1 directory skipped: permission denied\n"));
+ try testing.expect(std.mem.startsWith(u8, listed, "Find needle\nzz-needle.txt\n"));
+ // Nothing found: the miss is said, the query pane's count 0.
+ _ = std.c.chmod(locked, 0o755);
+ const missed = wr(p, Node.of(serialOf(p), .exec), "Find nosuchname\n");
+ try testing.expectEqual(E.NOENT, missed.errno());
+ try testing.expectEqual(@as(usize, 0), search.query.?.total);
+ try testing.expect(th.logHas(p, "Find: name not found"));
+}
+
+test "Lspinfo's answer is the +Lsp pane it fills, as a Rename preview's is its +Search" {
+ const p = try withFile(testing.allocator, "x\n");
+ defer p.deinit();
+ p.fs.lsp_result = null;
+ p.lspRequest(p.view().active, .status, "");
+ Ask.lspResponse(p, p.lsp_ask.wait.?.id, "language servers:\n");
+ const shown = p.paneBySerial(p.fs.lsp_result.?).?;
+ try testing.expect(std.mem.endsWith(u8, p.panes[shown].?.file.?.path, "+Lsp"));
+}
+
+
+test "DumpDir refuses a relative directory and one that may not be written, up front; a Dump there says permission denied" {
+ const p = try withFile(testing.allocator, "x\n");
+ defer p.deinit();
+ const root_ctl = @backingInt(tree.TopFile.ctl);
+ try testing.expectEqual(E.INVAL, wr(p, root_ctl, "DumpDir dumps\n").errno());
+ try testing.expectEqual(Status.ok, wr(p, root_ctl, "DumpDir /tmp/pardes-dumps-test\n").reply.status);
+ // The refusing directory is Linux's /proc/1/root.
+ if (comptime @import("builtin").os.tag != .linux) return;
+ try testing.expectEqual(E.INVAL, wr(p, root_ctl, "DumpDir /proc/1/root/dumps\n").errno());
+ p.fs.late_failure_len = 0;
+ p.dumpFailed("/proc/1/root/x/pardes.dump.zon", error.FileNotFound);
+ try testing.expect(std.mem.endsWith(u8, p.fs.late_failure[0..p.fs.late_failure_len], ": permission denied"));
+}
+
+test "a command or a terminal refused for room is refused before anything is logged of it, and its serial is never handed out again" {
+ const p = try withFile(testing.allocator, "x\n");
+ defer p.deinit();
+ const exec = Node.of(serialOf(p), .exec);
+ var buf: [32]u8 = undefined;
+ for ([_][]const u8{ "ls\n", "Term\n" }) |line| {
+ // Each a pane of its own until the column has no room for one more.
+ var before = p.next_serial;
+ var tries: usize = 0;
+ while (tries < pardes.MAX_PANES) : (tries += 1) {
+ before = p.next_serial;
+ const r = wr(p, exec, line);
+ p.sync();
+ if (r.reply.status == .err) break;
+ } else return error.NeverRefused;
+ // Nothing said of the refused one: no new, no run, no del.
+ for (before + 1..p.next_serial + 1) |n| {
+ try testing.expect(!th.logHas(p, try std.fmt.bufPrint(&buf, "new {d} ", .{n})));
+ try testing.expect(!th.logHas(p, try std.fmt.bufPrint(&buf, "run {d} ", .{n})));
+ try testing.expect(!th.logHas(p, try std.fmt.bufPrint(&buf, "del {d} ", .{n})));
+ }
+ // And the next pane made takes a serial past it.
+ const spent = p.next_serial;
+ p.update(.{ .resize = .{ .cols = 200, .rows = 200 } });
+ const made = try th.newPane(p);
+ try testing.expect(made > spent);
+ p.update(.{ .resize = .{ .cols = 80, .rows = 24 } });
+ }
+}
+
+test "the init file reads past a BOM, and every line it fails is a notice and an err, never silent" {
+ const p = try Pardes.init(testing.allocator, .{ .tty_only = true, .startup_config = "\xEF\xBB\xBFTheme dusk\nnosuchword 1\nTheme nosuchtheme\n# a comment\nInactiveDim 30 # not a comment, a bad value\n" });
+ defer p.deinit();
+ try testing.expectEqualStrings("dusk", p.theme().name);
+ try testing.expect(th.logHas(p, "err - init file line 2: unknown word \"nosuchword 1\""));
+ try testing.expect(th.logHas(p, "err - init file line 3: "));
+ try testing.expect(!th.logHas(p, "line 4"));
+ try testing.expect(th.logHas(p, "err - init file line 5: "));
+}
+
+test "a setting the other frontend has is passed over in the init file, not failed" {
+ const other = for (config.Runtime.settings) |s| {
+ if (!s.enabled(pardes.builtins.capabilities)) break s.word;
+ } else return; // this frontend has them all
+ var text: [64]u8 = undefined;
+ const p = try Pardes.init(testing.allocator, .{ .tty_only = true, .startup_config = try std.fmt.bufPrint(&text, "{s} 1\n", .{other}) });
+ defer p.deinit();
+ try testing.expect(!th.logHas(p, "init file line"));
+}
+
+test "the init file saved in a pane applies its settings again, and runs none of its commands twice" {
+ const p = try Pardes.init(testing.allocator, .{ .tty_only = true, .startup_config = "Theme dusk\n", .startup_config_path = "/tmp/pardes-init-test/init" });
+ defer p.deinit();
+ const cols = p.view().ncol;
+ pardes.exec.reapplyInitFile(p, "/tmp/pardes-init-test/elsewhere", "Theme acme\n");
+ try testing.expectEqualStrings("dusk", p.theme().name);
+ pardes.exec.reapplyInitFile(p, "/tmp/pardes-init-test/init", "Theme acme\nNewcol\n");
+ try testing.expectEqualStrings("acme", p.theme().name);
+ try testing.expectEqual(cols, p.view().ncol);
+}
diff --git a/core/ninep/events.zig b/core/ninep/events.zig
new file mode 100644
index 00000000..276261c8
--- /dev/null
+++ b/core/ninep/events.zig
@@ -0,0 +1,1497 @@
+//! Event streams: per-pane `event` records, the editor-wide `log`, and the
+//! bounded queues that park a read until something happens.
+const std = @import("std");
+const pardes = @import("../root.zig");
+const exec = @import("../exec.zig");
+const look = @import("../look.zig");
+const cloud9 = @import("cloud9");
+const tree = @import("tree.zig");
+const ctl = @import("ctl.zig");
+const pane_files = @import("pane.zig");
+const dump = @import("../dump.zig");
+
+const Pardes = pardes.Pardes;
+const Pane = pardes.Pane;
+const MAX_PANES = pardes.MAX_PANES;
+const Req = tree.Req;
+const Reply = tree.Reply;
+const E = tree.E;
+
+pub const queue_cap = 64 * 1024;
+
+/// Wall-clock seconds, or zero where the platform has no clock.
+pub fn now() u32 {
+ var ts: std.c.timespec = undefined;
+ if (std.c.clock_gettime(.REALTIME, &ts) != 0) return 0;
+ return std.math.cast(u32, ts.sec) orelse 0;
+}
+
+pub const Queue = struct {
+ buf: std.ArrayList(u8) = .empty,
+ head: usize = 0,
+ cap: usize = queue_cap,
+ /// Records pushed out of the front to make room: the sequence number of
+ /// the oldest one still held.
+ dropped: u64 = 0,
+
+ pub fn deinit(q: *Queue, gpa: std.mem.Allocator) void {
+ q.buf.deinit(gpa);
+ q.head = 0;
+ }
+
+ /// With no memory for it the record is lost, as one pushed out of a
+ /// full ring is: its callers have nowhere to say so (the log is one of
+ /// these rings, and an event or pty reader is told by what it reads).
+ pub fn push(q: *Queue, gpa: std.mem.Allocator, record: []const u8) void {
+ if (record.len > std.math.maxInt(u32)) return;
+ while (q.buf.items.len - q.head + record.len + 4 > q.cap) {
+ if (q.peek() == null) return;
+ q.pop();
+ q.dropped += 1;
+ }
+ q.compact();
+ var head: [4]u8 = undefined;
+ std.mem.writeInt(u32, &head, @intCast(record.len), .little);
+ q.buf.appendSlice(gpa, &head) catch return;
+ q.buf.appendSlice(gpa, record) catch {
+ q.buf.shrinkRetainingCapacity(q.buf.items.len - 4);
+ return;
+ };
+ }
+
+ pub fn peek(q: *const Queue) ?[]const u8 {
+ const rest = q.buf.items[@min(q.head, q.buf.items.len)..];
+ if (rest.len < 4) return null;
+ const len = std.mem.readInt(u32, rest[0..4], .little);
+ if (rest.len < 4 + len) return null;
+ return rest[4 .. 4 + len];
+ }
+
+ pub fn pop(q: *Queue) void {
+ const record = q.peek() orelse return;
+ q.head += 4 + record.len;
+ if (q.head == q.buf.items.len) {
+ q.buf.clearRetainingCapacity();
+ q.head = 0;
+ }
+ }
+
+ pub fn popFront(q: *Queue, n: usize) void {
+ const record = q.peek() orelse return;
+ if (n >= record.len) return q.pop();
+ q.head += n;
+ std.mem.writeInt(u32, q.buf.items[q.head..][0..4], @intCast(record.len - n), .little);
+ }
+
+ fn compact(q: *Queue) void {
+ if (q.head == 0 or q.head * 2 < q.buf.items.len) return;
+ const rest = q.buf.items.len - q.head;
+ std.mem.copyForwards(u8, q.buf.items[0..rest], q.buf.items[q.head..]);
+ q.buf.shrinkRetainingCapacity(rest);
+ q.head = 0;
+ }
+
+ pub fn empty(q: *const Queue) bool {
+ return q.peek() == null;
+ }
+
+ pub fn clearAndFree(q: *Queue, gpa: std.mem.Allocator) void {
+ q.buf.clearAndFree(gpa);
+ q.head = 0;
+ }
+};
+
+/// One record per read; `.again` holds the read until a record arrives.
+pub fn readQueue(p: *Pardes, req: Req, q: *Queue) Reply {
+ const record = q.peek() orelse return .{ .tag = req.tag, .status = .again };
+ // A read shorter than the record takes its front, and the next read the
+ // rest, as acme's event file and pty/data allow: a shell's `read`
+ // takes a byte at a time.
+ const n = @min(record.len, req.size);
+ const out = p.fs.stage(p.gpa);
+ out.appendSlice(p.gpa, record[0..n]) catch return Reply.fail(req.tag, E.NOMEM);
+ q.popFront(n);
+ return .{ .tag = req.tag, .payload = .{ .staged = @intCast(out.items.len) } };
+}
+
+// ---- the editor-wide log ----
+
+/// `unsaved`: a pane a refusal (Exit, Restore, Del, Delcol) is about,
+/// logged before the write's err so a script reads which, whole.
+pub const LogKind = enum { new, del, rename, save, unsaved };
+
+/// A pane leaving, before its state goes with it; one never announced
+/// leaves silently.
+pub fn noteRetire(p: *Pardes, pane: *Pane) void {
+ tree.pty.shellGone(p, pane, false);
+ p.fs.news = true; // a read held on its event or pty/data hears it went
+ p.fs.listeners -|= pane.fs.readers;
+ if (pane.fs.unannounced) {
+ pane.fs.unannounced = false;
+ return;
+ }
+ // A question still standing ends with it, so a follower of its `ask`
+ // hears the end.
+ if (pane.prompt == .repl_choice or pane.prompt == .del_side or pane.prompt == .save) {
+ var rec: [32]u8 = undefined;
+ notePath(p, "answer", std.fmt.bufPrint(&rec, "{d} -", .{pane.serial}) catch unreachable); // a u32 fits 32
+ }
+ noteLog(p, .del, pane);
+}
+
+/// Called at the end of every update: reports the panes installed by it.
+pub fn announce(p: *Pardes) void {
+ for (p.panes) |slot| {
+ const pane = slot orelse continue;
+ if (!pane.fs.unannounced) continue;
+ pane.fs.unannounced = false;
+ noteLog(p, .new, pane);
+ // A file, PDF or image opened (a look, a Restore, a boot): first in
+ // Recent.
+ if (pardes.Pardes.recentPlace(pane)) |d| if (pardes.Pardes.recentKeeps(d.path)) p.recent.opened(p.recentGpa(), d.path);
+ }
+}
+
+/// The panes present at boot are the log's first records: something said
+/// before the first update ends (an init file's notice) waits for them.
+/// The log is the session's (`p.fs`, the authority's): a replica client's,
+/// joined from a dump, is empty, and its step must not announce (taped
+/// reads, Recent's) where the session's, booted long ago, does not.
+fn bootFirst(p: *Pardes) void {
+ if (newest(p) == null and !pardes.tape.replaying()) announce(p);
+}
+
+/// Records `<kind> <serial> <name>`.
+pub fn noteLog(p: *Pardes, kind: LogKind, pane: *Pane) void {
+ // Nothing about a pane comes before its `new`: one not announced yet
+ // is announced first, and a rename of it is no record, as its `new`
+ // carries the name it has by then.
+ if (pane.fs.unannounced and kind != .new) {
+ if (kind == .rename) return;
+ announce(p);
+ }
+ noteLogAs(p, kind, pane, pane_files.nameOf(p, pane));
+}
+
+/// noteLog naming `path` rather than the pane's name: a `Save path` that
+/// writes a copy elsewhere is `save <serial> <path>`.
+pub fn noteLogAs(p: *Pardes, kind: LogKind, pane: *Pane, path: []const u8) void {
+ var buf: [4 * 4096 + 64]u8 = undefined;
+ var name_buf: [4 * 4096]u8 = undefined;
+ // As /index shows it: a newline in the name is `\n`.
+ const name = shown(path, &name_buf);
+ pushLog(p, std.fmt.bufPrint(&buf, "{s} {d} {s}\n", .{ @tagName(kind), pane.serial, name[0..@min(name.len, name_buf.len)] }) catch return); // no record rather than one cut short
+}
+
+/// Records `msg <serial> <text>` for what the editor said, `-` for no pane.
+/// Text past LoggedMessage.cap bytes is cut between words with an ellipsis,
+/// as an err record's reason is.
+pub fn noteMessage(p: *Pardes, serial: u32, said_stamped: []const u8) void {
+ // The message row's clock (`04:39:41 dumped themes`) is not the
+ // record's: the log has no times, and a script reads the words.
+ const said = pardes.Messages.Message.body(said_stamped);
+ var buf: [pardes.Messages.LoggedMessage.cap + 32]u8 = undefined;
+ const kept = pardes.Messages.clip(said, pardes.Messages.LoggedMessage.cap);
+ const cut = if (kept.len < said.len) "…" else "";
+ bootFirst(p);
+ pushCounting(p, (if (serial == 0)
+ std.fmt.bufPrint(&buf, "msg - {s}{s}\n", .{ kept[0..@min(kept.len, pardes.Messages.LoggedMessage.cap)], cut })
+ else
+ std.fmt.bufPrint(&buf, "msg {d} {s}{s}\n", .{ serial, kept[0..@min(kept.len, pardes.Messages.LoggedMessage.cap)], cut })) catch return, said); // no record rather than one cut short
+}
+
+/// `notePath` for an `err` record: the same one again straight after is
+/// counted, `(x2)`, as every err is.
+pub fn noteErrCounted(p: *Pardes, text: []const u8) void {
+ bootFirst(p);
+ var buf: [pardes.memory.limits.host_path_cap + 16]u8 = undefined;
+ pushCounting(p, std.fmt.bufPrint(&buf, "err {s}\n", .{text[0..@min(text.len, buf.len - 16)]}) catch unreachable, text); // buf.len - 16 and 5 fit buf.len
+}
+
+/// Records `<what> <path>`: `dump <path>` when a Dump is written,
+/// `restore <path>` first in a Restore's replacement.
+pub fn notePath(p: *Pardes, what: []const u8, path: []const u8) void {
+ bootFirst(p);
+ var buf: [pardes.memory.limits.host_path_cap + 16]u8 = undefined;
+ pushLog(p, std.fmt.bufPrint(&buf, "{s} {s}\n", .{ what[0..@min(what.len, 14)], path[0..@min(path.len, buf.len - 16)] }) catch return); // no record rather than one cut short
+}
+
+/// Records `err <serial|-> <file>: <why>` for a write that was refused or
+/// failed: through a mount a shell sees only the errno the kernel mapped
+/// the reply to (`Invalid argument`), and here is the reason. The log is
+/// the one place for it, as acme's `errors` file takes text and answers
+/// nothing: a per-pane readable error file would be a second.
+pub fn noteError(p: *Pardes, req: Req, reply: Reply) void {
+ const why = if (reply.ename.len > 0) reply.ename else cloud9.fs.errString(reply.errno);
+ var name: pardes.Kind.Buf(32) = .{};
+ var serial: []const u8 = "-";
+ var file: []const u8 = "os";
+ if (req.node & tree.sources.archive_node != 0) file = "src";
+ if (req.node != pardes.filesystem.os_root and req.node & pardes.filesystem.os_node == 0 and req.node & tree.sources.archive_node == 0) {
+ if (tree.Node.target(req.node)) |t| switch (t) {
+ .top => |f| {
+ file = f.fileName();
+ // The root's exec or look ran at the keyboard's pane: its
+ // failure is that pane's, as a click there would be.
+ if ((f == .exec or f == .look) and p.fs.ran_at != 0)
+ serial = name.print("{d}", .{p.fs.ran_at});
+ },
+ .port => |i| {
+ serial = "-";
+ file = name.print("plumb/{s}", .{pardes.Plumb.portName(p, i) orelse "?"});
+ },
+ .col => |c| {
+ serial = "-";
+ file = if (c.file == .dir)
+ name.print("col/{d}", .{c.serial})
+ else
+ name.print("col/{d}/{s}", .{ c.serial, @tagName(c.file) });
+ },
+ .pane => |pt| {
+ serial = name.print("{d}", .{pt.serial});
+ file = switch (pt.file) {
+ .pty_ctl => "pty/ctl",
+ .pty_status => "pty/status",
+ .pty_data => "pty/data",
+ .pty_run => "pty/run",
+ else => pt.file.fileName(),
+ };
+ },
+ };
+ }
+ var buf: [288]u8 = undefined;
+ // A reason that names its file already (`look: no space...` from a
+ // look) is not prefixed twice: `err 3 look: no space...`.
+ const reason = if (why.len > file.len + 2 and std.ascii.startsWithIgnoreCase(why, file) and std.mem.startsWith(u8, why[file.len..], ": ")) why[file.len + 2 ..] else why;
+ // A long reason is cut between words, with an ellipsis, never mid-word.
+ const kept = pardes.Messages.clip(reason, 200);
+ const record = std.fmt.bufPrint(&buf, "err {s} {s}: {s}{s}\n", .{ serial[0..@min(serial.len, 32)], file[0..@min(file.len, 32)], kept[0..@min(kept.len, 200)], if (kept.len < reason.len) "…" else "" }) catch return; // no record rather than one cut short
+ for (record[0 .. record.len - 1]) |*c| if (c.* < ' ') {
+ c.* = ' ';
+ };
+ pushCounting(p, record, reason);
+}
+
+/// Drops the newest record when it is a msg saying `text` (of any pane)
+/// that no follower has read: a failure its write's err record will say.
+pub fn dropMessage(p: *Pardes, text: []const u8) void {
+ const last = newest(p) orelse return;
+ if (followerRead(p, last.seq) or !std.mem.startsWith(u8, last.text, "msg ")) return;
+ const rest = last.text["msg ".len..];
+ const sp = std.mem.indexOfScalar(u8, rest, ' ') orelse return;
+ if (std.mem.eql(u8, rest[sp + 1 ..], text)) p.fs.log.buf.shrinkRetainingCapacity(last.at);
+}
+
+/// Pushes `record`, or, when it repeats the newest record word for word,
+/// counts that one instead: `<record> (x2)`, the count being every time it
+/// was said. One a follower has already read is not rewritten: the repeat
+/// is a new line carrying the running count, `(x3)`.
+/// `full` is the text before any cut: two records that agree only in what
+/// was cut to fit are no repeat (`fs.log_full_hash`).
+fn pushCounting(p: *Pardes, raw: []u8, full: []const u8) void {
+ const full_hash = std.hash.Wyhash.hash(0, full);
+ defer p.fs.log_full_hash = full_hash;
+ // A client retrying a write that fails the same way would fill the ring
+ // with one line, so a repeat of the newest record is that record counted,
+ // `(x3)`, as +Messages counts its repeats; unless a follower has read it
+ // already and so waits on the repeat as a line of its own.
+ var clean: [4 * 4096 + 256]u8 = undefined;
+ const record = sanitize(raw, &clean);
+ const last = newest(p) orelse return pushLog(p, record);
+ var said = last.text;
+ var times: u32 = 1;
+ if (std.mem.endsWith(u8, said, ")")) if (std.mem.lastIndexOf(u8, said, " (x")) |x| {
+ if (std.fmt.parseInt(u32, said[x + 3 .. said.len - 1], 10)) |n| {
+ times = n;
+ said = said[0..x];
+ } else |_| {}
+ };
+ if (!std.mem.eql(u8, said, record[0 .. record.len - 1]) or p.fs.log_full_hash != full_hash) return pushLog(p, record);
+ var counted: [pardes.Messages.LoggedMessage.cap + 64]u8 = undefined;
+ // A repeat too long to count is pushed as a line of its own.
+ const again = std.fmt.bufPrint(&counted, "{s} (x{d})\n", .{ said, times +| 1 }) catch return pushLog(p, record);
+ if (!followerRead(p, last.seq)) p.fs.log.buf.shrinkRetainingCapacity(last.at);
+ pushLog(p, again);
+}
+
+/// The newest record in the ring: where it starts, its sequence number and
+/// its text without the newline.
+fn newest(p: *Pardes) ?struct { at: usize, seq: u64, text: []const u8 } {
+ const q = &p.fs.log;
+ var at = q.head;
+ var last: ?usize = null;
+ var seq = q.dropped;
+ while (at + 4 <= q.buf.items.len) : (seq += 1) {
+ last = at;
+ at += 4 + std.mem.readInt(u32, q.buf.items[at..][0..4], .little);
+ }
+ const last_at = last orelse return null;
+ const text = q.buf.items[last_at + 4 ..];
+ return .{ .at = last_at, .seq = seq - 1, .text = text[0 .. text.len - 1] };
+}
+
+/// Whether a follower has read the record `seq`, or is part way through it.
+fn followerRead(p: *Pardes, seq: u64) bool {
+ for (p.fs.opens) |o| if (o.node != 0 and o.what == .log) {
+ const l = o.what.log;
+ if (l.follow and (l.next > seq or (l.next == seq and l.part > 0))) return true;
+ };
+ return false;
+}
+
+/// The log is one ring that records whether or not anyone reads it. A record
+/// is one line: a newline in a message or a name would read as two records.
+/// A record as one line of text (shown): the record's own newline, last,
+/// is kept.
+fn sanitize(record: []const u8, out: []u8) []u8 {
+ // A newline in a message is a space (its words go on); a name's own
+ // newline is escaped before it gets here (noteLog).
+ const w = shownAs(record[0 .. record.len - 1], out[0 .. out.len - 1], false).len;
+ out[w] = '\n';
+ return out[0 .. w + 1];
+}
+
+/// `text` as one line of UTF-8 a reader can split and decode, as /log and
+/// /index show names: a backslash is `\\`, a newline `\n` (a name with one
+/// stays readable as what it is, not run into the next), and any other
+/// control character, DEL, C1 control (U+0080-U+009F) or byte that is not
+/// UTF-8 `\xNN`, so a name read there decodes to the bytes it is. `out` of
+/// 4 bytes a byte of `text` holds it all.
+pub fn shown(text: []const u8, out: []u8) []u8 {
+ return shownAs(text, out, true);
+}
+
+fn shownAs(text: []const u8, out: []u8, escape_newline: bool) []u8 {
+ var w: usize = 0;
+ var i: usize = 0;
+ while (i < text.len and w + 4 <= out.len) {
+ const c = text[i];
+ // A name's own backslash is `\\`, so `\n` and `\xNN` read back as
+ // the escapes they are, never as a name that held them.
+ if (c == '\\' and escape_newline) {
+ @memcpy(out[w..][0..2], "\\\\");
+ w += 2;
+ i += 1;
+ continue;
+ }
+ if (c == '\n' and escape_newline) {
+ @memcpy(out[w..][0..2], "\\n");
+ w += 2;
+ i += 1;
+ continue;
+ }
+ if (c < ' ' or c == 0x7f) {
+ // A name's (escape_newline) is `\xNN`, so it reads back as the
+ // byte it was; a message's a space.
+ if (escape_newline) {
+ _ = std.fmt.bufPrint(out[w..], "\\x{x:0>2}", .{c}) catch break;
+ w += 4;
+ } else {
+ out[w] = ' ';
+ w += 1;
+ }
+ i += 1;
+ continue;
+ }
+ const n = std.unicode.utf8ByteSequenceLength(c) catch 0;
+ if (n == 0 or i + n > text.len or !std.unicode.utf8ValidateSlice(text[i .. i + n])) {
+ _ = std.fmt.bufPrint(out[w..], "\\x{x:0>2}", .{c}) catch break;
+ w += 4;
+ i += 1;
+ continue;
+ }
+ if (n == 2 and c == 0xC2 and text[i + 1] <= 0x9F) {
+ if (escape_newline) {
+ if (w + 8 > out.len) break;
+ _ = std.fmt.bufPrint(out[w..], "\\xc2\\x{x:0>2}", .{text[i + 1]}) catch break;
+ w += 8;
+ i += 2;
+ continue;
+ }
+ out[w] = ' ';
+ w += 1;
+ i += 2;
+ continue;
+ }
+ if (w + n > out.len) break;
+ @memcpy(out[w..][0..n], text[i..][0..n]);
+ w += n;
+ i += n;
+ }
+ return out[0..w];
+}
+
+fn pushLog(p: *Pardes, raw: []u8) void {
+ // A record not counted: the next one is no repeat of a counted one.
+ p.fs.log_full_hash = 0;
+ var clean: [4 * 4096 + 256]u8 = undefined;
+ const record = sanitize(raw, &clean);
+ // One record larger than the ring would push every other out and then
+ // not fit itself; cut it to what fits instead, on a character boundary.
+ var end = @min(record.len, p.fs.log.cap - 4) - 1;
+ while (end > 0 and record[end] & 0xC0 == 0x80) end -= 1;
+ record[end] = '\n';
+ p.fs.log.push(p.gpa, record[0 .. end + 1]);
+ p.fs.news = true;
+}
+
+/// What an open of /log holds.
+pub const LogOpen = struct {
+ /// The ring's text when it was opened.
+ bytes: []const u8 = &.{},
+ /// This open waits for records after `bytes`, from `next`.
+ follow: bool = false,
+ next: u64 = 0,
+ /// How much of record `next` a short read already took.
+ part: u32 = 0,
+ /// How much of `bytes` this open has read. Reads walk it as a stream once
+ /// following and ignore their offset, since `exec 3<>log; echo follow
+ /// >&3` leaves the shared offset past the word it wrote.
+ pos: u64 = 0,
+};
+
+/// An open freezes the ring's text, so `cat log` answers what happened lately
+/// and ends; `next` is where a follower picks up after it.
+pub fn freezeLog(p: *Pardes) error{OutOfMemory}!LogOpen {
+ var text: std.ArrayList(u8) = .empty;
+ errdefer text.deinit(p.gpa);
+ var at = p.fs.log.head;
+ const items = p.fs.log.buf.items;
+ var n: u64 = 0;
+ while (at + 4 <= items.len) : (n += 1) {
+ const len = std.mem.readInt(u32, items[at..][0..4], .little);
+ try text.appendSlice(p.gpa, items[at + 4 ..][0..len]);
+ at += 4 + len;
+ }
+ return .{ .bytes = try text.toOwnedSlice(p.gpa), .next = p.fs.log.dropped + n };
+}
+
+/// Past the frozen text, a following open reads newer records one per read,
+/// held until one arrives; one that fell behind the ring hears `lost N`.
+pub fn readLog(p: *Pardes, req: Req) Reply {
+ const slot = &(tree.openOf(p, req) orelse return Reply.fail(req.tag, E.INVAL)).what.log;
+ const frozen = slot.bytes;
+ const out = p.fs.stage(p.gpa);
+ if (!slot.follow or slot.pos < frozen.len) {
+ // Until `follow`, the frozen text is a file like any other: `tail -n`
+ // seeks near its end, `less` seeks back. After it, a stream.
+ const off = @min(if (slot.follow) slot.pos else req.off, frozen.len);
+ const len = @min(frozen.len - off, req.size);
+ out.appendSlice(p.gpa, frozen[off..][0..len]) catch return Reply.fail(req.tag, E.NOMEM);
+ slot.pos = off + len;
+ return .{ .tag = req.tag, .payload = .{ .staged = @intCast(len) } };
+ }
+ const q = &p.fs.log;
+ if (slot.next < q.dropped) {
+ out.print(p.gpa, "lost {d}\n", .{q.dropped - slot.next}) catch return Reply.fail(req.tag, E.NOMEM);
+ slot.next = q.dropped;
+ slot.part = 0;
+ return .{ .tag = req.tag, .payload = .{ .staged = @intCast(out.items.len) } };
+ }
+ // ponytail: walks the ring from its oldest record; it holds at most log_bytes.
+ var at = q.head;
+ var seq = q.dropped;
+ while (at + 4 <= q.buf.items.len) : (seq += 1) {
+ const len = std.mem.readInt(u32, q.buf.items[at..][0..4], .little);
+ if (seq == slot.next) {
+ // A short read (a shell's `read` takes a few bytes at a time)
+ // gets the record in pieces, as pty/data does.
+ const rest = q.buf.items[at + 4 + slot.part ..][0 .. len - slot.part];
+ const n = @min(rest.len, req.size);
+ out.appendSlice(p.gpa, rest[0..n]) catch return Reply.fail(req.tag, E.NOMEM);
+ slot.part += @intCast(n);
+ if (slot.part == len) {
+ slot.next += 1;
+ slot.part = 0;
+ }
+ // This is the last read a Restore lets through: it takes every
+ // whole record that fits, or they were lost with the hangup.
+ if (p.fs.hanging_up and slot.part == 0) {
+ at += 4 + len;
+ while (at + 4 <= q.buf.items.len) : (slot.next += 1) {
+ const more = std.mem.readInt(u32, q.buf.items[at..][0..4], .little);
+ if (out.items.len + more > req.size) break;
+ out.appendSlice(p.gpa, q.buf.items[at + 4 ..][0..more]) catch break;
+ at += 4 + more;
+ }
+ }
+ return .{ .tag = req.tag, .payload = .{ .staged = @intCast(out.items.len) } };
+ }
+ at += 4 + len;
+ }
+ return .{ .tag = req.tag, .status = .again };
+}
+
+/// `follow`, written to an open of the log, makes that open wait for newer
+/// records instead of ending; closing it is the way back.
+pub fn writeLog(p: *Pardes, req: Req) Reply {
+ const slot = &(tree.openOf(p, req) orelse return Reply.fail(req.tag, E.INVAL)).what.log;
+ const word = std.mem.trim(u8, req.data, " \t\r\n");
+ // `follow` reads what the open froze, then waits; `follow new` skips
+ // what was there and waits for what comes after, as tail -n0 -f does.
+ if (std.mem.eql(u8, word, "follow new")) {
+ slot.pos = slot.bytes.len;
+ } else if (!std.mem.eql(u8, word, "follow")) return tree.failText(req.tag, E.INVAL, "invalid write to log: it takes `follow` or `follow new`");
+ slot.follow = true;
+ return .{ .tag = req.tag, .written = @intCast(req.data.len) };
+}
+
+// ---- per-pane event records ----
+
+pub const max_record_text = 256;
+
+pub const Action = enum(u8) {
+ body_delete = 'D',
+ tag_delete = 'd',
+ body_insert = 'I',
+ tag_insert = 'i',
+ body_look = 'L',
+ tag_look = 'l',
+ body_exec = 'X',
+ tag_exec = 'x',
+
+ pub fn onTag(a: Action) bool {
+ return @backingInt(a) >= 'a';
+ }
+};
+
+pub const flag_builtin: u32 = 1;
+pub const flag_filename: u32 = 4;
+pub const flag_chorded: u32 = 8;
+
+pub const Span = struct { at: u32, removed: u32, inserted: u32 };
+
+/// What an edit about to be made changes, told to the pane's event
+/// readers: the `len` bytes of `old` at `off` replaced by `bytes`, as the
+/// span the texts before and after it differ in (its ends grown past the
+/// edit's as far as they agree), found from the edit, never the new text.
+pub fn noteEdit(p: *Pardes, id: usize, on_tag: bool, old: []const u8, off: usize, len: usize, bytes: []const u8) void {
+ const pane = p.panes[id] orelse return;
+ if (pane.fs.readers == 0) return;
+ const span = editSpan(old, off, len, bytes);
+ if (span.removed == 0 and span.inserted == 0) return;
+ if (span.removed > 0) noteAction(p, id, if (on_tag) .tag_delete else .body_delete, span.at, span.at + span.removed, 0, "");
+ if (span.inserted > 0) noteAction(p, id, if (on_tag) .tag_insert else .body_insert, span.at, span.at + span.inserted, 0, bytes[span.at - off ..][0..span.inserted]);
+}
+
+/// `noteEdit` for a text replaced whole by `new`.
+pub fn noteReplace(p: *Pardes, id: usize, on_tag: bool, old: []const u8, new: []const u8) void {
+ noteEdit(p, id, on_tag, old, 0, old.len, new);
+}
+
+fn editSpan(old: []const u8, off: usize, len: usize, bytes: []const u8) Span {
+ const n = old.len - len + bytes.len;
+ const New = struct {
+ old: []const u8,
+ off: usize,
+ len: usize,
+ bytes: []const u8,
+ fn at(t: @This(), i: usize) u8 {
+ if (i < t.off) return t.old[i];
+ if (i < t.off + t.bytes.len) return t.bytes[i - t.off];
+ return t.old[i - t.bytes.len + t.len];
+ }
+ };
+ const new: New = .{ .old = old, .off = off, .len = len, .bytes = bytes };
+ const both = @min(old.len, n);
+ var head = off;
+ while (head < both and old[head] == new.at(head)) head += 1;
+ const rest = both - head;
+ var tail = @min(old.len - off - len, rest);
+ while (tail < rest and old[old.len - 1 - tail] == new.at(n - 1 - tail)) tail += 1;
+ return .{ .at = @intCast(head), .removed = @intCast(old.len - tail - head), .inserted = @intCast(n - tail - head) };
+}
+
+/// Records `<origin><action><q0> <q1> <flag> <n> <text>` for a pane a
+/// script reads; a text of max_record_text and over is sent as none. One
+/// that follows another with no place of its own (a chorded exec's
+/// argument and its location, acme exec.c:182) is `<c>0 0 0 <n> <text>`.
+pub fn noteAction(p: *Pardes, id: usize, action: Action, q0: u32, q1: u32, flag: u32, text: []const u8) void {
+ const pane = p.panes[id] orelse return;
+ if (pane.fs.readers == 0) return;
+ const sent = if (text.len >= max_record_text) text[0..0] else text;
+ var buf: [max_record_text + 64]u8 = undefined;
+ // unreachable: two characters, four u32s, the count and a sent text fit
+ const record = std.fmt.bufPrint(&buf, "{c}{c}{d} {d} {d} {d} {s}\n", .{ p.fs.origin, @backingInt(action), q0, q1, flag, sent.len, sent }) catch unreachable;
+ pane.fs.events.push(p.gpa, record);
+ p.fs.news = true;
+}
+
+pub fn notePtyOutput(p: *Pardes, id: usize, bytes: []const u8) void {
+ if (id >= MAX_PANES or bytes.len == 0) return;
+ const pf = &(p.panes[id] orelse return).fs;
+ if (!pf.pty_reader) return;
+ var off: usize = 0;
+ while (off < bytes.len) {
+ const n = @min(bytes.len - off, queue_cap / 2);
+ pf.pty_out.push(p.gpa, bytes[off..][0..n]);
+ off += n;
+ }
+ p.fs.news = true;
+}
+
+const EventRecord = struct { origin: u8, action: Action, q0: u32, q1: u32, flag: u32 = 0, text: ?[]const u8 = null };
+
+const EventReader = struct {
+ data: []const u8,
+ i: usize = 0,
+ /// A number past what a range can hold: said as such, not clamped.
+ overflow: bool = false,
+
+ fn next(er: *EventReader) ?EventRecord {
+ if (er.i >= er.data.len) return null;
+ var i = er.i;
+ if (i + 2 > er.data.len) return null;
+ const origin = er.data[i];
+ i += 1;
+ const action = std.enums.fromInt(Action, er.data[i]) orelse return null;
+ i += 1;
+ const q0 = scanNumber(er.data, &i, &er.overflow) orelse return null;
+ const q1 = scanNumber(er.data, &i, &er.overflow) orelse return null;
+ while (i < er.data.len and er.data[i] == ' ') i += 1;
+ // acme takes only `origin action q0 q1`; the record whole, as read,
+ // is taken too, so a click with no place in the text (one written
+ // to a pane's own look or exec) can be written back and done.
+ var text: ?[]const u8 = null;
+ var flag: u32 = 0;
+ if (i < er.data.len and er.data[i] != '\n') {
+ flag = scanNumber(er.data, &i, &er.overflow) orelse return null;
+ const n = scanNumber(er.data, &i, &er.overflow) orelse return null;
+ if (i >= er.data.len or er.data[i] != ' ' or er.data.len - (i + 1) < n) return null;
+ text = er.data[i + 1 ..][0..n];
+ i += 1 + n;
+ }
+ if (i >= er.data.len or er.data[i] != '\n') return null;
+ er.i = i + 1;
+ return .{ .origin = origin, .action = action, .q0 = q0, .q1 = q1, .flag = flag, .text = text };
+ }
+};
+
+fn scanNumber(data: []const u8, i: *usize, overflow: *bool) ?u32 {
+ while (i.* < data.len and data[i.*] == ' ') i.* += 1;
+ const s = i.*;
+ var n: u64 = 0;
+ while (i.* < data.len and data[i.*] >= '0' and data[i.*] <= '9') : (i.* += 1) {
+ n = n * 10 + (data[i.*] - '0');
+ if (n > std.math.maxInt(u32)) {
+ overflow.* = true;
+ return null;
+ }
+ }
+ if (i.* == s) return null;
+ return @intCast(n);
+}
+
+/// What a click at `at` takes, as the mouse's does (exec.operandAt),
+/// for an empty range written back: the file name or word under it on its
+/// line (look.expandedWord), else nothing; in a body whose rows name
+/// addresses, for a look alone (`for_look`, exec.operandAt),
+/// look.rowAddressAt's answer, the row's address or its code's words.
+pub fn expandAt(p: *Pardes, pane: *Pane, whole: []const u8, at: usize, in_body: bool, for_look: bool) []const u8 {
+ const start = if (std.mem.lastIndexOfScalar(u8, whole[0..at], '\n')) |nl| nl + 1 else 0;
+ const end = std.mem.indexOfScalarPos(u8, whole, at, '\n') orelse whole.len;
+ var word_from: usize = 0;
+ if (in_body and for_look) row_address: {
+ const row = std.mem.count(u8, whole[0..start], "\n");
+ var buf: [4096 + 32]u8 = undefined;
+ const got = look.rowAddressAt(p, pane, row, at - start, &buf) orelse break :row_address;
+ // Only when the served line is the one the address was read from.
+ if (!std.mem.eql(u8, std.mem.trimEnd(u8, got.line, "\r"), std.mem.trimEnd(u8, whole[start..end], "\r"))) break :row_address;
+ if (got.address) |address| return p.scratch.allocator().dupe(u8, address) catch "";
+ word_from = got.word_from;
+ }
+ const line = whole[start..end];
+ if (at - start < word_from or word_from > line.len) return "";
+ const b = look.expandedWord(line[word_from..], at - start - word_from) orelse return "";
+ return whole[start + word_from + b.lo .. start + word_from + b.hi];
+}
+
+/// Writing a Look or Exec record back performs the action it names.
+pub fn writeEvent(p: *Pardes, asked: Req, id: usize) Reply {
+ const pane0 = p.panes[id] orelse return Reply.fail(asked.tag, E.NOENT);
+ // Its last record needs no newline, as every other line file's last
+ // line does not (`printf 'MX0 10' > event`).
+ var req = asked;
+ if (req.data.len > 0 and req.data[req.data.len - 1] != '\n') {
+ const whole = p.scratch.allocator().alloc(u8, req.data.len + 1) catch return Reply.fail(req.tag, E.NOMEM);
+ @memcpy(whole[0..req.data.len], req.data);
+ whole[req.data.len] = '\n';
+ req.data = whole;
+ }
+ const serial = pane0.serial;
+ {
+ const body = pane_files.bodyOf(pane0);
+ const tag = pane_files.tagOf(p, pane0) catch return Reply.fail(req.tag, E.NOMEM);
+ var check: EventReader = .{ .data = req.data };
+ while (check.next()) |r| {
+ // Who made it: E, F, K or M, as acme's records say.
+ if (std.mem.indexOfScalar(u8, "EFKM", r.origin) == null) return tree.failText(req.tag, E.INVAL, tree.e_bad_event ++ ": its origin is E, F, K or M");
+ switch (r.action) {
+ .body_look, .tag_look, .body_exec, .tag_exec => {},
+ else => return tree.failText(req.tag, E.INVAL, tree.e_bad_event ++ ": only a look or exec (L l X x) is written back"),
+ }
+ const n = if (r.action.onTag()) tag.len else body.len;
+ if (r.q0 > r.q1) return tree.failText(req.tag, E.INVAL, tree.e_bad_event ++ ": its range ends before it starts");
+ // Well formed, but not a range of this text: say which.
+ if (r.q1 > n) return tree.failText(req.tag, E.INVAL, if (r.action.onTag()) "range past end of tag" else "range past end of body");
+ }
+ if (check.overflow) return tree.failText(req.tag, E.INVAL, tree.e_bad_event ++ ": bad number: past what a range holds");
+ if (check.i != req.data.len) return tree.failText(req.tag, E.INVAL, tree.e_bad_event ++ ": a record is <origin><action><q0> <q1> <flag> <count> <text>, a line each");
+ }
+ // What a record written back runs fails the write as a click written
+ // to exec would (a refused Del: EIO and its err), not said and lost.
+ p.fs.capturing = true;
+ p.fs.failure_len = 0;
+ defer p.fs.capturing = false;
+ var run: EventReader = .{ .data = req.data };
+ while (run.next()) |r| {
+ const live = p.paneBySerial(serial) orelse break;
+ const pane = p.panes[live].?;
+ const whole = if (r.action.onTag()) pane_files.tagOf(p, pane) catch return Reply.fail(req.tag, E.NOMEM) else pane_files.bodyOf(pane);
+ const lo = @min(@as(usize, r.q0), whole.len);
+ const hi = @max(lo, @min(@as(usize, r.q1), whole.len));
+ // An empty range with no text is a click at that point: expanded as
+ // the click would be, to the word or file name under it (acme's
+ // expand, look.c).
+ const said = if (r.q0 == r.q1) r.text orelse expandAt(p, pane, whole, lo, !r.action.onTag(), r.action == .body_look or r.action == .tag_look) else whole[lo..hi];
+ const text = p.scratch.allocator().dupe(u8, said) catch continue;
+ switch (r.action) {
+ // A body's click written back is done as the click would have
+ // been (acme's xfideventwrite, xfid.c:842-844): a REPL bound for
+ // it takes it. One that came from a write to exec (`F`) was
+ // never a click, and runs as the command it was.
+ // The chorded exec a reader was told of runs with its argument
+ // (mouse.reportRange), when it is that range written back.
+ .body_exec, .tag_exec => {
+ const pf = &pane.fs;
+ // The two records that follow a chorded exec (its argument
+ // and where it came from), written back after it, are its:
+ // consumed, never run as commands of their own.
+ if (pf.chord_follow > 0 and r.q0 == 0 and r.q1 == 0 and r.flag == 0) {
+ pf.chord_follow -= 1;
+ // The argument a command written back alone waited for.
+ if (pf.chord_pending) |command| {
+ pf.chord_pending = null;
+ defer p.gpa.free(command);
+ const line = exec.withArg(p, command, r.text orelse "");
+ if (pf.chord_pending_tag) _ = exec.execute(p, live, line) else _ = exec.executeFrom(p, live, line, true);
+ }
+ continue;
+ }
+ var arg = if (pf.chord_arg) |a| (if (pf.chord_at.q0 == r.q0 and pf.chord_at.q1 == r.q1) a else null) else null;
+ if (r.flag & flag_chorded != 0) {
+ // Its argument is the next record when it came in the
+ // same write; the rest that follow are consumed.
+ pf.chord_follow = 2;
+ const save = run.i;
+ if (run.next()) |following| if (following.q0 == 0 and following.q1 == 0 and following.flag == 0) {
+ if (following.text) |t| arg = p.scratch.allocator().dupe(u8, t) catch arg;
+ pf.chord_follow = 1;
+ } else {
+ run.i = save;
+ };
+ // Alone, with no argument kept: it waits for its own.
+ if (arg == null) {
+ if (pf.chord_pending) |old| p.gpa.free(old);
+ pf.chord_pending = p.gpa.dupe(u8, text) catch null;
+ pf.chord_pending_tag = r.action == .tag_exec;
+ continue;
+ }
+ }
+ if (r.action == .tag_exec)
+ _ = exec.execute(p, live, exec.withArg(p, text, arg))
+ else
+ _ = exec.executeFrom(p, live, exec.withArg(p, text, arg), r.origin != 'F');
+ if (arg != null) if (p.paneBySerial(serial)) |still| {
+ const spf = &p.panes[still].?.fs;
+ if (spf.chord_arg) |a| p.gpa.free(a);
+ spf.chord_arg = null;
+ };
+ },
+ // What it found is what the look file reads back next, as a
+ // look written there would leave (ctl.run).
+ .body_look, .tag_look => {
+ p.look_missed = false;
+ look.lookAt(p, live, text);
+ p.fs.results_len = 0;
+ if (!p.look_missed) if (p.panes[p.view().active]) |found| {
+ p.fs.results[0] = found.serial;
+ p.fs.results_len = 1;
+ };
+ },
+ else => unreachable,
+ }
+ }
+ return ctl.failedWrite(p, req.tag) orelse .{ .tag = req.tag, .written = @intCast(asked.data.len) };
+}
+
+// ---- tests ----
+
+const testing = std.testing;
+const th = @import("testing.zig");
+const call = th.call;
+const rd = th.rd;
+const wr = th.wr;
+const withFile = th.withFile;
+const serialOf = th.serialOf;
+const Node = tree.Node;
+const Status = tree.Status;
+
+fn drainEvents(p: *Pardes, node: u64, store: []u8, out: [][]const u8) [][]const u8 {
+ var used: usize = 0;
+ var n: usize = 0;
+ while (n < out.len) {
+ const a = rd(p, node, 0, 4096);
+ if (a.reply.status != .ok) break;
+ @memcpy(store[used..][0..a.bytes.len], a.bytes);
+ out[n] = store[used..][0..a.bytes.len];
+ used += a.bytes.len;
+ n += 1;
+ }
+ return out[0..n];
+}
+
+test "an edit's span is where the texts before and after it differ" {
+ const reference = struct {
+ fn span(old: []const u8, new: []const u8) Span {
+ const both = @min(old.len, new.len);
+ var head: usize = 0;
+ while (head < both and old[head] == new[head]) head += 1;
+ var tail: usize = 0;
+ while (tail < both - head and old[old.len - 1 - tail] == new[new.len - 1 - tail]) tail += 1;
+ return .{ .at = @intCast(head), .removed = @intCast(old.len - tail - head), .inserted = @intCast(new.len - tail - head) };
+ }
+ }.span;
+ var prng = std.Random.DefaultPrng.init(3);
+ const r = prng.random();
+ var old: [24]u8 = undefined;
+ var new: [48]u8 = undefined;
+ var bytes: [24]u8 = undefined;
+ for (0..20000) |_| {
+ const old_len = r.uintAtMost(usize, old.len);
+ for (old[0..old_len]) |*c| c.* = "ab"[r.uintLessThan(usize, 2)];
+ const off = r.uintAtMost(usize, old_len);
+ const len = r.uintAtMost(usize, old_len - off);
+ const n = r.uintAtMost(usize, bytes.len);
+ for (bytes[0..n]) |*c| c.* = "ab"[r.uintLessThan(usize, 2)];
+ @memcpy(new[0..off], old[0..off]);
+ @memcpy(new[off..][0..n], bytes[0..n]);
+ @memcpy(new[off + n ..][0 .. old_len - off - len], old[off + len .. old_len]);
+ const new_len = old_len - len + n;
+ try std.testing.expectEqual(reference(old[0..old_len], new[0..new_len]), editSpan(old[0..old_len], off, len, bytes[0..n]));
+ }
+}
+
+test "a stream read at an offset inside its last answer gets the rest of it again, as bash's read seeks back" {
+ const p = try withFile(testing.allocator, "one\n");
+ defer p.deinit();
+ p.update(.tick);
+ while (p.nextEffect()) |_| {}
+ const log = @backingInt(tree.TopFile.log);
+ const f = call(p, .{ .tag = 1, .op = .open, .node = log }).reply.handle;
+ const frozen: u64 = call(p, .{ .tag = 2, .op = .read, .node = log, .handle = f, .size = 8192 }).bytes.len;
+ _ = call(p, .{ .tag = 3, .op = .write, .node = log, .handle = f, .data = "follow" });
+ notePath(p, "dump", "/a");
+ notePath(p, "dump", "/b");
+ const Read = struct {
+ fn at(pp: *Pardes, h: u32, off: u64) []const u8 {
+ return call(pp, .{ .tag = 4, .op = .read, .node = @backingInt(tree.TopFile.log), .handle = h, .off = off, .size = 128 }).bytes;
+ }
+ };
+ try testing.expectEqualStrings("dump /a\n", Read.at(p, f, frozen));
+ // bash kept "dump" and seeked back to just past it.
+ try testing.expectEqualStrings(" /a\n", Read.at(p, f, frozen + 4));
+ // At the end of what it was given: the next record.
+ try testing.expectEqualStrings("dump /b\n", Read.at(p, f, frozen + 8));
+ // A client that reads every record at one offset still gets new ones.
+ notePath(p, "dump", "/c");
+ try testing.expectEqualStrings("dump /c\n", Read.at(p, f, frozen + 8));
+}
+
+test "event records are acme's bytes, one per read, and .again when empty" {
+ const gpa = testing.allocator;
+ const p = try withFile(gpa, "Msg fs-ran\n");
+ defer p.deinit();
+ const serial = serialOf(p);
+ const event = Node.of(serial, .event);
+
+ noteAction(p, 0, .body_exec, 1, 4, flag_builtin, "sg ");
+ try testing.expect(p.panes[0].?.fs.events.empty());
+
+ const h = call(p, .{ .tag = 10, .op = .open, .node = event });
+ try testing.expect(h.reply.handle != 0);
+ try testing.expectEqual(@as(u16, 1), p.fs.listeners);
+
+ try testing.expectEqual(Status.again, rd(p, event, 0, 4096).reply.status);
+
+ p.fs.origin = 'M';
+ noteAction(p, 0, .body_exec, 1, 4, flag_builtin, "ell");
+ noteAction(p, 0, .body_delete, 0, 3, 0, "");
+ try testing.expectEqualStrings("MX1 4 1 3 ell\n", rd(p, event, 0, 4096).bytes);
+ try testing.expectEqualStrings("MD0 3 0 0 \n", rd(p, event, 0, 4096).bytes);
+ try testing.expectEqual(Status.again, rd(p, event, 0, 4096).reply.status);
+
+ noteAction(p, 0, .body_look, 0, 3, flag_filename, "one");
+ // A short read takes the record's front; the next, the rest.
+ try testing.expectEqualStrings("ML0 ", rd(p, event, 0, 4).bytes);
+ try testing.expectEqualStrings("3 4 3 one\n", rd(p, event, 0, 4096).bytes);
+
+ const big = &@as([max_record_text]u8, @splat('z'));
+ noteAction(p, 0, .body_exec, 0, max_record_text, 0, big);
+ try testing.expectEqualStrings("MX0 256 0 0 \n", rd(p, event, 0, 4096).bytes);
+
+ _ = call(p, .{ .tag = 11, .op = .release, .node = event, .handle = h.reply.handle });
+ try testing.expectEqual(@as(u16, 0), p.fs.listeners);
+}
+
+test "a write through the filesystem is reported once, attributed to the file it came through" {
+ const gpa = testing.allocator;
+ const p = try withFile(gpa, "one\ntwo\n");
+ defer p.deinit();
+ const serial = serialOf(p);
+ const event = Node.of(serial, .event);
+ _ = call(p, .{ .tag = 40, .op = .open, .node = event });
+ var store: [4096]u8 = undefined;
+ var slots: [16][]const u8 = undefined;
+ _ = drainEvents(p, event, &store, &slots);
+
+ _ = wr(p, Node.of(serial, .body), "three\n");
+ const body_recs = drainEvents(p, event, &store, &slots);
+ try testing.expect(body_recs.len >= 1);
+ try testing.expectEqualStrings("EI8 14 0 6 three\n\n", body_recs[0]);
+ for (body_recs[1..]) |r| {
+ try testing.expectEqual(@as(u8, 'E'), r[0]);
+ try testing.expect(std.enums.fromInt(Action, r[1]).?.onTag());
+ }
+
+ _ = wr(p, Node.of(serial, .addr), "1");
+ _ = wr(p, Node.of(serial, .data), "ONE\n");
+ const data_recs = drainEvents(p, event, &store, &slots);
+ try testing.expectEqual(@as(usize, 2), data_recs.len);
+ try testing.expectEqualStrings("FD0 3 0 0 \n", data_recs[0]);
+ try testing.expectEqualStrings("FI0 3 0 3 ONE\n", data_recs[1]);
+ try testing.expectEqual(Status.again, rd(p, event, 0, 4096).reply.status);
+}
+
+test "one event reader at a time, and a writer still holds the pane" {
+ const gpa = testing.allocator;
+ const p = try withFile(gpa, "x\n");
+ defer p.deinit();
+ const event = Node.of(serialOf(p), .event);
+
+ const reader = call(p, .{ .tag = 12, .op = .open, .node = event });
+ try testing.expectEqual(Status.ok, reader.reply.status);
+ // Reads consume, so a second reader would see half the clicks: refused.
+ const second = call(p, .{ .tag = 13, .op = .open, .node = event, .omode = 2 });
+ try testing.expectEqual(Status.err, second.reply.status);
+ try testing.expectEqualStrings(tree.e_in_use, second.reply.ename);
+ const writer = call(p, .{ .tag = 13, .op = .open, .node = event, .omode = 1 });
+ try testing.expectEqual(Status.ok, writer.reply.status);
+ try testing.expectEqual(@as(u16, 2), p.panes[0].?.fs.readers);
+ try testing.expectEqual(@as(u16, 2), p.fs.listeners);
+
+ _ = call(p, .{ .tag = 14, .op = .release, .node = event, .handle = writer.reply.handle });
+ try testing.expectEqual(@as(u16, 1), p.panes[0].?.fs.readers);
+ try testing.expect(p.panes[0].?.fs.readers != 0);
+
+ _ = call(p, .{ .tag = 15, .op = .release, .node = Node.of(serialOf(p), .body) });
+ try testing.expectEqual(@as(u16, 1), p.fs.listeners);
+
+ _ = call(p, .{ .tag = 16, .op = .release, .node = event, .handle = reader.reply.handle });
+ try testing.expectEqual(@as(u16, 0), p.fs.listeners);
+ try testing.expect(p.panes[0].?.fs.readers == 0);
+ _ = call(p, .{ .tag = 17, .op = .release, .node = event });
+ try testing.expectEqual(@as(u16, 0), p.fs.listeners);
+ // Once it closed, the next reader gets in.
+ const next = call(p, .{ .tag = 18, .op = .open, .node = event });
+ try testing.expectEqual(Status.ok, next.reply.status);
+ _ = call(p, .{ .tag = 19, .op = .release, .node = event, .handle = next.reply.handle });
+}
+
+test "an event write-back refuses an origin not E, F, K or M, a number past a range's, and a range past the end, EINVAL" {
+ const p = try withFile(testing.allocator, "hello world\n");
+ defer p.deinit();
+ const event = Node.of(serialOf(p), .event);
+ const h = call(p, .{ .tag = 1, .op = .open, .node = event }).reply.handle;
+ defer _ = call(p, .{ .tag = 9, .op = .release, .node = event, .handle = h });
+ for ([_][2][]const u8{
+ .{ "QX0 1\n", "its origin is E, F, K or M" },
+ .{ "MX18446744073709551616 1\n", "bad number" },
+ .{ "MX99999 99999\n", "range past end of body" },
+ }) |c| {
+ const r = wr(p, event, c[0]);
+ try testing.expectEqual(E.INVAL, r.errno());
+ try testing.expect(std.mem.indexOf(u8, r.reply.ename, c[1]) != null);
+ }
+}
+
+test "an event record read a byte at a time arrives whole, in order, as a shell's read takes it" {
+ const p = try withFile(testing.allocator, "x\n");
+ defer p.deinit();
+ const serial = serialOf(p);
+ const event = Node.of(serial, .event);
+ const h = call(p, .{ .tag = 1, .op = .open, .node = event }).reply.handle;
+ defer _ = call(p, .{ .tag = 9, .op = .release, .node = event, .handle = h });
+ _ = wr(p, Node.of(serial, .exec), "Msg piecewise\n");
+ _ = wr(p, Node.of(serial, .exec), "Msg second\n");
+ var got: [128]u8 = undefined;
+ var n: usize = 0;
+ while (n < got.len) {
+ const piece = call(p, .{ .tag = 2, .op = .read, .node = event, .handle = h, .off = n, .size = 1 });
+ if (piece.reply.status != .ok or piece.bytes.len == 0) break;
+ got[n] = piece.bytes[0];
+ n += 1;
+ if (std.mem.count(u8, got[0..n], "\n") == 2) break;
+ }
+ try testing.expectEqualStrings("FX0 0 1 13 Msg piecewise\nFX0 0 1 10 Msg second\n", got[0..n]);
+}
+
+test "a pane deleted while its event file is open leaves no suppression behind" {
+ const gpa = testing.allocator;
+ const p = try withFile(gpa, "x\n");
+ defer p.deinit();
+ const serial = serialOf(p);
+ const event = Node.of(serial, .event);
+ _ = try th.newPane(p);
+
+ const a = call(p, .{ .tag = 18, .op = .open, .node = event });
+ const b = call(p, .{ .tag = 19, .op = .open, .node = event, .omode = 1 });
+ try testing.expectEqual(@as(u16, 2), p.fs.listeners);
+
+ // Through ctl: a line written to its exec would go to the reader.
+ _ = wr(p, Node.of(serial, .ctl), "Del\n");
+ try testing.expect(p.paneBySerial(serial) == null);
+ try testing.expectEqual(@as(u16, 0), p.fs.listeners);
+ // The reader's next read is its end: no more records, no error.
+ const shut = call(p, .{ .tag = 19, .op = .read, .node = event, .handle = a.reply.handle, .size = 64 });
+ try testing.expectEqual(tree.Status.ok, shut.reply.status);
+ try testing.expectEqualStrings("", shut.bytes);
+
+ _ = call(p, .{ .tag = 20, .op = .release, .node = event, .handle = a.reply.handle });
+ _ = call(p, .{ .tag = 21, .op = .release, .node = event, .handle = b.reply.handle });
+ try testing.expectEqual(@as(u16, 0), p.fs.listeners);
+
+ try testing.expectEqual(E.NOENT, rd(p, event, 0, 64).errno());
+ try testing.expectEqual(E.NOENT, rd(p, Node.of(serial, .body), 0, 64).errno());
+ try testing.expectEqual(E.NOENT, wr(p, Node.of(serial, .dirty), "0\n").errno());
+ try testing.expectEqual(E.NOENT, call(p, .{ .tag = 22, .op = .open, .node = event }).errno());
+}
+
+test "writing an event record back performs the action it names" {
+ const gpa = testing.allocator;
+ const p = try withFile(gpa, "Msg fs-ran\n");
+ defer p.deinit();
+ const serial = serialOf(p);
+ const event = Node.of(serial, .event);
+ const pane = p.panes[0].?;
+
+ const w = wr(p, event, "FX0 10\n");
+ try testing.expectEqual(Status.ok, w.reply.status);
+ try testing.expectEqualStrings("fs-ran", pane.msg[0..pane.msg_len]);
+
+ pane.msg_len = 0;
+ try testing.expectEqual(Status.ok, wr(p, event, "FX0 10\nFX0 10\n").reply.status);
+ try testing.expectEqualStrings("fs-ran", pane.msg[0..pane.msg_len]);
+
+ // The last record needs no newline, as any line file's last line.
+ pane.msg_len = 0;
+ const bare = wr(p, event, "FX0 10");
+ try testing.expectEqual(Status.ok, bare.reply.status);
+ try testing.expectEqual(@as(u32, 6), bare.reply.written);
+ try testing.expectEqualStrings("fs-ran", pane.msg[0..pane.msg_len]);
+
+ pane.msg_len = 0;
+ for ([_][]const u8{
+ "FX0 10\nFQ0 1\n", // unknown type character
+ "FX0 999\n", // out of range
+ "FX5 1\n", // q0 > q1
+ "FD0 3\n", // a report, not a request
+ "F\n",
+ }) |bad| {
+ try testing.expectEqual(E.INVAL, wr(p, event, bad).errno());
+ try testing.expectEqual(@as(usize, 0), pane.msg_len);
+ }
+ // A look written back sets what look reads back.
+ _ = wr(p, event, "FL0 3\n");
+ var want_serial: [16]u8 = undefined;
+ try testing.expectEqualStrings(try std.fmt.bufPrint(&want_serial, "{d}\n", .{serial}), rd(p, @backingInt(tree.TopFile.look), 0, 64).bytes);
+ // Well formed but past the text: said so, not "bad event syntax".
+ try testing.expectEqualStrings("range past end of body", wr(p, event, "MX0 999\n").reply.ename);
+
+ _ = call(p, .{ .tag = 23, .op = .open, .node = event });
+ p.fs.origin = 'K';
+ _ = wr(p, event, "KX0 10\n");
+ try testing.expectEqual(@as(u8, 'F'), p.fs.origin);
+}
+
+test "the log records whether or not anyone reads, and an open that follows waits" {
+ const gpa = testing.allocator;
+ const p = try withFile(gpa, "logged\n");
+ defer p.deinit();
+ const log = @backingInt(tree.TopFile.log);
+ var expected: [4200]u8 = undefined;
+
+ // Nobody holds /log open, and the pane is recorded anyway.
+ const early = try th.newPane(p);
+ const early_line = try std.fmt.bufPrint(&expected, "new {d} {s}\n", .{ early, pane_files.nameOf(p, p.panes[p.paneBySerial(early).?].?) });
+ const early_owned = try gpa.dupe(u8, early_line);
+ defer gpa.free(early_owned);
+
+ // A plain open answers what happened so far, and ends: `cat log` never hangs.
+ const plain = call(p, .{ .tag = 1, .op = .open, .node = log });
+ try testing.expectEqual(Status.ok, plain.reply.status);
+ const first = call(p, .{ .tag = 2, .op = .read, .node = log, .handle = plain.reply.handle, .size = 8192 });
+ try testing.expect(std.mem.endsWith(u8, first.bytes, early_owned));
+ const past = call(p, .{ .tag = 3, .op = .read, .node = log, .handle = plain.reply.handle, .off = first.bytes.len, .size = 8192 });
+ try testing.expectEqual(Status.ok, past.reply.status);
+ try testing.expectEqual(@as(usize, 0), past.bytes.len);
+ const tail = call(p, .{ .tag = 3, .op = .read, .node = log, .handle = plain.reply.handle, .off = first.bytes.len - early_owned.len, .size = 8192 });
+ try testing.expectEqualStrings(early_owned, tail.bytes);
+ _ = call(p, .{ .tag = 4, .op = .release, .node = log, .handle = plain.reply.handle });
+
+ // `follow` on an open makes it wait past what it froze, one record a read.
+ const f = call(p, .{ .tag = 5, .op = .open, .node = log });
+ const fh = f.reply.handle;
+ const frozen = call(p, .{ .tag = 6, .op = .read, .node = log, .handle = fh, .size = 8192 }).bytes.len;
+ try testing.expectEqual(Status.err, call(p, .{ .tag = 7, .op = .write, .node = log, .handle = fh, .data = "tail\n" }).reply.status);
+ try testing.expectEqual(Status.ok, call(p, .{ .tag = 8, .op = .write, .node = log, .handle = fh, .data = "follow\n" }).reply.status);
+ // A stream: after `echo follow >&3` a shell reads at offset 7, and gets
+ // what comes next, not the frozen text from byte 7. Before `follow` the
+ // offset is honoured, so `tail -n` works (checked below on `plain`).
+ const rdf = struct {
+ fn next(pp: *Pardes, node: u64, h: u32, off: u64) th.Answer {
+ return call(pp, .{ .tag = 9, .op = .read, .node = node, .handle = h, .off = off, .size = 8192 });
+ }
+ };
+ // The word it refused is on record, and then there is nothing new.
+ try testing.expect(std.mem.startsWith(u8, rdf.next(p, log, fh, frozen).bytes, "err - log: "));
+ try testing.expectEqual(Status.again, rdf.next(p, log, fh, frozen).reply.status);
+
+ const serial = try th.newPane(p);
+ const id = p.paneBySerial(serial).?;
+ try testing.expectEqualStrings(
+ try std.fmt.bufPrint(&expected, "new {d} {s}\n", .{ serial, pane_files.nameOf(p, p.panes[id].?) }),
+ rdf.next(p, log, fh, frozen).bytes,
+ );
+ try testing.expectEqual(Status.ok, wr(p, Node.of(serial, .name), "/tmp/logged.txt\n").reply.status);
+ try testing.expectEqualStrings(
+ try std.fmt.bufPrint(&expected, "rename {d} /tmp/logged.txt\n", .{serial}),
+ rdf.next(p, log, fh, frozen).bytes,
+ );
+ // What the editor says is in the same stream, one line even when the
+ // message had several.
+ p.setMessage(id, "save: two\nlines");
+ try testing.expectEqualStrings(
+ try std.fmt.bufPrint(&expected, "msg {d} save: two lines\n", .{serial}),
+ rdf.next(p, log, fh, frozen).bytes,
+ );
+ // A builtin announces itself on the message row only: the log has
+ // what it did.
+ try testing.expectEqual(Status.ok, wr(p, Node.of(serial, .exec), "Del\n").reply.status);
+ try testing.expectEqualStrings(
+ try std.fmt.bufPrint(&expected, "del {d} /tmp/logged.txt\n", .{serial}),
+ rdf.next(p, log, fh, frozen).bytes,
+ );
+ try testing.expectEqual(Status.again, rdf.next(p, log, fh, frozen).reply.status);
+
+ // A shell's `read` asks for a few bytes at a time: the record comes in
+ // pieces rather than failing. A repeat the follower waits on, having
+ // read the first, is its own line.
+ const said_by = p.panes[0].?.serial;
+ p.setMessage(0, "same failure");
+ var pieced: [64]u8 = undefined;
+ var got: usize = 0;
+ while (got == 0 or pieced[got - 1] != '\n') {
+ const piece = call(p, .{ .tag = 9, .op = .read, .node = log, .handle = fh, .off = frozen, .size = 3 }).bytes;
+ @memcpy(pieced[got..][0..piece.len], piece);
+ got += piece.len;
+ }
+ try testing.expectEqualStrings(try std.fmt.bufPrint(&expected, "msg {d} same failure\n", .{said_by}), pieced[0..got]);
+ p.setMessage(0, "same failure");
+ try testing.expectEqualStrings(try std.fmt.bufPrint(&expected, "msg {d} same failure (x2)\n", .{said_by}), rdf.next(p, log, fh, frozen).bytes);
+
+ // A follower the ring outran hears how much it missed, then carries on.
+ var filler: [200]u8 = @splat('x');
+ for (0..p.fs.log.cap / filler.len + 8) |i| {
+ _ = std.fmt.bufPrint(&filler, "{d:0>6}", .{i}) catch unreachable; // a repeat would collapse
+ p.setMessage(0, &filler);
+ }
+ const lost = rdf.next(p, log, fh, frozen).bytes;
+ try testing.expect(std.mem.startsWith(u8, lost, "lost "));
+ try testing.expect(std.mem.startsWith(u8, rdf.next(p, log, fh, frozen).bytes, "msg "));
+ _ = call(p, .{ .tag = 10, .op = .release, .node = log, .handle = fh });
+ for (p.fs.opens) |o| try testing.expect(o.node == 0);
+
+ // A record bigger than the whole ring is cut to fit, not dropped with
+ // everything else pushed out ahead of it.
+ p.fs.log.cap = 128;
+ var huge: [300]u8 = @splat('y');
+ p.setMessage(0, &huge);
+ const cut = call(p, .{ .tag = 11, .op = .open, .node = log });
+ const kept = call(p, .{ .tag = 12, .op = .read, .node = log, .handle = cut.reply.handle, .size = 512 }).bytes;
+ try testing.expectEqual(@as(usize, 124), kept.len);
+ try testing.expect(std.mem.startsWith(u8, kept, "msg ") and kept[kept.len - 1] == '\n');
+ _ = call(p, .{ .tag = 13, .op = .release, .node = log, .handle = cut.reply.handle });
+}
+
+test "a refused or failed write is an err record in the log, saying which file and why" {
+ const p = try withFile(testing.allocator, "one\n");
+ defer p.deinit();
+ p.update(.tick); // the pane's `new` is logged before the log is opened
+ while (p.nextEffect()) |_| {}
+ const serial = serialOf(p);
+ const log = @backingInt(tree.TopFile.log);
+ const f = call(p, .{ .tag = 1, .op = .open, .node = log }).reply.handle;
+ const frozen = call(p, .{ .tag = 2, .op = .read, .node = log, .handle = f, .size = 1 << 16 }).bytes.len;
+ _ = call(p, .{ .tag = 3, .op = .write, .node = log, .handle = f, .data = "follow" });
+ var want: [128]u8 = undefined;
+ const next = struct {
+ fn record(pp: *Pardes, h: u32, off: usize) []const u8 {
+ return call(pp, .{ .tag = 4, .op = .read, .node = @backingInt(tree.TopFile.log), .handle = h, .off = off, .size = 4096 }).bytes;
+ }
+ };
+ _ = wr(p, Node.of(serial, .addr), "/nowhere/");
+ try testing.expectEqualStrings(try std.fmt.bufPrint(&want, "err {d} addr: no match for regexp\n", .{serial}), next.record(p, f, frozen));
+ _ = wr(p, @backingInt(tree.TopFile.ctl), "Bogus");
+ try testing.expectEqualStrings("err - ctl: unknown control message \"Bogus\"\n", next.record(p, f, frozen));
+ _ = wr(p, @backingInt(tree.TopFile.focus), "99999");
+ try testing.expectEqualStrings("err - focus: no such pane\n", next.record(p, f, frozen));
+ // A write that succeeds says nothing.
+ _ = wr(p, Node.of(serial, .addr), "#0");
+ try testing.expectEqual(Status.again, call(p, .{ .tag = 5, .op = .read, .node = log, .handle = f, .off = frozen, .size = 4096 }).reply.status);
+ // A follower that has read an err waits on its repeat: a line of its
+ // own, with the running count.
+ _ = wr(p, Node.of(serial, .addr), "/nowhere/");
+ try testing.expectEqualStrings(try std.fmt.bufPrint(&want, "err {d} addr: no match for regexp\n", .{serial}), next.record(p, f, frozen));
+ _ = wr(p, Node.of(serial, .addr), "/nowhere/");
+ try testing.expectEqualStrings(try std.fmt.bufPrint(&want, "err {d} addr: no match for regexp (x2)\n", .{serial}), next.record(p, f, frozen));
+ _ = call(p, .{ .tag = 6, .op = .release, .node = log, .handle = f });
+
+ // With the follower gone, repeats are the newest record counted on:
+ // its two, and three more.
+ for (0..3) |_| _ = wr(p, Node.of(serial, .addr), "/elsewhere/");
+ const g = call(p, .{ .tag = 7, .op = .open, .node = log }).reply.handle;
+ const text = call(p, .{ .tag = 8, .op = .read, .node = log, .handle = g, .size = 1 << 16 }).bytes;
+ try testing.expect(std.mem.endsWith(u8, text, try std.fmt.bufPrint(&want, "regexp\nerr {d} addr: no match for regexp (x5)\n", .{serial})));
+ _ = call(p, .{ .tag = 9, .op = .release, .node = log, .handle = g });
+}
+
+test "a Dump written and a Restore made are in the log, with their files" {
+ const p = try withFile(testing.allocator, "one\n");
+ defer p.deinit();
+ p.setLastDump("/tmp/pardes.dump.zon");
+ try dump.dumpState(p);
+ const restored = try dump.restore(p, p.dump_out.?, "/tmp/pardes.dump.zon");
+ defer restored.deinit();
+ for ([_]*Pardes{ p, restored }, [_][]const u8{ "dump", "restore" }) |core, what| {
+ const log = try freezeLog(core);
+ defer core.gpa.free(log.bytes);
+ var want: [64]u8 = undefined;
+ try testing.expect(std.mem.indexOf(u8, log.bytes, try std.fmt.bufPrint(&want, "{s} /tmp/pardes.dump.zon\n", .{what})) != null);
+ }
+ // Its panes and columns are the dump's, serials and all.
+ try testing.expectEqual(p.panes[0].?.serial, restored.panes[0].?.serial);
+ try testing.expectEqual(pardes.layout.columnSerial(p, 0), pardes.layout.columnSerial(restored, 0));
+}
+
+test "after a Restore a new pane or column takes a serial past every one the old session handed out" {
+ const p = try withFile(testing.allocator, "one\n");
+ defer p.deinit();
+ try dump.dumpState(p);
+ // Serials spent since the dump, on panes and columns since deleted.
+ p.next_serial += 5;
+ p.next_column_serial += 5;
+ const spent = p.next_serial;
+ const spent_col = p.next_column_serial;
+ const restored = try dump.restore(p, p.dump_out.?, "/tmp/pardes.dump.zon");
+ defer restored.deinit();
+ try testing.expect(restored.next_serial >= spent and restored.next_column_serial >= spent_col);
+}
+
+test "a pane named before it is announced has its new under that name, and no rename before it" {
+ if (pardes.Term.ops == null) return error.SkipZigTest; // a shell
+ const p = try withFile(testing.allocator, "one\n");
+ defer p.deinit();
+ const pane = p.panes[0].?;
+ // As a pane Config makes and names in one update.
+ pane.fs.unannounced = true;
+ try pane_files.nameBuffer(p, 0, "/tmp/named-first.txt", false);
+ announce(p);
+ const log = try freezeLog(p);
+ defer p.gpa.free(log.bytes);
+ var want: [64]u8 = undefined;
+ try testing.expect(std.mem.endsWith(u8, log.bytes, try std.fmt.bufPrint(&want, "new {d} /tmp/named-first.txt\n", .{pane.serial})));
+ try testing.expect(std.mem.indexOf(u8, log.bytes, try std.fmt.bufPrint(&want, "rename {d} ", .{pane.serial})) == null);
+ // A shell given no directory is named by the session's from the first,
+ // and saying it is there is no rename.
+ const free = p.freeSlot().?;
+ const shell = try p.newShell(free, "");
+ try testing.expectEqualStrings(p.sessionDir(), pane_files.nameOf(p, shell));
+ announce(p);
+ p.setCwd(free, p.sessionDir());
+ const after = try freezeLog(p);
+ defer p.gpa.free(after.bytes);
+ try testing.expect(std.mem.indexOf(u8, after.bytes, try std.fmt.bufPrint(&want, "rename {d} ", .{shell.serial})) == null);
+}
+
+test "an empty range written back is expanded as a click at that point would be" {
+ const p = try withFile(testing.allocator, "abc def abc\nx Newcol y\n");
+ defer p.deinit();
+ const serial = serialOf(p);
+ const pane = p.panes[p.paneBySerial(serial).?].?;
+ const event = Node.of(serial, .event);
+ // A look at 1 is a look at `abc`: from dot, past the first, the next.
+ pane_files.setDot(pane, .{ .q0 = 4, .q1 = 4 });
+ try testing.expectEqual(Status.ok, wr(p, event, "ML1 1\n").reply.status);
+ try testing.expectEqual(pane_files.State.Range{ .q0 = 8, .q1 = 11 }, pane_files.dotOf(pane));
+ // An exec at 15 runs the word there, `Newcol`.
+ const cols = p.view().ncol;
+ try testing.expectEqual(Status.ok, wr(p, event, "MX15 15\n").reply.status);
+ try testing.expectEqual(cols + 1, p.view().ncol);
+}
+
+test "opens of the log share the open records, and a closed one frees its record" {
+ const gpa = testing.allocator;
+ const p = try withFile(gpa, "x\n");
+ defer p.deinit();
+ const log = @backingInt(tree.TopFile.log);
+ var handles: [tree.open_slots]u32 = undefined;
+ for (&handles) |*h| h.* = call(p, .{ .tag = 1, .op = .open, .node = log }).reply.handle;
+ try testing.expectEqual(E.NFILE, call(p, .{ .tag = 2, .op = .open, .node = log }).errno());
+ _ = call(p, .{ .tag = 3, .op = .release, .node = log, .handle = handles[5] });
+ const again = call(p, .{ .tag = 4, .op = .open, .node = log });
+ try testing.expectEqual(Status.ok, again.reply.status);
+ handles[5] = again.reply.handle;
+ for (handles) |h| _ = call(p, .{ .tag = 5, .op = .release, .node = log, .handle = h });
+ for (p.fs.opens) |o| try testing.expect(o.node == 0);
+}
+
+test "a click in the body reports the offsets of the word it takes, so the record can be written back" {
+ const config = @import("../config.zig");
+ const gpa = testing.allocator;
+ const text = "alpha qty beta\n qty\n\tqty\ndef f(qty): return qty.x\n" ++ &@as([100]u8, @splat('w')) ++ " qty\n";
+ const p = try withFile(gpa, text);
+ defer p.deinit();
+ // A scratch made over 9P, clicked while another pane has the keyboard.
+ const scratch = try th.newPane(p);
+ _ = wr(p, Node.of(scratch, .body), text);
+ for ([_]u32{ serialOf(p), scratch }) |serial| {
+ const id = p.paneBySerial(serial).?;
+ p.view().active = p.paneBySerial(if (serial == scratch) serialOf(p) else scratch).?;
+ const event = Node.of(serial, .event);
+ const h = call(p, .{ .tag = 1, .op = .open, .node = event }).reply.handle;
+ var frame = std.heap.ArenaAllocator.init(gpa);
+ defer frame.deinit();
+ _ = try p.render(frame.allocator());
+ const rect = p.view().rects[id];
+ const x0 = rect.x + config.GUTTER + config.PREFIX_W;
+ const y0 = rect.y + p.panes[id].?.tag_rows;
+ const tab: u16 = config.tab_now;
+ const Click = struct { x: u16, y: u16, look: []const u8, exec: []const u8, scroll: i32 = 0 };
+ // Where the wrapped line's `qty` landed, as drawn.
+ const surface = try p.render(frame.allocator());
+ var wrap_col: u16 = 0;
+ while (wrap_col < rect.w and !std.mem.eql(u8, surface.at(x0 + wrap_col, y0 + 5).grapheme(), "q")) wrap_col += 1;
+ for ([_]Click{
+ .{ .x = x0 + 7, .y = y0, .look = "ML6 9 0 3 qty\n", .exec = "MX6 9 0 3 qty\n" },
+ .{ .x = x0 + 5, .y = y0 + 1, .look = "ML19 22 0 3 qty\n", .exec = "MX19 22 0 3 qty\n" },
+ .{ .x = x0 + tab + 1, .y = y0 + 2, .look = "ML24 27 0 3 qty\n", .exec = "MX24 27 0 3 qty\n" },
+ .{ .x = x0 + 7, .y = y0 + 3, .look = "ML34 37 0 3 qty\n", .exec = "MX34 37 0 3 qty\n" },
+ // Scrolled a line, the first row shows the second.
+ .{ .x = x0 + 5, .y = y0, .look = "ML19 22 0 3 qty\n", .exec = "MX19 22 0 3 qty\n", .scroll = 1 },
+ // Wrapped: the word on the continuation row.
+ .{ .x = x0 + wrap_col, .y = y0 + 5, .look = "ML154 157 0 3 qty\n", .exec = "MX154 157 0 3 qty\n" },
+ }) |c| for ([_]pardes.Mouse.Button{ config.look_button, config.exec_button }, [_][]const u8{ c.look, c.exec }) |button, want| {
+ // The pointer rests on the word first, as a hand's does, and
+ // the hover preview comes up under it.
+ p.panes[id].?.scrollBy(c.scroll);
+ _ = try p.render(frame.allocator());
+ p.update(.{ .mouse = .{ .button = .none, .kind = .motion, .col = c.x, .row = c.y } });
+ for (0..200) |_| p.update(.tick);
+ p.update(.{ .mouse = .{ .button = button, .kind = .press, .col = c.x, .row = c.y } });
+ p.update(.{ .mouse = .{ .button = button, .kind = .release, .col = c.x, .row = c.y } });
+ try testing.expectEqualStrings(want, call(p, .{ .tag = 2, .op = .read, .node = event, .handle = h, .size = 256 }).bytes);
+ p.panes[id].?.scrollBy(-c.scroll);
+ };
+ // A click on nothing expands to nothing, and acme then says
+ // nothing (look.c:37, exec.c:141).
+ p.update(.{ .mouse = .{ .button = config.look_button, .kind = .press, .col = x0 + 60, .row = y0 + 1 } });
+ p.update(.{ .mouse = .{ .button = config.look_button, .kind = .release, .col = x0 + 60, .row = y0 + 1 } });
+ try testing.expectEqual(Status.again, call(p, .{ .tag = 2, .op = .read, .node = event, .handle = h, .size = 256 }).reply.status);
+ _ = call(p, .{ .tag = 3, .op = .release, .node = event, .handle = h });
+ }
+}
+
+test "follow new skips what the log held and waits for what comes after" {
+ const p = try withFile(testing.allocator, "x\n");
+ defer p.deinit();
+ p.update(.tick); // the pane's `new` is logged first
+ while (p.nextEffect()) |_| {}
+ p.setMessage(0, "before the open");
+ const log = @backingInt(tree.TopFile.log);
+ const h = call(p, .{ .tag = 1, .op = .open, .node = log }).reply.handle;
+ try testing.expectEqual(Status.ok, call(p, .{ .tag = 2, .op = .write, .node = log, .handle = h, .data = "follow new\n" }).reply.status);
+ try testing.expectEqual(Status.again, call(p, .{ .tag = 3, .op = .read, .node = log, .handle = h, .size = 4096 }).reply.status);
+ p.setMessage(0, "after it");
+ try testing.expect(std.mem.endsWith(u8, call(p, .{ .tag = 4, .op = .read, .node = log, .handle = h, .size = 4096 }).bytes, " after it\n"));
+ _ = call(p, .{ .tag = 5, .op = .release, .node = log, .handle = h });
+}
+
+test "a long msg record is cut between words at its cap, with an ellipsis" {
+ const p = try withFile(testing.allocator, "x\n");
+ defer p.deinit();
+ const long = std.mem.asBytes(&@as([60][5]u8, @splat("word ".*))); // 300 bytes
+ _ = wr(p, Node.of(serialOf(p), .ctl), "Msg " ++ long ++ "\n");
+ const log = @backingInt(tree.TopFile.log);
+ const h = call(p, .{ .tag = 1, .op = .open, .node = log }).reply.handle;
+ const text = call(p, .{ .tag = 2, .op = .read, .node = log, .handle = h, .size = 1 << 16 }).bytes;
+ const at = std.mem.lastIndexOf(u8, text, "msg ").?;
+ const record = text[at .. std.mem.indexOfScalarPos(u8, text, at, '\n').? + 1];
+ try testing.expect(std.mem.endsWith(u8, record, " word…\n"));
+ try testing.expect(record.len <= "msg 1 ".len + pardes.Messages.LoggedMessage.cap + "…\n".len);
+ _ = call(p, .{ .tag = 3, .op = .release, .node = log, .handle = h });
+}
+
+test "a record is one line of UTF-8: DEL and C1 are spaces, bytes not UTF-8 are escaped" {
+ var out: [64]u8 = undefined;
+ var name: [64]u8 = undefined;
+ try testing.expectEqualStrings("/tmp/two\\nlines", shown("/tmp/two\nlines", &name));
+ // A backslash of the name's own is doubled: `\n` in a name differs from
+ // a newline in one.
+ try testing.expectEqualStrings("/tmp/a\\\\nb", shown("/tmp/a\\nb", &name));
+ try testing.expectEqualStrings("msg - a b c \\xff d\n", sanitize("msg - a\x7fb\xc2\x85c \xff d\n", &out));
+ try testing.expectEqualStrings("msg - caf\xc3\xa9\n", sanitize("msg - caf\xc3\xa9\n", &out));
+}
+
+test "a long err record keeps its end, its middle given up to an ellipsis" {
+ const p = try withFile(testing.allocator, "x\n");
+ defer p.deinit();
+ _ = wr(p, @backingInt(tree.TopFile.ctl), "Bogus" ++ std.mem.asBytes(&@as([40][8]u8, @splat("abcdefgh".*))) ++ "\n");
+ const log = @backingInt(tree.TopFile.log);
+ const h = call(p, .{ .tag = 1, .op = .open, .node = log }).reply.handle;
+ const text = call(p, .{ .tag = 2, .op = .read, .node = log, .handle = h, .size = 1 << 16 }).bytes;
+ const at = std.mem.lastIndexOf(u8, text, "err - ctl: ").?;
+ const record = text[at .. std.mem.indexOfScalarPos(u8, text, at, '\n').? + 1];
+ try testing.expect(std.mem.indexOf(u8, record, "…") != null);
+ try testing.expect(std.mem.startsWith(u8, record, "err - ctl: "));
+ try testing.expect(std.mem.endsWith(u8, record, "abcdefgh\"\n") or std.mem.endsWith(u8, record, "abcdefgh \"\n"));
+ _ = call(p, .{ .tag = 3, .op = .release, .node = log, .handle = h });
+}
+
+test "two failures that agree only in what their records cut are two records, not one counted" {
+ const p = try th.withFile(testing.allocator, "x\n");
+ defer p.deinit();
+ const long = std.mem.asBytes(&@as([80][4]u8, @splat("why ".*)));
+ p.setMessage(0, long ++ "first");
+ p.setMessage(0, long ++ "second");
+ try testing.expect(!th.logHas(p, "(x2)"));
+ p.setMessage(0, long ++ "second");
+ try testing.expect(th.logHas(p, "(x2)"));
+}
+
+test "a message the host stamped with its clock is recorded without it" {
+ const p = try withFile(testing.allocator, "x\n");
+ defer p.deinit();
+ noteMessage(p, 7, "04:39:41 dumped themes /tmp/t");
+ try testing.expect(th.logHas(p, "msg 7 dumped themes /tmp/t\n"));
+}
diff --git a/core/ninep/pane.zig b/core/ninep/pane.zig
new file mode 100644
index 00000000..11f0558e
--- /dev/null
+++ b/core/ninep/pane.zig
@@ -0,0 +1,1342 @@
+//! The files under /pane/<serial>/: name, body, tag, ctl, the three range
+//! files addr, dot and limit, data, xdata, sel, the three flag files dirty,
+//! mark and scroll, errors, event, look and exec. Terminals add pty/ (pty.zig).
+const std = @import("std");
+const pardes = @import("../root.zig");
+const tagline = @import("../tagline.zig");
+const exec = @import("../exec.zig");
+const layout = @import("../layout.zig");
+const look = @import("../look.zig");
+const panes = @import("../panes.zig");
+const modal = @import("../modal.zig");
+const config = @import("../config.zig");
+const fs = @import("../fs.zig");
+const tree = @import("tree.zig");
+const locations = @import("../locations.zig");
+const events = @import("events.zig");
+const addressing = @import("addr.zig");
+const ctl = @import("ctl.zig");
+const pty = @import("pty.zig");
+const screen = @import("screen.zig");
+const limits = @import("../memory.zig").limits;
+
+const Pardes = pardes.Pardes;
+const Pane = pardes.Pane;
+const Req = tree.Req;
+const Reply = tree.Reply;
+const E = tree.E;
+const PaneFile = tree.PaneFile;
+const Node = tree.Node;
+
+/// Filesystem state a pane carries beside its editor state.
+pub const State = struct {
+ /// The range `data` and `xdata` read and write through. acme clears it
+ /// when the first client opens `addr` (editors/acme/xfid.c:105-108),
+ /// which suits a client that holds the fid open; a shell cannot, and
+ /// would evaluate every `echo /re/ > addr` from #0 and never advance.
+ /// Here it is the pane's own register, cleared by neither an open nor
+ /// a truncation: `0` or `,` starts over, and `cp addr dot` and
+ /// `cat addr` answer what was written.
+ addr: Range = .{},
+ /// The last address written to `addr` failed, so there is none: `data`
+ /// and `xdata` refuse until a good one is written,
+ /// rather than act at the address before it, which acme would do.
+ addr_failed: bool = false,
+ limit: ?Range = null,
+ /// The limit a truncation cleared, kept until the write that follows it
+ /// on that open (a shell's `>`): a write that fails puts it back.
+ limit_truncated: ?Range = null,
+ /// `dot` was truncated and nothing written since: the write that
+ /// follows sets it or, refused, leaves it as it was; with none, the
+ /// open's release empties it (tree.zig releaseHandle).
+ dot_truncated: bool = false,
+ /// The open whose writes to `sel` are being kept together (0: none) and
+ /// the text they have made so far: the next write of that open goes at
+ /// its end, as acme's wrselrange does.
+ wrsel_by: u32 = 0,
+ wrsel: Range = .{},
+ /// Opens of `event`, which hold the pane scripted.
+ readers: u16 = 0,
+ /// One of `readers` reads `event`; a second reading open is refused.
+ event_reader: bool = false,
+ events: events.Queue = .{},
+ nomark: bool = false,
+ /// The revision a truncation or a write of `data`, `xdata` or `body`
+ /// left: the write that follows it at once joins its undo step, until
+ /// that open is released (tree.zig releaseHandle). So a shell's
+ /// `printf 'x\ny\n' > data` is one step, as acme's replace is, though
+ /// bash writes it a line at a time; any other edit between breaks it.
+ joined: ?u32 = null,
+ /// The open whose writes `joined` joins (0: any, as after a truncation
+ /// or for an open with no record): an interleaved open's write starts
+ /// a step of its own.
+ joined_by: u32 = 0,
+ noscroll: bool = false,
+ tag_snap: std.ArrayList(u8) = .empty,
+ /// An open reads pty/data, so output queues for it; a second is refused.
+ pty_reader: bool = false,
+ pty_out: events.Queue = .{},
+ /// The handle of the pty/run open waiting on this shell's current
+ /// command, good only through `tree.openOf` on this pane's run node.
+ run: ?u32 = null,
+ /// The handle of the ctl open that wrote `lock` (ctl.zig), the same way.
+ lock: ?u32 = null,
+ /// The host started a shell it could not teach to mark its prompts.
+ unmarked: bool = false,
+ /// `tag` was truncated (`echo X > tag`): until that open is released,
+ /// the newline that ends a write is held back, so the one that ends the
+ /// whole of it is dropped and draws no empty row.
+ tag_rewrite: bool = false,
+ tag_held_newline: bool = false,
+ /// A truncation of `tag` not yet done: the write after it does it, once
+ /// the write is known to fit, so a refused `>` leaves the tag as it was;
+ /// a read or a close with no write does it then.
+ tag_trunc_pending: bool = false,
+ /// The pty's size as pty/ctl's winsize last set it, until the pane's own
+ /// grid resizes and gives the pty its size again.
+ winsize: ?[2]u16 = null,
+ /// Installed during this update; /log hears about it once the update ends
+ /// and the pane has its file, name and place.
+ unannounced: bool = false,
+ /// A chorded exec's argument an event reader was told of (flag 8), kept
+ /// for the record's write-back at `chord_at`, which runs with it.
+ chord_arg: ?[]u8 = null,
+ chord_at: Range = .{},
+ /// A chorded record written back: how many of its two follow-up records
+ /// (argument, location) are still to be consumed rather than run.
+ chord_follow: u8 = 0,
+ /// A chorded record written back alone with no argument kept: the
+ /// command, run when its argument record comes.
+ chord_pending: ?[]u8 = null,
+ chord_pending_tag: bool = false,
+
+ pub const Range = struct { q0: u32 = 0, q1: u32 = 0 };
+
+ pub fn deinit(pf: *State, gpa: std.mem.Allocator) void {
+ if (pf.chord_arg) |a| gpa.free(a);
+ if (pf.chord_pending) |c| gpa.free(c);
+ pf.events.deinit(gpa);
+ pf.pty_out.deinit(gpa);
+ pf.tag_snap.deinit(gpa);
+ pf.* = .{};
+ }
+};
+
+// ---- what a pane is ----
+
+pub fn bodyOf(pane: *const Pane) []const u8 {
+ if (pane.file) |*f| return f.content;
+ return "";
+}
+
+pub fn fileOf(pane: *Pane) ?*panes.File.State {
+ return if (pane.file) |*f| f else null;
+}
+
+pub fn tagOf(p: *Pardes, pane: *Pane) error{OutOfMemory}![]const u8 {
+ return tagline.tagText(p, p.scratch.allocator(), pane);
+}
+
+pub fn dirtyOf(pane: *const Pane) bool {
+ const f = if (pane.file) |*x| x else return false;
+ if (!panes.Output.fileTraits(f.output).saves) return false;
+ // Its file deleted on disk: the text is only here now, as acme counts it.
+ return f.revision != f.saved_revision or f.disk_gone;
+}
+
+/// The pane's name: its file, its document, or a terminal's directory.
+pub fn nameOf(p: *Pardes, pane: *const Pane) []const u8 {
+ if (pane.file) |*f| return f.path;
+ if (pane.addon) |k| if (k.path.len > 0) return k.path;
+ const cwd = pane.cwdSlice();
+ // A shell given no directory was started in the session's, and is
+ // named by it until it says where it is (a `new` then, not a rename).
+ return if (cwd.len > 0) cwd else p.sessionDir();
+}
+
+pub fn kindOf(pane: *const Pane) []const u8 {
+ if (pane.file != null) return "text";
+ if (pane.addon) |k| return k.nameOf();
+ // A command's pane is no shell to type into: a script choosing a
+ // terminal by kind must not pick one.
+ if (pane.command != null) return "cmd";
+ return "term";
+}
+
+pub fn clip(n: usize) u32 {
+ return std.math.cast(u32, n) orelse std.math.maxInt(u32);
+}
+
+/// The file's line index when it describes `text` (built by a render or a
+/// look), else null: with it a row is a binary search, not a count of every
+/// newline from the top, which a bulk write paid on each flush, twice over.
+fn lineIndex(pane: *const Pane, text: []const u8) ?[]const usize {
+ const f = if (pane.file) |*file| file else return null;
+ if (f.line_starts.len == 0 or f.content.ptr != text.ptr or f.content.len != text.len) return null;
+ return f.line_starts;
+}
+
+/// The line `off` is on: the last start at or before it.
+fn rowAt(starts: []const usize, off: usize) usize {
+ const after = std.sort.upperBound(usize, starts, off, struct {
+ fn order(key: usize, item: usize) std.math.Order {
+ return std.math.order(key, item);
+ }
+ }.order);
+ return after -| 1;
+}
+
+fn lineEnd(starts: []const usize, text: []const u8, row: usize) usize {
+ return if (row + 1 < starts.len) starts[row + 1] - 1 else text.len;
+}
+
+/// `modal.runeOffsetAt`, through the line index when there is one.
+fn runeOffsetAt(pane: *const Pane, text: []const u8, c: modal.Cursor) usize {
+ const starts = lineIndex(pane, text) orelse return modal.runeOffsetAt(text, c);
+ const row = @min(c.row, starts.len - 1);
+ const s = starts[row];
+ const e = lineEnd(starts, text, row);
+ return s + modal.runeStart(text[s..e], @min(c.col, e - s));
+}
+
+/// `modal.runePositionAt`, through the line index when there is one.
+fn runePositionAt(pane: *const Pane, text: []const u8, off: usize) modal.Cursor {
+ const starts = lineIndex(pane, text) orelse return modal.runePositionAt(text, off);
+ const bounded = modal.runeStart(text, off);
+ const row = rowAt(starts, bounded);
+ return .{ .row = row, .col = bounded - starts[row] };
+}
+
+/// `modal.positionAt`, through the line index when there is one.
+fn positionAt(pane: *const Pane, text: []const u8, off: usize) modal.Cursor {
+ const starts = lineIndex(pane, text) orelse return modal.positionAt(text, off);
+ const bounded = @min(off, text.len);
+ const row = rowAt(starts, bounded);
+ const s = starts[row];
+ const e = lineEnd(starts, text, row);
+ return .{ .row = row, .col = modal.graphemeStart(text[s..e], @min(bounded - s, e - s)) };
+}
+
+pub fn dotOf(pane: *Pane) State.Range {
+ const text = bodyOf(pane);
+ // In runes, as every address is (modal.runeStart).
+ const head = runeOffsetAt(pane, text, .{ .row = @intCast(@max(0, pane.body.cur_row)), .col = @intCast(@max(0, pane.body.cur_col)) });
+ if (!pane.body.vsel.active) return .{ .q0 = clip(head), .q1 = clip(head) };
+ const anchor = runeOffsetAt(pane, text, .{ .row = @intCast(@max(0, pane.body.vsel.row)), .col = @intCast(@max(0, pane.body.vsel.col)) });
+ var hi = @max(head, anchor);
+ if (hi < text.len) hi = modal.nextRune(text, hi);
+ return .{ .q0 = clip(@min(head, anchor)), .q1 = clip(hi) };
+}
+
+pub fn setDot(pane: *Pane, r: State.Range) void {
+ const text = bodyOf(pane);
+ const q0 = @min(@as(usize, r.q0), text.len);
+ const q1 = @max(q0, @min(@as(usize, r.q1), text.len));
+ const a = runePositionAt(pane, text, q0);
+ pane.body.vsel = .{ .active = q1 > q0, .row = @intCast(a.row), .col = @intCast(a.col), .explicit = true };
+ const h = runePositionAt(pane, text, if (q1 > q0) modal.prevRune(text, q1) else q0);
+ pane.body.cur_row = @intCast(h.row);
+ pane.body.cur_col = @intCast(h.col);
+ pane.body.cur_pinned = true;
+ pane.body.sticky_col = -1;
+ pane.ensureCursorVisible();
+}
+
+/// Scrolls `off` into view and nothing else: the cursor is dot's head, and
+/// a write shown is not a write that moves dot (acme's textinsert leaves
+/// dot where its rule puts it; only the view follows the text).
+pub fn showOffset(pane: *Pane, off: usize) void {
+ const text = bodyOf(pane);
+ const c = positionAt(pane, text, @min(off, text.len));
+ // Where dot is now, kept: pinned, so the view moving under it does not
+ // move it to the view's top (pinCursor).
+ pane.pinCursor();
+ const row = pane.body.cur_row;
+ const col = pane.body.cur_col;
+ pane.body.cur_row = @intCast(c.row);
+ pane.body.cur_col = @intCast(c.col);
+ pane.ensureCursorVisible();
+ pane.body.cur_row = row;
+ pane.body.cur_col = col;
+}
+
+pub fn clampAddr(pf: *State, len: usize) void {
+ const n = clip(len);
+ pf.addr.q0 = @min(pf.addr.q0, n);
+ pf.addr.q1 = @min(pf.addr.q1, n);
+ if (pf.limit) |*l| {
+ l.q0 = @min(l.q0, n);
+ l.q1 = @min(l.q1, n);
+ }
+}
+
+fn shiftOne(v: u32, at: u32, removed: u32, inserted: u32) u32 {
+ if (v <= at) return v;
+ if (v <= at +| removed) return at +| inserted;
+ return v - removed +| inserted;
+}
+
+pub fn wholeUtf8(data: []const u8) usize {
+ var i = data.len;
+ var back: usize = 0;
+ while (i > 0 and back < 4) : (back += 1) {
+ i -= 1;
+ const c = data[i];
+ if (c < 0x80) return data.len;
+ if (c & 0xC0 == 0xC0) {
+ const need = std.unicode.utf8ByteSequenceLength(c) catch return data.len;
+ if (i + need <= data.len or i == 0) return data.len;
+ return i;
+ }
+ }
+ return data.len;
+}
+
+pub fn spliceBody(p: *Pardes, pane: *Pane, q0: usize, q1: usize, bytes: []const u8) ?usize {
+ const f = fileOf(pane) orelse return null;
+ const take = if (bytes.len == 0) 0 else wholeUtf8(bytes);
+ const lo = @min(q0, f.content.len);
+ const hi = @max(lo, @min(q1, f.content.len));
+ // An empty range deleted, or a range replaced by what it holds: no
+ // edit, so no undo step and no new revision.
+ if (std.mem.eql(u8, f.content[lo..hi], bytes[0..take])) return take;
+ const join = pane.fs.joined == f.revision;
+ pane.fs.joined = null;
+ if (!pane.fs.nomark and !join) panes.File.pushUndo(p, pane) catch return null;
+ if (!panes.File.replace(p, f, lo, hi - lo, bytes[0..take])) return null;
+ return take;
+}
+
+// ---- what stat reports ----
+
+/// A range file's text: acme's addr format, two right-aligned offsets, so
+/// that copying one range file onto another is the whole of `dot=addr`.
+pub const range_len: u64 = 24;
+
+pub fn fileSize(p: *Pardes, id: usize, f: PaneFile) u64 {
+ const pane = p.panes[id] orelse return 0;
+ const pf = &pane.fs;
+ return switch (f) {
+ // A terminal's body reads its screen and history, as text.
+ .body => if (pane.file == null and pane.isTerminal()) pardes.Term.scrollbackLen(pane.terminal) else if (kindText(p, pane)) |t| t.len else bodyOf(pane).len,
+ // What addr selects, generated by each read: no length, as acme's
+ // data and xdata have none; and rows, made by each read.
+ .data, .xdata, .rows => 0,
+ .tag => if (tagOf(p, pane)) |tag| tag.len else |_| 0, // a stat's length is a hint: none when the tag cannot be made
+ .name => nameOf(p, pane).len + 1,
+ .ctl => ctl: {
+ var buf: [ctl.pane_text_cap]u8 = undefined;
+ break :ctl ctl.paneText(p, pane, &buf).len;
+ },
+ .sel => sel: {
+ const d = dotOf(pane);
+ break :sel @max(d.q0, d.q1) - d.q0;
+ },
+ .addr => if (pf.addr_failed) 0 else range_len,
+ .dot => range_len,
+ .limit => if (pf.limit == null) 0 else range_len,
+ .dirty, .mark, .scroll => 2,
+ .look, .exec, .tagexec => ctl.resultsLen(p),
+ // What the next read would answer, which a client can see without
+ // parking on it.
+ .event => if (pf.events.peek()) |record| record.len else 0,
+ .pty_status => pty.status_len,
+ .pty_ctl => pty_ctl: {
+ var buf: [32]u8 = undefined;
+ // The size a read says: what winsize set, else the grid.
+ const size = pty.winsize(pane);
+ // unreachable: two u16s and 9 bytes fit 32
+ break :pty_ctl (std.fmt.bufPrint(&buf, "winsize {d} {d}\n", .{ size[0], size[1] }) catch unreachable).len;
+ },
+ .pty_data => if (pf.pty_out.peek()) |chunk| chunk.len else 0,
+ .dir, .errors, .pty, .pty_run => 0,
+ };
+}
+
+// ---- the index ----
+
+/// The serial of the column a pane is in, as /layout and /col name it; the
+/// last word of its /index line.
+pub fn columnOf(p: *Pardes, id: usize) u32 {
+ const at = pardes.layout.findPane(p, id) orelse return 0;
+ return pardes.layout.columnSerial(p, at.col);
+}
+
+// ---- reads ----
+
+pub fn read(p: *Pardes, req: Req, id: usize, pane: *Pane, file: PaneFile) Reply {
+ const pf = &pane.fs;
+ return switch (file) {
+ .name => name: {
+ const out = p.fs.stage(p.gpa);
+ out.appendSlice(p.gpa, nameOf(p, pane)) catch break :name Reply.fail(req.tag, E.NOMEM);
+ out.append(p.gpa, '\n') catch break :name Reply.fail(req.tag, E.NOMEM);
+ break :name tree.stagedReply(p, req);
+ },
+ .body => readBody(p, req, id, pane),
+ .tag => tag: {
+ applyTagTruncation(p, pane);
+ break :tag tree.window(p, req, tagOf(p, pane) catch break :tag Reply.fail(req.tag, E.NOMEM));
+ },
+ .ctl => ctl: {
+ var buf: [ctl.pane_text_cap]u8 = undefined;
+ break :ctl tree.window(p, req, ctl.paneText(p, pane, &buf));
+ },
+ // A failed address reads empty, as an unset limit does: there is
+ // none. data and xdata are what refuse.
+ .addr => readRange(p, req, if (pf.addr_failed) null else addr: {
+ clampAddr(pf, bodyOf(pane).len);
+ break :addr pf.addr;
+ }),
+ .dot => readRange(p, req, dotOf(pane)),
+ .limit => readRange(p, req, pf.limit),
+ .data => readData(req, id, pane, pf, false),
+ .xdata => readData(req, id, pane, pf, true),
+ .sel => readSel(req, id, pane),
+ .dirty => readFlag(p, req, dirtyOf(pane)),
+ .mark => readFlag(p, req, !pf.nomark),
+ .scroll => readFlag(p, req, !pf.noscroll),
+ .look, .exec, .tagexec => ctl.readResults(p, req),
+ .rows => rows: {
+ const f = fileOf(pane) orelse break :rows tree.window(p, req, "");
+ var text: std.Io.Writer.Allocating = .init(p.scratch.allocator());
+ locations.formatRows(f.location_rows, &text.writer) catch break :rows Reply.fail(req.tag, E.NOMEM);
+ break :rows tree.window(p, req, text.written());
+ },
+ .event => events.readQueue(p, req, &pf.events),
+ .pty_status => pty.readStatus(p, req, id, pane),
+ .pty_data => pty.readData(p, req, pf),
+ .pty_ctl => pty.readCtl(p, req, pane),
+ .pty_run => pty.readRun(p, req),
+ .dir, .errors, .pty => Reply.fail(req.tag, E.PERM),
+ };
+}
+
+/// An unset limit reads empty, which is how a client tells it from one that
+/// happens to bound nothing.
+fn readRange(p: *Pardes, req: Req, r: ?State.Range) Reply {
+ const out = p.fs.stage(p.gpa);
+ if (r) |range| out.print(p.gpa, "{d:>11} {d:>11} ", .{ range.q0, range.q1 }) catch return Reply.fail(req.tag, E.NOMEM);
+ return tree.stagedReply(p, req);
+}
+
+fn readFlag(p: *Pardes, req: Req, on: bool) Reply {
+ const out = p.fs.stage(p.gpa);
+ out.appendSlice(p.gpa, if (on) "1\n" else "0\n") catch return Reply.fail(req.tag, E.NOMEM);
+ return tree.stagedReply(p, req);
+}
+
+/// A kind's pane's text, read-only: its `body` (a PDF's: the text layer
+/// of the page shown); null for any other pane.
+fn kindText(p: *Pardes, pane: *Pane) ?[]const u8 {
+ if (pane.addon == null) return null;
+ return pardes.Kind.body(pane, p.scratch.allocator()) catch null;
+}
+
+fn readBody(p: *Pardes, req: Req, id: usize, pane: *Pane) Reply {
+ if (pane.file != null) {
+ const text = bodyOf(pane);
+ const off = @min(req.off, text.len);
+ const n = @min(text.len - off, req.size);
+ return .{ .tag = req.tag, .payload = .{ .region = .{
+ .pane = @intCast(id),
+ .serial = pane.serial,
+ .off = clip(off),
+ .len = clip(n),
+ } } };
+ }
+ // A kind's body is its text (a PDF's, the page shown's): read-only.
+ if (kindText(p, pane)) |text| return tree.window(p, req, text);
+ if (req.handle != 0 and pane.isTerminal()) return screen.readSnapshot(p, req, pane);
+ const text = pardes.Term.scrollback(pane.terminal, p.gpa) catch
+ return Reply.fail(req.tag, E.NOMEM);
+ defer p.gpa.free(text);
+ return tree.window(p, req, text);
+}
+
+fn readData(req: Req, id: usize, pane: *Pane, pf: *State, stop_at_end: bool) Reply {
+ if (pf.addr_failed) return tree.failText(req.tag, E.INVAL, e_addr_failed);
+ const text = bodyOf(pane);
+ clampAddr(pf, text.len);
+ const q0: usize = pf.addr.q0;
+ const hi: usize = if (stop_at_end) @max(q0, @as(usize, pf.addr.q1)) else text.len;
+ var end = @min(hi, q0 +| req.size);
+ end = @max(q0, modal.runeStart(text, end));
+ pf.addr.q0 = clip(end);
+ if (!stop_at_end) pf.addr.q1 = clip(end);
+ if (pane.file == null) return .{ .tag = req.tag };
+ return .{ .tag = req.tag, .payload = .{ .region = .{
+ .pane = @intCast(id),
+ .serial = pane.serial,
+ .off = clip(q0),
+ .len = clip(end - q0),
+ } } };
+}
+
+fn readSel(req: Req, id: usize, pane: *Pane) Reply {
+ if (pane.file == null) return .{ .tag = req.tag };
+ const text = bodyOf(pane);
+ const d = dotOf(pane);
+ const lo = @min(@as(usize, d.q0), text.len);
+ const hi = @max(lo, @min(@as(usize, d.q1), text.len));
+ const off = @min(req.off, hi - lo);
+ const n = @min(hi - lo - off, req.size);
+ return .{ .tag = req.tag, .payload = .{ .region = .{
+ .pane = @intCast(id),
+ .serial = pane.serial,
+ .off = clip(lo + off),
+ .len = clip(n),
+ } } };
+}
+
+// ---- writes ----
+
+pub fn write(p: *Pardes, req: Req, id: usize, pane: *Pane, file: PaneFile) Reply {
+ return switch (file) {
+ .name => writeName(p, req, id, pane),
+ .body => writeBody(p, req, id, pane),
+ .tag => writeTag(p, req, pane),
+ .ctl => ctl.writePane(p, req, pane),
+ .addr, .dot, .limit => writeRange(req, pane, file),
+ .data, .xdata => writeData(p, req, pane),
+ .sel => writeSel(p, req, pane),
+ .dirty, .mark, .scroll => writeFlag(p, req, pane, file),
+ .look, .exec => ctl.command(p, req, pane.serial, file == .exec, false),
+ // A click in its tag: an event reader holding the pane hears it as
+ // an `x` record (ctl.run), as acme's tag clicks are.
+ .tagexec => ctl.command(p, req, pane.serial, true, true),
+ .rows => writeRows(p, req, pane),
+ .event => events.writeEvent(p, req, id),
+ .errors => if (appendErrors(p, id, req.data)) |took|
+ .{ .tag = req.tag, .written = @intCast(took) }
+ else
+ Reply.fail(req.tag, E.IO),
+ .pty_ctl => pty.writeCtl(p, req, id),
+ .pty_data => pty.writeData(p, req, id),
+ .pty_run => pty.writeRun(p, req, id, pane),
+ .dir, .pty, .pty_status => Reply.fail(req.tag, E.PERM),
+ };
+}
+
+pub const e_rows_line = "invalid rows: a row is a line, ending in a newline";
+pub const e_rows_text = "invalid rows: a line is no row (the README's rows line says what one is)";
+pub const e_rows_fit = "invalid rows: more rows than the text has lines, or one past its line's end";
+
+/// Rows, whole lines of them (a write through a mount is cut anywhere: the
+/// rest of a line waits for the open's next write, tree.writeLines): at
+/// offset 0 they replace the pane's, at a later one they follow those it
+/// holds. Parsed (locations.parseRows) and handed to File.setRows, which
+/// refuses what the text cannot hold.
+fn writeRows(p: *Pardes, req: Req, pane: *Pane) Reply {
+ const f = fileOf(pane) orelse return Reply.fail(req.tag, E.PERM);
+ if (req.data.len == 0) return .{ .tag = req.tag, .written = 0 };
+ if (req.data[req.data.len - 1] != '\n') return tree.failText(req.tag, E.INVAL, e_rows_line);
+ const arena = p.scratch.allocator();
+ const written = locations.parseRows(arena, req.data) catch |err| return switch (err) {
+ error.OutOfMemory => Reply.fail(req.tag, E.NOMEM),
+ error.BadRows => tree.failText(req.tag, E.INVAL, e_rows_text),
+ };
+ const kept = if (req.off == 0) 0 else f.location_rows.len;
+ const all = arena.alloc(locations.Row, kept + written.len) catch return Reply.fail(req.tag, E.NOMEM);
+ @memcpy(all[0..kept], f.location_rows[0..kept]);
+ @memcpy(all[kept..], written);
+ const rows = locations.cloneRows(p.gpa, all) catch return Reply.fail(req.tag, E.NOMEM);
+ panes.File.setRows(p, f, rows) catch {
+ locations.freeRows(p.gpa, rows);
+ return tree.failText(req.tag, E.INVAL, e_rows_fit);
+ };
+ return .{ .tag = req.tag, .written = @intCast(req.data.len) };
+}
+
+/// spliceBody for a write of the open `handle`, in the undo step its open
+/// is making: it joins the step being made only when it is the same open's
+/// (or the step is anyone's, `joined_by` 0), another open's starting its
+/// own.
+fn spliceJoined(p: *Pardes, pane: *Pane, q0: usize, q1: usize, bytes: []const u8, handle: u32) ?usize {
+ if (pane.fs.joined_by != 0 and pane.fs.joined_by != handle) pane.fs.joined = null;
+ const take = spliceBody(p, pane, q0, q1, bytes) orelse return null;
+ pane.fs.joined = fileOf(pane).?.revision;
+ pane.fs.joined_by = handle;
+ return take;
+}
+
+/// How long writes in a row may pause before the editor's own step puts
+/// them in: long enough that a stream of 8 KB writes is one edit.
+pub const batch_pause_ns: u64 = 20 * std.time.ns_per_ms;
+
+/// The editor's step: the held writes go in once they have paused.
+pub fn flushPausedBatch(p: *Pardes) void {
+ const b = &p.fs.batch;
+ if (b.bytes.items.len == 0) return;
+ if (p.clock.now_ns != 0 and p.clock.now_ns -| b.last_ns < batch_pause_ns) return;
+ flushBatch(p);
+}
+
+/// Puts the held writes (`fs.batch`) in as one edit: before any other
+/// request, the open's release, or the editor's own step.
+pub fn flushBatch(p: *Pardes) void {
+ const b = &p.fs.batch;
+ if (b.bytes.items.len == 0) return;
+ defer b.bytes.clearRetainingCapacity();
+ const id = p.paneBySerial(b.serial) orelse return;
+ const pane = p.panes[id].?;
+ if (fileOf(pane) == null) return;
+ const before = dotOf(pane);
+ const take = spliceJoined(p, pane, b.at, b.at, b.bytes.items, b.handle) orelse return;
+ setDot(pane, .{
+ .q0 = shiftOne(before.q0, clip(b.at), 0, clip(take)),
+ .q1 = shiftOne(before.q1, clip(b.at), 0, clip(take)),
+ });
+ if (!pane.fs.noscroll) showOffset(pane, b.at + take);
+}
+
+/// How many bytes this open's write holds back (`fs.batch`) for its pane.
+fn heldBytes(p: *Pardes, req: Req, pane: *Pane) usize {
+ const b = &p.fs.batch;
+ return if (b.serial == pane.serial and b.node == req.node and b.handle == req.handle) b.bytes.items.len else 0;
+}
+
+/// Holds a write at `at` on this open with the bytes it goes on from: its
+/// own batch, when it ends right at `at`; any other is put in first. The
+/// bytes taken, or null when the write is not held (one with no record, a
+/// test's handle 0, is put in at once; a hold past 64 MiB is put in first).
+fn holdWrite(p: *Pardes, req: Req, pane: *Pane, at: usize) error{OutOfMemory}!?usize {
+ const b = &p.fs.batch;
+ if (b.bytes.items.len > 0 and !(heldBytes(p, req, pane) > 0 and b.at + b.bytes.items.len == at)) flushBatch(p);
+ if (req.handle == 0 or b.bytes.items.len > 64 << 20) {
+ flushBatch(p);
+ return null;
+ }
+ if (b.bytes.items.len == 0) b.* = .{ .serial = pane.serial, .node = req.node, .handle = req.handle, .at = at, .bytes = b.bytes };
+ const take = wholeUtf8(req.data);
+ try b.bytes.appendSlice(p.gpa, req.data[0..take]);
+ b.last_ns = p.clock.now_ns;
+ return take;
+}
+
+fn writeBody(p: *Pardes, req: Req, id: usize, pane: *Pane) Reply {
+ if (req.data.len == 0) return .{ .tag = req.tag, .written = 0 };
+ if (pane.file == null) {
+ // An image's or a PDF's body is no text a write goes into.
+ if (!pane.isTerminal()) return tree.failText(req.tag, E.INVAL, e_no_body);
+ const take = wholeUtf8(req.data);
+ p.emitWrite(id, req.data[0..take]);
+ return .{ .tag = req.tag, .written = @intCast(take) };
+ }
+ const at = bodyOf(pane).len + heldBytes(p, req, pane);
+ if (holdWrite(p, req, pane, at) catch return Reply.fail(req.tag, E.NOMEM)) |take| return .{ .tag = req.tag, .written = @intCast(take) };
+ const take = spliceJoined(p, pane, at, at, req.data, req.handle) orelse
+ return Reply.fail(req.tag, E.NOMEM);
+ if (!pane.fs.noscroll) showOffset(pane, at + take);
+ return .{ .tag = req.tag, .written = @intCast(take) };
+}
+
+/// Why `data` is no text a tag takes: a control character but a tab or a
+/// newline, DEL, a C1 control, or bytes that are not UTF-8 (a NUL in a tag
+/// made a Dump that wrote nothing).
+pub fn tagFault(data: []const u8) ?[]const u8 {
+ for (data) |c| if ((c < ' ' and c != '\t' and c != '\n') or c == 0x7f) return "invalid tag text: a control character";
+ if (!std.unicode.utf8ValidateSlice(data)) return "invalid tag text: not UTF-8";
+ var i: usize = 0;
+ while (std.mem.indexOfScalarPos(u8, data, i, 0xC2)) |at| : (i = at + 1)
+ if (at + 1 < data.len and data[at + 1] <= 0x9F) return "invalid tag text: a control character";
+ return null;
+}
+
+/// A tag write's limit, the same for a pane's, a column's and the
+/// workspace's: whole or not at all.
+pub const e_tag_over = std.fmt.comptimePrint("no space: over {d} bytes", .{limits.max_tag_tail});
+
+fn writeTag(p: *Pardes, req: Req, pane: *Pane) Reply {
+ if (req.data.len == 0) return .{ .tag = req.tag, .written = 0 };
+ const pf = &pane.fs;
+ // A refused write after a truncation changes nothing: the truncation
+ // it would have come with is dropped too.
+ if (tagFault(req.data)) |why| {
+ pf.tag_trunc_pending = false;
+ return tree.failText(req.tag, E.INVAL, why);
+ }
+ // The tag's own text grows by what is written, newlines and all: a tag
+ // is a text like any other (acme's tag file appends the same way).
+ const had = if (pf.tag_trunc_pending) 0 else tagline.curTail(pane).len;
+ const room = limits.max_tag_tail -| had -| @intFromBool(pf.tag_held_newline and !pf.tag_trunc_pending);
+ // A rewrite drops its one trailing newline: `echo <4096 bytes> > tag`
+ // is 4096 bytes of tag, and fits.
+ const rewrite = pf.tag_rewrite or pf.tag_trunc_pending;
+ const counted = req.data.len - @intFromBool(rewrite and req.data[req.data.len - 1] == '\n');
+ if (counted > room) {
+ pf.tag_trunc_pending = false;
+ return tree.failText(req.tag, E.NOSPC, e_tag_over);
+ }
+ applyTagTruncation(p, pane);
+ const take = wholeUtf8(req.data);
+ // A truncating write drops ONE trailing newline, its whole text's: a
+ // newline held from a write before goes in once more text follows it.
+ if (pf.tag_held_newline) {
+ pane.appendTag("\n") catch return Reply.fail(req.tag, E.NOMEM);
+ pf.tag_held_newline = false;
+ }
+ var text = req.data[0..take];
+ if (pf.tag_rewrite and text.len > 0 and text[text.len - 1] == '\n') {
+ text = text[0 .. text.len - 1];
+ pf.tag_held_newline = true;
+ }
+ pane.appendTag(text) catch return Reply.fail(req.tag, E.NOMEM);
+ return .{ .tag = req.tag, .written = @intCast(take) };
+}
+
+/// A pending truncation of the tag, done: its text cleared as `cleartag`
+/// clears it, the prefix left.
+pub fn applyTagTruncation(p: *Pardes, pane: *Pane) void {
+ const pf = &pane.fs;
+ if (!pf.tag_trunc_pending) return;
+ pf.tag_trunc_pending = false;
+ // An edit like a keyboard one: `u` in the tag brings it back.
+ pane.tag.remember(p.gpa, if (pane.tag.own) |own| .{ .text = own } else null) catch |err|
+ return p.reportError(p.paneBySerial(pane.serial) orelse return, "tag", err);
+ const empty = p.gpa.alloc(u8, 0) catch unreachable; // no byte: the allocator is not asked
+ if (pane.tag.own) |own| p.gpa.free(own);
+ pane.tag.own = empty;
+ // what is left is the prefix; the cursor goes after it
+ pane.tag.cur_row = 0;
+ pane.tag.cur_col = if (tagline.pathPrefix(p, p.scratch.allocator(), pane)) |prefix| @intCast(prefix.len) else |_| 0;
+ pane.tag.vsel.active = false;
+ pane.tag.nsel = 0;
+ pf.tag_rewrite = true;
+ pf.tag_held_newline = false;
+}
+
+/// A write only text takes, to a pane with none: said, as every EINVAL is.
+pub const e_no_text = "invalid write: this pane has no text (a terminal, an image or a PDF)";
+/// A body write to a pane whose body is a picture: a terminal's takes one
+/// (its keys), so the word is not "no text".
+pub const e_no_body = "invalid write: an image's or a PDF's body takes no writes";
+
+fn writeData(p: *Pardes, req: Req, pane: *Pane) Reply {
+ if (fileOf(pane) == null) return tree.failText(req.tag, E.INVAL, e_no_text);
+ const pf = &pane.fs;
+ if (pf.addr_failed) return tree.failText(req.tag, E.INVAL, e_addr_failed);
+ clampAddr(pf, bodyOf(pane).len + heldBytes(p, req, pane));
+ const q0: usize = pf.addr.q0;
+ const q1: usize = @max(q0, @as(usize, pf.addr.q1));
+ // An insert (an empty address) goes on from the open's held bytes.
+ if (q1 == q0) if (holdWrite(p, req, pane, q0) catch return Reply.fail(req.tag, E.NOMEM)) |take| {
+ pf.addr = .{ .q0 = clip(q0 + take), .q1 = clip(q0 + take) };
+ return .{ .tag = req.tag, .written = @intCast(take) };
+ };
+ flushBatch(p);
+ const before = dotOf(pane);
+ const take = spliceJoined(p, pane, q0, q1, req.data, req.handle) orelse
+ return Reply.fail(req.tag, E.NOMEM);
+ setDot(pane, .{
+ .q0 = shiftOne(before.q0, clip(q0), clip(q1 - q0), clip(take)),
+ .q1 = shiftOne(before.q1, clip(q0), clip(q1 - q0), clip(take)),
+ });
+ pf.addr = .{ .q0 = clip(q0 + take), .q1 = clip(q0 + take) };
+ if (!pf.noscroll) showOffset(pane, q0 + take);
+ return .{ .tag = req.tag, .written = @intCast(take) };
+}
+
+fn writeSel(p: *Pardes, req: Req, pane: *Pane) Reply {
+ if (fileOf(pane) == null) return tree.failText(req.tag, E.INVAL, e_no_text);
+ const pf = &pane.fs;
+ // The same open's next write follows its last; any other replaces dot.
+ const going_on = req.handle != 0 and pf.wrsel_by == req.handle;
+ const d = if (going_on) State.Range{ .q0 = pf.wrsel.q1, .q1 = pf.wrsel.q1 } else dotOf(pane);
+ const q0: usize = d.q0;
+ const q1: usize = @max(q0, @as(usize, d.q1));
+ const take = spliceBody(p, pane, q0, q1, req.data) orelse
+ return Reply.fail(req.tag, E.NOMEM);
+ // What was written is selected, as acme's wrsel leaves it: `cat sel`
+ // reads it back.
+ const start = if (going_on) pf.wrsel.q0 else clip(q0);
+ pf.wrsel = .{ .q0 = start, .q1 = clip(q0 + take) };
+ pf.wrsel_by = req.handle;
+ setDot(pane, pf.wrsel);
+ return .{ .tag = req.tag, .written = @intCast(take) };
+}
+
+/// The pair of offsets a range file reads back, so that copying `addr` onto
+/// `dot` or `limit` does what acme spelled `dot=addr` and `limit=addr`.
+fn pairOf(text: []const u8) ?State.Range {
+ var it = std.mem.tokenizeAny(u8, text, " \t");
+ const q0 = std.fmt.parseInt(u32, it.next() orelse return null, 10) catch return null;
+ const q1 = std.fmt.parseInt(u32, it.next() orelse return null, 10) catch return null;
+ if (it.next() != null) return null;
+ return .{ .q0 = q0, .q1 = q1 };
+}
+
+pub const e_no_text_address = "invalid address: this pane has no text to address";
+
+pub const e_addr_failed = "no address: the last one written to addr failed";
+
+/// A range file takes an address expression, or that pair of offsets. One
+/// that does not evaluate says why: `bad address syntax`, `no match for
+/// regexp`, `address out of range`, `bad regular expression`, `addresses
+/// out of order`.
+fn writeRange(req: Req, pane: *Pane, file: PaneFile) Reply {
+ // A terminal, an image or a PDF has no text an address names: refused
+ // alike for addr, dot and limit, before the expression is read.
+ if (fileOf(pane) == null) return tree.failText(req.tag, E.INVAL, e_no_text_address);
+ const pf = &pane.fs;
+ const text = bodyOf(pane);
+ clampAddr(pf, text.len);
+ const expr = std.mem.trimEnd(u8, req.data, "\n");
+ // One that goes from the address (`.`, `+`, `-`) has none to go from
+ // after a failed one: said, rather than going from the one before it.
+ if (file == .addr and pf.addr_failed and expr.len > 0 and std.mem.indexOfScalar(u8, ".+-", expr[0]) != null)
+ return tree.failText(req.tag, E.INVAL, e_addr_failed);
+ var a: addressing.Addr = .{ .text = text, .lim = pf.limit, .expr = expr };
+ // A pair is refused as the address form refuses it, never clamped: one
+ // past the text is out of range, one ending before it starts out of
+ // order (below).
+ var r = if (pairOf(expr)) |pair| pair: {
+ if (pair.q0 > clip(text.len) or pair.q1 > clip(text.len)) {
+ a.err = addressing.e_range;
+ break :pair null;
+ }
+ break :pair pair;
+ } else if (a.address(pf.addr)) |found| (if (a.i < expr.len) null else found) else null;
+ // sam's check, which acme leaves out: `#100,#50` names no range.
+ if (r) |found| if (found.q0 > found.q1) {
+ a.err = addressing.e_order;
+ r = null;
+ };
+ const range = r orelse {
+ if (file == .addr) pf.addr_failed = true;
+ if (file == .limit) if (pf.limit_truncated) |kept| {
+ pf.limit = kept;
+ pf.limit_truncated = null;
+ };
+ if (file == .dot) pf.dot_truncated = false;
+ return tree.failText(req.tag, E.INVAL, a.err);
+ };
+ if (file == .limit) pf.limit_truncated = null;
+ if (file == .dot) pf.dot_truncated = false;
+ switch (file) {
+ .addr => {
+ pf.addr = range;
+ pf.addr_failed = false;
+ },
+ .limit => pf.limit = range,
+ // Setting dot scrolls to it, which is the whole of acme's `show`.
+ .dot => setDot(pane, range),
+ else => unreachable,
+ }
+ return .{ .tag = req.tag, .written = @intCast(req.data.len) };
+}
+
+fn writeFlag(p: *Pardes, req: Req, pane: *Pane, file: PaneFile) Reply {
+ const word = std.mem.trim(u8, req.data, " \t\r\n");
+ if (!std.mem.eql(u8, word, "1") and !std.mem.eql(u8, word, "0")) return tree.failText(req.tag, E.INVAL, "bad flag: takes 1 or 0");
+ const on = word[0] == '1';
+ const pf = &pane.fs;
+ switch (file) {
+ .dirty => {
+ const f = fileOf(pane) orelse return tree.failText(req.tag, E.INVAL, e_no_text);
+ f.saved_revision = if (on) f.revision -% 1 else f.revision;
+ },
+ // acme's nomark joins the writes after it into one undo step. The
+ // step starts here: the text as it is now is what Undo brings back,
+ // and turning mark on again only ends it.
+ .mark => {
+ if (!on and !pf.nomark) panes.File.pushUndo(p, pane) catch return Reply.fail(req.tag, E.NOMEM);
+ pf.nomark = !on;
+ },
+ .scroll => pf.noscroll = !on,
+ else => unreachable,
+ }
+ return .{ .tag = req.tag, .written = @intCast(req.data.len) };
+}
+
+/// acme's words for a name it refuses (editors/acme/xfid.c:650-652), the
+/// reason after them.
+pub const e_name_char = "bad character in file name";
+
+/// What no file name can hold, said: a newline (a name is one line), a
+/// NUL, a component over 255 bytes. Any other byte a file system takes is
+/// taken, blanks, controls and bytes not UTF-8 included, so a name read
+/// from `name` writes back as it was.
+fn nameFault(name: []const u8) ?[]const u8 {
+ if (std.mem.indexOfScalar(u8, name, '\n') != null) return e_name_char ++ ": a newline (a name is one line)";
+ if (std.mem.indexOfScalar(u8, name, 0) != null) return e_name_char ++ ": a NUL";
+ // No file system takes a longer one (NAME_MAX): a Save would only fail.
+ var parts = std.mem.splitScalar(u8, name, '/');
+ while (parts.next()) |part| if (part.len > 255) return "invalid file name: a component over 255 bytes";
+ return null;
+}
+
+fn unnamed(pane: *const Pane) []const u8 {
+ return if (pane.isTerminal())
+ "invalid rename: a terminal is named by its shell's directory; cd there, or Term in another"
+ else
+ "invalid rename: an image or PDF is named by the file it shows";
+}
+
+/// Why a name still held for its newline (tree.zig) can never be taken,
+/// whatever follows: said by the write that held it, not at the close.
+pub fn heldNameFault(p: *Pardes, serial: u32, held: []const u8) ?[]const u8 {
+ const pane = p.panes[p.paneBySerial(serial) orelse return null].?;
+ if (fileOf(pane) == null) return unnamed(pane);
+ var parts = std.mem.splitScalar(u8, held, '/');
+ while (parts.next()) |part| if (part.len > 255) return "invalid file name: a component over 255 bytes";
+ if (held.len >= 4096) return "invalid file name: longer than a path may be";
+ return null;
+}
+
+/// Writing `name` renames the buffer: a relative name resolves against the
+/// pane's directory, as the tag's name field does.
+fn writeName(p: *Pardes, req: Req, id: usize, pane: *Pane) Reply {
+ // One name: its newline ends it, as `echo` writes it, and it is one.
+ const name = if (std.mem.endsWith(u8, req.data, "\n")) req.data[0 .. req.data.len - 1] else req.data;
+ if (name.len == 0) return tree.failText(req.tag, E.INVAL, e_name_char ++ ": an empty name");
+ if (nameFault(name)) |why| return tree.failText(req.tag, E.INVAL, why);
+ // Words 9ns maps to EINVAL, as every refusal of a name here.
+ if (fileOf(pane) == null) return tree.failText(req.tag, E.INVAL, unnamed(pane));
+ var home_buf: [4096]u8 = undefined;
+ const full = std.Io.Dir.path.resolvePosix(p.scratch.allocator(), &.{ pardes.Pardes.paneDir(pane), fs.expandHome(name, &home_buf) }) catch
+ return Reply.fail(req.tag, E.NOMEM);
+ if (!std.Io.Dir.path.isAbsolute(full) or full.len >= 4096) return tree.failText(req.tag, E.INVAL, "invalid file name: longer than a path may be");
+ // A directory (`~`, `/`, `foo/`) is no file to name a pane after: a
+ // Save could only fail. Said now, EISDIR.
+ const is_dir = name[name.len - 1] == '/' or std.mem.eql(u8, full, "/") or
+ (if (fs.localPath(full)) |local| exec.kindOf(local) == .directory else false);
+ if (is_dir) return tree.failText(req.tag, E.ISDIR, std.fmt.bufPrint(&p.fs.ename, "name: {s} is a directory, not a file", .{full[0..@min(full.len, 256)]}) catch &p.fs.ename); // cut to ename's 320
+ nameBuffer(p, id, full, false) catch |err| return Reply.fail(req.tag, switch (err) {
+ error.OutOfMemory => E.NOMEM,
+ else => E.INVAL,
+ });
+ return .{ .tag = req.tag, .written = @intCast(req.data.len) };
+}
+
+/// Change a buffer's absolute name without writing or renaming a disk file.
+/// Tag editing preserves user commands; the filesystem's rename resets its tail.
+pub fn nameBuffer(p: *Pardes, id: usize, full: []const u8, preserve_tag: bool) !void {
+ const pane = p.panes[id] orelse return error.NoPane;
+ const f = fileOf(pane) orelse return error.NotFile;
+ if (!std.Io.Dir.path.isAbsolute(full) or full.len == 0 or full.len >= 4096)
+ return error.InvalidName;
+ if (std.mem.indexOfAny(u8, full, "\x00\n") != null) return error.InvalidName;
+ if (std.mem.eql(u8, f.path, full)) return;
+ const copy = try p.gpa.dupe(u8, full);
+ // The name it ends is kept for an undo back across this rename.
+ panes.File.noteRenamed(p.gpa, f.history, f.path);
+ f.path = copy;
+ if (panes.Output.fileTraits(f.output).saves) {
+ f.output = null;
+ pane.clearCwd();
+ if (!preserve_tag) {
+ if (pane.tag.own) |own| p.gpa.free(own);
+ pane.tag.own = null;
+ }
+ // A name alone is no edit: dirty stays what the text made it, as
+ // the guards ask only whether it was ever edited, so /index, Exit
+ // and Restore agree. Save writes it under the new name all the same.
+ f.watch_after_save = fs.localPath(full) != null;
+ }
+ if (f.highlights.len > 0) p.tree_sitter_gpa.free(f.highlights);
+ f.highlights = &.{};
+ f.highlight_start = 0;
+ f.syntax_dirty = true;
+ f.context.revision = null;
+ pane.geometry_key = 0;
+ look.invalidateLookHover(p, id);
+ p.emit(.{ .watch = .{ .pane = @intCast(id), .on = false } });
+ events.noteLog(p, .rename, pane);
+ if (f.output == null and pardes.Pardes.recentKeeps(f.path)) p.recent.opened(p.recentGpa(), f.path);
+}
+
+/// Diagnostics go to the +Errors buffer of the pane's directory.
+pub fn appendErrors(p: *Pardes, id: usize, text: []const u8) ?usize {
+ if (text.len == 0) return 0;
+ const pane = p.panes[id] orelse return null;
+ const cwd = pane.cwdSlice();
+ const dir = if (pane.file) |*f| panes.Dir.ofName(f.path) else if (cwd.len > 0) cwd else "/";
+ for (p.panes) |slot| {
+ const q = slot orelse continue;
+ const qf = fileOf(q) orelse continue;
+ const o = qf.output orelse continue;
+ if (std.meta.activeTag(o.from) != .errors) continue;
+ if (!std.mem.eql(u8, std.Io.Dir.path.dirname(qf.path) orelse "", dir)) continue;
+ return spliceBody(p, q, qf.content.len, qf.content.len, text);
+ }
+ const free = p.freeSlot() orelse return null;
+ const content = p.gpa.dupe(u8, text) catch return null;
+ _ = panes.Output.open(p, free, dir, .errors, "", content) catch {
+ p.gpa.free(content);
+ return null;
+ };
+ layout.placeNew(p, id, id, free, .errors);
+ // No column had room for it (it closes at the step's end): the text is
+ // logged instead, a msg a line, so it is not lost and nothing fails.
+ if (p.unplaced.isSet(free)) {
+ var lines = std.mem.splitScalar(u8, std.mem.trimEnd(u8, text, "\n"), '\n');
+ while (lines.next()) |line| events.noteMessage(p, pane.serial, line[0..@min(line.len, pardes.Messages.LoggedMessage.cap)]);
+ }
+ return text.len;
+}
+
+/// Truncation empties whatever the file holds: the body, the tag's editable
+/// tail (acme's `cleartag`), a range. `data` and `xdata` hold what `addr`
+/// addresses, so truncating one deletes that range and no more, and a
+/// shell's `echo new > data` replaces it. Every other setattr just answers
+/// fresh attributes.
+pub fn truncate(p: *Pardes, pane: *Pane, file: PaneFile) tree.Status {
+ const pf = &pane.fs;
+ switch (file) {
+ .body => if (fileOf(pane) != null) {
+ pf.joined = null;
+ const was = fileOf(pane).?.revision;
+ _ = spliceBody(p, pane, 0, bodyOf(pane).len, "") orelse return .err;
+ // An empty body truncated is no edit: the write after it makes
+ // the step, rather than join one that was never pushed.
+ pf.joined = if (fileOf(pane).?.revision != was) fileOf(pane).?.revision else null;
+ pf.joined_by = 0;
+ pf.addr = .{};
+ setDot(pane, .{});
+ },
+ .data, .xdata => if (fileOf(pane) != null) {
+ clampAddr(pf, bodyOf(pane).len);
+ const q0 = pf.addr.q0;
+ const q1 = @max(q0, pf.addr.q1);
+ const before = dotOf(pane);
+ pf.joined = null;
+ const was = fileOf(pane).?.revision;
+ _ = spliceBody(p, pane, q0, q1, "") orelse return .err;
+ pf.joined = if (fileOf(pane).?.revision != was) fileOf(pane).?.revision else null;
+ pf.joined_by = 0;
+ setDot(pane, .{ .q0 = shiftOne(before.q0, q0, q1 - q0, 0), .q1 = shiftOne(before.q1, q0, q1 - q0, 0) });
+ pf.addr = .{ .q0 = q0, .q1 = q0 };
+ },
+ // Done with the write after it, which may yet be refused.
+ .tag => pf.tag_trunc_pending = true,
+ // A shell's `>` truncates before it writes: the address written
+ // is evaluated from where the last one left off, as with `>>`.
+ // `0` (or `,`) is how to start over. See State.addr.
+ .addr => {},
+ .limit => {
+ pf.limit_truncated = pf.limit;
+ pf.limit = null;
+ },
+ .dot => pf.dot_truncated = fileOf(pane) != null,
+ // `>` starts the rows over, as a write at 0 does.
+ .rows => if (fileOf(pane)) |f| panes.File.setRows(p, f, &.{}) catch unreachable,
+ else => {},
+ }
+ return .ok;
+}
+
+// ---- tests ----
+
+const testing = std.testing;
+const th = @import("testing.zig");
+const call = th.call;
+const rd = th.rd;
+const wr = th.wr;
+const withFile = th.withFile;
+const serialOf = th.serialOf;
+const Status = tree.Status;
+
+test "rows through the line index are the ones counting newlines gives, at every offset" {
+ const p = try withFile(testing.allocator, "héllo\nwo\u{301}rld\n\n last line é\ntail");
+ defer p.deinit();
+ const pane = p.panes[0].?;
+ const f = &pane.file.?;
+ _ = try panes.File.lineIndex(p.gpa, f);
+ const text = bodyOf(pane);
+ try testing.expect(lineIndex(pane, text) != null);
+ for (0..text.len + 2) |off| {
+ try testing.expectEqual(modal.positionAt(text, off), positionAt(pane, text, off));
+ try testing.expectEqual(modal.runePositionAt(text, off), runePositionAt(pane, text, off));
+ }
+ for (0..8) |row| for (0..16) |col| {
+ const c: modal.Cursor = .{ .row = row, .col = col };
+ try testing.expectEqual(modal.runeOffsetAt(text, c), runeOffsetAt(pane, text, c));
+ };
+}
+
+test "a terminal's body stats as long as it reads" {
+ if (pardes.Term.ops == null) return error.SkipZigTest; // a shell
+ const gpa = testing.allocator;
+ const p = try pardes.Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24 });
+ defer p.deinit();
+ while (p.nextEffect()) |_| {}
+ const pane = p.panes[0].?;
+ try testing.expect(pane.isTerminal());
+ p.update(.{ .output = .{ .pane = 0, .bytes = "$ ls\r\nalpha beta\r\n$ " } });
+ const body = Node.of(pane.serial, .body);
+ const whole = rd(p, body, 0, 1 << 16);
+ try testing.expect(whole.bytes.len > 0);
+ try testing.expectEqual(@as(u64, whole.bytes.len), call(p, .{ .tag = 1, .op = .getattr, .node = body }).reply.attr.size);
+}
+
+test "a body write to a terminal pane types at its shell" {
+ if (pardes.Term.ops == null) return error.SkipZigTest; // a shell
+ const gpa = testing.allocator;
+ const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 40, .rows = 10 });
+ defer p.deinit();
+ while (p.nextEffect()) |_| {}
+ const pane = p.panes[0].?;
+ try testing.expect(pane.isTerminal());
+
+ const a = wr(p, Node.of(pane.serial, .body), "ls -l\r");
+ try testing.expectEqual(@as(u32, 6), a.reply.written);
+ try testing.expectEqualStrings("ls -l\r", a.pty());
+
+ const r = rd(p, Node.of(pane.serial, .body), 0, 64);
+ try testing.expectEqual(Status.ok, r.reply.status);
+}
+
+test "data never splits a rune, in either direction" {
+ const gpa = testing.allocator;
+ const p = try withFile(gpa, "\u{00e9}x\n");
+ defer p.deinit();
+ const serial = serialOf(p);
+ _ = wr(p, Node.of(serial, .addr), "#0");
+ try testing.expectEqualStrings("", rd(p, Node.of(serial, .data), 0, 1).bytes);
+ _ = wr(p, Node.of(serial, .addr), "#0");
+ try testing.expectEqualStrings("\u{00e9}", rd(p, Node.of(serial, .data), 0, 2).bytes);
+
+ _ = wr(p, Node.of(serial, .addr), "#0");
+ try testing.expectEqual(@as(u32, 1), wr(p, Node.of(serial, .data), "a\xC3").reply.written);
+}
+
+test "the writes of one open are one undo step, as bash's line-buffered printf makes them; the next open is another" {
+ const p = try withFile(testing.allocator, "one\n");
+ defer p.deinit();
+ const serial = serialOf(p);
+ for ([_]u64{ Node.of(serial, .data), Node.of(serial, .body), Node.of(serial, .xdata) }) |node| {
+ _ = wr(p, Node.of(serial, .addr), "$");
+ for ([_][]const u8{ "x\n", "y\n", "z\n" }) |piece| try testing.expectEqual(Status.ok, wr(p, node, piece).reply.status);
+ _ = call(p, .{ .tag = 3, .op = .release, .node = node });
+ // A second open: its own step.
+ _ = wr(p, Node.of(serial, .addr), "$");
+ try testing.expectEqual(Status.ok, wr(p, node, "w\n").reply.status);
+ _ = call(p, .{ .tag = 3, .op = .release, .node = node });
+ try testing.expectEqual(Status.ok, wr(p, Node.of(serial, .ctl), "Undo").reply.status);
+ try testing.expectEqualStrings("one\nx\ny\nz\n", rd(p, Node.of(serial, .body), 0, 64).bytes);
+ try testing.expectEqual(Status.ok, wr(p, Node.of(serial, .ctl), "Undo").reply.status);
+ try testing.expectEqualStrings("one\n", rd(p, Node.of(serial, .body), 0, 64).bytes);
+ }
+}
+
+test "writes held before the shell's clock is first seen go in at its first step" {
+ const p = try withFile(testing.allocator, "one\n");
+ defer p.deinit();
+ const body = Node.of(serialOf(p), .body);
+ try testing.expect(!p.clock.started);
+ const h = call(p, .{ .tag = 1, .op = .open, .node = body, .omode = 1 }).reply.handle;
+ const revision = p.panes[0].?.file.?.revision;
+ _ = call(p, .{ .tag = 2, .op = .write, .node = body, .handle = h, .data = "x\n" });
+ try testing.expectEqual(@as(u64, 0), p.fs.batch.last_ns);
+ // A detached host's first step: its clock is days into the machine's.
+ p.advance(700_000 * std.time.ns_per_s);
+ flushPausedBatch(p);
+ try testing.expectEqual(revision + 1, p.panes[0].?.file.?.revision);
+}
+
+test "a tag write past the limit is refused whole, naming the limit" {
+ const p = try withFile(testing.allocator, "x\n");
+ defer p.deinit();
+ const tag = Node.of(serialOf(p), .tag);
+ const before = try testing.allocator.dupe(u8, rd(p, tag, 0, 1 << 16).bytes);
+ defer testing.allocator.free(before);
+ const big = &@as([limits.max_tag_tail + 10]u8, @splat('w'));
+ const r = wr(p, tag, big);
+ try testing.expectEqual(E.NOSPC, r.errno());
+ // `no space` is what 9ns maps to ENOSPC, so a shell through a mount
+ // sees the errno the tree gives.
+ try testing.expect(std.mem.startsWith(u8, r.reply.ename, "no space: over "));
+ try testing.expectEqualStrings(before, rd(p, tag, 0, 1 << 16).bytes);
+}
+
+test "two opens writing one body are two undo steps, however their writes interleave" {
+ const p = try withFile(testing.allocator, "one\n");
+ defer p.deinit();
+ const serial = serialOf(p);
+ const body = Node.of(serial, .body);
+ const a = call(p, .{ .tag = 1, .op = .open, .node = body, .omode = 1 }).reply.handle;
+ const b = call(p, .{ .tag = 1, .op = .open, .node = body, .omode = 1 }).reply.handle;
+ try testing.expect(a != 0 and b != 0 and a != b);
+ _ = call(p, .{ .tag = 2, .op = .write, .node = body, .handle = a, .data = "a\n" });
+ _ = call(p, .{ .tag = 2, .op = .write, .node = body, .handle = a, .data = "b\n" });
+ _ = call(p, .{ .tag = 2, .op = .write, .node = body, .handle = b, .data = "c\n" });
+ try testing.expectEqual(Status.ok, wr(p, Node.of(serial, .ctl), "Undo").reply.status);
+ try testing.expectEqualStrings("one\na\nb\n", rd(p, body, 0, 64).bytes);
+ try testing.expectEqual(Status.ok, wr(p, Node.of(serial, .ctl), "Undo").reply.status);
+ try testing.expectEqualStrings("one\n", rd(p, body, 0, 64).bytes);
+ _ = call(p, .{ .tag = 3, .op = .release, .node = body, .handle = a, .opened = true });
+ _ = call(p, .{ .tag = 3, .op = .release, .node = body, .handle = b, .opened = true });
+}
+
+test "after a failed address, one that goes from it says there is none" {
+ const p = try withFile(testing.allocator, "one\ntwo\n");
+ defer p.deinit();
+ const addr = Node.of(serialOf(p), .addr);
+ try testing.expectEqual(Status.err, wr(p, addr, "/nomatch/").reply.status);
+ try testing.expectEqualStrings(e_addr_failed, wr(p, addr, ".+1").reply.ename);
+ try testing.expectEqualStrings(e_addr_failed, wr(p, addr, "+1").reply.ename);
+ // An absolute one sets it again, and then `.` works.
+ try testing.expectEqual(Status.ok, wr(p, addr, "2").reply.status);
+ try testing.expectEqual(Status.ok, wr(p, addr, ".").reply.status);
+}
+
+// The rest moved to test/behaviour/panes.zig; a Save's failure and the
+// watches a rename asks for are effects a host performs.
+test "a long path's failed Save keeps its reason" {
+ const p = try withFile(testing.allocator, "x\n");
+ defer p.deinit();
+ const serial = serialOf(p);
+ // A Save of a 3000-byte path the host refuses: the waiting write's
+ // reason is at the end, the path giving up its middle.
+ // (Under /tmp: under / a user's Save is refused permission, not
+ // missing.)
+ const segment = &@as([200]u8, @splat('d')) ++ "/";
+ const long = "/tmp/nonexistent-pardes-root/" ++ std.mem.asBytes(&@as([15][201]u8, @splat(segment.*))) ++ "f.txt";
+ const id = p.paneBySerial(serial).?;
+ try nameBuffer(p, id, long, false);
+ p.fs.late_failure_len = 0;
+ p.saveFailed(@intCast(id), long, error.AccessDenied);
+ const late = p.fs.late_failure[0..p.fs.late_failure_len];
+ try testing.expect(std.mem.startsWith(u8, late, "Save /tmp/nonexistent-pardes-root/"));
+ try testing.expect(std.mem.endsWith(u8, late, "/f.txt: no such directory"));
+}
+
+test "a scratch renamed to a file watches it only after its Save, and a virtual name never" {
+ const p = try withFile(testing.allocator, "opener\n");
+ defer p.deinit();
+ const serial = try th.newPane(p);
+ const pane = p.panes[p.paneBySerial(serial).?].?;
+ const name = Node.of(serial, .name);
+ var tmp = testing.tmpDir(.{});
+ defer tmp.cleanup();
+ var directory_buf: [4096]u8 = undefined;
+ const directory = directory_buf[0..try tmp.dir.realPath(testing.io, &directory_buf)];
+ var line: [4120]u8 = undefined;
+ const renamed = wr(p, name, try std.fmt.bufPrint(&line, "{s}/renamed.zig\n", .{directory}));
+ try testing.expectEqual(false, renamed.watch.?);
+ try testing.expect(pane.file.?.watch_after_save);
+ const virtual = try th.newPane(p);
+ _ = wr(p, Node.of(virtual, .name), try std.fmt.bufPrint(&line, "/virtual/pane/{d}/body\n", .{serial}));
+ const unchanged = wr(p, Node.of(virtual, .name), "./body\n");
+ try testing.expect(unchanged.watch == null);
+ try testing.expect(!p.panes[p.paneBySerial(virtual).?].?.file.?.watch_after_save);
+}
+
+test "a replace through data, truncate then write, is one undo step" {
+ const p = try withFile(testing.allocator, "one two\n");
+ defer p.deinit();
+ const serial = serialOf(p);
+ _ = wr(p, Node.of(serial, .addr), "/two/");
+ _ = call(p, .{ .tag = 1, .op = .setattr, .node = Node.of(serial, .data), .truncate = true });
+ try testing.expectEqual(Status.ok, wr(p, Node.of(serial, .data), "2").reply.status);
+ try testing.expectEqualStrings("one 2\n", rd(p, Node.of(serial, .body), 0, 64).bytes);
+ try testing.expectEqual(Status.ok, wr(p, Node.of(serial, .ctl), "Undo").reply.status);
+ try testing.expectEqualStrings("one two\n", rd(p, Node.of(serial, .body), 0, 64).bytes);
+}
+
+test "writes under mark 0 are one undo step, even with no history before them" {
+ const p = try withFile(testing.allocator, "one\n");
+ defer p.deinit();
+ const serial = serialOf(p);
+ const body = Node.of(serial, .body);
+ try testing.expectEqual(Status.ok, wr(p, Node.of(serial, .mark), "0").reply.status);
+ _ = wr(p, body, "two\n");
+ _ = wr(p, body, "three\n");
+ try testing.expectEqual(Status.ok, wr(p, Node.of(serial, .mark), "1").reply.status);
+ try testing.expectEqualStrings("one\ntwo\nthree\n", rd(p, body, 0, 64).bytes);
+ try testing.expectEqual(Status.ok, wr(p, Node.of(serial, .ctl), "Undo").reply.status);
+ try testing.expectEqualStrings("one\n", rd(p, body, 0, 64).bytes);
+ try testing.expectEqual(Status.ok, wr(p, Node.of(serial, .ctl), "Redo").reply.status);
+ try testing.expectEqualStrings("one\ntwo\nthree\n", rd(p, body, 0, 64).bytes);
+}
+
+test "owned cwd name promotion releases the former directory" {
+ const p = try th.withTerm(testing.allocator);
+ defer p.deinit();
+ p.newScratchBelow(0);
+ const id = p.view().active;
+ const pane = p.panes[id].?;
+ try pane.setOwnedCwd("/old/directory");
+ const result = wr(p, Node.of(pane.serial, .name), "saved.txt\n");
+ try testing.expectEqual(Status.ok, result.reply.status);
+ try testing.expect(pane.cwd == .none);
+ try testing.expect(pane.file.?.output == null);
+ try testing.expectEqualStrings("/old/directory/saved.txt", pane.file.?.path);
+ try testing.expectEqualStrings("/old/directory", Pardes.paneDir(pane));
+}
+
+test "a limit write that fails keeps the limit a truncation cleared before it" {
+ const gpa = testing.allocator;
+ const p = try withFile(gpa, "one two\n");
+ defer p.deinit();
+ const limit = Node.of(serialOf(p), .limit);
+ _ = wr(p, limit, "#0,#3");
+ _ = call(p, .{ .tag = 1, .op = .setattr, .node = limit, .truncate = true });
+ try testing.expectEqual(Status.err, wr(p, limit, "/nomatch/").reply.status);
+ try testing.expectEqualStrings(" 0 3 ", rd(p, limit, 0, 100).bytes);
+ // A truncation with no write after it clears it.
+ _ = call(p, .{ .tag = 2, .op = .setattr, .node = limit, .truncate = true });
+ _ = call(p, .{ .tag = 3, .op = .release, .node = limit });
+ try testing.expectEqualStrings("", rd(p, limit, 0, 100).bytes);
+}
+
+test "index names a command's pane cmd, a shell's term" {
+ if (pardes.Term.ops == null) return error.SkipZigTest; // a command pane
+ const p = try withFile(testing.allocator, "x\n");
+ defer p.deinit();
+ try testing.expectEqual(Status.ok, wr(p, Node.of(serialOf(p), .exec), "true\n").reply.status);
+ const ran = p.panes[p.paneBySerial(p.fs.results[0]).?].?;
+ try testing.expectEqualStrings("cmd", kindOf(ran));
+ const shell = try p.newShell(p.freeSlot().?, "/tmp");
+ try testing.expectEqualStrings("term", kindOf(shell));
+}
+
+test "rows: a pane's rows read as lines, written whole or across writes, refused when its text cannot hold them" {
+ const gpa = testing.allocator;
+ const p = try withFile(gpa, "a.txt:3 one\n two\n");
+ defer p.deinit();
+ const rows = Node.of(serialOf(p), .rows);
+ try testing.expectEqualStrings("", rd(p, rows, 0, 4096).bytes);
+ const text = "m 3 0 0 0 0 7 8 3:0+3=keyword.add a.txt\ncd 0 0 0 0 0 0 0 - \n";
+ try testing.expectEqual(Status.ok, wr(p, rows, text).reply.status);
+ try testing.expectEqualStrings(text, rd(p, rows, 0, 4096).bytes);
+ const f = &p.panes[0].?.file.?;
+ try testing.expectEqual(@as(usize, 2), f.location_rows.len);
+ try testing.expectEqualStrings("a.txt", f.location_rows[0].path);
+ try testing.expect(f.location_rows[1].declaration and f.location_rows[1].kind == .context);
+ // A write at 0 starts them over; one open's writes, cut mid-line,
+ // make one set of rows, its later writes following its first.
+ const h = call(p, .{ .tag = 1, .op = .open, .node = rows, .omode = 1 }).reply.handle;
+ try testing.expectEqual(Status.ok, call(p, .{ .tag = 2, .op = .write, .node = rows, .handle = h, .off = 0, .data = "m 3 0 0 0 0 7 8 - a.t" }).reply.status);
+ try testing.expectEqual(Status.ok, call(p, .{ .tag = 3, .op = .write, .node = rows, .handle = h, .off = 21, .data = "xt\np 4 0 0 0 0 0 0 - a.txt\n" }).reply.status);
+ _ = call(p, .{ .tag = 4, .op = .release, .node = rows, .handle = h });
+ try testing.expectEqualStrings("m 3 0 0 0 0 7 8 - a.txt\np 4 0 0 0 0 0 0 - a.txt\n", rd(p, rows, 0, 4096).bytes);
+ // More rows than lines, an offset or styles past a line's end, a line
+ // that is no row: refused, the rows as they were.
+ for ([_][]const u8{ "m 1 0 0 0 0 0 0 - a\nm 1 0 0 0 0 0 0 - a\nm 1 0 0 0 0 0 0 - a\nm 1 0 0 0 0 0 0 - a\n", "m 1 0 0 0 0 12 0 - a\n", "m 1 0 0 0 0 0 8 9:0+1=add a\n", "q 1 0 0 0 0 0 0 - a\n", "m 1 0 0 0 0 0 0 - a" }) |bad|
+ try testing.expectEqual(Status.err, wr(p, rows, bad).reply.status);
+ try testing.expectEqual(@as(usize, 2), f.location_rows.len);
+ // `>` truncates: no rows.
+ _ = call(p, .{ .tag = 5, .op = .setattr, .node = rows, .truncate = true });
+ try testing.expectEqualStrings("", rd(p, rows, 0, 4096).bytes);
+ // An edit drops them.
+ try testing.expectEqual(Status.ok, wr(p, rows, text).reply.status);
+ try testing.expectEqual(Status.ok, wr(p, Node.of(serialOf(p), .body), "more\n").reply.status);
+ try testing.expectEqual(@as(usize, 0), f.location_rows.len);
+}
+
+test "rows: a +Search's rows read back as the addresses its text shows" {
+ const gpa = testing.allocator;
+ const p = try withFile(gpa, "x\n");
+ defer p.deinit();
+ try panes.Output.fillResults(p, 0, "/tmp", .search, "foo", try p.gpa.dupe(u8, "a.txt:1:1 foo\nb.txt:2:3 foo\n"), null);
+ const serial = for (p.panes) |slot| {
+ const pane = slot orelse continue;
+ const f = pane.file orelse continue;
+ if (f.output != null and f.location_rows.len > 0) break pane.serial;
+ } else return error.NoSearch;
+ const text = rd(p, Node.of(serial, .rows), 0, 4096).bytes;
+ try testing.expect(std.mem.indexOf(u8, text, "m 1 1 ") == 0);
+ try testing.expect(std.mem.indexOf(u8, text, " a.txt\n") != null and std.mem.indexOf(u8, text, "\nm 2 3 ") != null and std.mem.endsWith(u8, text, " b.txt\n"));
+}
diff --git a/core/ninep/pty.zig b/core/ninep/pty.zig
new file mode 100644
index 00000000..a66d9f23
--- /dev/null
+++ b/core/ninep/pty.zig
@@ -0,0 +1,1198 @@
+//! A terminal pane's pty/: ctl (winsize, sig, exec), status and the raw data stream.
+const std = @import("std");
+const pardes = @import("../root.zig");
+const tree = @import("tree.zig");
+const pane_files = @import("pane.zig");
+
+const Pardes = pardes.Pardes;
+const Pane = pardes.Pane;
+const Req = tree.Req;
+const Reply = tree.Reply;
+const E = tree.E;
+const PaneFile = tree.PaneFile;
+
+pub fn fileNamed(name: []const u8) ?PaneFile {
+ return switch (std.meta.stringToEnum(enum { ctl, status, data, run }, name) orelse return null) {
+ .ctl => .pty_ctl,
+ .status => .pty_status,
+ .data => .pty_data,
+ .run => .pty_run,
+ };
+}
+
+const Verb = enum { winsize, sig, exec };
+
+fn dimension(word: []const u8) ?u16 {
+ if (word.len == 0 or word.len > 5) return null;
+ for (word) |c| if (c < '0' or c > '9') return null;
+ const n = std.fmt.parseInt(u16, word, 10) catch return null;
+ return if (n == 0 or n > winsize_max) null else n;
+}
+
+/// The fewest rows a winsize write gives a terminal's pty.
+pub const pty_rows_min = 2;
+
+/// As the root ctl's `size` (4096 a side).
+const winsize_max = 4096;
+const e_winsize_range = std.fmt.comptimePrint("invalid winsize: out of range, 1x{d} to {d}x{d}", .{ pty_rows_min, winsize_max, winsize_max });
+const e_winsize_rows = std.fmt.comptimePrint("invalid winsize: at least {d} rows", .{pty_rows_min});
+
+fn signalNamed(word: []const u8) ?pardes.PtySignal {
+ return switch (std.meta.stringToEnum(enum { INT, TERM, HUP, QUIT, KILL }, word) orelse return null) {
+ .INT => .int,
+ .TERM => .term,
+ .HUP => .hup,
+ .QUIT => .quit,
+ .KILL => .kill,
+ };
+}
+
+pub fn writeCtl(p: *Pardes, req: Req, id: usize) Reply {
+ for ([2]bool{ false, true }) |apply| {
+ var it = std.mem.splitScalar(u8, req.data, '\n');
+ while (it.next()) |raw| {
+ const line = std.mem.trim(u8, raw, " \t\r");
+ if (line.len == 0) continue;
+ if (!apply and std.mem.eql(u8, line, "exec")) if (p.panes[id]) |pane| {
+ // A command pane's child is its command, done or running: exec
+ // would run its line again with no header, footer or records.
+ if (pane.command != null) return tree.failText(req.tag, E.INVAL, "invalid exec: a command pane does not restart");
+ // A shell restarted where the directory is gone would not start:
+ // refused before anything runs, as Term there is.
+ const dir = pane.cwdSlice();
+ if (pardes.exec.missingDir(p, dir))
+ return tree.failText(req.tag, E.NOENT, std.fmt.bufPrint(&p.fs.ename, "exec: {s}: no such directory", .{dir[0..@min(dir.len, 256)]}) catch &p.fs.ename); // cut to ename's 320
+ // Nor is a shell that is not there, or a script whose
+ // interpreter is not: refused, and the running shell kept.
+ const bin = pane.shell orelse p.shellBin();
+ var why: [320]u8 = undefined;
+ if (pardes.tape.value(.shell, @import("dev").host_io.Shell.refusal, .{ bin[0..@min(bin.len, 200)], &why })) |refused|
+ return tree.failText(req.tag, E.NOENT, std.fmt.bufPrint(&p.fs.ename, "exec: {s}", .{refused[0..@min(refused.len, 300)]}) catch &p.fs.ename); // cut to ename's 320
+ };
+ if (verb(p, id, line, apply)) |why| return tree.failText(req.tag, E.INVAL, why);
+ }
+ }
+ return .{ .tag = req.tag, .written = @intCast(req.data.len) };
+}
+
+/// The refusal of one pty/ctl line, or null when it is taken (and, with
+/// `apply`, done).
+fn verb(p: *Pardes, id: usize, line: []const u8, apply: bool) ?[]const u8 {
+ const pane = p.panes[id] orelse return e_bad_pty_ctl;
+ var words = std.mem.tokenizeAny(u8, line, " \t");
+ const v = std.meta.stringToEnum(Verb, words.next() orelse return e_bad_pty_ctl) orelse return e_bad_pty_ctl;
+ switch (v) {
+ .winsize => {
+ const c = words.next() orelse return e_bad_pty_ctl;
+ const r = words.next() orelse return e_bad_pty_ctl;
+ if (words.next() != null) return e_bad_pty_ctl;
+ // Numbers that are no sizes are said as such, not as a bad line.
+ _ = std.fmt.parseInt(u32, c, 10) catch return e_bad_pty_ctl;
+ _ = std.fmt.parseInt(u32, r, 10) catch return e_bad_pty_ctl;
+ const cols = dimension(c) orelse return e_winsize_range;
+ const rows = dimension(r) orelse return e_winsize_range;
+ // Two rows at least, as a pane is laid out: a one-row pty
+ // loses its prompt's input mark and reads busy for ever. Fewer
+ // is refused, never quietly raised.
+ if (rows < pty_rows_min) return e_winsize_rows;
+ if (!apply) return null;
+ p.emit(.{ .resize_pty = .{ .pane = @intCast(id), .cols = cols, .rows = rows } });
+ pane.fs.winsize = .{ cols, rows };
+ },
+ .sig => {
+ const which = signalNamed(words.next() orelse return e_bad_pty_ctl) orelse return e_bad_pty_ctl;
+ if (words.next() != null) return e_bad_pty_ctl;
+ if (!apply) return null;
+ p.emit(.{ .signal_pty = .{ .pane = @intCast(id), .serial = pane.serial, .sig = which } });
+ },
+ .exec => {
+ if (words.next() != null) return e_bad_pty_ctl;
+ if (pane.cwdSlice().len > pardes.effect_path_cap) return e_bad_pty_ctl;
+ if (!apply) return null;
+ p.emitSpawn(id, pane.serial, pane.cwdSlice());
+ },
+ }
+ return null;
+}
+
+/// ctl reads back its state in the words it takes, as a Plan 9 ctl does.
+pub fn readCtl(p: *Pardes, req: Req, pane: *Pane) Reply {
+ const size = winsize(pane);
+ p.fs.stage(p.gpa).print(p.gpa, "winsize {d} {d}\n", .{ size[0], size[1] }) catch
+ return Reply.fail(req.tag, E.NOMEM);
+ return tree.stagedReply(p, req);
+}
+
+/// The pty's size: what ctl's winsize set, else the pane's grid.
+pub fn winsize(pane: *const Pane) [2]u16 {
+ return pane.fs.winsize orelse .{ pane.cols, pane.rows };
+}
+
+/// Three right-aligned fields: the pty's cols and rows, and busy: whether a
+/// run written now would be told `busy` (a command runs, or text is typed at
+/// the prompt). A newline ends the line, as a Plan 9 status file's does.
+pub const status_len: u64 = 36;
+
+pub fn readStatus(p: *Pardes, req: Req, id: usize, pane: *Pane) Reply {
+ // Busy is what a run written now would be told: a command is running
+ // or a line is typed at the prompt. Before the shell's first prompt a
+ // run waits for it rather than answer busy, so that is not busy.
+ const marks = pardes.Term.prompt(pane.terminal);
+ const busy = p.hostTtyTaken(id) or (!pane.fs.unmarked and (waitingRun(p, pane) != null or
+ (marks.prompts > 0 and (marks.phase != .input or !marks.input_empty))));
+ const out = p.fs.stage(p.gpa);
+ const size = winsize(pane);
+ out.print(p.gpa, "{d:>11} {d:>11} {d:>11}\n", .{ size[0], size[1], @intFromBool(busy) }) catch return Reply.fail(req.tag, E.NOMEM);
+ return tree.stagedReply(p, req);
+}
+
+// ---- run: one command line in, how it ended out ----
+//
+// factotum's rpc shape (factotum(4)): write a request on an open, read the
+// answer on that same open, so the open is what ties a result to its
+// command. The shell's own OSC 133 marks say when the command started (C)
+// and ended (D, with its status); pardes injects them into bash and fish.
+
+/// The most of a command's output an answer carries: its last this-many
+/// bytes, since that is where a failure says what went wrong.
+pub const output_cap = 64 * 1024;
+
+/// The most rows above a command's end its output is read from: `output_cap`
+/// at eight bytes a row. The answer is made on the editor's thread, which
+/// would otherwise render a command's whole 16 MiB of history to keep 64 KiB.
+pub const output_rows = output_cap / 8;
+
+/// What an open of run holds (tree.zig's open records).
+pub const Run = struct {
+ /// `waiting`: the line is kept until the shell's first prompt (a new
+ /// terminal's shell takes a moment to draw it), then sent.
+ phase: enum { idle, waiting, sent, done } = .idle,
+ /// The line, gpa-owned, while it waits to be sent.
+ line: []u8 = &.{},
+ /// The shell's command count its C must reach for the end to be ours.
+ want: u32 = 0,
+ /// The shell's prompt count when the line went: a newer prompt with no
+ /// C for it means the shell never ran the line.
+ prompts: u32 = 0,
+ /// The shell's count of lines it handled without running when the line
+ /// went.
+ declined: u32 = 0,
+ /// How the refused line is being taken back.
+ cleared: enum { no, kept_line, continuation } = .no,
+ /// How much of the answer this open has read. A stream: a shell's
+ /// `exec 3<>run` shares one offset between the write and the read, so
+ /// the offset a read arrives with means nothing (acme's event file and
+ /// Plan 9's kprint read the same way).
+ read: usize = 0,
+ /// The first line: how it ended.
+ answer: [96]u8 = undefined,
+ len: u8 = 0,
+ /// Then what the command printed, gpa-owned.
+ output: []u8 = &.{},
+};
+
+fn answer(p: *Pardes, slot: *Run, comptime fmt: []const u8, args: anytype) void {
+ // A program's name comes from the host, whatever its length: an answer
+ // longer than the room is cut, its newline kept, never a panic.
+ var w: std.Io.Writer = .fixed(&slot.answer);
+ w.print(fmt ++ "\n", args) catch {
+ slot.answer[slot.answer.len - 1] = '\n';
+ };
+ slot.len = @intCast(w.end);
+ slot.phase = .done;
+ p.fs.news = true; // the read held on it can be answered
+}
+
+pub fn writeRun(p: *Pardes, req: Req, id: usize, pane: *Pane) Reply {
+ const slot = &(tree.openOf(p, req) orelse return Reply.fail(req.tag, E.INVAL)).what.run;
+ if (slot.phase == .sent or slot.phase == .waiting) return tree.failText(req.tag, E.BUSY, tree.e_in_use);
+ // One line a run, its answer read before the next: a second line (bash
+ // writes printf 'a\nb\n' a line at a time) would run and lose the
+ // first's answer.
+ const line = std.mem.trimEnd(u8, req.data, "\r\n");
+ if (std.mem.indexOfScalar(u8, line, '\n') != null or (slot.phase == .done and slot.read == 0))
+ return tree.failText(req.tag, E.INVAL, e_one_line);
+ // A new line on this open: a new answer.
+ p.gpa.free(slot.output);
+ p.gpa.free(slot.line);
+ slot.* = .{};
+ if (std.mem.trim(u8, line, " \t").len == 0) return tree.failText(req.tag, E.INVAL, e_bad_line);
+ for (line) |c| if (c < ' ' and c != '\t') return tree.failText(req.tag, E.INVAL, e_bad_line);
+ const pf = &pane.fs;
+ if (pane.terminal == null) return tree.failText(req.tag, E.INVAL, e_bad_line);
+ const marks = pardes.Term.prompt(pane.terminal);
+ if (pane.shell_failed) {
+ // Its shell never started: no prompt is coming to wait for.
+ answer(p, slot, "error shell gone", .{});
+ } else if (pane.command != null) {
+ // Its child is the command, and no shell is there to take a line.
+ answer(p, slot, "error {s}", .{if (pane.command_done) "command done; not a shell" else "a command runs here, not a shell"});
+ } else if (pf.unmarked) {
+ answer(p, slot, "error no prompt marks", .{});
+ } else if (waitingRun(p, pane) != null or (marks.prompts > 0 and (marks.phase != .input or
+ !marks.input_empty or p.hostTtyTaken(id))))
+ {
+ // Something is running or someone has typed at the prompt: sending
+ // now would type into the middle of it. The phase is pardes's own
+ // marks: a nested shell's prompt (ssh, a shell with its own
+ // integration) looks like an empty prompt to the emulator but is not the
+ // shell this run knows.
+ // Naming what runs, where the host can tell (Linux).
+ var name: [64]u8 = undefined;
+ if (p.hostForegroundName(id, &name)) |program|
+ answer(p, slot, "busy: {s} is running", .{program})
+ else if (pardes.Term.modes(pane.terminal).alternate)
+ answer(p, slot, "busy alternate screen", .{})
+ else
+ answer(p, slot, "busy", .{});
+ } else {
+ // Sent now if the shell is at its prompt, or at its first prompt
+ // when it has not drawn one yet (noteMarks).
+ slot.line = p.gpa.dupe(u8, line) catch return Reply.fail(req.tag, E.NOMEM);
+ slot.phase = .waiting;
+ pf.run = req.handle;
+ noteMarks(p, id, pane);
+ }
+ return .{ .tag = req.tag, .written = @intCast(req.data.len) };
+}
+
+pub fn readRun(p: *Pardes, req: Req) Reply {
+ const slot = &(tree.openOf(p, req) orelse return Reply.fail(req.tag, E.INVAL)).what.run;
+ switch (slot.phase) {
+ .idle => return .{ .tag = req.tag, .payload = .{ .staged = 0 } },
+ .waiting, .sent => return .{ .tag = req.tag, .status = .again },
+ .done => {},
+ }
+ // The answer line, then the output: one stream, read from `read` on.
+ const out = p.fs.stage(p.gpa);
+ var at = slot.read;
+ for ([_][]const u8{ slot.answer[0..slot.len], slot.output }) |part| {
+ if (at >= part.len) {
+ at -= part.len;
+ continue;
+ }
+ const n = @min(part.len - at, req.size - out.items.len);
+ out.appendSlice(p.gpa, part[at..][0..n]) catch return Reply.fail(req.tag, E.NOMEM);
+ at = 0;
+ if (out.items.len == req.size) break;
+ }
+ slot.read += out.items.len;
+ return .{ .tag = req.tag, .payload = .{ .staged = @intCast(out.items.len) } };
+}
+
+/// After each chunk of a terminal's output: once the command the run sent
+/// has ended and the shell is back at a prompt, the run answers how. Waiting
+/// for the prompt means whoever reads the answer can send the next command
+/// at once instead of finding the shell still drawing it.
+pub fn noteMarks(p: *Pardes, id: usize, pane: *Pane) void {
+ if (pane.terminal == null) return;
+ const pf = &pane.fs;
+ const slot = waitingRun(p, pane) orelse return;
+ const marks = pardes.Term.prompt(pane.terminal);
+ if (slot.phase == .waiting) {
+ if (pf.unmarked) {
+ answer(p, slot, "error no prompt marks", .{});
+ pf.run = null;
+ return;
+ }
+ if (marks.phase != .input or !marks.input_empty or p.hostTtyTaken(id)) return;
+ slot.want = marks.started +% 1;
+ slot.prompts = marks.prompts;
+ slot.declined = marks.declined;
+ // A prompt on the alternate screen (its program killed there): the
+ // emulator leaves it first, as a reused command pane does, so the
+ // run's output lands on the primary screen and is read whole.
+ if (pardes.Term.modes(pane.terminal).alternate) pane.feedOutput(p, "\x1b[?1049l");
+ p.emitWrite(id, slot.line);
+ p.emitWrite(id, "\r");
+ pane.noteCommand(slot.line);
+ // The run is the shell's first command: a greeting `ls` typed at the
+ // same prompt would run after it, and its C would be taken for ours.
+ pane.greet = false;
+ slot.phase = .sent;
+ return;
+ }
+ if (marks.phase != .input) return;
+ // ponytail: a prompt redrawn before the command starts (a resize in that
+ // instant) reads as not run; a per-command id in the marks would tell.
+ if (marks.started != slot.want and marks.prompts != slot.prompts) {
+ // fish keeps a refused line on the prompt for editing, and bash's
+ // continuation prompt holds an unfinished one (its line looks empty
+ // but the command is still pending). Either is the line this run
+ // typed into an empty prompt, so throw it away with Ctrl-C, which
+ // drops the whole pending command, and answer at the prompt after
+ // that, so the next line finds the shell clear.
+ const empty = marks.input_empty;
+ switch (slot.cleared) {
+ .no => {
+ if (marks.continuation) {
+ // bash holds the start of the command: Ctrl-C drops all of it
+ p.emitWrite(id, "\x03");
+ slot.cleared = .continuation;
+ slot.prompts = marks.prompts; // gone at the next prompt
+ return;
+ }
+ if (!empty) {
+ // fish keeps the refused line on the prompt; a run's line
+ // is one line, so Ctrl-U takes it all (a Ctrl-C sent while
+ // fish redraws is lost)
+ p.emitWrite(id, "\x15");
+ slot.cleared = .kept_line;
+ return;
+ }
+ // bash said it handled the line (a D) and cleared its prompt
+ if (marks.declined == slot.declined) return;
+ // Otherwise an empty ordinary prompt means fish has not drawn
+ // the kept line yet, or a redraw landed before the line ran
+ // (its C is still coming): the next output says which.
+ },
+ .continuation => if (marks.continuation) return,
+ .kept_line => {},
+ }
+ if (!empty) return;
+ answer(p, slot, "error not run", .{});
+ pf.run = null;
+ return;
+ }
+ const done = marks.finished orelse return;
+ if (done.seq != slot.want) return;
+ pf.run = null;
+ finish(p, slot, pane, done.status);
+}
+
+/// Answers a run whose command ended with `status`: the header and the
+/// output it printed.
+fn finish(p: *Pardes, slot: *Run, pane: *Pane, status_code: ?i32) void {
+ // As the authority's emulator has it (taped): a screen-state replica's
+ // is its deltas', which a lagging client's can be states behind, its
+ // pins in pages it never had (the emulator's leftWrap overflowed on one).
+ const printed = pardes.tape.value(.prompt, printedBy, .{ pane, p.scratch.allocator() }) orelse
+ return answer(p, slot, "error out of memory", .{});
+ // Keep the tail, cut at a line start so the first line kept is whole.
+ var keep: []const u8 = printed.text;
+ if (keep.len > output_cap) {
+ keep = keep[keep.len - output_cap ..];
+ if (std.mem.indexOfScalar(u8, keep, '\n')) |nl| keep = keep[nl + 1 ..];
+ }
+ if (keep.len > 0) {
+ const nl = @intFromBool(keep[keep.len - 1] != '\n');
+ const owned = p.gpa.alloc(u8, keep.len + nl) catch return answer(p, slot, "error out of memory", .{});
+ @memcpy(owned[0..keep.len], keep);
+ if (nl == 1) owned[keep.len] = '\n';
+ slot.output = owned;
+ }
+ // A D that carries no status says nothing of how the command went.
+ var code: [16]u8 = undefined;
+ // unreachable: an exit status fits 16
+ const status = if (status_code) |s| std.fmt.bufPrint(&code, "{d}", .{s}) catch unreachable else "?";
+ // The header is the whole first line, so a count there can never be
+ // mistaken for output; `cut` with no count: its start is not there to
+ // count from.
+ if (!printed.whole)
+ answer(p, slot, "exit {s} cut", .{status})
+ else if (printed.text.len > keep.len)
+ answer(p, slot, "exit {s} cut {d}", .{ status, printed.text.len - keep.len })
+ else
+ answer(p, slot, "exit {s}", .{status});
+}
+
+pub const Printed = struct { text: []const u8, whole: bool };
+
+/// What pane `pane`'s command printed (Term.commandOutput), in `arena`.
+fn printedBy(pane: *Pane, arena: std.mem.Allocator) ?Printed {
+ const out = pardes.Term.commandOutput(pane.terminal, arena, output_rows) catch return null;
+ return .{ .text = out.text, .whole = out.whole };
+}
+
+/// The shell itself exited (a run's `exit 3`, or one typed): a run waiting
+/// on the command it ran answers with the shell's status and what it
+/// printed, and the log says `exit` before the pane's `del`. Unknown, the
+/// status is not guessed: the run hears `error shell gone` when the pane
+/// goes.
+pub fn shellExited(p: *Pardes, pane: *Pane, status: ?u8) void {
+ const code = status orelse return;
+ if (waitingRun(p, pane)) |slot| if (slot.phase == .sent) {
+ pane.fs.run = null;
+ if (pane.terminal) |state| pardes.Term.endOutputHere(state);
+ finish(p, slot, pane, code);
+ };
+ var buf: [4]u8 = undefined;
+ // unreachable: a u8 exit code is at most 3 digits
+ pane.noteRun(p, "exit", std.fmt.bufPrint(&buf, "{d}", .{code}) catch unreachable);
+}
+
+/// The pane closed or its shell was replaced: the command's end will never
+/// be reported, so the run says so instead of waiting forever. A line not
+/// sent yet waits on for the replacement's first prompt.
+pub fn shellGone(p: *Pardes, pane: *Pane, respawn: bool) void {
+ const slot = waitingRun(p, pane) orelse return;
+ if (respawn and slot.phase == .waiting) return;
+ answer(p, slot, "error shell gone", .{});
+ pane.fs.run = null;
+}
+
+/// The run waiting on this shell's command. The pane keeps its open's
+/// handle, which names that open only on the node it was opened on, so it
+/// is looked up the way a request's is; one that no longer names a run is
+/// forgotten.
+fn waitingRun(p: *Pardes, pane: *Pane) ?*Run {
+ const handle = pane.fs.run orelse return null;
+ if (tree.openOf(p, .{ .tag = 0, .op = .read, .node = tree.Node.of(pane.serial, .pty_run), .handle = handle })) |o|
+ if (o.what == .run) return &o.what.run;
+ pane.fs.run = null;
+ return null;
+}
+
+const e_bad_line = "bad command line";
+const e_one_line = "invalid run: one line a run, its answer read before the next";
+const e_bad_pty_ctl = tree.e_bad_ctl ++ "; takes winsize COLS ROWS, sig INT|TERM|HUP|QUIT|KILL, or exec";
+
+pub fn readData(p: *Pardes, req: Req, pf: *pane_files.State) Reply {
+ if (pf.pty_out.empty()) return .{ .tag = req.tag, .status = .again };
+ const out = p.fs.stage(p.gpa);
+ while (out.items.len < req.size) {
+ const chunk = pf.pty_out.peek() orelse break;
+ const n = @min(chunk.len, req.size - out.items.len);
+ out.appendSlice(p.gpa, chunk[0..n]) catch break;
+ pf.pty_out.popFront(n);
+ }
+ return .{ .tag = req.tag, .payload = .{ .staged = @intCast(out.items.len) } };
+}
+
+pub fn writeData(p: *Pardes, req: Req, id: usize) Reply {
+ if (req.data.len == 0) return .{ .tag = req.tag, .written = 0 };
+ const take = pane_files.wholeUtf8(req.data);
+ p.emitWrite(id, req.data[0..take]);
+ return .{ .tag = req.tag, .written = @intCast(take) };
+}
+
+// ---- tests ----
+
+const testing = std.testing;
+const th = @import("testing.zig");
+const events = @import("events.zig");
+const call = th.call;
+const rd = th.rd;
+const wr = th.wr;
+const rdir = th.rdir;
+const look_up = th.look_up;
+const withFile = th.withFile;
+const withTerm = th.withTerm;
+const serialOf = th.serialOf;
+const Node = tree.Node;
+const Status = tree.Status;
+
+test "a pane that is not a terminal has no pty/ at all" {
+ const gpa = testing.allocator;
+ const p = try withFile(gpa, "hello\n");
+ defer p.deinit();
+ const serial = serialOf(p);
+ const dir = Node.of(serial, .dir);
+
+ try testing.expectEqual(E.NOENT, look_up(p, dir, "pty").errno());
+ try testing.expectEqual(E.NOENT, call(p, .{
+ .tag = 1,
+ .op = .getattr,
+ .node = Node.of(serial, .pty),
+ }).errno());
+ try testing.expectEqual(E.NOENT, rd(p, Node.of(serial, .pty_status), 0, 256).errno());
+ try testing.expectEqual(E.NOENT, wr(p, Node.of(serial, .pty_ctl), "winsize 80 24\n").errno());
+ try testing.expectEqual(E.NOENT, rdir(p, Node.of(serial, .pty), 0).errno());
+ try testing.expectEqual(E.NOENT, call(p, .{
+ .tag = 2,
+ .op = .open,
+ .node = Node.of(serial, .pty_data),
+ }).errno());
+ try testing.expect(!p.panes[0].?.fs.pty_reader);
+
+ var buf: [32]th.Dirent = undefined;
+ const files = th.dirents(rdir(p, dir, 0).bytes, &buf);
+ try testing.expectEqual(@as(usize, 19), files.len);
+ try testing.expect(th.nameAt(files, "pty") == null);
+
+ try testing.expectEqual(E.NOENT, look_up(p, dir, "pty_ctl").errno());
+ try testing.expectEqual(E.NOENT, look_up(p, dir, "status").errno());
+}
+
+test "a terminal pane's pty/ holds exactly ctl, status and data" {
+ const gpa = testing.allocator;
+ const p = try withTerm(gpa);
+ defer p.deinit();
+ const serial = serialOf(p);
+ const dir = Node.of(serial, .dir);
+
+ const pty = look_up(p, dir, "pty");
+ try testing.expectEqual(Node.of(serial, .pty), pty.reply.attr.node);
+ try testing.expect(pty.reply.attr.dir);
+ try testing.expectEqual(@as(u16, 0o755), pty.reply.attr.mode);
+
+ var buf: [32]th.Dirent = undefined;
+ const files = th.dirents(rdir(p, dir, 0).bytes, &buf);
+ try testing.expectEqual(@as(usize, 20), files.len);
+ try testing.expect(th.nameAt(files, "pty").?.dir);
+
+ const inside = th.dirents(rdir(p, Node.of(serial, .pty), 0).bytes, &buf);
+ try testing.expectEqual(@as(usize, 4), inside.len);
+ try testing.expectEqualStrings("ctl", inside[0].name);
+ try testing.expectEqualStrings("status", inside[1].name);
+ try testing.expectEqualStrings("data", inside[2].name);
+ try testing.expectEqualStrings("run", inside[3].name);
+ for (inside) |d| try testing.expect(!d.dir);
+ try testing.expectEqual(Node.of(serial, .pty_data), inside[2].node);
+
+ const ctl = look_up(p, Node.of(serial, .pty), "ctl");
+ try testing.expectEqual(Node.of(serial, .pty_ctl), ctl.reply.attr.node);
+ try testing.expectEqual(@as(u16, 0o666), ctl.reply.attr.mode);
+ try testing.expectEqual(@as(u16, 0o444), look_up(p, Node.of(serial, .pty), "status").reply.attr.mode);
+ try testing.expectEqual(E.NOENT, look_up(p, Node.of(serial, .pty), "body").errno());
+ try testing.expectEqual(E.NOENT, look_up(p, Node.of(serial, .pty), "pty").errno());
+
+ try testing.expectEqual(E.NOTDIR, look_up(p, Node.of(serial, .pty_ctl), "x").errno());
+ try testing.expectEqual(E.NOTDIR, rdir(p, Node.of(serial, .pty_ctl), 0).errno());
+ try testing.expectEqual(E.PERM, rd(p, Node.of(serial, .pty), 0, 16).errno());
+ try testing.expect(std.mem.startsWith(u8, rd(p, Node.of(serial, .pty_ctl), 0, 64).bytes, "winsize "));
+ try testing.expectEqual(E.PERM, wr(p, Node.of(serial, .pty_status), "x").errno());
+}
+
+test "every pty/ctl verb, and every refusal" {
+ const gpa = testing.allocator;
+ const p = try withTerm(gpa);
+ defer p.deinit();
+ const ctl = Node.of(serialOf(p), .pty_ctl);
+
+ const pane = p.panes[0].?;
+ const cols = pane.cols;
+ const rows = pane.rows;
+ var said: [32]u8 = undefined;
+ try testing.expectEqualStrings(try std.fmt.bufPrint(&said, "winsize {d} {d}\n", .{ cols, rows }), rd(p, ctl, 0, 64).bytes);
+ const ws = wr(p, ctl, "winsize 132 44\n");
+ try testing.expectEqual(@as(u32, "winsize 132 44\n".len), ws.reply.written);
+ try testing.expectEqual(@as(u16, 132), ws.winsize.?.cols);
+ try testing.expectEqual(@as(u16, 44), ws.winsize.?.rows);
+ try testing.expectEqual(cols, pane.cols);
+ try testing.expectEqual(rows, pane.rows);
+ // ctl and status read back the pty's size, until the pane resizes.
+ try testing.expectEqualStrings("winsize 132 44\n", rd(p, ctl, 0, 64).bytes);
+ // Its stat is that read's length, which a mount reads up to.
+ try testing.expectEqual(@as(u64, "winsize 132 44\n".len), call(p, .{ .tag = 1, .op = .getattr, .node = ctl }).reply.attr.size);
+ try testing.expect(std.mem.startsWith(u8, rd(p, Node.of(serialOf(p), .pty_status), 0, 64).bytes, " 132 44 "));
+ p.update(.{ .resize = .{ .cols = 76, .rows = 24 } });
+ try testing.expect(pane.cols != 132);
+ try testing.expectEqualStrings(try std.fmt.bufPrint(&said, "winsize {d} {d}\n", .{ pane.cols, pane.rows }), rd(p, ctl, 0, 64).bytes);
+
+ for ([_]struct { line: []const u8, want: pardes.PtySignal }{
+ .{ .line = "sig INT", .want = .int },
+ .{ .line = "sig TERM", .want = .term },
+ .{ .line = "sig HUP", .want = .hup },
+ .{ .line = "sig QUIT", .want = .quit },
+ .{ .line = "sig KILL", .want = .kill },
+ }) |c| {
+ const a = wr(p, ctl, c.line);
+ try testing.expectEqual(Status.ok, a.reply.status);
+ try testing.expectEqual(c.want, a.signal.?);
+ }
+
+ const ex = wr(p, ctl, "exec\n");
+ try testing.expectEqual(Status.ok, ex.reply.status);
+ try testing.expect(ex.spawned);
+
+ const both = wr(p, ctl, "winsize 100 30\nsig TERM");
+ try testing.expectEqual(@as(u16, 100), both.winsize.?.cols);
+ try testing.expectEqual(pardes.PtySignal.term, both.signal.?);
+
+ for ([_][]const u8{
+ "winsize", // no arguments
+ "winsize 80", // one argument
+ "winsize 80 24 extra", // three
+ "winsize -1 24", // not a decimal
+ "sig", // no name
+ "sig INT TERM", // two
+ "sig SIGINT",
+ "sig int", // lower case
+ "sig 9", // a number is one platform's number
+ "sig USR1", // a real signal, deliberately not offered
+ "exec /bin/sh", // the effect carries no argv; refused, never ignored
+ "raw",
+ "cooked",
+ "winsize 80 24\nbogus", // a good verb beside a bad one
+ "bogus\nwinsize 80 24",
+ "look x", // a pane command; pty/ctl shares none of that vocabulary
+ "exec Del",
+ }) |bad| {
+ const a = wr(p, ctl, bad);
+ try testing.expectEqual(E.INVAL, a.errno());
+ try testing.expectEqualStrings(e_bad_pty_ctl, a.reply.ename); // names what it takes
+ try testing.expect(a.winsize == null);
+ try testing.expect(a.signal == null);
+ try testing.expect(!a.spawned);
+ }
+ // Numbers, but no size: said as out of range, the bound size's.
+ for ([_][]const u8{ "winsize 0 24", "winsize 80 0", "winsize 0 0", "winsize 4097 24", "winsize 999999 24" }) |bad| {
+ const a = wr(p, ctl, bad);
+ try testing.expectEqual(E.INVAL, a.errno());
+ try testing.expectEqualStrings(e_winsize_range, a.reply.ename);
+ try testing.expect(a.winsize == null);
+ }
+
+ // One row is a size, but fewer than a pty takes: refused, and said so.
+ const one = wr(p, ctl, "winsize 80 1");
+ try testing.expectEqual(E.INVAL, one.errno());
+ try testing.expectEqualStrings("invalid winsize: at least 2 rows", one.reply.ename);
+ try testing.expect(one.winsize == null);
+ try testing.expectEqualStrings("invalid winsize: out of range, 1x2 to 4096x4096", e_winsize_range);
+
+ const spaced = wr(p, ctl, "\n winsize 90 20 \n\n");
+ try testing.expectEqual(Status.ok, spaced.reply.status);
+ try testing.expectEqual(@as(u16, 90), spaced.winsize.?.cols);
+ try testing.expectEqual(Status.ok, wr(p, ctl, "").reply.status);
+}
+
+test "owned cwd pty exec rejects long paths before applying its batch" {
+ const p = try withTerm(testing.allocator);
+ defer p.deinit();
+ const pane = p.panes[0].?;
+ // A one-row tag: the long path would wrap it onto rows and resize the pty.
+ pane.tag_expanded = false;
+ const ctl = Node.of(pane.serial, .pty_ctl);
+ var path: [1025]u8 = @splat('d');
+ path[0] = '/';
+ p.setCwd(0, &path);
+ for ([_][]const u8{ "exec\n", "winsize 100 30\nexec\n", "sig TERM\nexec\n" }) |command| {
+ const result = wr(p, ctl, command);
+ try testing.expectEqual(E.INVAL, result.errno());
+ try testing.expect(!result.spawned);
+ try testing.expect(result.signal == null and result.winsize == null);
+ }
+ try testing.expectEqualStrings(&path, pane.cwdSlice());
+ p.setCwd(0, path[0..pardes.effect_path_cap]);
+ const accepted = wr(p, ctl, "exec\n");
+ try testing.expectEqual(Status.ok, accepted.reply.status);
+ try testing.expect(accepted.spawned);
+}
+
+test "pty/status reports the grid and who holds the tty" {
+ const gpa = testing.allocator;
+ const p = try withTerm(gpa);
+ defer p.deinit();
+ const pane = p.panes[0].?;
+ const status = Node.of(pane.serial, .pty_status);
+
+ const a = rd(p, status, 0, 256);
+ try testing.expectEqual(Status.ok, a.reply.status);
+ var want: [64]u8 = undefined;
+ const whole = try std.fmt.bufPrint(&want, "{d:>11} {d:>11} {d:>11}\n", .{ pane.cols, pane.rows, 0 });
+ try testing.expectEqualStrings(whole, a.bytes);
+ try testing.expectEqual(@as(usize, 3 * 12), a.bytes.len);
+ try testing.expectEqualStrings(whole[12..], rd(p, status, 12, 256).bytes);
+
+ var probe: th.FakeTty = .{ .taken = true };
+ p.host = .{ .ctx = &probe, .vtable = &th.FakeTty.vtable };
+ const held = rd(p, status, 0, 256);
+ try testing.expectEqualStrings(
+ try std.fmt.bufPrint(&want, "{d:>11} {d:>11} {d:>11}\n", .{ pane.cols, pane.rows, 1 }),
+ held.bytes,
+ );
+}
+
+test "pty/data writes at the shell and reads the raw stream" {
+ const gpa = testing.allocator;
+ const p = try withTerm(gpa);
+ defer p.deinit();
+ const serial = serialOf(p);
+ const data = Node.of(serial, .pty_data);
+
+ const w = call(p, .{ .tag = 2, .op = .write, .node = data, .off = 999, .data = "ls -l\r" });
+ try testing.expectEqual(@as(u32, 6), w.reply.written);
+ try testing.expectEqualStrings("ls -l\r", w.pty());
+ try testing.expectEqual(@as(u32, 1), wr(p, data, "a\xC3").reply.written);
+ try testing.expectEqual(@as(u32, 0), wr(p, data, "").reply.written);
+
+ try testing.expectEqual(Status.again, rd(p, data, 0, 64).reply.status);
+
+ p.update(.{ .output = .{ .pane = 0, .bytes = "unwatched" } });
+ while (p.nextEffect()) |_| {}
+ try testing.expectEqual(@as(usize, 0), p.panes[0].?.fs.pty_out.buf.items.len);
+ try testing.expectEqual(Status.again, rd(p, data, 0, 64).reply.status);
+
+ // An open that only writes is not a reader: nothing queues for it.
+ const writer = call(p, .{ .tag = 4, .op = .open, .node = data, .omode = 1 });
+ try testing.expect(!p.panes[0].?.fs.pty_reader);
+ _ = call(p, .{ .tag = 4, .op = .release, .node = data, .handle = writer.reply.handle });
+
+ const reader = call(p, .{ .tag = 5, .op = .open, .node = data });
+ try testing.expect(p.panes[0].?.fs.pty_reader);
+ try testing.expectEqual(@as(u16, 0), p.fs.listeners);
+ try testing.expect(p.panes[0].?.fs.readers == 0);
+
+ p.update(.{ .output = .{ .pane = 0, .bytes = "hello" } });
+ while (p.nextEffect()) |_| {}
+ try testing.expectEqualStrings("hello", rd(p, data, 0, 64).bytes);
+ try testing.expectEqual(Status.again, rd(p, data, 0, 64).reply.status);
+
+ p.update(.{ .output = .{ .pane = 0, .bytes = "abcdef" } });
+ while (p.nextEffect()) |_| {}
+ try testing.expectEqualStrings("ab", rd(p, data, 0, 2).bytes);
+ try testing.expectEqualStrings("cd", rd(p, data, 0, 2).bytes);
+ p.update(.{ .output = .{ .pane = 0, .bytes = "ghi" } });
+ while (p.nextEffect()) |_| {}
+ try testing.expectEqualStrings("efghi", rd(p, data, 0, 64).bytes);
+
+ p.update(.{ .output = .{ .pane = 0, .bytes = "orphan" } });
+ while (p.nextEffect()) |_| {}
+ _ = call(p, .{ .tag = 6, .op = .release, .node = data, .handle = reader.reply.handle });
+ try testing.expect(!p.panes[0].?.fs.pty_reader);
+ try testing.expectEqual(@as(usize, 0), p.panes[0].?.fs.pty_out.buf.capacity);
+ try testing.expectEqual(Status.again, rd(p, data, 0, 64).reply.status);
+
+ // A second reader would take half the stream from the first: refused.
+ _ = call(p, .{ .tag = 7, .op = .open, .node = data });
+ const second = call(p, .{ .tag = 8, .op = .open, .node = data, .omode = 2 });
+ try testing.expectEqual(Status.err, second.reply.status);
+ try testing.expectEqualStrings(tree.e_in_use, second.reply.ename);
+ try testing.expect(p.panes[0].?.fs.pty_reader);
+ p.update(.{ .output = .{ .pane = 0, .bytes = "still" } });
+ while (p.nextEffect()) |_| {}
+ try testing.expectEqualStrings("still", rd(p, data, 0, 64).bytes);
+}
+
+test "a run waiting for a new terminal's first prompt is the only line typed there, no greeting after it" {
+ const gpa = testing.allocator;
+ const p = try withTerm(gpa);
+ defer p.deinit();
+ p.panes[0].?.greet = true; // a Term's, in a window (resized)
+ p.update(.{ .resize = .{ .cols = 80, .rows = 24 } });
+ while (p.nextEffect()) |_| {}
+ const node = Node.of(serialOf(p), .pty_run);
+ const h = call(p, .{ .tag = 1, .op = .open, .node = node }).reply.handle;
+ _ = call(p, .{ .tag = 2, .op = .write, .node = node, .handle = h, .data = "true\n" });
+ p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b]133;A;cl=line;aid=pardes\x07$ \x1b]133;B;aid=pardes\x07" } });
+ var sent: [32]u8 = undefined;
+ var len: usize = 0;
+ while (p.nextEffect()) |e| if (e == .write) {
+ const b = e.write.bytes.slice();
+ @memcpy(sent[len..][0..b.len], b);
+ len += b.len;
+ };
+ try testing.expectEqualStrings("true\r", sent[0..len]);
+}
+
+test "run answers how its command ended once the shell is back at a prompt" {
+ const gpa = testing.allocator;
+ const p = try withTerm(gpa);
+ defer p.deinit();
+ const node = Node.of(serialOf(p), .pty_run);
+ const out = struct {
+ fn put(pp: *Pardes, bytes: []const u8) void {
+ pp.update(.{ .output = .{ .pane = 0, .bytes = bytes } });
+ while (pp.nextEffect()) |_| {}
+ }
+ };
+ const prompt = "\x1b]133;A;cl=line;aid=pardes\x07$ \x1b]133;B;aid=pardes\x07";
+
+ // Before its first prompt the shell cannot take a line yet: the line
+ // waits for it, and pty/status does not call the shell busy meanwhile.
+ const status = Node.of(serialOf(p), .pty_status);
+ try testing.expect(std.mem.endsWith(u8, rd(p, status, 0, 64).bytes, " 0\n"));
+ const early = call(p, .{ .tag = 1, .op = .open, .node = node });
+ const waiting = call(p, .{ .tag = 2, .op = .write, .node = node, .handle = early.reply.handle, .data = "true\n" });
+ try testing.expectEqualStrings("", waiting.pty());
+ try testing.expectEqual(Status.again, call(p, .{ .tag = 3, .op = .read, .node = node, .handle = early.reply.handle, .size = 64 }).reply.status);
+ try testing.expect(std.mem.endsWith(u8, rd(p, status, 0, 64).bytes, " 1\n"));
+ // A respawn before that prompt keeps it waiting for the new shell's.
+ p.acknowledgeShell(0, "/bin/sh", true);
+ try testing.expectEqual(Status.again, call(p, .{ .tag = 3, .op = .read, .node = node, .handle = early.reply.handle, .size = 64 }).reply.status);
+ p.update(.{ .output = .{ .pane = 0, .bytes = prompt } });
+ var sent_late: [16]u8 = undefined;
+ var sent_len: usize = 0;
+ while (p.nextEffect()) |e| if (e == .write) {
+ const b = e.write.bytes.slice();
+ @memcpy(sent_late[sent_len..][0..b.len], b);
+ sent_len += b.len;
+ };
+ try testing.expectEqualStrings("true\r", sent_late[0..sent_len]);
+ out.put(p, "\x1b]133;C;aid=pardes\x07\x1b]133;D;0;aid=pardes\x07" ++ prompt);
+ try testing.expectEqualStrings("exit 0\n", call(p, .{ .tag = 3, .op = .read, .node = node, .handle = early.reply.handle, .size = 64 }).bytes);
+ _ = call(p, .{ .tag = 4, .op = .release, .node = node, .handle = early.reply.handle });
+
+ const r = call(p, .{ .tag = 5, .op = .open, .node = node });
+ const h = r.reply.handle;
+ const sent = call(p, .{ .tag = 6, .op = .write, .node = node, .handle = h, .data = "make\n" });
+ try testing.expectEqualStrings("make\r", sent.pty());
+ try testing.expectEqual(Status.again, call(p, .{ .tag = 7, .op = .read, .node = node, .handle = h, .size = 64 }).reply.status);
+ // A second line on the same open while the first runs is refused.
+ try testing.expectEqual(Status.err, call(p, .{ .tag = 8, .op = .write, .node = node, .handle = h, .data = "ls\n" }).reply.status);
+
+ // Untagged marks (fish's own, a nested shell's, a file being printed)
+ // and bash's C from its PROMPT_COMMAND trap change nothing.
+ out.put(p, "\x1b]133;D;9\x07\x1b]133;C;aid=pardes\x07building\r\n");
+ out.put(p, "\x1b]133;C;aid=pardes\x07\x1b]133;D;2;aid=pardes\x07");
+ try testing.expectEqual(Status.again, call(p, .{ .tag = 9, .op = .read, .node = node, .handle = h, .size = 64 }).reply.status);
+ out.put(p, prompt);
+ // A shell's `exec 3<>run; echo make >&3; cat <&3` reads at the offset
+ // its write left (5): the answer is a stream and comes whole anyway.
+ // The answer is how it ended, then what it printed.
+ try testing.expectEqualStrings("exit 2\nbuilding\n", call(p, .{ .tag = 10, .op = .read, .node = node, .handle = h, .off = 5, .size = 64 }).bytes);
+ try testing.expectEqual(@as(usize, 0), call(p, .{ .tag = 11, .op = .read, .node = node, .handle = h, .size = 64 }).bytes.len);
+ _ = call(p, .{ .tag = 12, .op = .release, .node = node, .handle = h });
+
+ // While a command runs, a nested shell's own (untagged) prompt looks
+ // like an empty prompt to the emulator; it is not this shell's.
+ const outer = call(p, .{ .tag = 30, .op = .open, .node = node });
+ _ = call(p, .{ .tag = 31, .op = .write, .node = node, .handle = outer.reply.handle, .data = "ssh box\n" });
+ out.put(p, "\x1b]133;C;aid=pardes\x07\x1b]133;A\x07remote$ \x1b]133;B\x07");
+ const nested = call(p, .{ .tag = 32, .op = .open, .node = node });
+ _ = call(p, .{ .tag = 33, .op = .write, .node = node, .handle = nested.reply.handle, .data = "true\n" });
+ try testing.expectEqualStrings("busy\n", call(p, .{ .tag = 34, .op = .read, .node = node, .handle = nested.reply.handle, .size = 64 }).bytes);
+ _ = call(p, .{ .tag = 35, .op = .release, .node = node, .handle = nested.reply.handle });
+ out.put(p, "logout\r\n\x1b]133;D;0;aid=pardes\x07" ++ prompt);
+ const ssh = call(p, .{ .tag = 36, .op = .read, .node = node, .handle = outer.reply.handle, .size = 64 }).bytes;
+ try testing.expect(std.mem.startsWith(u8, ssh, "exit 0\n") and std.mem.indexOf(u8, ssh, "remote$ logout\n") != null);
+ _ = call(p, .{ .tag = 37, .op = .release, .node = node, .handle = outer.reply.handle });
+
+ // Typed text on the prompt line: busy, rather than typing into it.
+ out.put(p, "ls -");
+ const typed = call(p, .{ .tag = 13, .op = .open, .node = node });
+ _ = call(p, .{ .tag = 14, .op = .write, .node = node, .handle = typed.reply.handle, .data = "true\n" });
+ try testing.expectEqualStrings("busy\n", call(p, .{ .tag = 15, .op = .read, .node = node, .handle = typed.reply.handle, .size = 64 }).bytes);
+ _ = call(p, .{ .tag = 16, .op = .release, .node = node, .handle = typed.reply.handle });
+ out.put(p, "\x08\x08\x08\x08\x1b[K");
+
+ // A line the shell refuses without running it (fish on a syntax error):
+ // a fresh prompt and no C. Waiting for a D would wait forever.
+ const refused = call(p, .{ .tag = 21, .op = .open, .node = node });
+ _ = call(p, .{ .tag = 22, .op = .write, .node = node, .handle = refused.reply.handle, .data = "(exit 7)\n" });
+ out.put(p, "\r\nfish: command substitutions not allowed\r\n" ++ prompt ++ "(exit 7)");
+ try testing.expectEqual(Status.again, call(p, .{ .tag = 23, .op = .read, .node = node, .handle = refused.reply.handle, .size = 64 }).reply.status);
+ out.put(p, "^C\r\n" ++ prompt);
+ try testing.expectEqualStrings("error not run\n", call(p, .{ .tag = 23, .op = .read, .node = node, .handle = refused.reply.handle, .size = 64 }).bytes);
+ _ = call(p, .{ .tag = 24, .op = .release, .node = node, .handle = refused.reply.handle });
+
+ // bash on a syntax error prints no C but still a D before its prompt.
+ const bad = call(p, .{ .tag = 40, .op = .open, .node = node });
+ _ = call(p, .{ .tag = 41, .op = .write, .node = node, .handle = bad.reply.handle, .data = "fi\n" });
+ out.put(p, "fi\r\nbash: syntax error\r\n\x1b]133;D;2;aid=pardes\x07" ++ prompt);
+ try testing.expectEqualStrings("error not run\n", call(p, .{ .tag = 42, .op = .read, .node = node, .handle = bad.reply.handle, .size = 64 }).bytes);
+ _ = call(p, .{ .tag = 43, .op = .release, .node = node, .handle = bad.reply.handle });
+
+ // An unfinished line (an open quote) leaves bash at its continuation
+ // prompt, tagged too: the line is thrown away with Ctrl-C, then answered.
+ const open_quote = call(p, .{ .tag = 25, .op = .open, .node = node });
+ const typed_quote = call(p, .{ .tag = 26, .op = .write, .node = node, .handle = open_quote.reply.handle, .data = "echo 'x\n" });
+ try testing.expectEqualStrings("echo 'x\r", typed_quote.pty());
+ const cont = call(p, .{ .tag = 27, .op = .read, .node = node, .handle = open_quote.reply.handle, .size = 64 });
+ try testing.expectEqual(Status.again, cont.reply.status);
+ out.put(p, "echo 'x\r\n\x1b]133;A;k=c;aid=pardes\x07> \x1b]133;B;aid=pardes\x07");
+ try testing.expectEqual(Status.again, call(p, .{ .tag = 28, .op = .read, .node = node, .handle = open_quote.reply.handle, .size = 64 }).reply.status);
+ out.put(p, "^C\r\n" ++ prompt);
+ try testing.expectEqualStrings("error not run\n", call(p, .{ .tag = 29, .op = .read, .node = node, .handle = open_quote.reply.handle, .size = 64 }).bytes);
+ _ = call(p, .{ .tag = 29, .op = .release, .node = node, .handle = open_quote.reply.handle });
+
+ // The pane going away while a command runs ends the wait.
+ out.put(p, "\r\n" ++ prompt);
+ const gone = call(p, .{ .tag = 17, .op = .open, .node = node });
+ _ = call(p, .{ .tag = 18, .op = .write, .node = node, .handle = gone.reply.handle, .data = "sleep 9\n" });
+ try p.removePane(0, null);
+ try testing.expectEqualStrings("error shell gone\n", call(p, .{ .tag = 19, .op = .read, .node = node, .handle = gone.reply.handle, .size = 64 }).bytes);
+ // It still stats while the run is open (a reader's fstat), on the
+ // open or on the file's name, and not once it is released.
+ try testing.expectEqual(Status.ok, call(p, .{ .tag = 19, .op = .getattr, .node = node, .handle = gone.reply.handle }).reply.status);
+ try testing.expectEqual(Status.ok, call(p, .{ .tag = 19, .op = .getattr, .node = node }).reply.status);
+ _ = call(p, .{ .tag = 20, .op = .release, .node = node, .handle = gone.reply.handle });
+ for (p.fs.opens) |o| try testing.expect(o.node == 0);
+ try testing.expectEqual(E.NOENT, call(p, .{ .tag = 21, .op = .getattr, .node = node }).errno());
+}
+
+test "a shell that exits under a run answers its status, and the log says exit before del" {
+ const gpa = testing.allocator;
+ const p = try withTerm(gpa);
+ defer p.deinit();
+ const serial = serialOf(p);
+ const node = Node.of(serial, .pty_run);
+ const prompt = "\x1b]133;A;cl=line;aid=pardes\x07$ \x1b]133;B;aid=pardes\x07";
+ p.update(.{ .output = .{ .pane = 0, .bytes = prompt } });
+ while (p.nextEffect()) |_| {}
+ const log = @backingInt(tree.TopFile.log);
+ const f = call(p, .{ .tag = 1, .op = .open, .node = log }).reply.handle;
+ const frozen = call(p, .{ .tag = 2, .op = .read, .node = log, .handle = f, .size = 1 << 16 }).bytes.len;
+ _ = call(p, .{ .tag = 3, .op = .write, .node = log, .handle = f, .data = "follow" });
+
+ const r = call(p, .{ .tag = 4, .op = .open, .node = node });
+ _ = call(p, .{ .tag = 5, .op = .write, .node = node, .handle = r.reply.handle, .data = "echo bye; exit 3\n" });
+ p.update(.{ .output = .{ .pane = 0, .bytes = "echo bye; exit 3\r\n\x1b]133;C;aid=pardes\x07bye\r\n" } });
+ p.update(.{ .exited = .{ .pane = 0, .status = 3 } });
+ p.update(.{ .eof = .{ .pane = 0 } });
+ while (p.nextEffect()) |_| {}
+ try testing.expect(p.paneBySerial(serial) == null);
+ try testing.expectEqualStrings("exit 3\nbye\n", call(p, .{ .tag = 6, .op = .read, .node = node, .handle = r.reply.handle, .size = 64 }).bytes);
+ var want: [128]u8 = undefined;
+ // A followed log reads a record at a time: the exit, then the del.
+ var records: [2][]const u8 = undefined;
+ var at = frozen;
+ for (&records) |*rec| {
+ rec.* = try gpa.dupe(u8, call(p, .{ .tag = 7, .op = .read, .node = log, .handle = f, .off = at, .size = 4096 }).bytes);
+ at += rec.len;
+ }
+ defer for (records) |rec| gpa.free(rec);
+ try testing.expectEqualStrings(try std.fmt.bufPrint(&want, "exit {d} 3\n", .{serial}), records[0]);
+ try testing.expect(std.mem.startsWith(u8, records[1], try std.fmt.bufPrint(&want, "del {d} ", .{serial})));
+ // A write to its pty/data now finds no pane.
+ try testing.expectEqual(E.NOENT, wr(p, Node.of(serial, .pty_data), "x").errno());
+ _ = call(p, .{ .tag = 8, .op = .release, .node = node, .handle = r.reply.handle });
+ _ = call(p, .{ .tag = 9, .op = .release, .node = log, .handle = f });
+}
+
+test "run on a command pane says no shell is there" {
+ const gpa = testing.allocator;
+ const p = try withTerm(gpa);
+ defer p.deinit();
+ const node = Node.of(serialOf(p), .pty_run);
+ const pane = p.panes[0].?;
+ pane.command = try gpa.dupe(u8, "make");
+ for ([_]struct { bool, []const u8 }{
+ .{ false, "error a command runs here, not a shell\n" },
+ .{ true, "error command done; not a shell\n" },
+ }) |case| {
+ pane.command_done = case[0];
+ const o = call(p, .{ .tag = 1, .op = .open, .node = node });
+ _ = call(p, .{ .tag = 2, .op = .write, .node = node, .handle = o.reply.handle, .data = "ls\n" });
+ try testing.expectEqualStrings(case[1], call(p, .{ .tag = 3, .op = .read, .node = node, .handle = o.reply.handle, .size = 64 }).bytes);
+ _ = call(p, .{ .tag = 4, .op = .release, .node = node, .handle = o.reply.handle });
+ }
+}
+
+test "a run's answer says cut when its output's start is gone, and reads a bounded tail" {
+ const gpa = testing.allocator;
+ if (pardes.Term.ops == null) return error.SkipZigTest; // it reads the emulator
+ const p = try withTerm(gpa);
+ defer p.deinit();
+ const node = Node.of(serialOf(p), .pty_run);
+ const pane = p.panes[0].?;
+ const sh = struct {
+ fn put(pp: *Pardes, bytes: []const u8) void {
+ pp.update(.{ .output = .{ .pane = 0, .bytes = bytes } });
+ while (pp.nextEffect()) |_| {}
+ }
+ fn send(pp: *Pardes, n: u64) u32 {
+ const h = call(pp, .{ .tag = 1, .op = .open, .node = n }).reply.handle;
+ _ = call(pp, .{ .tag = 2, .op = .write, .node = n, .handle = h, .data = "x\n" });
+ return h;
+ }
+ /// The whole answer, then the open is closed.
+ fn answered(pp: *Pardes, n: u64, h: u32, into: []u8) []const u8 {
+ defer _ = call(pp, .{ .tag = 4, .op = .release, .node = n, .handle = h });
+ var len: usize = 0;
+ while (true) {
+ const a = call(pp, .{ .tag = 3, .op = .read, .node = n, .handle = h, .size = 8192 });
+ if (a.reply.status != .ok or a.bytes.len == 0) return into[0..len];
+ @memcpy(into[len..][0..a.bytes.len], a.bytes);
+ len += a.bytes.len;
+ }
+ }
+ };
+ const prompt = "\x1b]133;A;cl=line;aid=pardes\x07$ \x1b]133;B;aid=pardes\x07";
+ const c = "\r\n\x1b]133;C;aid=pardes\x07";
+ const d = "\x1b]133;D;0;aid=pardes\x07";
+ const into = try gpa.alloc(u8, 2 * output_cap);
+ defer gpa.free(into);
+ sh.put(p, prompt);
+
+ // `clear` while it runs: what it printed after is its output, whole;
+ // what the clear erased was meant to go.
+ var h = sh.send(p, node);
+ sh.put(p, c ++ "before\r\n\x1b[H\x1b[2J\x1b[3Jafter\r\n" ++ d ++ prompt);
+ var got = sh.answered(p, node, h, into);
+ try testing.expectEqualStrings("exit 0\nafter\n", got);
+
+ // A resize between its start and end reflows the pins with the text.
+ h = sh.send(p, node);
+ sh.put(p, c ++ "one\r\ntwo\r\n");
+ pane.resizeGrid(50, 20);
+ sh.put(p, d ++ prompt);
+ try testing.expectEqualStrings("exit 0\none\ntwo\n", sh.answered(p, node, h, into));
+ pane.resizeGrid(pane.cols, pane.rows);
+
+ // A full-screen program leaves nothing on the primary screen, and a D
+ // with no status is not a success.
+ h = sh.send(p, node);
+ sh.put(p, c ++ "\x1b[?1049hwhole screen\x1b[?1049l\x1b]133;D;aid=pardes\x07" ++ prompt);
+ try testing.expectEqualStrings("exit ?\n", sh.answered(p, node, h, into));
+
+ // One killed there leaves the emulator on the alternate screen, and the
+ // shell draws its prompt there: not busy, and the next run is read
+ // whole from the primary screen, never `exit 0 cut` with nothing.
+ h = sh.send(p, node);
+ sh.put(p, c ++ "\x1b[?1049hhtop's screen\r\n");
+ _ = call(p, .{ .tag = 4, .op = .release, .node = node, .handle = h });
+ sh.put(p, "\x1b]133;D;137;aid=pardes\x07" ++ prompt);
+ try testing.expect(pardes.Term.modes(pane.terminal).alternate);
+ try testing.expect(std.mem.endsWith(u8, rd(p, Node.of(serialOf(p), .pty_status), 0, 64).bytes, " 0\n"));
+ h = sh.send(p, node);
+ sh.put(p, c ++ "after htop\r\n" ++ d ++ prompt);
+ try testing.expectEqualStrings("exit 0\nafter htop\n", sh.answered(p, node, h, into));
+ // Busy there with no prompt drawn, it says where it is.
+ h = sh.send(p, node);
+ sh.put(p, c ++ "\x1b[?1049hfull screen");
+ const busy = call(p, .{ .tag = 1, .op = .open, .node = node }).reply.handle;
+ _ = call(p, .{ .tag = 2, .op = .write, .node = node, .handle = busy, .data = "y\n" });
+ try testing.expectEqualStrings("busy alternate screen\n", sh.answered(p, node, busy, into));
+ sh.put(p, "\x1b[?1049l" ++ d ++ prompt);
+ _ = sh.answered(p, node, h, into);
+
+ // A megabyte of output: read from at most `output_rows` rows above its
+ // end (the history still holds its start), the last 64 KiB kept.
+ h = sh.send(p, node);
+ sh.put(p, c);
+ var line: [120]u8 = @splat('y');
+ line[118] = '\r';
+ line[119] = '\n';
+ for (0..(1 << 20) / line.len) |i| {
+ _ = std.fmt.bufPrint(&line, "{d:0>8}", .{i}) catch unreachable;
+ sh.put(p, &line);
+ }
+ try testing.expect(!pardes.Term.emulatorOf(pane.terminal.?).stream.handler.out_start.?.garbage);
+ sh.put(p, d ++ prompt);
+ got = sh.answered(p, node, h, into);
+ try testing.expect(std.mem.startsWith(u8, got, "exit 0 cut\n"));
+ try testing.expect(got.len <= "exit 0 cut\n".len + output_cap + 1);
+ try testing.expect(std.mem.endsWith(u8, got, "\n") and std.mem.indexOf(u8, got, "00008737") != null);
+
+ // Its start pruned from a history held to its least: what survived, and
+ // cut.
+ {
+ const q = try withTerm(gpa);
+ defer q.deinit();
+ const kept = q.panes[0].?;
+ pardes.Term.emulatorOf(kept.terminal.?).vt.screens.get(.primary).?.pages.limits.set(.bytes, 1);
+ const run = Node.of(serialOf(q), .pty_run);
+ sh.put(q, prompt);
+ h = sh.send(q, run);
+ sh.put(q, c);
+ const lines = std.mem.asBytes(&@as([64][8]u8, @splat("pruned\r\n".*)));
+ var fed: usize = 0;
+ while (!pardes.Term.emulatorOf(kept.terminal.?).stream.handler.out_start.?.garbage) : (fed += 1) {
+ if (fed == 1000) return error.TestUnexpectedResult;
+ sh.put(q, lines);
+ }
+ sh.put(q, d ++ prompt);
+ got = sh.answered(q, run, h, into);
+ try testing.expect(std.mem.startsWith(u8, got, "exit 0 cut\npruned\n"));
+ }
+
+ // No memory for the answer's output is said, not passed off as a cut.
+ h = sh.send(p, node);
+ sh.put(p, c ++ "short\r\n");
+ var failing = std.testing.FailingAllocator.init(gpa, .{ .fail_index = 0 });
+ p.gpa = failing.allocator();
+ sh.put(p, d ++ prompt);
+ p.gpa = gpa;
+ try testing.expectEqualStrings("error out of memory\n", sh.answered(p, node, h, into));
+ // An end drawn above the start (the prompt redrawn over what was
+ // printed, as in a window two rows high): cut, never an empty whole.
+ h = sh.send(p, node);
+ sh.put(p, c ++ "printed\r\nmore\r\n\x1b[4A" ++ d ++ prompt);
+ got = sh.answered(p, node, h, into);
+ try testing.expect(std.mem.startsWith(u8, got, "exit 0 cut\n"));
+}
+
+test "a terminal's ctl counts its body, and a new directory is a rename in the log" {
+ const gpa = testing.allocator;
+ const p = try withTerm(gpa);
+ defer p.deinit();
+ const serial = serialOf(p);
+ p.update(.{ .output = .{ .pane = 0, .bytes = "some history\r\nmore" } });
+ while (p.nextEffect()) |_| {}
+ const opened = call(p, .{ .tag = 1, .op = .open, .node = Node.of(serial, .body) });
+ const body_len = call(p, .{ .tag = 2, .op = .read, .node = Node.of(serial, .body), .handle = opened.reply.handle, .size = 1 << 16 }).bytes.len;
+ _ = call(p, .{ .tag = 3, .op = .release, .node = Node.of(serial, .body), .handle = opened.reply.handle });
+ try testing.expect(body_len > 0);
+ var fields = std.mem.tokenizeScalar(u8, rd(p, Node.of(serial, .ctl), 0, 4096).bytes, ' ');
+ _ = fields.next();
+ _ = fields.next();
+ try testing.expectEqual(body_len, try std.fmt.parseInt(usize, fields.next().?, 10));
+
+ const log = @backingInt(tree.TopFile.log);
+ const f = call(p, .{ .tag = 4, .op = .open, .node = log }).reply.handle;
+ const frozen = call(p, .{ .tag = 5, .op = .read, .node = log, .handle = f, .size = 1 << 16 }).bytes.len;
+ _ = call(p, .{ .tag = 6, .op = .write, .node = log, .handle = f, .data = "follow" });
+ p.setCwd(0, "/somewhere/else");
+ var want: [64]u8 = undefined;
+ try testing.expectEqualStrings(
+ try std.fmt.bufPrint(&want, "rename {d} /somewhere/else\n", .{serial}),
+ call(p, .{ .tag = 7, .op = .read, .node = log, .handle = f, .off = frozen, .size = 4096 }).bytes,
+ );
+ _ = call(p, .{ .tag = 8, .op = .release, .node = log, .handle = f });
+}
+
+test "closing a terminal pane asks its shell to hang up the pty" {
+ const p = try withTerm(testing.allocator);
+ defer p.deinit();
+ _ = try th.newPane(p);
+ const closed = th.rmdir(p, Node.of(serialOf(p), .dir));
+ try testing.expectEqual(Status.ok, closed.reply.status);
+ try testing.expect(closed.closed);
+ // A text pane has no shell to end.
+ const text = try th.newPane(p);
+ try testing.expect(!th.rmdir(p, Node.of(text, .dir)).closed);
+}
+
+test "the pty queue drops the oldest at its cap" {
+ const gpa = testing.allocator;
+ const p = try withTerm(gpa);
+ defer p.deinit();
+ const data = Node.of(serialOf(p), .pty_data);
+ _ = call(p, .{ .tag = 5, .op = .open, .node = data });
+
+ const oldest: [4096]u8 = @splat('A');
+ const rest: [4096]u8 = @splat('B');
+ events.notePtyOutput(p, 0, &oldest);
+ for (0..events.queue_cap / rest.len + 4) |_| events.notePtyOutput(p, 0, &rest);
+ const q = &p.panes[0].?.fs.pty_out;
+ try testing.expect(q.buf.items.len - q.head <= events.queue_cap);
+
+ var seen: usize = 0;
+ while (true) {
+ const a = rd(p, data, 0, 1 << 16);
+ if (a.reply.status == .again) break;
+ try testing.expect(std.mem.indexOfScalar(u8, a.bytes, 'A') == null);
+ if (a.bytes.len == 0) break;
+ seen += a.bytes.len;
+ }
+ try testing.expect(seen > 0 and seen <= events.queue_cap);
+}
+
+test "a run's answer longer than its room is cut, its newline kept" {
+ var slot: Run = .{};
+ const p = try th.withTerm(testing.allocator);
+ defer p.deinit();
+ answer(p, &slot, "busy: {s} is running", .{&@as([200]u8, @splat('x'))});
+ try testing.expectEqual(slot.answer.len, slot.len);
+ try testing.expectEqual(@as(u8, '\n'), slot.answer[slot.len - 1]);
+}
+
+test "exec on a command pane is refused: a command pane does not restart" {
+ const p = try th.withTerm(testing.allocator);
+ defer p.deinit();
+ const serial = th.serialOf(p);
+ const pane = p.panes[p.paneBySerial(serial).?].?;
+ pane.command = try p.gpa.dupe(u8, "echo hi");
+ const r = th.wr(p, tree.Node.of(serial, .pty_ctl), "exec\n");
+ try testing.expectEqual(tree.E.INVAL, r.errno());
+ try testing.expectEqualStrings("invalid exec: a command pane does not restart", r.reply.ename);
+}
+
+test "pty/run takes one line a run: two in one write, or a second before the first's answer is read, are refused" {
+ const p = try th.withTerm(testing.allocator);
+ defer p.deinit();
+ const serial = th.serialOf(p);
+ const run = tree.Node.of(serial, .pty_run);
+ const h = th.call(p, .{ .tag = 1, .op = .open, .node = run, .omode = 2 }).reply.handle;
+ const two = th.call(p, .{ .tag = 2, .op = .write, .node = run, .handle = h, .data = "true\nfalse\n" });
+ try testing.expectEqual(tree.E.INVAL, two.errno());
+ try testing.expectEqualStrings(e_one_line, two.reply.ename);
+ // A finished run whose answer nobody read takes no next line.
+ const slot = &tree.openOf(p, .{ .tag = 0, .op = .read, .node = run, .handle = h }).?.what.run;
+ slot.phase = .done;
+ slot.len = 7;
+ try testing.expectEqual(tree.E.INVAL, th.call(p, .{ .tag = 3, .op = .write, .node = run, .handle = h, .data = "true\n" }).errno());
+ _ = th.call(p, .{ .tag = 4, .op = .release, .node = run, .handle = h, .opened = true });
+}
diff --git a/core/ninep/screen.zig b/core/ninep/screen.zig
new file mode 100644
index 00000000..cd3c73b6
--- /dev/null
+++ b/core/ninep/screen.zig
@@ -0,0 +1,307 @@
+//! /screen, /listeners and the snapshots that freeze a screen or a terminal
+//! history between open and close (tree.zig's open records hold them).
+const std = @import("std");
+const pardes = @import("../root.zig");
+const panes = @import("../panes.zig");
+const tree = @import("tree.zig");
+
+const Pardes = pardes.Pardes;
+const Pane = pardes.Pane;
+const Req = tree.Req;
+const Reply = tree.Reply;
+const E = tree.E;
+
+pub fn render(p: *Pardes) ![]u8 {
+ var arena: std.heap.ArenaAllocator = .init(p.gpa);
+ defer arena.deinit();
+ const surface = try p.render(arena.allocator());
+ var styles: std.ArrayList(pardes.CellStyle) = .empty;
+ var indices: std.ArrayList(usize) = .empty;
+ for (surface.cells) |cell| {
+ const style: pardes.CellStyle = if (cell.default) .{} else cell.style;
+ const index = for (styles.items, 0..) |previous, i| {
+ if (std.meta.eql(style, previous)) break i;
+ } else new: {
+ try styles.append(arena.allocator(), style);
+ break :new styles.items.len - 1;
+ };
+ try indices.append(arena.allocator(), index);
+ }
+ var out: std.Io.Writer.Allocating = .init(p.gpa);
+ errdefer out.deinit();
+ const writer = &out.writer;
+ try writer.print("{{\"cols\":{d},\"rows\":{d},\"cursor\":", .{ surface.cols, surface.rows });
+ try std.json.Stringify.value(surface.cursor, .{}, writer);
+ try writer.writeAll(",\"styles\":");
+ try std.json.Stringify.value(styles.items, .{ .emit_strings_as_arrays = true }, writer);
+ try writer.writeAll(",\"cells\":[");
+ for (surface.cells, indices.items, 0..) |cell, index, i| {
+ if (i != 0) try writer.writeByte(',');
+ try std.json.Stringify.value(.{ if (cell.default) " " else cell.grapheme(), index }, .{}, writer);
+ }
+ try writer.writeByte(']');
+ // The pictures over the cells, which every frontend realises its own
+ // way (pixels, or glyph art in `rect`'s cells): a frame without any
+ // has no `images`.
+ if (surface.placements.items.len > 0) {
+ try writer.writeAll(",\"images\":[");
+ for (surface.placements.items, 0..) |place, i| {
+ if (i != 0) try writer.writeByte(',');
+ const serial = if (p.panes[place.pane]) |pane| pane.serial else 0;
+ try writer.print("{{\"serial\":{d},\"rect\":[{d},{d},{d},{d}],\"src\":[{d},{d},{d},{d}],\"key\":\"{x:0>16}\",\"petscii\":{}}}", .{
+ serial, place.dst.x, place.dst.y, place.dst.w, place.dst.h,
+ place.src.x, place.src.y, place.src.w, place.src.h, place.key,
+ place.art.glyph,
+ });
+ }
+ try writer.writeByte(']');
+ }
+ try writer.writeAll("}\n");
+ return out.toOwnedSlice();
+}
+
+pub fn readSnapshot(p: *Pardes, req: Req, pane: ?*Pane) Reply {
+ const snapshot = &(tree.openOf(p, req) orelse return Reply.fail(req.tag, E.INVAL)).what.snapshot;
+ if (snapshot.* == null) {
+ const terminal = pane orelse return Reply.fail(req.tag, E.INVAL);
+ snapshot.* = pardes.Term.scrollback(terminal.terminal, p.gpa) catch return Reply.fail(req.tag, E.NOMEM);
+ }
+ return tree.window(p, req, snapshot.*.?);
+}
+
+/// /listeners' text, a dial a line, in the step's scratch.
+pub fn listenersText(p: *Pardes) std.Io.Writer.Error![]const u8 {
+ var text: std.Io.Writer.Allocating = .init(p.scratch.allocator());
+ if (p.fs.socket_path.len != 0) try text.writer.print("unix!{s}\n", .{p.fs.socket_path});
+ if (p.fs.tcp_address) |address| switch (address) {
+ .ip4 => |ip| try text.writer.print("tcp!{d}.{d}.{d}.{d}!{d}\n", .{ ip.bytes[0], ip.bytes[1], ip.bytes[2], ip.bytes[3], ip.port }),
+ .ip6 => |ip| try text.writer.print("tcp!{f}!{d}\n", .{ std.Io.net.Ip6Address.Unresolved{ .bytes = ip.bytes, .interface_name = null }, ip.port }),
+ };
+ return text.written();
+}
+
+// ---- tests ----
+
+const testing = std.testing;
+const th = @import("testing.zig");
+const fs = @import("../fs.zig");
+const call = th.call;
+const rd = th.rd;
+const wr = th.wr;
+const withFile = th.withFile;
+const withTerm = th.withTerm;
+const serialOf = th.serialOf;
+const Node = tree.Node;
+const Status = tree.Status;
+const screen_node = @backingInt(tree.TopFile.screen);
+
+test "listener addresses are readable canonical dials with bounded partial reads" {
+ const gpa = testing.allocator;
+ const p = try Pardes.init(gpa, .{ .tty_only = true });
+ defer p.deinit();
+ p.fs.socket_path = "/tmp/a socket.sock";
+ p.fs.tcp_address = .{ .ip6 = .loopback(5641) };
+ const expected = "unix!/tmp/a socket.sock\ntcp!::1!5641\n";
+ for ([_][]const u8{ "/virtual/listeners", "/n/self/listeners" }) |path| {
+ const bytes = try fs.read(p, path);
+ defer gpa.free(bytes);
+ try testing.expectEqualStrings(expected, bytes);
+ try testing.expectError(error.ReadOnlyFilesystem, fs.write(p, path, ""));
+ }
+ const node = @backingInt(tree.TopFile.listeners);
+ var off: usize = 0;
+ while (off < expected.len) {
+ const part = rd(p, node, off, 3);
+ try testing.expectEqual(Status.ok, part.reply.status);
+ try testing.expectEqualStrings(expected[off..][0..@min(3, expected.len - off)], part.bytes);
+ off += part.bytes.len;
+ }
+ try testing.expectEqual(@as(usize, 0), rd(p, node, off, 3).bytes.len);
+}
+
+test "terminal body handles keep one history snapshot across fragmented reads" {
+ const gpa = testing.allocator;
+ const p = try withTerm(gpa);
+ defer p.deinit();
+ const node = Node.of(serialOf(p), .body);
+ p.update(.{ .output = .{ .pane = 0, .bytes = "old caf\xc3\xa9\r\nold tail" } });
+ while (p.nextEffect()) |_| {}
+ const original = try pardes.Term.scrollback(p.panes[0].?.terminal, gpa);
+ defer gpa.free(original);
+ const opened = call(p, .{ .tag = 1, .op = .open, .node = node });
+ try testing.expectEqual(Status.ok, opened.reply.status);
+ const first = call(p, .{ .tag = 2, .op = .read, .node = node, .handle = opened.reply.handle, .size = 3 });
+ try testing.expectEqualStrings(original[0..3], first.bytes);
+ p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[3J\x1b[2J\x1b[Hnew output" } });
+ while (p.nextEffect()) |_| {}
+ var offset: usize = 3;
+ while (offset < original.len) {
+ const part = call(p, .{ .tag = 3, .op = .read, .node = node, .handle = opened.reply.handle, .off = offset, .size = 3 });
+ try testing.expectEqualStrings(original[offset..][0..@min(3, original.len - offset)], part.bytes);
+ offset += part.bytes.len;
+ }
+ try testing.expectEqualStrings("", call(p, .{ .tag = 4, .op = .read, .node = node, .handle = opened.reply.handle, .off = original.len, .size = 3 }).bytes);
+ _ = call(p, .{ .tag = 5, .op = .release, .node = node, .handle = opened.reply.handle });
+ const newer = call(p, .{ .tag = 6, .op = .open, .node = node });
+ try testing.expectEqualStrings("new output\n", call(p, .{ .tag = 7, .op = .read, .node = node, .handle = newer.reply.handle, .size = 32 }).bytes);
+ _ = call(p, .{ .tag = 8, .op = .release, .node = node, .handle = newer.reply.handle });
+}
+
+test "an empty terminal body snapshot stays empty while output continues" {
+ const p = try withTerm(std.testing.allocator);
+ defer p.deinit();
+ const node = Node.of(serialOf(p), .body);
+ const opened = call(p, .{ .tag = 1, .op = .open, .node = node });
+ try testing.expectEqualStrings("", call(p, .{ .tag = 2, .op = .read, .node = node, .handle = opened.reply.handle, .size = 32 }).bytes);
+ try testing.expect(p.fs.opens[opened.reply.handle - 1].what.snapshot != null);
+ p.update(.{ .output = .{ .pane = 0, .bytes = "new output" } });
+ while (p.nextEffect()) |_| {}
+ try testing.expectEqualStrings("", call(p, .{ .tag = 3, .op = .read, .node = node, .handle = opened.reply.handle, .size = 32 }).bytes);
+ _ = call(p, .{ .tag = 4, .op = .release, .node = node, .handle = opened.reply.handle });
+ const newer = call(p, .{ .tag = 5, .op = .open, .node = node });
+ try testing.expectEqualStrings("new output\n", call(p, .{ .tag = 6, .op = .read, .node = node, .handle = newer.reply.handle, .size = 32 }).bytes);
+ _ = call(p, .{ .tag = 7, .op = .release, .node = node, .handle = newer.reply.handle });
+}
+
+test "terminal body snapshots are lazy bounded and released after the pane closes" {
+ const gpa = testing.allocator;
+ const p = try withTerm(gpa);
+ defer p.deinit();
+ const node = Node.of(serialOf(p), .body);
+ var handles: [tree.open_slots]u32 = undefined;
+ for (&handles) |*opened_handle| {
+ const opened = call(p, .{ .tag = 1, .op = .open, .node = node });
+ try testing.expectEqual(Status.ok, opened.reply.status);
+ opened_handle.* = opened.reply.handle;
+ }
+ for (p.fs.opens) |o| {
+ try testing.expectEqual(node, o.node);
+ try testing.expect(o.what.snapshot == null);
+ }
+ try testing.expectEqual(E.NFILE, call(p, .{ .tag = 2, .op = .open, .node = node }).errno());
+ const scratch = try th.newPane(p);
+ const scratch_id = p.paneBySerial(scratch).?;
+ try testing.expect(p.panes[scratch_id].?.file != null);
+ p.update(.{ .output = .{ .pane = 0, .bytes = "latest output" } });
+ while (p.nextEffect()) |_| {}
+ var failing = std.testing.FailingAllocator.init(gpa, .{ .fail_index = 0 });
+ p.gpa = failing.allocator();
+ const failed = call(p, .{ .tag = 3, .op = .read, .node = node, .handle = handles[0], .size = 32 });
+ p.gpa = gpa;
+ try testing.expectEqual(E.NOMEM, failed.errno());
+ try testing.expect(p.fs.opens[handles[0] - 1].what.snapshot == null);
+ const first = call(p, .{ .tag = 4, .op = .read, .node = node, .handle = handles[0], .size = 32 });
+ try testing.expectEqualStrings("latest output\n", first.bytes);
+ const saved = p.fs.opens[handles[0] - 1].what.snapshot.?;
+ failing = std.testing.FailingAllocator.init(gpa, .{ .fail_index = 0 });
+ p.gpa = failing.allocator();
+ const second = call(p, .{ .tag = 5, .op = .read, .node = node, .handle = handles[0], .off = 7, .size = 32 });
+ p.gpa = gpa;
+ try testing.expectEqualStrings("output\n", second.bytes);
+ try testing.expect(!failing.has_induced_failure);
+ try testing.expectEqual(saved.ptr, p.fs.opens[handles[0] - 1].what.snapshot.?.ptr);
+ try testing.expectEqual(E.INVAL, call(p, .{ .tag = 6, .op = .read, .node = screen_node, .handle = handles[0], .size = 32 }).errno());
+ _ = call(p, .{ .tag = 7, .op = .release, .node = screen_node, .handle = handles[0] });
+ try testing.expectEqual(node, p.fs.opens[handles[0] - 1].node);
+ try p.removePane(0, null);
+ for (handles) |opened_handle| _ = call(p, .{ .tag = 8, .op = .release, .node = node, .handle = opened_handle });
+ for (p.fs.opens) |o| try testing.expectEqual(@as(u64, 0), o.node);
+}
+
+test "screen snapshots preserve rendered cells and styles until their handle is released" {
+ const gpa = testing.allocator;
+ const p = try withFile(gpa, "const value = 1;\n");
+ defer p.deinit();
+ const opened = call(p, .{ .tag = 1, .op = .open, .node = screen_node });
+ try testing.expectEqual(Status.ok, opened.reply.status);
+ const snapshot = p.fs.opens[opened.reply.handle - 1].what.snapshot.?;
+ const original = try gpa.dupe(u8, snapshot);
+ defer gpa.free(original);
+ const parsed = try std.json.parseFromSlice(std.json.Value, gpa, original, .{});
+ defer parsed.deinit();
+ const data = parsed.value.object;
+ try testing.expectEqual(@as(i64, p.view().screen_w), data.get("cols").?.integer);
+ try testing.expectEqual(@as(i64, p.view().screen_h), data.get("rows").?.integer);
+ try testing.expectEqual(@as(usize, p.view().screen_w) * p.view().screen_h, data.get("cells").?.array.items.len);
+ try testing.expect(data.get("styles").?.array.items.len > 0);
+ _ = wr(p, Node.of(serialOf(p), .body), "changed\n");
+ const newer = call(p, .{ .tag = 2, .op = .open, .node = screen_node });
+ try testing.expectEqual(Status.ok, newer.reply.status);
+ try testing.expect(!std.mem.eql(u8, original, p.fs.opens[newer.reply.handle - 1].what.snapshot.?));
+ var off: usize = 0;
+ while (off < original.len) {
+ const result = call(p, .{ .tag = 3, .op = .read, .node = screen_node, .handle = opened.reply.handle, .off = off, .size = 13 });
+ try testing.expectEqual(Status.ok, result.reply.status);
+ try testing.expectEqualSlices(u8, original[off..][0..@min(13, original.len - off)], result.bytes);
+ off += result.bytes.len;
+ }
+ _ = call(p, .{ .tag = 4, .op = .release, .node = screen_node, .handle = opened.reply.handle });
+ _ = call(p, .{ .tag = 5, .op = .release, .node = screen_node, .handle = newer.reply.handle });
+ for (p.fs.opens) |o| try testing.expect(o.node == 0);
+}
+
+test "screen inspection leaves the next real frame as it would have been" {
+ const gpa = testing.allocator;
+ const control = try withFile(gpa, "const value = 1;\n");
+ defer control.deinit();
+ const inspected = try withFile(gpa, "const value = 1;\n");
+ defer inspected.deinit();
+ var arena: std.heap.ArenaAllocator = .init(gpa);
+ defer arena.deinit();
+ for ([_]*Pardes{ control, inspected }) |p| {
+ p.update(.tick);
+ _ = try p.render(arena.allocator());
+ p.presented();
+ }
+ for (0..4) |phase| {
+ for ([_]*Pardes{ control, inspected }) |p| switch (phase) {
+ 0 => {},
+ 1 => p.update(.{ .command = "New" }),
+ 2 => {
+ p.update(.tick);
+ try testing.expectEqual(Status.ok, wr(p, Node.of(p.panes[p.view().active].?.serial, .body), "changed cells\n").reply.status);
+ },
+ 3 => p.update(.{ .command = "Del" }),
+ else => unreachable,
+ };
+ for (0..2) |_| {
+ const opened = call(inspected, .{ .tag = 1, .op = .open, .node = screen_node });
+ try testing.expectEqual(Status.ok, opened.reply.status);
+ const captured = call(inspected, .{ .tag = 2, .op = .read, .node = screen_node, .handle = opened.reply.handle, .size = 32 });
+ try testing.expectEqual(Status.ok, captured.reply.status);
+ try testing.expect(captured.bytes.len > 0);
+ try testing.expectEqual(Status.ok, call(inspected, .{
+ .tag = 3,
+ .op = .release,
+ .node = screen_node,
+ .handle = opened.reply.handle,
+ }).reply.status);
+ }
+ const expected = try control.render(arena.allocator());
+ const actual = try inspected.render(arena.allocator());
+ try testing.expectEqual(expected.cols, actual.cols);
+ try testing.expectEqual(expected.rows, actual.rows);
+ try testing.expectEqualDeep(expected.cursor, actual.cursor);
+ try testing.expectEqual(expected.cells.len, actual.cells.len);
+ try testing.expectEqual(@as(usize, 0), expected.placements.items.len);
+ try testing.expectEqual(@as(usize, 0), actual.placements.items.len);
+ for (expected.cells, actual.cells) |*left, *right| try testing.expect(left.visuallyEqual(right));
+ control.presented();
+ inspected.presented();
+ _ = arena.reset(.retain_capacity);
+ }
+}
+
+test "a terminal's body is its logical lines: a row the terminal wrapped is joined again" {
+ const p = try th.withTerm(testing.allocator);
+ defer p.deinit();
+ const pane = p.panes[0].?;
+ const long = &@as([50]u8, @splat('w')) ++ &@as([150]u8, @splat('x')); // wider than the pane: it wraps
+ try testing.expect(long.len > pane.cols);
+ p.update(.{ .output = .{ .pane = 0, .bytes = long ++ "\r\nnext" } });
+ while (p.nextEffect()) |_| {}
+ const node = Node.of(pane.serial, .body);
+ const body = th.rd(p, node, 0, 4096).bytes;
+ try testing.expectEqualStrings(long ++ "\nnext\n", body);
+ try testing.expectEqual(@as(u64, body.len), th.call(p, .{ .tag = 1, .op = .getattr, .node = node }).reply.attr.size);
+}
diff --git a/core/ninep/sources.zig b/core/ninep/sources.zig
new file mode 100644
index 00000000..1d804e31
--- /dev/null
+++ b/core/ninep/sources.zig
@@ -0,0 +1,148 @@
+//! The editor's embedded sources, served read-only from the root when the
+//! build carries them (-Dembed-sources=true).
+const std = @import("std");
+const pardes = @import("../root.zig");
+const fs = @import("../fs.zig");
+const tree = @import("tree.zig");
+
+const Pardes = pardes.Pardes;
+const Req = tree.Req;
+const Reply = tree.Reply;
+const E = tree.E;
+const sources = fs.sources;
+
+pub const archive_node: u64 = 1 << 61;
+
+/// The node of an archive path, or null when nothing embedded lives there.
+/// The empty path is the archive root, which is never listed by itself.
+pub fn node(path: []const u8) ?u64 {
+ if (path.len == 0) return archive_node;
+ if (path.len >= 4096) return null;
+ for (sources, 0..) |source, i| {
+ if (std.mem.eql(u8, source.path, path) or
+ (source.path.len > path.len and source.path[path.len] == '/' and std.mem.startsWith(u8, source.path, path)))
+ return archive_node | (@as(u64, i) << 12) | path.len;
+ }
+ return null;
+}
+
+fn info(n: u64) ?struct { path: []const u8, contents: []const u8, dir: bool } {
+ if (n == archive_node) return .{ .path = "", .contents = "", .dir = true };
+ const index = (n & ~archive_node) >> 12;
+ if (index >= sources.len) return null;
+ const source = sources[@intCast(index)];
+ const len: usize = @intCast(n & 4095);
+ if (len > source.path.len) return null;
+ return .{ .path = source.path[0..len], .contents = source.contents, .dir = len < source.path.len };
+}
+
+/// Stages the children of one archive directory; "" lists the top-level
+/// directories the served root shows.
+pub fn stage(p: *Pardes, out: *std.ArrayList(u8), path: []const u8, skip: *u64) error{OutOfMemory}!void {
+ var seen: [sources.len][]const u8 = undefined;
+ var count: usize = 0;
+ for (sources, 0..) |source, i| {
+ if (path.len != 0 and
+ (source.path.len <= path.len or source.path[path.len] != '/' or !std.mem.startsWith(u8, source.path, path))) continue;
+ const start = if (path.len == 0) 0 else path.len + 1;
+ const rest = source.path[start..];
+ const len = std.mem.indexOfScalar(u8, rest, '/') orelse rest.len;
+ const name = rest[0..len];
+ var duplicate = false;
+ for (seen[0..count]) |previous| if (std.mem.eql(u8, name, previous)) {
+ duplicate = true;
+ break;
+ };
+ if (duplicate) continue;
+ seen[count] = name;
+ count += 1;
+ if (skip.* > 0) {
+ skip.* -= 1;
+ continue;
+ }
+ const child = archive_node | (@as(u64, i) << 12) | (start + len);
+ try tree.stageDirent(out, p.gpa, child, len < rest.len, name);
+ }
+}
+
+pub fn handle(p: *Pardes, req: Req) Reply {
+ const found = info(req.node) orelse return Reply.fail(req.tag, E.NOENT);
+ const attr: Reply.Attr = .{
+ .node = req.node,
+ .name = std.Io.Dir.path.basename(found.path),
+ .dir = found.dir,
+ .size = if (found.dir) 0 else found.contents.len,
+ .mode = if (found.dir) 0o555 else 0o444,
+ .mtime = p.fs.started,
+ };
+ switch (req.op) {
+ .getattr => return .{ .tag = req.tag, .attr = attr },
+ .open => return .{ .tag = req.tag, .handle = 1 },
+ .release => return .{ .tag = req.tag },
+ .lookup => {
+ if (!found.dir) return Reply.fail(req.tag, E.NOTDIR);
+ if (std.mem.eql(u8, req.data, "..")) {
+ const parent = std.Io.Dir.path.dirname(found.path) orelse "";
+ if (parent.len == 0) return tree.handle(p, .{ .tag = req.tag, .op = .getattr, .node = tree.root });
+ const parent_node = node(parent) orelse return Reply.fail(req.tag, E.NOENT);
+ return handle(p, .{ .tag = req.tag, .op = .getattr, .node = parent_node });
+ }
+ if (req.data.len == 0 or std.mem.indexOfAny(u8, req.data, "/\x00") != null) return Reply.fail(req.tag, E.NOENT);
+ var buf: [4096]u8 = undefined;
+ const path = if (found.path.len == 0) req.data else std.fmt.bufPrint(&buf, "{s}/{s}", .{ found.path, req.data }) catch return Reply.fail(req.tag, E.NOENT);
+ const child = node(path) orelse return Reply.fail(req.tag, E.NOENT);
+ return handle(p, .{ .tag = req.tag, .op = .getattr, .node = child });
+ },
+ .readdir => {
+ if (!found.dir) return Reply.fail(req.tag, E.NOTDIR);
+ const out = p.fs.stage(p.gpa);
+ var skip = req.off;
+ stage(p, out, found.path, &skip) catch return Reply.fail(req.tag, E.NOMEM);
+ return .{ .tag = req.tag, .payload = .{ .staged = @intCast(out.items.len) } };
+ },
+ .read => {
+ if (found.dir) return Reply.fail(req.tag, E.PERM);
+ return tree.window(p, req, found.contents);
+ },
+ else => return Reply.fail(req.tag, E.PERM),
+ }
+}
+
+const testing = std.testing;
+const th = @import("testing.zig");
+const limits = @import("../memory.zig").limits;
+
+test "embedded sources appear under the root only when the build carries them" {
+ const p = try th.withFile(testing.allocator, "x\n");
+ defer p.deinit();
+ var buf: [64]th.Dirent = undefined;
+ const top = th.dirents(th.rdir(p, tree.root, 0).bytes, &buf);
+ const listed = th.nameAt(top, "src");
+ try testing.expectEqual(limits.embedded_sources, listed != null);
+ const looked = th.look_up(p, tree.root, "src");
+ try testing.expectEqual(limits.embedded_sources, looked.reply.status == .ok);
+ try testing.expect(tree.resolveSelf(p, "shaders/../src/../") == tree.root);
+ if (!limits.embedded_sources) {
+ try testing.expect(tree.resolveSelf(p, "src/pardes.zig") == null);
+ try testing.expect(tree.resolveSelf(p, "src") == null);
+ try testing.expect(th.nameAt(top, "build.zig") == null);
+ return;
+ }
+ try testing.expect(looked.reply.attr.dir);
+ try testing.expectEqual(@as(u16, 0o555), looked.reply.attr.mode);
+ try testing.expectEqual(listed.?.node, looked.reply.attr.node);
+ try testing.expect(th.nameAt(top, "build.zig") == null);
+ try testing.expect(th.nameAt(top, "build.zig.zon") == null);
+ const file = th.look_up(p, looked.reply.attr.node, "pardes.zig");
+ try testing.expectEqual(tree.Status.ok, file.reply.status);
+ try testing.expectEqual(@as(u16, 0o444), file.reply.attr.mode);
+ try testing.expectEqual(@as(u64, fs.sourceBytes("src/pardes.zig").?.len), file.reply.attr.size);
+ try testing.expectEqual(file.reply.attr.node, tree.resolveSelf(p, "src/pardes.zig").?);
+ const opened = th.call(p, .{ .tag = 1, .op = .open, .node = file.reply.attr.node });
+ const head = th.call(p, .{ .tag = 2, .op = .read, .node = file.reply.attr.node, .handle = opened.reply.handle, .size = 16 });
+ try testing.expectEqualStrings(fs.sourceBytes("src/pardes.zig").?[0..16], head.bytes);
+ const parent = th.look_up(p, looked.reply.attr.node, "..");
+ try testing.expectEqual(tree.root, parent.reply.attr.node);
+ try testing.expectEqual(E.NOENT, th.look_up(p, tree.root, "build.zig").errno());
+ try testing.expectEqual(E.NOENT, th.look_up(p, looked.reply.attr.node, "missing.zig").errno());
+}
diff --git a/core/ninep/testing.zig b/core/ninep/testing.zig
new file mode 100644
index 00000000..23a9199f
--- /dev/null
+++ b/core/ninep/testing.zig
@@ -0,0 +1,168 @@
+//! Test helpers shared by the control-tree modules: drive one request
+//! through the core and collect the reply and the effects it raised.
+const std = @import("std");
+const pardes = @import("../root.zig");
+const tree = @import("tree.zig");
+const cloud9 = @import("cloud9");
+
+const Pardes = pardes.Pardes;
+pub const Req = tree.Req;
+pub const Reply = tree.Reply;
+pub const E = tree.E;
+
+pub const Answer = struct {
+ reply: Reply = .{ .tag = 0, .status = .err, .errno = E.IO },
+ bytes: []const u8 = "",
+ saved: bool = false,
+ watch: ?bool = null,
+ pty_buf: [256]u8 = undefined,
+ pty_len: usize = 0,
+ winsize: ?struct { cols: u16, rows: u16 } = null,
+ signal: ?pardes.PtySignal = null,
+ spawned: bool = false,
+ closed: bool = false,
+
+ pub fn pty(a: *const Answer) []const u8 {
+ return a.pty_buf[0..a.pty_len];
+ }
+
+ pub fn errno(a: Answer) u16 {
+ return if (a.reply.status == .err) a.reply.errno else 0;
+ }
+};
+
+pub fn call(p: *Pardes, req: Req) Answer {
+ var ans: Answer = .{};
+ ans.reply = p.serveFs(req);
+ // An EINVAL or ENOENT refusal says so in words a 9ns mount maps back
+ // to it (cloud9's enameErrno), or a shell through the mount hears EIO.
+ const said = ans.reply;
+ if (said.status == .err and said.ename.len > 0 and (said.errno == E.INVAL or said.errno == E.NOENT) and cloud9.fs.enameErrno(said.ename) != said.errno) {
+ std.debug.print("a mount reads this refusal as errno {d}, not {d}: \"{s}\"\n", .{ cloud9.fs.enameErrno(said.ename), said.errno, said.ename });
+ @panic("a refusal's words do not say its errno");
+ }
+ ans.bytes = p.fsPayload(ans.reply);
+ while (p.nextEffect()) |e| switch (e) {
+ .save_file, .save_text => ans.saved = true,
+ .watch => |w| ans.watch = w.on,
+ .write => |w| {
+ const b = w.bytes.slice();
+ const n = @min(b.len, ans.pty_buf.len - ans.pty_len);
+ @memcpy(ans.pty_buf[ans.pty_len..][0..n], b[0..n]);
+ ans.pty_len += n;
+ },
+ .resize_pty => |r| ans.winsize = .{ .cols = r.cols, .rows = r.rows },
+ .signal_pty => |s| ans.signal = s.sig,
+ .close_pty => ans.closed = true,
+ .spawn => ans.spawned = true,
+ else => {},
+ };
+ return ans;
+}
+
+pub fn rd(p: *Pardes, node: u64, off: u64, size: u32) Answer {
+ return call(p, .{ .tag = 1, .op = .read, .node = node, .off = off, .size = size });
+}
+
+/// Whether the log, read whole from a fresh open, holds `needle`.
+pub fn logHas(p: *Pardes, needle: []const u8) bool {
+ return logCount(p, needle) > 0;
+}
+
+/// How many times the log, read whole from a fresh open, holds `needle`.
+pub fn logCount(p: *Pardes, needle: []const u8) usize {
+ const log = @backingInt(tree.TopFile.log);
+ const h = call(p, .{ .tag = 1, .op = .open, .node = log }).reply.handle;
+ defer _ = call(p, .{ .tag = 3, .op = .release, .node = log, .handle = h });
+ const text = call(p, .{ .tag = 2, .op = .read, .node = log, .handle = h, .size = 1 << 16 }).bytes;
+ return std.mem.count(u8, text, needle);
+}
+
+pub fn wr(p: *Pardes, node: u64, data: []const u8) Answer {
+ return call(p, .{ .tag = 2, .op = .write, .node = node, .data = data });
+}
+
+pub fn rdir(p: *Pardes, node: u64, skip: u64) Answer {
+ return call(p, .{ .tag = 4, .op = .readdir, .node = node, .off = skip, .size = 4096 });
+}
+
+pub fn look_up(p: *Pardes, dir: u64, name: []const u8) Answer {
+ return call(p, .{ .tag = 3, .op = .lookup, .node = dir, .data = name });
+}
+
+/// Makes a pane the way a client does, by walking to /pane/new, and answers
+/// the serial of the pane the walk landed on.
+/// The open is what makes the pane; the handle it answers is the serial, which
+/// is also what a read of that fid reports.
+pub fn newPane(p: *Pardes) !u32 {
+ const made = call(p, .{ .tag = 8, .op = .open, .node = @backingInt(tree.TopFile.new) });
+ if (made.reply.status != .ok or made.reply.handle == 0) return error.NoPane;
+ return made.reply.handle;
+}
+
+pub fn rmdir(p: *Pardes, node: u64) Answer {
+ return call(p, .{ .tag = 9, .op = .release, .node = node, .remove = true });
+}
+
+pub fn withFile(gpa: std.mem.Allocator, text: []const u8) !*Pardes {
+ const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24 });
+ errdefer p.deinit();
+ while (p.nextEffect()) |_| {}
+ _ = try p.setTestFile(text);
+ while (p.nextEffect()) |_| {}
+ return p;
+}
+
+pub fn withTerm(gpa: std.mem.Allocator) !*Pardes {
+ if (pardes.Term.ops == null) return error.SkipZigTest; // a shell
+ const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24 });
+ errdefer p.deinit();
+ while (p.nextEffect()) |_| {}
+ std.debug.assert(p.panes[0].?.isTerminal());
+ return p;
+}
+
+pub fn serialOf(p: *Pardes) u32 {
+ return p.panes[0].?.serial;
+}
+
+pub const Dirent = struct { node: u64, dir: bool, name: []const u8 };
+
+pub fn dirents(bytes: []const u8, out: []Dirent) []Dirent {
+ var n: usize = 0;
+ var i: usize = 0;
+ while (i + 10 <= bytes.len and n < out.len) {
+ const node = std.mem.readInt(u64, bytes[i..][0..8], .little);
+ const kind = bytes[i + 8];
+ const len = bytes[i + 9];
+ i += 10;
+ if (i + len > bytes.len) break;
+ out[n] = .{ .node = node, .dir = kind == 1, .name = bytes[i .. i + len] };
+ i += len;
+ n += 1;
+ }
+ return out[0..n];
+}
+
+pub fn nameAt(list: []const Dirent, want: []const u8) ?Dirent {
+ for (list) |d| if (std.mem.eql(u8, d.name, want)) return d;
+ return null;
+}
+
+/// A host that starts shells and does nothing else: the core alone starts
+/// none.
+pub const starting: pardes.Host.VTable = .{ .spawn = startNothing };
+
+fn startNothing(_: ?*anyopaque, _: u8, _: []const u8) void {}
+
+pub const FakeTty = struct {
+ taken: bool,
+
+ pub const vtable: pardes.Host.VTable = .{ .tty_taken = answer };
+
+ fn answer(ctx: ?*anyopaque, pane: u8) bool {
+ _ = pane;
+ const f: *FakeTty = @ptrCast(@alignCast(ctx.?));
+ return f.taken;
+ }
+};
diff --git a/core/ninep/tree.zig b/core/ninep/tree.zig
new file mode 100644
index 00000000..d13a1b19
--- /dev/null
+++ b/core/ninep/tree.zig
@@ -0,0 +1,2273 @@
+//! The control tree served over 9P: its nodes, lookup, readdir and the
+//! dispatch that answers the engine (cloud9.fs.Server, configured in
+//! runtime/9p.zig). The backend contract (Req, Reply, Op, Status, E) is cloud9's,
+//! extended here with the editor's reply payload; fs.zig keeps host access
+//! and mounts.
+//!
+//! /README /index /status /look /exec /log /screen /listeners /sessions
+//! /pane/new an open makes a pane, a read names it
+//! /pane/<serial> rmdir closes that pane
+//! /pane/<serial>/{name,body,tag,ctl,addr,dot,limit,data,xdata,sel,
+//! dirty,mark,scroll,errors,event,look,exec,pty/}
+//! /os/... the host filesystem /src/... embedded sources (opt-in)
+const std = @import("std");
+const cloud9 = @import("cloud9");
+const pardes = @import("../root.zig");
+const fs = @import("../fs.zig");
+pub const events = @import("events.zig");
+pub const pane = @import("pane.zig");
+pub const addr = @import("addr.zig");
+pub const ctl = @import("ctl.zig");
+pub const cols = @import("cols.zig");
+const layout = pardes.layout;
+pub const pty = @import("pty.zig");
+pub const sources = @import("sources.zig");
+pub const screen = @import("screen.zig");
+const daemon = @import("runtime").daemon;
+const panes = @import("../panes.zig");
+const Plumb = @import("../Plumb.zig");
+
+const Pardes = pardes.Pardes;
+const Pane = pardes.Pane;
+const MAX_PANES = pardes.MAX_PANES;
+
+// ---- the backend contract: cloud9.fs, with the editor's payload locator ----
+
+pub const Op = cloud9.fs.Op;
+pub const Status = cloud9.fs.Status;
+pub const Req = cloud9.fs.Req;
+pub const E = cloud9.fs.E;
+
+/// Where a reply's bytes live. The engine ignores it; `Pardes.fsPayload`
+/// resolves it into the slice that travels beside the reply.
+pub const Payload = union(enum) {
+ none,
+ staged: u32,
+ region: struct { pane: u8, serial: u32, off: u32, len: u32 },
+};
+
+pub const Reply = cloud9.fs.ReplyWith(Payload);
+
+/// 9P answers a failure with a string, not a number (man 5 error): the errno
+/// still travels, for clients that map it, but the string is what a person
+/// reads. acme names its refusals the same way, and these are its spellings
+/// (editors/acme/xfid.c:19) for the ones this tree shares.
+pub fn failText(tag: u64, errno: u16, text: []const u8) Reply {
+ return .{ .tag = tag, .status = .err, .errno = errno, .ename = text };
+}
+
+pub const e_bad_ctl = "ill-formed control message";
+pub const e_bad_event = "bad event syntax";
+/// A second open reading a file whose reads consume: rio's word for it
+/// (windows/rio/xfid.c:25), which 9ns turns into EBUSY.
+pub const e_in_use = "file in use";
+/// A read held on a pane's event or pty/data that the pane closed under.
+/// acme says "window shut down" (xfid.c:1005), which 9ns reads as EIO;
+/// these words read as ENOENT, what every other file of a gone pane gives.
+pub const e_shut_down = "no such pane: its window shut";
+
+/// Tremove closes a pane; nothing else in the tree is created or destroyed by
+/// the protocol, and wstat stays a truncation. Making a pane is an open of
+/// /pane/new, so Tcreate is refused everywhere, as it is in acme
+/// (editors/acme/fsys.c, fsyscreate) -- here rather than by the engine, so
+/// a create in a pane that has closed says the pane is gone (a shell's `>`
+/// to a closed pane's file creates when its lookup fails).
+pub const features: cloud9.fs.Features = .{ .remove = true, .create = true };
+
+/// Whether a request must wait until no step is out in a syscall
+/// (`pardes.turn`): what would change a pane such a step still points into.
+/// Making a pane and rendering a screen do not -- every yield sits before
+/// the mutation of its own step, so the layout and the surface are whole
+/// under it -- and a step out there is never waiting on a write of its own,
+/// so what parks here is never the syscall's own request.
+pub fn needsQuiet(p: *Pardes, req: Req) bool {
+ return switch (req.op) {
+ .write => true,
+ .setattr => truncates(req),
+ .release => req.remove,
+ .read => holdsPage(p, req),
+ else => false,
+ };
+}
+
+/// A setattr that changes something: a truncate of a pane's file or a
+/// tag. `> exec` (a shell's truncating open) changes nothing, so it waits
+/// on nothing: through a mount it hung, as 9ns answers nothing else on the
+/// mount while it is out, and the editor's step may be out reading a pane's
+/// file through that mount, the quiet it waited for never coming.
+fn truncates(req: Req) bool {
+ if (!req.truncate) return false;
+ return switch (Node.target(req.node) orelse return false) {
+ .pane => true,
+ .col => |c| c.file == .tag,
+ .top => |f| f == .tag or f == .rules,
+ .port => false,
+ };
+}
+
+/// `needsQuiet`, plus the open that makes a pane and a close that hands
+/// held text on: what costs a frame and a wake of the editor.
+pub fn changesPane(p: *Pardes, req: Req) bool {
+ return needsQuiet(p, req) or switch (req.op) {
+ .open => req.node == @backingInt(TopFile.new),
+ .release => holdsLines(p, req) or holdsPage(p, req),
+ else => false,
+ };
+}
+
+pub const out_reserve = 4 * 1024;
+
+// ---- opens ----
+
+/// What one open holds from its open to its release, the way lib9p hangs a
+/// server's own state off each fid (`Fid.aux`) and acme keeps it on its Fid
+/// (editors/acme/dat.h:373-385). An open that holds something answers its
+/// record's index plus one as the handle; one that holds nothing answers 0.
+pub const Open = struct {
+ /// The node it was opened on, which every use checks; 0 is a free record.
+ node: u64 = 0,
+ what: union(enum) {
+ /// /screen's frame from the open, a terminal body's history from its
+ /// first read.
+ snapshot: ?[]const u8,
+ log: events.LogOpen,
+ run: pty.Run,
+ /// An open of a pane's event, holding the pane scripted; `true` for
+ /// the one that reads it.
+ event: bool,
+ /// The one open reading a pane's pty/data.
+ pty_data,
+ /// An open that may write a pane's ctl, and so hold its lock.
+ ctl,
+ /// An open of a file that takes lines of commands (look, exec, a
+ /// ctl, tagexec): its `pending` and `results`.
+ lines,
+ /// An open writing a file pane's body, data or xdata: its writes are
+ /// one undo step (pane.zig `joined_by`), another open's its own.
+ writes,
+ /// A listing (`/index`, `/layout`, `/recent`, `/commands`, `/status`,
+ /// `/listeners`, a ctl opened to read) frozen at the open, as
+ /// `/screen` is: reads in several chunks never splice two moments.
+ frozen: []const u8,
+ /// A /pager open past its directory line: the +Pager's serial, the
+ /// text after that line held in `pending` until its read puts it
+ /// in (ctl.fillPager), or its close hands it to the editor's step.
+ pager: u32,
+ /// An open writing plumb/rules or plumb/send: `pending` holds what
+ /// is not whole yet (rule sets with no blank line after them, a
+ /// message short of its data).
+ plumb,
+ /// An open reading a plumb port (Plumb.zig's ports, plumber(4)'s):
+ /// the messages sent to it since the open, packed, a read each.
+ port: struct { index: u8, queue: events.Queue = .{} },
+ } = .{ .snapshot = null },
+ /// What a write to a file of command lines left unfinished: a last line
+ /// with no newline yet, or an Edit block still open. A write through a
+ /// mount is cut at the 9P message size, so one `echo` of many lines may
+ /// come as several writes, cut anywhere; the rest waits for the open's
+ /// next write, or its release, and never runs as a fragment.
+ pending: std.ArrayList(u8) = .empty,
+ /// The panes this open's last write touched, which a read of look or
+ /// exec on it answers, as /net/tcp/clone answers on the open that
+ /// asked; a fresh open holds the session's last, from before it opened.
+ results: Results = .{},
+ /// A read that found nothing yet (`.again`), kept to be answered when
+ /// this open's file has something, the way factotum keeps its log's
+ /// waiting reads and answers them on append (security/auth/factotum/
+ /// log.c:4-52) and acme an event read (editors/acme/xfid.c:994). One at a
+ /// time, as acme's window keeps one `eventx`: a newer read takes the
+ /// place of the older. The listener fills it in and answers it
+ /// (runtime/9p_io.zig, `answerHeld`).
+ held: ?Held = null,
+ /// The last answer a stream open (a followed log, event, pty/data) gave,
+ /// and the offset it was read at. A read at an offset inside it is
+ /// answered from it again: bash's `read` takes a chunk, keeps a line and
+ /// lseeks back to just past it, and a stream has already moved on.
+ replay: ?Replay = null,
+ /// A `name` open has named its pane: one name an open, so a second line
+ /// on it (bash writes `printf 'a\nb\n'` a line at a time) is refused.
+ named: bool = false,
+ /// A line over 1 MiB was refused: what follows of it, through its
+ /// newline, is dropped rather than run as a line of its own.
+ discarding: bool = false,
+
+ pub const Replay = struct { off: u64, bytes: []u8 };
+
+ pub const Results = struct {
+ list: [pardes.MAX_PANES]u32 = undefined,
+ len: u8 = 0,
+ /// Written on: reads are a stream from the write on, whatever
+ /// offset they come at, since a shell's `exec 3<>look` shares one
+ /// offset between the write and the read (as pty/run does).
+ wrote: bool = false,
+ read: usize = 0,
+ };
+
+ /// `asker` is the connection the read came on, which only the listener
+ /// knows.
+ pub const Held = struct { asker: *anyopaque, req: Req, ticket: cloud9.fs.Ticket };
+
+ pub fn deinit(o: *Open, gpa: std.mem.Allocator) void {
+ switch (o.what) {
+ .snapshot => |bytes| if (bytes) |b| gpa.free(b),
+ .log => |log| gpa.free(log.bytes),
+ .run => |run| {
+ gpa.free(run.output);
+ gpa.free(run.line);
+ },
+ .frozen => |bytes| gpa.free(bytes),
+ .port => |*port| port.queue.deinit(gpa),
+ .event, .pty_data, .ctl, .lines, .writes, .pager, .plumb => {},
+ }
+ o.pending.deinit(gpa);
+ if (o.replay) |r| gpa.free(r.bytes);
+ o.* = .{};
+ }
+};
+
+/// Records for 64 opens at once; one more that would hold something fails.
+pub const open_slots = 64;
+
+/// The record a request's handle names, when it was opened on that node.
+pub fn openOf(p: *Pardes, req: Req) ?*Open {
+ if (req.handle == 0 or req.handle > p.fs.opens.len) return null;
+ const o = &p.fs.opens[req.handle - 1];
+ return if (o.node == req.node) o else null;
+}
+
+// ---- nodes ----
+
+pub const TopFile = enum(u5) {
+ root = 1,
+ README,
+ index,
+ status,
+ look,
+ exec,
+ log,
+ screen,
+ listeners,
+ pane,
+ new,
+ focus,
+ ctl,
+ commands,
+ layout,
+ tag,
+ col,
+ tagexec,
+ /// The files opened lately, closed ones too, a line each:
+ /// `open|closed <path>`, most recent first.
+ recent,
+ /// `pardes -`'s: a directory written, a new +Pager made there; a
+ /// read of the same open answers its serial.
+ pager,
+ /// The pardes daemon's sessions and shells, as `pardes --ps` lists
+ /// them: `daemon <pid>`, `session <pid> tty|gui attached|detached
+ /// <name>`, `shell <pid>` (the session above's), `orphan <pid>`.
+ sessions,
+ /// rio's kbdin (windows/rio/xfid.c:515): each rune written is a key
+ /// typed at the pane with the keyboard, done before the write answers.
+ kbdin,
+ /// devmouse's mousein: `m col row buttons`, the mouse as it now is.
+ mousein,
+ /// The dumps the state file keeps (core/Db.zig), a line each, the newest
+ /// first: `<label> <date> <size> <panes>`; `Restore <label>` brings one
+ /// back.
+ dumps,
+ /// The kinds of pane this session has, compiled in or an addon's, and
+ /// the addons refused, a line each: `<kind> <version> <abi>
+ /// static|loaded|refused: why [path]`.
+ addons,
+ /// The plumber's (Plumb.zig, Plan 9's plumber(4)): `rules` and `send`.
+ plumb,
+ /// plumb/rules: the rules in force, plumb(6)'s; a write adds rule
+ /// sets, a `>` replaces them.
+ rules,
+ /// plumb/send: a write is a message, plumb(6)'s six lines and data.
+ send,
+
+ pub fn fileName(f: TopFile) []const u8 {
+ return if (f == .root) "/" else @tagName(f);
+ }
+
+ pub fn mode(f: TopFile) u16 {
+ return switch (f) {
+ .root, .pane, .col, .plumb => 0o755,
+ .look, .exec, .log, .focus, .ctl, .tag, .tagexec, .pager, .rules => 0o666,
+ .README, .index, .status, .screen, .listeners, .new, .commands, .layout, .recent, .dumps, .sessions, .addons => 0o444,
+ .kbdin, .mousein, .send => 0o222,
+ };
+ }
+
+ pub fn dir(f: TopFile) bool {
+ return f == .root or f == .pane or f == .col or f == .plumb;
+ }
+};
+
+pub const root: u64 = @backingInt(TopFile.root);
+
+/// Declaration order is readdir order.
+pub const PaneFile = enum(u5) {
+ dir = 0,
+ name,
+ body,
+ tag,
+ ctl,
+ addr,
+ dot,
+ limit,
+ data,
+ xdata,
+ sel,
+ dirty,
+ mark,
+ scroll,
+ errors,
+ event,
+ look,
+ exec,
+ /// A word run as a click in the pane's tag, as /tagexec is in the
+ /// workspace's and col/<n>/exec in a column's.
+ tagexec,
+ /// A line a body row: where it points and how it is coloured
+ /// (locations.formatRows), a results pane's; written, the pane's.
+ rows,
+ pty,
+ pty_ctl,
+ pty_status,
+ pty_data,
+ pty_run,
+
+ pub fn fileName(f: PaneFile) []const u8 {
+ return switch (f) {
+ .dir => ".",
+ .pty_ctl => "ctl",
+ .pty_status => "status",
+ .pty_data => "data",
+ .pty_run => "run",
+ else => @tagName(f),
+ };
+ }
+
+ pub fn mode(f: PaneFile) u16 {
+ return switch (f) {
+ .dir, .pty => 0o755,
+ .errors => 0o222,
+ .pty_status => 0o444,
+ else => 0o666,
+ };
+ }
+
+ pub fn isDir(f: PaneFile) bool {
+ return f == .dir or f == .pty;
+ }
+
+ pub fn inPty(f: PaneFile) bool {
+ return switch (f) {
+ .pty, .pty_ctl, .pty_status, .pty_data, .pty_run => true,
+ else => false,
+ };
+ }
+};
+
+/// /col/<serial> and its tag: a column is named by its serial, which stays
+/// while it lives as a pane's does; this bit, past a pane serial's 32, keeps
+/// the two apart.
+pub const ColFile = enum(u5) {
+ dir = 0,
+ tag = 1,
+ ctl = 2,
+ exec = 3,
+
+ pub fn fileName(f: ColFile) []const u8 {
+ return @tagName(f);
+ }
+};
+const col_bit: u59 = 1 << 58;
+/// plumb/<port>: a port by its place in Plumb's list, which only grows;
+/// past a pane serial's 32 bits and clear of the host tree's and the
+/// archive's high bits (fs.os_node, sources.archive_node).
+const port_bit: u59 = 1 << 40;
+
+pub const Node = packed struct(u64) {
+ file: u5 = 0,
+ serial: u59 = 0,
+
+ pub fn of(serial: u32, file: PaneFile) u64 {
+ std.debug.assert(serial != 0);
+ return @bitCast(Node{ .file = @backingInt(file), .serial = serial });
+ }
+
+ pub fn ofCol(serial: u32, file: ColFile) u64 {
+ return @bitCast(Node{ .file = @backingInt(file), .serial = col_bit | @as(u59, serial) });
+ }
+
+ pub fn ofPort(index: u8) u64 {
+ return @bitCast(Node{ .serial = port_bit | @as(u59, index) });
+ }
+
+ pub fn target(node: u64) ?Target {
+ const n: Node = @bitCast(node);
+ if (n.serial == 0) {
+ return .{ .top = std.enums.fromInt(TopFile, n.file) orelse return null };
+ }
+ if (n.serial & port_bit != 0) return .{ .port = std.math.cast(u8, n.serial & ~port_bit) orelse return null };
+ if (n.serial & col_bit != 0) return .{ .col = .{
+ .serial = std.math.cast(u32, n.serial & ~col_bit) orelse return null,
+ .file = std.enums.fromInt(ColFile, n.file) orelse return null,
+ } };
+ return .{ .pane = .{
+ .serial = std.math.cast(u32, n.serial) orelse return null,
+ .file = std.enums.fromInt(PaneFile, n.file) orelse return null,
+ } };
+ }
+};
+
+pub const Target = union(enum) {
+ top: TopFile,
+ pane: struct { serial: u32, file: PaneFile },
+ col: struct { serial: u32, file: ColFile },
+ port: u8,
+};
+
+/// Opening /pane/new makes a pane and reading the open fid answers its
+/// serial, which is /net/tcp/clone's mechanism exactly (kernel/network/ip/
+/// devip.c, `case Qclone` in ipopen, whose Qctl read prints the number it
+/// allocated). acme spells the same idea as a directory made by the walk
+/// (editors/acme/fsys.c:481), which would be the nicer `new/body`, but a
+/// Plan 9 directory read carries every entry's stat and a kernel or FUSE
+/// mount instead walks each name it listed: allocating on the walk would
+/// make a pane every time someone ran `ls -l`. A stat is not an open, so
+/// this file can be listed. Panes are named by their serial, so the name
+/// can never collide with one.
+pub const new_pane = "new";
+
+pub fn nextSerialAfter(p: *Pardes, after: u32) ?u32 {
+ var best: ?u32 = null;
+ for (p.panes) |slot| {
+ const pn = slot orelse continue;
+ if (pn.serial <= after) continue;
+ if (best == null or pn.serial < best.?) best = pn.serial;
+ }
+ return best;
+}
+
+/// An editor path below the root (`pane/3/body`, `index`, `col/2/tag`,
+/// `src/...`) to its node: the walk a client's would be, a lookup a name,
+/// but for `os` (the disk is /n/os's) and /pane/new, served on the wire but
+/// unreachable from an editor path: this resolves Look targets and hover
+/// previews, and a preview that opened `new` to see what was there would
+/// make a pane per hover.
+pub fn resolveSelf(p: *Pardes, path: []const u8) ?u64 {
+ var path_buf: [4096]u8 = undefined;
+ const normalized = fs.normalizeVirtualPath(path, &path_buf) orelse return null;
+ var node = root;
+ var parts = std.mem.tokenizeScalar(u8, normalized, '/');
+ while (parts.next()) |name| {
+ if (node == root and std.mem.eql(u8, name, "os")) return null;
+ if (node == @backingInt(TopFile.pane) and std.mem.eql(u8, name, new_pane)) return null;
+ const req: Req = .{ .tag = 0, .op = .lookup, .node = node, .data = name };
+ const found = if (node & sources.archive_node != 0) sources.handle(p, req) else lookup(p, req, Node.target(node) orelse return null);
+ if (found.status != .ok) return null;
+ node = found.attr.node;
+ }
+ return node;
+}
+
+// ---- staging ----
+
+pub fn stageDirent(out: *std.ArrayList(u8), gpa: std.mem.Allocator, node: u64, dir: bool, name: []const u8) error{OutOfMemory}!void {
+ if (name.len == 0 or name.len > 255) return;
+ var head: [10]u8 = undefined;
+ std.mem.writeInt(u64, head[0..8], node, .little);
+ head[8] = @intFromBool(dir);
+ head[9] = @intCast(name.len);
+ // Head and name both or neither: a head alone would corrupt the listing.
+ try out.ensureUnusedCapacity(gpa, head.len + name.len);
+ out.appendSliceAssumeCapacity(&head);
+ out.appendSliceAssumeCapacity(name);
+}
+
+/// The daemon's registry (/sessions), its `list` answer as it gave it.
+fn daemonList(gpa: std.mem.Allocator) error{ NoDaemon, OutOfMemory }![]u8 {
+ var buf: [4096]u8 = undefined;
+ const said = daemon.ask("list", &buf) orelse return error.NoDaemon;
+ return gpa.dupe(u8, said);
+}
+
+/// Answers a read from whatever the handler staged, windowed by offset and size.
+pub fn stagedReply(p: *Pardes, req: Req) Reply {
+ const out = &p.fs.out;
+ const off = @min(req.off, out.items.len);
+ const n = @min(out.items.len - off, req.size);
+ if (off > 0) std.mem.copyForwards(u8, out.items[0..n], out.items[off..][0..n]);
+ out.shrinkRetainingCapacity(n);
+ return .{ .tag = req.tag, .payload = .{ .staged = @intCast(n) } };
+}
+
+/// Answers a read with the window of `bytes` its offset and size ask for.
+pub fn window(p: *Pardes, req: Req, bytes: []const u8) Reply {
+ const off = @min(req.off, bytes.len);
+ const n = @min(bytes.len - off, req.size);
+ p.fs.stage(p.gpa).appendSlice(p.gpa, bytes[off..][0..n]) catch return Reply.fail(req.tag, E.NOMEM);
+ return .{ .tag = req.tag, .payload = .{ .staged = @intCast(n) } };
+}
+
+// ---- dispatch ----
+
+pub fn handle(p: *Pardes, req: Req) Reply {
+ var reply = serve(p, req);
+ if (reply.status == .err and reply.ename.len == 0) reply.ename = errWords(reply.errno);
+ if (reply.status == .err and reply.ename.len > cloud9.fs.errmax)
+ if (p.scratch.allocator().alloc(u8, cloud9.fs.errmax)) |room| {
+ reply.ename = fitErr(reply.ename, room);
+ } else |_| {};
+ return reply;
+}
+
+/// A reason longer than an Rerror carries (Plan 9's ERRMAX, 128 bytes)
+/// keeps its end, which says why: the longest path in it -- else the whole
+/// text -- gives up its middle to `…`.
+pub fn fitErr(text: []const u8, out: []u8) []const u8 {
+ const ell = "…";
+ if (text.len <= out.len) return text;
+ const over = text.len - out.len + ell.len;
+ var from: usize = 0;
+ var to: usize = text.len;
+ var words = std.mem.tokenizeAny(u8, text, " \t");
+ var longest: usize = 0;
+ while (words.next()) |w| if (std.mem.indexOfScalar(u8, w, '/') != null and w.len > longest and w.len > over + 2) {
+ longest = w.len;
+ from = @intFromPtr(w.ptr) - @intFromPtr(text.ptr);
+ to = from + w.len;
+ };
+ var a = from + (to - from - over) / 2;
+ var b = a + over;
+ while (a > from and text[a] & 0xC0 == 0x80) a -= 1;
+ while (b < to and text[b] & 0xC0 == 0x80) b += 1;
+ return std.fmt.bufPrint(out, "{s}" ++ ell ++ "{s}", .{ text[0..a], text[b..] }) catch text[0..out.len];
+}
+
+/// A refusal with no reason of its own said in Plan 9's words, not the C
+/// library's (`Operation not permitted`); each maps back to its errno in
+/// 9ns (enameToErrno), EPERM's to EACCES as Plan 9's does.
+pub fn errWords(errno: u16) []const u8 {
+ return switch (errno) {
+ E.PERM => "permission denied",
+ E.NOENT => "file does not exist",
+ E.NOMEM => "out of memory",
+ E.BUSY => "file in use",
+ E.EXIST => "file already exists",
+ E.NOTDIR => "not a directory",
+ E.ISDIR => "is a directory",
+ E.INVAL => "bad argument",
+ E.NFILE => "too many open files",
+ E.NOSPC => "no space left",
+ E.NOSYS => "not supported",
+ E.NOTEMPTY => "directory not empty",
+ else => "i/o error",
+ };
+}
+
+fn serve(p: *Pardes, req: Req) Reply {
+ // Held writes go in before anything but the next write of their open.
+ if (p.fs.batch.bytes.items.len > 0 and !(req.op == .write and req.node == p.fs.batch.node and req.handle == p.fs.batch.handle))
+ pane.flushBatch(p);
+ if (req.op == .open and req.create) {
+ if (Node.target(req.node)) |t| if (t == .pane and p.paneBySerial(t.pane.serial) == null)
+ return Reply.fail(req.tag, E.NOENT);
+ return Reply.fail(req.tag, E.PERM);
+ }
+ const host = req.node == fs.os_root or req.node & fs.os_node != 0;
+ const archive = req.node & sources.archive_node != 0;
+ // Only a pane directory is removed. The host tree and the embedded
+ // sources say so, rather than quietly doing nothing.
+ if ((host or archive) and req.remove) return Reply.fail(req.tag, E.PERM);
+ if (host) return fs.osHandle(p, req);
+ if (archive) return sources.handle(p, req);
+ const target = Node.target(req.node) orelse return Reply.fail(req.tag, E.NOENT);
+ if (req.op == .write or req.op == .setattr) p.fs.origin = switch (target) {
+ .pane => |t| @as(u8, if (t.file == .body or t.file == .tag) 'E' else 'F'),
+ .top, .col, .port => 'F',
+ };
+ return switch (req.op) {
+ .lookup => lookup(p, req, target),
+ .getattr => .{ .tag = req.tag, .attr = attrOf(p, target) orelse runAttr(p, req, target) orelse return Reply.fail(req.tag, E.NOENT) },
+ .setattr => setattr(p, req, target),
+ .open => open(p, req, target),
+ .release => release(p, req),
+ .readdir => readdir(p, req, target),
+ .read => read(p, req, target),
+ .write => write(p, req, target),
+ };
+}
+
+/// A run's answer outlives its pane, so its file still stats while a run
+/// is open on it (a reader's fstat, cat's), as acme's fid keeps its window.
+/// The stat names the open when it came on one; a mount's comes on the
+/// file's walked name, and serials are never reused, so any run open on
+/// this node is the reader's.
+fn runAttr(p: *Pardes, req: Req, target: Target) ?Reply.Attr {
+ const t = switch (target) {
+ .pane => |t| t,
+ .top, .col, .port => return null,
+ };
+ if (t.file != .pty_run) return null;
+ const run = if (req.handle != 0) openOf(p, req) else for (&p.fs.opens) |*o| {
+ if (o.node == req.node and o.what == .run) break o;
+ } else null;
+ if ((run orelse return null).what != .run) return null;
+ return .{ .name = t.file.fileName(), .node = Node.of(t.serial, t.file), .mode = t.file.mode(), .mtime = p.fs.started };
+}
+
+fn attrOf(p: *Pardes, target: Target) ?Reply.Attr {
+ switch (target) {
+ .port => |i| return .{
+ .name = Plumb.portName(p, i) orelse return null,
+ .node = Node.ofPort(i),
+ .mode = 0o444,
+ .mtime = p.fs.started,
+ },
+ .top => |f| return .{
+ .name = f.fileName(),
+ .node = @backingInt(f),
+ .dir = f.dir(),
+ .mode = f.mode(),
+ .size = topSize(p, f),
+ .mtime = p.fs.started,
+ .append = f == .tag,
+ },
+ .col => |c| {
+ if (layout.columnBySerial(p, c.serial) == null) return null;
+ return .{
+ // unreachable: a u32 serial fits node_name (16)
+ .name = if (c.file == .dir) (std.fmt.bufPrint(&p.fs.node_name, "{d}", .{c.serial}) catch unreachable) else c.file.fileName(),
+ .node = Node.ofCol(c.serial, c.file),
+ .dir = c.file == .dir,
+ .mode = switch (c.file) {
+ .dir => 0o755,
+ .ctl => 0o222,
+ .tag, .exec => 0o666,
+ },
+ .size = switch (c.file) {
+ .tag => cols.headerText(p, c.serial).?.len,
+ .exec => ctl.resultsLen(p),
+ else => 0,
+ },
+ .mtime = p.fs.started,
+ .append = c.file == .tag,
+ };
+ },
+ .pane => |t| {
+ const id = p.paneBySerial(t.serial) orelse return null;
+ const pn = p.panes[id].?;
+ if (t.file.inPty() and !pn.isTerminal()) return null;
+ return .{
+ // unreachable: a u32 serial fits node_name (16)
+ .name = if (t.file == .dir) (std.fmt.bufPrint(&p.fs.node_name, "{d}", .{t.serial}) catch unreachable) else t.file.fileName(),
+ .node = Node.of(t.serial, t.file),
+ .dir = t.file.isDir(),
+ .mode = t.file.mode(),
+ .size = pane.fileSize(p, id, t.file),
+ .mtime = if (pn.file) |*f| (if (f.mtime != 0) f.mtime else p.fs.started) else p.fs.started,
+ // The qid version, which a client polls to watch a file for
+ // change. Only the pane's text can promise one: its revision
+ // counts every edit, and nothing else here changes in step.
+ .version = switch (t.file) {
+ .body, .data, .xdata => if (pn.file) |*f| f.revision else 0,
+ else => 0,
+ },
+ // A write to body or tag appends whatever its offset says,
+ // which is why acme's dirtab marks both DMAPPEND
+ // (editors/acme/fsys.c:78).
+ .append = t.file == .body or t.file == .tag,
+ };
+ },
+ }
+}
+
+fn topSize(p: *Pardes, f: TopFile) u64 {
+ return switch (f) {
+ // Views generated whole by each read have no length, as acme's
+ // generated files have none: /screen until an open renders its
+ // frame, /pane/new until an open has a pane to name, and the index,
+ // layout, recent list and listeners, which a stat would otherwise
+ // have to build to count.
+ .root, .pane, .col, .screen, .new, .layout, .index, .recent, .dumps, .addons, .listeners, .sessions, .kbdin, .mousein, .plumb, .rules, .send => 0,
+ .tag => cols.headerText(p, null).?.len,
+ .README => fs.help.len,
+ .status => if (ctl.statusText(p)) |text| text.len else |_| 0,
+ .look, .exec, .tagexec, .pager => ctl.resultsLen(p),
+ // A stream: a length would read as its end to a kernel that caches
+ // one (a 9ns mount's splice), and a follower's reads go past it.
+ .log => 0,
+ .ctl => if (ctl.settingsText(p)) |text| text.len else |_| 0,
+ .commands => if (ctl.commandsText(p)) |text| text.len else |_| 0,
+ .focus => focus: {
+ if (p.view().header != null) break :focus 0;
+ const pn = p.panes[p.view().active] orelse break :focus 0;
+ var digits: [16]u8 = undefined;
+ // unreachable: a u32 serial and a newline fit 16
+ break :focus (std.fmt.bufPrint(&digits, "{d}\n", .{pn.serial}) catch unreachable).len;
+ },
+ };
+}
+
+fn lookup(p: *Pardes, req: Req, target: Target) Reply {
+ const name = req.data;
+ if (std.mem.eql(u8, name, "..")) {
+ const parent: u64 = switch (target) {
+ .top => |top| if (top.dir()) root else return Reply.fail(req.tag, E.NOTDIR),
+ .pane => |t| switch (t.file) {
+ .dir => @backingInt(TopFile.pane),
+ .pty => Node.of(t.serial, .dir),
+ else => return Reply.fail(req.tag, E.NOTDIR),
+ },
+ .col => |c| if (c.file == .dir) @backingInt(TopFile.col) else return Reply.fail(req.tag, E.NOTDIR),
+ .port => return Reply.fail(req.tag, E.NOTDIR),
+ };
+ return handle(p, .{ .tag = req.tag, .op = .getattr, .node = parent });
+ }
+ if (name.len == 0 or std.mem.indexOfAny(u8, name, "/\x00") != null) return Reply.fail(req.tag, E.NOENT);
+ const node: u64 = switch (target) {
+ .top => |f| switch (f) {
+ .root => root: {
+ if (std.mem.eql(u8, name, "os")) return fs.osHandle(p, .{ .tag = req.tag, .op = .getattr, .node = fs.os_root });
+ // `new` is reached in /pane, where the panes it makes are,
+ // `rules` and `send` in /plumb.
+ if (std.meta.stringToEnum(TopFile, name)) |t| if (t != .root and t != .new and t != .rules and t != .send) break :root @backingInt(t);
+ if (sources.node(name)) |n| return sources.handle(p, .{ .tag = req.tag, .op = .getattr, .node = n });
+ return Reply.fail(req.tag, E.NOENT);
+ },
+ .pane, .col => dir: {
+ if (f == .pane and std.mem.eql(u8, name, new_pane)) break :dir @backingInt(TopFile.new);
+ // A pane's or a column's directory is its serial, in decimal
+ // digits and never 0.
+ if (name.len > 10) return Reply.fail(req.tag, E.NOENT);
+ for (name) |c| if (c < '0' or c > '9') return Reply.fail(req.tag, E.NOENT);
+ const serial = std.fmt.parseInt(u32, name, 10) catch return Reply.fail(req.tag, E.NOENT);
+ if (serial == 0) return Reply.fail(req.tag, E.NOENT);
+ break :dir if (f == .pane) Node.of(serial, .dir) else Node.ofCol(serial, .dir);
+ },
+ .plumb => if (std.mem.eql(u8, name, "rules")) @backingInt(TopFile.rules) else if (std.mem.eql(u8, name, "send")) @backingInt(TopFile.send) else if (Plumb.portIndex(p, name)) |i| Node.ofPort(i) else return Reply.fail(req.tag, E.NOENT),
+ else => return Reply.fail(req.tag, E.NOTDIR),
+ },
+ .port => return Reply.fail(req.tag, E.NOTDIR),
+ .col => |c| col: {
+ if (c.file != .dir) return Reply.fail(req.tag, E.NOTDIR);
+ const f = std.meta.stringToEnum(ColFile, name) orelse return Reply.fail(req.tag, E.NOENT);
+ if (f == .dir) return Reply.fail(req.tag, E.NOENT);
+ break :col Node.ofCol(c.serial, f);
+ },
+ .pane => |t| pane: {
+ _ = p.paneBySerial(t.serial) orelse return Reply.fail(req.tag, E.NOENT);
+ const f = switch (t.file) {
+ .dir => if (std.meta.stringToEnum(PaneFile, name)) |f| (if (f == .dir or (f.inPty() and f != .pty)) null else f) else null,
+ .pty => pty.fileNamed(name),
+ else => return Reply.fail(req.tag, E.NOTDIR),
+ } orelse return Reply.fail(req.tag, E.NOENT);
+ break :pane Node.of(t.serial, f);
+ },
+ };
+ const found = Node.target(node) orelse return Reply.fail(req.tag, E.NOENT);
+ return .{ .tag = req.tag, .attr = attrOf(p, found) orelse return Reply.fail(req.tag, E.NOENT) };
+}
+
+fn readdir(p: *Pardes, req: Req, target: Target) Reply {
+ const out = p.fs.stage(p.gpa);
+ stageDir(p, out, target, req.off) catch |err| return Reply.fail(req.tag, switch (err) {
+ error.OutOfMemory => E.NOMEM,
+ error.FileNotFound => E.NOENT,
+ error.NotDir => E.NOTDIR,
+ });
+ return .{ .tag = req.tag, .payload = .{ .staged = @intCast(out.items.len) } };
+}
+
+/// The entries of `target` from the `off`th on, staged into `out`.
+fn stageDir(p: *Pardes, out: *std.ArrayList(u8), target: Target, off: u64) error{ OutOfMemory, FileNotFound, NotDir }!void {
+ var skip = off;
+ switch (target) {
+ .top => |f| switch (f) {
+ .root => {
+ // The guide, then what describes the session, then the
+ // files that act, then the directories.
+ inline for (.{ TopFile.README, TopFile.index, TopFile.status, TopFile.focus, TopFile.ctl, TopFile.commands, TopFile.recent, TopFile.dumps, TopFile.addons, TopFile.look, TopFile.exec, TopFile.pager, TopFile.log, TopFile.screen, TopFile.listeners, TopFile.sessions, TopFile.layout, TopFile.tag, TopFile.tagexec, TopFile.kbdin, TopFile.mousein, TopFile.plumb, TopFile.pane, TopFile.col }) |t| {
+ if (skip > 0) skip -= 1 else try stageDirent(out, p.gpa, @backingInt(t), t.dir(), t.fileName());
+ }
+ if (skip > 0) skip -= 1 else try stageDirent(out, p.gpa, fs.os_root, true, "os");
+ try sources.stage(p, out, "", &skip);
+ },
+ .pane => {
+ if (skip > 0) skip -= 1 else try stageDirent(out, p.gpa, @backingInt(TopFile.new), false, TopFile.new.fileName());
+ var last: u32 = 0;
+ while (nextSerialAfter(p, last)) |serial| {
+ last = serial;
+ if (skip > 0) {
+ skip -= 1;
+ continue;
+ }
+ var buf: [16]u8 = undefined;
+ // unreachable: a u32 serial fits 16
+ const name = std.fmt.bufPrint(&buf, "{d}", .{serial}) catch unreachable;
+ try stageDirent(out, p.gpa, Node.of(serial, .dir), true, name);
+ }
+ },
+ // plumber(4)'s order: rules, send, then the ports as rules
+ // named them.
+ .plumb => {
+ inline for (.{ TopFile.rules, TopFile.send }) |t| {
+ if (skip > 0) skip -= 1 else try stageDirent(out, p.gpa, @backingInt(t), false, t.fileName());
+ }
+ for (p.plumber.ports.items, 0..) |name, i| {
+ if (skip > 0) skip -= 1 else try stageDirent(out, p.gpa, Node.ofPort(@intCast(i)), false, name);
+ }
+ },
+ .col => for (0..p.view().ncol) |c| {
+ if (skip > 0) {
+ skip -= 1;
+ continue;
+ }
+ var buf: [16]u8 = undefined;
+ const serial = layout.columnSerial(p, c);
+ // unreachable: a u32 serial fits 16
+ try stageDirent(out, p.gpa, Node.ofCol(serial, .dir), true, std.fmt.bufPrint(&buf, "{d}", .{serial}) catch unreachable);
+ },
+ else => return error.NotDir,
+ },
+ .col => |c| {
+ if (layout.columnBySerial(p, c.serial) == null) return error.FileNotFound;
+ if (c.file != .dir) return error.NotDir;
+ inline for (.{ ColFile.tag, ColFile.ctl, ColFile.exec }) |f| {
+ if (skip > 0) skip -= 1 else try stageDirent(out, p.gpa, Node.ofCol(c.serial, f), false, f.fileName());
+ }
+ },
+ .port => return error.NotDir,
+ .pane => |t| {
+ const id = p.paneBySerial(t.serial) orelse return error.FileNotFound;
+ const terminal = p.panes[id].?.isTerminal();
+ switch (t.file) {
+ // The pty files are listed inside pty/, and it only on a terminal.
+ .dir => inline for (comptime std.enums.values(PaneFile)) |f| {
+ if (comptime f == .dir or (f.inPty() and f != .pty)) continue;
+ if (f != .pty or terminal) {
+ if (skip > 0) skip -= 1 else try stageDirent(out, p.gpa, Node.of(t.serial, f), f.isDir(), f.fileName());
+ }
+ },
+ .pty => {
+ if (!terminal) return error.FileNotFound;
+ inline for (comptime std.enums.values(PaneFile)) |f| {
+ if (comptime !f.inPty() or f == .pty) continue;
+ if (skip > 0) skip -= 1 else try stageDirent(out, p.gpa, Node.of(t.serial, f), false, f.fileName());
+ }
+ },
+ else => return error.NotDir,
+ }
+ },
+ }
+}
+
+fn open(p: *Pardes, req: Req, target: Target) Reply {
+ var pane_of: ?*Pane = null;
+ const what: @FieldType(Open, "what") = switch (target) {
+ .top => |f| switch (f) {
+ // The made pane's serial is the handle: the fid remembers which
+ // pane it made, so reading it twice answers the same one and
+ // closing it leaves the pane alone.
+ .new => {
+ const slot = p.freeSlot() orelse return failText(req.tag, E.NOSPC, std.fmt.comptimePrint("pane/new: " ++ pardes.Messages.no_pane_slots, .{pardes.MAX_PANES}));
+ p.fs.no_pane_slot = false;
+ // Refused, the open's err is the one record of it (the
+ // one rule): no msg besides.
+ p.fs.capturing = true;
+ panes.newScratchFor(p, p.view().active, .fs);
+ p.fs.capturing = false;
+ p.fs.failure_len = 0;
+ const made = p.panes[slot] orelse return Reply.fail(req.tag, E.NFILE);
+ // No room in its column: it closes at the step's end.
+ if (p.unplaced.isSet(slot)) return failText(req.tag, E.NOSPC, p.fs.ename[0..p.fs.no_pane_slot_len]);
+ return .{ .tag = req.tag, .handle = made.serial };
+ },
+ .screen => .{ .snapshot = null },
+ .log => .{ .log = .{} },
+ .index, .layout, .recent, .dumps, .addons, .commands, .status, .listeners, .sessions => .{ .frozen = &.{} },
+ // The root's ctl opened only to read: its settings, frozen.
+ .ctl => if (linesOpen(target, req)) .lines else .{ .frozen = &.{} },
+ // One writer of the rules at a time, as plumber(4)'s.
+ .rules, .send => if (req.omode & 3 == 0) return .{ .tag = req.tag } else plumb: {
+ if (f == .rules) for (p.fs.opens) |o| if (o.node == req.node and o.what == .plumb) return failText(req.tag, E.BUSY, e_in_use);
+ break :plumb .plumb;
+ },
+ else => if (linesOpen(target, req)) .lines else return .{ .tag = req.tag },
+ },
+ .col => |c| if (layout.columnBySerial(p, c.serial) == null)
+ return Reply.fail(req.tag, E.NOENT)
+ else if (linesOpen(target, req)) .lines else if (c.file == .ctl) .{ .frozen = &.{} } else return .{ .tag = req.tag },
+ // A reader of the port: what is sent to it from now on, and what a
+ // `client` rule held for its first.
+ .port => |i| if (req.omode & 3 != 0) return Reply.fail(req.tag, E.PERM) else .{ .port = .{ .index = i } },
+ .pane => |t| what: {
+ const pn = p.panes[p.paneBySerial(t.serial) orelse return Reply.fail(req.tag, E.NOENT)].?;
+ if (t.file.inPty() and !pn.isTerminal()) return Reply.fail(req.tag, E.NOENT);
+ pane_of = pn;
+ const reader = req.omode & 3 != 1; // OWRITE is the one mode that never reads
+ break :what switch (t.file) {
+ .body => if (pn.isTerminal()) .{ .snapshot = null } else if (req.omode & 3 == 0) return .{ .tag = req.tag } else .writes,
+ // sel too: one open's writes run on from its last (wrsel).
+ .data, .xdata, .sel => if (req.omode & 3 != 0) .writes else return .{ .tag = req.tag },
+ // Reads of these consume, so two readers would each see half
+ // the stream; the second is refused rather than robbed.
+ .event => if (reader and pn.fs.event_reader) return failText(req.tag, E.BUSY, e_in_use) else .{ .event = reader },
+ .pty_data => if (!reader) return .{ .tag = req.tag } else if (pn.fs.pty_reader) return failText(req.tag, E.BUSY, e_in_use) else .pty_data,
+ .pty_run => .{ .run = .{} },
+ .ctl => switch (req.omode & 3) {
+ 1, 2 => .ctl, // OWRITE, ORDWR
+ else => return .{ .tag = req.tag },
+ },
+ else => if (linesOpen(target, req)) .lines else return .{ .tag = req.tag },
+ };
+ },
+ };
+ const i = for (p.fs.opens, 0..) |o, i| {
+ if (o.node == 0) break i;
+ } else return Reply.fail(req.tag, E.NFILE);
+ const o = &p.fs.opens[i];
+ o.* = .{ .node = req.node, .what = what };
+ if (resultsFile(target)) {
+ @memcpy(o.results.list[0..p.fs.results_len], p.fs.results[0..p.fs.results_len]);
+ o.results.len = p.fs.results_len;
+ }
+ switch (o.what) {
+ // A screen freezes at open; a terminal body at its first read.
+ .snapshot => |*bytes| if (pane_of == null) {
+ bytes.* = screen.render(p) catch {
+ o.* = .{};
+ return Reply.fail(req.tag, E.NOMEM);
+ };
+ },
+ .log => |*log| log.* = events.freezeLog(p) catch {
+ o.* = .{};
+ return Reply.fail(req.tag, E.NOMEM);
+ },
+ .frozen => |*bytes| {
+ const whole = readFile(p, .{ .tag = req.tag, .op = .read, .node = req.node, .size = 1 << 22 }, target);
+ bytes.* = if (whole.status == .ok) p.gpa.dupe(u8, p.fsPayload(whole)) catch {
+ o.* = .{};
+ return Reply.fail(req.tag, E.NOMEM);
+ } else &.{};
+ },
+ .event => |reader| {
+ const pn = pane_of.?;
+ pn.fs.readers +|= 1;
+ p.fs.listeners +|= 1;
+ pn.fs.event_reader = pn.fs.event_reader or reader;
+ },
+ .pty_data => pane_of.?.fs.pty_reader = true,
+ .port => |*port| Plumb.opened(p, port.index, &port.queue),
+ .run, .ctl, .lines, .writes, .pager, .plumb => {},
+ }
+ return .{ .tag = req.tag, .handle = @intCast(i + 1) };
+}
+
+/// Tremove closes a pane. Nothing else in the tree can be removed, and this
+/// is also where an ORCLOSE open lands, so every node is checked here.
+fn remove(p: *Pardes, req: Req) Reply {
+ const target = Node.target(req.node) orelse return Reply.fail(req.tag, E.NOENT);
+ const t = switch (target) {
+ .pane => |t| t,
+ .top, .port => return Reply.fail(req.tag, E.PERM),
+ .col => |c| return cols.remove(p, req, c.serial, c.file),
+ };
+ if (t.file != .dir) return Reply.fail(req.tag, E.PERM);
+ const id = p.paneBySerial(t.serial) orelse return Reply.fail(req.tag, E.NOENT);
+ // A pane an Edit's running commands will change stays until they end.
+ if (@import("../edit_cmd.zig").busyOn(p, id)) return failText(req.tag, E.BUSY, @import("../edit_cmd.zig").e_busy);
+ p.removePane(id, null) catch return Reply.fail(req.tag, E.IO);
+ return .{ .tag = req.tag };
+}
+
+fn release(p: *Pardes, req: Req) Reply {
+ // The handle's bookkeeping runs whether or not the removal is allowed.
+ releaseHandle(p, req);
+ return if (req.remove) remove(p, req) else .{ .tag = req.tag };
+}
+
+/// Gives up what the open held, a read held on it included: a hangup pays
+/// its releases before the connection's slot is reused, so none outlives
+/// the connection it came on.
+fn releaseHandle(p: *Pardes, req: Req) void {
+ const t = Node.target(req.node).?;
+ const of: ?*Pane = if (t == .pane) (if (p.paneBySerial(t.pane.serial)) |id| p.panes[id] else null) else null;
+ if (of) |pn| switch (t.pane.file) {
+ // A truncating write to `tag` is over when its open goes (pane.zig
+ // writeTag): a newline it held back is dropped.
+ .tag => {
+ pane.applyTagTruncation(p, pn);
+ pn.fs.tag_rewrite = false;
+ pn.fs.tag_held_newline = false;
+ },
+ // A sel open's run of writes ends with it.
+ .sel => if (pn.fs.wrsel_by == req.handle) {
+ pn.fs.wrsel_by = 0;
+ },
+ // The writes of one open are one undo step (pane.zig `joined`): its
+ // close ends that step.
+ .body, .data, .xdata => if (pn.fs.joined_by == 0 or pn.fs.joined_by == req.handle) {
+ pn.fs.joined = null;
+ },
+ // `: > limit` clears it for good once its open goes.
+ .limit => pn.fs.limit_truncated = null,
+ // `: > dot` empties it once its open goes, no write having set it.
+ .dot => {
+ if (pn.fs.dot_truncated) pane.setDot(pn, .{});
+ pn.fs.dot_truncated = false;
+ },
+ else => {},
+ };
+ if (t == .col and t.col.file == .tag) cols.released(p, t.col.serial);
+ if (t == .top and t.top == .tag) cols.released(p, null);
+ const o = openOf(p, req) orelse return;
+ // A message short of its data is dropped with its open, as plumber(4)
+ // drops a fid's writebuf; rule text left goes in at the editor's step.
+ if (o.what == .plumb and req.node == @backingInt(TopFile.send)) o.pending.clearRetainingCapacity();
+ // A /pager open's text, not read for, goes in at the editor's next
+ // step (ctl.fillClosedPagers): this close need not wait for quiet.
+ if (o.what == .pager and o.pending.items.len > 0) {
+ p.fs.pages.append(p.gpa, .{ .serial = o.what.pager, .bytes = o.pending }) catch o.pending.deinit(p.gpa);
+ o.pending = .empty;
+ }
+ // The last line an open wrote with no newline after it runs at the
+ // editor's next step (runClosedLines), as a /pager open's text does.
+ if (o.pending.items.len > 0) {
+ p.fs.closed_lines.append(p.gpa, .{ .node = req.node, .bytes = o.pending }) catch o.pending.deinit(p.gpa);
+ o.pending = .empty;
+ }
+ if (of) |pn| switch (o.what) {
+ .event => |reader| {
+ if (reader) pn.fs.event_reader = false;
+ pn.fs.readers -|= 1;
+ p.fs.listeners -|= 1;
+ if (pn.fs.readers == 0) pn.fs.tag_snap.clearAndFree(p.gpa);
+ },
+ .pty_data => {
+ pn.fs.pty_reader = false;
+ pn.fs.pty_out.clearAndFree(p.gpa);
+ },
+ // The command runs on in the shell; nobody is waiting for it any more.
+ .run => if (pn.fs.run == req.handle) {
+ pn.fs.run = null;
+ },
+ // Closing the open that holds the lock gives it up, as acme's clunk
+ // of its ctlfid does (editors/acme/xfid.c:211).
+ .ctl => if (pn.fs.lock == req.handle) {
+ pn.fs.lock = null;
+ },
+ .snapshot, .log, .lines, .writes, .frozen, .pager, .plumb, .port => {},
+ };
+ o.deinit(p.gpa);
+}
+
+fn setattr(p: *Pardes, req: Req, target: Target) Reply {
+ // A rename (`mv`) of a pane's directory, a column's or any file here:
+ // the tree names them, not the client. Refused as not permitted
+ // (EPERM), not taken and then lost, which a mount read as EIO.
+ if (req.set.name) return failText(req.tag, E.PERM, "rename not permitted: the tree names its files (a pane's name file renames its buffer)");
+ if (req.truncate) switch (target) {
+ .pane => |t| {
+ const id = p.paneBySerial(t.serial) orelse return Reply.fail(req.tag, E.NOENT);
+ if ((t.file == .data or t.file == .xdata) and p.panes[id].?.fs.addr_failed)
+ return failText(req.tag, E.INVAL, pane.e_addr_failed);
+ if (pane.truncate(p, p.panes[id].?, t.file) != .ok) return Reply.fail(req.tag, E.NOMEM);
+ },
+ .col => |c| if (c.file == .tag and cols.truncate(p, c.serial) != .ok) return Reply.fail(req.tag, E.NOENT),
+ .top => |f| if (f == .tag and cols.truncate(p, null) != .ok) return Reply.fail(req.tag, E.NOMEM) else if (f == .rules) Plumb.clear(p),
+ .port => return Reply.fail(req.tag, E.PERM),
+ };
+ return .{ .tag = req.tag, .attr = attrOf(p, target) orelse return Reply.fail(req.tag, E.NOENT) };
+}
+
+fn read(p: *Pardes, req: Req, target: Target) Reply {
+ const open_record = openOf(p, req);
+ // A /pager open's text goes in before its read answers the pane.
+ if (open_record) |o| if (o.what == .pager) ctl.fillPager(p, o.what.pager, &o.pending) catch return Reply.fail(req.tag, E.NOMEM);
+ // A listing reads what it was at the open.
+ if (open_record) |o| if (o.what == .frozen) return window(p, req, o.what.frozen);
+ // A port: a message a read, held until one is sent.
+ if (open_record) |o| if (o.what == .port) return events.readQueue(p, req, &o.what.port.queue);
+ const stream = if (open_record) |o| switch (o.what) {
+ .log => o,
+ .event => |reader| if (reader) o else null,
+ .pty_data => o,
+ else => null,
+ } else null;
+ const s = stream orelse return readFile(p, req, target);
+ // Strictly inside: a client that reads every record at one offset (the
+ // offset is ignored on a stream, as in Plan 9) always gets new ones.
+ if (s.replay) |r| if (req.off > r.off and req.off < r.off + r.bytes.len) {
+ var at = req;
+ at.off = req.off - r.off;
+ return window(p, at, r.bytes);
+ };
+ const reply = readFile(p, req, target);
+ if (reply.status != .ok) return reply;
+ const bytes = p.fsPayload(reply);
+ if (bytes.len == 0) return reply;
+ const kept = p.gpa.dupe(u8, bytes) catch return reply;
+ if (s.replay) |r| p.gpa.free(r.bytes);
+ s.replay = .{ .off = req.off, .bytes = kept };
+ return reply;
+}
+
+fn readFile(p: *Pardes, req: Req, target: Target) Reply {
+ switch (target) {
+ .top => |f| return switch (f) {
+ .kbdin, .mousein, .send => Reply.fail(req.tag, E.PERM),
+ .README => window(p, req, fs.help),
+ .rules => window(p, req, Plumb.inForce(p)),
+ .index => index: {
+ const out = p.fs.stage(p.gpa);
+ var last: u32 = 0;
+ while (nextSerialAfter(p, last)) |serial| {
+ last = serial;
+ const id = p.paneBySerial(serial).?;
+ const pn = p.panes[id].?;
+ // A name as /log shows it: one line of UTF-8, a
+ // newline in it `\n` (events.shown).
+ var name_buf: [4 * 4096]u8 = undefined;
+ const name = events.shown(pane.nameOf(p, pn), &name_buf);
+ out.print(p.gpa, "{d} {s} {d} {s} {d}\n", .{ serial, pane.kindOf(pn), @intFromBool(pane.dirtyOf(pn)), name, pane.columnOf(p, id) }) catch break :index Reply.fail(req.tag, E.NOMEM);
+ }
+ break :index stagedReply(p, req);
+ },
+ .status => window(p, req, ctl.statusText(p) catch return Reply.fail(req.tag, E.NOMEM)),
+ .look, .exec, .tagexec, .pager => ctl.readResults(p, req),
+ .log => events.readLog(p, req),
+ .screen => screen.readSnapshot(p, req, null),
+ .listeners => window(p, req, screen.listenersText(p) catch return Reply.fail(req.tag, E.NOMEM)),
+ .sessions => sessions: {
+ if (comptime !daemon.supported) break :sessions stagedReply(p, req);
+ // Out of the turn: the daemon answers within 2 s, or not at all.
+ const said = pardes.tape.site(.sessions, p.gpa, daemonList, .{p.gpa}) catch |err| break :sessions switch (err) {
+ error.OutOfMemory => Reply.fail(req.tag, E.NOMEM),
+ else => failText(req.tag, E.NOENT, "no pardes daemon answers"),
+ };
+ defer p.gpa.free(said);
+ break :sessions window(p, req, said);
+ },
+ .focus => ctl.readFocus(p, req),
+ .ctl => window(p, req, ctl.settingsText(p) catch return Reply.fail(req.tag, E.NOMEM)),
+ .commands => window(p, req, ctl.commandsText(p) catch return Reply.fail(req.tag, E.NOMEM)),
+ .recent => recent: {
+ // Every window's files: what the others wrote since, read,
+ // unless a step is out mid-syscall (nothing may change the
+ // core under it): then the list as it was.
+ if (pardes.turn.out == 0) p.db.readRecent(p);
+ var text: std.Io.Writer.Allocating = .init(p.scratch.allocator());
+ pardes.panes.Output.recentText(p, &text.writer, false) catch break :recent Reply.fail(req.tag, E.NOMEM);
+ break :recent window(p, req, text.written());
+ },
+ .addons => addons: {
+ var text: std.ArrayList(u8) = .empty;
+ pardes.Addon.list(p, &text, p.scratch.allocator()) catch break :addons Reply.fail(req.tag, E.NOMEM);
+ break :addons window(p, req, text.items);
+ },
+ .dumps => dumps: {
+ // The state file read now, unless a step is out mid-syscall
+ // (its database is the step's): then none.
+ var text: std.Io.Writer.Allocating = .init(p.scratch.allocator());
+ if (pardes.turn.out == 0) p.db.listDumps(p, &text.writer) catch |err| switch (err) {
+ error.OutOfMemory, error.WriteFailed => break :dumps Reply.fail(req.tag, E.NOMEM),
+ else => break :dumps Reply.fail(req.tag, E.IO),
+ };
+ break :dumps window(p, req, text.written());
+ },
+ .layout => layout: {
+ var text: std.Io.Writer.Allocating = .init(p.scratch.allocator());
+ cols.writeLayout(p, &text.writer) catch break :layout Reply.fail(req.tag, E.NOMEM);
+ break :layout window(p, req, text.written());
+ },
+ .tag => cols.read(p, req, null),
+ // The serial the open handed this fid, so that two reads of one
+ // fid answer the same pane: the read observes, the open acted.
+ .new => serial: {
+ if (req.handle == 0) break :serial Reply.fail(req.tag, E.IO);
+ p.fs.stage(p.gpa).print(p.gpa, "{d}\n", .{req.handle}) catch
+ break :serial Reply.fail(req.tag, E.NOMEM);
+ break :serial stagedReply(p, req);
+ },
+ .root, .pane, .col, .plumb => Reply.fail(req.tag, E.PERM),
+ },
+ .pane => |t| {
+ // A run's answer outlives the pane it ran in.
+ if (t.file == .pty_run and req.handle != 0) return pty.readRun(p, req);
+ const id = p.paneBySerial(t.serial) orelse {
+ // An event reader whose pane closed reads its end: there
+ // are no more records, as a pipe's writer gone is EOF, so
+ // `while read` and `cat` end cleanly. A pty/data read the
+ // pane closed under keeps acme's answer (xfid.c:1005).
+ if (openOf(p, req)) |o| {
+ if (o.what == .event) return .{ .tag = req.tag };
+ if (o.what == .pty_data) return failText(req.tag, E.NOENT, e_shut_down);
+ }
+ return Reply.fail(req.tag, E.NOENT);
+ };
+ const pn = p.panes[id].?;
+ if (t.file.inPty() and !pn.isTerminal()) return Reply.fail(req.tag, E.NOENT);
+ return pane.read(p, req, id, pn, t.file);
+ },
+ .col => |c| return switch (c.file) {
+ .tag => cols.read(p, req, c.serial),
+ .exec => ctl.readResults(p, req),
+ else => Reply.fail(req.tag, E.PERM),
+ },
+ // Read through its open (read), never without one.
+ .port => return Reply.fail(req.tag, E.PERM),
+ }
+}
+
+/// The files whose writes are lines of commands, run as each line is whole.
+fn linesFile(target: Target) bool {
+ return switch (target) {
+ .top => |f| f == .look or f == .exec or f == .ctl or f == .tagexec or f == .pager,
+ .col => |c| c.file == .ctl or c.file == .exec,
+ // `name` too: one name, however its writes cut it, applied once
+ // its newline comes, or with its write when that is whole.
+ .pane => |t| t.file == .look or t.file == .exec or t.file == .ctl or t.file == .tagexec or t.file == .name or t.file == .rows,
+ .port => false,
+ };
+}
+
+/// The ones of those a read answers with the panes a write touched.
+fn resultsFile(target: Target) bool {
+ return switch (target) {
+ .top => |f| f == .look or f == .exec or f == .tagexec or f == .pager,
+ .col => |c| c.file == .exec,
+ .pane => |t| t.file == .look or t.file == .exec or t.file == .tagexec,
+ .port => false,
+ };
+}
+
+/// An open that keeps lines or results: any that may write one of those
+/// files, and any that may read a look or exec.
+fn linesOpen(target: Target, req: Req) bool {
+ if (!linesFile(target)) return false;
+ return req.omode & 3 != 0 or resultsFile(target);
+}
+
+/// The editor's step: the last lines of closed opens run, each as a write
+/// of its own; a refusal is the log's err, as no open is left to answer.
+pub fn runClosedLines(p: *Pardes) void {
+ const taped = pardes.tape.enter(p, .run_closed_lines);
+ defer pardes.tape.leave(p, taped);
+ for (p.fs.closed_lines.items) |*line| {
+ defer line.bytes.deinit(p.gpa);
+ const t = Node.target(line.node) orelse continue;
+ const w: Req = .{ .tag = 0, .op = .write, .node = line.node, .data = line.bytes.items };
+ const reply = writeNow(p, w, t);
+ if (reply.status == .err) events.noteError(p, w, reply);
+ }
+ p.fs.closed_lines.clearRetainingCapacity();
+}
+
+/// A close that hands its open's held text, a last line or a /pager's
+/// page, to the editor's step: answered at once, never waiting on it.
+pub fn handsOff(p: *Pardes, req: Req) bool {
+ return (req.op == .release and holdsLines(p, req)) or holdsPage(p, req);
+}
+
+/// A release that will run a line its open held back.
+fn holdsLines(p: *Pardes, req: Req) bool {
+ const o = openOf(p, req) orelse return false;
+ return o.pending.items.len > 0 and o.what != .pager;
+}
+
+/// A line held back longer than this is refused rather than kept growing.
+const pending_cap = 1 << 20;
+
+/// The ctl files, whose lines are commands as look's and exec's are.
+fn ctlFile(target: Target) bool {
+ return switch (target) {
+ .top => |f| f == .ctl,
+ .col => |c| c.file == .ctl,
+ .pane => |t| t.file == .ctl,
+ .port => false,
+ };
+}
+
+/// /pager on an open: its first line names the directory and runs as any
+/// line does; what follows it, in that write and the open's later ones, is
+/// a program's output, escapes and all, held whole and never run as lines.
+fn write(p: *Pardes, req: Req, target: Target) Reply {
+ const o = (if (target == .top and target.top == .pager) openOf(p, req) else null) orelse return writeLines(p, req, target);
+ if (o.what == .pager) {
+ if (o.pending.items.len + req.data.len > pager_cap) return failText(req.tag, E.NOSPC, "pager: no space: the text is over a file's limit");
+ o.pending.appendSlice(p.gpa, req.data) catch return Reply.fail(req.tag, E.NOMEM);
+ return .{ .tag = req.tag, .written = @intCast(req.data.len) };
+ }
+ const nl = std.mem.indexOfScalar(u8, req.data, '\n') orelse return writeLines(p, req, target);
+ var head = req;
+ head.data = req.data[0 .. nl + 1];
+ const reply = writeLines(p, head, target);
+ if (reply.status != .ok or o.results.len == 0) return reply;
+ o.what = .{ .pager = o.results.list[0] };
+ o.pending.clearRetainingCapacity();
+ o.pending.appendSlice(p.gpa, req.data[nl + 1 ..]) catch return Reply.fail(req.tag, E.NOMEM);
+ return .{ .tag = req.tag, .written = @intCast(req.data.len) };
+}
+
+/// The most a /pager open holds: a file's limit, and `pardes -`'s note
+/// that its stdin was cut there.
+const pager_cap = @import("../memory.zig").limits.max_file_bytes + 4096;
+
+/// A /pager open holding text: its read puts it in (ctl.fillPager), its
+/// close hands it to the editor's step.
+pub fn holdsPage(p: *Pardes, req: Req) bool {
+ const o = openOf(p, req) orelse return false;
+ return o.what == .pager and o.pending.items.len > 0;
+}
+
+fn writeLines(p: *Pardes, req: Req, target: Target) Reply {
+ // A command line holds no control character but a tab: the whole write
+ // is refused at once, not held to fail unseen at the close, and the
+ // line it is in goes with it, as one refused for its length does: the
+ // start a write before held, and the rest, through its newline, that
+ // the next write brings.
+ if (resultsFile(target) or ctlFile(target)) for (req.data) |c| if ((c < ' ' and c != '\t' and c != '\n' and c != '\r') or c == 0x7f) {
+ if (openOf(p, req)) |o| if (o.what == .lines or o.what == .ctl) {
+ o.pending.clearRetainingCapacity();
+ o.discarding = !std.mem.endsWith(u8, req.data, "\n");
+ };
+ return failText(req.tag, E.INVAL, ctl.e_control);
+ };
+ // A NUL no name may hold fails its write at once, not the close.
+ if (target == .pane and target.pane.file == .name and std.mem.indexOfScalar(u8, req.data, 0) != null)
+ return failText(req.tag, E.INVAL, pane.e_name_char ++ ": a NUL");
+ const o = (if (linesFile(target)) openOf(p, req) else null) orelse return writeNow(p, req, target);
+ if (o.what != .lines and o.what != .ctl) return writeNow(p, req, target);
+ // The rest of a line refused for its length goes through its newline
+ // unread: its one refusal said it, and its tail is no command of its own.
+ var data = req.data;
+ if (o.discarding) {
+ const nl = std.mem.indexOfScalar(u8, data, '\n') orelse return .{ .tag = req.tag, .written = @intCast(req.data.len) };
+ o.discarding = false;
+ data = data[nl + 1 ..];
+ if (data.len == 0) return .{ .tag = req.tag, .written = @intCast(req.data.len) };
+ }
+ // One name an open, on one line: anything after its newline, in this
+ // write or a later one, is refused by the write that brings it, never
+ // left to rename the pane again at the close (`printf 'a\nb' > name`).
+ if (target == .pane and target.pane.file == .name) {
+ const past_newline = if (std.mem.indexOfScalar(u8, data, '\n')) |nl| nl + 1 < data.len else false;
+ if (o.named or past_newline) {
+ o.pending.clearRetainingCapacity();
+ return failText(req.tag, E.INVAL, "invalid file name: one name a write, on one line");
+ }
+ }
+ o.pending.appendSlice(p.gpa, data) catch return Reply.fail(req.tag, E.NOMEM);
+ // A line runs when its newline comes, or, the last one, when its open
+ // is let go (release). Nothing is inferred from a write's size: a mount
+ // cuts a long write anywhere (9ns sends 512 KiB as 65512-byte Twrites,
+ // stdio and the page cache at 4096 multiples), and a piece shorter than
+ // its message is no whole line. An Edit block is whole when it closes.
+ const end = ctl.completeEnd(p, o.pending.items);
+ if (end == 0) {
+ if (target == .pane and target.pane.file == .name) if (pane.heldNameFault(p, target.pane.serial, o.pending.items)) |why| {
+ o.pending.clearRetainingCapacity();
+ o.discarding = true;
+ return failText(req.tag, E.INVAL, why);
+ };
+ if (o.pending.items.len <= pending_cap) return .{ .tag = req.tag, .written = @intCast(req.data.len) };
+ o.pending.clearRetainingCapacity();
+ o.discarding = true;
+ return failText(req.tag, E.INVAL, "invalid write: a line or Edit block over 1 MiB");
+ }
+ if (target == .pane and target.pane.file == .name) {
+ if (o.named or std.mem.count(u8, o.pending.items[0..end], "\n") > 1) {
+ o.pending.clearRetainingCapacity();
+ return failText(req.tag, E.INVAL, "invalid file name: one name a write, on one line");
+ }
+ o.named = true;
+ }
+ // The line outlives any step its command runs (a `size` resizes and
+ // syncs, then quotes its value in a refusal): the step's scratch is
+ // reset under it, so the line is the gpa's until the write is answered.
+ const whole = p.gpa.dupe(u8, o.pending.items[0..end]) catch return Reply.fail(req.tag, E.NOMEM);
+ defer p.gpa.free(whole);
+ const rest = o.pending.items.len - end;
+ std.mem.copyForwards(u8, o.pending.items[0..rest], o.pending.items[end..]);
+ o.pending.shrinkRetainingCapacity(rest);
+ var w = req;
+ w.data = whole;
+ // At the offset its first byte was written at, an earlier write's
+ // held line included (a rows write at 0 starts the rows over).
+ w.off = (req.off + (req.data.len - data.len)) -| (end + rest - data.len);
+ // The command pane this open was answered holds no lease against its
+ // own next command (exec.leased): that one may run there again.
+ if (resultsFile(target)) o.results.len = 0;
+ var reply = writeNow(p, w, target);
+ if (resultsFile(target)) {
+ @memcpy(o.results.list[0..p.fs.results_len], p.fs.results[0..p.fs.results_len]);
+ o.results = .{ .list = o.results.list, .len = p.fs.results_len, .wrote = true };
+ }
+ if (reply.status == .ok) reply.written = @intCast(req.data.len);
+ return reply;
+}
+
+fn writeNow(p: *Pardes, req: Req, target: Target) Reply {
+ switch (target) {
+ .top => |f| return switch (f) {
+ .look, .exec => ctl.command(p, req, null, f == .exec, false),
+ .log => events.writeLog(p, req),
+ .focus => ctl.writeFocus(p, req),
+ .kbdin => ctl.writeKbdin(p, req),
+ .mousein => ctl.writeMousein(p, req),
+ .ctl => ctl.writeRoot(p, req),
+ .pager => ctl.writePager(p, req),
+ .tag => cols.write(p, req, null),
+ .tagexec => cols.writeExec(p, req, null),
+ .rules => writeRules(p, req),
+ .send => writeSend(p, req),
+ else => Reply.fail(req.tag, E.PERM),
+ },
+ .pane => |t| {
+ const id = p.paneBySerial(t.serial) orelse return Reply.fail(req.tag, E.NOENT);
+ const pn = p.panes[id].?;
+ if (t.file.inPty() and !pn.isTerminal()) return Reply.fail(req.tag, E.NOENT);
+ return pane.write(p, req, id, pn, t.file);
+ },
+ .col => |c| return switch (c.file) {
+ .tag => cols.write(p, req, c.serial),
+ .ctl => cols.writeCtl(p, req, c.serial),
+ .exec => cols.writeExec(p, req, c.serial),
+ .dir => Reply.fail(req.tag, E.PERM),
+ },
+ .port => return Reply.fail(req.tag, E.PERM),
+ }
+}
+
+/// plumb/rules: rule text added to the rules in force a rule set at a time,
+/// as each is whole (a blank line after it, rules.c's morerules), the rest
+/// at the open's close; a refusal is the write's, in plumb(6)'s words, the
+/// rules as they were and the text it held dropped.
+fn writeRules(p: *Pardes, req: Req) Reply {
+ const done: Reply = .{ .tag = req.tag, .written = @intCast(req.data.len) };
+ // A close's rest (runClosedLines), or a write with no open: whole.
+ const o = openOf(p, req) orelse return if (Plumb.apply(p, true, "plumb/rules", req.data)) |why| failText(req.tag, E.INVAL, why) else done;
+ if (o.pending.items.len + req.data.len > Plumb.max_text) {
+ o.pending.clearRetainingCapacity();
+ return failText(req.tag, E.INVAL, std.fmt.comptimePrint("rules too long; max {d} KiB", .{Plumb.max_text / 1024}));
+ }
+ o.pending.appendSlice(p.gpa, req.data) catch return Reply.fail(req.tag, E.NOMEM);
+ const end = Plumb.wholeSets(o.pending.items);
+ if (end == 0) return done;
+ const why = Plumb.apply(p, true, "plumb/rules", o.pending.items[0..end]);
+ if (why != null) o.pending.clearRetainingCapacity() else {
+ const rest = o.pending.items.len - end;
+ std.mem.copyForwards(u8, o.pending.items[0..rest], o.pending.items[end..]);
+ o.pending.shrinkRetainingCapacity(rest);
+ }
+ return if (why) |w| failText(req.tag, E.INVAL, w) else done;
+}
+
+/// plumb/send: a message, its writes put together until its data is all
+/// there (plumber(4)), then matched and sent: the write is answered when it
+/// has gone where the rules say, or with why not, in Plan 9's words.
+fn writeSend(p: *Pardes, req: Req) Reply {
+ const o = openOf(p, req);
+ const held = if (o) |op| op.pending.items.len > 0 else false;
+ if (held) o.?.pending.appendSlice(p.gpa, req.data) catch return Reply.fail(req.tag, E.NOMEM);
+ defer if (o) |op| if (op.pending.items.len > pending_cap) op.pending.clearRetainingCapacity();
+ switch (Plumb.unpack(if (held) o.?.pending.items else req.data)) {
+ .bad => {
+ if (o) |op| op.pending.clearRetainingCapacity();
+ return failText(req.tag, E.INVAL, Plumb.e_bad_msg);
+ },
+ .more => |n| {
+ const op = o orelse return failText(req.tag, E.INVAL, Plumb.e_bad_msg);
+ if (op.pending.items.len + n > pending_cap) {
+ op.pending.clearRetainingCapacity();
+ return failText(req.tag, E.INVAL, Plumb.e_bad_msg ++ ": over 1 MiB");
+ }
+ if (!held) op.pending.appendSlice(p.gpa, req.data) catch return Reply.fail(req.tag, E.NOMEM);
+ return .{ .tag = req.tag, .written = @intCast(req.data.len) };
+ },
+ .msg => |m| {
+ defer if (o) |op| op.pending.clearRetainingCapacity();
+ switch (Plumb.send(p, null, m, null)) {
+ .refused => |why| return failText(req.tag, E.IO, why),
+ .done, .look => {},
+ }
+ return .{ .tag = req.tag, .written = @intCast(req.data.len) };
+ },
+ }
+}
+
+// ---- tests ----
+
+const testing = std.testing;
+const th = @import("testing.zig");
+const config = @import("../config.zig");
+const call = th.call;
+const rd = th.rd;
+const wr = th.wr;
+const rdir = th.rdir;
+const look_up = th.look_up;
+const withFile = th.withFile;
+const serialOf = th.serialOf;
+
+test "a reason past 128 bytes keeps its end: the path in it gives up its middle" {
+ var out: [128]u8 = undefined;
+ const long = "Save /home/someone/projects/" ++ std.mem.asBytes(&@as([30][5]u8, @splat("deep/".*))) ++ "file.txt: no such directory";
+ const fit = fitErr(long, &out);
+ try testing.expect(fit.len <= 128);
+ try testing.expect(std.mem.startsWith(u8, fit, "Save /home/someone/"));
+ try testing.expect(std.mem.endsWith(u8, fit, "file.txt: no such directory"));
+ try testing.expect(std.mem.indexOf(u8, fit, "…") != null);
+ try testing.expect(std.unicode.utf8ValidateSlice(fit));
+ // No path: the whole text's middle goes, the end stays.
+ const words = std.mem.asBytes(&@as([40][4]u8, @splat("why ".*))) ++ "the reason";
+ try testing.expect(std.mem.endsWith(u8, fitErr(words, &out), "the reason"));
+ try testing.expectEqualStrings("short", fitErr("short", &out));
+ // Through the tree: a look at a long ./ name not there, a miss, says
+ // why at the end of its err record, the name giving up its middle.
+ const p = try th.withFile(testing.allocator, "x\n");
+ defer p.deinit();
+ var line: [512]u8 = undefined;
+ const r = th.wr(p, Node.of(serialOf(p), .look), try std.fmt.bufPrint(&line, "./{s}x.txt\n", .{std.mem.asBytes(&@as([20][12]u8, @splat("no-such-dir/".*)))}));
+ try testing.expectEqual(Status.ok, r.reply.status);
+ try testing.expect(th.logHas(p, "x.txt: no such file"));
+}
+
+test {
+ _ = events;
+ _ = pane;
+ _ = addr;
+ _ = ctl;
+ _ = pty;
+ _ = cols;
+ _ = sources;
+ _ = screen;
+}
+
+test "a listing read in chunks is what it was at the open, however the panes change between reads" {
+ const p = try th.withFile(testing.allocator, "x\n");
+ defer p.deinit();
+ for ([_]TopFile{ .index, .layout, .recent, .ctl }) |file| {
+ const node = @backingInt(file);
+ const whole = try testing.allocator.dupe(u8, th.rd(p, node, 0, 1 << 16).bytes);
+ defer testing.allocator.free(whole);
+ const h = th.call(p, .{ .tag = 1, .op = .open, .node = node }).reply.handle;
+ try testing.expect(h != 0);
+ var got: std.ArrayList(u8) = .empty;
+ defer got.deinit(testing.allocator);
+ try got.appendSlice(testing.allocator, th.call(p, .{ .tag = 2, .op = .read, .node = node, .handle = h, .size = 7 }).bytes);
+ // Something changes between the chunks.
+ const made = try th.newPane(p);
+ _ = th.wr(p, Node.of(made, .name), "/tmp/pardes-frozen-listing.txt\n");
+ _ = th.wr(p, @backingInt(TopFile.ctl), "Verbose off\n");
+ while (true) {
+ const more = th.call(p, .{ .tag = 2, .op = .read, .node = node, .handle = h, .off = got.items.len, .size = 7 }).bytes;
+ if (more.len == 0) break;
+ try got.appendSlice(testing.allocator, more);
+ }
+ _ = th.call(p, .{ .tag = 3, .op = .release, .node = node, .handle = h, .opened = true });
+ try testing.expectEqualStrings(whole, got.items);
+ _ = th.wr(p, @backingInt(TopFile.ctl), "Verbose on\n");
+ }
+}
+
+test "filesystem inspection preserves pending and displayed Look hover" {
+ const delay = config.look_preview_delay_frames;
+ const gpa = testing.allocator;
+ const p = try withFile(gpa, "alpha beta gamma\n");
+ defer p.deinit();
+ var frame: std.heap.ArenaAllocator = .init(gpa);
+ defer frame.deinit();
+ _ = try p.render(frame.allocator());
+ const rect = p.view().rects[0];
+ p.update(.{ .mouse = .{
+ .button = .none,
+ .kind = .motion,
+ .col = rect.x + config.GUTTER + config.PREFIX_W + 7,
+ .row = rect.y + pardes.BOX_H,
+ } });
+ try testing.expect(p.look_hover_wait != null);
+ const body = Node.of(serialOf(p), .body);
+ const screen_node = @backingInt(TopFile.screen);
+ for (0..2) |phase| {
+ if (phase == 1) {
+ for (0..delay) |_| p.update(.tick);
+ try testing.expect(p.look_hover_preview != null);
+ }
+ const waiting = p.look_hover_wait;
+ const preview = p.look_hover_preview;
+ const requests = [_]Req{
+ .{ .tag = 1, .op = .lookup, .node = root, .data = "screen" },
+ .{ .tag = 1, .op = .lookup, .node = root, .data = "status" },
+ .{ .tag = 1, .op = .getattr, .node = @backingInt(TopFile.pane) },
+ .{ .tag = 2, .op = .getattr, .node = body },
+ .{ .tag = 3, .op = .open, .node = body },
+ .{ .tag = 4, .op = .read, .node = body, .size = 5 },
+ .{ .tag = 5, .op = .release, .node = body, .handle = 1 },
+ .{ .tag = 6, .op = .readdir, .node = root, .size = 4096 },
+ .{ .tag = 7, .op = .open, .node = screen_node },
+ .{ .tag = 8, .op = .read, .node = screen_node, .handle = 1, .size = 32 },
+ .{ .tag = 9, .op = .release, .node = screen_node, .handle = 1 },
+ };
+ for (requests) |req| {
+ const answer = call(p, req);
+ try testing.expectEqual(Status.ok, answer.reply.status);
+ try testing.expect(std.meta.eql(waiting, p.look_hover_wait));
+ try testing.expect(std.meta.eql(preview, p.look_hover_preview));
+ try testing.expect(p.view().raw_hover_intent);
+ }
+ }
+ try testing.expectEqual(Status.ok, wr(p, body, "changed").reply.status);
+ try testing.expect(p.look_hover_wait == null);
+ try testing.expect(p.look_hover_preview == null);
+ try testing.expect(!p.view().raw_hover_intent);
+}
+
+test "log stats 0 however much it holds, a stream as acme's generated files are" {
+ const p = try th.withFile(testing.allocator, "x\n");
+ defer p.deinit();
+ _ = th.wr(p, Node.of(th.serialOf(p), .exec), "Msg a record for the log\n");
+ try testing.expect(th.logHas(p, "a record for the log"));
+ try testing.expectEqual(@as(u64, 0), call(p, .{ .tag = 1, .op = .getattr, .node = @backingInt(TopFile.log) }).reply.attr.size);
+}
+
+test "filesystem pane creation and truncation cancel Look hover" {
+ const requests = [_]Req{
+ // Opening `new` is what makes a pane now; walking to it makes none,
+ // and so must leave a pending hover alone.
+ .{ .tag = 2, .op = .open, .node = @backingInt(TopFile.new) },
+ .{ .tag = 3, .op = .setattr, .node = 0, .truncate = true },
+ };
+ for (requests) |request| {
+ const p = try withFile(testing.allocator, "word\n");
+ defer p.deinit();
+ p.look_hover_wait = .{ .col = 1, .row = 1, .pane = 0, .serial = serialOf(p) };
+ p.view().raw_hover_intent = true;
+ var req = request;
+ if (req.op == .setattr) req.node = Node.of(serialOf(p), .body);
+ try testing.expectEqual(Status.ok, call(p, req).reply.status);
+ try testing.expect(p.look_hover_wait == null);
+ try testing.expect(p.look_hover_preview == null);
+ try testing.expect(!p.view().raw_hover_intent);
+ }
+}
+
+test "README names every file the tree serves" {
+ // /README is the whole manual a client gets; a file it never mentions
+ // is one nobody can find without reading this source.
+ const words = struct {
+ fn has(name: []const u8) bool {
+ var it = std.mem.tokenizeAny(u8, fs.help, " \t\n,.:;()'\"$<>|=/");
+ while (it.next()) |w| if (std.mem.eql(u8, w, name)) return true;
+ return false;
+ }
+ };
+ inline for (@typeInfo(TopFile).@"enum".field_values) |value| {
+ const t: TopFile = @fromBackingInt(@intCast(value));
+ if (t != .root and !words.has(t.fileName())) {
+ std.debug.print("README does not mention /{s}\n", .{t.fileName()});
+ return error.Undocumented;
+ }
+ }
+ inline for (@typeInfo(PaneFile).@"enum".field_values) |value| {
+ const t: PaneFile = @fromBackingInt(@intCast(value));
+ const ok = if (t == .dir) true else if (t.inPty() and t != .pty)
+ std.mem.indexOf(u8, fs.help, "pty/" ++ comptime @as(PaneFile, @fromBackingInt(@intCast(value))).fileName()) != null
+ else
+ words.has(t.fileName());
+ if (!ok) {
+ std.debug.print("README does not mention pane file {s}\n", .{@tagName(t)});
+ return error.Undocumented;
+ }
+ }
+}
+
+test "readdir lists the root and a pane directory without creating anything" {
+ const gpa = testing.allocator;
+ const p = try withFile(gpa, "hello\n");
+ defer p.deinit();
+ const serial = serialOf(p);
+ var buf: [32]th.Dirent = undefined;
+
+ const before = p.next_serial;
+ const top_reply = rdir(p, root, 0);
+ try testing.expectEqual(Status.ok, top_reply.reply.status);
+ var top_bytes: [4096]u8 = undefined;
+ @memcpy(top_bytes[0..top_reply.bytes.len], top_reply.bytes);
+ const top = th.dirents(top_bytes[0..top_reply.bytes.len], &buf);
+ try testing.expect(top.len >= 10);
+ for ([_][]const u8{ "README", "index", "status", "focus", "ctl", "commands", "recent", "dumps", "addons", "look", "exec", "pager", "log", "screen", "listeners", "sessions", "layout", "tag", "tagexec", "kbdin", "mousein", "plumb", "pane", "col", "os" }, 0..) |name, i| {
+ try testing.expectEqualStrings(name, top[i].name);
+ try testing.expectEqual(i >= 21, top[i].dir);
+ }
+ try testing.expectEqual(@backingInt(TopFile.plumb), top[21].node);
+ try testing.expectEqual(@backingInt(TopFile.pane), top[22].node);
+ try testing.expectEqual(@backingInt(TopFile.col), top[23].node);
+ try testing.expectEqual(fs.os_root, top[24].node);
+ // The plumber's directory: its rules, then send.
+ const plumb_reply = rdir(p, @backingInt(TopFile.plumb), 0);
+ var plumb_bytes: [256]u8 = undefined;
+ @memcpy(plumb_bytes[0..plumb_reply.bytes.len], plumb_reply.bytes);
+ var plumb_buf: [4]th.Dirent = undefined;
+ const plumb = th.dirents(plumb_bytes[0..plumb_reply.bytes.len], &plumb_buf);
+ // Then the ports the default rules name, in their order.
+ try testing.expectEqual(@as(usize, 4), plumb.len);
+ for ([_][]const u8{ "rules", "send", "web", "edit" }, plumb) |want, got| try testing.expectEqualStrings(want, got.name);
+ var idbuf: [16]u8 = undefined;
+ try testing.expect(th.nameAt(top, try std.fmt.bufPrint(&idbuf, "{d}", .{serial})) == null);
+ try testing.expect(th.nameAt(top, "self") == null);
+ try testing.expect(th.nameAt(top, "cons") == null);
+
+ var rest_buf: [32]th.Dirent = undefined;
+ const rest = rdir(p, root, 3);
+ try testing.expectEqual(top.len - 3, th.dirents(rest.bytes, &rest_buf).len);
+ const eof = rdir(p, root, 99);
+ try testing.expectEqual(Status.ok, eof.reply.status);
+ try testing.expectEqual(@as(usize, 0), eof.bytes.len);
+
+ // Walk, stat and open-for-read every top entry a browser would, then every pane file.
+ for (top) |entry| {
+ if (std.mem.eql(u8, entry.name, "os")) continue;
+ const inspected = look_up(p, root, entry.name);
+ try testing.expectEqual(Status.ok, inspected.reply.status);
+ try testing.expectEqual(entry.node, inspected.reply.attr.node);
+ try testing.expectEqual(Status.ok, call(p, .{ .tag = 1, .op = .getattr, .node = entry.node }).reply.status);
+ try testing.expectEqual(before, p.next_serial);
+ }
+ const panes_dir = rdir(p, @backingInt(TopFile.pane), 0);
+ const listed = th.dirents(panes_dir.bytes, &buf);
+ var idname: [16]u8 = undefined;
+ const own = th.nameAt(listed, try std.fmt.bufPrint(&idname, "{d}", .{serial})).?;
+ try testing.expectEqual(Node.of(serial, .dir), own.node);
+ try testing.expect(own.dir);
+ // `new` is listed, so `ls` shows it. Walking and stat-ing it allocates
+ // nothing — only an open does — which is what keeps `ls -l` and any other
+ // client that stats every name a listing gave it inert.
+ const shown = th.nameAt(listed, new_pane).?;
+ try testing.expect(!shown.dir);
+ try testing.expectEqual(Status.ok, look_up(p, @backingInt(TopFile.pane), new_pane).reply.status);
+ try testing.expectEqual(Status.ok, call(p, .{ .tag = 1, .op = .getattr, .node = @backingInt(TopFile.new) }).reply.status);
+ try testing.expectEqual(before, p.next_serial);
+
+ const dir = rdir(p, Node.of(serial, .dir), 0);
+ const files = th.dirents(dir.bytes, &buf);
+ try testing.expectEqual(@as(usize, 19), files.len);
+ for ([_][]const u8{
+ "name", "body", "tag", "ctl", "addr", "dot", "limit", "data", "xdata", "sel",
+ "dirty", "mark", "scroll", "errors", "event", "look", "exec", "tagexec", "rows",
+ }, 0..) |name, i|
+ try testing.expectEqualStrings(name, files[i].name);
+ try testing.expect(th.nameAt(files, ".") == null);
+ try testing.expect(th.nameAt(files, "rdsel") == null);
+ try testing.expectEqual(Node.of(serial, .body), th.nameAt(files, "body").?.node);
+ for (files) |entry| {
+ const stat = call(p, .{ .tag = 1, .op = .getattr, .node = entry.node });
+ try testing.expectEqual(Status.ok, stat.reply.status);
+ try testing.expectEqual(p.fs.started, stat.reply.attr.mtime);
+ }
+ try testing.expectEqual(before, p.next_serial);
+
+ try testing.expectEqual(E.NOTDIR, rdir(p, Node.of(serial, .body), 0).errno());
+ try testing.expectEqual(E.NOTDIR, rdir(p, @backingInt(TopFile.index), 0).errno());
+}
+
+test "lookup resolves top files, pane serials and pane files" {
+ const gpa = testing.allocator;
+ const p = try withFile(gpa, "hello\n");
+ defer p.deinit();
+ const serial = serialOf(p);
+
+ try testing.expectEqual(@as(u64, @backingInt(TopFile.index)), look_up(p, root, "index").reply.attr.node);
+ try testing.expect(!look_up(p, root, "status").reply.attr.dir);
+ try testing.expectEqual(@as(u16, 0o444), look_up(p, root, "status").reply.attr.mode);
+ try testing.expectEqual(@as(u16, 0o666), look_up(p, root, "look").reply.attr.mode);
+ try testing.expectEqual(E.NOENT, look_up(p, root, "new").errno());
+ try testing.expect(look_up(p, root, "pane").reply.attr.dir);
+ try testing.expect(look_up(p, root, "os").reply.attr.dir);
+ try testing.expectEqual(E.NOENT, look_up(p, root, "nosuchthing").errno());
+ try testing.expectEqual(E.NOENT, look_up(p, root, "self").errno());
+ try testing.expectEqual(E.NOENT, look_up(p, root, "cons").errno());
+ try testing.expectEqual(E.NOTDIR, look_up(p, @backingInt(TopFile.index), "x").errno());
+
+ var idbuf: [16]u8 = undefined;
+ const serial_name = try std.fmt.bufPrint(&idbuf, "{d}", .{serial});
+ try testing.expectEqual(E.NOENT, look_up(p, root, serial_name).errno());
+ const dir = look_up(p, @backingInt(TopFile.pane), serial_name);
+ try testing.expectEqual(Node.of(serial, .dir), dir.reply.attr.node);
+ try testing.expect(dir.reply.attr.dir);
+ try testing.expectEqualStrings(serial_name, dir.reply.attr.name);
+ try testing.expectEqual(E.NOENT, look_up(p, @backingInt(TopFile.pane), "99999").errno());
+ try testing.expectEqual(E.NOENT, look_up(p, @backingInt(TopFile.pane), "0").errno());
+
+ const body = look_up(p, Node.of(serial, .dir), "body");
+ try testing.expectEqual(Node.of(serial, .body), body.reply.attr.node);
+ const stat = call(p, .{ .tag = 4, .op = .getattr, .node = Node.of(serial, .body) });
+ try testing.expectEqual(body.reply.attr.size, stat.reply.attr.size);
+ try testing.expectEqual(@as(u64, "hello\n".len), stat.reply.attr.size);
+ try testing.expectEqual(E.NOENT, look_up(p, Node.of(serial, .dir), "editout").errno());
+ try testing.expectEqual(E.NOENT, look_up(p, Node.of(serial, .dir), "rdsel").errno());
+ try testing.expectEqual(E.NOTDIR, look_up(p, Node.of(serial, .body), "x").errno());
+}
+
+test "opening /pane/new makes a pane and removing one closes it" {
+ const gpa = testing.allocator;
+ const p = try withFile(gpa, "first\n");
+ defer p.deinit();
+ const before = p.next_serial;
+ const panes_dir = @backingInt(TopFile.pane);
+
+ // Browsing /pane creates nothing, and neither does walking or stat-ing
+ // `new` itself: only an open does. That is what lets `new` be listed at
+ // all, since `ls -l` stats every name a listing handed it.
+ try testing.expectEqual(Status.ok, rdir(p, panes_dir, 0).reply.status);
+ try testing.expectEqual(Status.ok, look_up(p, panes_dir, new_pane).reply.status);
+ try testing.expectEqual(Status.ok, call(p, .{ .tag = 1, .op = .getattr, .node = @backingInt(TopFile.new) }).reply.status);
+ try testing.expectEqual(before, p.next_serial);
+
+ // The open makes the pane and hands back its serial; the read only
+ // observes, so two reads of one fid answer the same pane.
+ const made = call(p, .{ .tag = 2, .op = .open, .node = @backingInt(TopFile.new) });
+ try testing.expectEqual(Status.ok, made.reply.status);
+ try testing.expectEqual(before + 1, p.next_serial);
+ const serial = before + 1;
+ try testing.expectEqual(serial, made.reply.handle);
+ var expected: [16]u8 = undefined;
+ const want = try std.fmt.bufPrint(&expected, "{d}\n", .{serial});
+ for (0..2) |_| {
+ const answer = call(p, .{ .tag = 3, .op = .read, .node = @backingInt(TopFile.new), .handle = made.reply.handle, .size = 64 });
+ try testing.expectEqualStrings(want, answer.bytes);
+ }
+
+ const id = p.paneBySerial(serial).?;
+ try testing.expectEqualStrings("", p.panes[id].?.file.?.content);
+ // Its directory is the session's, not that of /test.txt, the pane
+ // that happened to have the keyboard.
+ var named: [4096]u8 = undefined;
+ try testing.expectEqualStrings(try std.fmt.bufPrint(&named, "{s}/+New", .{p.sessionDir()}), p.panes[id].?.file.?.path);
+ _ = wr(p, Node.of(serial, .body), "hi");
+
+ // A second open is a second pane, and releasing a clone fid leaves the
+ // pane it made standing.
+ const second = call(p, .{ .tag = 4, .op = .open, .node = @backingInt(TopFile.new) });
+ try testing.expectEqual(Status.ok, second.reply.status);
+ try testing.expect(second.reply.handle != made.reply.handle);
+ _ = call(p, .{ .tag = 5, .op = .release, .node = @backingInt(TopFile.new), .handle = made.reply.handle, .opened = true });
+ try testing.expect(p.paneBySerial(serial) != null);
+ try testing.expectEqualStrings("hi", p.panes[id].?.file.?.content);
+
+ // Every create is refused, a pane's that has closed as gone, and `new`
+ // is the only name in /pane that is not a serial.
+ try testing.expectEqual(E.PERM, call(p, .{ .tag = 6, .op = .open, .node = panes_dir, .create = true, .data = "scratch" }).errno());
+ try testing.expectEqual(E.PERM, call(p, .{ .tag = 6, .op = .open, .node = Node.of(serial, .dir), .create = true, .data = "x" }).errno());
+ try testing.expectEqual(E.NOENT, call(p, .{ .tag = 6, .op = .open, .node = Node.of(999_999, .dir), .create = true, .data = "exec" }).errno());
+ try testing.expectEqual(E.NOENT, look_up(p, panes_dir, "scratch").errno());
+ try testing.expectEqual(E.NOENT, look_up(p, root, new_pane).errno());
+ // ...and it is listed, because the user asked to see it in `ls`.
+ var listing: [32]th.Dirent = undefined;
+ const shown = rdir(p, panes_dir, 0);
+ try testing.expect(th.nameAt(th.dirents(shown.bytes, &listing), new_pane) != null);
+
+ // Tremove closes the pane it names, and nothing else in the tree.
+ try testing.expectEqual(E.PERM, th.rmdir(p, Node.of(serial, .body)).errno());
+ try testing.expectEqual(E.PERM, th.rmdir(p, @backingInt(TopFile.index)).errno());
+ try testing.expect(p.paneBySerial(serial) != null);
+ try testing.expectEqual(Status.ok, th.rmdir(p, Node.of(serial, .dir)).reply.status);
+ try testing.expect(p.paneBySerial(serial) == null);
+ try testing.expectEqual(E.NOENT, th.rmdir(p, Node.of(serial, .dir)).errno());
+}
+
+test "every open that holds something is one record, named by its handle only on its own node" {
+ const p = try th.withTerm(testing.allocator);
+ defer p.deinit();
+ const serial = serialOf(p);
+ const log = @backingInt(TopFile.log);
+ const event = Node.of(serial, .event);
+ const run = Node.of(serial, .pty_run);
+ const logged = call(p, .{ .tag = 1, .op = .open, .node = log }).reply.handle;
+ const reader = call(p, .{ .tag = 2, .op = .open, .node = event }).reply.handle;
+ const ran = call(p, .{ .tag = 3, .op = .open, .node = run }).reply.handle;
+ try testing.expect(logged != 0 and reader != 0 and ran != 0);
+ try testing.expect(logged != reader and reader != ran and logged != ran);
+ // An open that holds nothing takes no record.
+ try testing.expectEqual(@as(u32, 0), call(p, .{ .tag = 4, .op = .open, .node = Node.of(serial, .addr) }).reply.handle);
+
+ // A handle is refused on any other node, and releasing it there gives
+ // nothing up.
+ try testing.expectEqual(E.INVAL, call(p, .{ .tag = 5, .op = .read, .node = run, .handle = logged, .size = 64 }).errno());
+ try testing.expectEqual(E.INVAL, call(p, .{ .tag = 6, .op = .write, .node = log, .handle = ran, .data = "follow\n" }).errno());
+ _ = call(p, .{ .tag = 7, .op = .release, .node = log, .handle = reader });
+ try testing.expectEqualStrings(e_in_use, call(p, .{ .tag = 8, .op = .open, .node = event }).reply.ename);
+
+ for ([_]u64{ log, event, run }, [_]u32{ logged, reader, ran }) |node, h|
+ _ = call(p, .{ .tag = 9, .op = .release, .node = node, .handle = h });
+ for (p.fs.opens) |o| try testing.expect(o.node == 0);
+ try testing.expectEqual(@as(u16, 0), p.fs.listeners);
+}
+
+test "directories walk to their parents" {
+ const p = try withFile(testing.allocator, "contents\n");
+ defer p.deinit();
+ for ([_]struct { node: u64, parent: u64 }{
+ .{ .node = root, .parent = root },
+ .{ .node = @backingInt(TopFile.pane), .parent = root },
+ .{ .node = Node.of(serialOf(p), .dir), .parent = @backingInt(TopFile.pane) },
+ .{ .node = fs.os_root, .parent = root },
+ }) |case| {
+ const result = look_up(p, case.node, "..");
+ try testing.expectEqual(Status.ok, result.reply.status);
+ try testing.expectEqual(case.parent, result.reply.attr.node);
+ }
+ try testing.expectEqual(E.NOTDIR, look_up(p, @backingInt(TopFile.index), "..").errno());
+ try testing.expectEqual(E.NOTDIR, look_up(p, Node.of(serialOf(p), .body), "..").errno());
+}
+
+test "editor paths resolve to the same nodes the wire serves" {
+ const p = try withFile(testing.allocator, "contents\n");
+ defer p.deinit();
+ const serial = serialOf(p);
+ var path: [64]u8 = undefined;
+ try testing.expectEqual(root, resolveSelf(p, "").?);
+ try testing.expectEqual(root, resolveSelf(p, "/./pane/../").?);
+ try testing.expectEqual(@backingInt(TopFile.index), resolveSelf(p, "index").?);
+ try testing.expectEqual(@backingInt(TopFile.status), resolveSelf(p, "status").?);
+ try testing.expect(resolveSelf(p, "new") == null);
+ try testing.expectEqual(@backingInt(TopFile.pane), resolveSelf(p, "pane").?);
+ try testing.expectEqual(Node.of(serial, .dir), resolveSelf(p, try std.fmt.bufPrint(&path, "pane/{d}", .{serial})).?);
+ try testing.expectEqual(Node.of(serial, .sel), resolveSelf(p, try std.fmt.bufPrint(&path, "pane/{d}/sel", .{serial})).?);
+ try testing.expect(resolveSelf(p, try std.fmt.bufPrint(&path, "pane/{d}/pty/ctl", .{serial})) == null);
+ try testing.expect(resolveSelf(p, try std.fmt.bufPrint(&path, "pane/{d}/rdsel", .{serial})) == null);
+ try testing.expect(resolveSelf(p, "self/index") == null);
+ try testing.expect(resolveSelf(p, "status/ctl") == null);
+ try testing.expect(resolveSelf(p, "cons") == null);
+ try testing.expect(resolveSelf(p, "pane/0") == null);
+ // A column's files, as the wire serves them.
+ const col = layout.columnSerial(p, 0);
+ try testing.expectEqual(Node.ofCol(col, .tag), resolveSelf(p, try std.fmt.bufPrint(&path, "col/{d}/tag", .{col})).?);
+ // The editor resolves its own paths to inspect them, so `new` names
+ // nothing here; only a client's walk makes a pane.
+ const before = p.next_serial;
+ try testing.expect(resolveSelf(p, "pane/new") == null);
+ try testing.expect(resolveSelf(p, "pane/new/body") == null);
+ try testing.expectEqual(before, p.next_serial);
+}
+
+test "random placements, refused or not, leave no pane under its tag and two rows" {
+ var tmp = testing.tmpDir(.{});
+ defer tmp.cleanup();
+ try tmp.dir.writeFile(testing.io, .{ .sub_path = "f.txt", .data = "one\ntwo\n" });
+ var dir_buf: [4096]u8 = undefined;
+ const dir = dir_buf[0..try tmp.dir.realPath(testing.io, &dir_buf)];
+ var look_line: [4200]u8 = undefined;
+ const looked = try std.fmt.bufPrint(&look_line, "{s}/f.txt\n", .{dir});
+ var seed: u64 = 0;
+ while (seed < 300) : (seed += 1) {
+ var prng = std.Random.DefaultPrng.init(seed);
+ const r = prng.random();
+ const rows = r.intRangeAtMost(u16, 6, 40);
+ const p = try pardes.Pardes.init(testing.allocator, .{ .tty_only = true, .cols = r.intRangeAtMost(u16, 60, 240), .rows = rows });
+ defer p.deinit();
+ while (p.nextEffect()) |_| {}
+ _ = try p.setTestFile("x\n");
+ while (p.nextEffect()) |_| {}
+ for (0..r.uintLessThan(usize, 3)) |_| _ = th.wr(p, Node.of(serialOf(p), .exec), "Newcol\n");
+ for (0..40) |step| {
+ var serials: [pardes.MAX_PANES]u32 = undefined;
+ var n: usize = 0;
+ for (p.panes) |slot| if (slot) |pn| {
+ serials[n] = pn.serial;
+ n += 1;
+ };
+ if (n == 0) break;
+ const at = serials[r.uintLessThan(usize, n)];
+ const action = r.uintLessThan(u8, 8);
+ switch (action) {
+ 0 => _ = th.wr(p, Node.of(at, .exec), "New\n"),
+ 1 => _ = call(p, .{ .tag = 1, .op = .open, .node = @backingInt(TopFile.new) }),
+ 2 => _ = th.wr(p, Node.of(at, .exec), "Newcol\n"),
+ 3 => _ = th.wr(p, Node.of(at, .exec), "Edit =\n"),
+ 4 => _ = th.wr(p, Node.of(at, .exec), "Term\n"),
+ 5 => _ = th.wr(p, Node.of(at, .look), looked),
+ 6 => _ = th.wr(p, Node.of(at, .exec), "Delcol\n"),
+ else => _ = th.wr(p, Node.of(at, .ctl), "delete\n"),
+ }
+ for (0..p.view().ncol) |c| if (!layout.columnAtMinimums(p, c)) {
+ std.debug.print("seed {d} rows {d} step {d} action {d}: column {d} under its minimums\n", .{ seed, rows, step, action, c });
+ for (p.view().cols[c].panes[0..p.view().cols[c].n]) |id| std.debug.print(" pane {d} h {d} min {d}\n", .{ id, p.view().rects[id].h, layout.minRows(p, id) });
+ return error.TestUnexpectedResult;
+ };
+ }
+ }
+}
+
+test "at the pane cap, pane/new, look and New each say so, and look reads back empty" {
+ const p = try th.withFile(testing.allocator, "x\n");
+ defer p.deinit();
+ // Tall enough that the column holds every pane at its tag and two rows,
+ // and wide enough that each tag, the session directory's +New, is one.
+ p.update(.{ .resize = .{ .cols = 400, .rows = pardes.MAX_PANES * 4 } });
+ const new = @backingInt(TopFile.new);
+ while (p.freeSlot() != null) try testing.expectEqual(Status.ok, call(p, .{ .tag = 1, .op = .open, .node = new }).reply.status);
+ var want: [64]u8 = undefined;
+ const said = try std.fmt.bufPrint(&want, "no space for a pane: {d} max", .{pardes.MAX_PANES});
+ const refused = call(p, .{ .tag = 2, .op = .open, .node = new });
+ try testing.expectEqual(E.NOSPC, refused.errno());
+ try testing.expect(std.mem.endsWith(u8, refused.reply.ename, said));
+ // A refused open is its error alone: no err, and no msg besides.
+ try testing.expect(!th.logHas(p, said));
+ try testing.expect(!th.logHas(p, "New: no space"));
+ // A look that would open a pane fails its write, and says the same.
+ var tmp = testing.tmpDir(.{});
+ defer tmp.cleanup();
+ try tmp.dir.writeFile(testing.io, .{ .sub_path = "f.txt", .data = "f\n" });
+ var dir_buf: [4096]u8 = undefined;
+ const dir = dir_buf[0..try tmp.dir.realPath(testing.io, &dir_buf)];
+ var line: [4200]u8 = undefined;
+ const look_node = @backingInt(TopFile.look);
+ const looked = th.wr(p, look_node, try std.fmt.bufPrint(&line, "{s}/f.txt\n", .{dir}));
+ try testing.expect(looked.errno() != 0);
+ try testing.expect(std.mem.indexOf(u8, looked.reply.ename, said) != null);
+ // Its err record names the file once: `look: no space...`.
+ try testing.expect(th.logHas(p, "look: no space"));
+ try testing.expect(!th.logHas(p, "look: look:"));
+ try testing.expectEqualStrings("", th.rd(p, look_node, 0, 64).bytes);
+ // New from a pane's ctl fails as well.
+ const ctl_node = Node.of(p.panes[0].?.serial, .ctl);
+ const made = th.wr(p, ctl_node, "New\n");
+ try testing.expect(std.mem.indexOf(u8, made.reply.ename, said) != null);
+}
+
+test "nothing a mount's close or a no-op truncate sends waits on the editor: a held line runs at its next step" {
+ const p = try withFile(testing.allocator, "x\n");
+ defer p.deinit();
+ const exec = @backingInt(TopFile.exec);
+ // `> exec` truncates nothing; `> body` does.
+ try testing.expect(!needsQuiet(p, .{ .tag = 1, .op = .setattr, .node = exec, .truncate = true }));
+ try testing.expect(!changesPane(p, .{ .tag = 1, .op = .setattr, .node = exec, .truncate = true }));
+ try testing.expect(needsQuiet(p, .{ .tag = 1, .op = .setattr, .node = Node.of(serialOf(p), .body), .truncate = true }));
+ const h = call(p, .{ .tag = 2, .op = .open, .node = exec, .omode = 1 }).reply.handle;
+ _ = call(p, .{ .tag = 3, .op = .write, .node = exec, .handle = h, .data = "Msg at-step" });
+ const close: Req = .{ .tag = 4, .op = .release, .node = exec, .handle = h, .opened = true };
+ try testing.expect(!needsQuiet(p, close) and handsOff(p, close));
+ _ = call(p, close);
+ try testing.expect(!th.logHas(p, " at-step\n"));
+ runClosedLines(p);
+ try testing.expect(th.logHas(p, " at-step\n"));
+}
+
+test "a command line cut across writes runs once whole, and the last runs at release; an Edit block waits for its end" {
+ const p = try th.withFile(testing.allocator, "x\n");
+ defer p.deinit();
+ const exec = @backingInt(TopFile.exec);
+ const h = call(p, .{ .tag = 1, .op = .open, .node = exec, .omode = 1 }).reply.handle;
+ try testing.expect(h != 0);
+ // Each piece fills its Twrite (a client's one write cut at msize).
+ for ([_][]const u8{ "Msg he", "llo\nMsg wor", "ld\nMsg tail" }) |piece| {
+ p.fs.write_room = @intCast(piece.len);
+ try testing.expectEqual(Status.ok, call(p, .{ .tag = 2, .op = .write, .node = exec, .handle = h, .data = piece }).reply.status);
+ }
+ p.fs.write_room = 0;
+ try testing.expect(th.logHas(p, " hello\n") and th.logHas(p, " world\n"));
+ try testing.expect(!th.logHas(p, " he\n") and !th.logHas(p, " tail\n"));
+ _ = call(p, .{ .tag = 3, .op = .release, .node = exec, .handle = h, .opened = true });
+ runClosedLines(p);
+ try testing.expect(th.logHas(p, " tail\n"));
+ // An Edit block's text lines come in later writes on the same open.
+ const serial = serialOf(p);
+ const ctl_node = Node.of(serial, .ctl);
+ const c = call(p, .{ .tag = 4, .op = .open, .node = ctl_node, .omode = 1 }).reply.handle;
+ for ([_][]const u8{ "Edit ,a\n", "one\ntw", "o\n", ".\n" }) |piece|
+ try testing.expectEqual(Status.ok, call(p, .{ .tag = 5, .op = .write, .node = ctl_node, .handle = c, .data = piece }).reply.status);
+ _ = call(p, .{ .tag = 6, .op = .release, .node = ctl_node, .handle = c, .opened = true });
+ runClosedLines(p);
+ try testing.expectEqualStrings("x\none\ntwo\n", p.panes[0].?.file.?.content);
+}
+
+test "a refused open, create or remove says why in words and logs no err; a refused write logs one" {
+ const p = try th.withFile(testing.allocator, "x\n");
+ defer p.deinit();
+ const serial = serialOf(p);
+ // pane/new is read, never written: a write is refused, and is no
+ // failure the log tells of.
+ const new = th.wr(p, @backingInt(TopFile.new), "x\n");
+ try testing.expectEqual(Status.err, new.reply.status);
+ try testing.expectEqualStrings("permission denied", new.reply.ename);
+ const made = call(p, .{ .tag = 2, .op = .open, .node = Node.of(serial, .body), .create = true });
+ try testing.expectEqualStrings("permission denied", made.reply.ename);
+ const gone = th.rmdir(p, @backingInt(TopFile.index));
+ try testing.expectEqual(Status.err, gone.reply.status);
+ try testing.expect(gone.reply.ename.len > 0 and !std.ascii.isUpper(gone.reply.ename[0]));
+ // An OTRUNC open's truncation of data after a failed addr: refused, no err.
+ _ = th.wr(p, Node.of(serial, .addr), "/nothere/");
+ const errs = th.logCount(p, "\nerr ");
+ try testing.expectEqual(Status.err, call(p, .{ .tag = 3, .op = .setattr, .node = Node.of(serial, .data), .truncate = true }).reply.status);
+ try testing.expectEqual(errs, th.logCount(p, "\nerr "));
+ try testing.expectEqual(@as(usize, 1), errs); // the addr write's own
+ // A write is the rule's: refused, it logs its one err, in words too.
+ try testing.expectEqual(Status.err, th.wr(p, Node.of(serial, .ctl), "bogus\n").reply.status);
+ try testing.expectEqual(@as(usize, 2), th.logCount(p, "\nerr "));
+}
+
+test "a write with no newline waits for its newline or the close, whatever its size, and fails there in the log" {
+ const p = try th.withFile(testing.allocator, "abc\n");
+ defer p.deinit();
+ const serial = serialOf(p);
+ const ctl_node = Node.of(serial, .ctl);
+ const c = call(p, .{ .tag = 1, .op = .open, .node = ctl_node, .omode = 1 }).reply.handle;
+ // Short of its message or not, a piece with no newline is held: a mount
+ // cuts a long line anywhere.
+ p.fs.write_room = 8192;
+ defer p.fs.write_room = 0;
+ try testing.expectEqual(Status.ok, call(p, .{ .tag = 2, .op = .write, .node = ctl_node, .handle = c, .data = "Edit ,s/a/" }).reply.status);
+ try testing.expectEqual(Status.ok, call(p, .{ .tag = 3, .op = .write, .node = ctl_node, .handle = c, .data = "A/\n" }).reply.status);
+ try testing.expectEqualStrings("Abc\n", p.panes[0].?.file.?.content);
+ // An `a` needs its text and `.`: held across writes.
+ try testing.expectEqual(Status.ok, call(p, .{ .tag = 4, .op = .write, .node = ctl_node, .handle = c, .data = "Edit $a" }).reply.status);
+ try testing.expectEqual(Status.ok, call(p, .{ .tag = 5, .op = .write, .node = ctl_node, .handle = c, .data = "\nmore\n.\n" }).reply.status);
+ try testing.expectEqualStrings("Abc\nmore\n", p.panes[0].?.file.?.content);
+ // The last line, never ended, runs at the close: its failure is its err.
+ try testing.expectEqual(Status.ok, call(p, .{ .tag = 6, .op = .write, .node = ctl_node, .handle = c, .data = "bogus" }).reply.status);
+ try testing.expect(!th.logHas(p, "bogus"));
+ _ = call(p, .{ .tag = 7, .op = .release, .node = ctl_node, .handle = c, .opened = true });
+ runClosedLines(p);
+ try testing.expect(th.logHas(p, "unknown control message \"bogus\""));
+ // A name: a NUL fails its write, not the close after it.
+ const name = Node.of(serial, .name);
+ const n = call(p, .{ .tag = 10, .op = .open, .node = name, .omode = 1 }).reply.handle;
+ const bad = call(p, .{ .tag = 11, .op = .write, .node = name, .handle = n, .data = "del\x00ete" });
+ try testing.expectEqual(Status.err, bad.reply.status);
+ try testing.expect(std.mem.indexOf(u8, bad.reply.ename, "a NUL") != null);
+ try testing.expectEqual(Status.ok, call(p, .{ .tag = 12, .op = .release, .node = name, .handle = n, .opened = true }).reply.status);
+ runClosedLines(p);
+}
+
+test "look and exec read back what their own open's write touched; a fresh open reads the session's last" {
+ if (pardes.Term.ops == null) return error.SkipZigTest; // a shell, by Term
+ const p = try th.withFile(testing.allocator, "x\n");
+ defer p.deinit();
+ const exec = @backingInt(TopFile.exec);
+ const first = p.panes[0].?.serial;
+ const mine = call(p, .{ .tag = 1, .op = .open, .node = exec, .omode = 2 }).reply.handle;
+ const theirs = call(p, .{ .tag = 2, .op = .open, .node = exec, .omode = 2 }).reply.handle;
+ _ = call(p, .{ .tag = 3, .op = .write, .node = exec, .handle = mine, .data = "Term\n" });
+ const made = p.panes[p.view().active].?.serial;
+ try testing.expect(made != first);
+ _ = call(p, .{ .tag = 4, .op = .write, .node = exec, .handle = theirs, .data = "Msg hi\n" });
+ var want: [16]u8 = undefined;
+ // Read at the offset the write left, as a shell's `exec 3<>` does.
+ try testing.expectEqualStrings(try std.fmt.bufPrint(&want, "{d}\n", .{made}), call(p, .{ .tag = 5, .op = .read, .node = exec, .handle = mine, .off = 4, .size = 64 }).bytes);
+ try testing.expectEqualStrings("", call(p, .{ .tag = 6, .op = .read, .node = exec, .handle = mine, .off = 4, .size = 64 }).bytes);
+ const said = p.panes[p.view().active].?.serial;
+ try testing.expectEqualStrings(try std.fmt.bufPrint(&want, "{d}\n", .{said}), call(p, .{ .tag = 7, .op = .read, .node = exec, .handle = theirs, .size = 64 }).bytes);
+ const fresh = call(p, .{ .tag = 8, .op = .open, .node = exec }).reply.handle;
+ try testing.expectEqualStrings(try std.fmt.bufPrint(&want, "{d}\n", .{said}), call(p, .{ .tag = 9, .op = .read, .node = exec, .handle = fresh, .size = 64 }).bytes);
+ for ([_]u32{ mine, theirs, fresh }) |hh| _ = call(p, .{ .tag = 10, .op = .release, .node = exec, .handle = hh, .opened = true });
+}
+
+test "a write cut where a writer's 4096-byte buffer filled holds its partial line for the next write" {
+ const p = try th.withFile(testing.allocator, "x\n");
+ defer p.deinit();
+ const exec_node = Node.of(serialOf(p), .exec);
+ const h = call(p, .{ .tag = 1, .op = .open, .node = exec_node, .omode = 1 }).reply.handle;
+ // 4096 bytes: whole `Msg first` lines, then a line cut after `Msg`.
+ var buf: [4096]u8 = undefined;
+ const line = "Msg first\n";
+ var n: usize = 0;
+ while (n + line.len <= buf.len - 3) : (n += line.len) @memcpy(buf[n..][0..line.len], line);
+ @memset(buf[n..], ' ');
+ @memcpy(buf[buf.len - 3 ..], "Msg");
+ try testing.expectEqual(Status.ok, call(p, .{ .tag = 2, .op = .write, .node = exec_node, .handle = h, .data = &buf }).reply.status);
+ try testing.expectEqual(Status.ok, call(p, .{ .tag = 3, .op = .write, .node = exec_node, .handle = h, .data = " last\n" }).reply.status);
+ _ = call(p, .{ .tag = 4, .op = .release, .node = exec_node, .handle = h, .opened = true });
+ try testing.expect(th.logHas(p, "last"));
+ try testing.expect(!th.logHas(p, "wrong #args"));
+}
+
+test "a rename of a pane's directory or file is refused as not permitted" {
+ const p = try th.withFile(testing.allocator, "x\n");
+ defer p.deinit();
+ const serial = serialOf(p);
+ for ([_]u64{ Node.of(serial, .dir), Node.of(serial, .body) }) |node| {
+ const r = call(p, .{ .tag = 1, .op = .setattr, .node = node, .set = .{ .name = true } });
+ try testing.expectEqual(E.PERM, r.errno());
+ try testing.expect(std.mem.indexOf(u8, r.reply.ename, "not permitted") != null);
+ }
+}
+
+test "no placement leaves a pane shorter than its tag and two rows; a full column refuses the next" {
+ const p = try th.withFile(testing.allocator, "x\n");
+ defer p.deinit();
+ const new = @backingInt(TopFile.new);
+ var made: usize = 1;
+ const refused = while (made < pardes.MAX_PANES) : (made += 1) {
+ const a = call(p, .{ .tag = 1, .op = .open, .node = new });
+ if (a.reply.status == .err) break a;
+ } else return error.NeverRefused;
+ try testing.expectEqual(E.NOSPC, refused.errno());
+ try testing.expect(std.mem.indexOf(u8, refused.reply.ename, "no space for a pane in that column") != null);
+ // The refused pane was never there; its serial is not handed out again
+ // (gaps are fine: a serial once said names one pane for good).
+ const before = p.next_serial;
+ try testing.expectEqual(E.NOSPC, call(p, .{ .tag = 1, .op = .open, .node = new }).errno());
+ try testing.expectEqual(before + 1, p.next_serial);
+ p.sync();
+ var count: usize = 0;
+ for (p.panes) |slot| count += @intFromBool(slot != null);
+ try testing.expectEqual(made, count); // the refused one is gone
+ for (0..p.view().ncol) |c| for (p.view().cols[c].panes[0..p.view().cols[c].n]) |k| {
+ if (p.view().cols[c].n > 1 and !p.panes[k].?.collapsed)
+ try testing.expect(p.view().rects[k].h >= p.panes[k].?.tag_rows + pardes.layout.min_body_rows);
+ };
+}
+
+test "an Edit block still open when its open closes fails there with an err and changes nothing" {
+ const p = try th.withFile(testing.allocator, "abc\n");
+ defer p.deinit();
+ const ctl_node = Node.of(serialOf(p), .ctl);
+ const c = call(p, .{ .tag = 1, .op = .open, .node = ctl_node, .omode = 1 }).reply.handle;
+ _ = call(p, .{ .tag = 2, .op = .write, .node = ctl_node, .handle = c, .data = "Edit ,x/b/{\ni/[/\n" });
+ _ = call(p, .{ .tag = 3, .op = .release, .node = ctl_node, .handle = c, .opened = true });
+ runClosedLines(p);
+ try testing.expect(th.logHas(p, "unmatched"));
+ try testing.expectEqualStrings("abc\n", p.panes[0].?.file.?.content);
+}
+
+test "an a, c or i text still open when its open closes fails there too and changes nothing" {
+ const p = try th.withFile(testing.allocator, "abc\n");
+ defer p.deinit();
+ const ctl_node = Node.of(serialOf(p), .ctl);
+ const c = call(p, .{ .tag = 1, .op = .open, .node = ctl_node, .omode = 1 }).reply.handle;
+ _ = call(p, .{ .tag = 2, .op = .write, .node = ctl_node, .handle = c, .data = "Edit $a\nhalf of a block\n" });
+ _ = call(p, .{ .tag = 3, .op = .release, .node = ctl_node, .handle = c, .opened = true });
+ runClosedLines(p);
+ try testing.expect(th.logHas(p, "not ended by a . line"));
+ try testing.expectEqualStrings("abc\n", p.panes[0].?.file.?.content);
+}
+
+test "an a, c or i text cut short through exec is an err in the log, not a msg" {
+ const p = try th.withFile(testing.allocator, "abc\n");
+ defer p.deinit();
+ const exec = Node.of(serialOf(p), .exec);
+ const c = call(p, .{ .tag = 1, .op = .open, .node = exec, .omode = 1 }).reply.handle;
+ _ = call(p, .{ .tag = 2, .op = .write, .node = exec, .handle = c, .data = "Edit $a\nhalf\n" });
+ _ = call(p, .{ .tag = 3, .op = .release, .node = exec, .handle = c, .opened = true });
+ runClosedLines(p);
+ var want: [64]u8 = undefined;
+ try testing.expect(th.logHas(p, try std.fmt.bufPrint(&want, "err {d} exec: Edit: a, c or i text not ended", .{serialOf(p)})));
+ try testing.expect(!th.logHas(p, "msg 1 Edit: a, c or i"));
+ try testing.expectEqualStrings("abc\n", p.panes[0].?.file.?.content);
+}
+
+test "a pane made from pane/new goes last in its column, even when the last pane has no room to halve" {
+ const p = try th.withFile(testing.allocator, "x\n");
+ defer p.deinit();
+ for (0..3) |_| {
+ const made = call(p, .{ .tag = 1, .op = .open, .node = @backingInt(TopFile.new) }).reply.handle;
+ p.sync();
+ try testing.expectEqual(made, p.panes[p.view().cols[0].panes[p.view().cols[0].n - 1]].?.serial);
+ }
+}