summaryrefslogtreecommitdiff
path: root/core/Messages.zig
diff options
context:
space:
mode:
Diffstat (limited to 'core/Messages.zig')
-rw-r--r--core/Messages.zig887
1 files changed, 887 insertions, 0 deletions
diff --git a/core/Messages.zig b/core/Messages.zig
new file mode 100644
index 00000000..4080ff61
--- /dev/null
+++ b/core/Messages.zig
@@ -0,0 +1,887 @@
+//! The message row: messages and statuses a pane shows between its body and
+//! its tagline, how each line lingers once dismissed, the notices
+//! built from them every frame, and the log of everything said.
+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 Messages = @This();
+
+/// 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,
+
+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,
+
+ 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
+ /// `--:--:--`.
+ 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 as the session that said it read it, in its
+ // zone: a replica's clock and TZ are its own (core/tape.zig).
+ const clock = pardes.tape.value(.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 the message line in place (a progress count does not
+/// pile up); a message is an event, and stacks.
+pub fn setStatus(p: *Pardes, id: usize, text: []const u8) void {
+ const taped = pardes.tape.enter(p, .{ .set_status = .{ .id = id, .text = text } });
+ defer pardes.tape.leave(p, taped);
+ showMessage(p, id, text, false);
+}
+
+pub fn setMessage(p: *Pardes, id: usize, text: []const u8) void {
+ const taped = pardes.tape.enter(p, .{ .set_message = .{ .id = id, .text = text } });
+ defer pardes.tape.leave(p, taped);
+ logMessage(p, id, text);
+ showMessage(p, id, text, true);
+}
+
+fn showMessage(p: *Pardes, id: usize, text: []const u8, stack: bool) void {
+ if (id >= MAX_PANES) return;
+ const pane = p.panes[id] orelse return;
+ // 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 n: usize = @min(text.len, pane.msg.len);
+ if (n < text.len) {
+ while (n > 0 and text[n] & 0xC0 == 0x80) n -= 1;
+ }
+ const same = pane.msg_len == n and for (text[0..n], pane.msg[0..n]) |c, have| {
+ if ((if (c < 0x20 or c == 0x7f) ' ' else c) != have) break false;
+ } else true;
+ // A new event moves the line on screen up the stack, where it keeps
+ // its own timing, and falls in below it.
+ // Only an event stacks on an event: an announcement or a status
+ // stands in for whatever comes next.
+ if (stack and pane.msg_len > 0 and !same and !pane.msg_announcement and !pane.msg_status)
+ pane.pushOlderMessage();
+ if (pane.msg_len == 0) pane.msg_slot = pane.freeMessageSlot();
+ pane.msg_announcement = false;
+ pane.msg_sent = false;
+ pane.msg_status = !stack;
+ for (text[0..n], pane.msg[0..n]) |c, *cell| cell.* = if (c < 0x20 or c == 0x7f) ' ' else c;
+ pane.msg_len = @intCast(n);
+ // The clock when it was said (the session clock is the last pump's,
+ // and a 9P write after an idle hour would say it an hour ago).
+ pane.msg_said_ms = pardes.tape.value(.clock, nowMs, .{});
+ p.needs_frame = true;
+ // New, the same line again or a status update: fresh, so it stays.
+ pane.msg_life = .{};
+}
+
+/// With no frontend attached no input dismisses a message, and a detached
+/// session's /screen and messages kept what was said an hour ago: each
+/// pane's lines go once its newest has been up `message_linger_ms`, on the
+/// clock, checked as the core is stepped (each event, and each pump after
+/// its wait, which a message wakes) -- not as a 9P request is served, since
+/// a read is answered while a step is out and must change nothing, nor by
+/// the host, whose call is no input a replay makes.
+/// ponytail: a pane's older lines go with its newest, not each on its own
+/// clock; the render pipeline's clock will give every line its own.
+fn nowMs() i64 {
+ var ts: std.c.timespec = undefined;
+ if (std.c.clock_gettime(.MONOTONIC, &ts) != 0) return 0;
+ return @as(i64, ts.sec) * 1000 + @divTrunc(@as(i64, ts.nsec), 1_000_000);
+}
+
+pub fn expireUnattended(p: *Pardes) void {
+ if (!p.unattended) return;
+ // The clock as the session that recorded read it (core/tape.zig).
+ const now = pardes.tape.value(.clock, nowMs, .{});
+ for (p.panes) |slot| {
+ const pane = slot orelse continue;
+ if (pane.msg_len == 0 and pane.msg_older_len == 0) continue;
+ if (now - pane.msg_said_ms < p.settings.message_linger_ms) continue;
+ pane.msg_len = 0;
+ pane.msg_life = .{};
+ pane.msg_older_len = 0;
+ p.needs_frame = true;
+ }
+}
+
+/// The key or click that used to clear the message row now starts each
+/// line's exit: it stays `message_linger_ms`, then goes. A line already
+/// on its way out keeps its own timing.
+pub fn dismissMessage(p: *Pardes, pane: *Pane) void {
+ if (pane.msg_len > 0 and dismissLine(p, &pane.msg_life)) {
+ pane.msg_len = 0;
+ pane.msg_life = .{};
+ }
+ var i: usize = 0;
+ while (i < pane.msg_older_len) {
+ if (dismissLine(p, &pane.msg_older[i].life)) pane.removeOlderMessage(i) else i += 1;
+ }
+}
+
+/// Start one line's exit; true when it is gone at once (no linger).
+fn dismissLine(p: *const Pardes, life: *Pane.MessageLife) bool {
+ if (life.phase == .lingering) return false;
+ if (p.settings.message_linger_ms == 0) return true;
+ life.* = .{ .phase = .lingering };
+ return false;
+}
+
+/// One frame of every lingering message line. The one that goes owes a
+/// frame: a tick asks for none itself.
+pub fn advanceMessages(p: *Pardes) void {
+ for (p.panes) |slot| {
+ const pane = slot orelse continue;
+ if (pane.msg_len > 0 and pane.msg_life.phase != .shown) {
+ p.needs_frame = true;
+ if (advanceLine(p, &pane.msg_life)) {
+ pane.msg_len = 0;
+ pane.msg_life = .{};
+ }
+ }
+ var i: usize = 0;
+ while (i < pane.msg_older_len) {
+ if (pane.msg_older[i].life.phase != .shown) p.needs_frame = true;
+ if (advanceLine(p, &pane.msg_older[i].life)) pane.removeOlderMessage(i) else i += 1;
+ }
+ }
+}
+
+/// One frame of one line's life; true once it has gone.
+fn advanceLine(p: *const Pardes, life: *Pane.MessageLife) bool {
+ if (life.phase == .shown) return false;
+ life.frame +|= 1;
+ return life.frame >= messageFrames(p.settings.message_linger_ms);
+}
+
+/// Move every lingering message line `frames` along its linger at once:
+/// how `advance` jumps a wait instead of stepping it frame by frame.
+pub fn holdMessages(p: *Pardes, frames: u64) void {
+ const n: u16 = @intCast(@min(frames, std.math.maxInt(u16)));
+ for (p.panes) |slot| {
+ const pane = slot orelse continue;
+ if (pane.msg_len > 0 and pane.msg_life.phase == .lingering) pane.msg_life.frame +|= n;
+ for (pane.msg_older[0..pane.msg_older_len]) |*line| {
+ if (line.life.phase == .lingering) line.life.frame +|= n;
+ }
+ }
+}
+
+/// Frames until this pane's message lines next change: the rest of a
+/// linger, null when every line just shows.
+pub fn messageWake(p: *const Pardes, pane: *const Pane) ?u64 {
+ var soonest: ?u64 = null;
+ const linger = messageFrames(p.settings.message_linger_ms);
+ for (0..@as(usize, pane.msg_older_len) + 1) |i| {
+ const life = if (i < pane.msg_older_len) pane.msg_older[i].life else if (pane.msg_len > 0) pane.msg_life else continue;
+ if (life.phase == .shown) continue;
+ const frames: u64 = @max(1, linger -| life.frame);
+ soonest = if (soonest) |n| @min(n, frames) else frames;
+ }
+ return soonest;
+}
+
+/// Frames a message timing lasts; at least one.
+pub fn messageFrames(ms: u16) u16 {
+ return @intCast(@max(1, (@as(u32, ms) + pardes.frame_ms - 1) / pardes.frame_ms));
+}
+
+/// 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 => pane.msg[0..pane.msg_len],
+ .older => pane.msg_older[pane.notices.index[i]].slice(),
+ .leader => leaderText(p, leader_buf),
+ .prompt => pane.promptText() orelse "",
+ };
+}
+
+fn logMessage(p: *Pardes, id: usize, 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;
+ 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";
+
+/// `<operation>: <the error in words>`: 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 fn reportError(p: *Pardes, id: usize, operation: []const u8, err: anyerror) void {
+ const taped = pardes.tape.enter(p, .{ .report_error = .{ .id = id, .operation = operation, .err = err } });
+ defer pardes.tape.leave(p, taped);
+ // 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, 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, w.buffered());
+ }
+ var words: [128]u8 = undefined;
+ w.writeAll(errorWords(err, &words)) catch {};
+ reportFailure(p, id, 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 setMessage(p, id, text);
+ }
+ setMessage(p, 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(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;
+ // Oldest message line on top, so lines already up do not move when a
+ // new one lands under them; when rows run out the oldest go first.
+ for (pane.msg_older[0..pane.msg_older_len], 0..) |line, i| n.pushAt(.older, @intCast(i), line.slot);
+ if (pane.msg_len > 0) n.pushAt(.message, 0, pane.msg_slot);
+ 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.span() <= room) return n;
+ // Too short for the gaps: close them up in screen order, and if even
+ // that does not fit, the top bands go.
+ var i: usize = 1;
+ while (i < n.len) : (i += 1) {
+ var j = i;
+ while (j > 0 and n.row[j - 1] > n.row[j]) : (j -= 1) {
+ std.mem.swap(Pane.Notices.Kind, &n.kinds[j - 1], &n.kinds[j]);
+ std.mem.swap(u8, &n.index[j - 1], &n.index[j]);
+ std.mem.swap(u8, &n.row[j - 1], &n.row[j]);
+ }
+ }
+ const drop = n.len -| room;
+ for (0..n.len - drop) |k| {
+ n.kinds[k] = n.kinds[k + drop];
+ n.index[k] = n.index[k + drop];
+ n.row[k] = @intCast(k);
+ }
+ n.len -= @intCast(drop);
+ 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, 0, "14:32:07 saved /x.zig");
+ setMessage(p, 0, "14:32:09 saved /x.zig"); // same event, later clock
+ setMessage(p, 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, 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, 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, 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 writes the transient row by hand, bare or with text, and input ends 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()) |_| {}
+ const row = struct {
+ fn of(pp: *Pardes, i: usize) []const u8 {
+ const pane = pp.panes[i].?;
+ return pane.msg[0..pane.msg_len];
+ }
+ }.of;
+
+ // 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", row(p, 2));
+ // ...on the pane that ran it, and nowhere else
+ try std.testing.expectEqualStrings("", row(p, 0));
+
+ // Bare, it reports ITSELF through reportError — the `<operation>: <error in words>`
+ // every failed save and refused Look arrives in.
+ try std.testing.expect(p.executeBuiltinLine(2, "Msg"));
+ try std.testing.expectEqualStrings("Msg: no message", row(p, 2));
+
+ // Input starts its exit: it lingers, and is gone.
+ p.update(.{ .key = .{ .cp = Key.escape } });
+ try std.testing.expectEqualStrings("Msg: no message", row(p, 2));
+ for (0..200) |_| p.update(.tick);
+ try std.testing.expectEqualStrings("", row(p, 2));
+ // ...and with no linger it is as old as your last input.
+ try std.testing.expect(p.executeBuiltinLine(2, "MessageLinger 0"));
+ try std.testing.expect(p.executeBuiltinLine(2, "Msg gone"));
+ p.update(.{ .key = .{ .cp = 'h' } });
+ try std.testing.expectEqualStrings("", row(p, 2));
+
+ // Longer than the row's buffer 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(p.panes[2].?.msg.len, row(p, 2).len);
+}
+
+test "with no frontend attached a message goes once it has lingered, on the clock" {
+ const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true });
+ defer p.deinit();
+ const pane = p.panes[p.view().active].?;
+ p.setMessage(p.view().active, "said");
+ p.setMessage(p.view().active, "said again");
+ // Attached: it waits for input, however long.
+ pane.msg_said_ms -= 60_000;
+ p.update(.tick);
+ try std.testing.expect(pane.msg_len > 0);
+ // Detached with nobody attached: past its linger it is gone, and the
+ // line above it with it.
+ p.unattended = true;
+ // A read served meanwhile changes nothing; the session's step after its
+ // wait expires, not the host (whose call no replay makes).
+ _ = p.serveFs(.{ .tag = 1, .op = .read, .node = @backingInt(ctlfs.TopFile.index), .size = 64 });
+ try std.testing.expect(pane.msg_len > 0);
+ try p.pump(.{});
+ try std.testing.expectEqual(@as(u16, 0), pane.msg_len);
+ try std.testing.expectEqual(@as(u8, 0), pane.msg_older_len);
+ // A fresh one stays until its linger is up.
+ p.setMessage(p.view().active, "fresh");
+ p.update(.tick);
+ try std.testing.expect(pane.msg_len > 0);
+}
+
+test "a message lingers past the input that dismisses it, and goes" {
+ const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 80, .rows = 24 });
+ defer p.deinit();
+ while (p.nextEffect()) |_| {}
+ const pane = p.panes[p.view().active].?;
+ try std.testing.expect(p.executeBuiltinLine(p.view().active, "MessageLinger 160"));
+ try std.testing.expect(p.executeBuiltinLine(p.view().active, "Msg hello"));
+ // Shown at once, until input; the same line again stays shown.
+ try std.testing.expectEqual(Pane.MessagePhase.shown, pane.msg_life.phase);
+ try std.testing.expect(!p.animationActive());
+ for (0..100) |_| p.update(.tick);
+ try std.testing.expectEqual(Pane.MessagePhase.shown, pane.msg_life.phase);
+ try std.testing.expect(p.executeBuiltinLine(p.view().active, "Msg hello"));
+ try std.testing.expectEqual(Pane.MessagePhase.shown, pane.msg_life.phase);
+ // Input (a key that announces nothing): 160 ms of lingering (ten frames), unaffected by more input...
+ p.update(.{ .key = .{ .cp = 'h' } });
+ try std.testing.expectEqual(Pane.MessagePhase.lingering, pane.msg_life.phase);
+ for (0..9) |_| {
+ p.update(.tick);
+ p.update(.{ .key = .{ .cp = 'h' } });
+ }
+ try std.testing.expectEqual(Pane.MessagePhase.lingering, pane.msg_life.phase);
+ // ...then it is gone, and the tick that clears it owes the frame that
+ // shows it gone.
+ p.needs_frame = false;
+ p.update(.tick);
+ try std.testing.expectEqual(@as(u16, 0), pane.msg_len);
+ try std.testing.expect(p.needs_frame);
+ try std.testing.expect(!p.animationActive());
+ // Shown again while lingering: fresh, so it stays; a status update to a
+ // line on screen swaps its text in place.
+ try std.testing.expect(p.executeBuiltinLine(p.view().active, "Msg again"));
+ p.update(.{ .key = .{ .cp = 'h' } });
+ try std.testing.expectEqual(Pane.MessagePhase.lingering, pane.msg_life.phase);
+ try std.testing.expect(p.executeBuiltinLine(p.view().active, "Msg again"));
+ try std.testing.expectEqual(Pane.MessagePhase.shown, pane.msg_life.phase);
+ setStatus(p, p.view().active, "progress 50%");
+ try std.testing.expectEqual(Pane.MessagePhase.shown, pane.msg_life.phase);
+ try std.testing.expectEqualStrings("progress 50%", pane.msg[0..pane.msg_len]);
+ try std.testing.expectEqual(@as(u8, 0), pane.msg_older_len);
+}
+
+test "messages stack, oldest on top, each on its own timing" {
+ const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 80, .rows = 24 });
+ defer p.deinit();
+ while (p.nextEffect()) |_| {}
+ const pane = p.panes[p.view().active].?;
+ try std.testing.expect(p.executeBuiltinLine(p.view().active, "Verbose off"));
+ try std.testing.expect(p.executeBuiltinLine(p.view().active, "MessageLinger 160"));
+ // `Verbose off` announced itself before it took effect.
+ pane.msg_len = 0;
+ pane.msg_life = .{};
+ setMessage(p, p.view().active, "first");
+ try std.testing.expectEqual(Pane.MessagePhase.shown, pane.msg_life.phase);
+ // A second message stacks under the first instead of replacing it.
+ setMessage(p, p.view().active, "second");
+ try std.testing.expectEqual(@as(u8, 1), pane.msg_older_len);
+ try std.testing.expectEqualStrings("first", pane.msg_older[0].slice());
+ try std.testing.expectEqualStrings("second", pane.msg[0..pane.msg_len]);
+ collectNotices(p, pane, p.view().rects[p.view().active], p.view().active);
+ try std.testing.expectEqual(Pane.Notices.Kind.older, pane.notices.kinds[0]);
+ try std.testing.expectEqual(Pane.Notices.Kind.message, pane.notices.kinds[1]);
+ // One key dismisses both, each on its own clock: a line already
+ // lingering keeps its timing.
+ p.update(.{ .key = .{ .cp = 'h' } });
+ try std.testing.expectEqual(Pane.MessagePhase.lingering, pane.msg_older[0].life.phase);
+ try std.testing.expectEqual(Pane.MessagePhase.lingering, pane.msg_life.phase);
+ p.update(.tick);
+ setMessage(p, p.view().active, "third");
+ try std.testing.expectEqual(@as(u8, 2), pane.msg_older_len);
+ p.update(.{ .key = .{ .cp = 'h' } });
+ const linger = messageFrames(p.settings.message_linger_ms);
+ for (0..linger - 1) |_| p.update(.tick);
+ // The first two are gone; the third, a frame later, still lingers.
+ try std.testing.expectEqual(@as(u8, 0), pane.msg_older_len);
+ try std.testing.expectEqualStrings("third", pane.msg[0..pane.msg_len]);
+ try std.testing.expectEqual(Pane.MessagePhase.lingering, pane.msg_life.phase);
+ p.update(.tick);
+ try std.testing.expectEqual(@as(u16, 0), pane.msg_len);
+ try std.testing.expect(!p.animationActive());
+ // A status ticking in place does not pile up.
+ setStatus(p, p.view().active, "lsp 10%");
+ setStatus(p, p.view().active, "lsp 20%");
+ try std.testing.expectEqual(@as(u8, 0), pane.msg_older_len);
+ // Lines keep their rows: when the top one leaves, the one under it does
+ // not move up, and the next message fills the gap instead.
+ setMessage(p, p.view().active, "top");
+ setMessage(p, p.view().active, "under");
+ try std.testing.expectEqual(@as(u8, 0), pane.msg_older[0].slot);
+ try std.testing.expectEqual(@as(u8, 1), pane.msg_slot);
+ pane.removeOlderMessage(0);
+ collectNotices(p, pane, p.view().rects[p.view().active], p.view().active);
+ try std.testing.expectEqual(@as(u8, 1), pane.notices.row[0]);
+ try std.testing.expectEqual(@as(u8, 2), pane.notices.span());
+ setMessage(p, p.view().active, "fills");
+ try std.testing.expectEqual(@as(u8, 0), pane.msg_slot);
+ try std.testing.expectEqual(@as(u8, 1), pane.msg_older[0].slot);
+ // The stack keeps the newest few.
+ for ([_][]const u8{ "a", "b", "c", "d", "e" }) |text| setMessage(p, p.view().active, text);
+ try std.testing.expectEqual(@as(u8, Pane.message_stack), pane.msg_older_len);
+ try std.testing.expectEqualStrings("b", pane.msg_older[0].slice());
+ try std.testing.expectEqualStrings("e", pane.msg[0..pane.msg_len]);
+}
+
+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", pane.msg[0..pane.msg_len]);
+ // 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", pane.msg[0..pane.msg_len]);
+ 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", pane.msg[0..pane.msg_len]);
+
+ pane.msg_len = 0;
+ p.settings.verbose = false;
+ try std.testing.expect(p.executeBuiltinLine(p.view().active, "Wrap"));
+ try std.testing.expectEqual(@as(u16, 0), pane.msg_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;
+ pane.msg_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 lingering message sleeps to its linger's end" {
+ const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 80, .rows = 24 });
+ defer p.deinit();
+ while (p.nextEffect()) |_| {}
+ const frame = pardes.frame_ns;
+ p.advance(1_000_000);
+ try std.testing.expectEqual(@as(?u64, null), p.nextWake());
+ const pane = p.panes[p.view().active].?;
+ // Shown, a message asks for no wake.
+ try std.testing.expect(p.executeBuiltinLine(p.view().active, "Msg hello"));
+ try std.testing.expectEqual(Pane.MessagePhase.shown, pane.msg_life.phase);
+ try std.testing.expectEqual(@as(?u64, null), p.nextWake());
+ // A key starts the 800 ms linger: the core sleeps to its end, not a
+ // frame at a time, and the frames it jumps draw nothing.
+ p.update(.{ .key = .{ .cp = 'x' } });
+ try std.testing.expectEqual(Pane.MessagePhase.lingering, pane.msg_life.phase);
+ const linger = messageFrames(p.settings.message_linger_ms);
+ const due = p.clock.stepped_ns + linger * frame;
+ try std.testing.expectEqual(@as(?u64, due), p.nextWake());
+ p.needs_frame = false;
+ p.advance(due - frame);
+ try std.testing.expectEqual(@as(?u64, due), p.nextWake());
+ try std.testing.expectEqual(Pane.MessagePhase.lingering, pane.msg_life.phase);
+ p.advance(due);
+ try std.testing.expectEqual(@as(usize, 0), pane.msg_len);
+ try std.testing.expectEqual(@as(?u64, null), p.nextWake());
+
+ // A long linger ends when it says, jumped in one step, not stretched by
+ // the cap on catching up with moving frames.
+ try std.testing.expect(p.executeBuiltinLine(p.view().active, "MessageLinger 5000"));
+ try std.testing.expect(p.executeBuiltinLine(p.view().active, "Msg again"));
+ p.update(.{ .key = .{ .cp = 'x' } });
+ const long_due = p.clock.stepped_ns + messageFrames(5000) * frame;
+ try std.testing.expectEqual(@as(?u64, long_due), p.nextWake());
+ p.advance(long_due);
+ try std.testing.expectEqual(@as(usize, 0), pane.msg_len);
+}