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        Self::subscribe_to_updates(&project, cx);
369        Self {
370            file_finder,
371            workspace,
372            project,
373            search_count: 0,
374            latest_search_id: 0,
375            latest_search_did_cancel: false,
376            latest_search_query: None,
377            currently_opened_path,
378            matches: Matches::default(),
379            selected_index: 0,
380            cancel_flag: Arc::new(AtomicBool::new(false)),
381            history_items,
382        }
383    }
384
385    fn subscribe_to_updates(project: &Model<Project>, cx: &mut ViewContext<FileFinder>) {
386        cx.subscribe(project, |file_finder, _, event, cx| {
387            match event {
388                project::Event::WorktreeUpdatedEntries(_, _)
389                | project::Event::WorktreeAdded
390                | project::Event::WorktreeRemoved(_) => file_finder
391                    .picker
392                    .update(cx, |picker, cx| picker.refresh(cx)),
393                _ => {}
394            };
395        })
396        .detach();
397    }
398
399    fn spawn_search(
400        &mut self,
401        query: PathLikeWithPosition<FileSearchQuery>,
402        cx: &mut ViewContext<Picker<Self>>,
403    ) -> Task<()> {
404        let relative_to = self
405            .currently_opened_path
406            .as_ref()
407            .map(|found_path| Arc::clone(&found_path.project.path));
408        let worktrees = self
409            .project
410            .read(cx)
411            .visible_worktrees(cx)
412            .collect::<Vec<_>>();
413        let include_root_name = worktrees.len() > 1;
414        let candidate_sets = worktrees
415            .into_iter()
416            .map(|worktree| {
417                let worktree = worktree.read(cx);
418                PathMatchCandidateSet {
419                    snapshot: worktree.snapshot(),
420                    include_ignored: worktree
421                        .root_entry()
422                        .map_or(false, |entry| entry.is_ignored),
423                    include_root_name,
424                }
425            })
426            .collect::<Vec<_>>();
427
428        let search_id = util::post_inc(&mut self.search_count);
429        self.cancel_flag.store(true, atomic::Ordering::Relaxed);
430        self.cancel_flag = Arc::new(AtomicBool::new(false));
431        let cancel_flag = self.cancel_flag.clone();
432        cx.spawn(|picker, mut cx| async move {
433            let matches = fuzzy::match_path_sets(
434                candidate_sets.as_slice(),
435                query.path_like.path_query(),
436                relative_to,
437                false,
438                100,
439                &cancel_flag,
440                cx.background_executor().clone(),
441            )
442            .await
443            .into_iter()
444            .map(ProjectPanelOrdMatch);
445            let did_cancel = cancel_flag.load(atomic::Ordering::Relaxed);
446            picker
447                .update(&mut cx, |picker, cx| {
448                    picker
449                        .delegate
450                        .set_search_matches(search_id, did_cancel, query, matches, cx)
451                })
452                .log_err();
453        })
454    }
455
456    fn set_search_matches(
457        &mut self,
458        search_id: usize,
459        did_cancel: bool,
460        query: PathLikeWithPosition<FileSearchQuery>,
461        matches: impl IntoIterator<Item = ProjectPanelOrdMatch>,
462        cx: &mut ViewContext<Picker<Self>>,
463    ) {
464        if search_id >= self.latest_search_id {
465            self.latest_search_id = search_id;
466            let extend_old_matches = self.latest_search_did_cancel
467                && Some(query.path_like.path_query())
468                    == self
469                        .latest_search_query
470                        .as_ref()
471                        .map(|query| query.path_like.path_query());
472            self.matches.push_new_matches(
473                &self.history_items,
474                self.currently_opened_path.as_ref(),
475                &query,
476                matches.into_iter(),
477                extend_old_matches,
478            );
479            self.latest_search_query = Some(query);
480            self.latest_search_did_cancel = did_cancel;
481            self.selected_index = self.calculate_selected_index();
482            cx.notify();
483        }
484    }
485
486    fn labels_for_match(
487        &self,
488        path_match: Match,
489        cx: &AppContext,
490        ix: usize,
491    ) -> (String, Vec<usize>, String, Vec<usize>) {
492        let (file_name, file_name_positions, full_path, full_path_positions) = match path_match {
493            Match::History(found_path, found_path_match) => {
494                let worktree_id = found_path.project.worktree_id;
495                let project_relative_path = &found_path.project.path;
496                let has_worktree = self
497                    .project
498                    .read(cx)
499                    .worktree_for_id(worktree_id, cx)
500                    .is_some();
501
502                if !has_worktree {
503                    if let Some(absolute_path) = &found_path.absolute {
504                        return (
505                            absolute_path
506                                .file_name()
507                                .map_or_else(
508                                    || project_relative_path.to_string_lossy(),
509                                    |file_name| file_name.to_string_lossy(),
510                                )
511                                .to_string(),
512                            Vec::new(),
513                            absolute_path.to_string_lossy().to_string(),
514                            Vec::new(),
515                        );
516                    }
517                }
518
519                let mut path = Arc::clone(project_relative_path);
520                if project_relative_path.as_ref() == Path::new("") {
521                    if let Some(absolute_path) = &found_path.absolute {
522                        path = Arc::from(absolute_path.as_path());
523                    }
524                }
525
526                let mut path_match = PathMatch {
527                    score: ix as f64,
528                    positions: Vec::new(),
529                    worktree_id: worktree_id.to_usize(),
530                    path,
531                    path_prefix: "".into(),
532                    distance_to_relative_ancestor: usize::MAX,
533                };
534                if let Some(found_path_match) = found_path_match {
535                    path_match
536                        .positions
537                        .extend(found_path_match.0.positions.iter())
538                }
539
540                self.labels_for_path_match(&path_match)
541            }
542            Match::Search(path_match) => self.labels_for_path_match(&path_match.0),
543        };
544
545        if file_name_positions.is_empty() {
546            if let Some(user_home_path) = std::env::var("HOME").ok() {
547                let user_home_path = user_home_path.trim();
548                if !user_home_path.is_empty() {
549                    if (&full_path).starts_with(user_home_path) {
550                        return (
551                            file_name,
552                            file_name_positions,
553                            full_path.replace(user_home_path, "~"),
554                            full_path_positions,
555                        );
556                    }
557                }
558            }
559        }
560
561        (
562            file_name,
563            file_name_positions,
564            full_path,
565            full_path_positions,
566        )
567    }
568
569    fn labels_for_path_match(
570        &self,
571        path_match: &PathMatch,
572    ) -> (String, Vec<usize>, String, Vec<usize>) {
573        let path = &path_match.path;
574        let path_string = path.to_string_lossy();
575        let full_path = [path_match.path_prefix.as_ref(), path_string.as_ref()].join("");
576        let mut path_positions = path_match.positions.clone();
577
578        let file_name = path.file_name().map_or_else(
579            || path_match.path_prefix.to_string(),
580            |file_name| file_name.to_string_lossy().to_string(),
581        );
582        let file_name_start = path_match.path_prefix.len() + path_string.len() - file_name.len();
583        let file_name_positions = path_positions
584            .iter()
585            .filter_map(|pos| {
586                if pos >= &file_name_start {
587                    Some(pos - file_name_start)
588                } else {
589                    None
590                }
591            })
592            .collect();
593
594        let full_path = full_path.trim_end_matches(&file_name).to_string();
595        path_positions.retain(|idx| *idx < full_path.len());
596
597        (file_name, file_name_positions, full_path, path_positions)
598    }
599
600    fn lookup_absolute_path(
601        &self,
602        query: PathLikeWithPosition<FileSearchQuery>,
603        cx: &mut ViewContext<'_, Picker<Self>>,
604    ) -> Task<()> {
605        cx.spawn(|picker, mut cx| async move {
606            let Some((project, fs)) = picker
607                .update(&mut cx, |picker, cx| {
608                    let fs = Arc::clone(&picker.delegate.project.read(cx).fs());
609                    (picker.delegate.project.clone(), fs)
610                })
611                .log_err()
612            else {
613                return;
614            };
615
616            let query_path = Path::new(query.path_like.path_query());
617            let mut path_matches = Vec::new();
618            match fs.metadata(query_path).await.log_err() {
619                Some(Some(_metadata)) => {
620                    let update_result = project
621                        .update(&mut cx, |project, cx| {
622                            if let Some((worktree, relative_path)) =
623                                project.find_local_worktree(query_path, cx)
624                            {
625                                path_matches.push(ProjectPanelOrdMatch(PathMatch {
626                                    score: 1.0,
627                                    positions: Vec::new(),
628                                    worktree_id: worktree.read(cx).id().to_usize(),
629                                    path: Arc::from(relative_path),
630                                    path_prefix: "".into(),
631                                    distance_to_relative_ancestor: usize::MAX,
632                                }));
633                            }
634                        })
635                        .log_err();
636                    if update_result.is_none() {
637                        return;
638                    }
639                }
640                Some(None) => {}
641                None => return,
642            }
643
644            picker
645                .update(&mut cx, |picker, cx| {
646                    let picker_delegate = &mut picker.delegate;
647                    let search_id = util::post_inc(&mut picker_delegate.search_count);
648                    picker_delegate.set_search_matches(search_id, false, query, path_matches, cx);
649
650                    anyhow::Ok(())
651                })
652                .log_err();
653        })
654    }
655
656    /// Skips first history match (that is displayed topmost) if it's currently opened.
657    fn calculate_selected_index(&self) -> usize {
658        if let Some(Match::History(path, _)) = self.matches.get(0) {
659            if Some(path) == self.currently_opened_path.as_ref() {
660                let elements_after_first = self.matches.len() - 1;
661                if elements_after_first > 0 {
662                    return 1;
663                }
664            }
665        }
666        0
667    }
668}
669
670impl PickerDelegate for FileFinderDelegate {
671    type ListItem = ListItem;
672
673    fn placeholder_text(&self, _cx: &mut WindowContext) -> Arc<str> {
674        "Search project files...".into()
675    }
676
677    fn match_count(&self) -> usize {
678        self.matches.len()
679    }
680
681    fn selected_index(&self) -> usize {
682        self.selected_index
683    }
684
685    fn set_selected_index(&mut self, ix: usize, cx: &mut ViewContext<Picker<Self>>) {
686        self.selected_index = ix;
687        cx.notify();
688    }
689
690    fn separators_after_indices(&self) -> Vec<usize> {
691        let history_items = self.matches.history.len();
692        if history_items == 0 || self.matches.search.is_empty() {
693            Vec::new()
694        } else {
695            vec![history_items - 1]
696        }
697    }
698
699    fn update_matches(
700        &mut self,
701        raw_query: String,
702        cx: &mut ViewContext<Picker<Self>>,
703    ) -> Task<()> {
704        let raw_query = raw_query.replace(' ', "");
705        let raw_query = raw_query.trim();
706        if raw_query.is_empty() {
707            let project = self.project.read(cx);
708            self.latest_search_id = post_inc(&mut self.search_count);
709            self.matches = Matches {
710                history: Vec::new(),
711                search: Vec::new(),
712            };
713            self.matches.set_new_history(
714                self.currently_opened_path.as_ref(),
715                None,
716                self.history_items.iter().filter(|history_item| {
717                    project
718                        .worktree_for_id(history_item.project.worktree_id, cx)
719                        .is_some()
720                        || (project.is_local() && history_item.absolute.is_some())
721                }),
722            );
723
724            self.selected_index = self.calculate_selected_index();
725            cx.notify();
726            Task::ready(())
727        } else {
728            let query = PathLikeWithPosition::parse_str(raw_query, |path_like_str| {
729                Ok::<_, std::convert::Infallible>(FileSearchQuery {
730                    raw_query: raw_query.to_owned(),
731                    file_query_end: if path_like_str == raw_query {
732                        None
733                    } else {
734                        Some(path_like_str.len())
735                    },
736                })
737            })
738            .expect("infallible");
739
740            if Path::new(query.path_like.path_query()).is_absolute() {
741                self.lookup_absolute_path(query, cx)
742            } else {
743                self.spawn_search(query, cx)
744            }
745        }
746    }
747
748    fn confirm(&mut self, secondary: bool, cx: &mut ViewContext<Picker<FileFinderDelegate>>) {
749        if let Some(m) = self.matches.get(self.selected_index()) {
750            if let Some(workspace) = self.workspace.upgrade() {
751                let open_task = workspace.update(cx, move |workspace, cx| {
752                    let split_or_open = |workspace: &mut Workspace, project_path, cx| {
753                        if secondary {
754                            workspace.split_path(project_path, cx)
755                        } else {
756                            workspace.open_path(project_path, None, true, cx)
757                        }
758                    };
759                    match m {
760                        Match::History(history_match, _) => {
761                            let worktree_id = history_match.project.worktree_id;
762                            if workspace
763                                .project()
764                                .read(cx)
765                                .worktree_for_id(worktree_id, cx)
766                                .is_some()
767                            {
768                                split_or_open(
769                                    workspace,
770                                    ProjectPath {
771                                        worktree_id,
772                                        path: Arc::clone(&history_match.project.path),
773                                    },
774                                    cx,
775                                )
776                            } else {
777                                match history_match.absolute.as_ref() {
778                                    Some(abs_path) => {
779                                        if secondary {
780                                            workspace.split_abs_path(
781                                                abs_path.to_path_buf(),
782                                                false,
783                                                cx,
784                                            )
785                                        } else {
786                                            workspace.open_abs_path(
787                                                abs_path.to_path_buf(),
788                                                false,
789                                                cx,
790                                            )
791                                        }
792                                    }
793                                    None => split_or_open(
794                                        workspace,
795                                        ProjectPath {
796                                            worktree_id,
797                                            path: Arc::clone(&history_match.project.path),
798                                        },
799                                        cx,
800                                    ),
801                                }
802                            }
803                        }
804                        Match::Search(m) => split_or_open(
805                            workspace,
806                            ProjectPath {
807                                worktree_id: WorktreeId::from_usize(m.0.worktree_id),
808                                path: m.0.path.clone(),
809                            },
810                            cx,
811                        ),
812                    }
813                });
814
815                let row = self
816                    .latest_search_query
817                    .as_ref()
818                    .and_then(|query| query.row)
819                    .map(|row| row.saturating_sub(1));
820                let col = self
821                    .latest_search_query
822                    .as_ref()
823                    .and_then(|query| query.column)
824                    .unwrap_or(0)
825                    .saturating_sub(1);
826                let finder = self.file_finder.clone();
827
828                cx.spawn(|_, mut cx| async move {
829                    let item = open_task.await.log_err()?;
830                    if let Some(row) = row {
831                        if let Some(active_editor) = item.downcast::<Editor>() {
832                            active_editor
833                                .downgrade()
834                                .update(&mut cx, |editor, cx| {
835                                    let snapshot = editor.snapshot(cx).display_snapshot;
836                                    let point = snapshot
837                                        .buffer_snapshot
838                                        .clip_point(Point::new(row, col), Bias::Left);
839                                    editor.change_selections(Some(Autoscroll::center()), cx, |s| {
840                                        s.select_ranges([point..point])
841                                    });
842                                })
843                                .log_err();
844                        }
845                    }
846                    finder.update(&mut cx, |_, cx| cx.emit(DismissEvent)).ok()?;
847
848                    Some(())
849                })
850                .detach();
851            }
852        }
853    }
854
855    fn dismissed(&mut self, cx: &mut ViewContext<Picker<FileFinderDelegate>>) {
856        self.file_finder
857            .update(cx, |_, cx| cx.emit(DismissEvent))
858            .log_err();
859    }
860
861    fn render_match(
862        &self,
863        ix: usize,
864        selected: bool,
865        cx: &mut ViewContext<Picker<Self>>,
866    ) -> Option<Self::ListItem> {
867        let path_match = self
868            .matches
869            .get(ix)
870            .expect("Invalid matches state: no element for index {ix}");
871
872        let (file_name, file_name_positions, full_path, full_path_positions) =
873            self.labels_for_match(path_match, cx, ix);
874
875        Some(
876            ListItem::new(ix)
877                .spacing(ListItemSpacing::Sparse)
878                .inset(true)
879                .selected(selected)
880                .child(
881                    h_flex()
882                        .gap_2()
883                        .py_px()
884                        .child(HighlightedLabel::new(file_name, file_name_positions))
885                        .child(
886                            HighlightedLabel::new(full_path, full_path_positions)
887                                .size(LabelSize::Small)
888                                .color(Color::Muted),
889                        ),
890                ),
891        )
892    }
893}
894
895#[cfg(test)]
896mod tests {
897    use super::*;
898
899    #[test]
900    fn test_custom_project_search_ordering_in_file_finder() {
901        let mut file_finder_sorted_output = vec![
902            ProjectPanelOrdMatch(PathMatch {
903                score: 0.5,
904                positions: Vec::new(),
905                worktree_id: 0,
906                path: Arc::from(Path::new("b0.5")),
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("c1.0")),
915                path_prefix: Arc::from(""),
916                distance_to_relative_ancestor: 0,
917            }),
918            ProjectPanelOrdMatch(PathMatch {
919                score: 1.0,
920                positions: Vec::new(),
921                worktree_id: 0,
922                path: Arc::from(Path::new("a1.0")),
923                path_prefix: Arc::from(""),
924                distance_to_relative_ancestor: 0,
925            }),
926            ProjectPanelOrdMatch(PathMatch {
927                score: 0.5,
928                positions: Vec::new(),
929                worktree_id: 0,
930                path: Arc::from(Path::new("a0.5")),
931                path_prefix: Arc::from(""),
932                distance_to_relative_ancestor: 0,
933            }),
934            ProjectPanelOrdMatch(PathMatch {
935                score: 1.0,
936                positions: Vec::new(),
937                worktree_id: 0,
938                path: Arc::from(Path::new("b1.0")),
939                path_prefix: Arc::from(""),
940                distance_to_relative_ancestor: 0,
941            }),
942        ];
943        file_finder_sorted_output.sort_by(|a, b| b.cmp(a));
944
945        assert_eq!(
946            file_finder_sorted_output,
947            vec![
948                ProjectPanelOrdMatch(PathMatch {
949                    score: 1.0,
950                    positions: Vec::new(),
951                    worktree_id: 0,
952                    path: Arc::from(Path::new("a1.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("b1.0")),
961                    path_prefix: Arc::from(""),
962                    distance_to_relative_ancestor: 0,
963                }),
964                ProjectPanelOrdMatch(PathMatch {
965                    score: 1.0,
966                    positions: Vec::new(),
967                    worktree_id: 0,
968                    path: Arc::from(Path::new("c1.0")),
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("a0.5")),
977                    path_prefix: Arc::from(""),
978                    distance_to_relative_ancestor: 0,
979                }),
980                ProjectPanelOrdMatch(PathMatch {
981                    score: 0.5,
982                    positions: Vec::new(),
983                    worktree_id: 0,
984                    path: Arc::from(Path::new("b0.5")),
985                    path_prefix: Arc::from(""),
986                    distance_to_relative_ancestor: 0,
987                }),
988            ]
989        );
990    }
991}