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