file_finder.rs

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