//! The session's messages (pick-ui SPEC §10): each a kind, its cause as a //! word a Look understands, its text, the places it names and the lines //! that explain it, kept in a fixed list while it lives; the log of //! everything said behind them (the history, `SPC h m`, and 9P `/log`); //! the notice row at the window's foot that indexes them; and the //! transient band a pane shows over its body's top rows (a prompt waiting //! for input). const pardes = @import("root.zig"); const memory = @import("memory.zig"); const std = @import("std"); const layout = @import("layout.zig"); const ctlfs = @import("ninep/tree.zig"); const panes = @import("panes.zig"); const limits = memory.limits; const config = @import("config.zig"); const platform = pardes.platform; const Pane = panes.Pane; const MAX_PANES = pardes.MAX_PANES; const BOX_H = pardes.BOX_H; const Key = pardes.Key; const Rect = layout.Rect; const Pardes = pardes.Pardes; const Buf = pardes.Kind.Buf; const Messages = @This(); /// Where its ring's next line goes and how many it holds, held to the ring /// where a dump is read back (walk.zig `.place`); the live messages as far /// as they go. pub const replica = .{ .place = .{ .{ "head", "lastSlot" }, .{ "len", "size" } }, .len = .{.{ "live", "live_len" }} }; /// The message-row log: a fixed ring, never allocated, never grown. See /// `logMessage` and the `Messages` builtin. log: [limits.message_log]LoggedMessage = @splat(.{}), /// Next slot to write. `len` saturates at the ring's size. head: usize = 0, len: usize = 0, /// The messages that live, oldest first: what the notice row, the marks /// and the ghosts at a cause's line are drawn from each frame. live: [max_live]Said = undefined, live_len: u8 = 0, /// How many messages live at once: past it the oldest that is no /// question goes (a burst of distinct ones; a repeat only counts). pub const max_live = 16; pub fn lastSlot(m: *const Messages) usize { return m.log.len - 1; } pub fn size(m: *const Messages) usize { return m.log.len; } /// What a message is, which says how long it lives (SPEC §10.1): an echo /// and a notice until the next message, bright for `MessageLinger`; a /// warning bright twice that, until Esc; an error until Esc or the next /// error; a question until it is answered; progress while it runs, at the /// right end of its tag rather than on the notice row. pub const Kind = enum(u8) { echo, notice, warn, @"error", question, progress, pub fn glyph(k: Kind) []const u8 { return switch (k) { .echo => "\u{2713}", .notice => "\u{b7}", .warn => "!", .@"error" => "\u{2717}", .question => "?", .progress => "\u{22ef}", }; } /// Which wins the notice row and a mark: error, question, warning, /// notice, echo; progress never. pub fn rank(k: Kind) u8 { return switch (k) { .progress => 0, .echo => 1, .notice => 2, .warn => 3, .question => 4, .@"error" => 5, }; } }; /// A place a message names: a file's line and column, and what it says /// there (a compiler's `error: ...`), which the body shows at that line. pub const Place = struct { path: Buf(256) = .{}, line: u32 = 1, col: u32 = 1, text: Buf(128) = .{}, /// Its file's text changed since it was named (`edited`): its line may /// be another's now, so its words are not drawn at it (a mark on the /// wrong line is worse than none) until a run names it again. stale: bool = false, }; /// The questions the session asks in the background, and their answers. pub const Ask = enum(u8) { none, /// A file changed on disk under unsaved text. disk, /// Its answers, as its pane's tag offers them: the key that gives one, /// and its word (an Exec of the word's first word gives it too). pub fn answers(a: Ask) []const Answer { return switch (a) { .none => &.{}, .disk => &.{ .{ .key = 'r', .word = "Reload" }, .{ .key = 'k', .word = "Keep mine" }, .{ .key = 'd', .word = "Diff" } }, }; } }; pub const Answer = struct { key: u8, word: []const u8 }; /// One live message. pub const Said = struct { pub const replica = .{ .len = .{ .{ "places", "places_len" }, .{ "detail", "detail_len" } } }; pub const max_places = 4; pub const max_detail = 4; kind: Kind = .notice, /// Its cause, first, as a word a Look understands: a file's path, a /// pane's `@pN` (and its command), a server's name. src: Buf(96) = .{}, text: Buf(256) = .{}, places: [max_places]Place = undefined, places_len: u8 = 0, /// The lines that explain it, shown under the line it names when asked /// (`open`). detail: [max_detail]Buf(128) = undefined, detail_len: u8 = 0, /// The serial of the pane it is about, 0 for none in particular. pane: u32 = 0, asks: Ask = .none, /// Its detail unrolled, on request only (UX D13): K, SPC e or a Look on /// its words on the caret's line (detailAt), shown under that line until /// the caret leaves it (rollUp); a question's Diff under its place /// whatever the caret, until `d` again. open: bool = false, /// How many times in a row it was said. n: u16 = 1, /// When it was last said, on the core's clock (`Pardes.clock.now_ns`). t: u64 = 0, /// Its words without the clock a host stamped on them (Message.stamp). pub fn words(s: *const Said) []const u8 { return Message.body(s.text.slice()); } /// Whether it has dimmed: an echo or a notice past `linger_ms`, a /// warning past twice that. pub fn faded(s: *const Said, now_ns: u64, linger_ms: u16) bool { const bright: u64 = switch (s.kind) { .echo, .notice => linger_ms, .warn => 2 * @as(u64, linger_ms), else => return false, }; return now_ns -| s.t >= bright * std.time.ns_per_ms; } /// Whether it is about `pane`: said of it, or naming its file (as its /// cause or among its places). pub fn about(s: *const Said, pane: *const Pane) bool { if (s.pane != 0 and s.pane == pane.serial) return true; const f = pane.file orelse return false; if (std.mem.eql(u8, s.src.slice(), f.path)) return true; for (s.places[0..s.places_len]) |*place| if (std.mem.eql(u8, place.path.slice(), f.path)) return true; return false; } }; pub const LoggedMessage = struct { pub const cap = 256; pub const replica = .{ .len = .{.{ "text", "len" }} }; text: [cap]u8 = undefined, len: u16 = 0, /// The serial of the pane that said it, or 0 for none in particular. A /// serial, not a slot: slots are reused, so an old line would name /// whichever pane took the slot since. serial: u32 = 0, /// How many times in a row. Saturating: a key held down against the same /// refusal is one event, not four hundred. repeats: u16 = 0, kind: Kind = .notice, pub fn slice(m: *const LoggedMessage) []const u8 { return m.text[0..m.len]; } }; pub const Message = struct { const libc = std.c; const Tm = extern struct { sec: c_int, min: c_int, hour: c_int, mday: c_int, mon: c_int, year: c_int, wday: c_int, yday: c_int, isdst: c_int, gmtoff: c_long, zone: ?[*:0]const u8, }; extern "c" fn localtime_r(timep: *const libc.time_t, result: *Tm) ?*Tm; /// PARDES_NOTIME set (the tests, a snapshot run): every clock reads /// `--:--:--`. A host's (`stamp`, dev/lsp): no step reads it, the text /// it stamps crossing as a setMessage's. pub fn noTime() bool { const v = libc.getenv("PARDES_NOTIME") orelse return false; return std.mem.span(v).len != 0; } /// `HH:MM:SS` of `seconds` since the epoch in a zone `gmtoff` seconds /// east of UTC: the message row's time of day, and a replica's guess /// of the session's (core/tape.zig). pub fn clockText(seconds: i64, gmtoff: i64) [8]u8 { var text: [8]u8 = "--:--:--".*; if (noTime()) return text; const day: std.time.epoch.DaySeconds = .{ .secs = @intCast(@mod(seconds + gmtoff, 86400)) }; _ = std.fmt.bufPrint(&text, "{d:0>2}:{d:0>2}:{d:0>2}", .{ day.getHoursIntoDay(), day.getMinutesIntoHour(), day.getSecondsIntoMinute() }) catch unreachable; // a u5 and two u6s: two digits each return text; } fn timeOfDay() [8]u8 { var ts: libc.timespec = undefined; _ = libc.clock_gettime(.REALTIME, &ts); var tm: Tm = undefined; if (localtime_r(&ts.sec, &tm) == null) return "--:--:--".*; return clockText(ts.sec, tm.gmtoff); } pub fn body(text: []const u8) []const u8 { if (text.len < 10) return text; if (text[2] != ':' or text[5] != ':' or text[8] != ' ' or text[9] != ' ') return text; for ([_]usize{ 0, 1, 3, 4, 6, 7 }) |i| { if (!std.ascii.isDigit(text[i]) and text[i] != '-') return text; } return text[10..]; } pub fn stamp(buf: []u8, verb: []const u8, subject: []const u8) []const u8 { // The time of day of the host that stamps it, in its zone: only a // host stamps a message (a file reloaded, a save, a language // server's status), between steps, and the message it then hands // the core (`setMessage`, an input) is what the tape carries. const clock = timeOfDay(); const head = std.fmt.bufPrint(buf, "{s} {s} ", .{ &clock, verb }) catch return buf[0..0]; const room = buf.len - head.len; const tail = if (subject.len <= room) subject else subject[subject.len - room ..]; @memcpy(buf[head.len..][0..tail.len], tail); return buf[0 .. head.len + tail.len]; } }; /// A status updates its line in place (a progress count does not pile up), /// and is not logged; a message is an event. pub const setStatus = pardes.tape.taped(setStatusInner); fn setStatusInner(p: *Pardes, id: Pane.Id, text: []const u8) void { // No text: the pane's progress is over, and goes. if (text.len == 0) { const serial: u32 = if (id.index() < MAX_PANES) if (p.panes[id.index()]) |pane| pane.serial else 0 else 0; const m = &p.messages; for (m.live[0..m.live_len], 0..) |*s, i| if (s.kind == .progress and s.pane == serial) { m.remove(i); p.needs_frame = true; break; }; return; } _ = say(p, .progress, id.index(), text); } pub const setMessage = pardes.tape.taped(setMessageInner); fn setMessageInner(p: *Pardes, id: Pane.Id, text: []const u8) void { _ = say(p, .notice, id.index(), text); } /// Say `text`, a message of `kind` about pane `id` (MAX_PANES and up: /// none in particular), its cause first: logged (progress is not), and /// live (`keep`); the message, for the places it names. pub fn say(p: *Pardes, kind: Kind, id: usize, text: []const u8) *Said { if (kind != .progress) logMessage(p, id, kind, text); const pane: ?*Pane = if (id < MAX_PANES and !p.fs.session_write) p.panes[id] else null; var src: Buf(96) = .{}; if (pane) |cause| causeWord(cause, &src); return keep(p, kind, if (pane) |cause| cause.serial else 0, src.slice(), text); } /// A pane as a message names its cause: a file's path (a kind's too), else /// `@pN` and the command it runs. fn causeWord(pane: *const Pane, out: *Buf(96)) void { const path = if (pane.file) |f| f.path else if (pane.addon) |k| k.path else ""; if (path.len > 0) { if (path.len <= out.bytes.len) return out.set(path); // Longer than the room: its end, `…` first, so its name is whole // (UX D2: a path is cut from the left). var from = path.len - (out.bytes.len - "\u{2026}".len); while (from < path.len and path[from] & 0xC0 == 0x80) from += 1; _ = out.print("\u{2026}{s}", .{path[from..]}); return; } const line = pane.command orelse { _ = out.print(config.pane_addr ++ "{d}", .{pane.serial}); return; }; const first = line[0 .. std.mem.indexOfAny(u8, line, "\r\n") orelse line.len]; var cut = @min(first.len, 64); while (cut < first.len and cut > 0 and first[cut] & 0xC0 == 0x80) cut -= 1; // A command cut shows it (UX F2: every cut ends in `…`). _ = out.print(config.pane_addr ++ "{d} {s}{s}", .{ pane.serial, first[0..cut], if (cut < first.len) "\u{2026}" else "" }); } /// Make a message live, and return it (for its places and its detail): /// a new message retires every echo and notice, a new error the error /// before it; the same message again right after itself is counted. The /// list is in the order things were said. pub fn keep(p: *Pardes, kind: Kind, serial: u32, src: []const u8, text: []const u8) *Said { const m = &p.messages; p.needs_frame = true; // One row of printable text: a language server's multi-line report // reads as one line, and the cut never leaves half a glyph behind. var row: [256]u8 = undefined; var n: usize = @min(text.len, row.len); if (n < text.len) { while (n > 0 and text[n] & 0xC0 == 0x80) n -= 1; } for (text[0..n], row[0..n]) |c, *cell| cell.* = if (c < 0x20 or c == 0x7f) ' ' else c; const line = row[0..n]; const now = p.clock.now_ns; // Progress from the same cause is updated, and is the newest said. if (kind == .progress) for (m.live[0..m.live_len], 0..) |*s, i| { if (s.kind != .progress or s.pane != serial or !std.mem.eql(u8, s.src.slice(), src)) continue; const kept = s.*; m.remove(i); const last = &m.live[m.live_len]; m.live_len += 1; last.* = kept; last.text.set(line); last.t = now; return last; }; if (m.live_len > 0) { // The NEWEST wording wins, so it carries the latest clock. const last = &m.live[m.live_len - 1]; if (last.kind == kind and last.pane == serial and std.mem.eql(u8, last.src.slice(), src) and std.mem.eql(u8, Message.body(last.text.slice()), Message.body(line))) { last.n +|= 1; last.t = now; last.text.set(line); return last; } } if (kind != .progress) { var i: usize = 0; while (i < m.live_len) { const old = m.live[i].kind; if (old == .echo or old == .notice or (kind == .@"error" and old == .@"error")) m.remove(i) else i += 1; } } if (m.live_len == max_live) { var oldest: usize = 0; while (oldest + 1 < m.live_len and m.live[oldest].kind == .question) oldest += 1; m.remove(oldest); } const s = &m.live[m.live_len]; m.live_len += 1; s.* = .{ .kind = kind, .pane = serial, .t = now }; s.src.set(src); s.text.set(line); return s; } pub fn remove(m: *Messages, i: usize) void { std.mem.copyForwards(Said, m.live[i .. m.live_len - 1], m.live[i + 1 .. m.live_len]); m.live_len -= 1; } /// Retire every live message of `kinds` (Esc: the warnings and errors); /// how many went. pub fn retire(m: *Messages, kinds: []const Kind) usize { var gone: usize = 0; var i: usize = 0; while (i < m.live_len) { if (std.mem.indexOfScalar(Kind, kinds, m.live[i].kind) != null) { m.remove(i); gone += 1; } else i += 1; } return gone; } /// The message the notice row leads with: the highest-ranked, the newest /// within a rank; progress never. pub fn headline(m: *const Messages) ?*const Said { var best: ?*const Said = null; for (m.live[0..m.live_len]) |*s| { if (s.kind == .progress) continue; if (best == null or s.kind.rank() >= best.?.kind.rank()) best = s; } return best; } /// The kind a pane's mark shows, one cell after its box (SPEC §10.2): the /// most important live error, question, warning or progress about it (an /// echo or a notice marks nothing); null for none. pub fn markOf(m: *const Messages, pane: *const Pane) ?Kind { var best: ?Kind = null; for (m.live[0..m.live_len]) |*s| { if (s.kind == .echo or s.kind == .notice or !s.about(pane)) continue; if (best == null or s.kind.rank() > best.?.rank()) best = s.kind; } return best; } /// A message's ink on a ground of the chrome (R9), its glyph's, its /// mark's and its words': an error's, a warning's and a question's their /// severity's held there (a question info's), an echo, a notice and /// progress the ground's dim ink. `inks` a ground's (colors.Chrome.Inks) /// or a grip fill's (colors.Chrome.Marks). pub fn inkOn(inks: anytype, kind: Kind) [3]u8 { return switch (kind) { .@"error" => inks.severity[0], .warn => inks.severity[1], .question => inks.severity[2], .echo, .notice, .progress => inks.dim, }; } /// The places a compiler's report names put on `s`: each /// `path:line:col: error|warning|note: words` row (a relative path is /// `dir`'s), its words there, each place once, and the rows after the /// first error, up to the next place, its detail. How many it found; none /// without an error. pub fn readPlaces(s: *Said, dir: []const u8, rows: []const []const u8) usize { var errors: usize = 0; var detailing = false; for (rows) |raw| { const row = std.mem.trimEnd(u8, raw, " \t\r\n"); const found = placeOf(row) orelse { if (detailing and row.len > 0 and s.detail_len < Said.max_detail) { s.detail[s.detail_len] = .{}; s.detail[s.detail_len].set(row); s.detail_len += 1; } continue; }; detailing = false; const is_error = std.mem.startsWith(u8, found.text, "error"); if (is_error) { detailing = errors == 0; errors += 1; } if (s.places_len == Said.max_places) continue; const place = &s.places[s.places_len]; place.* = .{ .line = found.line, .col = found.col }; if (std.Io.Dir.path.isAbsolute(found.path)) place.path.set(found.path) else _ = place.path.print("{s}/{s}", .{ std.mem.trimEnd(u8, dir, "/"), found.path }); // A place named again (a note at its error's) is not a second one. const named = for (s.places[0..s.places_len]) |*was| { if (was.line == place.line and was.col == place.col and std.mem.eql(u8, was.path.slice(), place.path.slice())) break true; } else false; if (named) continue; place.text.set(if (std.mem.startsWith(u8, found.text, "error: ")) found.text["error: ".len..] else found.text); s.places_len += 1; } if (errors == 0) s.places_len = 0; return s.places_len; } /// A compiler's place row: `path:line:col: error|warning|note...`. fn placeOf(row: []const u8) ?struct { path: []const u8, line: u32, col: u32, text: []const u8 } { const a = std.mem.indexOfScalar(u8, row, ':') orelse return null; const path = row[0..a]; if (path.len == 0 or std.mem.indexOfAny(u8, path, " \t") != null) return null; var rest = row[a + 1 ..]; const b = std.mem.indexOfScalar(u8, rest, ':') orelse return null; const line = std.fmt.parseInt(u32, rest[0..b], 10) catch return null; rest = rest[b + 1 ..]; const c = std.mem.indexOfScalar(u8, rest, ':') orelse return null; const col = std.fmt.parseInt(u32, rest[0..c], 10) catch return null; const text = std.mem.trim(u8, rest[c + 1 ..], " "); for ([_][]const u8{ "error", "warning", "note" }) |word| { if (std.mem.startsWith(u8, text, word)) return .{ .path = path, .line = line, .col = col, .text = text }; } return null; } /// An edit of the text of the file at `path` (File.edit): the places that /// name it no longer know their lines (`Place.stale`); the box's mark and /// the notice row keep them until the next run. Bounded by the live /// messages' places. pub fn edited(m: *Messages, path: []const u8) void { for (m.live[0..m.live_len]) |*s| for (s.places[0..s.places_len]) |*place| { if (std.mem.eql(u8, place.path.slice(), path)) place.stale = true; }; } /// The question waiting on `pane`, an index into `live`; null for none. pub fn waiting(m: *const Messages, pane: *const Pane) ?usize { for (m.live[0..m.live_len], 0..) |*s, i| if (s.kind == .question and s.pane == pane.serial) return i; return null; } /// The answers of the question waiting on `pane`: what a `:` lists first /// (pick-ui SPEC §10.4); none without one. pub fn waitingAnswers(m: *const Messages, pane: *const Pane) []const Answer { const i = m.waiting(pane) orelse return &.{}; return m.live[i].asks.answers(); } /// Answer live question `i` with `key`: `r` reads the file again over its /// unsaved text, `k` keeps the text and lets the disk's be, `d` shows (or /// hides again) the disk's lines where they differ, as ghosts in its /// body. False for a key that is none of its answers. pub fn answer(p: *Pardes, i: usize, key: u8) bool { const m = &p.messages; const s = &m.live[i]; const a = for (s.asks.answers()) |a| { if (a.key == key) break a; } else return false; p.needs_frame = true; const id = p.paneBySerial(s.pane) orelse { m.remove(i); return true; }; var said: Buf(256) = .{}; if (key == 'd') { if (s.open) { s.open = false; return true; } diskDiff(p, s, id); return true; } logMessage(p, id, .echo, said.print("{s} {s} \u{b7} answered {s}", .{ s.src.slice(), s.words(), a.word })); m.remove(i); if (key == 'r') { const pane = p.panes[id].?; // The answer is the consent Get would ask for. if (pane.file) |f| pane.discard_warned = .{ .revision = f.revision, .by = .get }; pardes.exec.runBuiltin(p, .Get, id, "", null); } else _ = say(p, .echo, id, "kept yours; the disk's is not read"); return true; } /// SPC e (the Message word, SPEC §10.4): on a line a message names, its /// detail not unrolled, that detail (UX D13); else on the message the /// notice row leads with: an error that names places lands them as a list in pane /// `id`'s walk (Pick's `list`, its word `✗ ` in the trail), the /// first landed on, n and N walking the rest (a +Search under the pane /// where jumps do not walk, or for a 9P script: Pick.asked), the error /// kept: its mark and its words at the lines it names are where the walk /// lands, until Esc, the next error or its pane's next run; a question /// takes the keyboard in its pane's tag; anything else, or nothing, opens /// the history. pub fn act(p: *Pardes, id: usize) void { const m = &p.messages; // On a line a message names, its detail not unrolled: unrolled (UX // D13), the message kept; asked again, the walk below. if (id < MAX_PANES) if (p.panes[id]) |pane| if (pane.focus == .body) if (detailAt(p, pane, pane.body.cur_row)) |s| if (!s.open) { s.open = true; p.needs_frame = true; return; }; const lead = m.headline() orelse return history(p, id); if (lead.kind == .question) { p.view().answering = lead.pane; p.needs_frame = true; return; } if (lead.kind != .@"error" or lead.places_len == 0 or id >= MAX_PANES) return history(p, id); const pane = p.panes[id] orelse return; const picked = pardes.Pick.asked(p); var rows: std.Io.Writer.Allocating = .init(p.gpa); errdefer rows.deinit(); // A row as its list reads its column: a picker's as the compiler wrote // it, `path:line:col: words` (Prompt's rows too: a column with a blank // after it is the line's text to look.parsePathLine), a +Search's as // its locations are, `path:line:col words` (locations.parse). for (lead.places[0..lead.places_len]) |*place| rows.writer.print("{s}:{d}:{d}{s} {s}\n", .{ place.path.slice(), place.line, place.col, if (picked) ":" else "", place.text.slice() }) catch |err| return reportError(p, .at(id), "Message", err); const cause = lead.src; const content = rows.toOwnedSlice() catch |err| return reportError(p, .at(id), "Message", err); if (picked) { defer p.gpa.free(content); // The cause cut at a character's start to the word's room. const src = cause.slice(); var cut = @min(src.len, 24 - "\u{2717} ".len); while (cut > 0 and cut < src.len and src[cut] & 0xC0 == 0x80) cut -= 1; var word: Buf(24) = .{}; pardes.Pick.open(p, id, .list, word.print("\u{2717} {s}", .{src[0..cut]}), "", content); return pardes.Pick.landHere(p); } pardes.panes.Output.fillResults(p, id, pardes.panes.paneDir(pane), .search, cause.slice(), content, null) catch |err| return reportError(p, .at(id), "Message", err); _ = @import("look.zig").searchStep(p, id, 1); } /// The history (SPC h m, the Messages word; SPC e with nothing to act on): /// where jumps walk a picker over it in pane `id`'s tag (Pick's /// `messages`), the newest first, Enter Looking a row, C-q keeping it as /// a +Messages; else (or for a 9P script, Pick.asked) the +Messages. pub fn history(p: *Pardes, id: usize) void { if (pardes.Pick.asked(p) and id < MAX_PANES and p.panes[id] != null) return pardes.Pick.open(p, id, .messages, "", "", ""); pardes.panes.Output.openMessages(p, id) catch |err| reportError(p, .at(id), "messages", err); } /// An Exec of an answer's word in the tag of a pane a question waits on /// (B2 on `Reload`): that answer. False for any other word. pub fn answerWord(p: *Pardes, id: usize, word: []const u8) bool { if (id >= MAX_PANES) return false; const pane = p.panes[id] orelse return false; const i = p.messages.waiting(pane) orelse return false; const typed = std.mem.trim(u8, word, " \t\r\n"); for (p.messages.live[i].asks.answers()) |a| { const first = a.word[0 .. std.mem.indexOfScalar(u8, a.word, ' ') orelse a.word.len]; if (std.mem.eql(u8, typed, first)) return answer(p, i, a.key); } return false; } /// A question's Diff: the disk's text read (the host's read, taped) and /// set against the buffer's, the lines they share at either end left out; /// where they part, its place, and up to `Said.max_detail` of the lines /// there, the disk's `+` and then the buffer's `-`, its detail, shown. fn diskDiff(p: *Pardes, s: *Said, id: usize) void { const pane = p.panes[id].?; const f = if (pane.file) |*file| file else return; const disk = @import("fs.zig").read(p, f.path) catch |err| return pardes.Messages.reportError(p, .at(id), "Diff", err); defer p.gpa.free(disk); const mine = pardes.panes.File.fileText(f, p.scratch.allocator()) catch return; var a = std.mem.splitScalar(u8, mine, '\n'); var b = std.mem.splitScalar(u8, disk, '\n'); var line: u32 = 1; var ours: []const u8 = ""; var theirs: []const u8 = ""; while (true) : (line += 1) { const x = a.next(); const y = b.next(); if (x == null and y == null) return; if (x != null and y != null and std.mem.eql(u8, x.?, y.?)) continue; ours = if (x) |l| mine[@intFromPtr(l.ptr) - @intFromPtr(mine.ptr) ..] else ""; theirs = if (y) |l| disk[@intFromPtr(l.ptr) - @intFromPtr(disk.ptr) ..] else ""; break; } // The lines both end with, left out. var ours_end = ours.len; var theirs_end = theirs.len; while (ours_end > 0 and theirs_end > 0) { const ol = std.mem.lastIndexOfScalar(u8, ours[0 .. ours_end - 1], '\n'); const tl = std.mem.lastIndexOfScalar(u8, theirs[0 .. theirs_end - 1], '\n'); const o_line = ours[if (ol) |nl| nl + 1 else 0..ours_end]; const t_line = theirs[if (tl) |nl| nl + 1 else 0..theirs_end]; if (!std.mem.eql(u8, o_line, t_line)) break; ours_end = if (ol) |nl| nl + 1 else 0; theirs_end = if (tl) |nl| nl + 1 else 0; } s.places[0] = .{ .line = line, .col = 1 }; s.places[0].path.set(f.path); s.places[0].text.set("the disk's differs here"); s.places_len = 1; s.detail_len = 0; // The disk's first: it is what the answer shows. for ([_]struct { []const u8, []const u8 }{ .{ "+", theirs[0..theirs_end] }, .{ "-", ours[0..ours_end] } }) |side| { var rows = std.mem.splitScalar(u8, std.mem.trimEnd(u8, side[1], "\n"), '\n'); while (rows.next()) |row| { if (side[1].len == 0 or s.detail_len == Said.max_detail) break; s.detail[s.detail_len] = .{}; _ = s.detail[s.detail_len].print("{s}{s}", .{ side[0], row }); s.detail_len += 1; } } s.open = true; } /// The words the newest live message said of `pane` has, "" for none: /// what its band shows, and what a write that failed on it answers. pub fn saidBy(m: *const Messages, pane: *const Pane) []const u8 { var i = m.live_len; while (i > 0) { i -= 1; if (m.live[i].pane == pane.serial) return m.live[i].text.slice(); } return ""; } /// When the next live message dims, on the core's clock; null for none. pub fn dimDue(p: *const Pardes) ?u64 { const m = &p.messages; if (p.settings.message_linger_ms == 0) return null; var soonest: ?u64 = null; for (m.live[0..m.live_len]) |*s| { const bright: u64 = switch (s.kind) { .echo, .notice => p.settings.message_linger_ms, .warn => 2 * @as(u64, p.settings.message_linger_ms), else => continue, }; const due = s.t + bright * std.time.ns_per_ms; if (due <= p.clock.stepped_ns) continue; soonest = if (soonest) |first| @min(first, due) else due; } return soonest; } /// The notice row's line (SPEC §10.3), `width` columns: on the left the /// message the row leads with (`headline`), its glyph, its cause, its /// words, `×n` and the places it names; on the right how many more live, /// the questions waiting, or the way to the history. With nothing live the /// left says where the focused pane's caret is. Built each frame from the /// state, in `out`. pub const Row = struct { /// The left part's end and the right part's start, in bytes of `text`. left: usize = 0, right: usize = 0, text: []const u8 = "", /// The message the left says, when it says one. lead: ?*const Said = null, /// The left in the dim ink (a picker's sentence, UX D7), but for the /// bytes `word` (an address, in the text's). quiet_left: bool = false, word: [2]usize = .{ 0, 0 }, }; /// Room for the notice row's line: the widest window's at the tagline's /// pitch (Layer.capacity) is cut to it. pub const notice_row_cap = 1024; pub fn noticeRow(p: *Pardes, width: usize, out: *[notice_row_cap]u8) Row { const m = &p.messages; const tab = p.settings.tab; // A rolled level's last leaf, while the level shows: what it does, the // whole row (SPEC §3.7's first mockup). if (pardes.TagState.lastUsed(p, p.view(), out)) |used| { var end = @min(used.len, panes.File.rawAtDisplay(tab, used, width)); while (end > 0 and panes.File.displayWidth(tab, used[0..end]) > width) end -= 1; while (end > 0 and end < used.len and used[end] & 0xC0 == 0x80) end -= 1; return .{ .left = end, .right = end, .text = used[0..end] }; } var w: std.Io.Writer = .fixed(out); var live: usize = 0; var questions: usize = 0; for (m.live[0..m.live_len]) |*s| { if (s.kind == .progress) continue; live += 1; if (s.kind == .question) questions += 1; } // While a picker previews, its sentence (UX D7), before any message; // while a band shows with no room for its doc, the doc's first line // (UX D5's give-way). const said = pardes.Pick.sentence(p, &w); var doc_buf: [notice_row_cap]u8 = undefined; const doc = if (said == null) pardes.Band.docLeft(p, &doc_buf) else null; const lead = if (said == null and doc == null) m.headline() else null; // A message's cause, in bytes of `out`: the first item to give way. var cause_at: [2]usize = .{ 0, 0 }; if (said != null) {} else if (doc) |line| { w.writeAll(line) catch {}; } else if (lead) |s| { w.print("{s} ", .{s.kind.glyph()}) catch {}; // Its cause first, unless its words name it already (a cut one by // what it kept). const words = s.words(); const cause = s.src.slice(); const named = if (std.mem.startsWith(u8, cause, "\u{2026}")) cause["\u{2026}".len..] else cause; cause_at = .{ w.end, w.end }; if (cause.len > 0 and std.mem.indexOf(u8, words, named) == null) { w.writeAll(cause) catch {}; cause_at[1] = w.end; w.writeByte(' ') catch {}; } w.writeAll(words) catch {}; if (s.n > 1) w.print(" \u{d7}{d}", .{s.n}) catch {}; for (s.places[0..s.places_len], 0..) |*place, i| w.print("{s} {s}:{d}:{d}", .{ if (i > 0) " \u{b7}" else "", place.path.slice(), place.line, place.col }) catch {}; } else if (p.panes[p.view().active]) |pane| { if (pane.file) |f| w.print("{s}:{d}", .{ f.path, pane.body.cur_row + 1 }) catch {} else w.writeAll(pane.cwdSlice()) catch {}; } const left_end = w.end; var right: [64]u8 = undefined; var r: std.Io.Writer = .fixed(&right); if (live > 1) r.print("+{d} \u{b7} ", .{live - 1}) catch {}; if (questions > 0) r.print("{d} question{s} \u{b7} SPC e", .{ questions, if (questions == 1) "" else "s" }) catch {} else if (lead != null and lead.?.kind == .@"error" and lead.?.places_len > 0) r.writeAll("SPC e walk") catch {} else if (m.len > 0) r.print("{d} message{s} \u{b7} SPC h m", .{ m.len, if (m.len == 1) "" else "s" }) catch {}; // The keys of a root whose level waits for its delay, at once (UX D12: // vim's showcmd; the tag stays at rest until the level shows). var keys: [64]u8 = undefined; if (pardes.TagState.pending(p, p.view(), &keys)) |typed| r.print("{s}{s}", .{ if (r.end > 0) " " else "", typed }) catch {}; const tail = r.buffered(); // The left cut with `…` to make room for the right, two blanks between // them at least (UX D2): the pane's path from the left, so its name // and line stay (`…core/Store.zig:12`), anything else from the right. const tail_w = panes.File.displayWidth(tab, tail); const room = width -| (if (tail_w > 0) tail_w + 2 else 0); var cut = left_end; if (panes.File.displayWidth(tab, out[0..cut]) > room) { if (said == null and doc == null and lead == null) { var from: usize = 0; while (from < left_end and panes.File.displayWidth(tab, out[from..left_end]) > room -| 1) { from += 1; while (from < left_end and out[from] & 0xC0 == 0x80) from += 1; } var kept: [notice_row_cap]u8 = undefined; const name = kept[0 .. left_end - from]; @memcpy(name, out[from..left_end]); w.end = 0; w.writeAll(if (room > 0) "…" else "") catch {}; w.writeAll(name) catch {}; cut = w.end; } else { // A message (UX D2, F2): its cause gives way first (a path down // to its name, `…Query.zig`; a command down to its pane, // `@p2…`), then each path its words and places name, down to // its name; its words are cut last, from the right below. if (lead != null) { var over = panes.File.displayWidth(tab, out[0..left_end]) - room; var kept: [notice_row_cap]u8 = undefined; var k: std.Io.Writer = .fixed(&kept); k.writeAll(out[0..cause_at[0]]) catch {}; const cause = out[cause_at[0]..cause_at[1]]; over -|= giveWay(tab, &k, cause, over, !std.mem.startsWith(u8, cause, config.pane_addr) and std.mem.indexOfScalar(u8, cause, '/') != null); var items = std.mem.splitScalar(u8, out[cause_at[1]..left_end], ' '); var first = true; while (items.next()) |item| { if (!first) k.writeByte(' ') catch {}; first = false; if (std.mem.indexOfScalar(u8, item, '/') != null) over -|= giveWay(tab, &k, item, over, true) else k.writeAll(item) catch {}; } cut = k.end; @memcpy(out[0..cut], k.buffered()); } if (panes.File.displayWidth(tab, out[0..cut]) > room) { const end = cut; cut = panes.File.rawAtDisplay(tab, out[0..end], room -| 1); while (cut > 0 and panes.File.displayWidth(tab, out[0..cut]) > room -| 1) { cut -= 1; while (cut > 0 and out[cut] & 0xC0 == 0x80) cut -= 1; } w.end = cut; w.writeAll(if (room > 0) "…" else "") catch {}; cut = w.end; } } } w.end = cut; const gap = width -| (panes.File.displayWidth(tab, out[0..cut]) + tail_w); for (0..gap) |_| w.writeByte(' ') catch {}; const right_at = w.end; w.writeAll(tail) catch {}; return .{ .left = cut, .right = right_at, .text = w.buffered(), .lead = lead, .quiet_left = said != null, .word = said orelse .{ 0, 0 } }; } /// `item` written to `w` with `over` cells of it given back where it has /// them, `…` in their place (UX D2): a path from its left, never into its /// name (what follows its last `/`); anything else from its right, never /// into its first word. The cells it gave. fn giveWay(tab: u16, w: *std.Io.Writer, item: []const u8, over: usize, path: bool) usize { var edge: usize = if (path) 0 else item.len; var cells: usize = 0; if (path) { const name = if (std.mem.lastIndexOfScalar(u8, item, '/')) |slash| slash + 1 else 0; while (edge < name and cells < over + 1) { const next = @min(item.len, edge + (std.unicode.utf8ByteSequenceLength(item[edge]) catch 1)); cells += panes.File.displayWidth(tab, item[edge..next]); edge = next; } } else { const first = std.mem.indexOfScalar(u8, item, ' ') orelse item.len; while (edge > first and cells < over + 1) { var prev = edge - 1; while (prev > first and item[prev] & 0xC0 == 0x80) prev -= 1; cells += panes.File.displayWidth(tab, item[prev..edge]); edge = prev; } } // The `…` takes a cell of what was given. if (cells < 2) { w.writeAll(item) catch {}; return 0; } if (path) w.print("\u{2026}{s}", .{item[edge..]}) catch {} else w.print("{s}\u{2026}", .{item[0..edge]}) catch {}; return cells - 1; } /// What notice band `i` says. The grid pass and the band layers both /// read it here, so a terminal and a pixel shell show the same line. pub fn noticeText(pane: *const Pane, i: usize) []const u8 { return switch (pane.notices.kinds[i]) { .prompt => pane.promptText() orelse "", }; } fn logMessage(p: *Pardes, id: usize, kind: Kind, text: []const u8) void { if (text.len == 0) return; const serial: u32 = if (p.fs.session_write) 0 else if (id < MAX_PANES) if (p.panes[id]) |pane| pane.serial else 0 else 0; const kept = text[0..@min(text.len, LoggedMessage.cap)]; // /log hears every one (a failure of a ctl write as its err record). if (!p.fs.unlogged) ctlfs.events.noteMessage(p, serial, text); if (p.messages.len > 0) { const last = &p.messages.log[(p.messages.head + limits.message_log - 1) % limits.message_log]; if (last.serial == serial and std.mem.eql(u8, Message.body(last.slice()), Message.body(kept))) { // The NEWEST wording wins, so the row carries the latest clock // rather than the moment the run started. last.len = @intCast(kept.len); @memcpy(last.text[0..last.len], kept); last.repeats +|= 1; return; } } const slot = &p.messages.log[p.messages.head]; slot.len = @intCast(kept.len); @memcpy(slot.text[0..slot.len], kept); slot.serial = serial; slot.repeats = 1; slot.kind = kind; p.messages.head = (p.messages.head + 1) % limits.message_log; p.messages.len = @min(p.messages.len + 1, limits.message_log); } /// The log oldest-first, which is reading order. pub fn at(m: *const Messages, i: usize) ?*const LoggedMessage { if (i >= m.len) return null; const first = (m.head + limits.message_log - m.len) % limits.message_log; return &m.log[(first + i) % limits.message_log]; } /// What a route that would open a pane says when every slot is taken. /// "no space": 9ns's word for ENOSPC (it has none for ENFILE). pub const no_pane_slots = "no space for a pane: {d} max"; /// ...and when the column it would go in has no rows for one. pub const no_pane_room = "no space for a pane in that column: each keeps its tag and {d} rows"; /// `: `: FileNotFound reads "file not found". /// Why a peer could not be reached, in words, for an error of a 9P dial /// (runtime/9p_io.zig, Client); null for any other error. pub fn dialReason(err: anyerror) ?[]const u8 { return switch (err) { error.Dial => "no answer", error.Timeout => "timed out", error.Hangup => "hung up", error.Botch => "protocol botch", else => null, }; } pub const reportError = pardes.tape.taped(reportErrorInner); fn reportErrorInner(p: *Pardes, id: Pane.Id, operation: []const u8, err: anyerror) void { // Room for an operation naming the longest path and the reason after // it: a shorter one cut the reason off (`Save /long…`), and the reason // is what a failure is for. Where it must be shorter, the path gives. var buf: [@max(256, limits.host_path_cap + 128)]u8 = undefined; var w = std.Io.Writer.fixed(&buf); w.print("{s}: ", .{operation}) catch {}; // A peer out of reach says so, not the error's name (`dial`). if (dialReason(err)) |why| { w.print("dial failed: {s}", .{why}) catch {}; return reportFailure(p, id.index(), w.buffered()); } // Every route that opens a pane says the cap the same way. if (err == error.NoPaneSlots or err == error.NoPaneRoom) { if (err == error.NoPaneSlots) w.print(no_pane_slots, .{pardes.MAX_PANES}) catch {} else w.print(no_pane_room, .{pardes.layout.min_body_rows}) catch {}; // A 9P look or exec that would open the pane fails with it too. p.fs.no_pane_slot = true; @memcpy(p.fs.ename[0..w.buffered().len], w.buffered()); p.fs.no_pane_slot_len = @intCast(w.buffered().len); return reportFailure(p, id.index(), w.buffered()); } var words: [128]u8 = undefined; w.writeAll(errorWords(err, &words)) catch {}; reportFailure(p, id.index(), w.buffered()); } /// An error in a person's words, never its Zig name: the few that read /// badly spaced out said plainly, the rest spaced and lower case /// (`FileNotFound`, "file not found"). pub fn errorWords(err: anyerror, buf: []u8) []const u8 { return switch (err) { error.FileTooLarge => "too large", error.NoTerminal => pardes.Term.none, error.NotAFile => "not a regular file", // In the words a mount turns into EISDIR and EACCES (cloud9.fs.enameErrno). error.IsDirectory => "is a directory", error.PermissionDenied, error.AccessDenied => "permission denied", error.ReadFailed => "could not be read", error.ParseZon => "not valid ZON", error.ThemeFileTooLarge => "too large: a theme file is at most 1 MiB", error.InvalidThemeName => "its name is empty or over 255 bytes", else => { var w = std.Io.Writer.fixed(buf); for (@errorName(err), 0..) |c, i| { if (std.ascii.isUpper(c) and i > 0) w.writeByte(' ') catch break; w.writeByte(std.ascii.toLower(c)) catch break; } return w.buffered(); }, }; } /// A ZON parse failure in a person's words: the first error the parser /// found and its line, `line 3: expected ','`. pub fn zonWhy(diag: *const std.zon.parse.Diagnostics, buf: []u8) []const u8 { if (diag.errors.len == 0) return "not valid ZON"; const first = diag.errors[0]; var w: std.Io.Writer = .fixed(buf); w.print("line {d}: {s}", .{ first.loc.line + 1, first.msg }) catch {}; // a long message is cut at the room's end return w.buffered(); } /// The longest start of `text` that fits `max` bytes and ends between /// words (or, with no space to cut at, between characters). pub fn clip(text: []const u8, max: usize) []const u8 { if (text.len <= max) return text; if (std.mem.lastIndexOfScalar(u8, text[0 .. max + 1], ' ')) |sp| return text[0..sp]; var n = max; while (n > 0 and text[n] & 0xC0 == 0x80) n -= 1; return text[0..n]; } /// reportError with the words already chosen. pub fn reportFailure(p: *Pardes, id: usize, text: []const u8) void { p.fs.failures +%= 1; var fitted: @TypeOf(p.fs.said) = undefined; const said = pardes.ctlfs.fitErr(text, &fitted); @memcpy(p.fs.said[0..said.len], said); p.fs.said_len = @intCast(said.len); p.fs.said_at = p.fs.failures; // A builtin a ctl write runs: its first error is also the write's, its // path shortened in the middle if it must be, never its reason. const failing_write = p.fs.no_prompt or p.fs.capturing or p.fs.write_waits; if (failing_write and p.fs.failure_len == 0) { var room: @TypeOf(p.fs.failure) = undefined; const kept = pardes.ctlfs.fitErr(text, &room); @memcpy(p.fs.failure[0..kept.len], kept); p.fs.failure_len = @intCast(kept.len); } // The write fails with it, and its err record says it: no msg for it, // so the same failure again is the same record again, counted // (events.pushCounting). if (failing_write) { p.fs.unlogged = true; defer p.fs.unlogged = false; _ = say(p, .@"error", id, text); return; } _ = say(p, .@"error", id, text); } /// The one place that decides which transient lines a pane is showing and /// in what order. Everything downstream reads the answer: the body layer /// so it does not paint under them, and the paint pass so it can stack /// them instead of letting the last one win the row. pub fn collectNotices(p: *Pardes, pane: *Pane, r: Rect) void { pane.notices = bands(p, pane, pane.tag_rows, r); // A message's detail under the caret's line, where the body draws it // and a click's row is read (Pane.textRow): the step's, as the bands. const under = if (r.h > pane.tag_rows) detailUnder(p, pane, p.panes[p.view().active] == pane, r.h - pane.tag_rows) else null; pane.ghost_at = if (under) |d| d.row else 0; pane.ghost_rows = if (under) |d| d.rows else 0; // Each band's chip at the right edge, as wide as its own text and a // blank cell either side, the pane's width at most: a click finds it // whether or not a frame has drawn it. An overlay over the body's top // rows, not a row taken from them, it is counted in GRID columns, not // the tagline face it is drawn in: the grid is what a terminal client // draws, and a chip narrower than its text there would clip it. const tx = r.x + config.GUTTER; const tw = r.w -| config.GUTTER; for (0..pane.notices.len) |i| { const chip = panes.File.displayWidth(p.settings.tab, noticeText(pane, i)) + 2; pane.notices.left[i] = if (tw == 0) std.math.maxInt(u16) else tx + tw - @as(u16, @intCast(@min(chip, tw))); } } /// A message's detail unrolled (SPEC §10.2, UX D13: on request only), as a /// body of `body_h` rows shows it: the row of its line's last row, how many /// of the detail's lines fit under it, the message. The line is the /// caret's, where it was asked (the caret leaving it rolls it up), or a /// question's place; its message the first naming it, as the words after /// it are (firstAt). The caret passing a line never unrolls one. Only in /// the pane with the keyboard, in its body. Bounded by the live messages' /// places and the rows shown. pub fn detailUnder(p: *const Pardes, pane: *Pane, active: bool, body_h: u16) ?struct { row: u16, rows: u16, said: *const Said } { if (!active or pane.focus != .body or p.messages.live_len == 0) return null; const f = pane.file orelse return null; const m = &p.messages; const caret: u32 = @intCast(@max(0, pane.body.cur_row)); const said, const line = found: { if (m.firstAt(f.path, caret + 1)) |i| if (m.live[i].open) break :found .{ &m.live[i], @as(i32, @intCast(caret)) }; for (m.live[0..m.live_len], 0..) |*s, i| if (s.open and s.kind == .question and s.places_len > 0 and std.mem.eql(u8, s.places[0].path.slice(), f.path)) if (m.firstAt(f.path, s.places[0].line) == i) break :found .{ s, @as(i32, @intCast(s.places[0].line -| 1)) }; return null; }; if (said.detail_len == 0) return null; var row: u16 = 0; while (row < body_h) : (row += 1) { if (pane.wrapAt(p.settings.tab, row).line != line) continue; if (row + 1 < body_h and pane.wrapAt(p.settings.tab, row + 1).line == line) continue; const k: u16 = @intCast(@min(said.detail_len, body_h - row - 1)); return if (k == 0) null else .{ .row = row, .rows = k, .said = said }; } return null; } /// The first live message naming line `line` (1-based) of `path`, its /// place not stale: the one whose words are drawn after that line /// (body_layer messageGhosts). fn firstAt(m: *const Messages, path: []const u8, line: u32) ?usize { for (m.live[0..m.live_len], 0..) |*s, i| for (s.places[0..s.places_len]) |*place| { if (line > 0 and place.line == line and !place.stale and std.mem.eql(u8, place.path.slice(), path)) return i; }; return null; } /// The message whose words line `row` (0-based) of `pane`'s file shows, /// when it has a detail to unroll (UX D13): what K with one selection, SPC /// e and a Look on those words ask for. Not a question's (its Diff is `d`). pub fn detailAt(p: *Pardes, pane: *const Pane, row: i32) ?*Said { const f = pane.file orelse return null; if (row < 0) return null; const s = &p.messages.live[p.messages.firstAt(f.path, @intCast(row + 1)) orelse return null]; if (s.detail_len == 0 or s.kind == .question) return null; return s; } /// The keyboard's pane and its caret's line while a detail is unrolled on /// request; null with none (nothing to roll up: nothing else read). pub const Caret = struct { active: usize, row: i32 }; pub fn unrolledAt(p: *const Pardes) ?Caret { const v = p.view(); for (p.messages.live[0..p.messages.live_len]) |*s| if (s.open and s.kind != .question) { const pane = p.panes[v.active] orelse return .{ .active = v.active, .row = -1 }; return .{ .active = v.active, .row = pane.body.cur_row }; }; return null; } /// After a key or a click (Core.update): the caret left its line, or the /// keyboard went to another pane, since `was`: every detail unrolled on /// request rolls up (UX D13: the next motion; a motion along the line, or /// a click on the detail, which puts the caret on the line it explains, /// keeps it), a question's Diff stays. pub fn rollUp(p: *Pardes, was: ?Caret) void { const before = was orelse return; const now = unrolledAt(p) orelse return; if (std.meta.eql(before, now)) return; for (p.messages.live[0..p.messages.live_len]) |*s| if (s.kind != .question) { s.open = false; }; } /// The bands a pane shows over `r` below its `tag_rows`: the live view's /// each step, and any view's for its kind's facts (Kind.viewOf), made from /// what a dump keeps (the bands are derived). pub fn bands(p: *const Pardes, pane: *const Pane, tag_rows: u16, r: Rect) Pane.Notices { var n: Pane.Notices = .{}; if (r.w <= config.GUTTER or r.h <= tag_rows) return n; // Del's question shows once its delay is up: answered before that, it // was never there. const del_waiting = pane.prompt == .del_side and pane.question_due_ns > p.clock.now_ns; if (pane.promptText()) |text| if (text.len > 0 and !del_waiting) n.push(.prompt); // A pane only has so many rows to give. When they do not all fit the // LAST ones survive, because the prompt is last and it is the one // carrying the cursor: a prompt you cannot see is a prompt you type // into blind. A two-row pane spends its only body row on one notice, // which is what the single shared row used to do anyway. const room: u8 = @intCast(@min(@as(u16, Pane.Notices.max), r.h - tag_rows)); if (n.len <= room) return n; // Too short for them all: the top bands go. const drop = n.len - room; for (0..room) |k| { n.kinds[k] = n.kinds[k + drop]; n.row[k] = @intCast(k); } n.len = room; return n; } test "errors are said in words, and a ZON failure names its line" { var buf: [128]u8 = undefined; try std.testing.expectEqualStrings("file not found", errorWords(error.FileNotFound, &buf)); try std.testing.expectEqualStrings("too large", errorWords(error.FileTooLarge, &buf)); var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); defer arena.deinit(); var diag: std.zon.parse.Diagnostics = undefined; const T = struct { a: u8 }; try std.testing.expectError(error.ParseZon, std.zon.parse.fromSlice(T, .{ .gpa = std.testing.allocator, .arena = arena.allocator(), .source = ".{\n .a = 1,\n .b = 2 }", .diagnostics = &diag })); try std.testing.expect(std.mem.startsWith(u8, zonWhy(&diag, &buf), "line 3: ")); } test "an error reads as words and a failure is cut between them" { try std.testing.expectEqualStrings("go", clip("go haskell", 4)); try std.testing.expectEqualStrings("go haskell", clip("go haskell", 10)); try std.testing.expectEqualStrings("\u{e9}", clip("\u{e9}\u{e9}", 3)); } test "the message log keeps what the row forgets, and collapses repeats" { const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 100, .rows = 30 }); defer p.deinit(); setMessage(p, .at(0), "14:32:07 saved /x.zig"); setMessage(p, .at(0), "14:32:09 saved /x.zig"); // same event, later clock setMessage(p, .at(0), "save: AccessDenied"); try std.testing.expectEqual(@as(usize, 2), p.messages.len); const first = p.messages.at(0).?; try std.testing.expectEqual(@as(u16, 2), first.repeats); // ...and the NEWEST wording is what survives, so the row carries the last // time it happened rather than the first. try std.testing.expectEqualStrings("14:32:09 saved /x.zig", first.slice()); try std.testing.expectEqualStrings("save: AccessDenied", p.messages.at(1).?.slice()); try std.testing.expect(p.messages.at(2) == null); // The same text from a DIFFERENT pane is a different event: one pane's // failure must not be recorded as another's. p.newScratchBelow(0); const other = p.view().active; setMessage(p, .at(other), "save: AccessDenied"); try std.testing.expectEqual(@as(usize, 3), p.messages.len); try std.testing.expectEqual(p.panes[other].?.serial, p.messages.at(2).?.serial); // Progress is NOT logged: it arrives several times a second for a whole // index and would push everything else out (`setStatus`). setStatus(p, .at(0), "14:32:10 lsp rust-analyzer: Indexing 47%"); try std.testing.expectEqual(@as(usize, 3), p.messages.len); // The ring wraps rather than grows, and still reads oldest-first. for (0..limits.message_log + 5) |i| { var buf: [32]u8 = undefined; setMessage(p, .at(0), std.fmt.bufPrint(&buf, "line {d}", .{i}) catch unreachable); } try std.testing.expectEqual(@as(usize, limits.message_log), p.messages.len); try std.testing.expectEqualStrings("line 5", p.messages.at(0).?.slice()); var last_buf: [32]u8 = undefined; const want_last = std.fmt.bufPrint(&last_buf, "line {d}", .{limits.message_log + 4}) catch unreachable; try std.testing.expectEqualStrings(want_last, p.messages.at(limits.message_log - 1).?.slice()); } test "Msg says a notice by hand, bare or with text, and the next message retires it" { if (pardes.Term.ops == null) return error.SkipZigTest; // the classic boot's three shells const p = try Pardes.init(std.testing.allocator, .{ .shells = 3, .cols = 100, .rows = 30 }); defer p.deinit(); while (p.nextEffect()) |_| {} // the whole tail, spaces and all: the row is a sentence, not a word try std.testing.expect(p.executeBuiltinLine(2, "Msg saved /etc/hosts")); try std.testing.expectEqualStrings("saved /etc/hosts", p.messages.saidBy(p.panes[2].?)); // ...of the pane that ran it, its cause that pane's address try std.testing.expectEqualStrings("", p.messages.saidBy(p.panes[0].?)); var want: [16]u8 = undefined; try std.testing.expectEqualStrings(try std.fmt.bufPrint(&want, "@p{d}", .{p.panes[2].?.serial}), p.messages.headline().?.src.slice()); // Bare, it reports ITSELF through reportError — the `: ` // every failed save and refused Look arrives in: an error. try std.testing.expect(p.executeBuiltinLine(2, "Msg")); try std.testing.expectEqualStrings("Msg: no message", p.messages.saidBy(p.panes[2].?)); try std.testing.expectEqual(Kind.@"error", p.messages.headline().?.kind); // Input takes nothing away; the next message does what the notice // was, and the error stays until Esc. p.update(.{ .key = .{ .cp = 'h' } }); for (0..200) |_| p.update(.tick); try std.testing.expectEqualStrings("Msg: no message", p.messages.saidBy(p.panes[2].?)); try std.testing.expect(p.executeBuiltinLine(2, "Msg next")); try std.testing.expectEqual(@as(u8, 2), p.messages.live_len); try std.testing.expectEqual(Kind.@"error", p.messages.headline().?.kind); // Longer than a message's room is CUT, never refused and never overrun: // this word is the only way to reach that boundary without a 300-byte path. var long: [600]u8 = @splat('x'); var line: [608]u8 = undefined; const cmd = try std.fmt.bufPrint(&line, "Msg {s}", .{&long}); try std.testing.expect(p.executeBuiltinLine(2, cmd)); try std.testing.expectEqual(@as(usize, 256), p.messages.saidBy(p.panes[2].?).len); } test "an echo or a notice retires those before it, an error the error before it, a repeat counts and progress runs in place" { const p = try Pardes.init(std.testing.allocator, .{ .cols = 80, .rows = 24 }); defer p.deinit(); _ = try p.setTestFile("text\n"); const id = p.view().active; const m = &p.messages; m.live_len = 0; _ = say(p, .notice, id, "first"); _ = say(p, .echo, id, "second"); try std.testing.expectEqual(@as(u8, 1), m.live_len); try std.testing.expectEqualStrings("second", m.headline().?.text.slice()); _ = say(p, .@"error", id, "broke"); _ = say(p, .warn, id, "careful"); // The echo went with the error; the warning stands beside it. try std.testing.expectEqual(@as(u8, 2), m.live_len); try std.testing.expectEqual(Kind.@"error", m.headline().?.kind); _ = say(p, .@"error", id, "broke again"); try std.testing.expectEqual(@as(u8, 2), m.live_len); try std.testing.expectEqualStrings("broke again", m.headline().?.text.slice()); // The same again right after itself: one message, counted, its newest // wording (and clock) kept. for (0..9) |_| _ = say(p, .@"error", id, "broke again"); try std.testing.expectEqual(@as(u8, 2), m.live_len); try std.testing.expectEqual(@as(u16, 10), m.headline().?.n); // Progress updates its line in place and retires nothing. _ = say(p, .progress, id, "Changes: jj 1/4"); _ = say(p, .progress, id, "Changes: jj 3/4"); try std.testing.expectEqual(@as(u8, 3), m.live_len); try std.testing.expectEqualStrings("Changes: jj 3/4", m.saidBy(p.panes[id].?)); try std.testing.expectEqual(Kind.@"error", m.headline().?.kind); // Esc in normal mode takes the warnings and errors. p.update(.{ .key = .{ .cp = Key.escape } }); try std.testing.expectEqual(@as(u8, 1), m.live_len); try std.testing.expectEqual(Kind.progress, m.live[0].kind); try std.testing.expect(m.headline() == null); // Past the room, the oldest that is no question goes. m.live_len = 0; for (0..max_live + 3) |i| { var buf: [16]u8 = undefined; _ = say(p, .warn, id, std.fmt.bufPrint(&buf, "w{d}", .{i}) catch unreachable); } try std.testing.expectEqual(@as(u8, max_live), m.live_len); try std.testing.expectEqualStrings("w3", m.live[0].text.slice()); } test "a builtin announces itself on the notice row, an echo, and Verbose silences it" { if (pardes.Term.ops == null) return error.SkipZigTest; // a terminal's tag row const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 80, .rows = 24 }); defer p.deinit(); const pane = p.panes[p.view().active].?; p.sync(); try std.testing.expect(p.settings.verbose); // Wrap, not Collapse: a builtin that folds its own pane away is not // what this is testing. try std.testing.expect(p.executeBuiltinLine(p.view().active, "Wrap")); try std.testing.expectEqualStrings("Wrap", p.messages.saidBy(pane)); try std.testing.expectEqual(Kind.echo, p.messages.headline().?.kind); // A value it does not take is said, an error, and leads the row. const wrapped = p.settings.wrap; try std.testing.expect(p.executeBuiltinLine(p.view().active, "Wrap maybe")); try std.testing.expectEqualStrings("Wrap: takes on, off", p.messages.saidBy(pane)); try std.testing.expectEqual(wrapped, p.settings.wrap); // ...on the window's foot row, a tagline-shaped layer, not on a chip // over the pane's body. var frame = std.heap.ArenaAllocator.init(std.testing.allocator); defer frame.deinit(); const s = try p.render(frame.allocator()); try std.testing.expectEqual(@as(u8, 0), pane.notices.len); const row = for (s.tagLayers()) |*layer| { if (layer.rows != 0 and layer.kind == .notice_row) break layer; } else return error.NoNoticeRow; try std.testing.expectEqual(@as(u16, 1), row.viewport.h); try std.testing.expectEqual(p.view().screen_h - 1, row.viewport.y); var want: [64]u8 = undefined; const said = try std.fmt.bufPrint(&want, "\u{2717} @p{d} Wrap: takes on, off", .{pane.serial}); const grid = s.cells[@as(usize, row.viewport.y) * s.cols ..][0..s.cols]; var text: std.ArrayList(u8) = .empty; defer text.deinit(std.testing.allocator); for (grid) |cell| try text.appendSlice(std.testing.allocator, cell.grapheme()); try std.testing.expect(std.mem.indexOf(u8, text.items, said) != null); // Msg owns the row itself, so it does not announce over its own text. try std.testing.expect(p.executeBuiltinLine(p.view().active, "Msg hello")); try std.testing.expectEqualStrings("hello", p.messages.saidBy(pane)); p.messages.live_len = 0; p.settings.verbose = false; try std.testing.expect(p.executeBuiltinLine(p.view().active, "Wrap")); try std.testing.expectEqual(@as(usize, 0), p.messages.saidBy(pane).len); } test "the notice row leads with the most important live message, its count and places, and says how many more; with none, where the caret is" { const p = try Pardes.init(std.testing.allocator, .{ .cols = 80, .rows = 24 }); defer p.deinit(); const pane = try p.setTestFile("one\ntwo\nthree\n"); const id = p.view().active; p.messages.live_len = 0; p.messages.len = 0; pane.body.cur_row = 1; var buf: [notice_row_cap]u8 = undefined; var row = noticeRow(p, 60, &buf); try std.testing.expectEqualStrings("/test.txt:2", row.text[0..row.left]); try std.testing.expectEqual(@as(usize, 60), panes.File.displayWidth(p.settings.tab, row.text)); // A notice, then an error and a warning: the error leads, newest first // within a rank; the others are counted. _ = say(p, .notice, id, "indexed"); _ = say(p, .warn, id, "careful"); _ = say(p, .@"error", id, "broke"); row = noticeRow(p, 60, &buf); try std.testing.expectEqualStrings("\u{2717} /test.txt broke", row.text[0..row.left]); try std.testing.expect(std.mem.endsWith(u8, row.text, "+1 \u{b7} 3 messages \u{b7} SPC h m")); // A burst of the same: one message, counted; the row keeps its width. for (0..9) |_| _ = say(p, .@"error", id, "broke"); row = noticeRow(p, 60, &buf); try std.testing.expectEqualStrings("\u{2717} /test.txt broke \u{d7}10", row.text[0..row.left]); try std.testing.expectEqual(@as(usize, 60), panes.File.displayWidth(p.settings.tab, row.text)); // An error that names places offers the walk, its places as words. const err = keep(p, .@"error", 0, "@p9 zig build", "exit 1"); err.places[0] = .{ .line = 25, .col = 12 }; err.places[0].path.set("core/pick.zig"); err.places_len = 1; row = noticeRow(p, 80, &buf); try std.testing.expectEqualStrings("\u{2717} @p9 zig build exit 1 core/pick.zig:25:12", row.text[0..row.left]); try std.testing.expect(std.mem.endsWith(u8, row.text, "+1 \u{b7} SPC e walk")); // Too narrow: the left gives way, the right stays whole. row = noticeRow(p, 30, &buf); try std.testing.expect(std.mem.endsWith(u8, row.text, "+1 \u{b7} SPC e walk")); try std.testing.expect(panes.File.displayWidth(p.settings.tab, row.text) <= 30); // A question outranks a warning, not an error; it is counted on the right. _ = keep(p, .question, pane.serial, "/test.txt", "changed on disk"); row = noticeRow(p, 80, &buf); try std.testing.expect(std.mem.startsWith(u8, row.text, "\u{2717} @p9")); try std.testing.expect(std.mem.endsWith(u8, row.text, "+2 \u{b7} 1 question \u{b7} SPC e")); } test "a rolled level's last leaf is said on the notice row, the whole row, never in a chip over the body; at rest the row is the messages' again" { const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 120, .rows = 30 }); defer p.deinit(); const pane = try p.setTestFile("one\n"); p.messages.live_len = 0; p.clock.now_ns = 5 * std.time.ns_per_s; p.clock.stepped_ns = p.clock.now_ns; // SPC t w: Wrap, run from SPC t; then SPC t again, shown. for (" tw t") |c| p.update(.{ .key = .{ .cp = c } }); p.advance(p.clock.now_ns); p.clock.now_ns = p.view().tag_state.due_ns; p.sync(); _ = try p.render(p.scratch.allocator()); var buf: [notice_row_cap]u8 = undefined; var row = noticeRow(p, 110, &buf); try std.testing.expect(std.mem.startsWith(u8, row.text, "w Wrap: ")); try std.testing.expect(std.mem.endsWith(u8, row.text, " (last used here)")); try std.testing.expectEqual(row.text.len, row.right); try std.testing.expect(row.lead == null); try std.testing.expectEqual(@as(u8, 0), pane.notices.len); // Narrower than the line: cut to the width, never past it. row = noticeRow(p, 12, &buf); try std.testing.expectEqualStrings("w Wrap: Long", row.text); // Esc: at rest, the messages' (Wrap's echo), and with none where the // caret is. p.update(.{ .key = .{ .cp = pardes.Key.escape } }); row = noticeRow(p, 110, &buf); try std.testing.expect(row.lead != null); p.messages.live_len = 0; row = noticeRow(p, 110, &buf); try std.testing.expect(std.mem.startsWith(u8, row.text, "/test.txt:1")); } test "an idle core wants no wake, and a message wakes it once, when it dims" { const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 80, .rows = 24 }); defer p.deinit(); while (p.nextEffect()) |_| {} p.advance(1_000_000); p.messages.live_len = 0; try std.testing.expectEqual(@as(?u64, null), p.nextWake()); try std.testing.expect(p.executeBuiltinLine(p.view().active, "MessageLinger 160")); try std.testing.expect(p.executeBuiltinLine(p.view().active, "Msg hello")); const said = p.messages.headline().?; try std.testing.expect(!said.faded(p.clock.now_ns, p.settings.message_linger_ms)); // The core sleeps to its dimming, not a frame at a time. const frame = pardes.frame_ns; const due = said.t + 160 * std.time.ns_per_ms; const woken = p.nextWake().?; try std.testing.expect(woken >= due and woken < due + frame); p.advance(woken); try std.testing.expect(said.faded(p.clock.now_ns, p.settings.message_linger_ms)); try std.testing.expectEqual(@as(?u64, null), p.nextWake()); // A warning is bright twice as long; with no linger nothing wakes. try std.testing.expect(p.executeBuiltinLine(p.view().active, "MessageLinger 0")); _ = say(p, .warn, p.view().active, "careful"); try std.testing.expectEqual(@as(?u64, null), p.nextWake()); } test "a compiler's report names its places: each place's words, the first error's rows after it its detail, a relative path the run's directory's" { var s: Said = .{}; const rows = [_][]const u8{ "install", "+- compile exe pardes Debug native 1 errors", "core/pick.zig:25:12: error: expected 2 argument(s), found 3", " const best = rank(q, name, 3) orelse continue;", " ^~~~", "core/look.zig:14:5: note: function declared here", "pub fn rank(q: []const u8, name: []const u8) ?u32 {", "error: the following command failed with 1 compilation errors:", }; try std.testing.expectEqual(@as(usize, 2), readPlaces(&s, "/src/pardes/", &rows)); try std.testing.expectEqualStrings("/src/pardes/core/pick.zig", s.places[0].path.slice()); try std.testing.expectEqual(@as(u32, 25), s.places[0].line); try std.testing.expectEqual(@as(u32, 12), s.places[0].col); try std.testing.expectEqualStrings("expected 2 argument(s), found 3", s.places[0].text.slice()); try std.testing.expectEqualStrings("note: function declared here", s.places[1].text.slice()); try std.testing.expectEqual(@as(u8, 2), s.detail_len); try std.testing.expectEqualStrings(" const best = rank(q, name, 3) orelse continue;", s.detail[0].slice()); try std.testing.expectEqualStrings(" ^~~~", s.detail[1].slice()); // No error among them: no places. var none: Said = .{}; try std.testing.expectEqual(@as(usize, 0), readPlaces(&none, "/", &.{ "x.zig:1:1: note: only a note", "grep: nothing" })); } test "a burst of the same message is one message, counted, and moves nothing on the screen" { const p = try Pardes.init(std.testing.allocator, .{ .cols = 80, .rows = 20 }); defer p.deinit(); const pane = try p.setTestFile("text\n"); const id = p.view().active; _ = say(p, .@"error", id, "workspace/didChangeWatchedFiles: 3 files"); p.sync(); const rects = p.view().rects; const tag_rows = pane.tag_rows; for (0..9) |_| _ = say(p, .@"error", id, "workspace/didChangeWatchedFiles: 3 files"); p.sync(); try std.testing.expectEqual(@as(u8, 1), p.messages.live_len); try std.testing.expectEqual(@as(u16, 10), p.messages.headline().?.n); try std.testing.expectEqual(rects, p.view().rects); try std.testing.expectEqual(tag_rows, pane.tag_rows); var buf: [notice_row_cap]u8 = undefined; const row = noticeRow(p, 78, &buf); try std.testing.expect(std.mem.endsWith(u8, row.text[0..row.left], "3 files \u{d7}10")); } test "a question never adds a row to its tag: at every width the asking tag takes the rows the tag takes at rest, its answers always shown, the question cut before them" { const p = try Pardes.init(std.testing.allocator, .{ .cols = 120, .rows = 30 }); defer p.deinit(); const pane = try p.setTestFile("one\n"); const id = p.view().active; // A short name: the tag's rows have room for it and the answers. p.gpa.free(pane.file.?.path); pane.file.?.path = try p.gpa.dupe(u8, "/t/c.zig"); const f = &pane.file.?; f.saved_hash = panes.File.fileHash(f); for ([_]u21{ 'G', 'o', 'f', Key.escape }) |cp| p.update(.{ .key = .{ .cp = cp } }); // The tag's own words cut to one, so the question is the longer. pane.tag.own = try p.gpa.dupe(u8, " Put"); p.update(.{ .file_changed = .{ .pane = .at(id), .bytes = "zero\n" } }); _ = p.messages.waiting(pane) orelse return error.NotAsked; var frame = std.heap.ArenaAllocator.init(std.testing.allocator); defer frame.deinit(); for (56..161) |cols| { p.update(.{ .resize = .{ .cols = @intCast(cols), .rows = 30 } }); p.sync(); const rest = pardes.layout.wantedTagRows(p, id); try std.testing.expect(pane.tag_rows <= @max(rest, 1)); const shown = try pardes.tagline.tagText(p, frame.allocator(), pane); for ([_][]const u8{ "r Reload", "k Keep mine", "d Diff" }) |word| try std.testing.expect(std.mem.indexOf(u8, shown, word) != null); _ = frame.reset(.retain_capacity); } } test "a file changed on disk under unsaved text asks in its tag and never takes the keyboard: SPC e's keyboard answers, d shows the disk's lines as ghosts, Esc leaves it waiting, B2 on Reload reads it again" { // Wide: the tag at rest one row (UX K'3), the question whole in it. const p = try Pardes.init(std.testing.allocator, .{ .cols = 200, .rows = 20 }); defer p.deinit(); var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "c.zig", .data = "one\ntwo\nthree\n" }); var dir: [4096]u8 = undefined; const path = try std.fmt.allocPrint(std.testing.allocator, "{s}/c.zig", .{dir[0..try tmp.dir.realPath(std.testing.io, &dir)]}); defer std.testing.allocator.free(path); const pane = try p.setTestFile("one\ntwo\nthree\n"); const id = p.view().active; p.gpa.free(pane.file.?.path); pane.file.?.path = try p.gpa.dupe(u8, path); const f = &pane.file.?; f.saved_hash = panes.File.fileHash(f); // Unsaved: a line typed at the end. for ([_]u21{ 'G', 'o', 'f', 'o', 'u', 'r', Key.escape }) |cp| p.update(.{ .key = .{ .cp = cp } }); try std.testing.expect(f.revision != f.saved_revision); const disk = "zero\none\ntwo\nthree\n"; try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "c.zig", .data = disk }); p.update(.{ .file_changed = .{ .pane = .at(id), .bytes = disk } }); const i = p.messages.waiting(pane) orelse return error.NotAsked; try std.testing.expectEqual(Kind.question, p.messages.live[i].kind); // In its tag at rest, its answers offered in place of the tag's own // words (the head, walk UI R1), read-only; its mark `?`. var frame = std.heap.ArenaAllocator.init(std.testing.allocator); defer frame.deinit(); const shown = try pardes.tagline.tagText(p, frame.allocator(), pane); try std.testing.expect(std.mem.endsWith(u8, shown, " changed on disk \u{25b8} r Reload k Keep mine d Diff \u{b7} SPC e to answer")); try std.testing.expect(std.mem.startsWith(u8, shown, path)); try std.testing.expectEqual(Kind.question, p.messages.markOf(pane).?); try std.testing.expect(std.mem.indexOf(u8, shown, "Save") == null); const prefix = try pardes.tagline.tagPrefix(p, pane); try std.testing.expect(std.mem.indexOf(u8, prefix, "changed on disk") == null); // The tag's own text is no one's to edit meanwhile. try std.testing.expect((try pardes.TagState.head(p, frame.allocator(), pane)) != null); // Out of rest (SPC's level shown) the level's head, not the question; // at rest again, the question. p.update(.{ .key = .{ .cp = ' ' } }); p.advance(p.clock.now_ns); p.clock.now_ns = p.view().tag_state.due_ns; try std.testing.expect(std.mem.indexOf(u8, try pardes.tagline.tagText(p, frame.allocator(), pane), "changed on disk") == null); p.update(.{ .key = .{ .cp = Key.escape } }); try std.testing.expect(std.mem.indexOf(u8, try pardes.tagline.tagText(p, frame.allocator(), pane), "changed on disk") != null); try std.testing.expectEqualStrings("Reload", p.messages.waitingAnswers(pane)[0].word); // The keyboard is not its: `r` is the body's (helix's replace). p.update(.{ .key = .{ .cp = 'k' } }); try std.testing.expect(p.messages.waiting(pane) != null); // Given the keyboard: `d` shows the disk's lines and keeps asking; Esc // leaves it waiting. p.view().answering = pane.serial; p.update(.{ .key = .{ .cp = 'd' } }); const asked = &p.messages.live[p.messages.waiting(pane).?]; try std.testing.expect(asked.open); try std.testing.expectEqual(@as(u32, 1), asked.places[0].line); try std.testing.expectEqualStrings("+zero", asked.detail[0].slice()); try std.testing.expectEqual(pane.serial, p.view().answering); p.update(.{ .key = .{ .cp = Key.escape } }); try std.testing.expectEqual(@as(u32, 0), p.view().answering); try std.testing.expect(p.messages.waiting(pane) != null); // B2 on `Reload` in its tag: read again, the question gone. try std.testing.expectEqual(@as(?usize, null), pardes.exec.execute(p, id, "Reload")); while (p.nextEffect()) |_| {} try std.testing.expect(p.messages.waiting(pane) == null); try std.testing.expectEqualStrings(disk, p.panes[id].?.file.?.content); } test "SPC e on an error that names places lists them under the pane and lands on the first, on a question gives its tag the keyboard, and on anything else opens the history, the newest first" { const p = try Pardes.init(std.testing.allocator, .{ .cols = 100, .rows = 30 }); defer p.deinit(); // About a jump opening a pane: `Jumps new-pane` (SPEC §6.6). p.settings.jumps = .@"new-pane"; const pane = try p.setTestFile("one\ntwo\nthree\nfour\nfive\n"); const serial = pane.serial; p.messages.live_len = 0; const err = keep(p, .@"error", 0, "@p9 zig build", "exit 1"); for ([_]u32{ 2, 4 }, 0..) |line, k| { err.places[k] = .{ .line = line, .col = 1 }; err.places[k].path.set("/test.txt"); err.places[k].text.set("bad"); } err.places_len = 2; p.update(.{ .key = .{ .cp = ' ' } }); p.update(.{ .key = .{ .cp = 'e' } }); while (p.nextEffect()) |_| {} // The error kept, its lines marked, until Esc. try std.testing.expect(p.messages.headline() == err); const here = p.paneBySerial(serial).?; const list = p.panes[p.panes[here].?.search_pane orelse return error.NoList].?; try std.testing.expect(std.mem.indexOf(u8, list.file.?.content, "/test.txt:4:1") != null); try std.testing.expectEqual(@as(i32, 1), p.panes[here].?.body.cur_row); try std.testing.expectEqual(@as(usize, 1), p.messages.retire(&.{.@"error"})); // A question: its tag gets the keyboard. keep(p, .question, serial, "/test.txt", "changed on disk").asks = .disk; try std.testing.expect(p.executeBuiltinLine(here, "Message")); try std.testing.expectEqual(serial, p.view().answering); p.update(.{ .key = .{ .cp = Key.escape } }); try std.testing.expectEqual(@as(u32, 0), p.view().answering); // Anything else: the history, the newest first, each with its glyph. p.messages.live_len = 0; _ = say(p, .notice, here, "older words"); _ = say(p, .warn, here, "newer words"); try std.testing.expect(p.executeBuiltinLine(here, "Message")); const said_so_far = for (p.panes) |slot| { const shown = slot orelse continue; const f = shown.file orelse continue; if (std.mem.endsWith(u8, f.path, config.messages_buffer)) break f.content; } else return error.NoHistory; const newer = std.mem.indexOf(u8, said_so_far, "! ") orelse return error.NoGlyph; try std.testing.expect(newer < std.mem.indexOf(u8, said_so_far, "older words").?); } test "where jumps walk, SPC e lands an error's places as a list in the pane's walk, n walking them; SPC h m is a picker over the history in the pane's tag, the newest first, Enter on a message going to its cause, C-q keeping it as a +Messages" { const p = try Pardes.init(std.testing.allocator, .{ .cols = 100, .rows = 30 }); defer p.deinit(); p.settings.jumps = .walk; const pane = try p.setTestFile("one\ntwo\nthree\nfour\nfive\n"); const id = p.view().active; p.messages.live_len = 0; const err = keep(p, .@"error", 0, "@p9 zig build", "exit 1"); for ([_]u32{ 2, 4 }, 0..) |line, k| { err.places[k] = .{ .line = line, .col = 1 }; err.places[k].path.set("/test.txt"); err.places[k].text.set("bad"); } err.places_len = 2; var panes_before: usize = 0; for (p.panes) |slot| panes_before += @intFromBool(slot != null); for (" e") |c| p.update(.{ .key = .{ .cp = c } }); while (p.nextEffect()) |_| {} try std.testing.expect(p.messages.headline() == err); // Landed in this reading pane, no pane made: on the first place, the // list's word in its trail. var panes_now: usize = 0; for (p.panes) |slot| panes_now += @intFromBool(slot != null); try std.testing.expectEqual(panes_before, panes_now); try std.testing.expectEqual(id, p.view().active); try std.testing.expectEqual(@as(i32, 1), pane.body.cur_row); var frame = std.heap.ArenaAllocator.init(std.testing.allocator); defer frame.deinit(); try std.testing.expect(std.mem.indexOf(u8, try pardes.tagline.tagText(p, frame.allocator(), pane), "\u{2717} @p9 zig build 1/2") != null); // n: the next place, the word saying so. p.update(.{ .key = .{ .cp = 'n' } }); try std.testing.expectEqual(@as(i32, 3), pane.body.cur_row); try std.testing.expect(std.mem.indexOf(u8, try pardes.tagline.tagText(p, frame.allocator(), pane), "\u{2717} @p9 zig build 2/2") != null); // SPC h m: the history in this pane's tag, a row a message, the newest // first; no pane made. _ = say(p, .echo, id, "older"); _ = say(p, .warn, id, "newest"); for (" hm") |c| p.update(.{ .key = .{ .cp = c } }); while (p.nextEffect()) |_| {} try std.testing.expectEqual(pardes.TagState.Kind.pick, p.view().tag_state.kind); const pk = pardes.Pick.live(p).?; try std.testing.expectEqual(pardes.Pick.Source.messages, pk.source); var marks: [256]u16 = undefined; var nmarks: usize = 0; // (Row 0 is the word's own echo, `Messages`, said as it ran.) try std.testing.expect(std.mem.indexOf(u8, pk.names.row(1, &marks, &nmarks), "newest") != null); try std.testing.expect(std.mem.indexOf(u8, pk.names.row(2, &marks, &nmarks), "older") != null); // Enter on a message: its cause's pane has the keyboard, the picker // rolled up; then the history again. p.update(.{ .key = .{ .cp = Key.down } }); p.update(.{ .key = .{ .cp = Key.enter } }); while (p.nextEffect()) |_| {} try std.testing.expectEqual(pardes.TagState.Kind.rest, p.view().tag_state.kind); try std.testing.expectEqual(id, p.view().active); for (" hm") |c| p.update(.{ .key = .{ .cp = c } }); while (p.nextEffect()) |_| {} try std.testing.expectEqual(pardes.TagState.Kind.pick, p.view().tag_state.kind); // C-q: kept as the +Messages, the picker rolled up. p.update(.{ .key = .{ .cp = 'q', .ctrl = true } }); while (p.nextEffect()) |_| {} try std.testing.expectEqual(pardes.TagState.Kind.rest, p.view().tag_state.kind); panes_now = 0; for (p.panes) |slot| panes_now += @intFromBool(slot != null); try std.testing.expectEqual(panes_before + 1, panes_now); const kept = p.panes[p.view().active].?; try std.testing.expect(std.mem.endsWith(u8, kept.file.?.path, config.messages_buffer)); } test "Esc at rest takes a search's tints first, then the warnings and errors, and only then goes back" { const p = try Pardes.init(std.testing.allocator, .{ .cols = 100, .rows = 30 }); defer p.deinit(); const pane = try p.setTestFile("alpha beta alpha\n"); const id = p.view().active; p.messages.live_len = 0; p.update(.{ .key = .{ .cp = '*' } }); p.update(.{ .key = .{ .cp = 'n' } }); while (p.nextEffect()) |_| {} if (pane.places.pattern.len == 0 and pane.places.hits.items.len == 0) return error.NoTints; _ = say(p, .@"error", id, "broke"); p.update(.{ .key = .{ .cp = Key.escape } }); try std.testing.expect(pane.places.pattern.len == 0 and pane.places.hits.items.len == 0); try std.testing.expectEqual(@as(u8, 1), p.messages.live_len); p.update(.{ .key = .{ .cp = Key.escape } }); try std.testing.expectEqual(@as(u8, 0), p.messages.live_len); try std.testing.expectEqual(id, p.view().active); } test "the notice row's left is cut with `…` two blanks before its right block at least: the pane's path from the left, its name and line kept; a message from the right" { const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 80, .rows = 24 }); defer p.deinit(); const pane = try p.setTestFile("one\ntwo\n"); const id = p.view().active; p.gpa.free(pane.file.?.path); pane.file.?.path = try p.gpa.dupe(u8, "/home/someone/projects/a/long/way/down/core/Store.zig"); p.messages.live_len = 0; p.messages.len = 0; _ = say(p, .notice, id, "saved"); p.messages.live_len = 0; var buf: [notice_row_cap]u8 = undefined; const tab = p.settings.tab; // The path and `1 message · SPC h m`: 40 cells. var row = noticeRow(p, 40, &buf); try std.testing.expect(std.mem.startsWith(u8, row.text, "…") and std.mem.endsWith(u8, row.text[0..row.left], "/Store.zig:1")); try std.testing.expect(std.mem.endsWith(u8, row.text, "1 message \u{b7} SPC h m")); try std.testing.expect(row.right - row.left >= 2); try std.testing.expectEqual(@as(usize, 40), panes.File.displayWidth(tab, row.text)); // A live message: cut from the right, `…` at its end. _ = say(p, .@"error", id, "the build failed because something somewhere went badly wrong"); row = noticeRow(p, 40, &buf); try std.testing.expect(std.mem.startsWith(u8, row.text, "\u{2717} ") and std.mem.endsWith(u8, row.text[0..row.left], "…")); try std.testing.expect(row.right - row.left >= 2); try std.testing.expect(panes.File.displayWidth(tab, row.text) <= 40); // Room for it all: nothing cut, no `…`. row = noticeRow(p, 200, &buf); try std.testing.expect(std.mem.indexOf(u8, row.text, "…") == null); } test "a cause longer than its word's room keeps the path's end, `…` first, so the file's name is whole (S2 08b at 16 px: `…/core/Query.zi`, its last letter lost)" { const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 200, .rows = 24 }); defer p.deinit(); const pane = try p.setTestFile("one\n"); const id = p.view().active; const long = "/tmp/claude-1000/wS2g16/proj/a/rather/long/way/down/to/the/sources/of/this/project/core/Query.zig"; p.gpa.free(pane.file.?.path); pane.file.?.path = try p.gpa.dupe(u8, long); p.messages.live_len = 0; const s = say(p, .notice, id, "the build finished"); try std.testing.expect(std.mem.startsWith(u8, s.src.slice(), "\u{2026}")); try std.testing.expect(std.mem.endsWith(u8, long, s.src.slice()["\u{2026}".len..])); // The notice row names the file whole, its words after it. var buf: [notice_row_cap]u8 = undefined; var row = noticeRow(p, 190, &buf); try std.testing.expect(std.mem.endsWith(u8, row.text[0..row.left], "/core/Query.zig the build finished")); // Words that name the path already leave the cause out, cut or not // (S2 08a: `saved PATH`). p.messages.live_len = 0; _ = say(p, .notice, id, "saved " ++ long); row = noticeRow(p, 190, &buf); try std.testing.expectEqualStrings("\u{b7} saved " ++ long, row.text[0..row.left]); } test "a message too wide for the notice row gives way by its items, each cut showing `…`: its cause first (a path down to its name, a command down to its pane), then the paths it names down to theirs, then its words from the right; its right part whole, two blanks before it (UX D2, F2; S2 08a, 08b, 09a at 26 px)" { const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 100, .rows = 30 }); defer p.deinit(); const pane = try p.setTestFile("one\n"); const id = p.view().active; const long = "/tmp/claude-1000/wS2g26/proj/a/rather/long/way/down/to/the/sources/of/this/project/core/Query.zig"; p.gpa.free(pane.file.?.path); pane.file.?.path = try p.gpa.dupe(u8, long); p.messages.live_len = 0; p.messages.len = 0; const tab = p.settings.tab; var buf: [notice_row_cap]u8 = undefined; // 08b: the cause a long path, the words longer than the row. _ = say(p, .notice, id, "the build in the other column finished with three warnings and one error, the error in a file this pane does not show"); var row = noticeRow(p, 97, &buf); var left = row.text[0..row.left]; try std.testing.expect(std.mem.startsWith(u8, left, "\u{b7} \u{2026}Query.zig the build in the other column finished")); try std.testing.expect(std.mem.endsWith(u8, left, "\u{2026}")); try std.testing.expect(row.right - row.left >= 2); try std.testing.expectEqual(@as(usize, 97), panes.File.displayWidth(tab, row.text)); // 08a: the words name a path: it is cut from its left, its name whole. p.messages.live_len = 0; _ = say(p, .notice, id, "saved " ++ long); row = noticeRow(p, 97, &buf); left = row.text[0..row.left]; try std.testing.expect(std.mem.startsWith(u8, left, "\u{b7} saved \u{2026}")); try std.testing.expect(std.mem.endsWith(u8, left, "/core/Query.zig")); try std.testing.expect(row.right - row.left >= 2); // 09a: a command pane's cause gives way from its right, down to its // `@pN`, before the place it names: the place stays whole. p.messages.live_len = 0; const err = keep(p, .@"error", 0, "@p2 sh -c 'printf \"Store.zig:20:5: error: expected 2 argument(s), found 3", "exit 1"); err.places[0] = .{ .line = 20, .col = 5 }; err.places[0].path.set("/tmp/claude-1000/wS2g26/proj/core/Store.zig"); err.places_len = 1; row = noticeRow(p, 97, &buf); left = row.text[0..row.left]; try std.testing.expect(std.mem.startsWith(u8, left, "\u{2717} @p2 sh -c")); try std.testing.expect(std.mem.endsWith(u8, left, "\u{2026} exit 1 /tmp/claude-1000/wS2g26/proj/core/Store.zig:20:5")); try std.testing.expect(std.mem.endsWith(u8, row.text, "SPC e walk")); try std.testing.expect(row.right - row.left >= 2); // A command's echo cut for its word ends in `…` too (S2 09a: `fo exit 1`). pane.command = try p.gpa.dupe(u8, "sh -c 'printf \"Store.zig:20:5: error: expected 2 argument(s), found 3\\n\"; exit 1'"); const file = pane.file; pane.file = null; defer pane.file = file; var word: Buf(96) = .{}; causeWord(pane, &word); try std.testing.expect(std.mem.endsWith(u8, word.slice(), "\u{2026}")); } test "SPC e keeps the error it walks: the file it lands in, not open when the error was said, shows the error's mark in its box and its words after the place's line" { var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "report.zig", .data = "one\ntwo\nthree\nfour\n var s = 1;\nsix\n" }); var dir_buf: [4096]u8 = undefined; const dir = dir_buf[0..try tmp.dir.realPath(std.testing.io, &dir_buf)]; const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 100, .rows = 30 }); defer p.deinit(); p.settings.jumps = .walk; _ = try p.setTestFile("main\n"); p.messages.live_len = 0; const err = keep(p, .@"error", 0, "@p9 zig build", "exit 2"); err.places[0] = .{ .line = 5, .col = 9 }; _ = err.places[0].path.print("{s}/report.zig", .{dir}); err.places[0].text.set("local variable is never mutated"); err.places_len = 1; for (" e") |c| p.update(.{ .key = .{ .cp = c } }); while (p.nextEffect()) |_| {} p.sync(); const id = p.view().active; const pane = p.panes[id].?; try std.testing.expect(std.mem.endsWith(u8, pane.file.?.path, "/report.zig")); try std.testing.expectEqual(@as(i32, 4), pane.body.cur_row); // The error lives on (Esc, the next error or its pane's next run take // it): the line it names is marked where the walk landed. try std.testing.expect(p.messages.headline() != null and p.messages.headline().?.kind == .@"error"); var frame = std.heap.ArenaAllocator.init(std.testing.allocator); defer frame.deinit(); const s = try p.render(frame.allocator()); const r = p.view().rects[id]; try std.testing.expectEqualStrings("\u{2717}", s.at(r.x + config.GUTTER - 1, p.tagTop(pane, r)).grapheme()); var buf: [512]u8 = undefined; const marked = for (0..s.rows) |y| { var n: usize = 0; for (0..s.cols) |x| { const g = s.cells[y * s.cols + x].grapheme(); if (n + g.len > buf.len) break; @memcpy(buf[n..][0..g.len], g); n += g.len; } if (std.mem.indexOf(u8, buf[0..n], "var s = 1;") != null) break buf[0..n]; } else return error.LineNotShown; try std.testing.expect(std.mem.indexOf(u8, marked, "var s = 1; \u{2717} local variable is never mutated") != null); } test "SPC e lands on its place's column, where jumps walk and where they open a pane" { const p = try Pardes.init(std.testing.allocator, .{ .cols = 100, .rows = 30 }); defer p.deinit(); const pane = try p.setTestFile("one\ntwo\n var s = 1;\nfour\n"); for ([_]config.Settings.Jumps{ .walk, .@"new-pane" }) |jumps| { p.settings.jumps = jumps; p.view().active = p.paneBySerial(pane.serial).?; pane.body.cur_row = 0; pane.body.cur_col = 0; p.messages.live_len = 0; const err = keep(p, .@"error", 0, "@p9 zig build", "exit 2"); err.places[0] = .{ .line = 3, .col = 9 }; err.places[0].path.set("/test.txt"); err.places[0].text.set("local variable is never mutated"); err.places_len = 1; for (" e") |c| p.update(.{ .key = .{ .cp = c } }); while (p.nextEffect()) |_| {} const landed = p.panes[p.view().active].?; try std.testing.expectEqualStrings("/test.txt", landed.file.?.path); try std.testing.expectEqual(@as(i32, 2), landed.body.cur_row); try std.testing.expectEqual(@as(i32, 8), landed.body.cur_col); } } test "a file changed since the run that named its places draws none of their words at its lines (UX DESIGN H): a line put in above draws them at neither line, the box's mark and the notice row kept; the next run's error draws at its new line, and an edit on that line quiets it at once" { const p = try Pardes.init(std.testing.allocator, .{ .cols = 100, .rows = 30 }); defer p.deinit(); const pane = try p.setTestFile("const std = @import(\"std\");\n\npub fn print() void {\n var s = 1;\n _ = s;\n}\n"); const id = p.view().active; p.messages.live_len = 0; var frame = std.heap.ArenaAllocator.init(std.testing.allocator); defer frame.deinit(); var buf: [512]u8 = undefined; // The row its words are drawn on, null for none. const Shown = struct { fn row(pp: *Pardes, arena: *std.heap.ArenaAllocator, out: *[512]u8) !?[]const u8 { _ = arena.reset(.retain_capacity); pp.sync(); const s = try pp.render(arena.allocator()); for (0..s.rows) |y| { var n: usize = 0; for (0..s.cols) |x| { const g = s.cells[y * s.cols + x].grapheme(); if (n + g.len > out.len) break; @memcpy(out[n..][0..g.len], g); n += g.len; } if (std.mem.indexOf(u8, out[0..n], "\u{2717} local variable is never mutated") != null) return out[0..n]; } return null; } }; for (0..2) |run| { // A run names line 4 (the first) or 5 (the next, after the line // put in above): its pane's next run takes the last one's error // away (exec.zig) before it says its own. _ = p.messages.retire(&.{.@"error"}); const err = keep(p, .@"error", 0, "@p2 zig build", "exit 2"); err.places[0] = .{ .line = @intCast(4 + run), .col = 9 }; err.places[0].path.set("/test.txt"); err.places[0].text.set("local variable is never mutated"); err.places_len = 1; const drawn = try Shown.row(p, &frame, &buf) orelse return error.WordsNotDrawn; try std.testing.expect(std.mem.indexOf(u8, drawn, "var s = 1; \u{2717}") != null); if (run == 1) break; // A language server's edit puts a line in above it (File.load, a // code action's way): the words are at neither its line nor the // line it went to. const f = &pane.file.?; panes.File.load(p, f, try std.mem.concat(p.gpa, u8, &.{ "const std = @import(\"std\");\nconst Counts = u32;\n", f.content["const std = @import(\"std\");\n".len..] })); try std.testing.expect(try Shown.row(p, &frame, &buf) == null); // Its box's mark and the notice row's place stay until the run. const s = try p.render(frame.allocator()); const r = p.view().rects[id]; try std.testing.expectEqualStrings("\u{2717}", s.at(r.x + config.GUTTER - 1, p.tagTop(pane, r)).grapheme()); var row_buf: [notice_row_cap]u8 = undefined; try std.testing.expect(std.mem.indexOf(u8, noticeRow(p, 97, &row_buf).text, "/test.txt:4:9") != null); } // An edit on the line, the fix: quiet at once. const f = &pane.file.?; const var_at = std.mem.indexOf(u8, f.content, "var s") orelse return error.NoLine; try std.testing.expect(panes.File.replace(p, f, var_at, "var".len, "const")); try std.testing.expect(try Shown.row(p, &frame, &buf) == null); }