file_finder.rs

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