kiri-cli 0.2.0

Terminal and Neovim worker for the progressive kiri fuzzy finder
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
//! The finder's preview pane: it follows the selected candidate, fetches the
//! excerpt off the UI thread and only ever shows the result for the current
//! selection and query revision.

use std::{
    path::PathBuf,
    time::{Duration, Instant},
};

use kiri_core::{Candidate, Preview, PreviewOptions};
use ratatui::{
    style::{Color, Modifier, Style},
    text::{Line, Span},
};
use tokio::{runtime::Handle, sync::mpsc, task::AbortHandle};
use unicode_width::UnicodeWidthChar;

use super::display;

/// Selection changes settle for this long before a file is read.
const DEBOUNCE: Duration = Duration::from_millis(40);
const TAB: &str = "    ";
/// Terminals at least this wide show the pane without being asked.
const AUTO_WIDTH: u16 = 100;
/// An explicit toggle still hides the pane below this width.
const TOGGLE_WIDTH: u16 = 60;
pub(super) const SCROLL_STEP: isize = 3;

/// Candidate id and snapshot revision the preview was requested for.
pub(super) type Key = (u64, u64);

/// What is read: grep hits focus their line, files start at the top.
#[derive(Debug, Clone, PartialEq, Eq)]
struct Target {
    path: PathBuf,
    line: Option<u32>,
}

impl Target {
    fn of(candidate: &Candidate) -> Self {
        Self {
            path: crate::value_path(&candidate.value),
            line: candidate.location.map(|location| location.line),
        }
    }
}

pub(super) struct Pane {
    handle: Handle,
    sender: mpsc::UnboundedSender<(Key, Preview)>,
    receiver: mpsc::UnboundedReceiver<(Key, Preview)>,
    /// `None` follows the terminal width, `Some` is the user's choice.
    enabled: Option<bool>,
    wanted: Option<(Key, Target)>,
    loaded: Option<(Target, Preview)>,
    due: Option<Instant>,
    inflight: Option<AbortHandle>,
    scroll: isize,
    height: usize,
}

impl Pane {
    pub(super) fn new(handle: Handle) -> Self {
        let (sender, receiver) = mpsc::unbounded_channel();
        Self {
            handle,
            sender,
            receiver,
            enabled: None,
            wanted: None,
            loaded: None,
            due: None,
            inflight: None,
            scroll: 0,
            height: 0,
        }
    }

    pub(super) fn visible(&self, width: u16) -> bool {
        match self.enabled {
            None => width >= AUTO_WIDTH,
            Some(on) => on && width >= TOGGLE_WIDTH,
        }
    }

    pub(super) fn toggle(&mut self, width: u16) {
        self.enabled = Some(!self.visible(width));
    }

    pub(super) fn scroll_by(&mut self, delta: isize) {
        self.scroll = self.scroll.saturating_add(delta);
    }

    /// Follow the selection (`None`: nothing selected yet or pane hidden). A new key
    /// drops the running read and any other file's excerpt; the excerpt of the same
    /// file and line stays (typing in the files picker, a pending grep query), but is
    /// only shown while that candidate is selected again.
    pub(super) fn want(&mut self, next: Option<(Key, &Candidate)>, now: Instant) {
        if self.wanted.as_ref().map(|(key, _)| *key) == next.map(|(key, _)| key) {
            return;
        }
        self.wanted = next.map(|(key, candidate)| (key, Target::of(candidate)));
        self.abort();
        let Some((_, target)) = &self.wanted else {
            return;
        };
        if self
            .loaded
            .as_ref()
            .is_some_and(|(loaded, _)| loaded == target)
        {
            return;
        }
        self.loaded = None;
        self.scroll = 0;
        self.due = Some(now + DEBOUNCE);
    }

    /// Collect finished reads and start the debounced one. Never blocks. Returns
    /// whether the displayed preview changed.
    pub(super) fn poll(&mut self, now: Instant) -> bool {
        let mut changed = false;
        while let Ok((key, preview)) = self.receiver.try_recv() {
            changed |= self.deliver(key, preview);
        }
        if self.due.is_some_and(|due| due <= now)
            && let Some((key, target)) = &self.wanted
        {
            self.due = None;
            let options = PreviewOptions {
                line: target.line,
                before: self.height.max(10),
                after: (self.height * 2).max(30),
                ..Default::default()
            };
            let (path, key, sender) = (target.path.clone(), *key, self.sender.clone());
            self.inflight = Some(
                self.handle
                    .spawn(async move {
                        let preview = kiri_core::preview(path, options).await;
                        let _ = sender.send((key, preview));
                    })
                    .abort_handle(),
            );
        }
        changed
    }

    /// Accept a read result only for the key that is still wanted.
    fn deliver(&mut self, key: Key, preview: Preview) -> bool {
        let Some((wanted, target)) = &self.wanted else {
            return false;
        };
        if *wanted != key {
            return false;
        }
        self.inflight = None;
        self.loaded = Some((target.clone(), preview));
        true
    }

