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