file_finder.rs

  1#[cfg(test)]
  2mod file_finder_tests;
  3
  4use collections::{HashMap, HashSet};
  5use editor::{scroll::Autoscroll, Bias, Editor};
  6use fuzzy::{CharBag, PathMatch, PathMatchCandidate};
  7use gpui::{
  8    actions, rems, AppContext, DismissEvent, EventEmitter, FocusHandle, FocusableView, Model,
  9    ParentElement, Render, Styled, Task, View, ViewContext, VisualContext, WeakView,
 10};
 11use itertools::Itertools;
 12use picker::{Picker, PickerDelegate};
 13use project::{PathMatchCandidateSet, Project, ProjectPath, WorktreeId};
 14use std::{
 15    cmp,
 16    path::{Path, PathBuf},
 17    sync::{
 18        atomic::{self, AtomicBool},
 19        Arc,
 20    },
 21};
 22use text::Point;
 23use ui::{prelude::*, HighlightedLabel, ListItem, ListItemSpacing};
 24use util::{paths::PathLikeWithPosition, post_inc, ResultExt};
 25use workspace::{ModalView, Workspace};
 26
 27actions!(file_finder, [Toggle]);
 28
 29impl ModalView for FileFinder {}
 30
 31pub struct FileFinder {
 32    picker: View<Picker<FileFinderDelegate>>,
 33}
 34
 35pub fn init(cx: &mut AppContext) {
 36    cx.observe_new_views(FileFinder::register).detach();
 37}
 38
 39impl FileFinder {
 40    fn register(workspace: &mut Workspace, _: &mut ViewContext<Workspace>) {
 41        workspace.register_action(|workspace, _: &Toggle, cx| {
 42            let Some(file_finder) = workspace.active_modal::<Self>(cx) else {
 43                Self::open(workspace, cx);
 44                return;
 45            };
 46
 47            file_finder.update(cx, |file_finder, cx| {
 48                file_finder
 49                    .picker
 50                    .update(cx, |picker, cx| picker.cycle_selection(cx))
 51            });
 52        });
 53    }
 54
 55    fn open(workspace: &mut Workspace, cx: &mut ViewContext<Workspace>) {
 56        let project = workspace.project().read(cx);
 57
 58        let currently_opened_path = workspace
 59            .active_item(cx)
 60            .and_then(|item| item.project_path(cx))
 61            .map(|project_path| {
 62                let abs_path = project
 63                    .worktree_for_id(project_path.worktree_id, cx)
 64                    .map(|worktree| worktree.read(cx).abs_path().join(&project_path.path));
 65                FoundPath::new(project_path, abs_path)
 66            });
 67
 68        let history_items = workspace
 69            .recent_navigation_history(Some(MAX_RECENT_SELECTIONS), cx)
 70            .into_iter()
 71            .filter(|(_, history_abs_path)| match history_abs_path {
 72                Some(abs_path) => history_file_exists(abs_path),
 73                None => true,
 74            })
 75            .map(|(history_path, abs_path)| FoundPath::new(history_path, abs_path))
 76            .collect::<Vec<_>>();
 77
 78        let project = workspace.project().clone();
 79        let weak_workspace = cx.view().downgrade();
 80        workspace.toggle_modal(cx, |cx| {
 81            let delegate = FileFinderDelegate::new(
 82                cx.view().downgrade(),
 83                weak_workspace,
 84                project,
 85                currently_opened_path,
 86                history_items,
 87                cx,
 88            );
 89
 90            FileFinder::new(delegate, cx)
 91        });
 92    }
 93
 94    fn new(delegate: FileFinderDelegate, cx: &mut ViewContext<Self>) -> Self {
 95        Self {
 96            picker: cx.new_view(|cx| Picker::uniform_list(delegate, cx)),
 97        }
 98    }
 99}
