//! The band (walk UI, pick-ui SPEC.md §3.6): rows hanging under a pane's //! tag while it is out of rest, in the tag's tint, pushing its body down: //! the tag unrolled. Its steps stand side by side, each a column of rows //! (a level, Help's rows, a doc; later a picker's acts and sources, a //! prompt's history, the registers), a one-cell rule between them, right //! of a spine under each of the head's key cells. //! //! Derived from the live view's state each time it is asked (`of`), never //! stored (the coordinator's R2): the layout reads its height (`takes`, //! Pardes.sync, layout.floorRows), the frame paints it (draw.zig //! joinBand) as a tag layer of kind `.band`, and the mouse reads its words //! (`line`): read-only text, which B2 executes and B3 looks at as a tag's. //! //! A new kind of step: a function that fills a `Step` (its `rows`, in the //! frame's arena, as many as it shows, and whether it is a `doc`) from the //! state that owns it, called from `of` for the tag state it belongs to, //! with that state's rows in `height`; nothing else changes. const Band = @This(); const std = @import("std"); const pardes = @import("root.zig"); const bindings = @import("bindings.zig"); const tagline = @import("tagline.zig"); const layout = @import("layout.zig"); const modal = @import("modal.zig"); const panes = @import("panes.zig"); const builtins = @import("builtins.zig"); const TagState = @import("TagState.zig"); const Names = @import("Names.zig"); const Prompt = @import("Prompt.zig"); const Pardes = pardes.Pardes; const Pane = pardes.Pane; const File = panes.File; /// One row of a step: its text, as B2 and B3 read it, and how it is drawn. pub const Row = struct { text: []const u8, /// The rows' cursor: `▶` before it and the selection's tint over it. on: bool = false, /// Its first `key` bytes are a key: the key ink, bold. key: u8 = 0, dim: bool = false, /// The leaf its group ran last. under: bool = false, /// The bytes a query matched: the match tint. marks: []const u16 = &.{}, /// Its place in the list its step shows (a level's child, a hit): what /// a click on it moves the cursor to. index: u16 = 0, }; /// A column of rows. A level of more than 9 rows flows into two columns /// (`two`); a `doc` takes the width the others leave, wrapped to it, and is /// the first to give way. pub const Step = struct { rows: []const Row = &.{}, two: bool = false, doc: bool = false, /// Where it starts and how wide it is, in the band's columns (`place`). x: u16 = 0, width: u16 = 0, }; pub const max_steps = 4; pub const max_spines = 12; /// The narrowest a step is drawn (SPEC §3.6: box, spines, one 24-cell column). pub const min_width = 24; /// A doc's rows, the fewest a band with one has. const doc_rows = 4; /// A level's rows past which it flows into two columns. const one_column = 9; /// The columns of the head's key cells, in the band's columns: a spine /// hangs under each. spines: [max_spines]u16 = undefined, nspines: u8 = 0, steps: [max_steps]Step = undefined, nsteps: u8 = 0, height: u16 = 0, /// The band's width at the tagline's pitch. columns: u16 = 0, /// The rows the band under pane `id`'s tag takes in the live view, from /// its state alone: the layout's term, asked before any frame is made. pub fn takes(p: *Pardes, id: usize) u16 { const v = p.view(); const s = &v.tag_state; if (TagState.hostOf(p) != id) return 0; switch (s.kind) { .rest => {}, .help => return @max(doc_rows, @max(1, @min(Cursor.shown, s.nhits))), .describe => return 0, .prompt => return Prompt.takes(p), } if (!s.unrolled) return 0; const cur = TagState.current(p, v) orelse return 0; var children: [bindings.max_children]bindings.Child = undefined; const n: u16 = @intCast(bindings.level(p, cur.root, cur.path, &children).len); return @max(doc_rows, levelRows(n)); } fn levelRows(n: u16) u16 { return if (n > one_column) (n + 1) / 2 else n; } /// Pane `id`'s band as the live view's state has it, made in `arena`; /// null when its tag has none. pub fn of(p: *Pardes, arena: std.mem.Allocator, pane: *Pane, id: usize) !?Band { const rows = takes(p, id); if (rows == 0) return null; const v = p.view(); const s = &v.tag_state; var band: Band = .{ .height = rows, .columns = layout.tagCapacity(p, p.view().rects[id].w -| pardes.TAG_TEXT_INSET) }; switch (s.kind) { .rest => {}, .help => { try band.helpSteps(p, arena, s); try band.place(p, arena, pane, id); return band; }, .describe => return null, .prompt => { var steps: [max_steps]Step = undefined; for (try Prompt.steps(p, arena, &steps)) |step| band.add(step); try band.place(p, arena, pane, id); return band; }, } const cur = TagState.current(p, v).?; // The level, its cursor on the child it names, else the leaf its group // ran last, else the first; and that child's doc beside it. const node = bindings.nodeAt(cur.root, cur.path); const used = if (node) |n| s.used[n.group] else 0; var children: [bindings.max_children]bindings.Child = undefined; const level = bindings.level(p, cur.root, cur.path, &children); var at: usize = 0; for (level, 0..) |c, i| if (c.key == (if (s.hi != 0) s.hi else used)) { at = i; }; band.add(try levelStep(arena, pane, level, at, used)); band.add(try docStep(p, arena, cur.root, cur.path, level[at])); try band.place(p, arena, pane, id); return band; } /// Help's rows (`chord · word · group`, the query's bytes in the match /// tint) around the cursor, and the cursor's leaf's doc beside them. fn helpSteps(band: *Band, p: *Pardes, arena: std.mem.Allocator, s: *const TagState) !void { if (s.nhits == 0) { const none = try arena.alloc(Row, 1); none[0] = .{ .text = if (s.field.len == 0) "no keys here" else "no key matches", .dim = true }; band.add(.{ .rows = none }); return; } const w = s.rows.window(s.nhits); const rows = try arena.alloc(Row, w.hi - w.lo); const q = s.field.text(); for (rows, w.lo..) |*row, i| { const buf = try arena.create([TagState.row_max]u8); const leaf = TagState.helpLeaf(p, s.hits[i], buf); var marks: [Names.max_query * 4]u16 = undefined; var nmarks: usize = 0; if (std.mem.trim(u8, q, " ").len > 0) { const low = try std.ascii.allocLowerString(arena, leaf.row); _ = Names.match(q, leaf.row, low, 0, &marks, &nmarks); } row.* = .{ .text = leaf.row, .on = i == s.rows.at, .marks = try arena.dupe(u16, marks[0..nmarks]), .index = @intCast(i), .dim = bindings.dimmed(p.panes[p.view().active].?, leaf.child) }; } band.add(.{ .rows = rows }); var buf: [TagState.row_max]u8 = undefined; const at = TagState.helpLeaf(p, s.hits[s.rows.at], &buf); band.add(try docStep(p, arena, at.root, at.path[0 .. at.path.len - 1], at.child)); } /// A list's cursor and the rows of it a band shows: eleven at most, around /// the cursor (SPEC §3.6, the prototype's `H.window`). Each view's (a /// tag state's field): Help's rows, a picker's, a prompt's history. pub const Cursor = struct { at: u16 = 0, pub const shown = 11; /// Rows [lo, hi) of `n` the band shows. pub fn window(c: Cursor, n: u16) struct { lo: u16, hi: u16 } { const lo = @min(c.at -| shown / 2, n -| shown); return .{ .lo = lo, .hi = @min(n, lo + shown) }; } /// A key that steps a list of `n`: Down, C-j, C-n a row on, Up, C-k, /// C-p a row back, PageDown and PageUp ten; true when taken. pub fn key(c: *Cursor, k: pardes.Key, n: u16) bool { const Key = pardes.Key; const plain = !k.ctrl and !k.alt; const ctrl = k.ctrl and !k.alt; const step: i32 = if (plain and k.cp == Key.down or ctrl and (k.cp == 'j' or k.cp == 'n')) 1 else if (plain and k.cp == Key.up or ctrl and (k.cp == 'k' or k.cp == 'p')) -1 else if (plain and k.cp == Key.page_down) 10 else if (plain and k.cp == Key.page_up) -10 else return false; if (n == 0) return true; c.at = @intCast(std.math.clamp(@as(i32, c.at) + step, 0, @as(i32, n) - 1)); return true; } }; fn add(band: *Band, step: Step) void { if (band.nsteps == max_steps) return; band.steps[band.nsteps] = step; band.nsteps += 1; } /// A level's children as rows (`k Label`, a group's `label…`), the cursor /// on child `at`. pub fn levelStep(arena: std.mem.Allocator, pane: *const Pane, level: []const bindings.Child, at: usize, used: u8) !Step { const rows = try arena.alloc(Row, level.len); for (level, rows, 0..) |c, *row, i| { const key = bindings.keyName(c.key); row.* = .{ .text = try std.fmt.allocPrint(arena, "{s} {s}{s}", .{ key, c.label, if (c.group) "…" else "" }), .on = i == at, .key = @intCast(key.len), .dim = bindings.dimmed(pane, c), .under = c.key == used, .index = @intCast(i), }; } return .{ .rows = rows, .two = level.len > one_column }; } /// What child `c` is: a leaf's word and its whole documentation, then its /// keys; a group's children, a row each. pub fn docStep(p: *Pardes, arena: std.mem.Allocator, root: bindings.Root, path: []const u8, c: bindings.Child) !Step { var rows: std.ArrayList(Row) = .empty; const key = bindings.keyName(c.key); try rows.append(arena, .{ .text = try std.fmt.allocPrint(arena, "{s} {s}{s}", .{ key, c.label, if (c.group) "…" else "" }), .key = @intCast(key.len) }); if (c.group) { const here = try std.mem.concat(arena, u8, &.{ path, &.{c.key} }); var below: [bindings.max_children]bindings.Child = undefined; for (bindings.level(p, root, here, &below)) |g| { const k = bindings.keyName(g.key); try rows.append(arena, .{ .text = try std.fmt.allocPrint(arena, "{s} {s}{s}", .{ k, g.label, if (g.group) "…" else "" }), .key = @intCast(k.len) }); } return .{ .rows = rows.items, .doc = true }; } const doc = if (c.node) |n| switch (n.leaf.?) { .builtin => |b| builtins.registry.doc(b).text, .arg => |a| builtins.registry.doc(pardes.config.leader_args[a].cmd).text, .role => bindings.docOf(root, c, try arena.alloc(u8, 160)), } else bindings.docOf(root, c, &.{}); try rows.append(arena, .{ .text = doc }); var buf: [64]u8 = undefined; const here = try std.mem.concat(arena, u8, &.{ path, &.{c.key} }); try rows.append(arena, .{ .text = try std.fmt.allocPrint(arena, "keys {s}", .{bindings.chord(root, here, &buf)}) }); return .{ .rows = rows.items, .doc = true }; } /// Where each step goes: right of the spines, a rule's cell between steps; /// a doc takes what is left, wrapped to it. Narrow, the doc goes first, /// then the spines (the steps start at the band's left edge). fn place(band: *Band, p: *Pardes, arena: std.mem.Allocator, pane: *Pane, id: usize) !void { const tab = p.settings.tab; try band.findSpines(p, arena, pane, id); var x: u16 = if (band.nspines > 0) band.spines[band.nspines - 1] + 2 else 0; var need: u16 = 0; for (band.steps[0..band.nsteps]) |*step| { if (step.doc) continue; var widest: usize = 0; for (step.rows) |row| widest = @max(widest, File.displayWidth(tab, row.text)); const column: u16 = @intCast(@min(widest + 2, std.math.maxInt(u16) / 4)); step.width = if (step.two) 2 * column + 1 else column; need += step.width + 2; } if (x + need > band.columns) { band.nspines = 0; x = 0; } var kept: u8 = 0; for (band.steps[0..band.nsteps]) |step| { var placed = step; if (step.doc) { const room = band.columns -| x; if (room < min_width) continue; placed.width = room; placed.rows = try wrap(arena, tab, step.rows, room -| 1, band.height); } placed.x = x; x +|= placed.width + 2; band.steps[kept] = placed; kept += 1; } band.nsteps = kept; } /// The display columns of the head's key cells, when they are all on the /// tag's last row (the spines hang from there). fn findSpines(band: *Band, p: *Pardes, arena: std.mem.Allocator, pane: *Pane, id: usize) !void { const h = (try TagState.head(p, arena, pane)) orelse return; const whole = try tagline.tagText(p, arena, pane); const shown = try tagline.wrapTag(p.settings.tab, arena, whole, tagline.tagWidth(p, id)); const lead = whole.len - h.text.len; const last = shown.rows() -| 1; for (h.spans[0..h.cells]) |span| { const at = modal.positionAt(shown.text, shown.fromReal(lead + span.lo)); if (at.row != last or band.nspines == max_spines) { band.nspines = 0; return; } band.spines[band.nspines] = @intCast(File.rawDisplayCol(p.settings.tab, modal.lineSlice(shown.text, at.row), at.col)); band.nspines += 1; } } /// `rows` wrapped at `width` display columns, word by word, `height` rows /// at most: a doc's paragraphs. fn wrap(arena: std.mem.Allocator, tab: u16, rows: []const Row, width: u16, max: u16) ![]const Row { var out: std.ArrayList(Row) = .empty; for (rows) |row| { if (File.displayWidth(tab, row.text) <= width) { try out.append(arena, row); } else { var rest = row.text; while (rest.len > 0 and out.items.len < max) { var cut = File.byteAtDisplay(tab, rest, width); if (cut < rest.len) { if (std.mem.lastIndexOfScalar(u8, rest[0..cut], ' ')) |space| { if (space > 0) cut = space; } } if (cut == 0) cut = modal.nextGrapheme(rest, 0); try out.append(arena, .{ .text = std.mem.trimEnd(u8, rest[0..cut], " ") }); rest = std.mem.trimStart(u8, rest[cut..], " "); } } if (out.items.len >= max) break; } if (out.items.len > max) out.shrinkRetainingCapacity(max); return out.items; } /// One row of the band as text, and where each step's row starts in it. pub const Line = struct { text: []const u8, parts: []const Part, pub const Part = struct { col: u16, width: u16, row: Row }; }; /// Row `y`: the spines, then each step's row, padded to its width, a rule /// between steps. pub fn line(band: *const Band, arena: std.mem.Allocator, tab: u16, y: u16) !Line { var text: std.ArrayList(u8) = .empty; var parts: std.ArrayList(Line.Part) = .empty; var col: u16 = 0; for (band.spines[0..band.nspines]) |spine| { while (col < spine) : (col += 1) try text.append(arena, ' '); try text.appendSlice(arena, "│"); col += 1; } for (band.steps[0..band.nsteps], 0..) |step, i| { if (i > 0) { while (col + 2 < step.x) : (col += 1) try text.append(arena, ' '); try text.appendSlice(arena, "│ "); col += 2; } while (col < step.x) : (col += 1) try text.append(arena, ' '); const per = if (step.two) (step.width - 1) / 2 else step.width; const shown: u16 = if (step.two) levelRows(@intCast(step.rows.len)) else @intCast(step.rows.len); var lane: u16 = 0; while (lane < @as(u16, if (step.two) 2 else 1)) : (lane += 1) { const k = y + lane * shown; const start = step.x + lane * (per + 1); while (col < start) : (col += 1) try text.append(arena, ' '); if (y >= shown or k >= step.rows.len) continue; const row = step.rows[k]; const lead: []const u8 = if (step.doc) "" else if (row.on) "▶ " else " "; try text.appendSlice(arena, lead); col += @intCast(File.displayWidth(tab, lead)); try parts.append(arena, .{ .col = col, .width = per -| @as(u16, @intCast(File.displayWidth(tab, lead))), .row = row }); const room = per -| @as(u16, @intCast(File.displayWidth(tab, lead))); const cut = File.byteAtDisplay(tab, row.text, room); try text.appendSlice(arena, row.text[0..cut]); col += @intCast(File.displayWidth(tab, row.text[0..cut])); } } return .{ .text = text.items, .parts = parts.items }; } /// The word under column `col` of band row `y` of pane `id`, at the /// tagline's pitch: what B2 executes and B3 looks at. pub fn wordAt(p: *Pardes, arena: std.mem.Allocator, id: usize, y: u16, col: u16) !?[]const u8 { const pane = p.panes[id] orelse return null; const band = (try of(p, arena, pane, id)) orelse return null; if (y >= band.height) return null; const ln = try band.line(arena, p.settings.tab, y); const at = File.rawAtDisplay(p.settings.tab, ln.text, col); const b = tagline.wordBoundsAtCol(ln.text, at) orelse return null; if (b.lo == b.hi) return null; return ln.text[b.lo..b.hi]; } fn bandLayer(p: *Pardes, id: usize) ?*pardes.Layer { const layer = &p.surface.tag_layers[pardes.BAND_LAYER_BASE + id]; return if (layer.rows > 0 and layer.kind == .band) layer else null; } fn layerRow(arena: std.mem.Allocator, layer: *const pardes.Layer, row: usize) ![]const u8 { var out: std.ArrayList(u8) = .empty; for (layer.cells[row * layer.cols ..][0..layer.cols]) |cell| try out.appendSlice(arena, cell.grapheme()); return out.items; } test "SPC Down unrolls the level into a band under the tag's text, the body pushed down and never drawn over; Up on its first row rolls it up" { const Key = pardes.Key; const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 120, .rows = 40 }); defer p.deinit(); const pane = try p.setTestFile("one\ntwo\nthree\n"); const id = p.view().active; var frame = std.heap.ArenaAllocator.init(std.testing.allocator); defer frame.deinit(); p.sync(); const r = p.view().rects[id]; const text_rows = pane.tag_rows; const body_top = p.bodyTop(pane, r); _ = try p.render(frame.allocator()); try std.testing.expect(bandLayer(p, id) == null); p.update(.{ .key = .{ .cp = ' ' } }); p.update(.{ .key = .{ .cp = Key.down } }); try std.testing.expect(p.view().tag_state.unrolled); // SPC's top has more than nine children: two columns, and a doc. try std.testing.expect(pane.band_rows >= doc_rows); try std.testing.expectEqual(text_rows + pane.band_rows, pane.tag_rows); try std.testing.expectEqual(body_top + pane.band_rows, p.bodyTop(pane, r)); _ = frame.reset(.retain_capacity); const s = try p.render(frame.allocator()); const layer = bandLayer(p, id).?; try std.testing.expectEqual(p.tagTop(pane, r) + text_rows, layer.viewport.y); try std.testing.expectEqual(pane.band_rows, layer.viewport.h); // The body region starts under the band: nothing is drawn over it. const body = s.region(.body, id).?; try std.testing.expectEqual(layer.viewport.y + layer.viewport.h, body.rect.y); const first = try layerRow(frame.allocator(), layer, 0); try std.testing.expect(std.mem.indexOf(u8, first, "│") != null); try std.testing.expect(std.mem.indexOf(u8, first, "▶ b buffer…") != null); // The grid has the same row, where the layer is. var grid: std.ArrayList(u8) = .empty; for (s.cells[@as(usize, layer.viewport.y) * s.cols ..][layer.viewport.x..][0..layer.viewport.w]) |cell| try grid.appendSlice(frame.allocator(), cell.grapheme()); try std.testing.expect(std.mem.indexOf(u8, grid.items, "▶ b buffer…") != null); // The head names the level and says how to roll it up. try std.testing.expect(std.mem.endsWith(u8, try tagline.tagText(p, frame.allocator(), pane), " ␣ SPC ↑ roll up · ? field · esc")); // Down moves the cursor; Up back to the first row, then rolls up. p.update(.{ .key = .{ .cp = Key.down } }); try std.testing.expectEqual(@as(u8, 'c'), p.view().tag_state.hi); p.update(.{ .key = .{ .cp = Key.up } }); try std.testing.expect(p.view().tag_state.unrolled); p.update(.{ .key = .{ .cp = Key.up } }); try std.testing.expect(!p.view().tag_state.unrolled); try std.testing.expectEqual(@as(u16, 0), pane.band_rows); try std.testing.expectEqual(body_top, p.bodyTop(pane, r)); // Unrolled, Right enters the cursor's group and Left leaves it. p.update(.{ .key = .{ .cp = Key.down } }); p.update(.{ .key = .{ .cp = Key.right } }); try std.testing.expectEqualStrings("b", p.view().leader_keys[0..p.view().leader_n]); try std.testing.expect(p.view().tag_state.unrolled); p.update(.{ .key = .{ .cp = Key.left } }); try std.testing.expectEqual(@as(u8, 0), p.view().leader_n); p.update(.{ .key = .{ .cp = Key.escape } }); try std.testing.expectEqual(@as(u16, 0), pane.band_rows); try std.testing.expect(!p.view().tag_state.unrolled); } test "a pane whose body would drop below four rows under its band borrows them from its column" { const Key = pardes.Key; const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 120, .rows = 24 }); defer p.deinit(); _ = try p.setTestFile("one\n"); const top = p.view().active; p.newScratchBelow(top); const low = p.view().active; p.newScratchBelow(low); p.view().active = low; p.sync(); const before = p.view().rects[low].h; p.update(.{ .key = .{ .cp = ' ' } }); p.update(.{ .key = .{ .cp = Key.down } }); const pane = p.panes[low].?; const r = p.view().rects[low]; try std.testing.expect(r.h > before); try std.testing.expect(r.h -| pane.tag_rows >= 4); // The other panes dim; the one out of rest does not. var frame = std.heap.ArenaAllocator.init(std.testing.allocator); defer frame.deinit(); const s = try p.render(frame.allocator()); const other = p.view().rects[top]; try std.testing.expect(s.at(other.x + 3, other.y).style.dim); try std.testing.expect(!s.at(r.x + 3, r.y).style.dim); p.update(.{ .key = .{ .cp = Key.escape } }); try std.testing.expectEqual(before, p.view().rects[low].h); } test "the band's words are read-only text: B2 runs one, the tag back at rest" { const Key = pardes.Key; const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 120, .rows = 40 }); defer p.deinit(); _ = try p.setTestFile("one\n"); const id = p.view().active; var frame = std.heap.ArenaAllocator.init(std.testing.allocator); defer frame.deinit(); for ([_]u21{ ' ', 't', Key.down }) |c| p.update(.{ .key = .{ .cp = c } }); const s = try p.render(frame.allocator()); const layer = bandLayer(p, id).?; // Find `Wrap` in the grid's copy of the band. const at = found: for (0..layer.rows) |row| { const y = layer.viewport.y + row; var x: u16 = layer.viewport.x; while (x + 4 < layer.viewport.x + layer.viewport.w) : (x += 1) { const cells = s.cells[@as(usize, y) * s.cols + x ..][0..4]; if (std.mem.eql(u8, cells[0].grapheme(), "W") and std.mem.eql(u8, cells[1].grapheme(), "r") and std.mem.eql(u8, cells[2].grapheme(), "a") and std.mem.eql(u8, cells[3].grapheme(), "p")) break :found .{ x + 1, @as(u16, @intCast(y)) }; } } else return error.NoWrapInTheBand; const wrapped = p.settings.wrap; p.update(.{ .mouse = .{ .button = .middle, .kind = .press, .col = at[0], .row = at[1] } }); p.update(.{ .mouse = .{ .button = .middle, .kind = .release, .col = at[0], .row = at[1] } }); try std.testing.expect(p.settings.wrap != wrapped); try std.testing.expect(p.view().prefix == .none and !p.view().tag_state.unrolled); }