1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
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));
}
|