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 - px(512.)).max(small_width),
 359            FileFinderWidth::Large => (window_width - px(768.)).max(small_width),
 360            FileFinderWidth::Medium => (window_width - px(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    const 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    const 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    const 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    const 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            .worktree_store()
 870            .read(cx)
 871            .visible_worktrees_and_single_files(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.root_entry().is_some_and(|entry| entry.is_ignored)
 882                    }),
 883                    include_root_name,
 884                    candidates: project::Candidates::Files,
 885                }
 886            })
 887            .collect::<Vec<_>>();
 888
 889        let search_id = util::post_inc(&mut self.search_count);
 890        self.cancel_flag.store(true, atomic::Ordering::Release);
 891        self.cancel_flag = Arc::new(AtomicBool::new(false));
 892        let cancel_flag = self.cancel_flag.clone();
 893        cx.spawn_in(window, async move |picker, cx| {
 894            let matches = fuzzy::match_path_sets(
 895                candidate_sets.as_slice(),
 896                query.path_query(),
 897                &relative_to,
 898                false,
 899                100,
 900                &cancel_flag,
 901                cx.background_executor().clone(),
 902            )
 903            .await
 904            .into_iter()
 905            .map(ProjectPanelOrdMatch);
 906            let did_cancel = cancel_flag.load(atomic::Ordering::Acquire);
 907            picker
 908                .update(cx, |picker, cx| {
 909                    picker
 910                        .delegate
 911                        .set_search_matches(search_id, did_cancel, query, matches, cx)
 912                })
 913                .log_err();
 914        })
 915    }
 916
 917    fn set_search_matches(
 918        &mut self,
 919        search_id: usize,
 920        did_cancel: bool,
 921        query: FileSearchQuery,
 922        matches: impl IntoIterator<Item = ProjectPanelOrdMatch>,
 923        cx: &mut Context<Picker<Self>>,
 924    ) {
 925        if search_id >= self.latest_search_id {
 926            self.latest_search_id = search_id;
 927            let query_changed = Some(query.path_query())
 928                != self
 929                    .latest_search_query
 930                    .as_ref()
 931                    .map(|query| query.path_query());
 932            let extend_old_matches = self.latest_search_did_cancel && !query_changed;
 933
 934            let selected_match = if query_changed {
 935                None
 936            } else {
 937                self.matches.get(self.selected_index).cloned()
 938            };
 939
 940            self.matches.push_new_matches(
 941                &self.history_items,
 942                self.currently_opened_path.as_ref(),
 943                Some(&query),
 944                matches.into_iter(),
 945                extend_old_matches,
 946            );
 947
 948            let path_style = self.project.read(cx).path_style(cx);
 949            let query_path = query.raw_query.as_str();
 950            if let Ok(mut query_path) = RelPath::new(Path::new(query_path), path_style) {
 951                let available_worktree = self
 952                    .project
 953                    .read(cx)
 954                    .visible_worktrees(cx)
 955                    .filter(|worktree| !worktree.read(cx).is_single_file())
 956                    .collect::<Vec<_>>();
 957                let worktree_count = available_worktree.len();
 958                let mut expect_worktree = available_worktree.first().cloned();
 959                for worktree in available_worktree {
 960                    let worktree_root = worktree.read(cx).root_name();
 961                    if worktree_count > 1 {
 962                        if let Ok(suffix) = query_path.strip_prefix(worktree_root) {
 963                            query_path = Cow::Owned(suffix.to_owned());
 964                            expect_worktree = Some(worktree);
 965                            break;
 966                        }
 967                    }
 968                }
 969
 970                if let Some(FoundPath { ref project, .. }) = self.currently_opened_path {
 971                    let worktree_id = project.worktree_id;
 972                    expect_worktree = self.project.read(cx).worktree_for_id(worktree_id, cx);
 973                }
 974
 975                if let Some(worktree) = expect_worktree {
 976                    let worktree = worktree.read(cx);
 977                    if worktree.entry_for_path(&query_path).is_none()
 978                        && !query.raw_query.ends_with("/")
 979                        && !(path_style.is_windows() && query.raw_query.ends_with("\\"))
 980                    {
 981                        self.matches.matches.push(Match::CreateNew(ProjectPath {
 982                            worktree_id: worktree.id(),
 983                            path: query_path.into_arc(),
 984                        }));
 985                    }
 986                }
 987            }
 988
 989            self.selected_index = selected_match.map_or_else(
 990                || self.calculate_selected_index(cx),
 991                |m| {
 992                    self.matches
 993                        .position(&m, self.currently_opened_path.as_ref())
 994                        .unwrap_or(0)
 995                },
 996            );
 997
 998            self.latest_search_query = Some(query);
 999            self.latest_search_did_cancel = did_cancel;
1000
1001            cx.notify();
1002        }
1003    }
1004
1005    fn labels_for_match(
1006        &self,
1007        path_match: &Match,
1008        window: &mut Window,
1009        cx: &App,
1010    ) -> (HighlightedLabel, HighlightedLabel) {
1011        let path_style = self.project.read(cx).path_style(cx);
1012        let (file_name, file_name_positions, mut full_path, mut full_path_positions) =
1013            match &path_match {
1014                Match::History {
1015                    path: entry_path,
1016                    panel_match,
1017                } => {
1018                    let worktree_id = entry_path.project.worktree_id;
1019                    let worktree = self
1020                        .project
1021                        .read(cx)
1022                        .worktree_for_id(worktree_id, cx)
1023                        .filter(|worktree| worktree.read(cx).is_visible());
1024
1025                    if let Some(panel_match) = panel_match {
1026                        self.labels_for_path_match(&panel_match.0, path_style)
1027                    } else if let Some(worktree) = worktree {
1028                        let full_path =
1029                            worktree.read(cx).root_name().join(&entry_path.project.path);
1030                        let mut components = full_path.components();
1031                        let filename = components.next_back().unwrap_or("");
1032                        let prefix = components.rest();
1033                        (
1034                            filename.to_string(),
1035                            Vec::new(),
1036                            prefix.display(path_style).to_string() + path_style.separator(),
1037                            Vec::new(),
1038                        )
1039                    } else {
1040                        (
1041                            entry_path
1042                                .absolute
1043                                .file_name()
1044                                .map_or(String::new(), |f| f.to_string_lossy().into_owned()),
1045                            Vec::new(),
1046                            entry_path.absolute.parent().map_or(String::new(), |path| {
1047                                path.to_string_lossy().into_owned() + path_style.separator()
1048                            }),
1049                            Vec::new(),
1050                        )
1051                    }
1052                }
1053                Match::Search(path_match) => self.labels_for_path_match(&path_match.0, path_style),
1054                Match::CreateNew(project_path) => (
1055                    format!("Create file: {}", project_path.path.display(path_style)),
1056                    vec![],
1057                    String::from(""),
1058                    vec![],
1059                ),
1060            };
1061
1062        if file_name_positions.is_empty() {
1063            let user_home_path = util::paths::home_dir().to_string_lossy();
1064            if !user_home_path.is_empty() && full_path.starts_with(&*user_home_path) {
1065                full_path.replace_range(0..user_home_path.len(), "~");
1066                full_path_positions.retain_mut(|pos| {
1067                    if *pos >= user_home_path.len() {
1068                        *pos -= user_home_path.len();
1069                        *pos += 1;
1070                        true
1071                    } else {
1072                        false
1073                    }
1074                })
1075            }
1076        }
1077
1078        if full_path.is_ascii() {
1079            let file_finder_settings = FileFinderSettings::get_global(cx);
1080            let max_width =
1081                FileFinder::modal_max_width(file_finder_settings.modal_max_width, window);
1082            let (normal_em, small_em) = {
1083                let style = window.text_style();
1084                let font_id = window.text_system().resolve_font(&style.font());
1085                let font_size = TextSize::Default.rems(cx).to_pixels(window.rem_size());
1086                let normal = cx
1087                    .text_system()
1088                    .em_width(font_id, font_size)
1089                    .unwrap_or(px(16.));
1090                let font_size = TextSize::Small.rems(cx).to_pixels(window.rem_size());
1091                let small = cx
1092                    .text_system()
1093                    .em_width(font_id, font_size)
1094                    .unwrap_or(px(10.));
1095                (normal, small)
1096            };
1097            let budget = full_path_budget(&file_name, normal_em, small_em, max_width);
1098            // If the computed budget is zero, we certainly won't be able to achieve it,
1099            // so no point trying to elide the path.
1100            if budget > 0 && full_path.len() > budget {
1101                let components = PathComponentSlice::new(&full_path);
1102                if let Some(elided_range) =
1103                    components.elision_range(budget - 1, &full_path_positions)
1104                {
1105                    let elided_len = elided_range.end - elided_range.start;
1106                    let placeholder = "…";
1107                    full_path_positions.retain_mut(|mat| {
1108                        if *mat >= elided_range.end {
1109                            *mat -= elided_len;
1110                            *mat += placeholder.len();
1111                        } else if *mat >= elided_range.start {
1112                            return false;
1113                        }
1114                        true
1115                    });
1116                    full_path.replace_range(elided_range, placeholder);
1117                }
1118            }
1119        }
1120
1121        (
1122            HighlightedLabel::new(file_name, file_name_positions),
1123            HighlightedLabel::new(full_path, full_path_positions)
1124                .size(LabelSize::Small)
1125                .color(Color::Muted),
1126        )
1127    }
1128
1129    fn labels_for_path_match(
1130        &self,
1131        path_match: &PathMatch,
1132        path_style: PathStyle,
1133    ) -> (String, Vec<usize>, String, Vec<usize>) {
1134        let full_path = path_match.path_prefix.join(&path_match.path);
1135        let mut path_positions = path_match.positions.clone();
1136
1137        let file_name = full_path.file_name().unwrap_or("");
1138        let file_name_start = full_path.as_unix_str().len() - file_name.len();
1139        let file_name_positions = path_positions
1140            .iter()
1141            .filter_map(|pos| {
1142                if pos >= &file_name_start {
1143                    Some(pos - file_name_start)
1144                } else {
1145                    None
1146                }
1147            })
1148            .collect::<Vec<_>>();
1149
1150        let full_path = full_path
1151            .display(path_style)
1152            .trim_end_matches(&file_name)
1153            .to_string();
1154        path_positions.retain(|idx| *idx < full_path.len());
1155
1156        debug_assert!(
1157            file_name_positions
1158                .iter()
1159                .all(|ix| file_name[*ix..].chars().next().is_some()),
1160            "invalid file name positions {file_name:?} {file_name_positions:?}"
1161        );
1162        debug_assert!(
1163            path_positions
1164                .iter()
1165                .all(|ix| full_path[*ix..].chars().next().is_some()),
1166            "invalid path positions {full_path:?} {path_positions:?}"
1167        );
1168
1169        (
1170            file_name.to_string(),
1171            file_name_positions,
1172            full_path,
1173            path_positions,
1174        )
1175    }
1176
1177    /// Attempts to resolve an absolute file path and update the search matches if found.
1178    ///
1179    /// If the query path resolves to an absolute file that exists in the project,
1180    /// this method will find the corresponding worktree and relative path, create a
1181    /// match for it, and update the picker's search results.
1182    ///
1183    /// Returns `true` if the absolute path exists, otherwise returns `false`.
1184    fn lookup_absolute_path(
1185        &self,
1186        query: FileSearchQuery,
1187        window: &mut Window,
1188        cx: &mut Context<Picker<Self>>,
1189    ) -> Task<bool> {
1190        cx.spawn_in(window, async move |picker, cx| {
1191            let Some(project) = picker
1192                .read_with(cx, |picker, _| picker.delegate.project.clone())
1193                .log_err()
1194            else {
1195                return false;
1196            };
1197
1198            let query_path = Path::new(query.path_query());
1199            let mut path_matches = Vec::new();
1200
1201            let abs_file_exists = if let Ok(task) = project.update(cx, |this, cx| {
1202                this.resolve_abs_file_path(query.path_query(), cx)
1203            }) {
1204                task.await.is_some()
1205            } else {
1206                false
1207            };
1208
1209            if abs_file_exists {
1210                let update_result = project
1211                    .update(cx, |project, cx| {
1212                        if let Some((worktree, relative_path)) =
1213                            project.find_worktree(query_path, cx)
1214                        {
1215                            path_matches.push(ProjectPanelOrdMatch(PathMatch {
1216                                score: 1.0,
1217                                positions: Vec::new(),
1218                                worktree_id: worktree.read(cx).id().to_usize(),
1219                                path: relative_path,
1220                                path_prefix: RelPath::empty().into(),
1221                                is_dir: false, // File finder doesn't support directories
1222                                distance_to_relative_ancestor: usize::MAX,
1223                            }));
1224                        }
1225                    })
1226                    .log_err();
1227                if update_result.is_none() {
1228                    return abs_file_exists;
1229                }
1230            }
1231
1232            picker
1233                .update_in(cx, |picker, _, cx| {
1234                    let picker_delegate = &mut picker.delegate;
1235                    let search_id = util::post_inc(&mut picker_delegate.search_count);
1236                    picker_delegate.set_search_matches(search_id, false, query, path_matches, cx);
1237
1238                    anyhow::Ok(())
1239                })
1240                .log_err();
1241            abs_file_exists
1242        })
1243    }
1244
1245    /// Skips first history match (that is displayed topmost) if it's currently opened.
1246    fn calculate_selected_index(&self, cx: &mut Context<Picker<Self>>) -> usize {
1247        if FileFinderSettings::get_global(cx).skip_focus_for_active_in_search
1248            && let Some(Match::History { path, .. }) = self.matches.get(0)
1249            && Some(path) == self.currently_opened_path.as_ref()
1250        {
1251            let elements_after_first = self.matches.len() - 1;
1252            if elements_after_first > 0 {
1253                return 1;
1254            }
1255        }
1256
1257        0
1258    }
1259
1260    fn key_context(&self, window: &Window, cx: &App) -> KeyContext {
1261        let mut key_context = KeyContext::new_with_defaults();
1262        key_context.add("FileFinder");
1263
1264        if self.filter_popover_menu_handle.is_focused(window, cx) {
1265            key_context.add("filter_menu_open");
1266        }
1267
1268        if self.split_popover_menu_handle.is_focused(window, cx) {
1269            key_context.add("split_menu_open");
1270        }
1271        key_context
1272    }
1273}
1274
1275fn full_path_budget(
1276    file_name: &str,
1277    normal_em: Pixels,
1278    small_em: Pixels,
1279    max_width: Pixels,
1280) -> usize {
1281    (((max_width / 0.8) - file_name.len() * normal_em) / small_em) as usize
1282}
1283
1284impl PickerDelegate for FileFinderDelegate {
1285    type ListItem = ListItem;
1286
1287    fn placeholder_text(&self, _window: &mut Window, _cx: &mut App) -> Arc<str> {
1288        "Search project files...".into()
1289    }
1290
1291    fn match_count(&self) -> usize {
1292        self.matches.len()
1293    }
1294
1295    fn selected_index(&self) -> usize {
1296        self.selected_index
1297    }
1298
1299    fn set_selected_index(&mut self, ix: usize, _: &mut Window, cx: &mut Context<Picker<Self>>) {
1300        self.has_changed_selected_index = true;
1301        self.selected_index = ix;
1302        cx.notify();
1303    }
1304
1305    fn separators_after_indices(&self) -> Vec<usize> {
1306        if self.separate_history {
1307            let first_non_history_index = self
1308                .matches
1309                .matches
1310                .iter()
1311                .enumerate()
1312                .find(|(_, m)| !matches!(m, Match::History { .. }))
1313                .map(|(i, _)| i);
1314            if let Some(first_non_history_index) = first_non_history_index
1315                && first_non_history_index > 0
1316            {
1317                return vec![first_non_history_index - 1];
1318            }
1319        }
1320        Vec::new()
1321    }
1322
1323    fn update_matches(
1324        &mut self,
1325        raw_query: String,
1326        window: &mut Window,
1327        cx: &mut Context<Picker<Self>>,
1328    ) -> Task<()> {
1329        let raw_query = raw_query.replace(' ', "");
1330        let raw_query = raw_query.trim();
1331
1332        let raw_query = match &raw_query.get(0..2) {
1333            Some(".\\" | "./") => &raw_query[2..],
1334            Some(prefix @ ("a\\" | "a/" | "b\\" | "b/")) => {
1335                if self
1336                    .workspace
1337                    .upgrade()
1338                    .into_iter()
1339                    .flat_map(|workspace| workspace.read(cx).worktrees(cx))
1340                    .all(|worktree| {
1341                        worktree
1342                            .read(cx)
1343                            .entry_for_path(RelPath::unix(prefix.split_at(1).0).unwrap())
1344                            .is_none_or(|entry| !entry.is_dir())
1345                    })
1346                {
1347                    &raw_query[2..]
1348                } else {
1349                    raw_query
1350                }
1351            }
1352            _ => raw_query,
1353        };
1354
1355        if raw_query.is_empty() {
1356            // if there was no query before, and we already have some (history) matches
1357            // there's no need to update anything, since nothing has changed.
1358            // We also want to populate matches set from history entries on the first update.
1359            if self.latest_search_query.is_some() || self.first_update {
1360                let project = self.project.read(cx);
1361
1362                self.latest_search_id = post_inc(&mut self.search_count);
1363                self.latest_search_query = None;
1364                self.matches = Matches {
1365                    separate_history: self.separate_history,
1366                    ..Matches::default()
1367                };
1368                self.matches.push_new_matches(
1369                    self.history_items.iter().filter(|history_item| {
1370                        project
1371                            .worktree_for_id(history_item.project.worktree_id, cx)
1372                            .is_some()
1373                            || project.is_local()
1374                            || project.is_via_remote_server()
1375                    }),
1376                    self.currently_opened_path.as_ref(),
1377                    None,
1378                    None.into_iter(),
1379                    false,
1380                );
1381
1382                self.first_update = false;
1383                self.selected_index = 0;
1384            }
1385            cx.notify();
1386            Task::ready(())
1387        } else {
1388            let path_position = PathWithPosition::parse_str(raw_query);
1389            let raw_query = raw_query.trim().trim_end_matches(':').to_owned();
1390            let path = path_position.path.clone();
1391            let path_str = path_position.path.to_str();
1392            let path_trimmed = path_str.unwrap_or(&raw_query).trim_end_matches(':');
1393            let file_query_end = if path_trimmed == raw_query {
1394                None
1395            } else {
1396                // Safe to unwrap as we won't get here when the unwrap in if fails
1397                Some(path_str.unwrap().len())
1398            };
1399
1400            let query = FileSearchQuery {
1401                raw_query,
1402                file_query_end,
1403                path_position,
1404            };
1405
1406            cx.spawn_in(window, async move |this, cx| {
1407                let _ = maybe!(async move {
1408                    let is_absolute_path = path.is_absolute();
1409                    let did_resolve_abs_path = is_absolute_path
1410                        && this
1411                            .update_in(cx, |this, window, cx| {
1412                                this.delegate
1413                                    .lookup_absolute_path(query.clone(), window, cx)
1414                            })?
1415                            .await;
1416
1417                    // Only check for relative paths if no absolute paths were
1418                    // found.
1419                    if !did_resolve_abs_path {
1420                        this.update_in(cx, |this, window, cx| {
1421                            this.delegate.spawn_search(query, window, cx)
1422                        })?
1423                        .await;
1424                    }
1425                    anyhow::Ok(())
1426                })
1427                .await;
1428            })
1429        }
1430    }
1431
1432    fn confirm(
1433        &mut self,
1434        secondary: bool,
1435        window: &mut Window,
1436        cx: &mut Context<Picker<FileFinderDelegate>>,
1437    ) {
1438        if let Some(m) = self.matches.get(self.selected_index())
1439            && let Some(workspace) = self.workspace.upgrade()
1440        {
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 if secondary {
1511                            workspace.split_abs_path(path.absolute.clone(), false, window, cx)
1512                        } else {
1513                            workspace.open_abs_path(
1514                                path.absolute.clone(),
1515                                OpenOptions {
1516                                    visible: Some(OpenVisible::None),
1517                                    ..Default::default()
1518                                },
1519                                window,
1520                                cx,
1521                            )
1522                        }
1523                    }
1524                    Match::Search(m) => split_or_open(
1525                        workspace,
1526                        ProjectPath {
1527                            worktree_id: WorktreeId::from_usize(m.0.worktree_id),
1528                            path: m.0.path.clone(),
1529                        },
1530                        window,
1531                        cx,
1532                    ),
1533                }
1534            });
1535
1536            let row = self
1537                .latest_search_query
1538                .as_ref()
1539                .and_then(|query| query.path_position.row)
1540                .map(|row| row.saturating_sub(1));
1541            let col = self
1542                .latest_search_query
1543                .as_ref()
1544                .and_then(|query| query.path_position.column)
1545                .unwrap_or(0)
1546                .saturating_sub(1);
1547            let finder = self.file_finder.clone();
1548
1549            cx.spawn_in(window, async move |_, cx| {
1550                let item = open_task.await.notify_async_err(cx)?;
1551                if let Some(row) = row
1552                    && let Some(active_editor) = item.downcast::<Editor>()
1553                {
1554                    active_editor
1555                        .downgrade()
1556                        .update_in(cx, |editor, window, cx| {
1557                            editor.go_to_singleton_buffer_point(Point::new(row, col), window, cx);
1558                        })
1559                        .log_err();
1560                }
1561                finder.update(cx, |_, cx| cx.emit(DismissEvent)).ok()?;
1562
1563                Some(())
1564            })
1565            .detach();
1566        }
1567    }
1568
1569    fn dismissed(&mut self, _: &mut Window, cx: &mut Context<Picker<FileFinderDelegate>>) {
1570        self.file_finder
1571            .update(cx, |_, cx| cx.emit(DismissEvent))
1572            .log_err();
1573    }
1574
1575    fn render_match(
1576        &self,
1577        ix: usize,
1578        selected: bool,
1579        window: &mut Window,
1580        cx: &mut Context<Picker<Self>>,
1581    ) -> Option<Self::ListItem> {
1582        let settings = FileFinderSettings::get_global(cx);
1583
1584        let path_match = self.matches.get(ix)?;
1585
1586        let history_icon = match &path_match {
1587            Match::History { .. } => Icon::new(IconName::HistoryRerun)
1588                .color(Color::Muted)
1589                .size(IconSize::Small)
1590                .into_any_element(),
1591            Match::Search(_) => v_flex()
1592                .flex_none()
1593                .size(IconSize::Small.rems())
1594                .into_any_element(),
1595            Match::CreateNew(_) => Icon::new(IconName::Plus)
1596                .color(Color::Muted)
1597                .size(IconSize::Small)
1598                .into_any_element(),
1599        };
1600        let (file_name_label, full_path_label) = self.labels_for_match(path_match, window, cx);
1601
1602        let file_icon = maybe!({
1603            if !settings.file_icons {
1604                return None;
1605            }
1606            let abs_path = path_match.abs_path(&self.project, cx)?;
1607            let file_name = abs_path.file_name()?;
1608            let icon = FileIcons::get_icon(file_name.as_ref(), cx)?;
1609            Some(Icon::from_path(icon).color(Color::Muted))
1610        });
1611
1612        Some(
1613            ListItem::new(ix)
1614                .spacing(ListItemSpacing::Sparse)
1615                .start_slot::<Icon>(file_icon)
1616                .end_slot::<AnyElement>(history_icon)
1617                .inset(true)
1618                .toggle_state(selected)
1619                .child(
1620                    h_flex()
1621                        .gap_2()
1622                        .py_px()
1623                        .child(file_name_label)
1624                        .child(full_path_label),
1625                ),
1626        )
1627    }
1628
1629    fn render_footer(
1630        &self,
1631        window: &mut Window,
1632        cx: &mut Context<Picker<Self>>,
1633    ) -> Option<AnyElement> {
1634        let focus_handle = self.focus_handle.clone();
1635
1636        Some(
1637            h_flex()
1638                .w_full()
1639                .p_1p5()
1640                .justify_between()
1641                .border_t_1()
1642                .border_color(cx.theme().colors().border_variant)
1643                .child(
1644                    PopoverMenu::new("filter-menu-popover")
1645                        .with_handle(self.filter_popover_menu_handle.clone())
1646                        .attach(gpui::Corner::BottomRight)
1647                        .anchor(gpui::Corner::BottomLeft)
1648                        .offset(gpui::Point {
1649                            x: px(1.0),
1650                            y: px(1.0),
1651                        })
1652                        .trigger_with_tooltip(
1653                            IconButton::new("filter-trigger", IconName::Sliders)
1654                                .icon_size(IconSize::Small)
1655                                .icon_size(IconSize::Small)
1656                                .toggle_state(self.include_ignored.unwrap_or(false))
1657                                .when(self.include_ignored.is_some(), |this| {
1658                                    this.indicator(Indicator::dot().color(Color::Info))
1659                                }),
1660                            {
1661                                let focus_handle = focus_handle.clone();
1662                                move |window, cx| {
1663                                    Tooltip::for_action_in(
1664                                        "Filter Options",
1665                                        &ToggleFilterMenu,
1666                                        &focus_handle,
1667                                        window,
1668                                        cx,
1669                                    )
1670                                }
1671                            },
1672                        )
1673                        .menu({
1674                            let focus_handle = focus_handle.clone();
1675                            let include_ignored = self.include_ignored;
1676
1677                            move |window, cx| {
1678                                Some(ContextMenu::build(window, cx, {
1679                                    let focus_handle = focus_handle.clone();
1680                                    move |menu, _, _| {
1681                                        menu.context(focus_handle.clone())
1682                                            .header("Filter Options")
1683                                            .toggleable_entry(
1684                                                "Include Ignored Files",
1685                                                include_ignored.unwrap_or(false),
1686                                                ui::IconPosition::End,
1687                                                Some(ToggleIncludeIgnored.boxed_clone()),
1688                                                move |window, cx| {
1689                                                    window.focus(&focus_handle);
1690                                                    window.dispatch_action(
1691                                                        ToggleIncludeIgnored.boxed_clone(),
1692                                                        cx,
1693                                                    );
1694                                                },
1695                                            )
1696                                    }
1697                                }))
1698                            }
1699                        }),
1700                )
1701                .child(
1702                    h_flex()
1703                        .gap_0p5()
1704                        .child(
1705                            PopoverMenu::new("split-menu-popover")
1706                                .with_handle(self.split_popover_menu_handle.clone())
1707                                .attach(gpui::Corner::BottomRight)
1708                                .anchor(gpui::Corner::BottomLeft)
1709                                .offset(gpui::Point {
1710                                    x: px(1.0),
1711                                    y: px(1.0),
1712                                })
1713                                .trigger(
1714                                    ButtonLike::new("split-trigger")
1715                                        .child(Label::new("Split…"))
1716                                        .selected_style(ButtonStyle::Tinted(TintColor::Accent))
1717                                        .children(
1718                                            KeyBinding::for_action_in(
1719                                                &ToggleSplitMenu,
1720                                                &focus_handle,
1721                                                window,
1722                                                cx,
1723                                            )
1724                                            .map(|kb| kb.size(rems_from_px(12.))),
1725                                        ),
1726                                )
1727                                .menu({
1728                                    let focus_handle = focus_handle.clone();
1729
1730                                    move |window, cx| {
1731                                        Some(ContextMenu::build(window, cx, {
1732                                            let focus_handle = focus_handle.clone();
1733                                            move |menu, _, _| {
1734                                                menu.context(focus_handle)
1735                                                    .action(
1736                                                        "Split Left",
1737                                                        pane::SplitLeft.boxed_clone(),
1738                                                    )
1739                                                    .action(
1740                                                        "Split Right",
1741                                                        pane::SplitRight.boxed_clone(),
1742                                                    )
1743                                                    .action("Split Up", pane::SplitUp.boxed_clone())
1744                                                    .action(
1745                                                        "Split Down",
1746                                                        pane::SplitDown.boxed_clone(),
1747                                                    )
1748                                            }
1749                                        }))
1750                                    }
1751                                }),
1752                        )
1753                        .child(
1754                            Button::new("open-selection", "Open")
1755                                .key_binding(
1756                                    KeyBinding::for_action_in(
1757                                        &menu::Confirm,
1758                                        &focus_handle,
1759                                        window,
1760                                        cx,
1761                                    )
1762                                    .map(|kb| kb.size(rems_from_px(12.))),
1763                                )
1764                                .on_click(|_, window, cx| {
1765                                    window.dispatch_action(menu::Confirm.boxed_clone(), cx)
1766                                }),
1767                        ),
1768                )
1769                .into_any(),
1770        )
1771    }
1772}
1773
1774#[derive(Clone, Debug, PartialEq, Eq)]
1775struct PathComponentSlice<'a> {
1776    path: Cow<'a, Path>,
1777    path_str: Cow<'a, str>,
1778    component_ranges: Vec<(Component<'a>, Range<usize>)>,
1779}
1780
1781impl<'a> PathComponentSlice<'a> {
1782    fn new(path: &'a str) -> Self {
1783        let trimmed_path = Path::new(path).components().as_path().as_os_str();
1784        let mut component_ranges = Vec::new();
1785        let mut components = Path::new(trimmed_path).components();
1786        let len = trimmed_path.as_encoded_bytes().len();
1787        let mut pos = 0;
1788        while let Some(component) = components.next() {
1789            component_ranges.push((component, pos..0));
1790            pos = len - components.as_path().as_os_str().as_encoded_bytes().len();
1791        }
1792        for ((_, range), ancestor) in component_ranges
1793            .iter_mut()
1794            .rev()
1795            .zip(Path::new(trimmed_path).ancestors())
1796        {
1797            range.end = ancestor.as_os_str().as_encoded_bytes().len();
1798        }
1799        Self {
1800            path: Cow::Borrowed(Path::new(path)),
1801            path_str: Cow::Borrowed(path),
1802            component_ranges,
1803        }
1804    }
1805
1806    fn elision_range(&self, budget: usize, matches: &[usize]) -> Option<Range<usize>> {
1807        let eligible_range = {
1808            assert!(matches.windows(2).all(|w| w[0] <= w[1]));
1809            let mut matches = matches.iter().copied().peekable();
1810            let mut longest: Option<Range<usize>> = None;
1811            let mut cur = 0..0;
1812            let mut seen_normal = false;
1813            for (i, (component, range)) in self.component_ranges.iter().enumerate() {
1814                let is_normal = matches!(component, Component::Normal(_));
1815                let is_first_normal = is_normal && !seen_normal;
1816                seen_normal |= is_normal;
1817                let is_last = i == self.component_ranges.len() - 1;
1818                let contains_match = matches.peek().is_some_and(|mat| range.contains(mat));
1819                if contains_match {
1820                    matches.next();
1821                }
1822                if is_first_normal || is_last || !is_normal || contains_match {
1823                    if longest
1824                        .as_ref()
1825                        .is_none_or(|old| old.end - old.start <= cur.end - cur.start)
1826                    {
1827                        longest = Some(cur);
1828                    }
1829                    cur = i + 1..i + 1;
1830                } else {
1831                    cur.end = i + 1;
1832                }
1833            }
1834            if longest
1835                .as_ref()
1836                .is_none_or(|old| old.end - old.start <= cur.end - cur.start)
1837            {
1838                longest = Some(cur);
1839            }
1840            longest
1841        };
1842
1843        let eligible_range = eligible_range?;
1844        assert!(eligible_range.start <= eligible_range.end);
1845        if eligible_range.is_empty() {
1846            return None;
1847        }
1848
1849        let elided_range: Range<usize> = {
1850            let byte_range = self.component_ranges[eligible_range.start].1.start
1851                ..self.component_ranges[eligible_range.end - 1].1.end;
1852            let midpoint = self.path_str.len() / 2;
1853            let distance_from_start = byte_range.start.abs_diff(midpoint);
1854            let distance_from_end = byte_range.end.abs_diff(midpoint);
1855            let pick_from_end = distance_from_start > distance_from_end;
1856            let mut len_with_elision = self.path_str.len();
1857            let mut i = eligible_range.start;
1858            while i < eligible_range.end {
1859                let x = if pick_from_end {
1860                    eligible_range.end - i + eligible_range.start - 1
1861                } else {
1862                    i
1863                };
1864                len_with_elision -= self.component_ranges[x]
1865                    .0
1866                    .as_os_str()
1867                    .as_encoded_bytes()
1868                    .len()
1869                    + 1;
1870                if len_with_elision <= budget {
1871                    break;
1872                }
1873                i += 1;
1874            }
1875            if len_with_elision > budget {
1876                return None;
1877            } else if pick_from_end {
1878                let x = eligible_range.end - i + eligible_range.start - 1;
1879                x..eligible_range.end
1880            } else {
1881                let x = i;
1882                eligible_range.start..x + 1
1883            }
1884        };
1885
1886        let byte_range = self.component_ranges[elided_range.start].1.start
1887            ..self.component_ranges[elided_range.end - 1].1.end;
1888        Some(byte_range)
1889    }
1890}