    fn abort(&mut self) {
        if let Some(read) = self.inflight.take() {
            read.abort();
        }
        self.due = None;
    }

    pub(super) fn rows(&mut self, width: usize, height: usize) -> Vec<Line<'static>> {
        self.height = height;
        if self.wanted.is_none() {
            return Vec::new();
        }
        self.loaded
            .as_ref()
            .map(|(_, preview)| render(preview, width, height, &mut self.scroll))
            .unwrap_or_default()
    }
}

impl Drop for Pane {
    fn drop(&mut self) {
        self.abort();
    }
}

/// First row of the window and the scroll offset that is actually in effect.
/// The focus row sits in the middle (or as close as the content allows), and
/// manual scrolling is clamped so the content always fills the pane.
fn window(rows: usize, height: usize, focus: Option<usize>, scroll: isize) -> (usize, isize) {
    let max_top = rows.saturating_sub(height);
    let base = focus
        .map_or(0, |focus| focus.saturating_sub(height / 2))
        .min(max_top);
    let top = base.saturating_add_signed(scroll).min(max_top);
    (top, top as isize - base as isize)
}

fn note(text: &str) -> Vec<Line<'static>> {
    vec![Line::styled(
        text.to_owned(),
        Style::default().add_modifier(Modifier::DIM),
    )]
}

/// Tabs become four spaces, control characters glyphs; cut at `width` terminal cells.
fn fit(text: &str, width: usize) -> String {
    let text = display(&text.replace('\t', TAB)).into_owned();
    let mut used = 0;
    text.chars()
        .take_while(|c| {
            used += c.width().unwrap_or(0);
            used <= width
        })
        .collect()
}

fn render(
    preview: &Preview,
    width: usize,
    height: usize,
    scroll: &mut isize,
) -> Vec<Line<'static>> {
    if let Some(error) = &preview.error {
        return note(&fit(&format!("[error: {error}]"), width));
    }
    if preview.binary {
        return note("[binary file]");
    }
    let lines = preview.lines.len();
    // A dim ellipsis row stands for the content after the window.
    let rows = lines + usize::from(preview.truncated);
    let focus = preview
        .focus
        .and_then(|line| line.checked_sub(preview.start_line))
        .map(|index| index as usize)
        .filter(|&index| index < lines);
    let (top, clamped) = window(rows, height, focus, *scroll);
    *scroll = clamped;
    let last = preview.start_line as usize + lines.saturating_sub(1);
    let digits = last.max(1).to_string().len();
    let content = width.saturating_sub(digits + 1);
    (top..rows.min(top + height))
        .map(|index| {
            let Some(text) = preview.lines.get(index) else {
                return Line::styled("…", Style::default().add_modifier(Modifier::DIM));
            };
            let number = preview.start_line as usize + index;
            let line = Line::from(vec![
                Span::styled(
                    format!("{number:>digits$} "),
                    Style::default().fg(Color::DarkGray),
                ),
                Span::raw(fit(text, content)),
            ]);
            if focus == Some(index) {
                line.style(Style::default().add_modifier(Modifier::REVERSED | Modifier::BOLD))
            } else {
                line
            }
        })
        .collect()
}

#[cfg(test)]
mod tests {
    use super::*;
    use kiri_core::Location;

    fn candidate(id: u64, path: &str, line: Option<u32>) -> Candidate {
        Candidate {
            id,
            text: path.to_owned(),
            value: path.as_bytes().to_vec(),
            size: None,
            modified: None,
            location: line.map(|line| Location { line, column: 1 }),
        }
    }

    fn excerpt(start_line: u32, count: u32, focus: Option<u32>, truncated: bool) -> Preview {
        Preview {
            path: "f".into(),
            start_line,
            lines: (start_line..start_line + count)
                .map(|n| format!("line {n}"))
                .collect(),
            focus,
            truncated,
            ..Default::default()
        }
    }

    fn text(line: &Line) -> String {
        line.spans.iter().map(|s| s.content.as_ref()).collect()
    }

    #[test]
    fn focus_stays_visible_and_centered_for_any_window() {
        for rows in 1..40 {
            for height in 1..15 {
                for focus in 0..rows {
                    let (top, scroll) = window(rows, height, Some(focus), 0);
                    assert_eq!(scroll, 0);
                    assert!(
                        (top..top + height).contains(&focus),
                        "{rows} {height} {focus}"
                    );
                    assert!(top + height <= rows.max(height));
                }
            }
        }
        // Centered when the content allows it, pinned to the ends otherwise.
        assert_eq!(window(41, 10, Some(20), 0).0, 15);
        assert_eq!(window(41, 10, Some(2), 0).0, 0);
        assert_eq!(window(41, 10, Some(40), 0).0, 31);
    }

