file_finder.rs

  1use editor::{Editor, EditorSettings};
  2use fuzzy::PathMatch;
  3use gpui::{
  4    action,
  5    elements::*,
  6    keymap::{self, Binding},
  7    AppContext, Axis, Entity, ModelHandle, MutableAppContext, RenderContext, Task, View,
  8    ViewContext, ViewHandle, WeakViewHandle,
  9};
 10use postage::watch;
 11use project::{Project, ProjectPath, WorktreeId};
 12use std::{
 13    cmp,
 14    path::Path,
 15    sync::{
 16        atomic::{self, AtomicBool},
 17        Arc,
 18    },
 19};
 20use util::post_inc;
 21use workspace::{
 22    menu::{Confirm, SelectNext, SelectPrev},
 23    Settings, Workspace,
 24};
 25
 26pub struct FileFinder {
 27    handle: WeakViewHandle<Self>,
 28    settings: watch::Receiver<Settings>,
 29    project: ModelHandle<Project>,
 30    query_editor: ViewHandle<Editor>,
 31    search_count: usize,
 32    latest_search_id: usize,
 33    latest_search_did_cancel: bool,
 34    latest_search_query: String,
 35    matches: Vec<PathMatch>,
 36    selected: Option<(usize, Arc<Path>)>,
 37    cancel_flag: Arc<AtomicBool>,
 38    list_state: UniformListState,
 39}
 40
 41action!(Toggle);
 42action!(Select, ProjectPath);
 43
 44pub fn init(cx: &mut MutableAppContext) {
 45    cx.add_action(FileFinder::toggle);
 46    cx.add_action(FileFinder::confirm);
 47    cx.add_action(FileFinder::select);
 48    cx.add_action(FileFinder::select_prev);
 49    cx.add_action(FileFinder::select_next);
 50
 51    cx.add_bindings(vec![
 52        Binding::new("cmd-p", Toggle, None),
 53        Binding::new("escape", Toggle, Some("FileFinder")),
 54    ]);
 55}
 56
 57pub enum Event {
 58    Selected(ProjectPath),
 59    Dismissed,
 60}
 61
 62impl Entity for FileFinder {
 63    type Event = Event;
 64}
 65
 66impl View for FileFinder {
 67    fn ui_name() -> &'static str {
 68        "FileFinder"
 69    }
 70
 71    fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
 72        let settings = self.settings.borrow();
 73
 74        Align::new(
 75            ConstrainedBox::new(
 76                Container::new(
 77                    Flex::new(Axis::Vertical)
 78                        .with_child(
 79                            Container::new(ChildView::new(self.query_editor.id()).boxed())
 80                                .with_style(settings.theme.selector.input_editor.container)
 81                                .boxed(),
 82                        )
 83                        .with_child(Flexible::new(1.0, false, self.render_matches()).boxed())
 84                        .boxed(),
 85                )
 86                .with_style(settings.theme.selector.container)
 87                .boxed(),
 88            )
 89            .with_max_width(500.0)
 90            .with_max_height(420.0)
 91            .boxed(),
 92        )
 93        .top()
 94        .named("file finder")
 95    }
 96
 97    fn on_focus(&mut self, cx: &mut ViewContext<Self>) {
 98        cx.focus(&self.query_editor);
 99    }
