file_finder.rs

  1use fuzzy::PathMatch;
  2use gpui::{
  3    actions, elements::*, AppContext, Entity, ModelHandle, MouseState, MutableAppContext,
  4    RenderContext, Task, View, ViewContext, ViewHandle,
  5};
  6use picker::{Picker, PickerDelegate};
  7use project::{Project, ProjectPath, WorktreeId};
  8use settings::Settings;
  9use std::{
 10    path::Path,
 11    sync::{
 12        atomic::{self, AtomicBool},
 13        Arc,
 14    },
 15};
 16use util::post_inc;
 17use workspace::Workspace;
 18
 19pub struct FileFinder {
 20    project: ModelHandle<Project>,
 21    picker: ViewHandle<Picker<Self>>,
 22    search_count: usize,
 23    latest_search_id: usize,
 24    latest_search_did_cancel: bool,
 25    latest_search_query: String,
 26    matches: Vec<PathMatch>,
 27    selected: Option<(usize, Arc<Path>)>,
 28    cancel_flag: Arc<AtomicBool>,
 29}
 30
 31actions!(file_finder, [Toggle]);
 32
 33pub fn init(cx: &mut MutableAppContext) {
 34    cx.add_action(FileFinder::toggle);
 35    Picker::<FileFinder>::init(cx);
 36}
 37
 38pub enum Event {
 39    Selected(ProjectPath),
 40    Dismissed,
 41}
 42
 43impl Entity for FileFinder {
 44    type Event = Event;
 45}
 46
 47impl View for FileFinder {
 48    fn ui_name() -> &'static str {
 49        "FileFinder"
 50    }
 51
 52    fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
 53        ChildView::new(self.picker.clone()).boxed()
 54    }
 55
 56    fn on_focus(&mut self, cx: &mut ViewContext<Self>) {
 57        cx.focus(&self.picker);
 58    }
 59}
 60
 61impl FileFinder {
 62    fn labels_for_match(&self, path_match: &PathMatch) -> (String, Vec<usize>, String, Vec<usize>) {
 63        let path_string = path_match.path.to_string_lossy();
 64        let full_path = [path_match.path_prefix.as_ref(), path_string.as_ref()].join("");
 65        let path_positions = path_match.positions.clone();
 66
 67        let file_name = path_match.path.file_name().map_or_else(
 68            || path_match.path_prefix.to_string(),
 69            |file_name| file_name.to_string_lossy().to_string(),
 70        );
 71        let file_name_start = path_match.path_prefix.chars().count() + path_string.chars().count()
 72            - file_name.chars().count();
 73        let file_name_positions = path_positions
 74            .iter()
 75            .filter_map(|pos| {
 76                if pos >= &file_name_start {
 77                    Some(pos - file_name_start)
 78                } else {
 79                    None
 80                }
 81            })
 82            .collect();
 83
 84        (file_name, file_name_positions, full_path, path_positions)
 85    }
 86
 87    fn toggle(workspace: &mut Workspace, _: &Toggle, cx: &mut ViewContext<Workspace>) {
 88        workspace.toggle_modal(cx, |workspace, cx| {
 89            let project = workspace.project().clone();
 90            let finder = cx.add_view(|cx| Self::new(project, cx));
 91            cx.subscribe(&finder, Self::on_event).detach();
 92            finder
 93        });
 94    }
 95
 96    fn on_event(
 97        workspace: &mut Workspace,
 98        _: ViewHandle<FileFinder>,
 99        event: &Event,
100        cx: &mut ViewContext<Workspace>,
101    ) {
102        match event {
103            Event::Selected(project_path) => {
104                workspace
105                    .open_path(project_path.clone(), true, cx)
106                    .detach_and_log_err(cx);
107                workspace.dismiss_modal(cx);
108            }
109            Event::Dismissed => {
110                workspace.dismiss_modal(cx);
111            }
112        }
113    }
114
115    pub fn new(project: ModelHandle<Project>, cx: &mut ViewContext<Self>) -> Self {
116        let handle = cx.weak_handle();
117        cx.observe(&project, Self::project_updated).detach();
118        Self {
119            project,
120            picker: cx.add_view(|cx| Picker::new(handle, cx)),
121            search_count: 0,
122            latest_search_id: 0,
123            latest_search_did_cancel: false,
124            latest_search_query: String::new(),
125            matches: Vec::new(),
126            selected: None,
127            cancel_flag: Arc::new(AtomicBool::new(false)),
128        }
129    }
130
131    fn project_updated(&mut self, _: ModelHandle<Project>, cx: &mut ViewContext<Self>) {
132        self.spawn_search(self.picker.read(cx).query(cx), cx)
133            .detach();
134    }
135
136    fn spawn_search(&mut self, query: String, cx: &mut ViewContext<Self>) -> Task<()> {
137        let search_id = util::post_inc(&mut self.search_count);
138        self.cancel_flag.store(true, atomic::Ordering::Relaxed);
139        self.cancel_flag = Arc::new(AtomicBool::new(false));
140        let cancel_flag = self.cancel_flag.clone();
141        let project = self.project.clone();
142        cx.spawn(|this, mut cx| async move {
143            let matches = project
144                .read_with(&cx, |project, cx| {
145                    project.match_paths(&query, false, false, 100, cancel_flag.as_ref(), cx)
146                })
147                .await;
148            let did_cancel = cancel_flag.load(atomic::Ordering::Relaxed);
149            this.update(&mut cx, |this, cx| {
150                this.set_matches(search_id, did_cancel, query, matches, cx)
151            });
152        })
153    }
154
155    fn set_matches(
156        &mut self,
157        search_id: usize,
158        did_cancel: bool,
159        query: String,
160        matches: Vec<PathMatch>,
161        cx: &mut ViewContext<Self>,
162    ) {
163        if search_id >= self.latest_search_id {
164            self.latest_search_id = search_id;
165            if self.latest_search_did_cancel && query == self.latest_search_query {
166                util::extend_sorted(&mut self.matches, matches.into_iter(), 100, |a, b| b.cmp(a));
167            } else {
168                self.matches = matches;
169            }
170            self.latest_search_query = query;
171            self.latest_search_did_cancel = did_cancel;
172            cx.notify();
173            self.picker.update(cx, |_, cx| cx.notify());
174        }
175    }
176}
177
178impl PickerDelegate for FileFinder {
179    fn match_count(&self) -> usize {
180        self.matches.len()
181    }
182
183    fn selected_index(&self) -> usize {
184        if let Some(selected) = self.selected.as_ref() {
185            for (ix, path_match) in self.matches.iter().enumerate() {
186                if (path_match.worktree_id, path_match.path.as_ref())
187                    == (selected.0, selected.1.as_ref())
188                {
189                    return ix;
190                }
191            }
192        }
193        0
194    }
195
196    fn set_selected_index(&mut self, ix: usize, cx: &mut ViewContext<Self>) {
197        let mat = &self.matches[ix];
198        self.selected = Some((mat.worktree_id, mat.path.clone()));
199        cx.notify();
200    }
201
202    fn update_matches(&mut self, query: String, cx: &mut ViewContext<Self>) -> Task<()> {
203        if query.is_empty() {
204            self.latest_search_id = post_inc(&mut self.search_count);
205            self.matches.clear();
206            cx.notify();
207            Task::ready(())
208        } else {
209            self.spawn_search(query, cx)
210        }
211    }
212
213    fn confirm(&mut self, cx: &mut ViewContext<Self>) {
214        if let Some(m) = self.matches.get(self.selected_index()) {
215            cx.emit(Event::Selected(ProjectPath {
216                worktree_id: WorktreeId::from_usize(m.worktree_id),
217                path: m.path.clone(),
218            }));
219        }
220    }
221
222    fn dismiss(&mut self, cx: &mut ViewContext<Self>) {
223        cx.emit(Event::Dismissed);
224    }
225
226    fn render_match(
227        &self,
228        ix: usize,
229        mouse_state: MouseState,
230        selected: bool,
231        cx: &AppContext,
232    ) -> ElementBox {
233        let path_match = &self.matches[ix];
234        let settings = cx.global::<Settings>();
235        let style = settings.theme.picker.item.style_for(mouse_state, selected);
236        let (file_name, file_name_positions, full_path, full_path_positions) =
237            self.labels_for_match(path_match);
238        Flex::column()
239            .with_child(
240                Label::new(file_name.to_string(), style.label.clone())
241                    .with_highlights(file_name_positions)
242                    .boxed(),
243            )
244            .with_child(
245                Label::new(full_path, style.label.clone())
246                    .with_highlights(full_path_positions)
247                    .boxed(),
248            )
249            .flex(1., false)
250            .contained()
251            .with_style(style.container)
252            .named("match")
253    }
254}
255
256#[cfg(test)]
257mod tests {
258    use super::*;
259    use editor::{Editor, Input};
260    use menu::{Confirm, SelectNext};
261    use serde_json::json;
262    use workspace::{AppState, Workspace};
263
264    #[ctor::ctor]
265    fn init_logger() {
266        if std::env::var("RUST_LOG").is_ok() {
267            env_logger::init();
268        }
269    }
270
271    #[gpui::test]
272    async fn test_matching_paths(cx: &mut gpui::TestAppContext) {
273        let app_state = cx.update(|cx| {
274            super::init(cx);
275            editor::init(cx);
276            AppState::test(cx)
277        });
278
279        app_state
280            .fs
281            .as_fake()
282            .insert_tree(
283                "/root",
284                json!({
285                    "a": {
286                        "banana": "",
287                        "bandana": "",
288                    }
289                }),
290            )
291            .await;
292
293        let project = Project::test(app_state.fs.clone(), ["/root".as_ref()], cx).await;
294        let (window_id, workspace) = cx.add_window(|cx| Workspace::new(project, cx));
295        cx.dispatch_action(window_id, Toggle);
296
297        let finder = cx.read(|cx| {
298            workspace
299                .read(cx)
300                .modal()
301                .cloned()
302                .unwrap()
303                .downcast::<FileFinder>()
304                .unwrap()
305        });
306        cx.dispatch_action(window_id, Input("b".into()));
307        cx.dispatch_action(window_id, Input("n".into()));
308        cx.dispatch_action(window_id, Input("a".into()));
309        finder
310            .condition(&cx, |finder, _| finder.matches.len() == 2)
311            .await;
312
313        let active_pane = cx.read(|cx| workspace.read(cx).active_pane().clone());
314        cx.dispatch_action(window_id, SelectNext);
315        cx.dispatch_action(window_id, Confirm);
316        active_pane
317            .condition(&cx, |pane, _| pane.active_item().is_some())
318            .await;
319        cx.read(|cx| {
320            let active_item = active_pane.read(cx).active_item().unwrap();
321            assert_eq!(
322                active_item
323                    .to_any()
324                    .downcast::<Editor>()
325                    .unwrap()
326                    .read(cx)
327                    .title(cx),
328                "bandana"
329            );
330        });
331    }
332
333    #[gpui::test]
334    async fn test_matching_cancellation(cx: &mut gpui::TestAppContext) {
335        let app_state = cx.update(AppState::test);
336        app_state
337            .fs
338            .as_fake()
339            .insert_tree(
340                "/dir",
341                json!({
342                    "hello": "",
343                    "goodbye": "",
344                    "halogen-light": "",
345                    "happiness": "",
346                    "height": "",
347                    "hi": "",
348                    "hiccup": "",
349                }),
350            )
351            .await;
352
353        let project = Project::test(app_state.fs.clone(), ["/dir".as_ref()], cx).await;
354        let (_, workspace) = cx.add_window(|cx| Workspace::new(project, cx));
355        let (_, finder) =
356            cx.add_window(|cx| FileFinder::new(workspace.read(cx).project().clone(), cx));
357
358        let query = "hi".to_string();
359        finder
360            .update(cx, |f, cx| f.spawn_search(query.clone(), cx))
361            .await;
362        finder.read_with(cx, |f, _| assert_eq!(f.matches.len(), 5));
363
364        finder.update(cx, |finder, cx| {
365            let matches = finder.matches.clone();
366
367            // Simulate a search being cancelled after the time limit,
368            // returning only a subset of the matches that would have been found.
369            drop(finder.spawn_search(query.clone(), cx));
370            finder.set_matches(
371                finder.latest_search_id,
372                true, // did-cancel
373                query.clone(),
374                vec![matches[1].clone(), matches[3].clone()],
375                cx,
376            );
377
378            // Simulate another cancellation.
379            drop(finder.spawn_search(query.clone(), cx));
380            finder.set_matches(
381                finder.latest_search_id,
382                true, // did-cancel
383                query.clone(),
384                vec![matches[0].clone(), matches[2].clone(), matches[3].clone()],
385                cx,
386            );
387
388            assert_eq!(finder.matches, matches[0..4])
389        });
390    }
391
392    #[gpui::test]
393    async fn test_single_file_worktrees(cx: &mut gpui::TestAppContext) {
394        let app_state = cx.update(AppState::test);
395        app_state
396            .fs
397            .as_fake()
398            .insert_tree("/root", json!({ "the-parent-dir": { "the-file": "" } }))
399            .await;
400
401        let project = Project::test(
402            app_state.fs.clone(),
403            ["/root/the-parent-dir/the-file".as_ref()],
404            cx,
405        )
406        .await;
407        let (_, workspace) = cx.add_window(|cx| Workspace::new(project, cx));
408        let (_, finder) =
409            cx.add_window(|cx| FileFinder::new(workspace.read(cx).project().clone(), cx));
410
411        // Even though there is only one worktree, that worktree's filename
412        // is included in the matching, because the worktree is a single file.
413        finder
414            .update(cx, |f, cx| f.spawn_search("thf".into(), cx))
415            .await;
416        cx.read(|cx| {
417            let finder = finder.read(cx);
418            assert_eq!(finder.matches.len(), 1);
419
420            let (file_name, file_name_positions, full_path, full_path_positions) =
421                finder.labels_for_match(&finder.matches[0]);
422            assert_eq!(file_name, "the-file");
423            assert_eq!(file_name_positions, &[0, 1, 4]);
424            assert_eq!(full_path, "the-file");
425            assert_eq!(full_path_positions, &[0, 1, 4]);
426        });
427
428        // Since the worktree root is a file, searching for its name followed by a slash does
429        // not match anything.
430        finder
431            .update(cx, |f, cx| f.spawn_search("thf/".into(), cx))
432            .await;
433        finder.read_with(cx, |f, _| assert_eq!(f.matches.len(), 0));
434    }
435
436    #[gpui::test]
437    async fn test_multiple_matches_with_same_relative_path(cx: &mut gpui::TestAppContext) {
438        cx.foreground().forbid_parking();
439
440        let app_state = cx.update(AppState::test);
441        app_state
442            .fs
443            .as_fake()
444            .insert_tree(
445                "/root",
446                json!({
447                    "dir1": { "a.txt": "" },
448                    "dir2": { "a.txt": "" }
449                }),
450            )
451            .await;
452
453        let project = Project::test(
454            app_state.fs.clone(),
455            ["/root/dir1".as_ref(), "/root/dir2".as_ref()],
456            cx,
457        )
458        .await;
459        let (_, workspace) = cx.add_window(|cx| Workspace::new(project, cx));
460        let (_, finder) =
461            cx.add_window(|cx| FileFinder::new(workspace.read(cx).project().clone(), cx));
462
463        // Run a search that matches two files with the same relative path.
464        finder
465            .update(cx, |f, cx| f.spawn_search("a.t".into(), cx))
466            .await;
467
468        // Can switch between different matches with the same relative path.
469        finder.update(cx, |f, cx| {
470            assert_eq!(f.matches.len(), 2);
471            assert_eq!(f.selected_index(), 0);
472            f.set_selected_index(1, cx);
473            assert_eq!(f.selected_index(), 1);
474            f.set_selected_index(0, cx);
475            assert_eq!(f.selected_index(), 0);
476        });
477    }
478}