file_finder.rs

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