1#![allow(unused)]
5
6use super::{Line, Span, Style, Text};
7use bitflags::bitflags;
8
9use ratatui::style::Modifier;
10use std::{
11 borrow::Cow,
12 sync::{
13 Arc,
14 atomic::{self, AtomicU32},
15 },
16};
17use unicode_segmentation::UnicodeSegmentation;
18use unicode_width::UnicodeWidthStr;
19
20use super::{injector::WorkerInjector, query::PickerQuery};
21use crate::{
22 SSS,
23 nucleo::Render,
24 utils::text::{apply_style_at, plain_text, wrap_text},
25};
26use cli_boilerplate_automation::text::StrExt;
27
28type ColumnFormatFn<T> = Box<dyn for<'a> Fn(&'a T) -> Text<'a> + Send + Sync>;
29pub struct Column<T> {
30 pub name: Arc<str>,
31 pub(super) format: ColumnFormatFn<T>,
32 pub(super) filter: bool,
34}
35
36impl<T> Column<T> {
37 pub fn new_boxed(name: impl Into<Arc<str>>, format: ColumnFormatFn<T>) -> Self {
38 Self {
39 name: name.into(),
40 format,
41 filter: true,
42 }
43 }
44
45 pub fn new<F>(name: impl Into<Arc<str>>, f: F) -> Self
46 where
47 F: for<'a> Fn(&'a T) -> Text<'a> + SSS,
48 {
49 Self {
50 name: name.into(),
51 format: Box::new(f),
52 filter: true,
53 }
54 }
55
56 pub fn without_filtering(mut self) -> Self {
58 self.filter = false;
59 self
60 }
61
62 pub(super) fn format<'a>(&self, item: &'a T) -> Text<'a> {
63 (self.format)(item)
64 }
65
66 pub(super) fn format_text<'a>(&self, item: &'a T) -> Cow<'a, str> {
68 Cow::Owned(plain_text(&(self.format)(item)))
69 }
70}
71
72pub struct Worker<T>
76where
77 T: SSS,
78{
79 pub(crate) nucleo: nucleo::Nucleo<T>,
81 pub(super) query: PickerQuery,
83 pub(super) col_indices_buffer: Vec<u32>,
86 pub(crate) columns: Arc<[Column<T>]>,
87
88 pub(super) version: Arc<AtomicU32>,
90 column_options: Vec<ColumnOptions>,
92}
93
94bitflags! {
100 #[derive(Default, Clone, Debug)]
101 pub struct ColumnOptions: u8 {
102 const Optional = 1 << 0;
103 const OrUseDefault = 1 << 2;
104 }
105}
106
107impl<T> Worker<T>
108where
109 T: SSS,
110{
111 pub fn new(columns: impl IntoIterator<Item = Column<T>>, default_column: usize) -> Self {
113 let columns: Arc<[_]> = columns.into_iter().collect();
114 let matcher_columns = columns.iter().filter(|col| col.filter).count() as u32;
115
116 let inner = nucleo::Nucleo::new(
117 nucleo::Config::DEFAULT,
118 Arc::new(|| {}),
119 None,
120 matcher_columns,
121 );
122
123 Self {
124 nucleo: inner,
125 col_indices_buffer: Vec::with_capacity(128),
126 query: PickerQuery::new(columns.iter().map(|col| &col.name).cloned(), default_column),
127 column_options: vec![ColumnOptions::default(); columns.len()],
128 columns,
129 version: Arc::new(AtomicU32::new(0)),
130 }
131 }
132
133 #[cfg(feature = "experimental")]
134 pub fn set_column_options(&mut self, index: usize, options: ColumnOptions) {
135 if options.contains(ColumnOptions::Optional) {
136 self.nucleo
137 .pattern
138 .configure_column(index, nucleo::pattern::Variant::Optional)
139 }
140
141 self.column_options[index] = options
142 }
143
144 pub fn injector(&self) -> WorkerInjector<T> {
145 WorkerInjector {
146 inner: self.nucleo.injector(),
147 columns: self.columns.clone(),
148 version: self.version.load(atomic::Ordering::Relaxed),
149 picker_version: self.version.clone(),
150 }
151 }
152
153 pub fn find(&mut self, line: &str) {
154 let old_query = self.query.parse(line);
155 if self.query == old_query {
156 return;
157 }
158 for (i, column) in self
159 .columns
160 .iter()
161 .filter(|column| column.filter)
162 .enumerate()
163 {
164 let pattern = self
165 .query
166 .get(&column.name)
167 .map(|s| &**s)
168 .unwrap_or_else(|| {
169 self.column_options[i]
170 .contains(ColumnOptions::OrUseDefault)
171 .then(|| self.query.primary_column_query())
172 .flatten()
173 .unwrap_or_default()
174 });
175
176 let old_pattern = old_query
177 .get(&column.name)
178 .map(|s| &**s)
179 .unwrap_or_else(|| {
180 self.column_options[i]
181 .contains(ColumnOptions::OrUseDefault)
182 .then(|| {
183 let name = self.query.primary_column_name()?;
184 old_query.get(name).map(|s| &**s)
185 })
186 .flatten()
187 .unwrap_or_default()
188 });
189
190 if pattern == old_pattern {
192 continue;
193 }
194 let is_append = pattern.starts_with(old_pattern);
195
196 self.nucleo.pattern.reparse(
197 i,
198 pattern,
199 nucleo::pattern::CaseMatching::Smart,
200 nucleo::pattern::Normalization::Smart,
201 is_append,
202 );
203 }
204 }
205
206 pub fn get_nth(&self, n: u32) -> Option<&T> {
208 self.nucleo
209 .snapshot()
210 .get_matched_item(n)
211 .map(|item| item.data)
212 }
213
214 pub fn new_snapshot(nucleo: &mut nucleo::Nucleo<T>) -> (&nucleo::Snapshot<T>, Status) {
215 let nucleo::Status { changed, running } = nucleo.tick(10);
216 let snapshot = nucleo.snapshot();
217 (
218 snapshot,
219 Status {
220 item_count: snapshot.item_count(),
221 matched_count: snapshot.matched_item_count(),
222 running,
223 changed,
224 },
225 )
226 }
227
228 pub fn raw_results(&self) -> impl ExactSizeIterator<Item = &T> + DoubleEndedIterator + '_ {
229 let snapshot = self.nucleo.snapshot();
230 snapshot.matched_items(..).map(|item| item.data)
231 }
232
233 pub fn counts(&self) -> (u32, u32) {
235 let snapshot = self.nucleo.snapshot();
236 (snapshot.matched_item_count(), snapshot.item_count())
237 }
238
239 #[cfg(feature = "experimental")]
240 pub fn set_stability(&mut self, threshold: u32) {
241 self.nucleo.set_stability(threshold);
242 }
243
244 #[cfg(feature = "experimental")]
245 pub fn get_stability(&self) -> u32 {
246 self.nucleo.get_stability()
247 }
248
249 pub fn restart(&mut self, clear_snapshot: bool) {
250 self.nucleo.restart(clear_snapshot);
251 }
252}
253
254#[derive(Debug, Default, Clone)]
255pub struct Status {
256 pub item_count: u32,
257 pub matched_count: u32,
258 pub running: bool,
259 pub changed: bool,
260}
261
262#[derive(Debug, thiserror::Error)]
263pub enum WorkerError {
264 #[error("the matcher injector has been shut down")]
265 InjectorShutdown,
266 #[error("{0}")]
267 Custom(&'static str),
268}
269
270pub type WorkerResults<'a, T> = Vec<(Vec<Text<'a>>, &'a T, u16)>;
272
273impl<T: SSS> Worker<T> {
274 pub fn results(
282 &mut self,
283 start: u32,
284 end: u32,
285 width_limits: &[u16],
286 highlight_style: Style,
287 matcher: &mut nucleo::Matcher,
288 ) -> (WorkerResults<'_, T>, Vec<u16>, Status) {
289 let (snapshot, status) = Self::new_snapshot(&mut self.nucleo);
290
291 let mut widths = vec![0u16; self.columns.len()];
292
293 let iter =
294 snapshot.matched_items(start.min(status.matched_count)..end.min(status.matched_count));
295
296 let table = iter
297 .map(|item| {
298 let mut widths = widths.iter_mut();
299 let mut height = 0;
300
301 let row = self
302 .columns
303 .iter()
304 .enumerate()
305 .zip(width_limits.iter().chain(std::iter::repeat(&u16::MAX)))
306 .map(|((col_idx, column), &width_limit)| {
307 let max_width = widths.next().unwrap();
308 let cell = column.format(item.data);
309
310 if width_limit == 0 {
312 return Text::default();
313 }
314
315 let (cell, width) = if column.filter {
316 render_cell(
317 cell,
318 col_idx,
319 snapshot,
320 &item,
321 matcher,
322 highlight_style,
323 width_limit,
324 &mut self.col_indices_buffer,
325 )
326 } else if width_limit != u16::MAX {
327 let (cell, wrapped) = wrap_text(cell, width_limit - 1);
328
329 let width = if wrapped {
330 width_limit as usize
331 } else {
332 cell.width()
333 };
334 (cell, width)
335 } else {
336 let width = cell.width();
337 (cell, width)
338 };
339
340 if width as u16 > *max_width {
342 *max_width = width as u16;
343 }
344
345 if cell.height() as u16 > height {
346 height = cell.height() as u16;
347 }
348
349 cell
350 });
351
352 (row.collect(), item.data, height)
353 })
354 .collect();
355
356 for (w, c) in widths.iter_mut().zip(self.columns.iter()) {
358 let name_width = c.name.width() as u16;
359 if *w != 0 {
360 *w = (*w).max(name_width);
361 }
362 }
363
364 (table, widths, status)
365 }
366
367 pub fn exact_column_match(&mut self, column: &str) -> Option<&T> {
368 let (i, col) = self
369 .columns
370 .iter()
371 .enumerate()
372 .find(|(_, c)| column == &*c.name)?;
373
374 let query = self.query.get(column).map(|s| &**s).or_else(|| {
375 self.column_options[i]
376 .contains(ColumnOptions::OrUseDefault)
377 .then(|| self.query.primary_column_query())
378 .flatten()
379 })?;
380
381 let snapshot = self.nucleo.snapshot();
382 snapshot.matched_items(..).find_map(|item| {
383 let content = col.format_text(item.data);
384 if content.as_str() == query {
385 Some(item.data)
386 } else {
387 None
388 }
389 })
390 }
391
392 pub fn format_with<'a>(&'a self, item: &'a T, col: &str) -> Option<Cow<'a, str>> {
393 self.columns
394 .iter()
395 .find(|c| &*c.name == col)
396 .map(|c| c.format_text(item))
397 }
398}
399
400fn render_cell<T: SSS>(
401 cell: Text<'_>,
402 col_idx: usize,
403 snapshot: &nucleo::Snapshot<T>,
404 item: &nucleo::Item<T>,
405 matcher: &mut nucleo::Matcher,
406 highlight_style: Style,
407 width_limit: u16,
408 col_indices_buffer: &mut Vec<u32>,
409) -> (Text<'static>, usize) {
410 let mut cell_width = 0;
411 let mut wrapped = false;
412
413 let indices_buffer = col_indices_buffer;
415 indices_buffer.clear();
416 snapshot.pattern().column_pattern(col_idx).indices(
417 item.matcher_columns[col_idx].slice(..),
418 matcher,
419 indices_buffer,
420 );
421 indices_buffer.sort_unstable();
422 indices_buffer.dedup();
423 let mut indices = indices_buffer.drain(..);
424
425 let mut lines = vec![];
426 let mut next_highlight_idx = indices.next().unwrap_or(u32::MAX);
427 let mut grapheme_idx = 0u32;
428
429 for line in cell {
430 let mut current_spans = Vec::new();
431 let mut current_span = String::new();
432 let mut current_style = Style::default();
433 let mut current_width = 0;
434
435 for span in line {
436 if width_limit != u16::MAX {}
443 let mut graphemes = span.content.graphemes(true).peekable();
444 while let Some(grapheme) = graphemes.next() {
445 let grapheme_width = UnicodeWidthStr::width(grapheme);
446
447 if width_limit != u16::MAX {
448 if current_width + grapheme_width > (width_limit - 1) as usize && {
449 grapheme_width > 1 || graphemes.peek().is_some()
450 } {
451 current_spans.push(Span::styled(current_span, current_style));
452 current_spans.push(Span::styled(
453 "↵",
454 Style::default().add_modifier(Modifier::DIM),
455 ));
456 lines.push(Line::from(current_spans));
457
458 current_spans = Vec::new();
459 current_span = String::new();
460 current_width = 0;
461 wrapped = true;
462 }
463 }
464
465 let style = if grapheme_idx == next_highlight_idx {
466 next_highlight_idx = indices.next().unwrap_or(u32::MAX);
467 span.style.patch(highlight_style)
468 } else {
469 span.style
470 };
471
472 if style != current_style {
473 if !current_span.is_empty() {
474 current_spans.push(Span::styled(current_span, current_style))
475 }
476 current_span = String::new();
477 current_style = style;
478 }
479 current_span.push_str(grapheme);
480 grapheme_idx += 1;
481 current_width += grapheme_width;
482 }
483 }
484
485 current_spans.push(Span::styled(current_span, current_style));
486 lines.push(Line::from(current_spans));
487 cell_width = cell_width.max(current_width);
488 grapheme_idx += 1; }
490
491 (
492 Text::from(lines),
493 if wrapped {
494 width_limit as usize
495 } else {
496 cell_width
497 },
498 )
499}