    #[test]
    fn manual_scroll_is_clamped_to_the_content() {
        assert_eq!(window(41, 10, Some(20), 4), (19, 4));
        assert_eq!(window(41, 10, Some(20), 1000), (31, 16));
        assert_eq!(window(41, 10, Some(20), -1000), (0, -15));
        assert_eq!(window(5, 10, None, 3), (0, 0));
        let mut scroll = 1000;
        let rendered = render(&excerpt(1, 41, Some(21), false), 30, 10, &mut scroll);
        assert_eq!(scroll, 16);
        assert_eq!(text(rendered.last().unwrap()), "41 line 41");
    }

    #[test]
    fn renders_gutter_focus_tabs_and_cell_width() {
        let mut preview = excerpt(8, 3, Some(9), true);
        preview.lines[0] = "\ta\u{1}".into();
        preview.lines[1] = "日本語日本語".into();
        let rows = render(&preview, 11, 10, &mut 0);
        assert_eq!(rows.len(), 4);
        assert_eq!(text(&rows[0]), " 8     a\u{fffd}");
        // 3 gutter + 8 content cells: four full-width characters fit.
        assert_eq!(text(&rows[1]), " 9 日本語日");
        assert!(
            rows[1]
                .style
                .add_modifier
                .contains(Modifier::REVERSED | Modifier::BOLD)
        );
        assert!(!rows[0].style.add_modifier.contains(Modifier::REVERSED));
        assert_eq!(text(&rows[3]), "…");
    }

    #[test]
    fn reports_binary_and_error_files() {
        let binary = Preview {
            binary: true,
            ..Default::default()
        };
        assert_eq!(text(&render(&binary, 40, 5, &mut 0)[0]), "[binary file]");
        let error = Preview {
            error: Some("no such file".into()),
            ..Default::default()
        };
        assert_eq!(
            text(&render(&error, 40, 5, &mut 0)[0]),
            "[error: no such file]"
        );
    }

    #[tokio::test]
    async fn never_shows_a_result_for_a_superseded_selection_or_revision() {
        let mut pane = Pane::new(Handle::current());
        let now = Instant::now();
        let a = candidate(1, "a.rs", Some(3));
        let b = candidate(2, "b.rs", Some(3));
        pane.want(Some(((1, 1), &a)), now);
        pane.want(Some(((2, 1), &b)), now);
        assert!(!pane.deliver((1, 1), excerpt(1, 1, None, false)));
        assert!(pane.deliver((2, 1), excerpt(1, 1, None, false)));
        // Same hit under a new query revision keeps its excerpt; a late result
        // for the old revision is still rejected.
        pane.want(Some(((7, 2), &b)), now);
        assert!(pane.loaded.is_some());
        assert!(!pane.deliver((2, 1), excerpt(1, 2, None, false)));
        assert_eq!(pane.loaded.as_ref().unwrap().1.lines.len(), 1);
        // A different line of the same file is a different preview.
        pane.want(Some(((8, 3), &candidate(8, "b.rs", Some(9)))), now);
        assert!(pane.loaded.is_none());
        assert!(!pane.deliver((7, 2), excerpt(1, 1, None, false)));
        assert!(pane.deliver((8, 3), excerpt(1, 1, None, false)));
        // While nothing is selected (pending query, hidden pane) nothing is shown and
        // late results are rejected; the same hit selected again needs no re-read.
        pane.want(None, now);
        assert!(pane.rows(20, 5).is_empty());
        assert!(!pane.deliver((8, 3), excerpt(1, 2, None, false)));
        pane.want(Some(((9, 4), &candidate(9, "b.rs", Some(9)))), now);
        assert_eq!(pane.rows(20, 5).len(), 1);
        assert!(pane.due.is_none());
    }

    #[tokio::test]
    async fn debounces_then_reads_the_wanted_file() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("note.txt");
        std::fs::write(&path, "one\ntwo\nthree\n").unwrap();
        let mut pane = Pane::new(Handle::current());
        let start = Instant::now();
        let candidate = Candidate {
            value: path.as_os_str().as_encoded_bytes().to_vec(),
            ..candidate(1, "note.txt", Some(2))
        };
        pane.want(Some(((1, 1), &candidate)), start);
        assert!(!pane.poll(start));
        assert!(pane.inflight.is_none());
        pane.poll(start + DEBOUNCE);
        assert!(pane.inflight.is_some());
        for _ in 0..200 {
            if pane.poll(start + DEBOUNCE) {
                break;
            }
            tokio::time::sleep(Duration::from_millis(10)).await;
        }
        let (_, preview) = pane.loaded.as_ref().expect("preview was delivered");
        assert_eq!(preview.lines, ["one", "two", "three"]);
        assert_eq!(preview.focus, Some(2));
    }
}