diff options
| author | Gabriel Schneider <[email protected]> | 2026-11-18 22:03:14 -0300 |
|---|---|---|
| committer | Gabriel Schneider <[email protected]> | 2026-11-18 22:23:51 -0300 |
| commit | 99f5b10eccd95aa0066ea6fe6bb75f367ab56a47 (patch) | |
| tree | 813596ea84318a7bae4fd7416ba463de8e3b7107 /core/ninep/ctl.zig | |
| parent | 92d553123673376adf6126ab90d49a22c5b833d2 (diff) | |
| download | pardes-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/ctl.zig')
| -rw-r--r-- | core/ninep/ctl.zig | 2909 |
1 files changed, 2909 insertions, 0 deletions
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("ed); + try writeQuoted(&w, "DejaVu Sans Mono"); + try testing.expectEqualStrings("'DejaVu Sans Mono'", w.buffered()); + w = std.Io.Writer.fixed("ed); + 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); +} |