100
101impl EventEmitter<DismissEvent> for FileFinder {}
102
103impl FocusableView for FileFinder {
104    fn focus_handle(&self, cx: &AppContext) -> FocusHandle {
105        self.picker.focus_handle(cx)
106    }
107}
108
109impl Render for FileFinder {
110    fn render(&mut self, _cx: &mut ViewContext<Self>) -> impl IntoElement {
111        v_flex().w(rems(34.)).child(self.picker.clone())
112    }
113}
114
115pub struct FileFinderDelegate {
116    file_finder: WeakView<FileFinder>,
117    workspace: WeakView<Workspace>,
118    project: Model<Project>,
119    search_count: usize,
120    latest_search_id: usize,
121    latest_search_did_cancel: bool,
122    latest_search_query: Option<PathLikeWithPosition<FileSearchQuery>>,
123    currently_opened_path: Option<FoundPath>,
124    matches: Matches,
125    selected_index: usize,
126    cancel_flag: Arc<AtomicBool>,
127    history_items: Vec<FoundPath>,
128}
129
130/// Use a custom ordering for file finder: the regular one
131/// defines max element with the highest score and the latest alphanumerical path (in case of a tie on other params), e.g:
132/// `[{score: 0.5, path = "c/d" }, { score: 0.5, path = "/a/b" }]`
133///
134/// In the file finder, we would prefer to have the max element with the highest score and the earliest alphanumerical path, e.g:
135/// `[{ score: 0.5, path = "/a/b" }, {score: 0.5, path = "c/d" }]`
136/// as the files are shown in the project panel lists.
137#[derive(Debug, Clone, PartialEq, Eq)]
138struct ProjectPanelOrdMatch(PathMatch);
139
140impl Ord for ProjectPanelOrdMatch {
141    fn cmp(&self, other: &Self) -> cmp::Ordering {
142        self.0
143            .score
144            .partial_cmp(&other.0.score)
145            .unwrap_or(cmp::Ordering::Equal)
146            .then_with(|| self.0.worktree_id.cmp(&other.0.worktree_id))
147            .then_with(|| {
148                other
149                    .0
150                    .distance_to_relative_ancestor
151                    .cmp(&self.0.distance_to_relative_ancestor)
152            })
153            .then_with(|| self.0.path.cmp(&other.0.path).reverse())
154    }
155}
156
157impl PartialOrd for ProjectPanelOrdMatch {
158    fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> {
159        Some(self.cmp(other))
160    }
161}
162
163#[derive(Debug, Default)]
164struct Matches {
165    history: Vec<(FoundPath, Option<ProjectPanelOrdMatch>)>,
166    search: Vec<ProjectPanelOrdMatch>,
167}
168
169#[derive(Debug)]
170enum Match<'a> {
171    History(&'a FoundPath, Option<&'a ProjectPanelOrdMatch>),
172    Search(&'a ProjectPanelOrdMatch),
173}
174
175impl Matches {
176    fn len(&self) -> usize {
177        self.history.len() + self.search.len()
178    }
179
180    fn get(&self, index: usize) -> Option<Match<'_>> {
181        if index < self.history.len() {
182            self.history
183                .get(index)
184                .map(|(path, path_match)| Match::History(path, path_match.as_ref()))
185        } else {
186            self.search
187                .get(index - self.history.len())
188                .map(Match::Search)
189        }
190    }
191
192    fn push_new_matches(
193        &mut self,
194        history_items: &Vec<FoundPath>,
195        currently_opened: Option<&FoundPath>,
196        query: &PathLikeWithPosition<FileSearchQuery>,
197        new_search_matches: impl Iterator<Item = ProjectPanelOrdMatch>,
198        extend_old_matches: bool,
199    ) {
200        let matching_history_paths =
201            matching_history_item_paths(history_items, currently_opened, query);
202        let new_search_matches = new_search_matches
203            .filter(|path_match| !matching_history_paths.contains_key(&path_match.0.path));
204
205        self.set_new_history(
206            currently_opened,
207            Some(&matching_history_paths),
208            history_items,
209        );
210        if extend_old_matches {
211            self.search
212                .retain(|path_match| !matching_history_paths.contains_key(&path_match.0.path));
213        } else {
214            self.search.clear();
215        }
216        util::extend_sorted(&mut self.search, new_search_matches, 100, |a, b| b.cmp(a));
217    }
218
219    fn set_new_history<'a>(
220        &mut self,
221        currently_opened: Option<&'a FoundPath>,
222        query_matches: Option<&'a HashMap<Arc<Path>, ProjectPanelOrdMatch>>,
223        history_items: impl IntoIterator<Item = &'a FoundPath> + 'a,
224    ) {
225        let mut processed_paths = HashSet::default();
226        self.history = history_items
227            .into_iter()
228            .chain(currently_opened)
229            .filter(|&path| processed_paths.insert(path))
230            .filter_map(|history_item| match &query_matches {
231                Some(query_matches) => Some((
232                    history_item.clone(),
233                    Some(query_matches.get(&history_item.project.path)?.clone()),
234                )),
235                None => Some((history_item.clone(), None)),
236            })
237            .enumerate()
238            .sorted_by(
239                |(index_a, (path_a, match_a)), (index_b, (path_b, match_b))| match (
240                    Some(path_a) == currently_opened,
241                    Some(path_b) == currently_opened,
242                ) {
243                    // bubble currently opened files to the top
244                    (true, false) => cmp::Ordering::Less,
245                    (false, true) => cmp::Ordering::Greater,
246                    // arrange the files by their score (best score on top) and by their occurrence in the history
247                    // (history items visited later are on the top)
248                    _ => match_b.cmp(match_a).then(index_a.cmp(index_b)),
249                },
250            )
251            .map(|(_, paths)| paths)
252            .collect();
253    }
254}
255
256fn matching_history_item_paths(
257    history_items: &Vec<FoundPath>,
258    currently_opened: Option<&FoundPath>,
259    query: &PathLikeWithPosition<FileSearchQuery>,
260) -> HashMap<Arc<Path>, ProjectPanelOrdMatch> {
261    let history_items_by_worktrees = history_items
262        .iter()
263        .chain(currently_opened)
264        .filter_map(|found_path| {
265            let candidate = PathMatchCandidate {
266                path: &found_path.project.path,
267                // Only match history items names, otherwise their paths may match too many queries, producing false positives.
268                // E.g. `foo` would match both `something/foo/bar.rs` and `something/foo/foo.rs` and if the former is a history item,
269                // it would be shown first always, despite the latter being a better match.
270                char_bag: CharBag::from_iter(
271                    found_path
272                        .project
273                        .path
274                        .file_name()?
275                        .to_string_lossy()
276                        .to_lowercase()
277                        .chars(),
278                ),
279            };
280            Some((found_path.project.worktree_id, candidate))
281        })
282        .fold(
283            HashMap::default(),
284            |mut candidates, (worktree_id, new_candidate)| {
285                candidates
286                    .entry(worktree_id)
287                    .or_insert_with(Vec::new)
288                    .push(new_candidate);
289                candidates
290            },
291        );
292    let mut matching_history_paths = HashMap::default();
293    for (worktree, candidates) in history_items_by_worktrees {
294        let max_results = candidates.len() + 1;
295        matching_history_paths.extend(
296            fuzzy::match_fixed_path_set(
297                candidates,
298                worktree.to_usize(),
299                query.path_like.path_query(),
300                false,
301                max_results,
302            )
303            .into_iter()
304            .map(|path_match| {
305                (
306                    Arc::clone(&path_match.path),
307                    ProjectPanelOrdMatch(path_match),
308                )
309            }),
310        );
311    }
312    matching_history_paths
313}
314
315#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
316struct FoundPath {
317    project: ProjectPath,
318    absolute: Option<PathBuf>,
319}
320
321impl FoundPath {
322    fn new(project: ProjectPath, absolute: Option<PathBuf>) -> Self {
323        Self { project, absolute }
324    }
325}
326
327const MAX_RECENT_SELECTIONS: usize = 20;
328
329#[cfg(not(test))]
330fn history_file_exists(abs_path: &PathBuf) -> bool {
331    abs_path.exists()
332}
333
334#[cfg(test)]
335fn history_file_exists(abs_path: &PathBuf) -> bool {
336    !abs_path.ends_with("nonexistent.rs")
337}
338
339pub enum Event {
340    Selected(ProjectPath),
341    Dismissed,
342}
343
344#[derive(Debug, Clone)]
345struct FileSearchQuery {
346    raw_query: String,
347    file_query_end: Option<usize>,
348}
349
350impl FileSearchQuery {
351    fn path_query(&self) -> &str {
352        match self.file_query_end {
353            Some(file_path_end) => &self.raw_query[..file_path_end],
354            None => &self.raw_query,
355        }
356    }
357}
358
359impl FileFinderDelegate {
360    fn new(
361        file_finder: WeakView<FileFinder>,
362        workspace: WeakView<Workspace>,
363        project: Model<Project>,
364        currently_opened_path: Option<FoundPath>,
365        history_items: Vec<FoundPath>,
366        cx: &mut ViewContext<FileFinder>,
367    ) -> Self {
368        cx.observe(&project, |file_finder, _, cx| {
369            //todo We should probably not re-render on every project anything
370            file_finder
371                .picker
372                .update(cx, |picker, cx| picker.refresh(cx))
373        })
374        .detach();
375
376        Self {
377            file_finder,
378            workspace,
379            project,
380            search_count: 0,
381            latest_search_id: 0,
382            latest_search_did_cancel: false,
383            latest_search_query: None,
384            currently_opened_path,
385            matches: Matches::default(),
386            selected_index: 0,
387            cancel_flag: Arc::new(AtomicBool::new(false)),
388            history_items,
389        }
390    }
391
392    fn spawn_search(
393        &mut self,
394        query: PathLikeWithPosition<FileSearchQuery>,
395        cx: &mut ViewContext<Picker<Self>>,
396    ) -> Task<()> {
397        let relative_to = self
398            .currently_opened_path
399            .as_ref()
400            .map(|found_path| Arc::clone(&found_path.project.path));
401        let worktrees = self
402            .project
403            .read(cx)
404            .visible_worktrees(cx)
405            .collect::<Vec<_>>();
406        let include_root_name = worktrees.len() > 1;
407        let candidate_sets = worktrees
408            .into_iter()
409            .map(|worktree| {
410                let worktree = worktree.read(cx);
411                PathMatchCandidateSet {
412                    snapshot: worktree.snapshot(),
413                    include_ignored: worktree
414                        .root_entry()
415                        .map_or(false, |entry| entry.is_ignored),
416                    include_root_name,
417                }
418            })
419            .collect::<Vec<_>>();
420
421        let search_id = util::post_inc(&mut self.search_count);
422        self.cancel_flag.store(true, atomic::Ordering::Relaxed);
423        self.cancel_flag = Arc::new(AtomicBool::new(false));
424        let cancel_flag = self.cancel_flag.clone();
425        cx.spawn(|picker, mut cx| async move {
426            let matches = fuzzy::match_path_sets(
427                candidate_sets.as_slice(),
428                query.path_like.path_query(),
429                relative_to,
430                false,
431                100,
432                &cancel_flag,
433                cx.background_executor().clone(),
434            )
435            .await
436            .into_iter()
437            .map(ProjectPanelOrdMatch);
438            let did_cancel = cancel_flag.load(atomic::Ordering::Relaxed);
439            picker
440                .update(&mut cx, |picker, cx| {
441                    picker
442                        .delegate
443                        .set_search_matches(search_id, did_cancel, query, matches, cx)
444                })
445                .log_err();
446        })
447    }
448
449    fn set_search_matches(
450        &mut self,
451        search_id: usize,
452        did_cancel: bool,
453        query: PathLikeWithPosition<FileSearchQuery>,
454        matches: impl IntoIterator<Item = ProjectPanelOrdMatch>,
455        cx: &mut ViewContext<Picker<Self>>,
456    ) {
457        if search_id >= self.latest_search_id {
458            self.latest_search_id = search_id;
459            let extend_old_matches = self.latest_search_did_cancel
460                && Some(query.path_like.path_query())
461                    == self
462                        .latest_search_query
463                        .as_ref()
464                        .map(|query| query.path_like.path_query());
465            self.matches.push_new_matches(
466                &self.history_items,
467                self.currently_opened_path.as_ref(),
468                &query,
469                matches.into_iter(),
470                extend_old_matches,
471            );
472            self.latest_search_query = Some(query);
473            self.latest_search_did_cancel = did_cancel;
474            self.selected_index = self.calculate_selected_index();
475            cx.notify();
476        }
477    }
478
479    fn labels_for_match(
480        &self,
481        path_match: Match,
482        cx: &AppContext,
483        ix: usize,
484    ) -> (String, Vec<usize>, String, Vec<usize>) {
485        let (file_name, file_name_positions, full_path, full_path_positions) = match path_match {
486            Match::History(found_path, found_path_match) => {
487                let worktree_id = found_path.project.worktree_id;
488                let project_relative_path = &found_path.project.path;
489                let has_worktree = self
490                    .project
491                    .read(cx)
492                    .worktree_for_id(worktree_id, cx)
493                    .is_some();
494
495                if !has_worktree {
496                    if let Some(absolute_path) = &found_path.absolute {
497                        return (
498                            absolute_path
499                                .file_name()
500                                .map_or_else(
501                                    || project_relative_path.to_string_lossy(),
502                                    |file_name| file_name.to_string_lossy(),
503                                )
504                                .to_string(),
505                            Vec::new(),
506                            absolute_path.to_string_lossy().to_string(),
507                            Vec::new(),
508                        );
509                    }
510                }
511
512                let mut path = Arc::clone(project_relative_path);
513                if project_relative_path.as_ref() == Path::new("") {
514                    if let Some(absolute_path) = &found_path.absolute {
515                        path = Arc::from(absolute_path.as_path());
516                    }
517                }
518
519                let mut path_match = PathMatch {
520                    score: ix as f64,
521                    positions: Vec::new(),
522                    worktree_id: worktree_id.to_usize(),
523                    path,
524                    path_prefix: "".into(),
525                    distance_to_relative_ancestor: usize::MAX,
526                };
527                if let Some(found_path_match) = found_path_match {
528                    path_match
529                        .positions
530                        .extend(found_path_match.0.positions.iter())
531                }
532
533                self.labels_for_path_match(&path_match)
534            }
535            Match::Search(path_match) => self.labels_for_path_match(&path_match.0),
536        };
537
538        if file_name_positions.is_empty() {
539            if let Some(user_home_path) = std::env::var("HOME").ok() {
540                let user_home_path = user_home_path.trim();
541                if !user_home_path.is_empty() {
542                    if (&full_path).starts_with(user_home_path) {
543                        return (
544                            file_name,
545                            file_name_positions,
546                            full_path.replace(user_home_path, "~"),
547                            full_path_positions,
548                        );
549                    }
550                }
551            }
552        }
553
554        (
555            file_name,
556            file_name_positions,
557            full_path,
558            full_path_positions,
559        )
560    }
561
562    fn labels_for_path_match(
563        &self,
564        path_match: &PathMatch,
565    ) -> (String, Vec<usize>, String, Vec<usize>) {
566        let path = &path_match.path;
567        let path_string = path.to_string_lossy();
568        let full_path = [path_match.path_prefix.as_ref(), path_string.as_ref()].join("");
569        let mut path_positions = path_match.positions.clone();
570
571        let file_name = path.file_name().map_or_else(
572            || path_match.path_prefix.to_string(),
573            |file_name| file_name.to_string_lossy().to_string(),
574        );
575        let file_name_start = path_match.path_prefix.len() + path_string.len() - file_name.len();
576        let file_name_positions = path_positions
577            .iter()
578            .filter_map(|pos| {
579                if pos >= &file_name_start {
580                    Some(pos - file_name_start)
581                } else {
582                    None
583                }
584            })
585            .collect();
586
587        let full_path = full_path.trim_end_matches(&file_name).to_string();
588        path_positions.retain(|idx| *idx < full_path.len());
589
590        (file_name, file_name_positions, full_path, path_positions)
591    }
592
593    fn lookup_absolute_path(
594        &self,
595        query: PathLikeWithPosition<FileSearchQuery>,
596        cx: &mut ViewContext<'_, Picker<Self>>,
597    ) -> Task<()> {
598        cx.spawn(|picker, mut cx| async move {
599            let Some((project, fs)) = picker
600                .update(&mut cx, |picker, cx| {
601                    let fs = Arc::clone(&picker.delegate.project.read(cx).fs());
602                    (picker.delegate.project.clone(), fs)
603                })
604                .log_err()
605            else {
606                return;
607            };
608
609            let query_path = Path::new(query.path_like.path_query());
610            let mut path_matches = Vec::new();
611            match fs.metadata(query_path).await.log_err() {
612                Some(Some(_metadata)) => {
613                    let update_result = project
614                        .update(&mut cx, |project, cx| {
615                            if let Some((worktree, relative_path)) =
616                                project.find_local_worktree(query_path, cx)
617                            {
618                                path_matches.push(ProjectPanelOrdMatch(PathMatch {
619                                    score: 1.0,
620                                    positions: Vec::new(),
621                                    worktree_id: worktree.read(cx).id().to_usize(),
622                                    path: Arc::from(relative_path),
623                                    path_prefix: "".into(),
624                                    distance_to_relative_ancestor: usize::MAX,
625                                }));
626                            }
627                        })
628                        .log_err();
629                    if update_result.is_none() {
630                        return;
631                    }
632                }
633                Some(None) => {}
634                None => return,
635            }
636
637            picker
638                .update(&mut cx, |picker, cx| {
639                    let picker_delegate = &mut picker.delegate;
640                    let search_id = util::post_inc(&mut picker_delegate.search_count);
641                    picker_delegate.set_search_matches(search_id, false, query, path_matches, cx);
642
643                    anyhow::Ok(())
644                })
645                .log_err();
646        })
647    }
648
649    /// Skips first history match (that is displayed topmost) if it's currently opened.
650    fn calculate_selected_index(&self) -> usize {
651        if let Some(Match::History(path, _)) = self.matches.get(0) {
652            if Some(path) == self.currently_opened_path.as_ref() {
653                let elements_after_first = self.matches.len() - 1;
654                if elements_after_first > 0 {
655                    return 1;
656                }
657            }
658        }
659        0
660    }
661}
662
663impl PickerDelegate for FileFinderDelegate {
664    type ListItem = ListItem;
665
666    fn placeholder_text(&self) -> Arc<str> {
667        "Search project files...".into()
668    }
669
670    fn match_count(&self) -> usize {
671        self.matches.len()
672    }
673
674    fn selected_index(&self) -> usize {
675        self.selected_index
676    }
677
678    fn set_selected_index(&mut self, ix: usize, cx: &mut ViewContext<Picker<Self>>) {
679        self.selected_index = ix;
680        cx.notify();
681    }
682
683    fn separators_after_indices(&self) -> Vec<usize> {
684        let history_items = self.matches.history.len();
685        if history_items == 0 || self.matches.search.is_empty() {
686            Vec::new()
687        } else {
688            vec![history_items - 1]
689        }
690    }
691
692    fn update_matches(
693        &mut self,
694        raw_query: String,
695        cx: &mut ViewContext<Picker<Self>>,
696    ) -> Task<()> {
697        let raw_query = raw_query.replace(" ", "");
698        let raw_query = raw_query.trim();
699        if raw_query.is_empty() {
700            let project = self.project.read(cx);
701            self.latest_search_id = post_inc(&mut self.search_count);
702            self.matches = Matches {
703                history: Vec::new(),
704                search: Vec::new(),
705            };
706            self.matches.set_new_history(
707                self.currently_opened_path.as_ref(),
708                None,
709                self.history_items.iter().filter(|history_item| {
710                    project
711                        .worktree_for_id(history_item.project.worktree_id, cx)
712                        .is_some()
713                        || (project.is_local() && history_item.absolute.is_some())
714                }),
715            );
716
717            self.selected_index = self.calculate_selected_index();
718            cx.notify();
719            Task::ready(())
720        } else {
721            let query = PathLikeWithPosition::parse_str(raw_query, |path_like_str| {
722                Ok::<_, std::convert::Infallible>(FileSearchQuery {
723                    raw_query: raw_query.to_owned(),
724                    file_query_end: if path_like_str == raw_query {
725                        None
726                    } else {
727                        Some(path_like_str.len())
728                    },
729                })
730            })
731            .expect("infallible");
732
733            if Path::new(query.path_like.path_query()).is_absolute() {
734                self.lookup_absolute_path(query, cx)
735            } else {
736                self.spawn_search(query, cx)
737            }
738        }
739    }
740
741    fn confirm(&mut self, secondary: bool, cx: &mut ViewContext<Picker<FileFinderDelegate>>) {
742        if let Some(m) = self.matches.get(self.selected_index()) {
743            if let Some(workspace) = self.workspace.upgrade() {
744                let open_task = workspace.update(cx, move |workspace, cx| {
745                    let split_or_open = |workspace: &mut Workspace, project_path, cx| {
746                        if secondary {
747                            workspace.split_path(project_path, cx)
748                        } else {
749                            workspace.open_path(project_path, None, true, cx)
750                        }
751                    };
752                    match m {
753                        Match::History(history_match, _) => {
754                            let worktree_id = history_match.project.worktree_id;
755                            if workspace
756                                .project()
757                                .read(cx)
758                                .worktree_for_id(worktree_id, cx)
759                                .is_some()
760                            {
761                                split_or_open(
762                                    workspace,
763                                    ProjectPath {
764                                        worktree_id,
765                                        path: Arc::clone(&history_match.project.path),
766                                    },
767                                    cx,
768                                )
769                            } else {
770                                match history_match.absolute.as_ref() {
771                                    Some(abs_path) => {
772                                        if secondary {
773                                            workspace.split_abs_path(
774                                                abs_path.to_path_buf(),
775                                                false,
776                                                cx,
777                                            )
778                                        } else {
779                                            workspace.open_abs_path(
780                                                abs_path.to_path_buf(),
781                                                false,
782                                                cx,
783                                            )
784                                        }
785                                    }
786                                    None => split_or_open(
787                                        workspace,
788                                        ProjectPath {
789                                            worktree_id,
790                                            path: Arc::clone(&history_match.project.path),
791                                        },
792                                        cx,
793                                    ),
794                                }
795                            }
796                        }
797                        Match::Search(m) => split_or_open(
798                            workspace,
799                            ProjectPath {
800                                worktree_id: WorktreeId::from_usize(m.0.worktree_id),
801                                path: m.0.path.clone(),
802                            },
803                            cx,
804                        ),
805                    }
806                });
807
808                let row = self
809                    .latest_search_query
810                    .as_ref()
811                    .and_then(|query| query.row)
812                    .map(|row| row.saturating_sub(1));
813                let col = self
814                    .latest_search_query
815                    .as_ref()
816                    .and_then(|query| query.column)
817                    .unwrap_or(0)
818                    .saturating_sub(1);
819                let finder = self.file_finder.clone();
820
821                cx.spawn(|_, mut cx| async move {
822                    let item = open_task.await.log_err()?;
823                    if let Some(row) = row {
824                        if let Some(active_editor) = item.downcast::<Editor>() {
825                            active_editor
826                                .downgrade()
827                                .update(&mut cx, |editor, cx| {
828                                    let snapshot = editor.snapshot(cx).display_snapshot;
829                                    let point = snapshot
830                                        .buffer_snapshot
831                                        .clip_point(Point::new(row, col), Bias::Left);
832                                    editor.change_selections(Some(Autoscroll::center()), cx, |s| {
833                                        s.select_ranges([point..point])
834                                    });
835                                })
836                                .log_err();
837                        }
838                    }
839                    finder.update(&mut cx, |_, cx| cx.emit(DismissEvent)).ok()?;
840
841                    Some(())
842                })
843                .detach();
844            }
845        }
846    }
847
848    fn dismissed(&mut self, cx: &mut ViewContext<Picker<FileFinderDelegate>>) {
849        self.file_finder
850            .update(cx, |_, cx| cx.emit(DismissEvent))
851            .log_err();
852    }
853
854    fn render_match(
855        &self,
856        ix: usize,
857        selected: bool,
858        cx: &mut ViewContext<Picker<Self>>,
859    ) -> Option<Self::ListItem> {
860        let path_match = self
861            .matches
862            .get(ix)
863            .expect("Invalid matches state: no element for index {ix}");
864
865        let (file_name, file_name_positions, full_path, full_path_positions) =
866            self.labels_for_match(path_match, cx, ix);
867
868        Some(
869            ListItem::new(ix)
870                .spacing(ListItemSpacing::Sparse)
871                .inset(true)
872                .selected(selected)
873                .child(
874                    h_flex()
875                        .gap_2()
876                        .child(HighlightedLabel::new(file_name, file_name_positions))
877                        .child(
878                            HighlightedLabel::new(full_path, full_path_positions)
879                                .size(LabelSize::Small)
880                                .color(Color::Muted),
881                        ),
882                ),
883        )
884    }
885}
886
887#[cfg(test)]
888mod tests {
889    use super::*;
890
891    #[test]
892    fn test_custom_project_search_ordering_in_file_finder() {
893        let mut file_finder_sorted_output = vec![
894            ProjectPanelOrdMatch(PathMatch {
895                score: 0.5,
896                positions: Vec::new(),
897                worktree_id: 0,
898                path: Arc::from(Path::new("b0.5")),
899                path_prefix: Arc::from(""),
900                distance_to_relative_ancestor: 0,
901            }),
902            ProjectPanelOrdMatch(PathMatch {
903                score: 1.0,
904                positions: Vec::new(),
905                worktree_id: 0,
906                path: Arc::from(Path::new("c1.0")),
907                path_prefix: Arc::from(""),
908                distance_to_relative_ancestor: 0,
909            }),
910            ProjectPanelOrdMatch(PathMatch {
911                score: 1.0,
912                positions: Vec::new(),
913                worktree_id: 0,
914                path: Arc::from(Path::new("a1.0")),
915                path_prefix: Arc::from(""),
916                distance_to_relative_ancestor: 0,
917            }),
918            ProjectPanelOrdMatch(PathMatch {
919                score: 0.5,
920                positions: Vec::new(),
921                worktree_id: 0,
922                path: Arc::from(Path::new("a0.5")),
923                path_prefix: Arc::from(""),
924                distance_to_relative_ancestor: 0,
925            }),
926            ProjectPanelOrdMatch(PathMatch {
927                score: 1.0,
928                positions: Vec::new(),
929                worktree_id: 0,
930                path: Arc::from(Path::new("b1.0")),
931                path_prefix: Arc::from(""),
932                distance_to_relative_ancestor: 0,
933            }),
934        ];
935        file_finder_sorted_output.sort_by(|a, b| b.cmp(a));
936
937        assert_eq!(
938            file_finder_sorted_output,
939            vec![
940                ProjectPanelOrdMatch(PathMatch {
941                    score: 1.0,
942                    positions: Vec::new(),
943                    worktree_id: 0,
944                    path: Arc::from(Path::new("a1.0")),
945                    path_prefix: Arc::from(""),
946                    distance_to_relative_ancestor: 0,
947                }),
948                ProjectPanelOrdMatch(PathMatch {
949                    score: 1.0,
950                    positions: Vec::new(),
951                    worktree_id: 0,
952                    path: Arc::from(Path::new("b1.0")),
953                    path_prefix: Arc::from(""),
954                    distance_to_relative_ancestor: 0,
955                }),
956                ProjectPanelOrdMatch(PathMatch {
957                    score: 1.0,
958                    positions: Vec::new(),
959                    worktree_id: 0,
960                    path: Arc::from(Path::new("c1.0")),
961                    path_prefix: Arc::from(""),
962                    distance_to_relative_ancestor: 0,
963                }),
964                ProjectPanelOrdMatch(PathMatch {
965                    score: 0.5,
966                    positions: Vec::new(),
967                    worktree_id: 0,
968                    path: Arc::from(Path::new("a0.5")),
969                    path_prefix: Arc::from(""),
970                    distance_to_relative_ancestor: 0,
971                }),
972                ProjectPanelOrdMatch(PathMatch {
973                    score: 0.5,
974                    positions: Vec::new(),
975                    worktree_id: 0,
976                    path: Arc::from(Path::new("b0.5")),
977                    path_prefix: Arc::from(""),
978                    distance_to_relative_ancestor: 0,
979                }),
980            ]
981        );
982    }
983}