file_finder.rs

  1use fuzzy::PathMatch;
  2use gpui::{
  3    actions, elements::*, AnyViewHandle, AppContext, Entity, ModelHandle, MouseState,
  4    MutableAppContext, RenderContext, Task, View, ViewContext, ViewHandle,
  5};
  6use picker::{Picker, PickerDelegate};
  7use project::{PathMatchCandidateSet, 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    relative_to: Option<Arc<Path>>,
 27    matches: Vec<PathMatch>,
 28    selected: Option<(usize, Arc<Path>)>,
 29    cancel_flag: Arc<AtomicBool>,
 30}
 31
 32actions!(file_finder, [Toggle]);
 33
 34pub fn init(cx: &mut MutableAppContext) {
 35    cx.add_action(FileFinder::toggle);
 36    Picker::<FileFinder>::init(cx);
 37}
 38
 39pub enum Event {
 40    Selected(ProjectPath),
 41    Dismissed,
 42}
 43
 44impl Entity for FileFinder {
 45    type Event = Event;
 46}
 47
 48impl View for FileFinder {
 49    fn ui_name() -> &'static str {
 50        "FileFinder"
 51    }
 52
 53    fn render(&mut self, cx: &mut RenderContext<Self>) -> ElementBox {
 54        ChildView::new(self.picker.clone(), cx).boxed()
 55    }
 56
 57    fn focus_in(&mut self, _: AnyViewHandle, cx: &mut ViewContext<Self>) {
 58        if cx.is_self_focused() {
 59            cx.focus(&self.picker);
 60        }
 61    }
 62}
 63
 64impl FileFinder {
 65    fn labels_for_match(&self, path_match: &PathMatch) -> (String, Vec<usize>, String, Vec<usize>) {
 66        let path = &path_match.path;
 67        let path_string = path.to_string_lossy();
 68        let full_path = [path_match.path_prefix.as_ref(), path_string.as_ref()].join("");
 69        let path_positions = path_match.positions.clone();
 70
 71        let file_name = path.file_name().map_or_else(
 72            || path_match.path_prefix.to_string(),
 73            |file_name| file_name.to_string_lossy().to_string(),
 74        );
 75        let file_name_start = path_match.path_prefix.chars().count() + path_string.chars().count()
 76            - file_name.chars().count();
 77        let file_name_positions = path_positions
 78            .iter()
 79            .filter_map(|pos| {
 80                if pos >= &file_name_start {
 81                    Some(pos - file_name_start)
 82                } else {
 83                    None
 84                }
 85            })
 86            .collect();
 87
 88        (file_name, file_name_positions, full_path, path_positions)
 89    }
 90
 91    fn toggle(workspace: &mut Workspace, _: &Toggle, cx: &mut ViewContext<Workspace>) {
 92        workspace.toggle_modal(cx, |workspace, cx| {
 93            let project = workspace.project().clone();
 94            let relative_to = workspace
 95                .active_item(cx)
 96                .and_then(|item| item.project_path(cx))
 97                .map(|project_path| project_path.path.clone());
 98            let finder = cx.add_view(|cx| Self::new(project, relative_to, cx));
 99            cx.subscribe(&finder, Self::on_event).detach();
100            finder
101        });
102    }
103
104    fn on_event(
105        workspace: &mut Workspace,
106        _: ViewHandle<FileFinder>,
107        event: &Event,
108        cx: &mut ViewContext<Workspace>,
109    ) {
110        match event {
111            Event::Selected(project_path) => {
112                workspace
113                    .open_path(project_path.clone(), None, true, cx)
114                    .detach_and_log_err(cx);
115                workspace.dismiss_modal(cx);
116            }
117            Event::Dismissed => {
118                workspace.dismiss_modal(cx);
119            }
120        }
121    }
122
123    pub fn new(
124        project: ModelHandle<Project>,
125        relative_to: Option<Arc<Path>>,
126        cx: &mut ViewContext<Self>,
127    ) -> Self {
128        let handle = cx.weak_handle();
129        cx.observe(&project, Self::project_updated).detach();
130        Self {
131            project,
132            picker: cx.add_view(|cx| Picker::new("Search project files...", handle, cx)),
133            search_count: 0,
134            latest_search_id: 0,
135            latest_search_did_cancel: false,
136            latest_search_query: String::new(),
137            relative_to,
138            matches: Vec::new(),
139            selected: None,
140            cancel_flag: Arc::new(AtomicBool::new(false)),
141        }
142    }
143
144    fn project_updated(&mut self, _: ModelHandle<Project>, cx: &mut ViewContext<Self>) {
145        self.spawn_search(self.picker.read(cx).query(cx), cx)
146            .detach();
147    }
148
149    fn spawn_search(&mut self, query: String, cx: &mut ViewContext<Self>) -> Task<()> {
150        let relative_to = self.relative_to.clone();
151        let worktrees = self
152            .project
153            .read(cx)
154            .visible_worktrees(cx)
155            .collect::<Vec<_>>();
156        let include_root_name = worktrees.len() > 1;
157        let candidate_sets = worktrees
158            .into_iter()
159            .map(|worktree| {
160                let worktree = worktree.read(cx);
161                PathMatchCandidateSet {
162                    snapshot: worktree.snapshot(),
163                    include_ignored: worktree
164                        .root_entry()
165                        .map_or(false, |entry| entry.is_ignored),
166                    include_root_name,
167                }
168            })
169            .collect::<Vec<_>>();
170
171        let search_id = util::post_inc(&mut self.search_count);
172        self.cancel_flag.store(true, atomic::Ordering::Relaxed);
173        self.cancel_flag = Arc::new(AtomicBool::new(false));
174        let cancel_flag = self.cancel_flag.clone();
175        cx.spawn(|this, mut cx| async move {
176            let matches = fuzzy::match_path_sets(
177                candidate_sets.as_slice(),
178                &query,
179                relative_to,
180                false,
181                100,
182                &cancel_flag,
183                cx.background(),
184            )
185            .await;
186            let did_cancel = cancel_flag.load(atomic::Ordering::Relaxed);
187            this.update(&mut cx, |this, cx| {
188                this.set_matches(search_id, did_cancel, query, matches, cx)
189            });
190        })
191    }
192
193    fn set_matches(
194        &mut self,
195        search_id: usize,
196        did_cancel: bool,
197        query: String,
198        matches: Vec<PathMatch>,
199        cx: &mut ViewContext<Self>,
200    ) {
201        if search_id >= self.latest_search_id {
202            self.latest_search_id = search_id;
203            if self.latest_search_did_cancel && query == self.latest_search_query {
204                util::extend_sorted(&mut self.matches, matches.into_iter(), 100, |a, b| b.cmp(a));
205            } else {
206                self.matches = matches;
207            }
208            self.latest_search_query = query;
209            self.latest_search_did_cancel = did_cancel;
210            cx.notify();
211            self.picker.update(cx, |_, cx| cx.notify());
212        }
213    }
214}
215
216impl PickerDelegate for FileFinder {
217    fn match_count(&self) -> usize {
218        self.matches.len()
219    }
220
221    fn selected_index(&self) -> usize {
222        if let Some(selected) = self.selected.as_ref() {
223            for (ix, path_match) in self.matches.iter().enumerate() {
224                if (path_match.worktree_id, path_match.path.as_ref())
225                    == (selected.0, selected.1.as_ref())
226                {
227                    return ix;
228                }
229            }
230        }
231        0
232    }
233
234    fn set_selected_index(&mut self, ix: usize, cx: &mut ViewContext<Self>) {
235        let mat = &self.matches[ix];
236        self.selected = Some((mat.worktree_id, mat.path.clone()));
237        cx.notify();
238    }
239
240    fn update_matches(&mut self, query: String, cx: &mut ViewContext<Self>) -> Task<()> {
241        if query.is_empty() {
242            self.latest_search_id = post_inc(&mut self.search_count);
243            self.matches.clear();
244            cx.notify();
245            Task::ready(())
246        } else {
247            self.spawn_search(query, cx)
248        }
249    }
250
251    fn confirm(&mut self, cx: &mut ViewContext<Self>) {
252        if let Some(m) = self.matches.get(self.selected_index()) {
253            cx.emit(Event::Selected(ProjectPath {
254                worktree_id: WorktreeId::from_usize(m.worktree_id),
255                path: m.path.clone(),
256            }));
257        }
258    }
259
260    fn dismiss(&mut self, cx: &mut ViewContext<Self>) {
261        cx.emit(Event::Dismissed);
262    }
263
264    fn render_match(
265        &self,
266        ix: usize,
267        mouse_state: &mut MouseState,
268        selected: bool,
269        cx: &AppContext,
270    ) -> ElementBox {
271        let path_match = &self.matches[ix];
272        let settings = cx.global::<Settings>();
273        let style = settings.theme.picker.item.style_for(mouse_state, selected);
274        let (file_name, file_name_positions, full_path, full_path_positions) =
275            self.labels_for_match(path_match);
276        Flex::column()
277            .with_child(
278                Label::new(file_name, style.label.clone())
279                    .with_highlights(file_name_positions)
280                    .boxed(),
281            )
282            .with_child(
283                Label::new(full_path, style.label.clone())
284                    .with_highlights(full_path_positions)
285                    .boxed(),
286            )
287            .flex(1., false)
288            .contained()
289            .with_style(style.container)
290            .named("match")
291    }
292}
293
294#[cfg(test)]
295mod tests {
296    use super::*;
297    use editor::Editor;
298    use menu::{Confirm, SelectNext};
299    use serde_json::json;
300    use workspace::{AppState, Workspace};
301
302    #[ctor::ctor]
303    fn init_logger() {
304        if std::env::var("RUST_LOG").is_ok() {
305            env_logger::init();
306        }
307    }
308
309    #[gpui::test]
310    async fn test_matching_paths(cx: &mut gpui::TestAppContext) {
311        let app_state = cx.update(|cx| {
312            super::init(cx);
313            editor::init(cx);
314            AppState::test(cx)
315        });
316
317        app_state
318            .fs
319            .as_fake()
320            .insert_tree(
321                "/root",
322                json!({
323                    "a": {
324                        "banana": "",
325                        "bandana": "",
326                    }
327                }),
328            )
329            .await;
330
331        let project = Project::test(app_state.fs.clone(), ["/root".as_ref()], cx).await;
332        let (window_id, workspace) = cx.add_window(|cx| Workspace::test_new(project, cx));
333        cx.dispatch_action(window_id, Toggle);
334
335        let finder = cx.read(|cx| workspace.read(cx).modal::<FileFinder>().unwrap());
336        finder
337            .update(cx, |finder, cx| {
338                finder.update_matches("bna".to_string(), cx)
339            })
340            .await;
341        finder.read_with(cx, |finder, _| {
342            assert_eq!(finder.matches.len(), 2);
343        });
344
345        let active_pane = cx.read(|cx| workspace.read(cx).active_pane().clone());
346        cx.dispatch_action(window_id, SelectNext);
347        cx.dispatch_action(window_id, Confirm);
348        active_pane
349            .condition(cx, |pane, _| pane.active_item().is_some())
350            .await;
351        cx.read(|cx| {
352            let active_item = active_pane.read(cx).active_item().unwrap();
353            assert_eq!(
354                active_item
355                    .to_any()
356                    .downcast::<Editor>()
357                    .unwrap()
358                    .read(cx)
359                    .title(cx),
360                "bandana"
361            );
362        });
363    }
364
365    #[gpui::test]
366    async fn test_matching_cancellation(cx: &mut gpui::TestAppContext) {
367        let app_state = cx.update(AppState::test);
368        app_state
369            .fs
370            .as_fake()
371            .insert_tree(
372                "/dir",
373                json!({
374                    "hello": "",
375                    "goodbye": "",
376                    "halogen-light": "",
377                    "happiness": "",
378                    "height": "",
379                    "hi": "",
380                    "hiccup": "",
381                }),
382            )
383            .await;
384
385        let project = Project::test(app_state.fs.clone(), ["/dir".as_ref()], cx).await;
386        let (_, workspace) = cx.add_window(|cx| Workspace::test_new(project, cx));
387        let (_, finder) =
388            cx.add_window(|cx| FileFinder::new(workspace.read(cx).project().clone(), None, cx));
389
390        let query = "hi".to_string();
391        finder
392            .update(cx, |f, cx| f.spawn_search(query.clone(), cx))
393            .await;
394        finder.read_with(cx, |f, _| assert_eq!(f.matches.len(), 5));
395
396        finder.update(cx, |finder, cx| {
397            let matches = finder.matches.clone();
398
399            // Simulate a search being cancelled after the time limit,
400            // returning only a subset of the matches that would have been found.
401            drop(finder.spawn_search(query.clone(), cx));
402            finder.set_matches(
403                finder.latest_search_id,
404                true, // did-cancel
405                query.clone(),
406                vec![matches[1].clone(), matches[3].clone()],
407                cx,
408            );
409
410            // Simulate another cancellation.
411            drop(finder.spawn_search(query.clone(), cx));
412            finder.set_matches(
413                finder.latest_search_id,
414                true, // did-cancel
415                query.clone(),
416                vec![matches[0].clone(), matches[2].clone(), matches[3].clone()],
417                cx,
418            );
419
420            assert_eq!(finder.matches, matches[0..4])
421        });
422    }
423
424    #[gpui::test]
425    async fn test_ignored_files(cx: &mut gpui::TestAppContext) {
426        let app_state = cx.update(AppState::test);
427        app_state
428            .fs
429            .as_fake()
430            .insert_tree(
431                "/ancestor",
432                json!({
433                    ".gitignore": "ignored-root",
434                    "ignored-root": {
435                        "happiness": "",
436                        "height": "",
437                        "hi": "",
438                        "hiccup": "",
439                    },
440                    "tracked-root": {
441                        ".gitignore": "height",
442                        "happiness": "",
443                        "height": "",
444                        "hi": "",
445                        "hiccup": "",
446                    },
447                }),
448            )
449            .await;
450
451        let project = Project::test(
452            app_state.fs.clone(),
453            [
454                "/ancestor/tracked-root".as_ref(),
455                "/ancestor/ignored-root".as_ref(),
456            ],
457            cx,
458        )
459        .await;
460        let (_, workspace) = cx.add_window(|cx| Workspace::test_new(project, cx));
461        let (_, finder) =
462            cx.add_window(|cx| FileFinder::new(workspace.read(cx).project().clone(), None, cx));
463        finder
464            .update(cx, |f, cx| f.spawn_search("hi".into(), cx))
465            .await;
466        finder.read_with(cx, |f, _| assert_eq!(f.matches.len(), 7));
467    }
468
469    #[gpui::test]
470    async fn test_single_file_worktrees(cx: &mut gpui::TestAppContext) {
471        let app_state = cx.update(AppState::test);
472        app_state
473            .fs
474            .as_fake()
475            .insert_tree("/root", json!({ "the-parent-dir": { "the-file": "" } }))
476            .await;
477
478        let project = Project::test(
479            app_state.fs.clone(),
480            ["/root/the-parent-dir/the-file".as_ref()],
481            cx,
482        )
483        .await;
484        let (_, workspace) = cx.add_window(|cx| Workspace::test_new(project, cx));
485        let (_, finder) =
486            cx.add_window(|cx| FileFinder::new(workspace.read(cx).project().clone(), None, cx));
487
488        // Even though there is only one worktree, that worktree's filename
489        // is included in the matching, because the worktree is a single file.
490        finder
491            .update(cx, |f, cx| f.spawn_search("thf".into(), cx))
492            .await;
493        cx.read(|cx| {
494            let finder = finder.read(cx);
495            assert_eq!(finder.matches.len(), 1);
496
497            let (file_name, file_name_positions, full_path, full_path_positions) =
498                finder.labels_for_match(&finder.matches[0]);
499            assert_eq!(file_name, "the-file");
500            assert_eq!(file_name_positions, &[0, 1, 4]);
501            assert_eq!(full_path, "the-file");
502            assert_eq!(full_path_positions, &[0, 1, 4]);
503        });
504
505        // Since the worktree root is a file, searching for its name followed by a slash does
506        // not match anything.
507        finder
508            .update(cx, |f, cx| f.spawn_search("thf/".into(), cx))
509            .await;
510        finder.read_with(cx, |f, _| assert_eq!(f.matches.len(), 0));
511    }
512
513    #[gpui::test]
514    async fn test_multiple_matches_with_same_relative_path(cx: &mut gpui::TestAppContext) {
515        cx.foreground().forbid_parking();
516
517        let app_state = cx.update(AppState::test);
518        app_state
519            .fs
520            .as_fake()
521            .insert_tree(
522                "/root",
523                json!({
524                    "dir1": { "a.txt": "" },
525                    "dir2": { "a.txt": "" }
526                }),
527            )
528            .await;
529
530        let project = Project::test(
531            app_state.fs.clone(),
532            ["/root/dir1".as_ref(), "/root/dir2".as_ref()],
533            cx,
534        )
535        .await;
536        let (_, workspace) = cx.add_window(|cx| Workspace::test_new(project, cx));
537
538        let (_, finder) =
539            cx.add_window(|cx| FileFinder::new(workspace.read(cx).project().clone(), None, cx));
540
541        // Run a search that matches two files with the same relative path.
542        finder
543            .update(cx, |f, cx| f.spawn_search("a.t".into(), cx))
544            .await;
545
546        // Can switch between different matches with the same relative path.
547        finder.update(cx, |f, cx| {
548            assert_eq!(f.matches.len(), 2);
549            assert_eq!(f.selected_index(), 0);
550            f.set_selected_index(1, cx);
551            assert_eq!(f.selected_index(), 1);
552            f.set_selected_index(0, cx);
553            assert_eq!(f.selected_index(), 0);
554        });
555    }
556
557    #[gpui::test]
558    async fn test_path_distance_ordering(cx: &mut gpui::TestAppContext) {
559        cx.foreground().forbid_parking();
560
561        let app_state = cx.update(AppState::test);
562        app_state
563            .fs
564            .as_fake()
565            .insert_tree(
566                "/root",
567                json!({
568                    "dir1": { "a.txt": "" },
569                    "dir2": {
570                        "a.txt": "",
571                        "b.txt": ""
572                    }
573                }),
574            )
575            .await;
576
577        let project = Project::test(app_state.fs.clone(), ["/root".as_ref()], cx).await;
578        let (_, workspace) = cx.add_window(|cx| Workspace::test_new(project, cx));
579
580        // When workspace has an active item, sort items which are closer to that item
581        // first when they have the same name. In this case, b.txt is closer to dir2's a.txt
582        // so that one should be sorted earlier
583        let b_path = Some(Arc::from(Path::new("/root/dir2/b.txt")));
584        let (_, finder) =
585            cx.add_window(|cx| FileFinder::new(workspace.read(cx).project().clone(), b_path, cx));
586
587        finder
588            .update(cx, |f, cx| f.spawn_search("a.txt".into(), cx))
589            .await;
590
591        finder.read_with(cx, |f, _| {
592            assert_eq!(f.matches[0].path.as_ref(), Path::new("dir2/a.txt"));
593            assert_eq!(f.matches[1].path.as_ref(), Path::new("dir1/a.txt"));
594        });
595    }
596
597    #[gpui::test]
598    async fn test_search_worktree_without_files(cx: &mut gpui::TestAppContext) {
599        let app_state = cx.update(AppState::test);
600        app_state
601            .fs
602            .as_fake()
603            .insert_tree(
604                "/root",
605                json!({
606                    "dir1": {},
607                    "dir2": {
608                        "dir3": {}
609                    }
610                }),
611            )
612            .await;
613
614        let project = Project::test(app_state.fs.clone(), ["/root".as_ref()], cx).await;
615        let (_, workspace) = cx.add_window(|cx| Workspace::test_new(project, cx));
616        let (_, finder) =
617            cx.add_window(|cx| FileFinder::new(workspace.read(cx).project().clone(), None, cx));
618        finder
619            .update(cx, |f, cx| f.spawn_search("dir".into(), cx))
620            .await;
621        cx.read(|cx| {
622            let finder = finder.read(cx);
623            assert_eq!(finder.matches.len(), 0);
624        });
625    }
626}