diff options
| author | Gabriel Schneider <[email protected]> | 2026-11-24 20:13:20 -0300 |
|---|---|---|
| committer | Gabriel Schneider <[email protected]> | 2026-11-24 20:13:20 -0300 |
| commit | b77eac2511cb247ebae07494bbb13b2e6a1139ab (patch) | |
| tree | 3e8f3d610485b43fc0cfc904397e51725ec8b1a6 /core/Pick.zig | |
| parent | 480f36b85299fa7407c20a2d6482dd093f842bf7 (diff) | |
| download | pardes-b77eac2511cb247ebae07494bbb13b2e6a1139ab.tar.gz pardes-b77eac2511cb247ebae07494bbb13b2e6a1139ab.zip | |
Pick: a picker unrolls in the tag of the pane its Enter lands in (walk UI, pick-ui SPEC.md §3.5, §5.1-§5.3, item 1 of line D): core/Pick.zig, a picker the session's (Pardes.picks, a ring of max_lists 8, each named by a serial from the panes' counter so the disk engine's target names it as it names a pane, Stream.receive giving it its batches through Query.take, now taking either), live in a view's tag as TagState kind pick (TagState.pick its serial, host its landing pane: the asking pane when it reads, else its reader, else a pane made for it where its reader would go, an empty +Preview until the preview fills it, taken away by Esc); its sources Query.zig's producers re-presented: Find's listing from the disk engine's worker and Recent, Panes, Symbols (Query.gather, the name gathering startSource did, now shared), the jump list (Output.jumpsText, what +Jumps lists) and a list's rows handed over (a language server's answer, titled by its word), all scored by Names a frame's count at a time; Grep's lines from the worker after its pause, All the places each open text finds (as Query's All); the head ` ␣ f Find pick 3/6 ⋯` (key cells from the source's leader keys, the word, the field, cursor/total, ⋯ while scoring or searching) and a second row of the other sources' words under spines continued from the key cells (TagState.Head.cells counts the second row's spines, which Band.findSpines hangs the band from); the band's rows eleven around the cursor, made in the frame's arena for the rows shown only (O(rows shown): a Find of 50k paths makes 11 rows a frame), a place prefix in the name's tint, a path's directory dimmed, matches in the match tint; the preview is the landing pane's body: the current row's file at its line (a Grep's matches lit as its places), taken from an open pane's text or read, on the frame after the cursor stood (never on the key that moved it: Pick.busy asks the frame), a reading pane's own text set aside meanwhile (Pick.aside) and put back when it rolls up, a twinned text never previewed in; TagState.toRest rolls a live picker up first, whoever puts the tag to rest; A's API: TagState.Kind pick and its pick field, Band.takes/of's pick arm, Band.Row mark/pre/faint (drawn in draw.zig joinBand), Band.place holding a step to the band's width, TagState.point on a picker's row; TEST FIRST: Pick.zig "a picker from a held pane unrolls in a reader made for it ..." and "a picker from a reading pane unrolls in that pane, its own text set aside while it previews and back on Esc"; core-test 1014/1180 (166 skipped), 0 failed
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Diffstat (limited to 'core/Pick.zig')
| -rw-r--r-- | core/Pick.zig | 785 |
1 files changed, 785 insertions, 0 deletions
diff --git a/core/Pick.zig b/core/Pick.zig new file mode 100644 index 00000000..30cf74ab --- /dev/null +++ b/core/Pick.zig @@ -0,0 +1,785 @@ +//! A picker (pick-ui SPEC.md §5, direction E): a list of places, panes or +//! names unrolled in the tag of the pane its Enter lands in (§3.5): the +//! asking pane when it reads, else its reader, made for the picker when it +//! has none and taken away again by Esc. Its query is typed in that tag's +//! field (TagState.field), its rows hang in the band under it (Band.zig) +//! eleven at a time around the cursor, and that pane's body is the preview: +//! the current row's file at its line, its own text set aside meanwhile and +//! put back when the picker rolls up. +//! +//! The rows are Query.zig's producers', re-presented: names scored by +//! Names.zig a frame's count at a time (Find's listing from the disk +//! engine's worker, Recent, Panes, the asking text's declarations, the +//! rows a language server answered, the jump list), Grep's lines from the +//! disk engine's worker (Stream.zig: its pause, its cap). A frame makes +//! only the rows it shows, in its arena. +//! +//! A picker is the session's, named by a serial drawn from the panes' +//! counter (`id`), so the disk engine's `target` names it as it names a +//! pane; one is live in a view's tag (TagState.pick), and the last +//! `max_lists` are kept after they roll up. +const Pick = @This(); + +const std = @import("std"); +const pardes = @import("root.zig"); +const config = @import("config.zig"); +const layout = @import("layout.zig"); +const look = @import("look.zig"); +const panes = @import("panes.zig"); +const filesystem = @import("fs.zig"); +const exec = @import("exec.zig"); +const bindings = @import("bindings.zig"); +const Kind = @import("Kind.zig"); +const Names = @import("Names.zig"); +const Stream = @import("Stream.zig"); +const Trail = @import("Trail.zig"); +const TagState = @import("TagState.zig"); +const Band = @import("Band.zig"); +const Query = panes.Query; +const File = panes.File; +const Output = panes.Output; +const Pardes = pardes.Pardes; +const Pane = panes.Pane; +const Key = pardes.Key; + +/// What a picker lists (SPEC §5.1, the sources pardes has): the files +/// under the asking pane's directory, the lines of them holding the +/// query, the files opened lately, the panes, the asking text's +/// declarations, the lines holding the query in every open pane (All, its +/// places in each), the jump list, and rows handed over (a language +/// server's answer), titled by their word. +pub const Source = enum { find, grep, recent, panes, symbols, all, jumplist, list }; + +/// Each source's word in the tag and the leader keys of the builtin that +/// opens it, its key cells (`␣ f Find`). +const words = std.EnumArray(Source, struct { word: []const u8, keys: []const u8 }).init(.{ + .find = .{ .word = "Find", .keys = "f" }, + .grep = .{ .word = "Grep", .keys = "f" }, + .recent = .{ .word = "Recent", .keys = "f" }, + .panes = .{ .word = "Panes", .keys = "b" }, + .symbols = .{ .word = "Symbols", .keys = "s" }, + .all = .{ .word = "All", .keys = "" }, + .jumplist = .{ .word = "Jumplist", .keys = "j" }, + .list = .{ .word = "List", .keys = "" }, +}); + +/// The pickers kept after they roll up, for their list words and Resume. +pub const max_lists = 8; + +/// Its serial: the disk engine's target, a list word's index. +id: u32, +source: Source, +/// Its word, `Find`, or a list's own (`Refs`). +word: Kind.Buf(24) = .{}, +/// The leader keys under which its builtin is, drawn as key cells. +keys: Kind.Buf(4) = .{}, +/// Where Find and Grep look; what the rows' paths are relative to. +dir: Kind.Buf(4096) = .{}, +/// The pane that asked, and the one its Enter lands in, by serial. +owner: u32 = 0, +landing: u32 = 0, +/// The landing pane was made for it: Esc takes it away. +made: bool = false, +/// Unrolled in a view's tag now. +unrolled: bool = false, +names: Names = .{}, +/// A Grep's lines, as the disk engine sends them (Query.take). +found: std.ArrayList(Query.Found) = .empty, +found_bytes: std.ArrayList(u8) = .empty, +/// A list's rows, as they were handed over (`path:line:col text`). +rows: []u8 = &.{}, +/// The query and the cursor as it rolled up (live, they are its view's +/// field and cursor). +query: Kind.Buf(256) = .{}, +at: u32 = 0, +/// The landing pane's own text while its body previews (a reading pane: +/// put back when the picker rolls up), and its caret then. +aside: ?File.State = null, +aside_row: i32 = 0, +aside_col: i32 = 0, +/// The row the preview shows (`no_row`: none yet); asked again on the +/// frame after the cursor moves, never on the key that moved it. +shown: u32 = no_row, +fed: u64 = 0, + +const no_row = std.math.maxInt(u32); + +pub fn deinit(pk: *Pick, gpa: std.mem.Allocator) void { + pk.names.deinit(gpa); + pk.found.deinit(gpa); + pk.found_bytes.deinit(gpa); + gpa.free(pk.rows); +} + +/// Picker `id`, kept or live. +pub fn byId(p: *const Pardes, id: u32) ?*Pick { + if (id == 0) return null; + for (p.picks) |slot| if (slot) |pk| if (pk.id == id) return pk; + return null; +} + +/// The picker live in the live view's tag. +pub fn live(p: *const Pardes) ?*Pick { + const s = &p.view().tag_state; + if (s.kind != .pick) return null; + const pk = byId(p, s.pick) orelse return null; + return if (pk.unrolled) pk else null; +} + +/// A picker of `source` asked from pane `from`, unrolled in the tag of the +/// pane its Enter will land in (SPEC §3.5), its field `query`. `rows` are +/// a list's (`source` `list`, titled `word`). +pub fn open(p: *Pardes, from: usize, source: Source, word: []const u8, query: []const u8, rows: []const u8) void { + const asker = p.panes[from] orelse return; + TagState.toRest(p); + const pk = make(p, source) catch |err| return p.reportError(.at(from), "pick", err); + pk.word.set(if (word.len > 0) word else words.get(source).word); + pk.keys.set(words.get(source).keys); + pk.dir.set(Pardes.paneDir(asker)); + pk.owner = asker.serial; + pk.rows = p.gpa.dupe(u8, rows) catch |err| return p.reportError(.at(from), "pick", err); + const landing = landingFor(p, from) catch |err| return p.reportError(.at(from), "pick", err); + // The keyboard stays where it was: the landing pane is the tag's host. + p.view().active = from; + pk.landing = p.panes[landing].?.serial; + pk.made = landing != from and Trail.readerOf(p, asker) != landing and !Trail.reading(p, asker); + unroll(p, pk, query); + start(p, pk); + filter(p, pk); +} + +/// A new picker in the ring, the oldest kept one dropped for it. +fn make(p: *Pardes, source: Source) !*Pick { + var slot: ?usize = null; + for (p.picks, 0..) |s, i| if (s == null) { + slot = i; + break; + }; + if (slot == null) { + // The oldest not live. + var oldest: ?usize = null; + for (p.picks, 0..) |s, i| if (s) |pk| if (!pk.unrolled and (oldest == null or pk.id < p.picks[oldest.?].?.id)) { + oldest = i; + }; + const i = oldest orelse return error.NoPickerSlots; + p.picks[i].?.deinit(p.gpa); + p.gpa.destroy(p.picks[i].?); + p.picks[i] = null; + slot = i; + } + const pk = try p.gpa.create(Pick); + p.next_serial += 1; + pk.* = .{ .id = p.next_serial, .source = source }; + p.picks[slot.?] = pk; + return pk; +} + +/// The pane a picker from pane `from` lands in: `from` when it reads; its +/// reader when it is held and has one; else a pane made under it as its +/// reader would be, empty until the preview fills it. +fn landingFor(p: *Pardes, from: usize) !usize { + const asker = p.panes[from].?; + if (Trail.reading(p, asker)) return from; + if (Trail.readerOf(p, asker)) |r| return r; + const free = p.freeSlot() orelse return error.NoPaneSlots; + const content = try p.gpa.dupe(u8, ""); + errdefer p.gpa.free(content); + _ = try Output.open(p, free, Pardes.paneDir(asker), .preview, "", content); + layout.placeNew(p, from, from, free, .reader); + layout.compute(p); + return free; +} + +/// Picker `pk` live in the live view's tag: its host its landing pane, its +/// field `query`, the cursor where it was. +fn unroll(p: *Pardes, pk: *Pick, query: []const u8) void { + const v = p.view(); + const s = &v.tag_state; + s.kind = .pick; + s.pick = pk.id; + s.host = pk.landing; + s.field.set(query); + s.rows = .{ .at = @intCast(@min(pk.at, std.math.maxInt(u16))) }; + pk.unrolled = true; + pk.shown = no_row; + if (p.paneBySerial(pk.landing)) |id| s.previewing.set(id); +} + +/// Its source begun: the names gathered, a listing started. +fn start(p: *Pardes, pk: *Pick) void { + pk.names.reset(); + pk.found.clearRetainingCapacity(); + pk.found_bytes.clearRetainingCapacity(); + const dir = pk.dir.slice(); + switch (pk.source) { + .find => { + Stream.query(p, pk.id, .files, "", dir, .now) catch |err| return p.reportError(.at(p.view().active), "pick", err); + if (p.fs.serving) Stream.step(p); + }, + .grep, .all => {}, + .recent => Query.gather(p, &pk.names, .recent, dir, null, null), + .panes => Query.gather(p, &pk.names, .panes, dir, null, null), + .symbols => Query.gather(p, &pk.names, .symbols, dir, null, p.paneBySerial(pk.owner)), + .jumplist => { + var out: std.Io.Writer.Allocating = .init(p.gpa); + defer out.deinit(); + Output.jumpsText(p, &out.writer) catch return; + addRows(p, pk, out.written()); + }, + .list => addRows(p, pk, pk.rows), + } +} + +/// Rows of text as names, a row each, matched whole. +fn addRows(p: *Pardes, pk: *Pick, text: []const u8) void { + var lines = std.mem.splitScalar(u8, text, '\n'); + var i: u32 = 0; + while (lines.next()) |ln| : (i += 1) { + if (ln.len == 0) continue; + pk.names.add(p.gpa, ln, 0, ln.len, 0, i) catch return; + } +} + +/// The field typed: the rows again for it. A Grep's lines are the disk +/// engine's, once the typing pauses; the names are scored a frame's count +/// at a time from here. +pub fn filter(p: *Pardes, pk: *Pick) void { + const q = std.mem.trim(u8, p.view().tag_state.field.text(), " "); + p.view().tag_state.rows.at = 0; + pk.shown = no_row; + if (pk.source == .grep) { + pk.found.clearRetainingCapacity(); + pk.found_bytes.clearRetainingCapacity(); + if (q.len > 0) { + Stream.query(p, pk.id, .grep, q, pk.dir.slice(), if (p.fs.serving) .now else .typed) catch |err| return p.reportError(.at(p.view().active), "pick", err); + if (p.fs.serving) Stream.step(p); + } else if (p.stream.target == pk.id) _ = p.stream.stop(); + return; + } + if (pk.source == .all) { + // Each open text's places, found a frame's more at a time. + for (p.panes) |slot| { + const tp = slot orelse continue; + if (!searchable(tp)) continue; + if (q.len == 0) { + if (tp.places.from == pk.id) tp.places.clear(p.gpa); + } else tp.places.search(p, tp, .list, pk.id, q, false, null, false); + } + return; + } + pk.names.typed(p.gpa, q); +} + +/// A pane whose text All searches: a file's or a list's, not a query +/// pane's nor a preview's. +fn searchable(tp: *const Pane) bool { + const f = tp.file orelse return false; + if (tp.query != null) return false; + if (f.output) |o| if (o.from == .preview) return false; + return true; +} + +/// The panes All's places are in, in the order of their serials. +fn allPanes(p: *const Pardes, pk: *const Pick, out: *[pardes.MAX_PANES]usize) []usize { + var n: usize = 0; + for (p.panes, 0..) |slot, i| if (slot) |tp| if (tp.places.from == pk.id and tp.places.shows(tp) and tp.places.hits.items.len > 0) { + out[n] = i; + n += 1; + }; + std.mem.sort(usize, out[0..n], p, struct { + fn lt(pp: *const Pardes, a: usize, b: usize) bool { + return pp.panes[a].?.serial < pp.panes[b].?.serial; + } + }.lt); + return out[0..n]; +} + +/// The disk engine's rows for picker `target` (Stream.receive). +pub fn take(p: *Pardes, target: u32, kind: Stream.Kind, rows: []const u8) bool { + const pk = byId(p, target) orelse return false; + Query.take(p, pk, kind, rows); + // A listing's names, scored as they come. + if (kind == .files) pk.names.rescore(p.gpa); + return true; +} + +/// Pane `serial`'s declarations came (Stream.receiveParse): a Symbols +/// picker asked from it gathers them. +pub fn declsArrived(p: *Pardes, serial: u32) void { + for (p.picks) |slot| if (slot) |pk| if (pk.unrolled and pk.source == .symbols and pk.owner == serial and pk.names.cands.items.len == 0) { + Query.gather(p, &pk.names, .symbols, pk.dir.slice(), null, p.paneBySerial(serial)); + pk.names.typed(p.gpa, pk.names.queryText()); + pk.names.rescore(p.gpa); + }; +} + +/// After every step: each live picker's names scored on (a frame's count), +/// and on a frame of its own after the cursor stood, the preview of the +/// current row. +pub fn produceAll(p: *Pardes, tick: bool) void { + for (p.picks) |slot| if (slot) |pk| if (pk.unrolled) { + if (pk.names.busy()) pk.names.rescore(p.gpa); + if (tick) preview(p, pk); + }; +} + +/// The frames a live picker still owes: scoring, a preview (nextWake's). +pub fn busy(p: *const Pardes) bool { + for (p.picks) |slot| if (slot) |pk| if (pk.unrolled) { + if (pk.names.busy() or pk.shown != p.view().tag_state.rows.at) return true; + }; + return false; +} + +// ---- the rows ---- + +/// The rows the list has now. +pub fn count(p: *const Pardes, pk: *const Pick) usize { + switch (pk.source) { + .grep => return pk.found.items.len, + .all => { + var order: [pardes.MAX_PANES]usize = undefined; + var n: usize = 0; + for (allPanes(p, pk, &order)) |i| n += p.panes[i].?.places.hits.items.len; + return n; + }, + else => return pk.names.hits.items.len, + } +} + +/// Where a row points: a place in a file, or a pane by its serial. +const Target = union(enum) { none, place: struct { path: []const u8, at: look.Spot }, pane: u32 }; + +/// Row `i` as the band shows it and what it points at, its text in +/// `arena`. +const Row = struct { text: []const u8, pre: u16 = 0, faint: u16 = 0, dim: bool = false, marks: []const u16 = &.{}, target: Target = .none }; + +fn rowAt(p: *Pardes, pk: *const Pick, arena: std.mem.Allocator, i: usize) !Row { + const dir = pk.dir.slice(); + if (pk.source == .all) { + var order: [pardes.MAX_PANES]usize = undefined; + var k = i; + for (allPanes(p, pk, &order)) |id| { + const tp = p.panes[id].?; + const hits = tp.places.hits.items; + if (k >= hits.len) { + k -= hits.len; + continue; + } + const f = &tp.file.?; + const h = hits[k]; + const line = @import("Places.zig").lineOf(try File.lineIndex(p.gpa, f), h.start); + const ls = File.lineStart(p.gpa, f, line); + const le = std.mem.indexOfScalarPos(u8, f.content, h.start, '\n') orelse f.content.len; + const whole = f.content[ls..le]; + const lead = whole.len - std.mem.trimStart(u8, whole, " \t").len; + const name = if (f.output == null) std.Io.Dir.path.basename(f.path) else ""; + const pre = try std.fmt.allocPrint(arena, config.pane_addr ++ "{d} {s}:{d}", .{ tp.serial, name, line + 1 }); + const text = try std.fmt.allocPrint(arena, "{s} {s}", .{ pre, whole[lead..@min(whole.len, lead + 240)] }); + var marks: std.ArrayList(u16) = .empty; + var c = h.start - ls; + while (c < h.end - ls and c >= lead and pre.len + 1 + c - lead < text.len) : (c += 1) try marks.append(arena, @intCast(pre.len + 1 + c - lead)); + const target: Target = if (f.output == null) .{ .place = .{ .path = f.path, .at = .{ .line = line + 1, .col = h.start - ls + 1 } } } else .{ .pane = tp.serial }; + return .{ .text = text, .pre = @intCast(pre.len), .marks = marks.items, .target = target }; + } + return .{ .text = "" }; + } + if (pk.source == .grep) { + const fd = pk.found.items[i]; + const name = pk.found_bytes.items[fd.path..][0..fd.path_len]; + const code = pk.found_bytes.items[fd.code..][0..fd.code_len]; + const lead = code.len - std.mem.trimStart(u8, code, " \t").len; + const pre = try std.fmt.allocPrint(arena, "{f}:{d}", .{ look.quoted(name), fd.line }); + const text = try std.fmt.allocPrint(arena, "{s} {s}", .{ pre, code[lead..] }); + var marks: std.ArrayList(u16) = .empty; + var c = fd.col; + while (c < fd.end and c >= lead and pre.len + 1 + c - lead < text.len) : (c += 1) try marks.append(arena, @intCast(pre.len + 1 + c - lead)); + const path = try std.Io.Dir.path.join(arena, &.{ dir, name }); + return .{ .text = text, .pre = @intCast(pre.len), .marks = marks.items, .target = .{ .place = .{ .path = path, .at = .{ .line = fd.line, .col = fd.col + 1 } } } }; + } + var marks: [Names.max_query * 4]u16 = undefined; + var nmarks: usize = 0; + const text = pk.names.row(i, &marks, &nmarks); + const cand = pk.names.cands.items[pk.names.hits.items[i].cand]; + var row: Row = .{ .text = text, .marks = try arena.dupe(u16, marks[0..nmarks]) }; + switch (pk.source) { + .find => { + var namebuf: [4096]u8 = undefined; + const name = if (text.len > 1 and text[0] == '"' and text[text.len - 1] == '"') look.unquoted(&namebuf, text[1 .. text.len - 1]) else text; + row.faint = @intCast(if (std.mem.lastIndexOfScalar(u8, text, '/')) |k| k + 1 else 0); + row.target = .{ .place = .{ .path = try std.Io.Dir.path.join(arena, &.{ dir, name }), .at = .{} } }; + }, + .panes => { + row.pre = cand.key -| 1; + row.dim = p.paneBySerial(cand.ref) == null; + row.target = .{ .pane = cand.ref }; + }, + .symbols => { + row.pre = 6; + const owner = p.panes[p.paneBySerial(pk.owner) orelse return row] orelse return row; + const f = owner.file orelse return row; + row.target = .{ .place = .{ .path = f.path, .at = .{ .line = cand.ref } } }; + }, + .recent, .jumplist, .list, .grep, .all => { + const t = look.parsePathLine(text); + row.pre = @intCast(t.end); + if (t.path.len == 0) return row; + const path = if (t.path[0] == '/' or t.path[0] == '@') t.path else try std.Io.Dir.path.join(arena, &.{ dir, t.path }); + row.target = .{ .place = .{ .path = path, .at = t.at } }; + }, + } + return row; +} + +// ---- the tag ---- + +/// The head of the landing pane's tag (SPEC §5.3): the key cells, the +/// source's word, the query, the count `cursor/total` and `•marked`; on a +/// second row the other sources' words, under spines from the key cells. +pub fn head(p: *Pardes, arena: std.mem.Allocator, pane: *Pane) !?TagState.Head { + const pk = live(p) orelse return null; + const s = &p.view().tag_state; + var text: std.ArrayList(u8) = .empty; + var spans: std.ArrayList(TagState.Span) = .empty; + try text.append(arena, ' '); + var cells: [4][2]u32 = undefined; + var ncells: usize = 0; + // SPC's cell, then its keys': `␣ f`. + if (pk.keys.len > 0) for (0..pk.keys.len + 1) |k| { + const name = if (k == 0) "␣" else bindings.keyName(pk.keys.slice()[k - 1]); + cells[ncells] = .{ @intCast(text.items.len), @intCast(text.items.len + name.len) }; + ncells += 1; + try text.appendSlice(arena, name); + try text.append(arena, ' '); + }; + try text.appendSlice(arena, pk.word.slice()); + try text.append(arena, ' '); + const caret: u32 = @intCast(text.items.len + s.field.caret); + try text.appendSlice(arena, s.field.text()); + const n = count(p, pk); + try text.print(arena, " {d}/{d}", .{ if (n == 0) 0 else s.rows.at + 1, n }); + if (pk.names.busy() or p.stream.busyFor(pk.id)) try text.appendSlice(arena, " ⋯"); + // The second row: the spines go on through it from the key cells, + // then the other sources' words, each switching to it. + try text.append(arena, '\n'); + const prefix = try pardes.tagline.prefixIn(p, arena, pane); + const width = pardes.tagline.tagWidth(p, panes.paneIdOf(p, pane) orelse 0); + const lead = File.displayWidth(p.settings.tab, prefix) % @max(1, width); + var col: usize = 0; + for (cells[0..ncells]) |c| { + const at = lead + File.displayWidth(p.settings.tab, text.items[0..c[0]]); + while (col < at) : (col += 1) try text.append(arena, ' '); + try spans.append(arena, .{ .lo = @intCast(text.items.len), .hi = @intCast(text.items.len + "│".len), .style = .key }); + try text.appendSlice(arena, "│"); + col += 1; + } + const nspines: u8 = @intCast(spans.items.len); + try text.appendSlice(arena, if (ncells == 0) "" else " "); + var first = true; + inline for (comptime std.enums.values(Source)) |src| if (src != .list) { + if (src != pk.source) { + if (!first) try text.append(arena, ' '); + first = false; + try text.appendSlice(arena, words.get(src).word); + } + }; + for (cells[0..ncells]) |c| try spans.append(arena, .{ .lo = c[0], .hi = c[1], .style = .key }); + return .{ .text = text.items, .spans = spans.items, .cells = nspines, .caret = caret }; +} + +/// The band's rows: as many as the list will show, eleven at most, from +/// what the source has (not what the query keeps: typing never moves the +/// body). +pub fn bandRows(p: *const Pardes) u16 { + const pk = live(p) orelse return 0; + const have = if (pk.source == .grep or pk.source == .all) Band.Cursor.shown else pk.names.cands.items.len; + return @intCast(@max(1, @min(Band.Cursor.shown, have))); +} + +/// The band's steps: the rows around the cursor. +pub fn steps(p: *Pardes, arena: std.mem.Allocator) ![]Band.Step { + const pk = live(p) orelse return &.{}; + const s = &p.view().tag_state; + const n = count(p, pk); + const out = try arena.alloc(Band.Step, 1); + if (n == 0) { + const none = try arena.alloc(Band.Row, 1); + none[0] = .{ .text = if (pk.names.busy() or p.stream.busyFor(pk.id)) "⋯" else if (s.field.len == 0 and pk.source == .grep) "type to search" else "nothing matches", .dim = true }; + out[0] = .{ .rows = none }; + return out; + } + const w = s.rows.window(@intCast(@min(n, std.math.maxInt(u16)))); + const rows = try arena.alloc(Band.Row, w.hi - w.lo); + for (rows, w.lo..) |*row, i| { + const r = try rowAt(p, pk, arena, i); + row.* = .{ .text = r.text, .on = i == s.rows.at, .dim = r.dim, .pre = r.pre, .faint = r.faint, .marks = r.marks, .index = @intCast(i) }; + } + out[0] = .{ .rows = rows }; + return out; +} + +// ---- the preview ---- + +/// The landing pane's body showing the current row's place (SPEC §5.3): +/// a file at its line, the query's matches lit for a Grep. Its own text is +/// set aside the first time, put back when the picker rolls up. A file an +/// open pane shows is taken from it; any other is read. +fn preview(p: *Pardes, pk: *Pick) void { + const s = &p.view().tag_state; + if (pk.shown == s.rows.at) return; + pk.shown = s.rows.at; + if (count(p, pk) == 0) return; + var frame = std.heap.ArenaAllocator.init(p.gpa); + defer frame.deinit(); + const row = rowAt(p, pk, frame.allocator(), s.rows.at) catch return; + const place = switch (row.target) { + .place => |t| t, + else => return, + }; + const id = p.paneBySerial(pk.landing) orelse return; + const pane = p.panes[id].?; + const f = if (pane.file) |*file| file else return; + if (f.twin != 0) return; + if (!std.mem.eql(u8, f.path, place.path)) { + if (exec.kindOf(p.tape, place.path)) |kind| if (kind != .file) return; + const bytes = openText(p, place.path) orelse (p.tape.site(.preview, p.gpa, filesystem.read, .{ p, place.path }) catch return); + if (std.mem.indexOfScalar(u8, bytes[0..@min(bytes.len, 8000)], 0) != null) { + p.gpa.free(bytes); + return; + } + const path = p.gpa.dupe(u8, place.path) catch { + p.gpa.free(bytes); + return; + }; + if (pk.aside == null and !pk.made) { + const history = File.History.create(p.gpa) catch { + p.gpa.free(bytes); + p.gpa.free(path); + return; + }; + pk.aside = pane.file; + pk.aside_row = pane.body.cur_row; + pk.aside_col = pane.body.cur_col; + pane.file = .{ .path = path, .content = bytes, .output = .{ .from = .preview }, .history = history }; + } else { + const pf = &pane.file.?; + p.gpa.free(pf.path); + pf.path = path; + File.setContent(p, pf, bytes); + pf.saved_revision = pf.revision; + pf.scroll = 0; + pf.scroll_row = 0; + pf.syntax_dirty = true; + pane.places.clear(p.gpa); + } + pane.hscroll = 0; + p.sync(); + } + const keyboard = p.view().active; + defer p.view().active = keyboard; + look.clearNavigationSelection(p, pane); + const pf = &pane.file.?; + const at = place.at; + if (at.line == 0 or at.line > File.nlines(p.gpa, pf)) { + pf.scroll = 0; + pf.scroll_row = 0; + pane.body.cur_row = 0; + pane.body.cur_col = 0; + return; + } + look.focusPaneLine(p, id, at, .center); + // A Grep's matches in the file lit, as its own pane would have them. + if (pk.source == .grep) pane.places.search(p, pane, .list, pk.id, std.mem.trim(u8, s.field.text(), " "), true, null, false); +} + +/// The text of `path` as an open pane has it, copied: no read for it. +fn openText(p: *Pardes, path: []const u8) ?[]u8 { + for (p.panes) |slot| { + const tp = slot orelse continue; + const tf = tp.file orelse continue; + if (tf.output != null or !std.mem.eql(u8, tf.path, path)) continue; + return p.gpa.dupe(u8, tf.content) catch null; + } + return null; +} + +/// The landing pane as the picker found it: its own text back, or the +/// pane made for the picker taken away (`keep`: it stays, the place +/// landed on is its). +fn restore(p: *Pardes, pk: *Pick) void { + const id = p.paneBySerial(pk.landing) orelse return; + const pane = p.panes[id].?; + for (p.panes) |slot| if (slot) |tp| if (tp.places.from == pk.id) tp.places.clear(p.gpa); + if (pk.made) { + pk.made = false; + p.removePane(id, p.paneBySerial(pk.owner)) catch |err| p.reportError(.at(id), "pick", err); + return; + } + const own = pk.aside orelse return; + pk.aside = null; + File.deinit(p, pane, &pane.file.?); + pane.file = own; + pane.body.cur_row = pk.aside_row; + pane.body.cur_col = pk.aside_col; + pane.body.vsel.active = false; + p.sync(); +} + +/// The live picker rolled up (Esc, or the tag put to rest by anything): +/// its query and cursor kept for its list word and Resume, every body as +/// it was (TagState.toRest). +pub fn rollUp(p: *Pardes) void { + const pk = live(p) orelse return; + const s = &p.view().tag_state; + pk.query.set(s.field.text()); + pk.at = s.rows.at; + pk.unrolled = false; + if (p.stream.target == pk.id) _ = p.stream.stop(); + restore(p, pk); +} + +/// Every picker freed, a live one's landing pane put back first (the +/// session's end). +pub fn deinitAll(p: *Pardes) void { + for (&p.picks) |*slot| if (slot.*) |pk| { + if (pk.unrolled) { + pk.unrolled = false; + if (pk.aside) |own| if (p.paneBySerial(pk.landing)) |id| { + const pane = p.panes[id].?; + File.deinit(p, pane, &pane.file.?); + pane.file = own; + pk.aside = null; + }; + } + pk.deinit(p.gpa); + p.gpa.destroy(pk); + slot.* = null; + }; +} + +// ---- keys ---- + +/// A key in the live picker (keys.zig tagStateKey): the rows' cursor, the +/// field. Esc is the tag's (TagState.toRest rolls it up). +pub fn key(p: *Pardes, k: Key) void { + const pk = live(p) orelse return TagState.toRest(p); + const s = &p.view().tag_state; + const n: u16 = @intCast(@min(count(p, pk), std.math.maxInt(u16))); + if (s.rows.key(k, n)) return; + if (s.field.key(k)) filter(p, pk); +} + +fn testFile(p: *Pardes, tmp: *std.testing.TmpDir, name: []const u8, text: []const u8) ![]u8 { + try tmp.dir.writeFile(std.testing.io, .{ .sub_path = name, .data = text }); + var base_buf: [std.Io.Dir.max_path_bytes]u8 = undefined; + const dir = base_buf[0..try tmp.dir.realPath(std.testing.io, &base_buf)]; + return std.Io.Dir.path.join(p.gpa, &.{ dir, name }); +} + +fn tagOf(p: *Pardes, arena: std.mem.Allocator, id: usize) ![]const u8 { + return pardes.tagline.tagText(p, arena, p.panes[id].?); +} + +fn paneCount(p: *const Pardes) usize { + var n: usize = 0; + for (p.panes) |slot| n += @intFromBool(slot != null); + return n; +} + +fn settle(p: *Pardes) void { + var n: usize = 0; + while (n < 50 and (busy(p) or p.stream.busyFor(live(p).?.id))) : (n += 1) { + Stream.step(p); + p.update(.tick); + } +} + +test "a picker from a held pane unrolls in a reader made for it: its rows in the band, the body the current row's file, Esc takes the reader away" { + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 140, .rows = 50 }); + defer p.deinit(); + p.settings.jumps = .walk; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + const a_path = try testFile(p, &tmp, "alpha.zig", "const alpha = 1;\n"); + defer p.gpa.free(a_path); + const b_path = try testFile(p, &tmp, "pick_state.zig", "//! The state a picker keeps\nconst x = 2;\n"); + defer p.gpa.free(b_path); + const held = try p.setTestFile("held\n"); + _ = held; + const asker = p.view().active; + // Held: Keep. + Trail.keep(p.panes[asker].?); + const dir = std.Io.Dir.path.dirname(a_path).?; + p.gpa.free(p.panes[asker].?.file.?.path); + p.panes[asker].?.file.?.path = try std.Io.Dir.path.join(p.gpa, &.{ dir, "held.txt" }); + p.stream.engine = .walk; + const npanes = paneCount(p); + open(p, asker, .find, "", "", ""); + const pk = live(p).?; + // A reader made for it, under the asker; its tag is the picker's. + try std.testing.expectEqual(npanes + 1, paneCount(p)); + try std.testing.expect(pk.made); + const reader = p.paneBySerial(pk.landing).?; + try std.testing.expectEqual(@as(?usize, reader), TagState.hostOf(p)); + try std.testing.expectEqual(asker, p.view().active); + settle(p); + try std.testing.expectEqual(@as(usize, 2), count(p, pk)); + for ("pick") |c| p.update(.{ .key = .{ .cp = c, .text = &[_]u8{c} } }); + settle(p); + try std.testing.expectEqual(@as(usize, 1), count(p, pk)); + var frame = std.heap.ArenaAllocator.init(std.testing.allocator); + defer frame.deinit(); + const a = frame.allocator(); + const tag = try tagOf(p, a, reader); + try std.testing.expect(std.mem.indexOf(u8, tag, " ␣ f Find pick 1/1\n") != null); + try std.testing.expect(std.mem.indexOf(u8, tag, "│ Grep Recent Panes Symbols All Jumplist") != null); + // The body previews the row's file, after a frame of its own. + p.update(.tick); + try std.testing.expectEqualStrings(b_path, p.panes[reader].?.file.?.path); + _ = try p.render(a); + const r = p.view().rects[reader]; + try std.testing.expectEqualStrings("^", p.surface.at(r.x, r.y).grapheme()); + try std.testing.expect(p.panes[reader].?.band_rows >= 1); + // Esc: the reader made for it goes, the asker as it was. + p.update(.{ .key = .{ .cp = Key.escape } }); + try std.testing.expectEqual(npanes, paneCount(p)); + try std.testing.expect(live(p) == null); + try std.testing.expectEqual(TagState.Kind.rest, p.view().tag_state.kind); + try std.testing.expectEqualStrings("pick", pk.query.slice()); +} + +test "a picker from a reading pane unrolls in that pane, its own text set aside while it previews and back on Esc" { + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 140, .rows = 50 }); + defer p.deinit(); + p.settings.jumps = .walk; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + const a_path = try testFile(p, &tmp, "alpha.zig", "const alpha = 1;\n"); + defer p.gpa.free(a_path); + const b_path = try testFile(p, &tmp, "beta.zig", "one\ntwo\nthree\n"); + defer p.gpa.free(b_path); + look.lookAt(p, p.view().active, a_path); + const id = p.view().active; + try std.testing.expect(Trail.reading(p, p.panes[id].?)); + const npanes = paneCount(p); + open(p, id, .list, "Refs", "", "beta.zig:2:1 two\nalpha.zig:1:7 alpha\n"); + const pk = live(p).?; + try std.testing.expect(!pk.made); + try std.testing.expectEqual(npanes, paneCount(p)); + try std.testing.expectEqual(@as(?usize, id), TagState.hostOf(p)); + settle(p); + try std.testing.expectEqual(@as(usize, 2), count(p, pk)); + try std.testing.expectEqualStrings(b_path, p.panes[id].?.file.?.path); + try std.testing.expectEqual(@as(i32, 1), p.panes[id].?.body.cur_row); + try std.testing.expect(pk.aside != null); + // Down: the next row's file, on the frame after. + p.update(.{ .key = .{ .cp = Key.down } }); + try std.testing.expectEqualStrings(b_path, p.panes[id].?.file.?.path); + p.update(.tick); + try std.testing.expectEqualStrings(a_path, p.panes[id].?.file.?.path); + p.update(.{ .key = .{ .cp = Key.escape } }); + try std.testing.expect(pk.aside == null); + try std.testing.expectEqualStrings(a_path, p.panes[id].?.file.?.path); + try std.testing.expect(p.panes[id].?.file.?.output == null); + try std.testing.expectEqual(npanes, paneCount(p)); +} |
