//! 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`); //! and the transient bands a pane shows over its body's top rows (the //! pending leader chord, 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) = .{}, }; /// 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, }; /// 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 its first place's line while /// the caret is on it. 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, /// 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]; } }; /// `SPC` plus the chord keys typed so far, spaced out the way the help /// index spells a leader path. fn leaderText(p: *const Pardes, buf: *[16]u8) []const u8 { buf.* = @splat(' '); @memcpy(buf[0..3], "SPC"); var end: usize = 3; for (p.view().leader_keys[0..p.view().leader_n]) |ch| { if (end + 2 > buf.len) break; buf[end + 1] = ch; end += 2; } return buf[0..end]; } 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 { 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`). pub fn say(p: *Pardes, kind: Kind, id: usize, text: []const u8) void { 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| { if (cause.file) |f| src.set(f.path) else if (cause.command) |line| { 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; _ = src.print(config.pane_addr ++ "{d} {s}", .{ cause.serial, first[0..cut] }); } else _ = src.print(config.pane_addr ++ "{d}", .{cause.serial}); } _ = keep(p, kind, if (pane) |cause| cause.serial else 0, src.slice(), text); } /// 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; } 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 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; } /// 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(p: *const Pardes, pane: *const Pane, i: usize, leader_buf: *[16]u8) []const u8 { return switch (pane.notices.kinds[i]) { .message => p.messages.saidBy(pane), .leader => leaderText(p, leader_buf), .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; return say(p, .@"error", id, text); } 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, id: usize) void { pane.notices = bands(p, p.view(), pane, pane.tag_rows, r, id); // 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; var leader_buf: [16]u8 = undefined; for (0..pane.notices.len) |i| { const chip = panes.File.displayWidth(p.settings.tab, noticeText(p, pane, i, &leader_buf)) + 2; pane.notices.left[i] = if (tw == 0) std.math.maxInt(u16) else tx + tw - @as(u16, @intCast(@min(chip, tw))); } } /// The bands pane `id` shows in view `v`, 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, v: *const Pardes.View, pane: *const Pane, tag_rows: u16, r: Rect, id: usize) Pane.Notices { var n: Pane.Notices = .{}; if (r.w <= config.GUTTER or r.h <= tag_rows) return n; // The newest message said of it on top. if (p.messages.saidBy(pane).len > 0) n.push(.message); if (id == v.active and v.prefix == .leader) n.push(.leader); // 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 message row, 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 leaves no row // for its announcement, which is correct and not what this is testing. try std.testing.expect(p.executeBuiltinLine(p.view().active, "Wrap")); try std.testing.expectEqualStrings("Wrap", p.messages.saidBy(pane)); // A value it does not take is said, in place of the announcement. 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); // The notice list is what the paint pass reads, so the announcement has to // reach it, not just the buffer. collectNotices(p, pane, p.view().rects[p.view().active], p.view().active); try std.testing.expect(pane.notices.len > 0); try std.testing.expectEqual(Pane.Notices.Kind.message, pane.notices.kinds[0]); // ...and it is carried as a tagline band, not a body row: that is what // gives it the tagline's height, its small font and its border. var frame = std.heap.ArenaAllocator.init(std.testing.allocator); defer frame.deinit(); _ = try p.render(frame.allocator()); const r = p.view().rects[p.view().active]; const band = for (p.surface.tagLayers()) |*layer| { if (layer.rows != 0 and layer.kind == .notice) break layer; } else return error.NoNoticeBand; try std.testing.expectEqual(@as(u16, 1), band.viewport.h); try std.testing.expectEqual(r.y + BOX_H, band.viewport.y); // Right aligned: the text ends at the band's right edge. const line = band.cells[0..band.cols]; var last: usize = line.len; while (last > 0 and line[last - 1].grapheme()[0] == ' ') last -= 1; try std.testing.expect(last > 0); try std.testing.expect(line[0].grapheme()[0] == ' '); // 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 "notices stack over the body's top rows without moving them" { const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 80, .rows = 24 }); defer p.deinit(); const id = p.view().active; const pane = p.panes[id].?; p.sync(); var frame = std.heap.ArenaAllocator.init(std.testing.allocator); defer frame.deinit(); const r = p.view().rects[id]; const top = p.bodyTop(pane, r); // A message and a leader prefix at once: two chips, in the order // collectNotices chose, each one row tall and each one row further down. try std.testing.expect(p.executeBuiltinLine(id, "Msg first")); p.view().prefix = .leader; p.view().leader_n = 0; _ = frame.reset(.retain_capacity); _ = try p.render(frame.allocator()); try std.testing.expectEqual(@as(u8, 2), pane.notices.len); // An overlay, not a reservation: the body still starts where it did. try std.testing.expectEqual(top, p.bodyTop(pane, r)); var seen: usize = 0; for (p.surface.tagLayers()) |*layer| { if (layer.rows == 0 or layer.kind != .notice) continue; try std.testing.expectEqual(@as(u16, 1), layer.viewport.h); // Sized to its own message, right up against the pane's right edge -- // not the width of the pane. try std.testing.expectEqual(r.x + r.w, layer.viewport.x + layer.viewport.w); try std.testing.expect(layer.viewport.w < r.w - config.GUTTER); try std.testing.expect(layer.viewport.y == top or layer.viewport.y == top + 1); try std.testing.expectEqual(pane.notices.left[layer.viewport.y - top], layer.viewport.x); seen += 1; } try std.testing.expectEqual(@as(usize, 2), seen); // "first" is longer than "SPC", so its chip is wider. try std.testing.expect(pane.notices.left[0] < pane.notices.left[1]); // Gone with the notices: no stale chip left behind. p.view().prefix = .none; p.messages.live_len = 0; _ = frame.reset(.retain_capacity); _ = try p.render(frame.allocator()); for (p.surface.tagLayers()) |*layer| try std.testing.expect(layer.rows == 0 or layer.kind != .notice); } 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()); }