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