file_finder.rs

   1#[cfg(test)]
   2mod file_finder_tests;
   3
   4mod file_finder_settings;
   5mod new_path_prompt;
   6mod open_path_prompt;
   7
   8pub use open_path_prompt::OpenPathDelegate;
   9
  10use collections::HashMap;
  11use editor::{scroll::Autoscroll, Bias, Editor};
  12use file_finder_settings::FileFinderSettings;
  13use file_icons::FileIcons;
  14use fuzzy::{CharBag, PathMatch, PathMatchCandidate};
  15use gpui::{
  16    actions, rems, Action, AnyElement, AppContext, DismissEvent, EventEmitter, FocusHandle,
  17    FocusableView, Model, Modifiers, ModifiersChangedEvent, ParentElement, Render, Styled, Task,
  18    View, ViewContext, VisualContext, WeakView,
  19};
  20use new_path_prompt::NewPathPrompt;
  21use open_path_prompt::OpenPathPrompt;
  22use picker::{Picker, PickerDelegate};
  23use project::{PathMatchCandidateSet, Project, ProjectPath, WorktreeId};
  24use settings::Settings;
  25use std::{
  26    cmp,
  27    path::{Path, PathBuf},
  28    sync::{
  29        atomic::{self, AtomicBool},
  30        Arc,
  31    },
  32};
  33use text::Point;
  34use ui::{prelude::*, HighlightedLabel, ListItem, ListItemSpacing};
  35use util::{paths::PathWithPosition, post_inc, ResultExt};
  36use workspace::{item::PreviewTabsSettings, notifications::NotifyResultExt, ModalView, Workspace};
  37
  38actions!(file_finder, [SelectPrev]);
  39
  40impl ModalView for FileFinder {}
  41
  42pub struct FileFinder {
  43    picker: View<Picker<FileFinderDelegate>>,
  44    init_modifiers: Option<Modifiers>,
  45}
  46
  47pub fn init_settings(cx: &mut AppContext) {
  48    FileFinderSettings::register(cx);
  49}
  50
  51pub fn init(cx: &mut AppContext) {
  52    init_settings(cx);
  53    cx.observe_new_views(FileFinder::register).detach();
  54    cx.observe_new_views(NewPathPrompt::register).detach();
  55    cx.observe_new_views(OpenPathPrompt::register).detach();
  56}
  57
  58impl FileFinder {
  59    fn register(workspace: &mut Workspace, _: &mut ViewContext<Workspace>) {
  60        workspace.register_action(|workspace, action: &workspace::ToggleFileFinder, cx| {
  61            let Some(file_finder) = workspace.active_modal::<Self>(cx) else {
  62                Self::open(workspace, action.separate_history, cx);
  63                return;
  64            };
  65
  66            file_finder.update(cx, |file_finder, cx| {
  67                file_finder.init_modifiers = Some(cx.modifiers());
  68                file_finder.picker.update(cx, |picker, cx| {
  69                    picker.cycle_selection(cx);
  70                });
  71            });
  72        });
  73    }
  74
  75    fn open(workspace: &mut Workspace, separate_history: bool, cx: &mut ViewContext<Workspace>) {
  76        let project = workspace.project().read(cx);
  77
  78        let currently_opened_path = workspace
  79            .active_item(cx)
  80            .and_then(|item| item.project_path(cx))
  81            .map(|project_path| {
  82                let abs_path = project
  83                    .worktree_for_id(project_path.worktree_id, cx)
  84                    .map(|worktree| worktree.read(cx).abs_path().join(&project_path.path));
  85                FoundPath::new(project_path, abs_path)
  86            });
  87
  88        let history_items = workspace
  89            .recent_navigation_history(Some(MAX_RECENT_SELECTIONS), cx)
  90            .into_iter()
  91            .filter(|(_, history_abs_path)| match history_abs_path {
  92                Some(abs_path) => history_file_exists(abs_path),
  93                None => true,
  94            })
  95            .map(|(history_path, abs_path)| FoundPath::new(history_path, abs_path))
  96            .collect::<Vec<_>>();
  97
  98        let project = workspace.project().clone();
  99        let weak_workspace = cx.view().downgrade();
 100        workspace.toggle_modal(cx, |cx| {
 101            let delegate = FileFinderDelegate::new(
 102                cx.view().downgrade(),
 103                weak_workspace,
 104                project,
 105                currently_opened_path,
 106                history_items,
 107                separate_history,
 108                cx,
 109            );
 110
 111            FileFinder::new(delegate, cx)
 112        });
 113    }
 114
 115    fn new(delegate: FileFinderDelegate, cx: &mut ViewContext<Self>) -> Self {
 116        Self {
 117            picker: cx.new_view(|cx| Picker::uniform_list(delegate, cx)),
 118            init_modifiers: cx.modifiers().modified().then_some(cx.modifiers()),
 119        }
 120    }
 121
 122    fn handle_modifiers_changed(
 123        &mut self,
 124        event: &ModifiersChangedEvent,
 125        cx: &mut ViewContext<Self>,
 126    ) {
 127        let Some(init_modifiers) = self.init_modifiers.take() else {
 128            return;
 129        };
 130        if self.picker.read(cx).delegate.has_changed_selected_index {
 131            if !event.modified() || !init_modifiers.is_subset_of(&event) {
 132                self.init_modifiers = None;
 133                cx.dispatch_action(menu::Confirm.boxed_clone());
 134            }
 135        }
 136    }
 137
 138    fn handle_select_prev(&mut self, _: &SelectPrev, cx: &mut ViewContext<Self>) {
 139        self.init_modifiers = Some(cx.modifiers());
 140        cx.dispatch_action(Box::new(menu::SelectPrev));
 141    }
 142}
 143
 144impl EventEmitter<DismissEvent> for FileFinder {}
 145
 146impl FocusableView for FileFinder {
 147    fn focus_handle(&self, cx: &AppContext) -> FocusHandle {
 148        self.picker.focus_handle(cx)
 149    }
 150}
 151
 152impl Render for FileFinder {
 153    fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
 154        v_flex()
 155            .key_context("FileFinder")
 156            .w(rems(34.))
 157            .on_modifiers_changed(cx.listener(Self::handle_modifiers_changed))
 158            .on_action(cx.listener(Self::handle_select_prev))
 159            .child(self.picker.clone())
 160    }
 161}
 162
 163pub struct FileFinderDelegate {
 164    file_finder: WeakView<FileFinder>,
 165    workspace: WeakView<Workspace>,
 166    project: Model<Project>,
 167    search_count: usize,
 168    latest_search_id: usize,
 169    latest_search_did_cancel: bool,
 170    latest_search_query: Option<FileSearchQuery>,
 171    currently_opened_path: Option<FoundPath>,
 172    matches: Matches,
 173    selected_index: usize,
 174    has_changed_selected_index: bool,
 175    cancel_flag: Arc<AtomicBool>,
 176    history_items: Vec<FoundPath>,
 177    separate_history: bool,
 178    first_update: bool,
 179}
 180
 181/// Use a custom ordering for file finder: the regular one
 182/// defines max element with the highest score and the latest alphanumerical path (in case of a tie on other params), e.g:
 183/// `[{score: 0.5, path = "c/d" }, { score: 0.5, path = "/a/b" }]`
 184///
 185/// In the file finder, we would prefer to have the max element with the highest score and the earliest alphanumerical path, e.g:
 186/// `[{ score: 0.5, path = "/a/b" }, {score: 0.5, path = "c/d" }]`
 187/// as the files are shown in the project panel lists.
 188#[derive(Debug, Clone, PartialEq, Eq)]
 189struct ProjectPanelOrdMatch(PathMatch);
 190
 191impl Ord for ProjectPanelOrdMatch {
 192    fn cmp(&self, other: &Self) -> cmp::Ordering {
 193        self.0
 194            .score
 195            .partial_cmp(&other.0.score)
 196            .unwrap_or(cmp::Ordering::Equal)
 197            .then_with(|| self.0.worktree_id.cmp(&other.0.worktree_id))
 198            .then_with(|| {
 199                other
 200                    .0
 201                    .distance_to_relative_ancestor
 202                    .cmp(&self.0.distance_to_relative_ancestor)
 203            })
 204            .then_with(|| self.0.path.cmp(&other.0.path).reverse())
 205    }
 206}
 207
 208impl PartialOrd for ProjectPanelOrdMatch {
 209    fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> {
 210        Some(self.cmp(other))
 211    }
 212}
 213
 214#[derive(Debug, Default)]
 215struct Matches {
 216    separate_history: bool,
 217    matches: Vec<Match>,
 218}
 219
 220#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone)]
 221enum Match {
 222    History {
 223        path: FoundPath,
 224        panel_match: Option<ProjectPanelOrdMatch>,
 225    },
 226    Search(ProjectPanelOrdMatch),
 227}
 228
 229impl Match {
 230    fn path(&self) -> &Arc<Path> {
 231        match self {
 232            Match::History { path, .. } => &path.project.path,
 233            Match::Search(panel_match) => &panel_match.0.path,
 234        }
 235    }
 236
 237    fn panel_match(&self) -> Option<&ProjectPanelOrdMatch> {
 238        match self {
 239            Match::History { panel_match, .. } => panel_match.as_ref(),
 240            Match::Search(panel_match) => Some(&panel_match),
 241        }
 242    }
 243}
 244
 245impl Matches {
 246    fn len(&self) -> usize {
 247        self.matches.len()
 248    }
 249
 250    fn get(&self, index: usize) -> Option<&Match> {
 251        self.matches.get(index)
 252    }
 253
 254    fn position(
 255        &self,
 256        entry: &Match,
 257        currently_opened: Option<&FoundPath>,
 258    ) -> Result<usize, usize> {
 259        if let Match::History {
 260            path,
 261            panel_match: None,
 262        } = entry
 263        {
 264            // Slow case: linear search by path. Should not happen actually,
 265            // since we call `position` only if matches set changed, but the query has not changed.
 266            // And History entries do not have panel_match if query is empty, so there's no
 267            // reason for the matches set to change.
 268            self.matches
 269                .iter()
 270                .position(|m| path.project.path == *m.path())
 271                .ok_or(0)
 272        } else {
 273            self.matches.binary_search_by(|m| {
 274                // `reverse()` since if cmp_matches(a, b) == Ordering::Greater, then a is better than b.
 275                // And we want the better entries go first.
 276                Self::cmp_matches(self.separate_history, currently_opened, &m, &entry).reverse()
 277            })
 278        }
 279    }
 280
 281    fn push_new_matches<'a>(
 282        &'a mut self,
 283        history_items: impl IntoIterator<Item = &'a FoundPath> + Clone,
 284        currently_opened: Option<&'a FoundPath>,
 285        query: Option<&FileSearchQuery>,
 286        new_search_matches: impl Iterator<Item = ProjectPanelOrdMatch>,
 287        extend_old_matches: bool,
 288    ) {
 289        let Some(query) = query else {
 290            // assuming that if there's no query, then there's no search matches.
 291            self.matches.clear();
 292            let path_to_entry = |found_path: &FoundPath| Match::History {
 293                path: found_path.clone(),
 294                panel_match: None,
 295            };
 296            self.matches
 297                .extend(currently_opened.into_iter().map(path_to_entry));
 298
 299            self.matches.extend(
 300                history_items
 301                    .into_iter()
 302                    .filter(|found_path| Some(*found_path) != currently_opened)
 303                    .map(path_to_entry),
 304            );
 305            return;
 306        };
 307
 308        let new_history_matches = matching_history_items(history_items, currently_opened, query);
 309        let new_search_matches: Vec<Match> = new_search_matches
 310            .filter(|path_match| !new_history_matches.contains_key(&path_match.0.path))
 311            .map(Match::Search)
 312            .collect();
 313
 314        if extend_old_matches {
 315            // since we take history matches instead of new search matches
 316            // and history matches has not changed(since the query has not changed and we do not extend old matches otherwise),
 317            // old matches can't contain paths present in history_matches as well.
 318            self.matches.retain(|m| matches!(m, Match::Search(_)));
 319        } else {
 320            self.matches.clear();
 321        }
 322
 323        // At this point we have an unsorted set of new history matches, an unsorted set of new search matches
 324        // and a sorted set of old search matches.
 325        // It is possible that the new search matches' paths contain some of the old search matches' paths.
 326        // History matches' paths are unique, since store in a HashMap by path.
 327        // We build a sorted Vec<Match>, eliminating duplicate search matches.
 328        // Search matches with the same paths should have equal `ProjectPanelOrdMatch`, so we should
 329        // not have any duplicates after building the final list.
 330        for new_match in new_history_matches
 331            .into_values()
 332            .chain(new_search_matches.into_iter())
 333        {
 334            match self.position(&new_match, currently_opened) {
 335                Ok(_duplicate) => continue,
 336                Err(i) => {
 337                    self.matches.insert(i, new_match);
 338                    if self.matches.len() == 100 {
 339                        break;
 340                    }
 341                }
 342            }
 343        }
 344    }
 345
 346    /// If a < b, then a is a worse match, aligning with the `ProjectPanelOrdMatch` ordering.
 347    fn cmp_matches(
 348        separate_history: bool,
 349        currently_opened: Option<&FoundPath>,
 350        a: &Match,
 351        b: &Match,
 352    ) -> cmp::Ordering {
 353        debug_assert!(a.panel_match().is_some() && b.panel_match().is_some());
 354
 355        match (&a, &b) {
 356            // bubble currently opened files to the top
 357            (Match::History { path, .. }, _) if Some(path) == currently_opened => {
 358                cmp::Ordering::Greater
 359            }
 360            (_, Match::History { path, .. }) if Some(path) == currently_opened => {
 361                cmp::Ordering::Less
 362            }
 363
 364            (Match::History { .. }, Match::Search(_)) if separate_history => cmp::Ordering::Greater,
 365            (Match::Search(_), Match::History { .. }) if separate_history => cmp::Ordering::Less,
 366
 367            _ => a.panel_match().cmp(&b.panel_match()),
 368        }
 369    }
 370}
 371
 372fn matching_history_items<'a>(
 373    history_items: impl IntoIterator<Item = &'a FoundPath>,
 374    currently_opened: Option<&'a FoundPath>,
 375    query: &FileSearchQuery,
 376) -> HashMap<Arc<Path>, Match> {
 377    let mut candidates_paths = HashMap::default();
 378
 379    let history_items_by_worktrees = history_items
 380        .into_iter()
 381        .chain(currently_opened)
 382        .filter_map(|found_path| {
 383            let candidate = PathMatchCandidate {
 384                is_dir: false, // You can't open directories as project items
 385                path: &found_path.project.path,
 386                // Only match history items names, otherwise their paths may match too many queries, producing false positives.
 387                // E.g. `foo` would match both `something/foo/bar.rs` and `something/foo/foo.rs` and if the former is a history item,
 388                // it would be shown first always, despite the latter being a better match.
 389                char_bag: CharBag::from_iter(
 390                    found_path
 391                        .project
 392                        .path
 393                        .file_name()?
 394                        .to_string_lossy()
 395                        .to_lowercase()
 396                        .chars(),
 397                ),
 398            };
 399            candidates_paths.insert(&found_path.project, found_path);
 400            Some((found_path.project.worktree_id, candidate))
 401        })
 402        .fold(
 403            HashMap::default(),
 404            |mut candidates, (worktree_id, new_candidate)| {
 405                candidates
 406                    .entry(worktree_id)
 407                    .or_insert_with(Vec::new)
 408                    .push(new_candidate);
 409                candidates
 410            },
 411        );
 412    let mut matching_history_paths = HashMap::default();
 413    for (worktree, candidates) in history_items_by_worktrees {
 414        let max_results = candidates.len() + 1;
 415        matching_history_paths.extend(
 416            fuzzy::match_fixed_path_set(
 417                candidates,
 418                worktree.to_usize(),
 419                query.path_query(),
 420                false,
 421                max_results,
 422            )
 423            .into_iter()
 424            .filter_map(|path_match| {
 425                candidates_paths
 426                    .remove_entry(&ProjectPath {
 427                        worktree_id: WorktreeId::from_usize(path_match.worktree_id),
 428                        path: Arc::clone(&path_match.path),
 429                    })
 430                    .map(|(_, found_path)| {
 431                        (
 432                            Arc::clone(&path_match.path),
 433                            Match::History {
 434                                path: found_path.clone(),
 435                                panel_match: Some(ProjectPanelOrdMatch(path_match)),
 436                            },
 437                        )
 438                    })
 439            }),
 440        );
 441    }
 442    matching_history_paths
 443}
 444
 445#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
 446struct FoundPath {
 447    project: ProjectPath,
 448    absolute: Option<PathBuf>,
 449}
 450
 451impl FoundPath {
 452    fn new(project: ProjectPath, absolute: Option<PathBuf>) -> Self {
 453        Self { project, absolute }
 454    }
 455}
 456
 457const MAX_RECENT_SELECTIONS: usize = 20;
 458
 459#[cfg(not(test))]
 460fn history_file_exists(abs_path: &PathBuf) -> bool {
 461    abs_path.exists()
 462}
 463
 464#[cfg(test)]
 465fn history_file_exists(abs_path: &Path) -> bool {
 466    !abs_path.ends_with("nonexistent.rs")
 467}
 468
 469pub enum Event {
 470    Selected(ProjectPath),
 471    Dismissed,
 472}
 473
 474#[derive(Debug, Clone)]
 475struct FileSearchQuery {
 476    raw_query: String,
 477    file_query_end: Option<usize>,
 478    path_position: PathWithPosition,
 479}
 480
 481impl FileSearchQuery {
 482    fn path_query(&self) -> &str {
 483        match self.file_query_end {
 484            Some(file_path_end) => &self.raw_query[..file_path_end],
 485            None => &self.raw_query,
 486        }
 487    }
 488}
 489
 490impl FileFinderDelegate {
 491    fn new(
 492        file_finder: WeakView<FileFinder>,
 493        workspace: WeakView<Workspace>,
 494        project: Model<Project>,
 495        currently_opened_path: Option<FoundPath>,
 496        history_items: Vec<FoundPath>,
 497        separate_history: bool,
 498        cx: &mut ViewContext<FileFinder>,
 499    ) -> Self {
 500        Self::subscribe_to_updates(&project, cx);
 501        Self {
 502            file_finder,
 503            workspace,
 504            project,
 505            search_count: 0,
 506            latest_search_id: 0,
 507            latest_search_did_cancel: false,
 508            latest_search_query: None,
 509            currently_opened_path,
 510            matches: Matches::default(),
 511            has_changed_selected_index: false,
 512            selected_index: 0,
 513            cancel_flag: Arc::new(AtomicBool::new(false)),
 514            history_items,
 515            separate_history,
 516            first_update: true,
 517        }
 518    }
 519
 520    fn subscribe_to_updates(project: &Model<Project>, cx: &mut ViewContext<FileFinder>) {
 521        cx.subscribe(project, |file_finder, _, event, cx| {
 522            match event {
 523                project::Event::WorktreeUpdatedEntries(_, _)
 524                | project::Event::WorktreeAdded
 525                | project::Event::WorktreeRemoved(_) => file_finder
 526                    .picker
 527                    .update(cx, |picker, cx| picker.refresh(cx)),
 528                _ => {}
 529            };
 530        })
 531        .detach();
 532    }
 533
 534    fn spawn_search(
 535        &mut self,
 536        query: FileSearchQuery,
 537        cx: &mut ViewContext<Picker<Self>>,
 538    ) -> Task<()> {
 539        let relative_to = self
 540            .currently_opened_path
 541            .as_ref()
 542            .map(|found_path| Arc::clone(&found_path.project.path));
 543        let worktrees = self
 544            .project
 545            .read(cx)
 546            .visible_worktrees(cx)
 547            .collect::<Vec<_>>();
 548        let include_root_name = worktrees.len() > 1;
 549        let candidate_sets = worktrees
 550            .into_iter()
 551            .map(|worktree| {
 552                let worktree = worktree.read(cx);
 553                PathMatchCandidateSet {
 554                    snapshot: worktree.snapshot(),
 555                    include_ignored: worktree
 556                        .root_entry()
 557                        .map_or(false, |entry| entry.is_ignored),
 558                    include_root_name,
 559                    candidates: project::Candidates::Files,
 560                }
 561            })
 562            .collect::<Vec<_>>();
 563
 564        let search_id = util::post_inc(&mut self.search_count);
 565        self.cancel_flag.store(true, atomic::Ordering::Relaxed);
 566        self.cancel_flag = Arc::new(AtomicBool::new(false));
 567        let cancel_flag = self.cancel_flag.clone();
 568        cx.spawn(|picker, mut cx| async move {
 569            let matches = fuzzy::match_path_sets(
 570                candidate_sets.as_slice(),
 571                query.path_query(),
 572                relative_to,
 573                false,
 574                100,
 575                &cancel_flag,
 576                cx.background_executor().clone(),
 577            )
 578            .await
 579            .into_iter()
 580            .map(ProjectPanelOrdMatch);
 581            let did_cancel = cancel_flag.load(atomic::Ordering::Relaxed);
 582            picker
 583                .update(&mut cx, |picker, cx| {
 584                    picker
 585                        .delegate
 586                        .set_search_matches(search_id, did_cancel, query, matches, cx)
 587                })
 588                .log_err();
 589        })
 590    }
 591
 592    fn set_search_matches(
 593        &mut self,
 594        search_id: usize,
 595        did_cancel: bool,
 596        query: FileSearchQuery,
 597        matches: impl IntoIterator<Item = ProjectPanelOrdMatch>,
 598        cx: &mut ViewContext<Picker<Self>>,
 599    ) {
 600        if search_id >= self.latest_search_id {
 601            self.latest_search_id = search_id;
 602            let query_changed = Some(query.path_query())
 603                != self
 604                    .latest_search_query
 605                    .as_ref()
 606                    .map(|query| query.path_query());
 607            let extend_old_matches = self.latest_search_did_cancel && !query_changed;
 608
 609            let selected_match = if query_changed {
 610                None
 611            } else {
 612                self.matches.get(self.selected_index).cloned()
 613            };
 614
 615            self.matches.push_new_matches(
 616                &self.history_items,
 617                self.currently_opened_path.as_ref(),
 618                Some(&query),
 619                matches.into_iter(),
 620                extend_old_matches,
 621            );
 622
 623            self.selected_index = selected_match.map_or_else(
 624                || self.calculate_selected_index(),
 625                |m| {
 626                    self.matches
 627                        .position(&m, self.currently_opened_path.as_ref())
 628                        .unwrap_or(0)
 629                },
 630            );
 631
 632            self.latest_search_query = Some(query);
 633            self.latest_search_did_cancel = did_cancel;
 634
 635            cx.notify();
 636        }
 637    }
 638
 639    fn labels_for_match(
 640        &self,
 641        path_match: &Match,
 642        cx: &AppContext,
 643        ix: usize,
 644    ) -> (String, Vec<usize>, String, Vec<usize>) {
 645        let (file_name, file_name_positions, full_path, full_path_positions) = match &path_match {
 646            Match::History {
 647                path: entry_path,
 648                panel_match,
 649            } => {
 650                let worktree_id = entry_path.project.worktree_id;
 651                let project_relative_path = &entry_path.project.path;
 652                let has_worktree = self
 653                    .project
 654                    .read(cx)
 655                    .worktree_for_id(worktree_id, cx)
 656                    .is_some();
 657
 658                if !has_worktree {
 659                    if let Some(absolute_path) = &entry_path.absolute {
 660                        return (
 661                            absolute_path
 662                                .file_name()
 663                                .map_or_else(
 664                                    || project_relative_path.to_string_lossy(),
 665                                    |file_name| file_name.to_string_lossy(),
 666                                )
 667                                .to_string(),
 668                            Vec::new(),
 669                            absolute_path.to_string_lossy().to_string(),
 670                            Vec::new(),
 671                        );
 672                    }
 673                }
 674
 675                let mut path = Arc::clone(project_relative_path);
 676                if project_relative_path.as_ref() == Path::new("") {
 677                    if let Some(absolute_path) = &entry_path.absolute {
 678                        path = Arc::from(absolute_path.as_path());
 679                    }
 680                }
 681
 682                let mut path_match = PathMatch {
 683                    score: ix as f64,
 684                    positions: Vec::new(),
 685                    worktree_id: worktree_id.to_usize(),
 686                    path,
 687                    is_dir: false, // File finder doesn't support directories
 688                    path_prefix: "".into(),
 689                    distance_to_relative_ancestor: usize::MAX,
 690                };
 691                if let Some(found_path_match) = &panel_match {
 692                    path_match
 693                        .positions
 694                        .extend(found_path_match.0.positions.iter())
 695                }
 696
 697                self.labels_for_path_match(&path_match)
 698            }
 699            Match::Search(path_match) => self.labels_for_path_match(&path_match.0),
 700        };
 701
 702        if file_name_positions.is_empty() {
 703            if let Some(user_home_path) = std::env::var("HOME").ok() {
 704                let user_home_path = user_home_path.trim();
 705                if !user_home_path.is_empty() {
 706                    if (&full_path).starts_with(user_home_path) {
 707                        return (
 708                            file_name,
 709                            file_name_positions,
 710                            full_path.replace(user_home_path, "~"),
 711                            full_path_positions,
 712                        );
 713                    }
 714                }
 715            }
 716        }
 717
 718        (
 719            file_name,
 720            file_name_positions,
 721            full_path,
 722            full_path_positions,
 723        )
 724    }
 725
 726    fn labels_for_path_match(
 727        &self,
 728        path_match: &PathMatch,
 729    ) -> (String, Vec<usize>, String, Vec<usize>) {
 730        let path = &path_match.path;
 731        let path_string = path.to_string_lossy();
 732        let full_path = [path_match.path_prefix.as_ref(), path_string.as_ref()].join("");
 733        let mut path_positions = path_match.positions.clone();
 734
 735        let file_name = path.file_name().map_or_else(
 736            || path_match.path_prefix.to_string(),
 737            |file_name| file_name.to_string_lossy().to_string(),
 738        );
 739        let file_name_start = path_match.path_prefix.len() + path_string.len() - file_name.len();
 740        let file_name_positions = path_positions
 741            .iter()
 742            .filter_map(|pos| {
 743                if pos >= &file_name_start {
 744                    Some(pos - file_name_start)
 745                } else {
 746                    None
 747                }
 748            })
 749            .collect();
 750
 751        let full_path = full_path.trim_end_matches(&file_name).to_string();
 752        path_positions.retain(|idx| *idx < full_path.len());
 753
 754        (file_name, file_name_positions, full_path, path_positions)
 755    }
 756
 757    fn lookup_absolute_path(
 758        &self,
 759        query: FileSearchQuery,
 760        cx: &mut ViewContext<'_, Picker<Self>>,
 761    ) -> Task<()> {
 762        cx.spawn(|picker, mut cx| async move {
 763            let Some(project) = picker
 764                .update(&mut cx, |picker, _| picker.delegate.project.clone())
 765                .log_err()
 766            else {
 767                return;
 768            };
 769
 770            let query_path = Path::new(query.path_query());
 771            let mut path_matches = Vec::new();
 772
 773            let abs_file_exists = if let Ok(task) = project.update(&mut cx, |this, cx| {
 774                this.abs_file_path_exists(query.path_query(), cx)
 775            }) {
 776                task.await
 777            } else {
 778                false
 779            };
 780
 781            if abs_file_exists {
 782                let update_result = project
 783                    .update(&mut cx, |project, cx| {
 784                        if let Some((worktree, relative_path)) =
 785                            project.find_worktree(query_path, cx)
 786                        {
 787                            path_matches.push(ProjectPanelOrdMatch(PathMatch {
 788                                score: 1.0,
 789                                positions: Vec::new(),
 790                                worktree_id: worktree.read(cx).id().to_usize(),
 791                                path: Arc::from(relative_path),
 792                                path_prefix: "".into(),
 793                                is_dir: false, // File finder doesn't support directories
 794                                distance_to_relative_ancestor: usize::MAX,
 795                            }));
 796                        }
 797                    })
 798                    .log_err();
 799                if update_result.is_none() {
 800                    return;
 801                }
 802            }
 803
 804            picker
 805                .update(&mut cx, |picker, cx| {
 806                    let picker_delegate = &mut picker.delegate;
 807                    let search_id = util::post_inc(&mut picker_delegate.search_count);
 808                    picker_delegate.set_search_matches(search_id, false, query, path_matches, cx);
 809
 810                    anyhow::Ok(())
 811                })
 812                .log_err();
 813        })
 814    }
 815
 816    /// Skips first history match (that is displayed topmost) if it's currently opened.
 817    fn calculate_selected_index(&self) -> usize {
 818        if let Some(Match::History { path, .. }) = self.matches.get(0) {
 819            if Some(path) == self.currently_opened_path.as_ref() {
 820                let elements_after_first = self.matches.len() - 1;
 821                if elements_after_first > 0 {
 822                    return 1;
 823                }
 824            }
 825        }
 826
 827        0
 828    }
 829}
 830
 831impl PickerDelegate for FileFinderDelegate {
 832    type ListItem = ListItem;
 833
 834    fn placeholder_text(&self, _cx: &mut WindowContext) -> Arc<str> {
 835        "Search project files...".into()
 836    }
 837
 838    fn match_count(&self) -> usize {
 839        self.matches.len()
 840    }
 841
 842    fn selected_index(&self) -> usize {
 843        self.selected_index
 844    }
 845
 846    fn set_selected_index(&mut self, ix: usize, cx: &mut ViewContext<Picker<Self>>) {
 847        self.has_changed_selected_index = true;
 848        self.selected_index = ix;
 849        cx.notify();
 850    }
 851
 852    fn separators_after_indices(&self) -> Vec<usize> {
 853        if self.separate_history {
 854            let first_non_history_index = self
 855                .matches
 856                .matches
 857                .iter()
 858                .enumerate()
 859                .find(|(_, m)| !matches!(m, Match::History { .. }))
 860                .map(|(i, _)| i);
 861            if let Some(first_non_history_index) = first_non_history_index {
 862                if first_non_history_index > 0 {
 863                    return vec![first_non_history_index - 1];
 864                }
 865            }
 866        }
 867        Vec::new()
 868    }
 869
 870    fn update_matches(
 871        &mut self,
 872        raw_query: String,
 873        cx: &mut ViewContext<Picker<Self>>,
 874    ) -> Task<()> {
 875        let raw_query = raw_query.replace(' ', "");
 876        let raw_query = raw_query.trim();
 877        if raw_query.is_empty() {
 878            // if there was no query before, and we already have some (history) matches
 879            // there's no need to update anything, since nothing has changed.
 880            // We also want to populate matches set from history entries on the first update.
 881            if self.latest_search_query.is_some() || self.first_update {
 882                let project = self.project.read(cx);
 883
 884                self.latest_search_id = post_inc(&mut self.search_count);
 885                self.latest_search_query = None;
 886                self.matches = Matches {
 887                    separate_history: self.separate_history,
 888                    ..Matches::default()
 889                };
 890                self.matches.push_new_matches(
 891                    self.history_items.iter().filter(|history_item| {
 892                        project
 893                            .worktree_for_id(history_item.project.worktree_id, cx)
 894                            .is_some()
 895                            || ((project.is_local() || project.is_via_ssh())
 896                                && history_item.absolute.is_some())
 897                    }),
 898                    self.currently_opened_path.as_ref(),
 899                    None,
 900                    None.into_iter(),
 901                    false,
 902                );
 903
 904                self.first_update = false;
 905                self.selected_index = 0;
 906            }
 907            cx.notify();
 908            Task::ready(())
 909        } else {
 910            let path_position = PathWithPosition::parse_str(&raw_query);
 911
 912            let query = FileSearchQuery {
 913                raw_query: raw_query.trim().to_owned(),
 914                file_query_end: if path_position.path.to_str().unwrap_or(raw_query) == raw_query {
 915                    None
 916                } else {
 917                    // Safe to unwrap as we won't get here when the unwrap in if fails
 918                    Some(path_position.path.to_str().unwrap().len())
 919                },
 920                path_position,
 921            };
 922
 923            if Path::new(query.path_query()).is_absolute() {
 924                self.lookup_absolute_path(query, cx)
 925            } else {
 926                self.spawn_search(query, cx)
 927            }
 928        }
 929    }
 930
 931    fn confirm(&mut self, secondary: bool, cx: &mut ViewContext<Picker<FileFinderDelegate>>) {
 932        if let Some(m) = self.matches.get(self.selected_index()) {
 933            if let Some(workspace) = self.workspace.upgrade() {
 934                let open_task = workspace.update(cx, move |workspace, cx| {
 935                    let split_or_open =
 936                        |workspace: &mut Workspace,
 937                         project_path,
 938                         cx: &mut ViewContext<Workspace>| {
 939                            let allow_preview =
 940                                PreviewTabsSettings::get_global(cx).enable_preview_from_file_finder;
 941                            if secondary {
 942                                workspace.split_path_preview(project_path, allow_preview, cx)
 943                            } else {
 944                                workspace.open_path_preview(
 945                                    project_path,
 946                                    None,
 947                                    true,
 948                                    allow_preview,
 949                                    cx,
 950                                )
 951                            }
 952                        };
 953                    match &m {
 954                        Match::History { path, .. } => {
 955                            let worktree_id = path.project.worktree_id;
 956                            if workspace
 957                                .project()
 958                                .read(cx)
 959                                .worktree_for_id(worktree_id, cx)
 960                                .is_some()
 961                            {
 962                                split_or_open(
 963                                    workspace,
 964                                    ProjectPath {
 965                                        worktree_id,
 966                                        path: Arc::clone(&path.project.path),
 967                                    },
 968                                    cx,
 969                                )
 970                            } else {
 971                                match path.absolute.as_ref() {
 972                                    Some(abs_path) => {
 973                                        if secondary {
 974                                            workspace.split_abs_path(
 975                                                abs_path.to_path_buf(),
 976                                                false,
 977                                                cx,
 978                                            )
 979                                        } else {
 980                                            workspace.open_abs_path(
 981                                                abs_path.to_path_buf(),
 982                                                false,
 983                                                cx,
 984                                            )
 985                                        }
 986                                    }
 987                                    None => split_or_open(
 988                                        workspace,
 989                                        ProjectPath {
 990                                            worktree_id,
 991                                            path: Arc::clone(&path.project.path),
 992                                        },
 993                                        cx,
 994                                    ),
 995                                }
 996                            }
 997                        }
 998                        Match::Search(m) => split_or_open(
 999                            workspace,
1000                            ProjectPath {
1001                                worktree_id: WorktreeId::from_usize(m.0.worktree_id),
1002                                path: m.0.path.clone(),
1003                            },
1004                            cx,
1005                        ),
1006                    }
1007                });
1008
1009                let row = self
1010                    .latest_search_query
1011                    .as_ref()
1012                    .and_then(|query| query.path_position.row)
1013                    .map(|row| row.saturating_sub(1));
1014                let col = self
1015                    .latest_search_query
1016                    .as_ref()
1017                    .and_then(|query| query.path_position.column)
1018                    .unwrap_or(0)
1019                    .saturating_sub(1);
1020                let finder = self.file_finder.clone();
1021
1022                cx.spawn(|_, mut cx| async move {
1023                    let item = open_task.await.notify_async_err(&mut cx)?;
1024                    if let Some(row) = row {
1025                        if let Some(active_editor) = item.downcast::<Editor>() {
1026                            active_editor
1027                                .downgrade()
1028                                .update(&mut cx, |editor, cx| {
1029                                    let snapshot = editor.snapshot(cx).display_snapshot;
1030                                    let point = snapshot
1031                                        .buffer_snapshot
1032                                        .clip_point(Point::new(row, col), Bias::Left);
1033                                    editor.change_selections(Some(Autoscroll::center()), cx, |s| {
1034                                        s.select_ranges([point..point])
1035                                    });
1036                                })
1037                                .log_err();
1038                        }
1039                    }
1040                    finder.update(&mut cx, |_, cx| cx.emit(DismissEvent)).ok()?;
1041
1042                    Some(())
1043                })
1044                .detach();
1045            }
1046        }
1047    }
1048
1049    fn dismissed(&mut self, cx: &mut ViewContext<Picker<FileFinderDelegate>>) {
1050        self.file_finder
1051            .update(cx, |_, cx| cx.emit(DismissEvent))
1052            .log_err();
1053    }
1054
1055    fn render_match(
1056        &self,
1057        ix: usize,
1058        selected: bool,
1059        cx: &mut ViewContext<Picker<Self>>,
1060    ) -> Option<Self::ListItem> {
1061        let settings = FileFinderSettings::get_global(cx);
1062
1063        let path_match = self
1064            .matches
1065            .get(ix)
1066            .expect("Invalid matches state: no element for index {ix}");
1067
1068        let history_icon = match &path_match {
1069            Match::History { .. } => Icon::new(IconName::HistoryRerun)
1070                .color(Color::Muted)
1071                .size(IconSize::Small)
1072                .into_any_element(),
1073            Match::Search(_) => v_flex()
1074                .flex_none()
1075                .size(IconSize::Small.rems())
1076                .into_any_element(),
1077        };
1078        let (file_name, file_name_positions, full_path, full_path_positions) =
1079            self.labels_for_match(path_match, cx, ix);
1080
1081        let file_icon = if settings.file_icons {
1082            FileIcons::get_icon(Path::new(&file_name), cx)
1083                .map(Icon::from_path)
1084                .map(|icon| icon.color(Color::Muted))
1085        } else {
1086            None
1087        };
1088
1089        Some(
1090            ListItem::new(ix)
1091                .spacing(ListItemSpacing::Sparse)
1092                .start_slot::<Icon>(file_icon)
1093                .end_slot::<AnyElement>(history_icon)
1094                .inset(true)
1095                .selected(selected)
1096                .child(
1097                    h_flex()
1098                        .gap_2()
1099                        .py_px()
1100                        .child(HighlightedLabel::new(file_name, file_name_positions))
1101                        .child(
1102                            HighlightedLabel::new(full_path, full_path_positions)
1103                                .size(LabelSize::Small)
1104                                .color(Color::Muted),
1105                        ),
1106                ),
1107        )
1108    }
1109}
1110
1111#[cfg(test)]
1112mod tests {
1113    use super::*;
1114
1115    #[test]
1116    fn test_custom_project_search_ordering_in_file_finder() {
1117        let mut file_finder_sorted_output = vec![
1118            ProjectPanelOrdMatch(PathMatch {
1119                score: 0.5,
1120                positions: Vec::new(),
1121                worktree_id: 0,
1122                path: Arc::from(Path::new("b0.5")),
1123                path_prefix: Arc::default(),
1124                distance_to_relative_ancestor: 0,
1125                is_dir: false,
1126            }),
1127            ProjectPanelOrdMatch(PathMatch {
1128                score: 1.0,
1129                positions: Vec::new(),
1130                worktree_id: 0,
1131                path: Arc::from(Path::new("c1.0")),
1132                path_prefix: Arc::default(),
1133                distance_to_relative_ancestor: 0,
1134                is_dir: false,
1135            }),
1136            ProjectPanelOrdMatch(PathMatch {
1137                score: 1.0,
1138                positions: Vec::new(),
1139                worktree_id: 0,
1140                path: Arc::from(Path::new("a1.0")),
1141                path_prefix: Arc::default(),
1142                distance_to_relative_ancestor: 0,
1143                is_dir: false,
1144            }),
1145            ProjectPanelOrdMatch(PathMatch {
1146                score: 0.5,
1147                positions: Vec::new(),
1148                worktree_id: 0,
1149                path: Arc::from(Path::new("a0.5")),
1150                path_prefix: Arc::default(),
1151                distance_to_relative_ancestor: 0,
1152                is_dir: false,
1153            }),
1154            ProjectPanelOrdMatch(PathMatch {
1155                score: 1.0,
1156                positions: Vec::new(),
1157                worktree_id: 0,
1158                path: Arc::from(Path::new("b1.0")),
1159                path_prefix: Arc::default(),
1160                distance_to_relative_ancestor: 0,
1161                is_dir: false,
1162            }),
1163        ];
1164        file_finder_sorted_output.sort_by(|a, b| b.cmp(a));
1165
1166        assert_eq!(
1167            file_finder_sorted_output,
1168            vec![
1169                ProjectPanelOrdMatch(PathMatch {
1170                    score: 1.0,
1171                    positions: Vec::new(),
1172                    worktree_id: 0,
1173                    path: Arc::from(Path::new("a1.0")),
1174                    path_prefix: Arc::default(),
1175                    distance_to_relative_ancestor: 0,
1176                    is_dir: false,
1177                }),
1178                ProjectPanelOrdMatch(PathMatch {
1179                    score: 1.0,
1180                    positions: Vec::new(),
1181                    worktree_id: 0,
1182                    path: Arc::from(Path::new("b1.0")),
1183                    path_prefix: Arc::default(),
1184                    distance_to_relative_ancestor: 0,
1185                    is_dir: false,
1186                }),
1187                ProjectPanelOrdMatch(PathMatch {
1188                    score: 1.0,
1189                    positions: Vec::new(),
1190                    worktree_id: 0,
1191                    path: Arc::from(Path::new("c1.0")),
1192                    path_prefix: Arc::default(),
1193                    distance_to_relative_ancestor: 0,
1194                    is_dir: false,
1195                }),
1196                ProjectPanelOrdMatch(PathMatch {
1197                    score: 0.5,
1198                    positions: Vec::new(),
1199                    worktree_id: 0,
1200                    path: Arc::from(Path::new("a0.5")),
1201                    path_prefix: Arc::default(),
1202                    distance_to_relative_ancestor: 0,
1203                    is_dir: false,
1204                }),
1205                ProjectPanelOrdMatch(PathMatch {
1206                    score: 0.5,
1207                    positions: Vec::new(),
1208                    worktree_id: 0,
1209                    path: Arc::from(Path::new("b0.5")),
1210                    path_prefix: Arc::default(),
1211                    distance_to_relative_ancestor: 0,
1212                    is_dir: false,
1213                }),
1214            ]
1215        );
1216    }
1217}