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
use crate::{selectable::SelectableItem, ui::ui};
use crossterm::{
event::{self, DisableMouseCapture, EnableMouseCapture, Event, KeyCode, KeyModifiers},
execute,
terminal::{disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen},
};
use nucleo::{
pattern::{CaseMatching, Normalization},
Config, Injector, Nucleo, Snapshot,
};
use ratatui::{prelude::CrosstermBackend, Terminal};
use std::{
error,
fmt::Display,
io,
ops::{Range, RangeInclusive},
sync::Arc,
thread::JoinHandle,
time::Duration,
};
pub type AppResult<T> = std::result::Result<T, Box<dyn error::Error>>;
// TODO convert static to a proper lifetime
pub struct Picker<T>
where
T: Sync + Send + 'static,
{
pub matcher: Nucleo<SelectableItem<T>>,
pub first_visible_item_index: u32,
pub current_index: u32,
pub height: u16,
pub query: String,
pub query_index: usize,
pub join_handles: Vec<JoinHandle<()>>,
}
impl<T: Sync + Send + Display> Default for Picker<T> {
fn default() -> Self {
Self::new()
}
}
// TODO maybe expose the Nucleo update callback
impl<T> Picker<T>
where
T: Sync + Send + Display,
{
pub fn new() -> Self {
let matcher = Nucleo::new(Config::DEFAULT, Arc::new(|| {}), None, 1);
Picker {
matcher,
first_visible_item_index: 0,
current_index: 0,
height: 0,
query: String::new(),
query_index: 0,
join_handles: Vec::new(),
}
}
pub fn inject_items<F>(&self, f: F)
where
F: FnOnce(&Injector<SelectableItem<T>>),
{
let injector = self.matcher.injector();
f(&injector);
}
pub fn inject_items_threaded<F>(&mut self, f: F)
where
F: FnOnce(&Injector<SelectableItem<T>>) + Send + 'static,
{
let injector = self.matcher.injector();
let handle = std::thread::spawn(move || {
f(&injector);
});
self.join_handles.push(handle);
}
pub fn join_finished_threads(&mut self) -> usize {
let mut remaining_handles = Vec::new();
for handle in self.join_handles.drain(..) {
if handle.is_finished() {
// Thread is finished, join it (ignore any errors)
let _ = handle.join();
} else {
// Thread is still running, keep it
remaining_handles.push(handle);
}
}
self.join_handles = remaining_handles;
self.join_handles.len()
}
pub fn running_threads(&self) -> usize {
self.join_handles.len()
}
pub fn item_count(&self) -> u32 {
self.matcher.snapshot().item_count()
}
pub fn height(&self) -> u16 {
// truncation should be fine since we are getting the min and we don't want this to panic
self.height.min(self.item_count() as u16)
}
pub fn tick(&mut self, timeout: u64) -> nucleo::Status {
// TODO ensure that this is the correct place to call the thread join
let _running_indexers = self.join_finished_threads();
self.matcher.tick(timeout)
}
pub fn snapshot(&self) -> &Snapshot<SelectableItem<T>> {
self.matcher.snapshot()
}
pub(crate) fn first_visible_item_index(&self) -> u32 {
self.first_visible_item_index
}
pub(crate) fn last_visible_item_index(&self) -> u32 {
// TODO probable need to remove the -1 here
(self.first_visible_item_index + (self.height() as u32))
// limiting this so we don't get an out of bounds error before loading items or when there are no matches
.min(self.last_item_index())
}
// this should return a valid range that does not exceed the maximum number of items
pub(crate) fn visible_item_range(&mut self) -> RangeInclusive<u32> {
// we must use an inclusive range here or we'll be missing items that will cause some weird issues
self.first_visible_item_index()..=self.last_visible_item_index()
}
pub fn matched_items(&mut self) -> Vec<&SelectableItem<T>> {
// return if the matcher is empty or passing an inclusive range to matched_items will panic
if self.snapshot().item_count() == 0 {
return vec![];
}
// can't inline this or we'll have ownership issues
let item_range = self.visible_item_range();
self.snapshot()
// is important to restrict this to the visible range or things get really slow with lots of items
.matched_items(item_range)
.map(|i| i.data)
.collect()
}
pub(crate) fn update_height(&mut self, height: u16) {
self.height = height;
}
pub(crate) fn selected_items(&self) -> Vec<&T> {
// NOTE: matched_items is not factored out due to ownership issues
let selected_items: Vec<&T> = self
.snapshot()
.matched_items(..)
.filter(|i| i.data.is_selected())
.map(|i| i.data.value())
.collect();
if !selected_items.is_empty() {
selected_items
} else {
self.snapshot()
.matched_items(..)
.nth(self.current_index as usize)
.map(|i| vec![i.data.value()])
.unwrap_or_default()
}
}
/// Returns the total number of matched items
pub fn matched_item_count(&self) -> u32 {
self.snapshot().matched_item_count()
}
/// Returns the index of the last matched item
// TODO maybe return an Option<u32> here if there are not items. It might improve flow control
pub fn last_item_index(&self) -> u32 {
self.snapshot().matched_item_count().saturating_sub(1)
}
// this function should constrain the range to valid values and slide the window if necessary
// NOTE: we're taking an i64 here so we can handle negative values without truncating on the upper end of inputs
pub fn set_current_index(&mut self, new_index: i64, wrap_around: bool) -> u32 {
// ensure that the index is in range
self.current_index = if new_index < 0 {
if wrap_around {
self.last_item_index()
} else {
0
}
} else if new_index > self.last_item_index().into() {
if wrap_around {
0
} else {
self.last_item_index()
}
} else {
new_index.try_into().unwrap()
};
self.set_item_window(self.current_index.into(), wrap_around);
self.current_index
}
// TODO maybe make new_index into a u32
pub fn set_item_window(&mut self, new_index: i64, wrap_around: bool) {
// ensure that the window contains the index
// TODO handle wrapping
if new_index < self.first_visible_item_index.into() {
self.first_visible_item_index = if new_index < 0 {
if wrap_around {
self.last_item_index().saturating_sub(self.height().into())
} else {
0
}
} else {
new_index.try_into().unwrap()
// self.first_visible_item_index().saturating_sub(1)
}
// these are unsigned ints so they shouldn't be able to go below zero
} else if new_index > self.last_visible_item_index().into() {
self.first_visible_item_index = if new_index > self.last_item_index().into() {
if wrap_around {
0
} else {
self.last_item_index().saturating_sub(self.height().into())
}
} else {
new_index as u32 - (self.height() as u32)
}
}
// otherwise we don't need to shift the window
}
pub fn next(&mut self) {
let indices = self.last_item_index();
if indices == 0 {
return;
}
self.set_current_index((self.current_index + 1).into(), true);
}
fn next_page(&mut self) {
let indices = self.last_visible_item_index();
if indices == 0 {
return;
}
let next_page_index = if self.current_index < self.last_visible_item_index() {
self.last_visible_item_index()
} else {
self.current_index + self.height() as u32
};
self.set_current_index(next_page_index.into(), false);
}
fn end(&mut self) {
let indices = self.last_item_index();
if indices == 0 {
return;
}
self.set_current_index(indices.into(), false);
}
pub fn previous(&mut self) {
let indices = self.last_item_index();
if indices == 0 {
return;
}
self.set_current_index(self.current_index as i64 - 1, true);
}
pub fn previous_page(&mut self) {
let indices = self.last_item_index();
if indices == 0 {
return;
}
let previous_page_index = if self.current_index > self.first_visible_item_index() {
self.first_visible_item_index().into()
} else {
self.current_index as i64 - self.height() as i64
};
self.set_current_index(previous_page_index, false);
}
fn home(&mut self) {
let indices = self.last_item_index();
if indices == 0 {
return;
}
self.set_current_index(0, false);
}
pub fn toggle_selected(&mut self) {
let snapshot = self.snapshot();
if snapshot.matched_item_count() == 0 {
return;
}
// get the currently selected item and toggle it's selected state
if let Some(i) = snapshot.get_matched_item(self.current_index) {
i.data.toggle_selected();
};
}
pub(crate) fn append_to_query(&mut self, key: char) {
// TODO constrain selected item to match range
if self.query_index >= self.query.len() {
self.query.push(key);
} else {
self.query.insert(self.query_index, key);
}
self.matcher.pattern.reparse(
0,
&self.query,
CaseMatching::Smart,
Normalization::Smart,
true,
);
// ensure that the selection stays in range
// TODO find a better way, ideally one that preserves the position as much as possible
self.set_current_index(0, false);
}
pub(crate) fn jump_word_forward(&mut self) {
let query_len = self.query.len();
if self.query_index >= query_len {
return;
}
// Start from current position
let remaining = &self.query[self.query_index..];
// Find the next word boundary
let mut chars = remaining.char_indices();
// Skip the current word if we're in the middle of one
while let Some((i, c)) = chars.next() {
if c.is_whitespace() {
break;
}
if i == remaining.len() - 1 {
// If we reach the end of the string, set index to the end
self.query_index = query_len;
return;
}
}
// Skip any whitespace
let mut word_start = 0;
while let Some((i, c)) = chars.next() {
if !c.is_whitespace() {
word_start = i;
break;
}
if i == remaining.len() - 1 {
// If we reach the end of the string, set index to the end
self.query_index = query_len;
return;
}
}
// Move to the start of the next word
self.query_index += word_start;
}
pub(crate) fn jump_word_backward(&mut self) {
if self.query_index == 0 {
return;
}
// Get the part of the query before the current position
let before_cursor = &self.query[..self.query_index];
// Find the previous word boundary
let chars: Vec<char> = before_cursor.chars().collect();
let mut pos = chars.len() - 1;
// Skip any whitespace before the cursor
while pos > 0 && chars[pos].is_whitespace() {
pos -= 1;
}
// Skip the current word
while pos > 0 && !chars[pos].is_whitespace() {
pos -= 1;
}
// If we stopped at whitespace and we're not at the beginning, move to the next char
if pos > 0 && chars[pos].is_whitespace() {
pos += 1;
}
self.query_index = pos;
}
pub(crate) fn delete_word_backward(&mut self) {
if self.query_index == 0 {
return;
}
// Get the part of the query before the current position
let before_cursor = &self.query[..self.query_index];
// Find the previous word boundary
let chars: Vec<char> = before_cursor.chars().collect();
let mut pos = chars.len() - 1;
// Skip any whitespace before the cursor
while pos > 0 && chars[pos].is_whitespace() {
pos -= 1;
}
// Skip the current word
while pos > 0 && !chars[pos].is_whitespace() {
pos -= 1;
}
// If we stopped at whitespace and we're not at the beginning, move to the next char
if pos > 0 && chars[pos].is_whitespace() {
pos += 1;
}
// Remove the characters between the new position and the old cursor position
self.query = format!("{}{}", &self.query[..pos], &self.query[self.query_index..]);
self.query_index = pos;
// Update the matcher
self.matcher.pattern.reparse(
0,
&self.query,
CaseMatching::Smart,
Normalization::Smart,
false,
);
}
pub(crate) fn delete_word_forward(&mut self) {
let query_len = self.query.len();
if self.query_index >= query_len {
return;
}
// Start from current position
let remaining = &self.query[self.query_index..];
// Find the next word boundary
let mut chars = remaining.char_indices();
let mut end_pos = query_len;
// If we're at the beginning of a word, delete that word
if let Some((_, first_char)) = chars.next() {
if !first_char.is_whitespace() {
// Skip until we hit whitespace or end
while let Some((i, c)) = chars.next() {
if c.is_whitespace() {
end_pos = self.query_index + i;
break;
}
}
} else {
// Skip whitespace
while let Some((_i, c)) = chars.next() {
if !c.is_whitespace() {
// Then skip until next whitespace or end
while let Some((j, c2)) = chars.next() {
if c2.is_whitespace() {
end_pos = self.query_index + j;
break;
}
}
break;
}
}
}
}
// Remove the characters between the cursor position and the end position
self.query = format!(
"{}{}",
&self.query[..self.query_index],
&self.query[end_pos..]
);
// Update the matcher
self.matcher.pattern.reparse(
0,
&self.query,
CaseMatching::Smart,
Normalization::Smart,
false,
);
}
pub(crate) fn delete_to_end(&mut self) {
if self.query_index >= self.query.len() {
return;
}
// Truncate the query at the cursor position
self.query.truncate(self.query_index);
// Update the matcher
self.matcher.pattern.reparse(
0,
&self.query,
CaseMatching::Smart,
Normalization::Smart,
false,
);
}
pub(crate) fn delete_from_query(&mut self) {
if self.query_index > 0 && !self.query.is_empty() {
// Remove the character before the cursor
self.query.remove(self.query_index - 1);
}
self.matcher.pattern.reparse(
0,
&self.query,
CaseMatching::Smart,
Normalization::Smart,
false,
);
}
pub(crate) fn clear_query(&mut self) {
self.query.clear();
// TODO seems like there should be a better way to clear the query
self.matcher.pattern.reparse(
0,
&self.query,
CaseMatching::Smart,
Normalization::Smart,
false,
);
}
pub fn run(&mut self) -> AppResult<Vec<&T>> {
// Setup terminal
enable_raw_mode()?;
// TODO should we allow the caller to pass any arbitrary stream?
let mut stream = io::stderr();
execute!(stream, EnterAlternateScreen, EnableMouseCapture)?;
let backend = CrosstermBackend::new(stream);
let mut terminal = Terminal::new(backend)?;
let result = self.run_loop(&mut terminal);
// Restore terminal
disable_raw_mode()?;
execute!(
terminal.backend_mut(),
LeaveAlternateScreen,
DisableMouseCapture
)?;
terminal.show_cursor()?;
result
}
pub(crate) fn run_loop<B: ratatui::backend::Backend>(
&mut self,
terminal: &mut Terminal<B>,
) -> AppResult<Vec<&T>> {
// draw the UI once initially before any timeouts so it appears to the user immediately
terminal.draw(|f| ui(f, self))?;
let mut event_received = false;
// enter the actual event loop
loop {
let status = self.tick(10);
// ensure that we update the UI, even when we aren't receiving events from the user
if event::poll(Duration::from_millis(16))? {
// read the event that is ready (normally read blocks, but we're polling until it's ready)
if let Ok(Event::Key(key)) = event::read() {
event_received = true;
match (key.code, key.modifiers) {
(KeyCode::Char(key), KeyModifiers::NONE)
| (KeyCode::Char(key), KeyModifiers::SHIFT) => {
self.append_to_query(key);
// NOTE: this probably doesn't need to saturate, that would require an absurdly long query
self.query_index = self.query_index.saturating_add(1);
}
(KeyCode::Backspace, KeyModifiers::NONE) => {
self.delete_from_query();
// NOTE: this needs to saturate to handle deleting when the query is empty
self.query_index = self.query_index.saturating_sub(1);
}
// TODO find out if it's a local keybinding that's preventing `Ctrl + Backspace` from working or if it's actually a bug
(KeyCode::Backspace, KeyModifiers::CONTROL)
| (KeyCode::Backspace, KeyModifiers::ALT) => {
self.delete_word_backward();
}
(KeyCode::Right, KeyModifiers::NONE) => {
// NOTE: this probably doesn't need to saturate, that would require an absurdly long query
self.query_index = self.query_index.saturating_add(1);
}
(KeyCode::Right, KeyModifiers::CONTROL)
| (KeyCode::Right, KeyModifiers::ALT) => {
self.jump_word_forward();
}
(KeyCode::Left, KeyModifiers::NONE) => {
// NOTE: this needs to saturate to handle deleting when the query is empty
self.query_index = self.query_index.saturating_sub(1);
}
(KeyCode::Left, KeyModifiers::CONTROL)
| (KeyCode::Left, KeyModifiers::ALT) => {
self.jump_word_backward();
}
(KeyCode::Delete, KeyModifiers::CONTROL)
| (KeyCode::Delete, KeyModifiers::ALT) => {
self.delete_word_forward();
}
(KeyCode::Esc, KeyModifiers::NONE) => {
return Ok(vec![]);
}
(KeyCode::Char('u'), KeyModifiers::CONTROL) => {
self.clear_query();
self.query_index = 0;
}
(KeyCode::Char('c'), KeyModifiers::CONTROL) => {
return Ok(vec![]);
}
(KeyCode::Char('a'), KeyModifiers::CONTROL) => {
self.query_index = 0;
}
(KeyCode::Char('e'), KeyModifiers::CONTROL) => {
self.query_index = self.query.len();
}
(KeyCode::Char('k'), KeyModifiers::CONTROL) => {
self.delete_to_end();
}
(KeyCode::Enter, KeyModifiers::NONE) => {
// Print selected items and exit
return Ok(self.selected_items());
}
(KeyCode::Down, KeyModifiers::NONE) => {
self.next();
}
(KeyCode::PageDown, KeyModifiers::NONE) => {
self.next_page();
}
(KeyCode::End, KeyModifiers::NONE) => {
self.end();
}
(KeyCode::Up, KeyModifiers::NONE) => {
self.previous();
}
(KeyCode::PageUp, KeyModifiers::NONE) => {
self.previous_page();
}
(KeyCode::Home, KeyModifiers::NONE) => {
self.home();
}
(KeyCode::Tab, KeyModifiers::NONE) => {
self.toggle_selected();
self.next();
}
// ignore other key codes
_ => {
event_received = false;
}
}
};
}
// if necessary, redraw the screen
if event_received || status.changed || status.running {
// TODO need to debounce events here
terminal.draw(|f| ui(f, self))?;
}
}
}
}