Skip to main content

cdt_view/
run.rs

1//! Terminal lifecycle and the key loop. `on_key` holds the whole key table and
2//! touches no IO, so the bindings are testable without a terminal.
3use std::io;
4use std::path::PathBuf;
5use std::time::Duration;
6
7use ratatui::crossterm::event::{self, Event, KeyCode, KeyEventKind};
8use ratatui::crossterm::execute;
9use ratatui::crossterm::terminal::{
10    EnterAlternateScreen, LeaveAlternateScreen, disable_raw_mode, enable_raw_mode,
11};
12use ratatui::prelude::*;
13
14use crate::Res;
15use crate::app::{App, Mode};
16use crate::view;
17
18/// What a keypress asks the loop to do. `None` from `on_key` means "redraw".
19#[derive(Debug, PartialEq)]
20pub(crate) enum Action {
21    Quit,
22    Pick(PathBuf),
23}
24
25/// Puts the terminal back on the way out, on every path: a clean pick, an
26/// early `?`, or a panic unwinding through the loop. Without it a crash leaves
27/// the caller's shell in raw mode on the alternate screen.
28struct Restore;
29
30impl Drop for Restore {
31    fn drop(&mut self) {
32        let _ = disable_raw_mode();
33        let _ = execute!(io::stderr(), LeaveAlternateScreen);
34    }
35}
36
37/// Run the picker. `Ok(None)` means the user quit without choosing.
38pub fn pick(root: PathBuf) -> Res<Option<PathBuf>> {
39    let mut app = App::new(root);
40    enable_raw_mode()?;
41    // Armed only once raw mode is actually on, so a failure above restores
42    // nothing it did not change.
43    let _restore = Restore;
44    execute!(io::stderr(), EnterAlternateScreen)?;
45    event_loop(
46        &mut Terminal::new(CrosstermBackend::new(io::stderr()))?,
47        &mut app,
48    )
49}
50
51/// How long to wait for a key before looking for search results. Short enough
52/// that hits appear promptly, long enough to idle at no measurable cost.
53const TICK: Duration = Duration::from_millis(80);
54
55/// How long Enter will wait for a search that has not answered yet. Long
56/// enough for a big tree, short enough that a wedged `rg` still lets you out.
57const PICK_WAIT: Duration = Duration::from_secs(5);
58
59fn event_loop(
60    term: &mut Terminal<CrosstermBackend<io::Stderr>>,
61    app: &mut App,
62) -> Res<Option<PathBuf>> {
63    let mut dirty = true;
64    loop {
65        if dirty {
66            term.draw(|f| view::draw(f, app))?;
67            dirty = false;
68        }
69        // Poll rather than block: a search finishing is also a reason to redraw.
70        if event::poll(TICK)? {
71            if let Event::Key(k) = event::read()? {
72                if k.kind == KeyEventKind::Press {
73                    match on_key(app, k.code) {
74                        Some(Action::Quit) => return Ok(None),
75                        Some(Action::Pick(p)) => return Ok(Some(p)),
76                        None => dirty = true,
77                    }
78                }
79            }
80        }
81        if let Some(done) = app.search.take_fresh() {
82            app.apply(done);
83            dirty = true;
84        }
85    }
86}
87
88pub(crate) fn on_key(app: &mut App, code: KeyCode) -> Option<Action> {
89    match app.mode {
90        Mode::Tree => on_tree_key(app, code),
91        _ => on_search_key(app, code),
92    }
93}
94
95/// In search mode every plain character is query text, so `q`, `/` and `.`
96/// type rather than act. Enter picks, Esc goes back to the tree.
97fn on_search_key(app: &mut App, code: KeyCode) -> Option<Action> {
98    let (Mode::Find(q) | Mode::Grep(q)) = &app.mode else {
99        return None;
100    };
101    let grep = matches!(app.mode, Mode::Grep(_));
102    let mut q = q.clone();
103    match code {
104        KeyCode::Char(c) => q.push(c),
105        KeyCode::Backspace => {
106            q.pop();
107        }
108        KeyCode::Esc => {
109            app.back_to_tree();
110            return None;
111        }
112        KeyCode::Enter => {
113            // The result still in flight is the one being chosen. Waiting for
114            // it beats picking from an empty list, which would cd to the root.
115            if app.search.pending() {
116                if let Some(d) = app.search.wait(PICK_WAIT) {
117                    app.apply(d);
118                }
119            }
120            return Some(Action::Pick(app.target()));
121        }
122        KeyCode::Down | KeyCode::Tab => {
123            app.move_by(1);
124            return None;
125        }
126        KeyCode::Up => {
127            app.move_by(-1);
128            return None;
129        }
130        _ => return None,
131    }
132    app.mode = if grep { Mode::Grep(q) } else { Mode::Find(q) };
133    // Mode is set first so the worker is told which backend the new query wants.
134    let (Mode::Find(q) | Mode::Grep(q)) = &app.mode else {
135        return None;
136    };
137    let q = q.clone();
138    app.request_search(&q);
139    None
140}
141
142fn on_tree_key(app: &mut App, code: KeyCode) -> Option<Action> {
143    match code {
144        KeyCode::Char('q') | KeyCode::Esc => return Some(Action::Quit),
145        KeyCode::Enter => return Some(Action::Pick(app.target())),
146        KeyCode::Char('j') | KeyCode::Down => app.move_by(1),
147        KeyCode::Char('k') | KeyCode::Up => app.move_by(-1),
148        KeyCode::Char('g') => app.sel = 0,
149        KeyCode::Char('G') => app.sel = app.len().saturating_sub(1),
150        KeyCode::Char('l') | KeyCode::Right | KeyCode::Tab | KeyCode::Char(' ') => {
151            app.tree.toggle(app.sel)
152        }
153        KeyCode::Char('h') | KeyCode::Left => app.collapse_or_up(),
154        KeyCode::Char('.') => app.toggle_hidden(),
155        KeyCode::Char('/') => app.mode = Mode::Find(String::new()),
156        KeyCode::Char('s') => app.mode = Mode::Grep(String::new()),
157        _ => {}
158    }
159    None
160}
161
162#[cfg(test)]
163mod tests {
164    use super::*;
165
166    fn app() -> App {
167        App::new(PathBuf::from(env!("CARGO_MANIFEST_DIR")))
168    }
169
170    #[test]
171    fn q_and_esc_quit_without_choosing() {
172        assert_eq!(on_key(&mut app(), KeyCode::Char('q')), Some(Action::Quit));
173        assert_eq!(on_key(&mut app(), KeyCode::Esc), Some(Action::Quit));
174    }
175
176    /// The core contract: Enter hands back a directory and ends the loop.
177    #[test]
178    fn enter_picks_a_directory_and_ends_the_loop() {
179        let mut app = app();
180        if let Some(Action::Pick(p)) = on_key(&mut app, KeyCode::Enter) {
181            assert!(p.is_dir(), "{p:?}");
182        } else {
183            panic!("Enter must pick");
184        };
185    }
186
187    #[test]
188    fn l_expands_a_directory_and_h_collapses_it() {
189        let mut app = app();
190        app.sel = app
191            .tree
192            .entries
193            .iter()
194            .position(|e| e.is_dir)
195            .expect("src/ exists");
196        let before = app.tree.len();
197
198        assert_eq!(on_key(&mut app, KeyCode::Char('l')), None);
199        assert!(app.tree.len() > before);
200
201        assert_eq!(on_key(&mut app, KeyCode::Char('h')), None);
202        assert_eq!(app.tree.len(), before);
203    }
204
205    #[test]
206    fn slash_and_s_enter_the_two_search_modes() {
207        let mut app = app();
208        on_key(&mut app, KeyCode::Char('/'));
209        assert!(matches!(app.mode, Mode::Find(ref q) if q.is_empty()));
210
211        app.back_to_tree();
212        on_key(&mut app, KeyCode::Char('s'));
213        assert!(matches!(app.mode, Mode::Grep(ref q) if q.is_empty()));
214    }
215
216    /// `q` must type into the query instead of quitting once searching.
217    #[test]
218    fn letters_type_into_the_query_rather_than_acting() {
219        let mut app = app();
220        on_key(&mut app, KeyCode::Char('/'));
221        for c in ['q', '.', 's'] {
222            assert_eq!(on_key(&mut app, KeyCode::Char(c)), None);
223        }
224        assert!(matches!(app.mode, Mode::Find(ref q) if q == "q.s"));
225
226        on_key(&mut app, KeyCode::Backspace);
227        assert!(matches!(app.mode, Mode::Find(ref q) if q == "q."));
228    }
229
230    #[test]
231    fn esc_leaves_search_and_returns_to_the_tree() {
232        let mut app = app();
233        on_key(&mut app, KeyCode::Char('/'));
234        on_key(&mut app, KeyCode::Char('l'));
235        assert_eq!(on_key(&mut app, KeyCode::Esc), None);
236        assert!(matches!(app.mode, Mode::Tree));
237        assert!(app.hits.is_empty());
238    }
239
240    /// A find hit for a file resolves to its directory, which is what makes
241    /// "Enter on a file" cd to the folder holding it.
242    #[test]
243    fn enter_on_a_file_hit_picks_its_directory() {
244        let mut app = app();
245        on_key(&mut app, KeyCode::Char('/'));
246        for c in "lib.rs".chars() {
247            on_key(&mut app, KeyCode::Char(c));
248        }
249        app.settle(); // the worker answers off the key loop now
250        assert!(!app.hits.is_empty(), "lib.rs must be found");
251        assert!(app.hits.iter().any(|p| p.is_file()));
252
253        if let Some(Action::Pick(p)) = on_key(&mut app, KeyCode::Enter) {
254            assert!(p.is_dir(), "{p:?}");
255        } else {
256            panic!("Enter must pick");
257        };
258    }
259
260    /// The whole point of the worker: a keystroke returns before the search
261    /// does, so the UI never stalls on a large tree.
262    #[test]
263    fn typing_returns_immediately_and_results_land_later() {
264        let mut app = app();
265        on_key(&mut app, KeyCode::Char('/'));
266        for c in "lib".chars() {
267            assert_eq!(on_key(&mut app, KeyCode::Char(c)), None);
268        }
269        assert!(app.search.pending(), "the search should still be running");
270        assert!(app.hits.is_empty(), "hits must not be filled inline");
271
272        app.settle();
273        assert!(!app.search.pending());
274        assert!(!app.hits.is_empty());
275    }
276
277    /// Enter pressed before the hits land must still pick the hit, not fall
278    /// back to the root because the list happened to be empty at that instant.
279    #[test]
280    fn enter_before_the_results_land_still_picks_a_hit() {
281        let mut app = app();
282        on_key(&mut app, KeyCode::Char('/'));
283        for c in "lib.rs".chars() {
284            on_key(&mut app, KeyCode::Char(c));
285        }
286        assert!(app.search.pending(), "precondition: still searching");
287        assert!(app.hits.is_empty(), "precondition: nothing arrived yet");
288
289        if let Some(Action::Pick(p)) = on_key(&mut app, KeyCode::Enter) {
290            assert_eq!(p, app.tree.root.join("src"), "picked {p:?}");
291            assert_ne!(p, app.tree.root, "fell back to the root");
292        } else {
293            panic!("Enter must pick");
294        };
295    }
296
297    /// Backspacing the query away clears the list without a round trip.
298    #[test]
299    fn clearing_the_query_empties_the_hits_at_once() {
300        let mut app = app();
301        on_key(&mut app, KeyCode::Char('/'));
302        on_key(&mut app, KeyCode::Char('l'));
303        app.settle();
304        assert!(!app.hits.is_empty());
305
306        on_key(&mut app, KeyCode::Backspace);
307        assert!(matches!(app.mode, Mode::Find(ref q) if q.is_empty()));
308        assert!(app.hits.is_empty(), "an empty query must show nothing");
309        assert!(!app.search.pending(), "nothing to wait for");
310    }
311
312    #[test]
313    fn dot_toggles_hidden_and_reloads() {
314        let mut app = app();
315        assert!(!app.tree.hidden);
316        on_key(&mut app, KeyCode::Char('.'));
317        assert!(app.tree.hidden);
318        on_key(&mut app, KeyCode::Char('.'));
319        assert!(!app.tree.hidden);
320    }
321
322    #[test]
323    fn g_and_shift_g_jump_to_the_ends() {
324        let mut app = app();
325        on_key(&mut app, KeyCode::Char('G'));
326        assert_eq!(app.sel, app.len() - 1);
327        on_key(&mut app, KeyCode::Char('g'));
328        assert_eq!(app.sel, 0);
329    }
330}