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