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