file_finder.rs

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