file_finder.rs

   1#[cfg(test)]
   2mod file_finder_tests;
   3#[cfg(test)]
   4mod open_path_prompt_tests;
   5
   6pub mod file_finder_settings;
   7mod open_path_prompt;
   8
   9use futures::future::join_all;
  10pub use open_path_prompt::OpenPathDelegate;
  11
  12use collections::HashMap;
  13use editor::Editor;
  14use file_finder_settings::{FileFinderSettings, FileFinderWidth};
  15use file_icons::FileIcons;
  16use fuzzy::{CharBag, PathMatch, PathMatchCandidate};
  17use gpui::{
  18    Action, AnyElement, App, Context, DismissEvent, Entity, EventEmitter, FocusHandle, Focusable,
  19    KeyContext, Modifiers, ModifiersChangedEvent, ParentElement, Render, Styled, Task, WeakEntity,
  20    Window, actions, rems,
  21};
  22use open_path_prompt::OpenPathPrompt;
  23use picker::{Picker, PickerDelegate};
  24use project::{
  25    PathMatchCandidateSet, Project, ProjectPath, WorktreeId, worktree_store::WorktreeStore,
  26};
  27use search::ToggleIncludeIgnored;
  28use settings::Settings;
  29use std::{
  30    borrow::Cow,
  31    cmp,
  32    ops::Range,
  33    path::{Component, Path, PathBuf},
  34    sync::{
  35        Arc,
  36        atomic::{self, AtomicBool},
  37    },
  38};
  39use text::Point;
  40use ui::{
  41    ButtonLike, ContextMenu, HighlightedLabel, Indicator, KeyBinding, ListItem, ListItemSpacing,
  42    PopoverMenu, PopoverMenuHandle, TintColor, Tooltip, prelude::*,
  43};
  44use util::{
  45    ResultExt, maybe,
  46    paths::{PathStyle, PathWithPosition},
  47    post_inc,
  48    rel_path::RelPath,
  49};
  50use workspace::{
  51    ModalView, OpenOptions, OpenVisible, SplitDirection, Workspace, item::PreviewTabsSettings,
  52    notifications::NotifyResultExt, pane,
  53};
  54
  55actions!(
  56    file_finder,
  57    [
  58        /// Selects the previous item in the file finder.
  59        SelectPrevious,
  60        /// Toggles the file filter menu.
  61        ToggleFilterMenu,
  62        /// Toggles the split direction menu.
  63        ToggleSplitMenu
  64    ]
  65);
  66
  67impl ModalView for FileFinder {
  68    fn on_before_dismiss(
  69        &mut self,
  70        window: &mut Window,
  71        cx: &mut Context<Self>,
  72    ) -> workspace::DismissDecision {
  73        let submenu_focused = self.picker.update(cx, |picker, cx| {
  74            picker
  75                .delegate
  76                .filter_popover_menu_handle
  77                .is_focused(window, cx)
  78                || picker
  79                    .delegate
  80                    .split_popover_menu_handle
  81                    .is_focused(window, cx)
  82        });
  83        workspace::DismissDecision::Dismiss(!submenu_focused)
  84    }
  85}
  86
  87pub struct FileFinder {
  88    picker: Entity<Picker<FileFinderDelegate>>,
  89    picker_focus_handle: FocusHandle,
  90    init_modifiers: Option<Modifiers>,
  91}
  92
  93pub fn init_settings(cx: &mut App) {
  94    FileFinderSettings::register(cx);
  95}
  96
  97pub fn init(cx: &mut App) {
  98    init_settings(cx);
  99    cx.observe_new(FileFinder::register).detach();
 100    cx.observe_new(OpenPathPrompt::register).detach();
 101    cx.observe_new(OpenPathPrompt::register_new_path).detach();
 102}
 103
 104impl FileFinder {
 105    fn register(
 106        workspace: &mut Workspace,
 107        _window: Option<&mut Window>,
 108        _: &mut Context<Workspace>,
 109    ) {
 110        workspace.register_action(
 111            |workspace, action: &workspace::ToggleFileFinder, window, cx| {
 112                let Some(file_finder) = workspace.active_modal::<Self>(cx) else {
 113                    Self::open(workspace, action.separate_history, window, cx).detach();
 114                    return;
 115                };
 116
 117                file_finder.update(cx, |file_finder, cx| {
 118                    file_finder.init_modifiers = Some(window.modifiers());
 119                    file_finder.picker.update(cx, |picker, cx| {
 120                        picker.cycle_selection(window, cx);
 121                    });
 122                });
 123            },
 124        );
 125    }
 126
 127    fn open(
 128        workspace: &mut Workspace,
 129        separate_history: bool,
 130        window: &mut Window,
 131        cx: &mut Context<Workspace>,
 132    ) -> Task<()> {
 133        let project = workspace.project().read(cx);
 134        let fs = project.fs();
 135
 136        let currently_opened_path = workspace.active_item(cx).and_then(|item| {
 137            let project_path = item.project_path(cx)?;
 138            let abs_path = project
 139                .worktree_for_id(project_path.worktree_id, cx)?
 140                .read(cx)
 141                .absolutize(&project_path.path);
 142            Some(FoundPath::new(project_path, abs_path))
 143        });
 144
 145        let history_items = workspace
 146            .recent_navigation_history(Some(MAX_RECENT_SELECTIONS), cx)
 147            .into_iter()
 148            .filter_map(|(project_path, abs_path)| {
 149                if project.entry_for_path(&project_path, cx).is_some() {
 150                    return Some(Task::ready(Some(FoundPath::new(project_path, abs_path?))));
 151                }
 152                let abs_path = abs_path?;
 153                if project.is_local() {
 154                    let fs = fs.clone();
 155                    Some(cx.background_spawn(async move {
 156                        if fs.is_file(&abs_path).await {
 157                            Some(FoundPath::new(project_path, abs_path))
 158                        } else {
 159                            None
 160                        }
 161                    }))
 162                } else {
 163                    Some(Task::ready(Some(FoundPath::new(project_path, abs_path))))
 164                }
 165            })
 166            .collect::<Vec<_>>();
 167        cx.spawn_in(window, async move |workspace, cx| {
 168            let history_items = join_all(history_items).await.into_iter().flatten();
 169
 170            workspace
 171                .update_in(cx, |workspace, window, cx| {
 172                    let project = workspace.project().clone();
 173                    let weak_workspace = cx.entity().downgrade();
 174                    workspace.toggle_modal(window, cx, |window, cx| {
 175                        let delegate = FileFinderDelegate::new(
 176                            cx.entity().downgrade(),
 177                            weak_workspace,
 178                            project,
 179                            currently_opened_path,
 180                            history_items.collect(),
 181                            separate_history,
 182                            window,
 183                            cx,
 184                        );
 185
 186                        FileFinder::new(delegate, window, cx)
 187                    });
 188                })
 189                .ok();
 190        })
 191    }
 192
 193    fn new(delegate: FileFinderDelegate, window: &mut Window, cx: &mut Context<Self>) -> Self {
 194        let picker = cx.new(|cx| Picker::uniform_list(delegate, window, cx));
 195        let picker_focus_handle = picker.focus_handle(cx);
 196        picker.update(cx, |picker, _| {
 197            picker.delegate.focus_handle = picker_focus_handle.clone();
 198        });
 199        Self {
 200            picker,
 201            picker_focus_handle,
 202            init_modifiers: window.modifiers().modified().then_some(window.modifiers()),
 203        }
 204    }
 205
 206    fn handle_modifiers_changed(
 207        &mut self,
 208        event: &ModifiersChangedEvent,
 209        window: &mut Window,
 210        cx: &mut Context<Self>,
 211    ) {
 212        let Some(init_modifiers) = self.init_modifiers.take() else {
 213            return;
 214        };
 215        if self.picker.read(cx).delegate.has_changed_selected_index
 216            && (!event.modified() || !init_modifiers.is_subset_of(event))
 217        {
 218            self.init_modifiers = None;
 219            window.dispatch_action(menu::Confirm.boxed_clone(), cx);
 220        }
 221    }
 222
 223    fn handle_select_prev(
 224        &mut self,
 225        _: &SelectPrevious,
 226        window: &mut Window,
 227        cx: &mut Context<Self>,
 228    ) {
 229        self.init_modifiers = Some(window.modifiers());
 230        window.dispatch_action(Box::new(menu::SelectPrevious), cx);
 231    }
 232
 233    fn handle_filter_toggle_menu(
 234        &mut self,
 235        _: &ToggleFilterMenu,
 236        window: &mut Window,
 237        cx: &mut Context<Self>,
 238    ) {
 239        self.picker.update(cx, |picker, cx| {
 240            let menu_handle = &picker.delegate.filter_popover_menu_handle;
 241            if menu_handle.is_deployed() {
 242                menu_handle.hide(cx);
 243            } else {
 244                menu_handle.show(window, cx);
 245            }
 246        });
 247    }
 248
 249    fn handle_split_toggle_menu(
 250        &mut self,
 251        _: &ToggleSplitMenu,
 252        window: &mut Window,
 253        cx: &mut Context<Self>,
 254    ) {
 255        self.picker.update(cx, |picker, cx| {
 256            let menu_handle = &picker.delegate.split_popover_menu_handle;
 257            if menu_handle.is_deployed() {
 258                menu_handle.hide(cx);
 259            } else {
 260                menu_handle.show(window, cx);
 261            }
 262        });
 263    }
 264
 265    fn handle_toggle_ignored(
 266        &mut self,
 267        _: &ToggleIncludeIgnored,
 268        window: &mut Window,
 269        cx: &mut Context<Self>,
 270    ) {
 271        self.picker.update(cx, |picker, cx| {
 272            picker.delegate.include_ignored = match picker.delegate.include_ignored {
 273                Some(true) => FileFinderSettings::get_global(cx)
 274                    .include_ignored
 275                    .map(|_| false),
 276                Some(false) => Some(true),
 277                None => Some(true),
 278            };
 279            picker.delegate.include_ignored_refresh =
 280                picker.delegate.update_matches(picker.query(cx), window, cx);
 281        });
 282    }
 283
 284    fn go_to_file_split_left(
 285        &mut self,
 286        _: &pane::SplitLeft,
 287        window: &mut Window,
 288        cx: &mut Context<Self>,
 289    ) {
 290        self.go_to_file_split_inner(SplitDirection::Left, window, cx)
 291    }
 292
 293    fn go_to_file_split_right(
 294        &mut self,
 295        _: &pane::SplitRight,
 296        window: &mut Window,
 297        cx: &mut Context<Self>,
 298    ) {
 299        self.go_to_file_split_inner(SplitDirection::Right, window, cx)
 300    }
 301
 302    fn go_to_file_split_up(
 303        &mut self,
 304        _: &pane::SplitUp,
 305        window: &mut Window,
 306        cx: &mut Context<Self>,
 307    ) {
 308        self.go_to_file_split_inner(SplitDirection::Up, window, cx)
 309    }
 310
 311    fn go_to_file_split_down(
 312        &mut self,
 313        _: &pane::SplitDown,
 314        window: &mut Window,
 315        cx: &mut Context<Self>,
 316    ) {
 317        self.go_to_file_split_inner(SplitDirection::Down, window, cx)
 318    }
 319
 320    fn go_to_file_split_inner(
 321        &mut self,
 322        split_direction: SplitDirection,
 323        window: &mut Window,
 324        cx: &mut Context<Self>,
 325    ) {
 326        self.picker.update(cx, |picker, cx| {
 327            let delegate = &mut picker.delegate;
 328            if let Some(workspace) = delegate.workspace.upgrade()
 329                && let Some(m) = delegate.matches.get(delegate.selected_index())
 330            {
 331                let path = match &m {
 332                    Match::History { path, .. } => {
 333                        let worktree_id = path.project.worktree_id;
 334                        ProjectPath {
 335                            worktree_id,
 336                            path: Arc::clone(&path.project.path),
 337                        }
 338                    }
 339                    Match::Search(m) => ProjectPath {
 340                        worktree_id: WorktreeId::from_usize(m.0.worktree_id),
 341                        path: m.0.path.clone(),
 342                    },
 343                    Match::CreateNew(p) => p.clone(),
 344                };
 345                let open_task = workspace.update(cx, move |workspace, cx| {
 346                    workspace.split_path_preview(path, false, Some(split_direction), window, cx)
 347                });
 348                open_task.detach_and_log_err(cx);
 349            }
 350        })
 351    }
 352
 353    pub fn modal_max_width(width_setting: FileFinderWidth, window: &mut Window) -> Pixels {
 354        let window_width = window.viewport_size().width;
 355        let small_width = rems(34.).to_pixels(window.rem_size());
 356
 357        match width_setting {
 358            FileFinderWidth::Small => small_width,
 359            FileFinderWidth::Full => window_width,
 360            FileFinderWidth::XLarge => (window_width - px(512.)).max(small_width),
 361            FileFinderWidth::Large => (window_width - px(768.)).max(small_width),
 362            FileFinderWidth::Medium => (window_width - px(1024.)).max(small_width),
 363        }
 364    }
 365}
 366
 367impl EventEmitter<DismissEvent> for FileFinder {}
 368
 369impl Focusable for FileFinder {
 370    fn focus_handle(&self, _: &App) -> FocusHandle {
 371        self.picker_focus_handle.clone()
 372    }
 373}
 374
 375impl Render for FileFinder {
 376    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
 377        let key_context = self.picker.read(cx).delegate.key_context(window, cx);
 378
 379        let file_finder_settings = FileFinderSettings::get_global(cx);
 380        let modal_max_width = Self::modal_max_width(file_finder_settings.modal_max_width, window);
 381
 382        v_flex()
 383            .key_context(key_context)
 384            .w(modal_max_width)
 385            .on_modifiers_changed(cx.listener(Self::handle_modifiers_changed))
 386            .on_action(cx.listener(Self::handle_select_prev))
 387            .on_action(cx.listener(Self::handle_filter_toggle_menu))
 388            .on_action(cx.listener(Self::handle_split_toggle_menu))
 389            .on_action(cx.listener(Self::handle_toggle_ignored))
 390            .on_action(cx.listener(Self::go_to_file_split_left))
 391            .on_action(cx.listener(Self::go_to_file_split_right))
 392            .on_action(cx.listener(Self::go_to_file_split_up))
 393            .on_action(cx.listener(Self::go_to_file_split_down))
 394            .child(self.picker.clone())
 395    }
 396}
 397
 398pub struct FileFinderDelegate {
 399    file_finder: WeakEntity<FileFinder>,
 400    workspace: WeakEntity<Workspace>,
 401    project: Entity<Project>,
 402    search_count: usize,
 403    latest_search_id: usize,
 404    latest_search_did_cancel: bool,
 405    latest_search_query: Option<FileSearchQuery>,
 406    currently_opened_path: Option<FoundPath>,
 407    matches: Matches,
 408    selected_index: usize,
 409    has_changed_selected_index: bool,
 410    cancel_flag: Arc<AtomicBool>,
 411    history_items: Vec<FoundPath>,
 412    separate_history: bool,
 413    first_update: bool,
 414    filter_popover_menu_handle: PopoverMenuHandle<ContextMenu>,
 415    split_popover_menu_handle: PopoverMenuHandle<ContextMenu>,
 416    focus_handle: FocusHandle,
 417    include_ignored: Option<bool>,
 418    include_ignored_refresh: Task<()>,
 419}
 420
 421/// Use a custom ordering for file finder: the regular one
 422/// defines max element with the highest score and the latest alphanumerical path (in case of a tie on other params), e.g:
 423/// `[{score: 0.5, path = "c/d" }, { score: 0.5, path = "/a/b" }]`
 424///
 425/// In the file finder, we would prefer to have the max element with the highest score and the earliest alphanumerical path, e.g:
 426/// `[{ score: 0.5, path = "/a/b" }, {score: 0.5, path = "c/d" }]`
 427/// as the files are shown in the project panel lists.
 428#[derive(Debug, Clone, PartialEq, Eq)]
 429struct ProjectPanelOrdMatch(PathMatch);
 430
 431impl Ord for ProjectPanelOrdMatch {
 432    fn cmp(&self, other: &Self) -> cmp::Ordering {
 433        self.0
 434            .score
 435            .partial_cmp(&other.0.score)
 436            .unwrap_or(cmp::Ordering::Equal)
 437            .then_with(|| self.0.worktree_id.cmp(&other.0.worktree_id))
 438            .then_with(|| {
 439                other
 440                    .0
 441                    .distance_to_relative_ancestor
 442                    .cmp(&self.0.distance_to_relative_ancestor)
 443            })
 444            .then_with(|| self.0.path.cmp(&other.0.path).reverse())
 445    }
 446}
 447
 448impl PartialOrd for ProjectPanelOrdMatch {
 449    fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> {
 450        Some(self.cmp(other))
 451    }
 452}
 453
 454#[derive(Debug, Default)]
 455struct Matches {
 456    separate_history: bool,
 457    matches: Vec<Match>,
 458}
 459
 460#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone)]
 461enum Match {
 462    History {
 463        path: FoundPath,
 464        panel_match: Option<ProjectPanelOrdMatch>,
 465    },
 466    Search(ProjectPanelOrdMatch),
 467    CreateNew(ProjectPath),
 468}
 469
 470impl Match {
 471    fn relative_path(&self) -> Option<&Arc<RelPath>> {
 472        match self {
 473            Match::History { path, .. } => Some(&path.project.path),
 474            Match::Search(panel_match) => Some(&panel_match.0.path),
 475            Match::CreateNew(_) => None,
 476        }
 477    }
 478
 479    fn abs_path(&self, project: &Entity<Project>, cx: &App) -> Option<PathBuf> {
 480        match self {
 481            Match::History { path, .. } => Some(path.absolute.clone()),
 482            Match::Search(ProjectPanelOrdMatch(path_match)) => Some(
 483                project
 484                    .read(cx)
 485                    .worktree_for_id(WorktreeId::from_usize(path_match.worktree_id), cx)?
 486                    .read(cx)
 487                    .absolutize(&path_match.path),
 488            ),
 489            Match::CreateNew(_) => None,
 490        }
 491    }
 492
 493    fn panel_match(&self) -> Option<&ProjectPanelOrdMatch> {
 494        match self {
 495            Match::History { panel_match, .. } => panel_match.as_ref(),
 496            Match::Search(panel_match) => Some(panel_match),
 497            Match::CreateNew(_) => None,
 498        }
 499    }
 500}
 501
 502impl Matches {
 503    fn len(&self) -> usize {
 504        self.matches.len()
 505    }
 506
 507    fn get(&self, index: usize) -> Option<&Match> {
 508        self.matches.get(index)
 509    }
 510
 511    fn position(
 512        &self,
 513        entry: &Match,
 514        currently_opened: Option<&FoundPath>,
 515    ) -> Result<usize, usize> {
 516        if let Match::History {
 517            path,
 518            panel_match: None,
 519        } = entry
 520        {
 521            // Slow case: linear search by path. Should not happen actually,
 522            // since we call `position` only if matches set changed, but the query has not changed.
 523            // And History entries do not have panel_match if query is empty, so there's no
 524            // reason for the matches set to change.
 525            self.matches
 526                .iter()
 527                .position(|m| match m.relative_path() {
 528                    Some(p) => path.project.path == *p,
 529                    None => false,
 530                })
 531                .ok_or(0)
 532        } else {
 533            self.matches.binary_search_by(|m| {
 534                // `reverse()` since if cmp_matches(a, b) == Ordering::Greater, then a is better than b.
 535                // And we want the better entries go first.
 536                Self::cmp_matches(self.separate_history, currently_opened, m, entry).reverse()
 537            })
 538        }
 539    }
 540
 541    fn push_new_matches<'a>(
 542        &'a mut self,
 543        worktree_store: Entity<WorktreeStore>,
 544        cx: &'a App,
 545        history_items: impl IntoIterator<Item = &'a FoundPath> + Clone,
 546        currently_opened: Option<&'a FoundPath>,
 547        query: Option<&FileSearchQuery>,
 548        new_search_matches: impl Iterator<Item = ProjectPanelOrdMatch>,
 549        extend_old_matches: bool,
 550        path_style: PathStyle,
 551    ) {
 552        let Some(query) = query else {
 553            // assuming that if there's no query, then there's no search matches.
 554            self.matches.clear();
 555            let path_to_entry = |found_path: &FoundPath| Match::History {
 556                path: found_path.clone(),
 557                panel_match: None,
 558            };
 559
 560            self.matches
 561                .extend(history_items.into_iter().map(path_to_entry));
 562            return;
 563        };
 564        // If several worktress are open we have to set the worktree root names in path prefix
 565        let several_worktrees = worktree_store.read(cx).worktrees().count() > 1;
 566        let worktree_name_by_id = several_worktrees.then(|| {
 567            worktree_store
 568                .read(cx)
 569                .worktrees()
 570                .map(|worktree| {
 571                    let snapshot = worktree.read(cx).snapshot();
 572                    (snapshot.id(), snapshot.root_name().into())
 573                })
 574                .collect()
 575        });
 576        let new_history_matches = matching_history_items(
 577            history_items,
 578            currently_opened,
 579            worktree_name_by_id,
 580            query,
 581            path_style,
 582        );
 583        let new_search_matches: Vec<Match> = new_search_matches
 584            .filter(|path_match| {
 585                !new_history_matches.contains_key(&ProjectPath {
 586                    path: path_match.0.path.clone(),
 587                    worktree_id: WorktreeId::from_usize(path_match.0.worktree_id),
 588                })
 589            })
 590            .map(Match::Search)
 591            .collect();
 592
 593        if extend_old_matches {
 594            // since we take history matches instead of new search matches
 595            // and history matches has not changed(since the query has not changed and we do not extend old matches otherwise),
 596            // old matches can't contain paths present in history_matches as well.
 597            self.matches.retain(|m| matches!(m, Match::Search(_)));
 598        } else {
 599            self.matches.clear();
 600        }
 601
 602        // At this point we have an unsorted set of new history matches, an unsorted set of new search matches
 603        // and a sorted set of old search matches.
 604        // It is possible that the new search matches' paths contain some of the old search matches' paths.
 605        // History matches' paths are unique, since store in a HashMap by path.
 606        // We build a sorted Vec<Match>, eliminating duplicate search matches.
 607        // Search matches with the same paths should have equal `ProjectPanelOrdMatch`, so we should
 608        // not have any duplicates after building the final list.
 609        for new_match in new_history_matches
 610            .into_values()
 611            .chain(new_search_matches.into_iter())
 612        {
 613            match self.position(&new_match, currently_opened) {
 614                Ok(_duplicate) => continue,
 615                Err(i) => {
 616                    self.matches.insert(i, new_match);
 617                    if self.matches.len() == 100 {
 618                        break;
 619                    }
 620                }
 621            }
 622        }
 623    }
 624
 625    /// If a < b, then a is a worse match, aligning with the `ProjectPanelOrdMatch` ordering.
 626    fn cmp_matches(
 627        separate_history: bool,
 628        currently_opened: Option<&FoundPath>,
 629        a: &Match,
 630        b: &Match,
 631    ) -> cmp::Ordering {
 632        // Handle CreateNew variant - always put it at the end
 633        match (a, b) {
 634            (Match::CreateNew(_), _) => return cmp::Ordering::Less,
 635            (_, Match::CreateNew(_)) => return cmp::Ordering::Greater,
 636            _ => {}
 637        }
 638        debug_assert!(a.panel_match().is_some() && b.panel_match().is_some());
 639
 640        match (&a, &b) {
 641            // bubble currently opened files to the top
 642            (Match::History { path, .. }, _) if Some(path) == currently_opened => {
 643                return cmp::Ordering::Greater;
 644            }
 645            (_, Match::History { path, .. }) if Some(path) == currently_opened => {
 646                return cmp::Ordering::Less;
 647            }
 648
 649            _ => {}
 650        }
 651
 652        if separate_history {
 653            match (a, b) {
 654                (Match::History { .. }, Match::Search(_)) => return cmp::Ordering::Greater,
 655                (Match::Search(_), Match::History { .. }) => return cmp::Ordering::Less,
 656
 657                _ => {}
 658            }
 659        }
 660
 661        let a_panel_match = match a.panel_match() {
 662            Some(pm) => pm,
 663            None => {
 664                return if b.panel_match().is_some() {
 665                    cmp::Ordering::Less
 666                } else {
 667                    cmp::Ordering::Equal
 668                };
 669            }
 670        };
 671
 672        let b_panel_match = match b.panel_match() {
 673            Some(pm) => pm,
 674            None => return cmp::Ordering::Greater,
 675        };
 676
 677        let a_in_filename = Self::is_filename_match(a_panel_match);
 678        let b_in_filename = Self::is_filename_match(b_panel_match);
 679
 680        match (a_in_filename, b_in_filename) {
 681            (true, false) => return cmp::Ordering::Greater,
 682            (false, true) => return cmp::Ordering::Less,
 683            _ => {} // Both are filename matches or both are path matches
 684        }
 685
 686        a_panel_match.cmp(b_panel_match)
 687    }
 688
 689    /// Determines if the match occurred within the filename rather than in the path
 690    fn is_filename_match(panel_match: &ProjectPanelOrdMatch) -> bool {
 691        if panel_match.0.positions.is_empty() {
 692            return false;
 693        }
 694
 695        if let Some(filename) = panel_match.0.path.file_name() {
 696            let path_str = panel_match.0.path.as_unix_str();
 697
 698            if let Some(filename_pos) = path_str.rfind(filename)
 699                && panel_match.0.positions[0] >= filename_pos
 700            {
 701                let mut prev_position = panel_match.0.positions[0];
 702                for p in &panel_match.0.positions[1..] {
 703                    if *p != prev_position + 1 {
 704                        return false;
 705                    }
 706                    prev_position = *p;
 707                }
 708                return true;
 709            }
 710        }
 711
 712        false
 713    }
 714}
 715
 716fn matching_history_items<'a>(
 717    history_items: impl IntoIterator<Item = &'a FoundPath>,
 718    currently_opened: Option<&'a FoundPath>,
 719    worktree_name_by_id: Option<HashMap<WorktreeId, Arc<RelPath>>>,
 720    query: &FileSearchQuery,
 721    path_style: PathStyle,
 722) -> HashMap<ProjectPath, Match> {
 723    let mut candidates_paths = HashMap::default();
 724
 725    let history_items_by_worktrees = history_items
 726        .into_iter()
 727        .chain(currently_opened)
 728        .filter_map(|found_path| {
 729            let candidate = PathMatchCandidate {
 730                is_dir: false, // You can't open directories as project items
 731                path: &found_path.project.path,
 732                // Only match history items names, otherwise their paths may match too many queries, producing false positives.
 733                // E.g. `foo` would match both `something/foo/bar.rs` and `something/foo/foo.rs` and if the former is a history item,
 734                // it would be shown first always, despite the latter being a better match.
 735                char_bag: CharBag::from_iter(
 736                    found_path
 737                        .project
 738                        .path
 739                        .file_name()?
 740                        .to_string()
 741                        .to_lowercase()
 742                        .chars(),
 743                ),
 744            };
 745            candidates_paths.insert(&found_path.project, found_path);
 746            Some((found_path.project.worktree_id, candidate))
 747        })
 748        .fold(
 749            HashMap::default(),
 750            |mut candidates, (worktree_id, new_candidate)| {
 751                candidates
 752                    .entry(worktree_id)
 753                    .or_insert_with(Vec::new)
 754                    .push(new_candidate);
 755                candidates
 756            },
 757        );
 758    let mut matching_history_paths = HashMap::default();
 759    for (worktree, candidates) in history_items_by_worktrees {
 760        let max_results = candidates.len() + 1;
 761        let worktree_root_name = worktree_name_by_id
 762            .as_ref()
 763            .and_then(|w| w.get(&worktree).cloned());
 764        matching_history_paths.extend(
 765            fuzzy::match_fixed_path_set(
 766                candidates,
 767                worktree.to_usize(),
 768                worktree_root_name,
 769                query.path_query(),
 770                false,
 771                max_results,
 772                path_style,
 773            )
 774            .into_iter()
 775            .filter_map(|path_match| {
 776                candidates_paths
 777                    .remove_entry(&ProjectPath {
 778                        worktree_id: WorktreeId::from_usize(path_match.worktree_id),
 779                        path: Arc::clone(&path_match.path),
 780                    })
 781                    .map(|(project_path, found_path)| {
 782                        (
 783                            project_path.clone(),
 784                            Match::History {
 785                                path: found_path.clone(),
 786                                panel_match: Some(ProjectPanelOrdMatch(path_match)),
 787                            },
 788                        )
 789                    })
 790            }),
 791        );
 792    }
 793    matching_history_paths
 794}
 795
 796#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
 797struct FoundPath {
 798    project: ProjectPath,
 799    absolute: PathBuf,
 800}
 801
 802impl FoundPath {
 803    fn new(project: ProjectPath, absolute: PathBuf) -> Self {
 804        Self { project, absolute }
 805    }
 806}
 807
 808const MAX_RECENT_SELECTIONS: usize = 20;
 809
 810pub enum Event {
 811    Selected(ProjectPath),
 812    Dismissed,
 813}
 814
 815#[derive(Debug, Clone)]
 816struct FileSearchQuery {
 817    raw_query: String,
 818    file_query_end: Option<usize>,
 819    path_position: PathWithPosition,
 820}
 821
 822impl FileSearchQuery {
 823    fn path_query(&self) -> &str {
 824        match self.file_query_end {
 825            Some(file_path_end) => &self.raw_query[..file_path_end],
 826            None => &self.raw_query,
 827        }
 828    }
 829}
 830
 831impl FileFinderDelegate {
 832    fn new(
 833        file_finder: WeakEntity<FileFinder>,
 834        workspace: WeakEntity<Workspace>,
 835        project: Entity<Project>,
 836        currently_opened_path: Option<FoundPath>,
 837        history_items: Vec<FoundPath>,
 838        separate_history: bool,
 839        window: &mut Window,
 840        cx: &mut Context<FileFinder>,
 841    ) -> Self {
 842        Self::subscribe_to_updates(&project, window, cx);
 843        Self {
 844            file_finder,
 845            workspace,
 846            project,
 847            search_count: 0,
 848            latest_search_id: 0,
 849            latest_search_did_cancel: false,
 850            latest_search_query: None,
 851            currently_opened_path,
 852            matches: Matches::default(),
 853            has_changed_selected_index: false,
 854            selected_index: 0,
 855            cancel_flag: Arc::new(AtomicBool::new(false)),
 856            history_items,
 857            separate_history,
 858            first_update: true,
 859            filter_popover_menu_handle: PopoverMenuHandle::default(),
 860            split_popover_menu_handle: PopoverMenuHandle::default(),
 861            focus_handle: cx.focus_handle(),
 862            include_ignored: FileFinderSettings::get_global(cx).include_ignored,
 863            include_ignored_refresh: Task::ready(()),
 864        }
 865    }
 866
 867    fn subscribe_to_updates(
 868        project: &Entity<Project>,
 869        window: &mut Window,
 870        cx: &mut Context<FileFinder>,
 871    ) {
 872        cx.subscribe_in(project, window, |file_finder, _, event, window, cx| {
 873            match event {
 874                project::Event::WorktreeUpdatedEntries(_, _)
 875                | project::Event::WorktreeAdded(_)
 876                | project::Event::WorktreeRemoved(_) => file_finder
 877                    .picker
 878                    .update(cx, |picker, cx| picker.refresh(window, cx)),
 879                _ => {}
 880            };
 881        })
 882        .detach();
 883    }
 884
 885    fn spawn_search(
 886        &mut self,
 887        query: FileSearchQuery,
 888        window: &mut Window,
 889        cx: &mut Context<Picker<Self>>,
 890    ) -> Task<()> {
 891        let relative_to = self
 892            .currently_opened_path
 893            .as_ref()
 894            .map(|found_path| Arc::clone(&found_path.project.path));
 895        let worktrees = self
 896            .project
 897            .read(cx)
 898            .worktree_store()
 899            .read(cx)
 900            .visible_worktrees_and_single_files(cx)
 901            .collect::<Vec<_>>();
 902        let include_root_name = worktrees.len() > 1;
 903        let candidate_sets = worktrees
 904            .into_iter()
 905            .map(|worktree| {
 906                let worktree = worktree.read(cx);
 907                PathMatchCandidateSet {
 908                    snapshot: worktree.snapshot(),
 909                    include_ignored: self.include_ignored.unwrap_or_else(|| {
 910                        worktree.root_entry().is_some_and(|entry| entry.is_ignored)
 911                    }),
 912                    include_root_name,
 913                    candidates: project::Candidates::Files,
 914                }
 915            })
 916            .collect::<Vec<_>>();
 917
 918        let search_id = util::post_inc(&mut self.search_count);
 919        self.cancel_flag.store(true, atomic::Ordering::Release);
 920        self.cancel_flag = Arc::new(AtomicBool::new(false));
 921        let cancel_flag = self.cancel_flag.clone();
 922        cx.spawn_in(window, async move |picker, cx| {
 923            let matches = fuzzy::match_path_sets(
 924                candidate_sets.as_slice(),
 925                query.path_query(),
 926                &relative_to,
 927                false,
 928                100,
 929                &cancel_flag,
 930                cx.background_executor().clone(),
 931            )
 932            .await
 933            .into_iter()
 934            .map(ProjectPanelOrdMatch);
 935            let did_cancel = cancel_flag.load(atomic::Ordering::Acquire);
 936            picker
 937                .update(cx, |picker, cx| {
 938                    picker
 939                        .delegate
 940                        .set_search_matches(search_id, did_cancel, query, matches, cx)
 941                })
 942                .log_err();
 943        })
 944    }
 945
 946    fn set_search_matches(
 947        &mut self,
 948        search_id: usize,
 949        did_cancel: bool,
 950        query: FileSearchQuery,
 951        matches: impl IntoIterator<Item = ProjectPanelOrdMatch>,
 952        cx: &mut Context<Picker<Self>>,
 953    ) {
 954        if search_id >= self.latest_search_id {
 955            self.latest_search_id = search_id;
 956            let query_changed = Some(query.path_query())
 957                != self
 958                    .latest_search_query
 959                    .as_ref()
 960                    .map(|query| query.path_query());
 961            let extend_old_matches = self.latest_search_did_cancel && !query_changed;
 962
 963            let selected_match = if query_changed {
 964                None
 965            } else {
 966                self.matches.get(self.selected_index).cloned()
 967            };
 968
 969            let path_style = self.project.read(cx).path_style(cx);
 970            self.matches.push_new_matches(
 971                self.project.read(cx).worktree_store(),
 972                cx,
 973                &self.history_items,
 974                self.currently_opened_path.as_ref(),
 975                Some(&query),
 976                matches.into_iter(),
 977                extend_old_matches,
 978                path_style,
 979            );
 980
 981            let query_path = query.raw_query.as_str();
 982            if let Ok(mut query_path) = RelPath::new(Path::new(query_path), path_style) {
 983                let available_worktree = self
 984                    .project
 985                    .read(cx)
 986                    .visible_worktrees(cx)
 987                    .filter(|worktree| !worktree.read(cx).is_single_file())
 988                    .collect::<Vec<_>>();
 989                let worktree_count = available_worktree.len();
 990                let mut expect_worktree = available_worktree.first().cloned();
 991                for worktree in available_worktree {
 992                    let worktree_root = worktree.read(cx).root_name();
 993                    if worktree_count > 1 {
 994                        if let Ok(suffix) = query_path.strip_prefix(worktree_root) {
 995                            query_path = Cow::Owned(suffix.to_owned());
 996                            expect_worktree = Some(worktree);
 997                            break;
 998                        }
 999                    }
1000                }
1001
1002                if let Some(FoundPath { ref project, .. }) = self.currently_opened_path {
1003                    let worktree_id = project.worktree_id;
1004                    expect_worktree = self.project.read(cx).worktree_for_id(worktree_id, cx);
1005                }
1006
1007                if let Some(worktree) = expect_worktree {
1008                    let worktree = worktree.read(cx);
1009                    if worktree.entry_for_path(&query_path).is_none()
1010                        && !query.raw_query.ends_with("/")
1011                        && !(path_style.is_windows() && query.raw_query.ends_with("\\"))
1012                    {
1013                        self.matches.matches.push(Match::CreateNew(ProjectPath {
1014                            worktree_id: worktree.id(),
1015                            path: query_path.into_arc(),
1016                        }));
1017                    }
1018                }
1019            }
1020
1021            self.selected_index = selected_match.map_or_else(
1022                || self.calculate_selected_index(cx),
1023                |m| {
1024                    self.matches
1025                        .position(&m, self.currently_opened_path.as_ref())
1026                        .unwrap_or(0)
1027                },
1028            );
1029
1030            self.latest_search_query = Some(query);
1031            self.latest_search_did_cancel = did_cancel;
1032
1033            cx.notify();
1034        }
1035    }
1036
1037    fn labels_for_match(
1038        &self,
1039        path_match: &Match,
1040        window: &mut Window,
1041        cx: &App,
1042    ) -> (HighlightedLabel, HighlightedLabel) {
1043        let path_style = self.project.read(cx).path_style(cx);
1044        let (file_name, file_name_positions, mut full_path, mut full_path_positions) =
1045            match &path_match {
1046                Match::History {
1047                    path: entry_path,
1048                    panel_match,
1049                } => {
1050                    let worktree_id = entry_path.project.worktree_id;
1051                    let worktree = self
1052                        .project
1053                        .read(cx)
1054                        .worktree_for_id(worktree_id, cx)
1055                        .filter(|worktree| worktree.read(cx).is_visible());
1056
1057                    if let Some(panel_match) = panel_match {
1058                        self.labels_for_path_match(&panel_match.0, path_style)
1059                    } else if let Some(worktree) = worktree {
1060                        let full_path =
1061                            worktree.read(cx).root_name().join(&entry_path.project.path);
1062                        let mut components = full_path.components();
1063                        let filename = components.next_back().unwrap_or("");
1064                        let prefix = components.rest();
1065                        (
1066                            filename.to_string(),
1067                            Vec::new(),
1068                            prefix.display(path_style).to_string() + path_style.separator(),
1069                            Vec::new(),
1070                        )
1071                    } else {
1072                        (
1073                            entry_path
1074                                .absolute
1075                                .file_name()
1076                                .map_or(String::new(), |f| f.to_string_lossy().into_owned()),
1077                            Vec::new(),
1078                            entry_path.absolute.parent().map_or(String::new(), |path| {
1079                                path.to_string_lossy().into_owned() + path_style.separator()
1080                            }),
1081                            Vec::new(),
1082                        )
1083                    }
1084                }
1085                Match::Search(path_match) => self.labels_for_path_match(&path_match.0, path_style),
1086                Match::CreateNew(project_path) => (
1087                    format!("Create file: {}", project_path.path.display(path_style)),
1088                    vec![],
1089                    String::from(""),
1090                    vec![],
1091                ),
1092            };
1093
1094        if file_name_positions.is_empty() {
1095            let user_home_path = util::paths::home_dir().to_string_lossy();
1096            if !user_home_path.is_empty() && full_path.starts_with(&*user_home_path) {
1097                full_path.replace_range(0..user_home_path.len(), "~");
1098                full_path_positions.retain_mut(|pos| {
1099                    if *pos >= user_home_path.len() {
1100                        *pos -= user_home_path.len();
1101                        *pos += 1;
1102                        true
1103                    } else {
1104                        false
1105                    }
1106                })
1107            }
1108        }
1109
1110        if full_path.is_ascii() {
1111            let file_finder_settings = FileFinderSettings::get_global(cx);
1112            let max_width =
1113                FileFinder::modal_max_width(file_finder_settings.modal_max_width, window);
1114            let (normal_em, small_em) = {
1115                let style = window.text_style();
1116                let font_id = window.text_system().resolve_font(&style.font());
1117                let font_size = TextSize::Default.rems(cx).to_pixels(window.rem_size());
1118                let normal = cx
1119                    .text_system()
1120                    .em_width(font_id, font_size)
1121                    .unwrap_or(px(16.));
1122                let font_size = TextSize::Small.rems(cx).to_pixels(window.rem_size());
1123                let small = cx
1124                    .text_system()
1125                    .em_width(font_id, font_size)
1126                    .unwrap_or(px(10.));
1127                (normal, small)
1128            };
1129            let budget = full_path_budget(&file_name, normal_em, small_em, max_width);
1130            // If the computed budget is zero, we certainly won't be able to achieve it,
1131            // so no point trying to elide the path.
1132            if budget > 0 && full_path.len() > budget {
1133                let components = PathComponentSlice::new(&full_path);
1134                if let Some(elided_range) =
1135                    components.elision_range(budget - 1, &full_path_positions)
1136                {
1137                    let elided_len = elided_range.end - elided_range.start;
1138                    let placeholder = "";
1139                    full_path_positions.retain_mut(|mat| {
1140                        if *mat >= elided_range.end {
1141                            *mat -= elided_len;
1142                            *mat += placeholder.len();
1143                        } else if *mat >= elided_range.start {
1144                            return false;
1145                        }
1146                        true
1147                    });
1148                    full_path.replace_range(elided_range, placeholder);
1149                }
1150            }
1151        }
1152
1153        (
1154            HighlightedLabel::new(file_name, file_name_positions),
1155            HighlightedLabel::new(full_path, full_path_positions)
1156                .size(LabelSize::Small)
1157                .color(Color::Muted),
1158        )
1159    }
1160
1161    fn labels_for_path_match(
1162        &self,
1163        path_match: &PathMatch,
1164        path_style: PathStyle,
1165    ) -> (String, Vec<usize>, String, Vec<usize>) {
1166        let full_path = path_match.path_prefix.join(&path_match.path);
1167        let mut path_positions = path_match.positions.clone();
1168
1169        let file_name = full_path.file_name().unwrap_or("");
1170        let file_name_start = full_path.as_unix_str().len() - file_name.len();
1171        let file_name_positions = path_positions
1172            .iter()
1173            .filter_map(|pos| {
1174                if pos >= &file_name_start {
1175                    Some(pos - file_name_start)
1176                } else {
1177                    None
1178                }
1179            })
1180            .collect::<Vec<_>>();
1181
1182        let full_path = full_path
1183            .display(path_style)
1184            .trim_end_matches(&file_name)
1185            .to_string();
1186        path_positions.retain(|idx| *idx < full_path.len());
1187
1188        debug_assert!(
1189            file_name_positions
1190                .iter()
1191                .all(|ix| file_name[*ix..].chars().next().is_some()),
1192            "invalid file name positions {file_name:?} {file_name_positions:?}"
1193        );
1194        debug_assert!(
1195            path_positions
1196                .iter()
1197                .all(|ix| full_path[*ix..].chars().next().is_some()),
1198            "invalid path positions {full_path:?} {path_positions:?}"
1199        );
1200
1201        (
1202            file_name.to_string(),
1203            file_name_positions,
1204            full_path,
1205            path_positions,
1206        )
1207    }
1208
1209    /// Attempts to resolve an absolute file path and update the search matches if found.
1210    ///
1211    /// If the query path resolves to an absolute file that exists in the project,
1212    /// this method will find the corresponding worktree and relative path, create a
1213    /// match for it, and update the picker's search results.
1214    ///
1215    /// Returns `true` if the absolute path exists, otherwise returns `false`.
1216    fn lookup_absolute_path(
1217        &self,
1218        query: FileSearchQuery,
1219        window: &mut Window,
1220        cx: &mut Context<Picker<Self>>,
1221    ) -> Task<bool> {
1222        cx.spawn_in(window, async move |picker, cx| {
1223            let Some(project) = picker
1224                .read_with(cx, |picker, _| picker.delegate.project.clone())
1225                .log_err()
1226            else {
1227                return false;
1228            };
1229
1230            let query_path = Path::new(query.path_query());
1231            let mut path_matches = Vec::new();
1232
1233            let abs_file_exists = if let Ok(task) = project.update(cx, |this, cx| {
1234                this.resolve_abs_file_path(query.path_query(), cx)
1235            }) {
1236                task.await.is_some()
1237            } else {
1238                false
1239            };
1240
1241            if abs_file_exists {
1242                let update_result = project
1243                    .update(cx, |project, cx| {
1244                        if let Some((worktree, relative_path)) =
1245                            project.find_worktree(query_path, cx)
1246                        {
1247                            path_matches.push(ProjectPanelOrdMatch(PathMatch {
1248                                score: 1.0,
1249                                positions: Vec::new(),
1250                                worktree_id: worktree.read(cx).id().to_usize(),
1251                                path: relative_path,
1252                                path_prefix: RelPath::empty().into(),
1253                                is_dir: false, // File finder doesn't support directories
1254                                distance_to_relative_ancestor: usize::MAX,
1255                            }));
1256                        }
1257                    })
1258                    .log_err();
1259                if update_result.is_none() {
1260                    return abs_file_exists;
1261                }
1262            }
1263
1264            picker
1265                .update_in(cx, |picker, _, cx| {
1266                    let picker_delegate = &mut picker.delegate;
1267                    let search_id = util::post_inc(&mut picker_delegate.search_count);
1268                    picker_delegate.set_search_matches(search_id, false, query, path_matches, cx);
1269
1270                    anyhow::Ok(())
1271                })
1272                .log_err();
1273            abs_file_exists
1274        })
1275    }
1276
1277    /// Skips first history match (that is displayed topmost) if it's currently opened.
1278    fn calculate_selected_index(&self, cx: &mut Context<Picker<Self>>) -> usize {
1279        if FileFinderSettings::get_global(cx).skip_focus_for_active_in_search
1280            && let Some(Match::History { path, .. }) = self.matches.get(0)
1281            && Some(path) == self.currently_opened_path.as_ref()
1282        {
1283            let elements_after_first = self.matches.len() - 1;
1284            if elements_after_first > 0 {
1285                return 1;
1286            }
1287        }
1288
1289        0
1290    }
1291
1292    fn key_context(&self, window: &Window, cx: &App) -> KeyContext {
1293        let mut key_context = KeyContext::new_with_defaults();
1294        key_context.add("FileFinder");
1295
1296        if self.filter_popover_menu_handle.is_focused(window, cx) {
1297            key_context.add("filter_menu_open");
1298        }
1299
1300        if self.split_popover_menu_handle.is_focused(window, cx) {
1301            key_context.add("split_menu_open");
1302        }
1303        key_context
1304    }
1305}
1306
1307fn full_path_budget(
1308    file_name: &str,
1309    normal_em: Pixels,
1310    small_em: Pixels,
1311    max_width: Pixels,
1312) -> usize {
1313    (((max_width / 0.8) - file_name.len() * normal_em) / small_em) as usize
1314}
1315
1316impl PickerDelegate for FileFinderDelegate {
1317    type ListItem = ListItem;
1318
1319    fn placeholder_text(&self, _window: &mut Window, _cx: &mut App) -> Arc<str> {
1320        "Search project files...".into()
1321    }
1322
1323    fn match_count(&self) -> usize {
1324        self.matches.len()
1325    }
1326
1327    fn selected_index(&self) -> usize {
1328        self.selected_index
1329    }
1330
1331    fn set_selected_index(&mut self, ix: usize, _: &mut Window, cx: &mut Context<Picker<Self>>) {
1332        self.has_changed_selected_index = true;
1333        self.selected_index = ix;
1334        cx.notify();
1335    }
1336
1337    fn separators_after_indices(&self) -> Vec<usize> {
1338        if self.separate_history {
1339            let first_non_history_index = self
1340                .matches
1341                .matches
1342                .iter()
1343                .enumerate()
1344                .find(|(_, m)| !matches!(m, Match::History { .. }))
1345                .map(|(i, _)| i);
1346            if let Some(first_non_history_index) = first_non_history_index
1347                && first_non_history_index > 0
1348            {
1349                return vec![first_non_history_index - 1];
1350            }
1351        }
1352        Vec::new()
1353    }
1354
1355    fn update_matches(
1356        &mut self,
1357        raw_query: String,
1358        window: &mut Window,
1359        cx: &mut Context<Picker<Self>>,
1360    ) -> Task<()> {
1361        let raw_query = raw_query.replace(' ', "");
1362        let raw_query = raw_query.trim();
1363
1364        let raw_query = match &raw_query.get(0..2) {
1365            Some(".\\" | "./") => &raw_query[2..],
1366            Some(prefix @ ("a\\" | "a/" | "b\\" | "b/")) => {
1367                if self
1368                    .workspace
1369                    .upgrade()
1370                    .into_iter()
1371                    .flat_map(|workspace| workspace.read(cx).worktrees(cx))
1372                    .all(|worktree| {
1373                        worktree
1374                            .read(cx)
1375                            .entry_for_path(RelPath::unix(prefix.split_at(1).0).unwrap())
1376                            .is_none_or(|entry| !entry.is_dir())
1377                    })
1378                {
1379                    &raw_query[2..]
1380                } else {
1381                    raw_query
1382                }
1383            }
1384            _ => raw_query,
1385        };
1386
1387        if raw_query.is_empty() {
1388            // if there was no query before, and we already have some (history) matches
1389            // there's no need to update anything, since nothing has changed.
1390            // We also want to populate matches set from history entries on the first update.
1391            if self.latest_search_query.is_some() || self.first_update {
1392                let project = self.project.read(cx);
1393
1394                self.latest_search_id = post_inc(&mut self.search_count);
1395                self.latest_search_query = None;
1396                self.matches = Matches {
1397                    separate_history: self.separate_history,
1398                    ..Matches::default()
1399                };
1400                let path_style = self.project.read(cx).path_style(cx);
1401
1402                self.matches.push_new_matches(
1403                    project.worktree_store(),
1404                    cx,
1405                    self.history_items.iter().filter(|history_item| {
1406                        project
1407                            .worktree_for_id(history_item.project.worktree_id, cx)
1408                            .is_some()
1409                            || project.is_local()
1410                            || project.is_via_remote_server()
1411                    }),
1412                    self.currently_opened_path.as_ref(),
1413                    None,
1414                    None.into_iter(),
1415                    false,
1416                    path_style,
1417                );
1418
1419                self.first_update = false;
1420                self.selected_index = 0;
1421            }
1422            cx.notify();
1423            Task::ready(())
1424        } else {
1425            let path_position = PathWithPosition::parse_str(raw_query);
1426            let raw_query = raw_query.trim().trim_end_matches(':').to_owned();
1427            let path = path_position.path.clone();
1428            let path_str = path_position.path.to_str();
1429            let path_trimmed = path_str.unwrap_or(&raw_query).trim_end_matches(':');
1430            let file_query_end = if path_trimmed == raw_query {
1431                None
1432            } else {
1433                // Safe to unwrap as we won't get here when the unwrap in if fails
1434                Some(path_str.unwrap().len())
1435            };
1436
1437            let query = FileSearchQuery {
1438                raw_query,
1439                file_query_end,
1440                path_position,
1441            };
1442
1443            cx.spawn_in(window, async move |this, cx| {
1444                let _ = maybe!(async move {
1445                    let is_absolute_path = path.is_absolute();
1446                    let did_resolve_abs_path = is_absolute_path
1447                        && this
1448                            .update_in(cx, |this, window, cx| {
1449                                this.delegate
1450                                    .lookup_absolute_path(query.clone(), window, cx)
1451                            })?
1452                            .await;
1453
1454                    // Only check for relative paths if no absolute paths were
1455                    // found.
1456                    if !did_resolve_abs_path {
1457                        this.update_in(cx, |this, window, cx| {
1458                            this.delegate.spawn_search(query, window, cx)
1459                        })?
1460                        .await;
1461                    }
1462                    anyhow::Ok(())
1463                })
1464                .await;
1465            })
1466        }
1467    }
1468
1469    fn confirm(
1470        &mut self,
1471        secondary: bool,
1472        window: &mut Window,
1473        cx: &mut Context<Picker<FileFinderDelegate>>,
1474    ) {
1475        if let Some(m) = self.matches.get(self.selected_index())
1476            && let Some(workspace) = self.workspace.upgrade()
1477        {
1478            let open_task = workspace.update(cx, |workspace, cx| {
1479                let split_or_open =
1480                    |workspace: &mut Workspace,
1481                     project_path,
1482                     window: &mut Window,
1483                     cx: &mut Context<Workspace>| {
1484                        let allow_preview =
1485                            PreviewTabsSettings::get_global(cx).enable_preview_from_file_finder;
1486                        if secondary {
1487                            workspace.split_path_preview(
1488                                project_path,
1489                                allow_preview,
1490                                None,
1491                                window,
1492                                cx,
1493                            )
1494                        } else {
1495                            workspace.open_path_preview(
1496                                project_path,
1497                                None,
1498                                true,
1499                                allow_preview,
1500                                true,
1501                                window,
1502                                cx,
1503                            )
1504                        }
1505                    };
1506                match &m {
1507                    Match::CreateNew(project_path) => {
1508                        // Create a new file with the given filename
1509                        if secondary {
1510                            workspace.split_path_preview(
1511                                project_path.clone(),
1512                                false,
1513                                None,
1514                                window,
1515                                cx,
1516                            )
1517                        } else {
1518                            workspace.open_path_preview(
1519                                project_path.clone(),
1520                                None,
1521                                true,
1522                                false,
1523                                true,
1524                                window,
1525                                cx,
1526                            )
1527                        }
1528                    }
1529
1530                    Match::History { path, .. } => {
1531                        let worktree_id = path.project.worktree_id;
1532                        if workspace
1533                            .project()
1534                            .read(cx)
1535                            .worktree_for_id(worktree_id, cx)
1536                            .is_some()
1537                        {
1538                            split_or_open(
1539                                workspace,
1540                                ProjectPath {
1541                                    worktree_id,
1542                                    path: Arc::clone(&path.project.path),
1543                                },
1544                                window,
1545                                cx,
1546                            )
1547                        } else if secondary {
1548                            workspace.split_abs_path(path.absolute.clone(), false, window, cx)
1549                        } else {
1550                            workspace.open_abs_path(
1551                                path.absolute.clone(),
1552                                OpenOptions {
1553                                    visible: Some(OpenVisible::None),
1554                                    ..Default::default()
1555                                },
1556                                window,
1557                                cx,
1558                            )
1559                        }
1560                    }
1561                    Match::Search(m) => split_or_open(
1562                        workspace,
1563                        ProjectPath {
1564                            worktree_id: WorktreeId::from_usize(m.0.worktree_id),
1565                            path: m.0.path.clone(),
1566                        },
1567                        window,
1568                        cx,
1569                    ),
1570                }
1571            });
1572
1573            let row = self
1574                .latest_search_query
1575                .as_ref()
1576                .and_then(|query| query.path_position.row)
1577                .map(|row| row.saturating_sub(1));
1578            let col = self
1579                .latest_search_query
1580                .as_ref()
1581                .and_then(|query| query.path_position.column)
1582                .unwrap_or(0)
1583                .saturating_sub(1);
1584            let finder = self.file_finder.clone();
1585
1586            cx.spawn_in(window, async move |_, cx| {
1587                let item = open_task.await.notify_async_err(cx)?;
1588                if let Some(row) = row
1589                    && let Some(active_editor) = item.downcast::<Editor>()
1590                {
1591                    active_editor
1592                        .downgrade()
1593                        .update_in(cx, |editor, window, cx| {
1594                            editor.go_to_singleton_buffer_point(Point::new(row, col), window, cx);
1595                        })
1596                        .log_err();
1597                }
1598                finder.update(cx, |_, cx| cx.emit(DismissEvent)).ok()?;
1599
1600                Some(())
1601            })
1602            .detach();
1603        }
1604    }
1605
1606    fn dismissed(&mut self, _: &mut Window, cx: &mut Context<Picker<FileFinderDelegate>>) {
1607        self.file_finder
1608            .update(cx, |_, cx| cx.emit(DismissEvent))
1609            .log_err();
1610    }
1611
1612    fn render_match(
1613        &self,
1614        ix: usize,
1615        selected: bool,
1616        window: &mut Window,
1617        cx: &mut Context<Picker<Self>>,
1618    ) -> Option<Self::ListItem> {
1619        let settings = FileFinderSettings::get_global(cx);
1620
1621        let path_match = self.matches.get(ix)?;
1622
1623        let history_icon = match &path_match {
1624            Match::History { .. } => Icon::new(IconName::HistoryRerun)
1625                .color(Color::Muted)
1626                .size(IconSize::Small)
1627                .into_any_element(),
1628            Match::Search(_) => v_flex()
1629                .flex_none()
1630                .size(IconSize::Small.rems())
1631                .into_any_element(),
1632            Match::CreateNew(_) => Icon::new(IconName::Plus)
1633                .color(Color::Muted)
1634                .size(IconSize::Small)
1635                .into_any_element(),
1636        };
1637        let (file_name_label, full_path_label) = self.labels_for_match(path_match, window, cx);
1638
1639        let file_icon = maybe!({
1640            if !settings.file_icons {
1641                return None;
1642            }
1643            let abs_path = path_match.abs_path(&self.project, cx)?;
1644            let file_name = abs_path.file_name()?;
1645            let icon = FileIcons::get_icon(file_name.as_ref(), cx)?;
1646            Some(Icon::from_path(icon).color(Color::Muted))
1647        });
1648
1649        Some(
1650            ListItem::new(ix)
1651                .spacing(ListItemSpacing::Sparse)
1652                .start_slot::<Icon>(file_icon)
1653                .end_slot::<AnyElement>(history_icon)
1654                .inset(true)
1655                .toggle_state(selected)
1656                .child(
1657                    h_flex()
1658                        .gap_2()
1659                        .py_px()
1660                        .child(file_name_label)
1661                        .child(full_path_label),
1662                ),
1663        )
1664    }
1665
1666    fn render_footer(
1667        &self,
1668        window: &mut Window,
1669        cx: &mut Context<Picker<Self>>,
1670    ) -> Option<AnyElement> {
1671        let focus_handle = self.focus_handle.clone();
1672
1673        Some(
1674            h_flex()
1675                .w_full()
1676                .p_1p5()
1677                .justify_between()
1678                .border_t_1()
1679                .border_color(cx.theme().colors().border_variant)
1680                .child(
1681                    PopoverMenu::new("filter-menu-popover")
1682                        .with_handle(self.filter_popover_menu_handle.clone())
1683                        .attach(gpui::Corner::BottomRight)
1684                        .anchor(gpui::Corner::BottomLeft)
1685                        .offset(gpui::Point {
1686                            x: px(1.0),
1687                            y: px(1.0),
1688                        })
1689                        .trigger_with_tooltip(
1690                            IconButton::new("filter-trigger", IconName::Sliders)
1691                                .icon_size(IconSize::Small)
1692                                .icon_size(IconSize::Small)
1693                                .toggle_state(self.include_ignored.unwrap_or(false))
1694                                .when(self.include_ignored.is_some(), |this| {
1695                                    this.indicator(Indicator::dot().color(Color::Info))
1696                                }),
1697                            {
1698                                let focus_handle = focus_handle.clone();
1699                                move |window, cx| {
1700                                    Tooltip::for_action_in(
1701                                        "Filter Options",
1702                                        &ToggleFilterMenu,
1703                                        &focus_handle,
1704                                        window,
1705                                        cx,
1706                                    )
1707                                }
1708                            },
1709                        )
1710                        .menu({
1711                            let focus_handle = focus_handle.clone();
1712                            let include_ignored = self.include_ignored;
1713
1714                            move |window, cx| {
1715                                Some(ContextMenu::build(window, cx, {
1716                                    let focus_handle = focus_handle.clone();
1717                                    move |menu, _, _| {
1718                                        menu.context(focus_handle.clone())
1719                                            .header("Filter Options")
1720                                            .toggleable_entry(
1721                                                "Include Ignored Files",
1722                                                include_ignored.unwrap_or(false),
1723                                                ui::IconPosition::End,
1724                                                Some(ToggleIncludeIgnored.boxed_clone()),
1725                                                move |window, cx| {
1726                                                    window.focus(&focus_handle);
1727                                                    window.dispatch_action(
1728                                                        ToggleIncludeIgnored.boxed_clone(),
1729                                                        cx,
1730                                                    );
1731                                                },
1732                                            )
1733                                    }
1734                                }))
1735                            }
1736                        }),
1737                )
1738                .child(
1739                    h_flex()
1740                        .gap_0p5()
1741                        .child(
1742                            PopoverMenu::new("split-menu-popover")
1743                                .with_handle(self.split_popover_menu_handle.clone())
1744                                .attach(gpui::Corner::BottomRight)
1745                                .anchor(gpui::Corner::BottomLeft)
1746                                .offset(gpui::Point {
1747                                    x: px(1.0),
1748                                    y: px(1.0),
1749                                })
1750                                .trigger(
1751                                    ButtonLike::new("split-trigger")
1752                                        .child(Label::new("Split…"))
1753                                        .selected_style(ButtonStyle::Tinted(TintColor::Accent))
1754                                        .children(
1755                                            KeyBinding::for_action_in(
1756                                                &ToggleSplitMenu,
1757                                                &focus_handle,
1758                                                window,
1759                                                cx,
1760                                            )
1761                                            .map(|kb| kb.size(rems_from_px(12.))),
1762                                        ),
1763                                )
1764                                .menu({
1765                                    let focus_handle = focus_handle.clone();
1766
1767                                    move |window, cx| {
1768                                        Some(ContextMenu::build(window, cx, {
1769                                            let focus_handle = focus_handle.clone();
1770                                            move |menu, _, _| {
1771                                                menu.context(focus_handle)
1772                                                    .action(
1773                                                        "Split Left",
1774                                                        pane::SplitLeft.boxed_clone(),
1775                                                    )
1776                                                    .action(
1777                                                        "Split Right",
1778                                                        pane::SplitRight.boxed_clone(),
1779                                                    )
1780                                                    .action("Split Up", pane::SplitUp.boxed_clone())
1781                                                    .action(
1782                                                        "Split Down",
1783                                                        pane::SplitDown.boxed_clone(),
1784                                                    )
1785                                            }
1786                                        }))
1787                                    }
1788                                }),
1789                        )
1790                        .child(
1791                            Button::new("open-selection", "Open")
1792                                .key_binding(
1793                                    KeyBinding::for_action_in(
1794                                        &menu::Confirm,
1795                                        &focus_handle,
1796                                        window,
1797                                        cx,
1798                                    )
1799                                    .map(|kb| kb.size(rems_from_px(12.))),
1800                                )
1801                                .on_click(|_, window, cx| {
1802                                    window.dispatch_action(menu::Confirm.boxed_clone(), cx)
1803                                }),
1804                        ),
1805                )
1806                .into_any(),
1807        )
1808    }
1809}
1810
1811#[derive(Clone, Debug, PartialEq, Eq)]
1812struct PathComponentSlice<'a> {
1813    path: Cow<'a, Path>,
1814    path_str: Cow<'a, str>,
1815    component_ranges: Vec<(Component<'a>, Range<usize>)>,
1816}
1817
1818impl<'a> PathComponentSlice<'a> {
1819    fn new(path: &'a str) -> Self {
1820        let trimmed_path = Path::new(path).components().as_path().as_os_str();
1821        let mut component_ranges = Vec::new();
1822        let mut components = Path::new(trimmed_path).components();
1823        let len = trimmed_path.as_encoded_bytes().len();
1824        let mut pos = 0;
1825        while let Some(component) = components.next() {
1826            component_ranges.push((component, pos..0));
1827            pos = len - components.as_path().as_os_str().as_encoded_bytes().len();
1828        }
1829        for ((_, range), ancestor) in component_ranges
1830            .iter_mut()
1831            .rev()
1832            .zip(Path::new(trimmed_path).ancestors())
1833        {
1834            range.end = ancestor.as_os_str().as_encoded_bytes().len();
1835        }
1836        Self {
1837            path: Cow::Borrowed(Path::new(path)),
1838            path_str: Cow::Borrowed(path),
1839            component_ranges,
1840        }
1841    }
1842
1843    fn elision_range(&self, budget: usize, matches: &[usize]) -> Option<Range<usize>> {
1844        let eligible_range = {
1845            assert!(matches.windows(2).all(|w| w[0] <= w[1]));
1846            let mut matches = matches.iter().copied().peekable();
1847            let mut longest: Option<Range<usize>> = None;
1848            let mut cur = 0..0;
1849            let mut seen_normal = false;
1850            for (i, (component, range)) in self.component_ranges.iter().enumerate() {
1851                let is_normal = matches!(component, Component::Normal(_));
1852                let is_first_normal = is_normal && !seen_normal;
1853                seen_normal |= is_normal;
1854                let is_last = i == self.component_ranges.len() - 1;
1855                let contains_match = matches.peek().is_some_and(|mat| range.contains(mat));
1856                if contains_match {
1857                    matches.next();
1858                }
1859                if is_first_normal || is_last || !is_normal || contains_match {
1860                    if longest
1861                        .as_ref()
1862                        .is_none_or(|old| old.end - old.start <= cur.end - cur.start)
1863                    {
1864                        longest = Some(cur);
1865                    }
1866                    cur = i + 1..i + 1;
1867                } else {
1868                    cur.end = i + 1;
1869                }
1870            }
1871            if longest
1872                .as_ref()
1873                .is_none_or(|old| old.end - old.start <= cur.end - cur.start)
1874            {
1875                longest = Some(cur);
1876            }
1877            longest
1878        };
1879
1880        let eligible_range = eligible_range?;
1881        assert!(eligible_range.start <= eligible_range.end);
1882        if eligible_range.is_empty() {
1883            return None;
1884        }
1885
1886        let elided_range: Range<usize> = {
1887            let byte_range = self.component_ranges[eligible_range.start].1.start
1888                ..self.component_ranges[eligible_range.end - 1].1.end;
1889            let midpoint = self.path_str.len() / 2;
1890            let distance_from_start = byte_range.start.abs_diff(midpoint);
1891            let distance_from_end = byte_range.end.abs_diff(midpoint);
1892            let pick_from_end = distance_from_start > distance_from_end;
1893            let mut len_with_elision = self.path_str.len();
1894            let mut i = eligible_range.start;
1895            while i < eligible_range.end {
1896                let x = if pick_from_end {
1897                    eligible_range.end - i + eligible_range.start - 1
1898                } else {
1899                    i
1900                };
1901                len_with_elision -= self.component_ranges[x]
1902                    .0
1903                    .as_os_str()
1904                    .as_encoded_bytes()
1905                    .len()
1906                    + 1;
1907                if len_with_elision <= budget {
1908                    break;
1909                }
1910                i += 1;
1911            }
1912            if len_with_elision > budget {
1913                return None;
1914            } else if pick_from_end {
1915                let x = eligible_range.end - i + eligible_range.start - 1;
1916                x..eligible_range.end
1917            } else {
1918                let x = i;
1919                eligible_range.start..x + 1
1920            }
1921        };
1922
1923        let byte_range = self.component_ranges[elided_range.start].1.start
1924            ..self.component_ranges[elided_range.end - 1].1.end;
1925        Some(byte_range)
1926    }
1927}