file_finder.rs

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