100
101    fn keymap_context(&self, _: &AppContext) -> keymap::Context {
102        let mut cx = Self::default_keymap_context();
103        cx.set.insert("menu".into());
104        cx
105    }
106}
107
108impl FileFinder {
109    fn render_matches(&self) -> ElementBox {
110        if self.matches.is_empty() {
111            let settings = self.settings.borrow();
112            return Container::new(
113                Label::new(
114                    "No matches".into(),
115                    settings.theme.selector.empty.label.clone(),
116                )
117                .boxed(),
118            )
119            .with_style(settings.theme.selector.empty.container)
120            .named("empty matches");
121        }
122
123        let handle = self.handle.clone();
124        let list = UniformList::new(
125            self.list_state.clone(),
126            self.matches.len(),
127            move |mut range, items, cx| {
128                let cx = cx.as_ref();
129                let finder = handle.upgrade(cx).unwrap();
130                let finder = finder.read(cx);
131                let start = range.start;
132                range.end = cmp::min(range.end, finder.matches.len());
133                items.extend(
134                    finder.matches[range]
135                        .iter()
136                        .enumerate()
137                        .map(move |(i, path_match)| finder.render_match(path_match, start + i)),
138                );
139            },
140        );
141
142        Container::new(list.boxed())
143            .with_margin_top(6.0)
144            .named("matches")
145    }
146
147    fn render_match(&self, path_match: &PathMatch, index: usize) -> ElementBox {
148        let selected_index = self.selected_index();
149        let settings = self.settings.borrow();
150        let style = if index == selected_index {
151            &settings.theme.selector.active_item
152        } else {
153            &settings.theme.selector.item
154        };
155        let (file_name, file_name_positions, full_path, full_path_positions) =
156            self.labels_for_match(path_match);
157        let container = Container::new(
158            Flex::row()
159                // .with_child(
160                //     Container::new(
161                //         LineBox::new(
162                //             Svg::new("icons/file-16.svg")
163                //                 .with_color(style.label.text.color)
164                //                 .boxed(),
165                //             style.label.text.clone(),
166                //         )
167                //         .boxed(),
168                //     )
169                //     .with_padding_right(6.0)
170                //     .boxed(),
171                // )
172                .with_child(
173                    Flexible::new(
174                        1.0,
175                        false,
176                        Flex::column()
177                            .with_child(
178                                Label::new(file_name.to_string(), style.label.clone())
179                                    .with_highlights(file_name_positions)
180                                    .boxed(),
181                            )
182                            .with_child(
183                                Label::new(full_path, style.label.clone())
184                                    .with_highlights(full_path_positions)
185                                    .boxed(),
186                            )
187                            .boxed(),
188                    )
189                    .boxed(),
190                )
191                .boxed(),
192        )
193        .with_style(style.container);
194
195        let action = Select(ProjectPath {
196            worktree_id: WorktreeId::from_usize(path_match.worktree_id),
197            path: path_match.path.clone(),
198        });
199        EventHandler::new(container.boxed())
200            .on_mouse_down(move |cx| {
201                cx.dispatch_action(action.clone());
202                true
203            })
204            .named("match")
205    }
206
207    fn labels_for_match(&self, path_match: &PathMatch) -> (String, Vec<usize>, String, Vec<usize>) {
208        let path_string = path_match.path.to_string_lossy();
209        let full_path = [path_match.path_prefix.as_ref(), path_string.as_ref()].join("");
210        let path_positions = path_match.positions.clone();
211
212        let file_name = path_match.path.file_name().map_or_else(
213            || path_match.path_prefix.to_string(),
214            |file_name| file_name.to_string_lossy().to_string(),
215        );
216        let file_name_start = path_match.path_prefix.chars().count() + path_string.chars().count()
217            - file_name.chars().count();
218        let file_name_positions = path_positions
219            .iter()
220            .filter_map(|pos| {
221                if pos >= &file_name_start {
222                    Some(pos - file_name_start)
223                } else {
224                    None
225                }
226            })
227            .collect();
228
229        (file_name, file_name_positions, full_path, path_positions)
230    }
231
232    fn toggle(workspace: &mut Workspace, _: &Toggle, cx: &mut ViewContext<Workspace>) {
233        workspace.toggle_modal(cx, |cx, workspace| {
234            let project = workspace.project().clone();
235            let finder = cx.add_view(|cx| Self::new(workspace.settings.clone(), project, cx));
236            cx.subscribe(&finder, Self::on_event).detach();
237            finder
238        });
239    }
240
241    fn on_event(
242        workspace: &mut Workspace,
243        _: ViewHandle<FileFinder>,
244        event: &Event,
245        cx: &mut ViewContext<Workspace>,
246    ) {
247        match event {
248            Event::Selected(project_path) => {
249                workspace
250                    .open_path(project_path.clone(), cx)
251                    .detach_and_log_err(cx);
252                workspace.dismiss_modal(cx);
253            }
254            Event::Dismissed => {
255                workspace.dismiss_modal(cx);
256            }
257        }
258    }
259
260    pub fn new(
261        settings: watch::Receiver<Settings>,
262        project: ModelHandle<Project>,
263        cx: &mut ViewContext<Self>,
264    ) -> Self {
265        cx.observe(&project, Self::project_updated).detach();
266
267        let query_editor = cx.add_view(|cx| {
268            Editor::single_line(
269                {
270                    let settings = settings.clone();
271                    Arc::new(move |_| {
272                        let settings = settings.borrow();
273                        EditorSettings {
274                            style: settings.theme.selector.input_editor.as_editor(),
275                            tab_size: settings.tab_size,
276                            soft_wrap: editor::SoftWrap::None,
277                        }
278                    })
279                },
280                cx,
281            )
282        });
283        cx.subscribe(&query_editor, Self::on_query_editor_event)
284            .detach();
285
286        Self {
287            handle: cx.weak_handle(),
288            settings,
289            project,
290            query_editor,
291            search_count: 0,
292            latest_search_id: 0,
293            latest_search_did_cancel: false,
294            latest_search_query: String::new(),
295            matches: Vec::new(),
296            selected: None,
297            cancel_flag: Arc::new(AtomicBool::new(false)),
298            list_state: Default::default(),
299        }
300    }
301
302    fn project_updated(&mut self, _: ModelHandle<Project>, cx: &mut ViewContext<Self>) {
303        let query = self.query_editor.update(cx, |buffer, cx| buffer.text(cx));
304        if let Some(task) = self.spawn_search(query, cx) {
305            task.detach();
306        }
307    }
308
309    fn on_query_editor_event(
310        &mut self,
311        _: ViewHandle<Editor>,
312        event: &editor::Event,
313        cx: &mut ViewContext<Self>,
314    ) {
315        match event {
316            editor::Event::Edited => {
317                let query = self.query_editor.update(cx, |buffer, cx| buffer.text(cx));
318                if query.is_empty() {
319                    self.latest_search_id = post_inc(&mut self.search_count);
320                    self.matches.clear();
321                    cx.notify();
322                } else {
323                    if let Some(task) = self.spawn_search(query, cx) {
324                        task.detach();
325                    }
326                }
327            }
328            editor::Event::Blurred => cx.emit(Event::Dismissed),
329            _ => {}
330        }
331    }
332
333    fn selected_index(&self) -> usize {
334        if let Some(selected) = self.selected.as_ref() {
335            for (ix, path_match) in self.matches.iter().enumerate() {
336                if (path_match.worktree_id, path_match.path.as_ref())
337                    == (selected.0, selected.1.as_ref())
338                {
339                    return ix;
340                }
341            }
342        }
343        0
344    }
345
346    fn select_prev(&mut self, _: &SelectPrev, cx: &mut ViewContext<Self>) {
347        let mut selected_index = self.selected_index();
348        if selected_index > 0 {
349            selected_index -= 1;
350            let mat = &self.matches[selected_index];
351            self.selected = Some((mat.worktree_id, mat.path.clone()));
352        }
353        self.list_state
354            .scroll_to(ScrollTarget::Show(selected_index));
355        cx.notify();
356    }
357
358    fn select_next(&mut self, _: &SelectNext, cx: &mut ViewContext<Self>) {
359        let mut selected_index = self.selected_index();
360        if selected_index + 1 < self.matches.len() {
361            selected_index += 1;
362            let mat = &self.matches[selected_index];
363            self.selected = Some((mat.worktree_id, mat.path.clone()));
364        }
365        self.list_state
366            .scroll_to(ScrollTarget::Show(selected_index));
367        cx.notify();
368    }
369
370    fn confirm(&mut self, _: &Confirm, cx: &mut ViewContext<Self>) {
371        if let Some(m) = self.matches.get(self.selected_index()) {
372            cx.emit(Event::Selected(ProjectPath {
373                worktree_id: WorktreeId::from_usize(m.worktree_id),
374                path: m.path.clone(),
375            }));
376        }
377    }
378
379    fn select(&mut self, Select(project_path): &Select, cx: &mut ViewContext<Self>) {
380        cx.emit(Event::Selected(project_path.clone()));
381    }
382
383    #[must_use]
384    fn spawn_search(&mut self, query: String, cx: &mut ViewContext<Self>) -> Option<Task<()>> {
385        let search_id = util::post_inc(&mut self.search_count);
386        self.cancel_flag.store(true, atomic::Ordering::Relaxed);
387        self.cancel_flag = Arc::new(AtomicBool::new(false));
388        let cancel_flag = self.cancel_flag.clone();
389        let project = self.project.clone();
390        Some(cx.spawn(|this, mut cx| async move {
391            let matches = project
392                .read_with(&cx, |project, cx| {
393                    project.match_paths(&query, false, false, 100, cancel_flag.as_ref(), cx)
394                })
395                .await;
396            let did_cancel = cancel_flag.load(atomic::Ordering::Relaxed);
397            this.update(&mut cx, |this, cx| {
398                this.update_matches((search_id, did_cancel, query, matches), cx)
399            });
400        }))
401    }
402
403    fn update_matches(
404        &mut self,
405        (search_id, did_cancel, query, matches): (usize, bool, String, Vec<PathMatch>),
406        cx: &mut ViewContext<Self>,
407    ) {
408        if search_id >= self.latest_search_id {
409            self.latest_search_id = search_id;
410            if self.latest_search_did_cancel && query == self.latest_search_query {
411                util::extend_sorted(&mut self.matches, matches.into_iter(), 100, |a, b| b.cmp(a));
412            } else {
413                self.matches = matches;
414            }
415            self.latest_search_query = query;
416            self.latest_search_did_cancel = did_cancel;
417            self.list_state
418                .scroll_to(ScrollTarget::Show(self.selected_index()));
419            cx.notify();
420        }
421    }
422}
423
424#[cfg(test)]
425mod tests {
426    use super::*;
427    use editor::Input;
428    use serde_json::json;
429    use std::path::PathBuf;
430    use workspace::{Workspace, WorkspaceParams};
431
432    #[gpui::test]
433    async fn test_matching_paths(mut cx: gpui::TestAppContext) {
434        let mut path_openers = Vec::new();
435        cx.update(|cx| {
436            super::init(cx);
437            editor::init(cx, &mut path_openers);
438        });
439
440        let mut params = cx.update(WorkspaceParams::test);
441        params.path_openers = Arc::from(path_openers);
442        params
443            .fs
444            .as_fake()
445            .insert_tree(
446                "/root",
447                json!({
448                    "a": {
449                        "banana": "",
450                        "bandana": "",
451                    }
452                }),
453            )
454            .await;
455
456        let (window_id, workspace) = cx.add_window(|cx| Workspace::new(&params, cx));
457        workspace
458            .update(&mut cx, |workspace, cx| {
459                workspace.add_worktree(Path::new("/root"), cx)
460            })
461            .await
462            .unwrap();
463        cx.read(|cx| workspace.read(cx).worktree_scans_complete(cx))
464            .await;
465        cx.dispatch_action(window_id, vec![workspace.id()], Toggle);
466
467        let finder = cx.read(|cx| {
468            workspace
469                .read(cx)
470                .modal()
471                .cloned()
472                .unwrap()
473                .downcast::<FileFinder>()
474                .unwrap()
475        });
476        let query_buffer = cx.read(|cx| finder.read(cx).query_editor.clone());
477
478        let chain = vec![finder.id(), query_buffer.id()];
479        cx.dispatch_action(window_id, chain.clone(), Input("b".into()));
480        cx.dispatch_action(window_id, chain.clone(), Input("n".into()));
481        cx.dispatch_action(window_id, chain.clone(), Input("a".into()));
482        finder
483            .condition(&cx, |finder, _| finder.matches.len() == 2)
484            .await;
485
486        let active_pane = cx.read(|cx| workspace.read(cx).active_pane().clone());
487        cx.dispatch_action(window_id, vec![workspace.id(), finder.id()], SelectNext);
488        cx.dispatch_action(window_id, vec![workspace.id(), finder.id()], Confirm);
489        active_pane
490            .condition(&cx, |pane, _| pane.active_item().is_some())
491            .await;
492        cx.read(|cx| {
493            let active_item = active_pane.read(cx).active_item().unwrap();
494            assert_eq!(active_item.title(cx), "bandana");
495        });
496    }
497
498    #[gpui::test]
499    async fn test_matching_cancellation(mut cx: gpui::TestAppContext) {
500        let params = cx.update(WorkspaceParams::test);
501        let fs = params.fs.as_fake();
502        fs.insert_tree(
503            "/dir",
504            json!({
505                "hello": "",
506                "goodbye": "",
507                "halogen-light": "",
508                "happiness": "",
509                "height": "",
510                "hi": "",
511                "hiccup": "",
512            }),
513        )
514        .await;
515
516        let (_, workspace) = cx.add_window(|cx| Workspace::new(&params, cx));
517        workspace
518            .update(&mut cx, |workspace, cx| {
519                workspace.add_worktree("/dir".as_ref(), cx)
520            })
521            .await
522            .unwrap();
523        cx.read(|cx| workspace.read(cx).worktree_scans_complete(cx))
524            .await;
525        let (_, finder) = cx.add_window(|cx| {
526            FileFinder::new(
527                params.settings.clone(),
528                workspace.read(cx).project().clone(),
529                cx,
530            )
531        });
532
533        let query = "hi".to_string();
534        finder
535            .update(&mut cx, |f, cx| f.spawn_search(query.clone(), cx))
536            .unwrap()
537            .await;
538        finder.read_with(&cx, |f, _| assert_eq!(f.matches.len(), 5));
539
540        finder.update(&mut cx, |finder, cx| {
541            let matches = finder.matches.clone();
542
543            // Simulate a search being cancelled after the time limit,
544            // returning only a subset of the matches that would have been found.
545            finder.spawn_search(query.clone(), cx).unwrap().detach();
546            finder.update_matches(
547                (
548                    finder.latest_search_id,
549                    true, // did-cancel
550                    query.clone(),
551                    vec![matches[1].clone(), matches[3].clone()],
552                ),
553                cx,
554            );
555
556            // Simulate another cancellation.
557            finder.spawn_search(query.clone(), cx).unwrap().detach();
558            finder.update_matches(
559                (
560                    finder.latest_search_id,
561                    true, // did-cancel
562                    query.clone(),
563                    vec![matches[0].clone(), matches[2].clone(), matches[3].clone()],
564                ),
565                cx,
566            );
567
568            assert_eq!(finder.matches, matches[0..4])
569        });
570    }
571
572    #[gpui::test]
573    async fn test_single_file_worktrees(mut cx: gpui::TestAppContext) {
574        let params = cx.update(WorkspaceParams::test);
575        params
576            .fs
577            .as_fake()
578            .insert_tree("/root", json!({ "the-parent-dir": { "the-file": "" } }))
579            .await;
580
581        let (_, workspace) = cx.add_window(|cx| Workspace::new(&params, cx));
582        workspace
583            .update(&mut cx, |workspace, cx| {
584                workspace.add_worktree(Path::new("/root/the-parent-dir/the-file"), cx)
585            })
586            .await
587            .unwrap();
588        cx.read(|cx| workspace.read(cx).worktree_scans_complete(cx))
589            .await;
590        let (_, finder) = cx.add_window(|cx| {
591            FileFinder::new(
592                params.settings.clone(),
593                workspace.read(cx).project().clone(),
594                cx,
595            )
596        });
597
598        // Even though there is only one worktree, that worktree's filename
599        // is included in the matching, because the worktree is a single file.
600        finder
601            .update(&mut cx, |f, cx| f.spawn_search("thf".into(), cx))
602            .unwrap()
603            .await;
604        cx.read(|cx| {
605            let finder = finder.read(cx);
606            assert_eq!(finder.matches.len(), 1);
607
608            let (file_name, file_name_positions, full_path, full_path_positions) =
609                finder.labels_for_match(&finder.matches[0]);
610            assert_eq!(file_name, "the-file");
611            assert_eq!(file_name_positions, &[0, 1, 4]);
612            assert_eq!(full_path, "the-file");
613            assert_eq!(full_path_positions, &[0, 1, 4]);
614        });
615
616        // Since the worktree root is a file, searching for its name followed by a slash does
617        // not match anything.
618        finder
619            .update(&mut cx, |f, cx| f.spawn_search("thf/".into(), cx))
620            .unwrap()
621            .await;
622        finder.read_with(&cx, |f, _| assert_eq!(f.matches.len(), 0));
623    }
624
625    #[gpui::test(retries = 5)]
626    async fn test_multiple_matches_with_same_relative_path(mut cx: gpui::TestAppContext) {
627        let params = cx.update(WorkspaceParams::test);
628        params
629            .fs
630            .as_fake()
631            .insert_tree(
632                "/root",
633                json!({
634                    "dir1": { "a.txt": "" },
635                    "dir2": { "a.txt": "" }
636                }),
637            )
638            .await;
639
640        let (_, workspace) = cx.add_window(|cx| Workspace::new(&params, cx));
641
642        workspace
643            .update(&mut cx, |workspace, cx| {
644                workspace.open_paths(
645                    &[PathBuf::from("/root/dir1"), PathBuf::from("/root/dir2")],
646                    cx,
647                )
648            })
649            .await;
650        cx.read(|cx| workspace.read(cx).worktree_scans_complete(cx))
651            .await;
652
653        let (_, finder) = cx.add_window(|cx| {
654            FileFinder::new(
655                params.settings.clone(),
656                workspace.read(cx).project().clone(),
657                cx,
658            )
659        });
660
661        // Run a search that matches two files with the same relative path.
662        finder
663            .update(&mut cx, |f, cx| f.spawn_search("a.t".into(), cx))
664            .unwrap()
665            .await;
666
667        // Can switch between different matches with the same relative path.
668        finder.update(&mut cx, |f, cx| {
669            assert_eq!(f.matches.len(), 2);
670            assert_eq!(f.selected_index(), 0);
671            f.select_next(&SelectNext, cx);
672            assert_eq!(f.selected_index(), 1);
673            f.select_prev(&SelectPrev, cx);
674            assert_eq!(f.selected_index(), 0);
675        });
676    }
677}