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        // If several worktress are open we have to set the worktree root names in path prefix
 567        let several_worktrees = worktree_store.read(cx).worktrees().count() > 1;
 568        let worktree_name_by_id = several_worktrees.then(|| {
 569            worktree_store
 570                .read(cx)
 571                .worktrees()
 572                .map(|worktree| {
 573                    let snapshot = worktree.read(cx).snapshot();
 574                    (snapshot.id(), snapshot.root_name().into())
 575                })
 576                .collect()
 577        });
 578        let new_history_matches = matching_history_items(
 579            history_items,
 580            currently_opened,
 581            worktree_name_by_id,
 582            query,
 583            path_style,
 584        );
 585        let new_search_matches: Vec<Match> = new_search_matches
 586            .filter(|path_match| {
 587                !new_history_matches.contains_key(&ProjectPath {
 588                    path: path_match.0.path.clone(),
 589                    worktree_id: WorktreeId::from_usize(path_match.0.worktree_id),
 590                })
 591            })
 592            .map(Match::Search)
 593            .collect();
 594
 595        if extend_old_matches {
 596            // since we take history matches instead of new search matches
 597            // and history matches has not changed(since the query has not changed and we do not extend old matches otherwise),
 598            // old matches can't contain paths present in history_matches as well.
 599            self.matches.retain(|m| matches!(m, Match::Search(_)));
 600        } else {
 601            self.matches.clear();
 602        }
 603
 604        // At this point we have an unsorted set of new history matches, an unsorted set of new search matches
 605        // and a sorted set of old search matches.
 606        // It is possible that the new search matches' paths contain some of the old search matches' paths.
 607        // History matches' paths are unique, since store in a HashMap by path.
 608        // We build a sorted Vec<Match>, eliminating duplicate search matches.
 609        // Search matches with the same paths should have equal `ProjectPanelOrdMatch`, so we should
 610        // not have any duplicates after building the final list.
 611        for new_match in new_history_matches
 612            .into_values()
 613            .chain(new_search_matches.into_iter())
 614        {
 615            match self.position(&new_match, currently_opened) {
 616                Ok(_duplicate) => continue,
 617                Err(i) => {
 618                    self.matches.insert(i, new_match);
 619                    if self.matches.len() == 100 {
 620                        break;
 621                    }
 622                }
 623            }
 624        }
 625    }
 626
 627    /// If a < b, then a is a worse match, aligning with the `ProjectPanelOrdMatch` ordering.
 628    fn cmp_matches(
 629        separate_history: bool,
 630        currently_opened: Option<&FoundPath>,
 631        a: &Match,
 632        b: &Match,
 633    ) -> cmp::Ordering {
 634        // Handle CreateNew variant - always put it at the end
 635        match (a, b) {
 636            (Match::CreateNew(_), _) => return cmp::Ordering::Less,
 637            (_, Match::CreateNew(_)) => return cmp::Ordering::Greater,
 638            _ => {}
 639        }
 640
 641        match (&a, &b) {
 642            // bubble currently opened files to the top
 643            (Match::History { path, .. }, _) if Some(path) == currently_opened => {
 644                return cmp::Ordering::Greater;
 645            }
 646            (_, Match::History { path, .. }) if Some(path) == currently_opened => {
 647                return cmp::Ordering::Less;
 648            }
 649
 650            _ => {}
 651        }
 652
 653        if separate_history {
 654            match (a, b) {
 655                (Match::History { .. }, Match::Search(_)) => return cmp::Ordering::Greater,
 656                (Match::Search(_), Match::History { .. }) => return cmp::Ordering::Less,
 657
 658                _ => {}
 659            }
 660        }
 661
 662        // For file-vs-file matches, use the existing detailed comparison.
 663        if let (Some(a_panel), Some(b_panel)) = (a.panel_match(), b.panel_match()) {
 664            let a_in_filename = Self::is_filename_match(a_panel);
 665            let b_in_filename = Self::is_filename_match(b_panel);
 666
 667            match (a_in_filename, b_in_filename) {
 668                (true, false) => return cmp::Ordering::Greater,
 669                (false, true) => return cmp::Ordering::Less,
 670                _ => {}
 671            }
 672
 673            return a_panel.cmp(b_panel);
 674        }
 675
 676        let a_score = Self::match_score(a);
 677        let b_score = Self::match_score(b);
 678        // When at least one side is a channel, compare by raw score.
 679        a_score
 680            .partial_cmp(&b_score)
 681            .unwrap_or(cmp::Ordering::Equal)
 682    }
 683
 684    fn match_score(m: &Match) -> f64 {
 685        match m {
 686            Match::History { panel_match, .. } => panel_match.as_ref().map_or(0.0, |pm| pm.0.score),
 687            Match::Search(pm) => pm.0.score,
 688            Match::Channel { string_match, .. } => string_match.score,
 689            Match::CreateNew(_) => 0.0,
 690        }
 691    }
 692
 693    /// Determines if the match occurred within the filename rather than in the path
 694    fn is_filename_match(panel_match: &ProjectPanelOrdMatch) -> bool {
 695        if panel_match.0.positions.is_empty() {
 696            return false;
 697        }
 698
 699        if let Some(filename) = panel_match.0.path.file_name() {
 700            let path_str = panel_match.0.path.as_unix_str();
 701
 702            if let Some(filename_pos) = path_str.rfind(filename)
 703                && panel_match.0.positions[0] >= filename_pos
 704            {
 705                let mut prev_position = panel_match.0.positions[0];
 706                for p in &panel_match.0.positions[1..] {
 707                    if *p != prev_position + 1 {
 708                        return false;
 709                    }
 710                    prev_position = *p;
 711                }
 712                return true;
 713            }
 714        }
 715
 716        false
 717    }
 718}
 719
 720fn matching_history_items<'a>(
 721    history_items: impl IntoIterator<Item = &'a FoundPath>,
 722    currently_opened: Option<&'a FoundPath>,
 723    worktree_name_by_id: Option<HashMap<WorktreeId, Arc<RelPath>>>,
 724    query: &FileSearchQuery,
 725    path_style: PathStyle,
 726) -> HashMap<ProjectPath, Match> {
 727    let mut candidates_paths = HashMap::default();
 728
 729    let history_items_by_worktrees = history_items
 730        .into_iter()
 731        .chain(currently_opened)
 732        .filter_map(|found_path| {
 733            let candidate = PathMatchCandidate {
 734                is_dir: false, // You can't open directories as project items
 735                path: &found_path.project.path,
 736                // Only match history items names, otherwise their paths may match too many queries, producing false positives.
 737                // E.g. `foo` would match both `something/foo/bar.rs` and `something/foo/foo.rs` and if the former is a history item,
 738                // it would be shown first always, despite the latter being a better match.
 739                char_bag: CharBag::from_iter(
 740                    found_path
 741                        .project
 742                        .path
 743                        .file_name()?
 744                        .to_string()
 745                        .to_lowercase()
 746                        .chars(),
 747                ),
 748            };
 749            candidates_paths.insert(&found_path.project, found_path);
 750            Some((found_path.project.worktree_id, candidate))
 751        })
 752        .fold(
 753            HashMap::default(),
 754            |mut candidates, (worktree_id, new_candidate)| {
 755                candidates
 756                    .entry(worktree_id)
 757                    .or_insert_with(Vec::new)
 758                    .push(new_candidate);
 759                candidates
 760            },
 761        );
 762    let mut matching_history_paths = HashMap::default();
 763    for (worktree, candidates) in history_items_by_worktrees {
 764        let max_results = candidates.len() + 1;
 765        let worktree_root_name = worktree_name_by_id
 766            .as_ref()
 767            .and_then(|w| w.get(&worktree).cloned());
 768        matching_history_paths.extend(
 769            fuzzy::match_fixed_path_set(
 770                candidates,
 771                worktree.to_usize(),
 772                worktree_root_name,
 773                query.path_query(),
 774                false,
 775                max_results,
 776                path_style,
 777            )
 778            .into_iter()
 779            .filter_map(|path_match| {
 780                candidates_paths
 781                    .remove_entry(&ProjectPath {
 782                        worktree_id: WorktreeId::from_usize(path_match.worktree_id),
 783                        path: Arc::clone(&path_match.path),
 784                    })
 785                    .map(|(project_path, found_path)| {
 786                        (
 787                            project_path.clone(),
 788                            Match::History {
 789                                path: found_path.clone(),
 790                                panel_match: Some(ProjectPanelOrdMatch(path_match)),
 791                            },
 792                        )
 793                    })
 794            }),
 795        );
 796    }
 797    matching_history_paths
 798}
 799
 800#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
 801struct FoundPath {
 802    project: ProjectPath,
 803    absolute: PathBuf,
 804}
 805
 806impl FoundPath {
 807    fn new(project: ProjectPath, absolute: PathBuf) -> Self {
 808        Self { project, absolute }
 809    }
 810}
 811
 812const MAX_RECENT_SELECTIONS: usize = 20;
 813
 814pub enum Event {
 815    Selected(ProjectPath),
 816    Dismissed,
 817}
 818
 819#[derive(Debug, Clone)]
 820struct FileSearchQuery {
 821    raw_query: String,
 822    file_query_end: Option<usize>,
 823    path_position: PathWithPosition,
 824}
 825
 826impl FileSearchQuery {
 827    fn path_query(&self) -> &str {
 828        match self.file_query_end {
 829            Some(file_path_end) => &self.raw_query[..file_path_end],
 830            None => &self.raw_query,
 831        }
 832    }
 833}
 834
 835impl FileFinderDelegate {
 836    fn new(
 837        file_finder: WeakEntity<FileFinder>,
 838        workspace: WeakEntity<Workspace>,
 839        project: Entity<Project>,
 840        currently_opened_path: Option<FoundPath>,
 841        history_items: Vec<FoundPath>,
 842        separate_history: bool,
 843        window: &mut Window,
 844        cx: &mut Context<FileFinder>,
 845    ) -> Self {
 846        Self::subscribe_to_updates(&project, window, cx);
 847        let channel_store = ChannelStore::try_global(cx);
 848        Self {
 849            file_finder,
 850            workspace,
 851            project,
 852            channel_store,
 853            search_count: 0,
 854            latest_search_id: 0,
 855            latest_search_did_cancel: false,
 856            latest_search_query: None,
 857            currently_opened_path,
 858            matches: Matches::default(),
 859            has_changed_selected_index: false,
 860            selected_index: 0,
 861            cancel_flag: Arc::new(AtomicBool::new(false)),
 862            history_items,
 863            separate_history,
 864            first_update: true,
 865            filter_popover_menu_handle: PopoverMenuHandle::default(),
 866            split_popover_menu_handle: PopoverMenuHandle::default(),
 867            focus_handle: cx.focus_handle(),
 868            include_ignored: FileFinderSettings::get_global(cx).include_ignored,
 869            include_ignored_refresh: Task::ready(()),
 870        }
 871    }
 872
 873    fn subscribe_to_updates(
 874        project: &Entity<Project>,
 875        window: &mut Window,
 876        cx: &mut Context<FileFinder>,
 877    ) {
 878        cx.subscribe_in(project, window, |file_finder, _, event, window, cx| {
 879            match event {
 880                project::Event::WorktreeUpdatedEntries(_, _)
 881                | project::Event::WorktreeAdded(_)
 882                | project::Event::WorktreeRemoved(_) => file_finder
 883                    .picker
 884                    .update(cx, |picker, cx| picker.refresh(window, cx)),
 885                _ => {}
 886            };
 887        })
 888        .detach();
 889    }
 890
 891    fn spawn_search(
 892        &mut self,
 893        query: FileSearchQuery,
 894        window: &mut Window,
 895        cx: &mut Context<Picker<Self>>,
 896    ) -> Task<()> {
 897        let relative_to = self
 898            .currently_opened_path
 899            .as_ref()
 900            .map(|found_path| Arc::clone(&found_path.project.path));
 901        let worktrees = self
 902            .project
 903            .read(cx)
 904            .worktree_store()
 905            .read(cx)
 906            .visible_worktrees_and_single_files(cx)
 907            .collect::<Vec<_>>();
 908        let include_root_name = worktrees.len() > 1;
 909        let candidate_sets = worktrees
 910            .into_iter()
 911            .map(|worktree| {
 912                let worktree = worktree.read(cx);
 913                PathMatchCandidateSet {
 914                    snapshot: worktree.snapshot(),
 915                    include_ignored: self.include_ignored.unwrap_or_else(|| {
 916                        worktree.root_entry().is_some_and(|entry| entry.is_ignored)
 917                    }),
 918                    include_root_name,
 919                    candidates: project::Candidates::Files,
 920                }
 921            })
 922            .collect::<Vec<_>>();
 923
 924        let search_id = util::post_inc(&mut self.search_count);
 925        self.cancel_flag.store(true, atomic::Ordering::Release);
 926        self.cancel_flag = Arc::new(AtomicBool::new(false));
 927        let cancel_flag = self.cancel_flag.clone();
 928        cx.spawn_in(window, async move |picker, cx| {
 929            let matches = fuzzy::match_path_sets(
 930                candidate_sets.as_slice(),
 931                query.path_query(),
 932                &relative_to,
 933                false,
 934                100,
 935                &cancel_flag,
 936                cx.background_executor().clone(),
 937            )
 938            .await
 939            .into_iter()
 940            .map(ProjectPanelOrdMatch);
 941            let did_cancel = cancel_flag.load(atomic::Ordering::Acquire);
 942            picker
 943                .update(cx, |picker, cx| {
 944                    picker
 945                        .delegate
 946                        .set_search_matches(search_id, did_cancel, query, matches, cx)
 947                })
 948                .log_err();
 949        })
 950    }
 951
 952    fn set_search_matches(
 953        &mut self,
 954        search_id: usize,
 955        did_cancel: bool,
 956        query: FileSearchQuery,
 957        matches: impl IntoIterator<Item = ProjectPanelOrdMatch>,
 958        cx: &mut Context<Picker<Self>>,
 959    ) {
 960        if search_id >= self.latest_search_id {
 961            self.latest_search_id = search_id;
 962            let query_changed = Some(query.path_query())
 963                != self
 964                    .latest_search_query
 965                    .as_ref()
 966                    .map(|query| query.path_query());
 967            let extend_old_matches = self.latest_search_did_cancel && !query_changed;
 968
 969            let selected_match = if query_changed {
 970                None
 971            } else {
 972                self.matches.get(self.selected_index).cloned()
 973            };
 974
 975            let path_style = self.project.read(cx).path_style(cx);
 976            self.matches.push_new_matches(
 977                self.project.read(cx).worktree_store(),
 978                cx,
 979                &self.history_items,
 980                self.currently_opened_path.as_ref(),
 981                Some(&query),
 982                matches.into_iter(),
 983                extend_old_matches,
 984                path_style,
 985            );
 986
 987            // Add channel matches
 988            if let Some(channel_store) = &self.channel_store {
 989                let channel_store = channel_store.read(cx);
 990                let channels: Vec<_> = channel_store.channels().cloned().collect();
 991                if !channels.is_empty() {
 992                    let candidates = channels
 993                        .iter()
 994                        .enumerate()
 995                        .map(|(id, channel)| StringMatchCandidate::new(id, &channel.name));
 996                    let channel_query = query.path_query();
 997                    let query_lower = channel_query.to_lowercase();
 998                    let mut channel_matches = Vec::new();
 999                    for candidate in candidates {
1000                        let channel_name = candidate.string;
1001                        let name_lower = channel_name.to_lowercase();
1002
1003                        let mut positions = Vec::new();
1004                        let mut query_idx = 0;
1005                        for (name_idx, name_char) in name_lower.char_indices() {
1006                            if query_idx < query_lower.len() {
1007                                let query_char =
1008                                    query_lower[query_idx..].chars().next().unwrap_or_default();
1009                                if name_char == query_char {
1010                                    positions.push(name_idx);
1011                                    query_idx += query_char.len_utf8();
1012                                }
1013                            }
1014                        }
1015
1016                        if query_idx == query_lower.len() {
1017                            let channel = &channels[candidate.id];
1018                            let score = if name_lower == query_lower {
1019                                1.0
1020                            } else if name_lower.starts_with(&query_lower) {
1021                                0.8
1022                            } else {
1023                                0.5 * (query_lower.len() as f64 / name_lower.len() as f64)
1024                            };
1025                            channel_matches.push(Match::Channel {
1026                                channel_id: channel.id,
1027                                channel_name: channel.name.clone(),
1028                                string_match: StringMatch {
1029                                    candidate_id: candidate.id,
1030                                    score,
1031                                    positions,
1032                                    string: channel_name,
1033                                },
1034                            });
1035                        }
1036                    }
1037                    for channel_match in channel_matches {
1038                        match self
1039                            .matches
1040                            .position(&channel_match, self.currently_opened_path.as_ref())
1041                        {
1042                            Ok(_duplicate) => {}
1043                            Err(ix) => self.matches.matches.insert(ix, channel_match),
1044                        }
1045                    }
1046                }
1047            }
1048
1049            let query_path = query.raw_query.as_str();
1050            if let Ok(mut query_path) = RelPath::new(Path::new(query_path), path_style) {
1051                let available_worktree = self
1052                    .project
1053                    .read(cx)
1054                    .visible_worktrees(cx)
1055                    .filter(|worktree| !worktree.read(cx).is_single_file())
1056                    .collect::<Vec<_>>();
1057                let worktree_count = available_worktree.len();
1058                let mut expect_worktree = available_worktree.first().cloned();
1059                for worktree in &available_worktree {
1060                    let worktree_root = worktree.read(cx).root_name();
1061                    if worktree_count > 1 {
1062                        if let Ok(suffix) = query_path.strip_prefix(worktree_root) {
1063                            query_path = Cow::Owned(suffix.to_owned());
1064                            expect_worktree = Some(worktree.clone());
1065                            break;
1066                        }
1067                    }
1068                }
1069
1070                if let Some(FoundPath { ref project, .. }) = self.currently_opened_path {
1071                    let worktree_id = project.worktree_id;
1072                    let focused_file_in_available_worktree = available_worktree
1073                        .iter()
1074                        .any(|wt| wt.read(cx).id() == worktree_id);
1075
1076                    if focused_file_in_available_worktree {
1077                        expect_worktree = self.project.read(cx).worktree_for_id(worktree_id, cx);
1078                    }
1079                }
1080
1081                if let Some(worktree) = expect_worktree {
1082                    let worktree = worktree.read(cx);
1083                    if worktree.entry_for_path(&query_path).is_none()
1084                        && !query.raw_query.ends_with("/")
1085                        && !(path_style.is_windows() && query.raw_query.ends_with("\\"))
1086                    {
1087                        self.matches.matches.push(Match::CreateNew(ProjectPath {
1088                            worktree_id: worktree.id(),
1089                            path: query_path.into_arc(),
1090                        }));
1091                    }
1092                }
1093            }
1094
1095            self.selected_index = selected_match.map_or_else(
1096                || self.calculate_selected_index(cx),
1097                |m| {
1098                    self.matches
1099                        .position(&m, self.currently_opened_path.as_ref())
1100                        .unwrap_or(0)
1101                },
1102            );
1103
1104            self.latest_search_query = Some(query);
1105            self.latest_search_did_cancel = did_cancel;
1106
1107            cx.notify();
1108        }
1109    }
1110
1111    fn labels_for_match(
1112        &self,
1113        path_match: &Match,
1114        window: &mut Window,
1115        cx: &App,
1116    ) -> (HighlightedLabel, HighlightedLabel) {
1117        let path_style = self.project.read(cx).path_style(cx);
1118        let (file_name, file_name_positions, mut full_path, mut full_path_positions) =
1119            match &path_match {
1120                Match::History {
1121                    path: entry_path,
1122                    panel_match,
1123                } => {
1124                    let worktree_id = entry_path.project.worktree_id;
1125                    let worktree = self
1126                        .project
1127                        .read(cx)
1128                        .worktree_for_id(worktree_id, cx)
1129                        .filter(|worktree| worktree.read(cx).is_visible());
1130
1131                    if let Some(panel_match) = panel_match {
1132                        self.labels_for_path_match(&panel_match.0, path_style)
1133                    } else if let Some(worktree) = worktree {
1134                        let multiple_folders_open = self
1135                            .project
1136                            .read(cx)
1137                            .visible_worktrees(cx)
1138                            .filter(|worktree| !worktree.read(cx).is_single_file())
1139                            .nth(1)
1140                            .is_some();
1141
1142                        let full_path = if ProjectPanelSettings::get_global(cx).hide_root
1143                            && !multiple_folders_open
1144                        {
1145                            entry_path.project.path.clone()
1146                        } else {
1147                            worktree.read(cx).root_name().join(&entry_path.project.path)
1148                        };
1149                        let mut components = full_path.components();
1150                        let filename = components.next_back().unwrap_or("");
1151                        let prefix = components.rest();
1152                        (
1153                            filename.to_string(),
1154                            Vec::new(),
1155                            prefix.display(path_style).to_string() + path_style.primary_separator(),
1156                            Vec::new(),
1157                        )
1158                    } else {
1159                        (
1160                            entry_path
1161                                .absolute
1162                                .file_name()
1163                                .map_or(String::new(), |f| f.to_string_lossy().into_owned()),
1164                            Vec::new(),
1165                            entry_path.absolute.parent().map_or(String::new(), |path| {
1166                                path.to_string_lossy().into_owned() + path_style.primary_separator()
1167                            }),
1168                            Vec::new(),
1169                        )
1170                    }
1171                }
1172                Match::Search(path_match) => self.labels_for_path_match(&path_match.0, path_style),
1173                Match::Channel {
1174                    channel_name,
1175                    string_match,
1176                    ..
1177                } => (
1178                    channel_name.to_string(),
1179                    string_match.positions.clone(),
1180                    "Channel Notes".to_string(),
1181                    vec![],
1182                ),
1183                Match::CreateNew(project_path) => (
1184                    format!("Create file: {}", project_path.path.display(path_style)),
1185                    vec![],
1186                    String::from(""),
1187                    vec![],
1188                ),
1189            };
1190
1191        if file_name_positions.is_empty() {
1192            let user_home_path = util::paths::home_dir().to_string_lossy();
1193            if !user_home_path.is_empty() && full_path.starts_with(&*user_home_path) {
1194                full_path.replace_range(0..user_home_path.len(), "~");
1195                full_path_positions.retain_mut(|pos| {
1196                    if *pos >= user_home_path.len() {
1197                        *pos -= user_home_path.len();
1198                        *pos += 1;
1199                        true
1200                    } else {
1201                        false
1202                    }
1203                })
1204            }
1205        }
1206
1207        if full_path.is_ascii() {
1208            let file_finder_settings = FileFinderSettings::get_global(cx);
1209            let max_width =
1210                FileFinder::modal_max_width(file_finder_settings.modal_max_width, window);
1211            let (normal_em, small_em) = {
1212                let style = window.text_style();
1213                let font_id = window.text_system().resolve_font(&style.font());
1214                let font_size = TextSize::Default.rems(cx).to_pixels(window.rem_size());
1215                let normal = cx
1216                    .text_system()
1217                    .em_width(font_id, font_size)
1218                    .unwrap_or(px(16.));
1219                let font_size = TextSize::Small.rems(cx).to_pixels(window.rem_size());
1220                let small = cx
1221                    .text_system()
1222                    .em_width(font_id, font_size)
1223                    .unwrap_or(px(10.));
1224                (normal, small)
1225            };
1226            let budget = full_path_budget(&file_name, normal_em, small_em, max_width);
1227            // If the computed budget is zero, we certainly won't be able to achieve it,
1228            // so no point trying to elide the path.
1229            if budget > 0 && full_path.len() > budget {
1230                let components = PathComponentSlice::new(&full_path);
1231                if let Some(elided_range) =
1232                    components.elision_range(budget - 1, &full_path_positions)
1233                {
1234                    let elided_len = elided_range.end - elided_range.start;
1235                    let placeholder = "";
1236                    full_path_positions.retain_mut(|mat| {
1237                        if *mat >= elided_range.end {
1238                            *mat -= elided_len;
1239                            *mat += placeholder.len();
1240                        } else if *mat >= elided_range.start {
1241                            return false;
1242                        }
1243                        true
1244                    });
1245                    full_path.replace_range(elided_range, placeholder);
1246                }
1247            }
1248        }
1249
1250        (
1251            HighlightedLabel::new(file_name, file_name_positions),
1252            HighlightedLabel::new(full_path, full_path_positions)
1253                .size(LabelSize::Small)
1254                .color(Color::Muted),
1255        )
1256    }
1257
1258    fn labels_for_path_match(
1259        &self,
1260        path_match: &PathMatch,
1261        path_style: PathStyle,
1262    ) -> (String, Vec<usize>, String, Vec<usize>) {
1263        let full_path = path_match.path_prefix.join(&path_match.path);
1264        let mut path_positions = path_match.positions.clone();
1265
1266        let file_name = full_path.file_name().unwrap_or("");
1267        let file_name_start = full_path.as_unix_str().len() - file_name.len();
1268        let file_name_positions = path_positions
1269            .iter()
1270            .filter_map(|pos| {
1271                if pos >= &file_name_start {
1272                    Some(pos - file_name_start)
1273                } else {
1274                    None
1275                }
1276            })
1277            .collect::<Vec<_>>();
1278
1279        let full_path = full_path
1280            .display(path_style)
1281            .trim_end_matches(&file_name)
1282            .to_string();
1283        path_positions.retain(|idx| *idx < full_path.len());
1284
1285        debug_assert!(
1286            file_name_positions
1287                .iter()
1288                .all(|ix| file_name[*ix..].chars().next().is_some()),
1289            "invalid file name positions {file_name:?} {file_name_positions:?}"
1290        );
1291        debug_assert!(
1292            path_positions
1293                .iter()
1294                .all(|ix| full_path[*ix..].chars().next().is_some()),
1295            "invalid path positions {full_path:?} {path_positions:?}"
1296        );
1297
1298        (
1299            file_name.to_string(),
1300            file_name_positions,
1301            full_path,
1302            path_positions,
1303        )
1304    }
1305
1306    /// Attempts to resolve an absolute file path and update the search matches if found.
1307    ///
1308    /// If the query path resolves to an absolute file that exists in the project,
1309    /// this method will find the corresponding worktree and relative path, create a
1310    /// match for it, and update the picker's search results.
1311    ///
1312    /// Returns `true` if the absolute path exists, otherwise returns `false`.
1313    fn lookup_absolute_path(
1314        &self,
1315        query: FileSearchQuery,
1316        window: &mut Window,
1317        cx: &mut Context<Picker<Self>>,
1318    ) -> Task<bool> {
1319        cx.spawn_in(window, async move |picker, cx| {
1320            let Some(project) = picker
1321                .read_with(cx, |picker, _| picker.delegate.project.clone())
1322                .log_err()
1323            else {
1324                return false;
1325            };
1326
1327            let query_path = Path::new(query.path_query());
1328            let mut path_matches = Vec::new();
1329
1330            let abs_file_exists = project
1331                .update(cx, |this, cx| {
1332                    this.resolve_abs_file_path(query.path_query(), cx)
1333                })
1334                .await
1335                .is_some();
1336
1337            if abs_file_exists {
1338                project.update(cx, |project, cx| {
1339                    if let Some((worktree, relative_path)) = project.find_worktree(query_path, cx) {
1340                        path_matches.push(ProjectPanelOrdMatch(PathMatch {
1341                            score: 1.0,
1342                            positions: Vec::new(),
1343                            worktree_id: worktree.read(cx).id().to_usize(),
1344                            path: relative_path,
1345                            path_prefix: RelPath::empty().into(),
1346                            is_dir: false, // File finder doesn't support directories
1347                            distance_to_relative_ancestor: usize::MAX,
1348                        }));
1349                    }
1350                });
1351            }
1352
1353            picker
1354                .update_in(cx, |picker, _, cx| {
1355                    let picker_delegate = &mut picker.delegate;
1356                    let search_id = util::post_inc(&mut picker_delegate.search_count);
1357                    picker_delegate.set_search_matches(search_id, false, query, path_matches, cx);
1358
1359                    anyhow::Ok(())
1360                })
1361                .log_err();
1362            abs_file_exists
1363        })
1364    }
1365
1366    /// Skips first history match (that is displayed topmost) if it's currently opened.
1367    fn calculate_selected_index(&self, cx: &mut Context<Picker<Self>>) -> usize {
1368        if FileFinderSettings::get_global(cx).skip_focus_for_active_in_search
1369            && let Some(Match::History { path, .. }) = self.matches.get(0)
1370            && Some(path) == self.currently_opened_path.as_ref()
1371        {
1372            let elements_after_first = self.matches.len() - 1;
1373            if elements_after_first > 0 {
1374                return 1;
1375            }
1376        }
1377
1378        0
1379    }
1380
1381    fn key_context(&self, window: &Window, cx: &App) -> KeyContext {
1382        let mut key_context = KeyContext::new_with_defaults();
1383        key_context.add("FileFinder");
1384
1385        if self.filter_popover_menu_handle.is_focused(window, cx) {
1386            key_context.add("filter_menu_open");
1387        }
1388
1389        if self.split_popover_menu_handle.is_focused(window, cx) {
1390            key_context.add("split_menu_open");
1391        }
1392        key_context
1393    }
1394}
1395
1396fn full_path_budget(
1397    file_name: &str,
1398    normal_em: Pixels,
1399    small_em: Pixels,
1400    max_width: Pixels,
1401) -> usize {
1402    (((max_width / 0.8) - file_name.len() * normal_em) / small_em) as usize
1403}
1404
1405impl PickerDelegate for FileFinderDelegate {
1406    type ListItem = ListItem;
1407
1408    fn placeholder_text(&self, _window: &mut Window, _cx: &mut App) -> Arc<str> {
1409        "Search project files...".into()
1410    }
1411
1412    fn match_count(&self) -> usize {
1413        self.matches.len()
1414    }
1415
1416    fn selected_index(&self) -> usize {
1417        self.selected_index
1418    }
1419
1420    fn set_selected_index(&mut self, ix: usize, _: &mut Window, cx: &mut Context<Picker<Self>>) {
1421        self.has_changed_selected_index = true;
1422        self.selected_index = ix;
1423        cx.notify();
1424    }
1425
1426    fn separators_after_indices(&self) -> Vec<usize> {
1427        if self.separate_history {
1428            let first_non_history_index = self
1429                .matches
1430                .matches
1431                .iter()
1432                .enumerate()
1433                .find(|(_, m)| !matches!(m, Match::History { .. }))
1434                .map(|(i, _)| i);
1435            if let Some(first_non_history_index) = first_non_history_index
1436                && first_non_history_index > 0
1437            {
1438                return vec![first_non_history_index - 1];
1439            }
1440        }
1441        Vec::new()
1442    }
1443
1444    fn update_matches(
1445        &mut self,
1446        raw_query: String,
1447        window: &mut Window,
1448        cx: &mut Context<Picker<Self>>,
1449    ) -> Task<()> {
1450        let raw_query = raw_query.replace(' ', "");
1451        let raw_query = raw_query.trim();
1452
1453        let raw_query = match &raw_query.get(0..2) {
1454            Some(".\\" | "./") => &raw_query[2..],
1455            Some(prefix @ ("a\\" | "a/" | "b\\" | "b/")) => {
1456                if self
1457                    .workspace
1458                    .upgrade()
1459                    .into_iter()
1460                    .flat_map(|workspace| workspace.read(cx).worktrees(cx))
1461                    .all(|worktree| {
1462                        worktree
1463                            .read(cx)
1464                            .entry_for_path(RelPath::unix(prefix.split_at(1).0).unwrap())
1465                            .is_none_or(|entry| !entry.is_dir())
1466                    })
1467                {
1468                    &raw_query[2..]
1469                } else {
1470                    raw_query
1471                }
1472            }
1473            _ => raw_query,
1474        };
1475
1476        if raw_query.is_empty() {
1477            // if there was no query before, and we already have some (history) matches
1478            // there's no need to update anything, since nothing has changed.
1479            // We also want to populate matches set from history entries on the first update.
1480            if self.latest_search_query.is_some() || self.first_update {
1481                let project = self.project.read(cx);
1482
1483                self.latest_search_id = post_inc(&mut self.search_count);
1484                self.latest_search_query = None;
1485                self.matches = Matches {
1486                    separate_history: self.separate_history,
1487                    ..Matches::default()
1488                };
1489                let path_style = self.project.read(cx).path_style(cx);
1490
1491                self.matches.push_new_matches(
1492                    project.worktree_store(),
1493                    cx,
1494                    self.history_items.iter().filter(|history_item| {
1495                        project
1496                            .worktree_for_id(history_item.project.worktree_id, cx)
1497                            .is_some()
1498                            || project.is_local()
1499                            || project.is_via_remote_server()
1500                    }),
1501                    self.currently_opened_path.as_ref(),
1502                    None,
1503                    None.into_iter(),
1504                    false,
1505                    path_style,
1506                );
1507
1508                self.first_update = false;
1509                self.selected_index = 0;
1510            }
1511            cx.notify();
1512            Task::ready(())
1513        } else {
1514            let path_position = PathWithPosition::parse_str(raw_query);
1515            let raw_query = raw_query.trim().trim_end_matches(':').to_owned();
1516            let path = path_position.path.clone();
1517            let path_str = path_position.path.to_str();
1518            let path_trimmed = path_str.unwrap_or(&raw_query).trim_end_matches(':');
1519            let file_query_end = if path_trimmed == raw_query {
1520                None
1521            } else {
1522                // Safe to unwrap as we won't get here when the unwrap in if fails
1523                Some(path_str.unwrap().len())
1524            };
1525
1526            let query = FileSearchQuery {
1527                raw_query,
1528                file_query_end,
1529                path_position,
1530            };
1531
1532            cx.spawn_in(window, async move |this, cx| {
1533                let _ = maybe!(async move {
1534                    let is_absolute_path = path.is_absolute();
1535                    let did_resolve_abs_path = is_absolute_path
1536                        && this
1537                            .update_in(cx, |this, window, cx| {
1538                                this.delegate
1539                                    .lookup_absolute_path(query.clone(), window, cx)
1540                            })?
1541                            .await;
1542
1543                    // Only check for relative paths if no absolute paths were
1544                    // found.
1545                    if !did_resolve_abs_path {
1546                        this.update_in(cx, |this, window, cx| {
1547                            this.delegate.spawn_search(query, window, cx)
1548                        })?
1549                        .await;
1550                    }
1551                    anyhow::Ok(())
1552                })
1553                .await;
1554            })
1555        }
1556    }
1557
1558    fn confirm(
1559        &mut self,
1560        secondary: bool,
1561        window: &mut Window,
1562        cx: &mut Context<Picker<FileFinderDelegate>>,
1563    ) {
1564        if let Some(m) = self.matches.get(self.selected_index())
1565            && let Some(workspace) = self.workspace.upgrade()
1566        {
1567            // Channel matches are handled separately since they dispatch an action
1568            // rather than directly opening a file path.
1569            if let Match::Channel { channel_id, .. } = m {
1570                let channel_id = channel_id.0;
1571                let finder = self.file_finder.clone();
1572                window.dispatch_action(OpenChannelNotesById { channel_id }.boxed_clone(), cx);
1573                finder.update(cx, |_, cx| cx.emit(DismissEvent)).log_err();
1574                return;
1575            }
1576
1577            let open_task = workspace.update(cx, |workspace, cx| {
1578                let split_or_open =
1579                    |workspace: &mut Workspace,
1580                     project_path,
1581                     window: &mut Window,
1582                     cx: &mut Context<Workspace>| {
1583                        let allow_preview =
1584                            PreviewTabsSettings::get_global(cx).enable_preview_from_file_finder;
1585                        if secondary {
1586                            workspace.split_path_preview(
1587                                project_path,
1588                                allow_preview,
1589                                None,
1590                                window,
1591                                cx,
1592                            )
1593                        } else {
1594                            workspace.open_path_preview(
1595                                project_path,
1596                                None,
1597                                true,
1598                                allow_preview,
1599                                true,
1600                                window,
1601                                cx,
1602                            )
1603                        }
1604                    };
1605                match &m {
1606                    Match::CreateNew(project_path) => {
1607                        // Create a new file with the given filename
1608                        if secondary {
1609                            workspace.split_path_preview(
1610                                project_path.clone(),
1611                                false,
1612                                None,
1613                                window,
1614                                cx,
1615                            )
1616                        } else {
1617                            workspace.open_path_preview(
1618                                project_path.clone(),
1619                                None,
1620                                true,
1621                                false,
1622                                true,
1623                                window,
1624                                cx,
1625                            )
1626                        }
1627                    }
1628
1629                    Match::History { path, .. } => {
1630                        let worktree_id = path.project.worktree_id;
1631                        if workspace
1632                            .project()
1633                            .read(cx)
1634                            .worktree_for_id(worktree_id, cx)
1635                            .is_some()
1636                        {
1637                            split_or_open(
1638                                workspace,
1639                                ProjectPath {
1640                                    worktree_id,
1641                                    path: Arc::clone(&path.project.path),
1642                                },
1643                                window,
1644                                cx,
1645                            )
1646                        } else if secondary {
1647                            workspace.split_abs_path(path.absolute.clone(), false, window, cx)
1648                        } else {
1649                            workspace.open_abs_path(
1650                                path.absolute.clone(),
1651                                OpenOptions {
1652                                    visible: Some(OpenVisible::None),
1653                                    ..Default::default()
1654                                },
1655                                window,
1656                                cx,
1657                            )
1658                        }
1659                    }
1660                    Match::Search(m) => split_or_open(
1661                        workspace,
1662                        ProjectPath {
1663                            worktree_id: WorktreeId::from_usize(m.0.worktree_id),
1664                            path: m.0.path.clone(),
1665                        },
1666                        window,
1667                        cx,
1668                    ),
1669                    Match::Channel { .. } => unreachable!("handled above"),
1670                }
1671            });
1672
1673            let row = self
1674                .latest_search_query
1675                .as_ref()
1676                .and_then(|query| query.path_position.row)
1677                .map(|row| row.saturating_sub(1));
1678            let col = self
1679                .latest_search_query
1680                .as_ref()
1681                .and_then(|query| query.path_position.column)
1682                .unwrap_or(0)
1683                .saturating_sub(1);
1684            let finder = self.file_finder.clone();
1685            let workspace = self.workspace.clone();
1686
1687            cx.spawn_in(window, async move |_, mut cx| {
1688                let item = open_task
1689                    .await
1690                    .notify_workspace_async_err(workspace, &mut cx)?;
1691                if let Some(row) = row
1692                    && let Some(active_editor) = item.downcast::<Editor>()
1693                {
1694                    active_editor
1695                        .downgrade()
1696                        .update_in(cx, |editor, window, cx| {
1697                            editor.go_to_singleton_buffer_point(Point::new(row, col), window, cx);
1698                        })
1699                        .log_err();
1700                }
1701                finder.update(cx, |_, cx| cx.emit(DismissEvent)).ok()?;
1702
1703                Some(())
1704            })
1705            .detach();
1706        }
1707    }
1708
1709    fn dismissed(&mut self, _: &mut Window, cx: &mut Context<Picker<FileFinderDelegate>>) {
1710        self.file_finder
1711            .update(cx, |_, cx| cx.emit(DismissEvent))
1712            .log_err();
1713    }
1714
1715    fn render_match(
1716        &self,
1717        ix: usize,
1718        selected: bool,
1719        window: &mut Window,
1720        cx: &mut Context<Picker<Self>>,
1721    ) -> Option<Self::ListItem> {
1722        let settings = FileFinderSettings::get_global(cx);
1723
1724        let path_match = self.matches.get(ix)?;
1725
1726        let end_icon = match path_match {
1727            Match::History { .. } => Icon::new(IconName::HistoryRerun)
1728                .color(Color::Muted)
1729                .size(IconSize::Small)
1730                .into_any_element(),
1731            Match::Search(_) => v_flex()
1732                .flex_none()
1733                .size(IconSize::Small.rems())
1734                .into_any_element(),
1735            Match::Channel { .. } => v_flex()
1736                .flex_none()
1737                .size(IconSize::Small.rems())
1738                .into_any_element(),
1739            Match::CreateNew(_) => Icon::new(IconName::Plus)
1740                .color(Color::Muted)
1741                .size(IconSize::Small)
1742                .into_any_element(),
1743        };
1744        let (file_name_label, full_path_label) = self.labels_for_match(path_match, window, cx);
1745
1746        let file_icon = match path_match {
1747            Match::Channel { .. } => Some(Icon::new(IconName::Hash).color(Color::Muted)),
1748            _ => maybe!({
1749                if !settings.file_icons {
1750                    return None;
1751                }
1752                let abs_path = path_match.abs_path(&self.project, cx)?;
1753                let file_name = abs_path.file_name()?;
1754                let icon = FileIcons::get_icon(file_name.as_ref(), cx)?;
1755                Some(Icon::from_path(icon).color(Color::Muted))
1756            }),
1757        };
1758
1759        Some(
1760            ListItem::new(ix)
1761                .spacing(ListItemSpacing::Sparse)
1762                .start_slot::<Icon>(file_icon)
1763                .end_slot::<AnyElement>(end_icon)
1764                .inset(true)
1765                .toggle_state(selected)
1766                .child(
1767                    h_flex()
1768                        .gap_2()
1769                        .py_px()
1770                        .child(file_name_label)
1771                        .child(full_path_label),
1772                ),
1773        )
1774    }
1775
1776    fn render_footer(&self, _: &mut Window, cx: &mut Context<Picker<Self>>) -> Option<AnyElement> {
1777        let focus_handle = self.focus_handle.clone();
1778
1779        Some(
1780            h_flex()
1781                .w_full()
1782                .p_1p5()
1783                .justify_between()
1784                .border_t_1()
1785                .border_color(cx.theme().colors().border_variant)
1786                .child(
1787                    PopoverMenu::new("filter-menu-popover")
1788                        .with_handle(self.filter_popover_menu_handle.clone())
1789                        .attach(gpui::Corner::BottomRight)
1790                        .anchor(gpui::Corner::BottomLeft)
1791                        .offset(gpui::Point {
1792                            x: px(1.0),
1793                            y: px(1.0),
1794                        })
1795                        .trigger_with_tooltip(
1796                            IconButton::new("filter-trigger", IconName::Sliders)
1797                                .icon_size(IconSize::Small)
1798                                .icon_size(IconSize::Small)
1799                                .toggle_state(self.include_ignored.unwrap_or(false))
1800                                .when(self.include_ignored.is_some(), |this| {
1801                                    this.indicator(Indicator::dot().color(Color::Info))
1802                                }),
1803                            {
1804                                let focus_handle = focus_handle.clone();
1805                                move |_window, cx| {
1806                                    Tooltip::for_action_in(
1807                                        "Filter Options",
1808                                        &ToggleFilterMenu,
1809                                        &focus_handle,
1810                                        cx,
1811                                    )
1812                                }
1813                            },
1814                        )
1815                        .menu({
1816                            let focus_handle = focus_handle.clone();
1817                            let include_ignored = self.include_ignored;
1818
1819                            move |window, cx| {
1820                                Some(ContextMenu::build(window, cx, {
1821                                    let focus_handle = focus_handle.clone();
1822                                    move |menu, _, _| {
1823                                        menu.context(focus_handle.clone())
1824                                            .header("Filter Options")
1825                                            .toggleable_entry(
1826                                                "Include Ignored Files",
1827                                                include_ignored.unwrap_or(false),
1828                                                ui::IconPosition::End,
1829                                                Some(ToggleIncludeIgnored.boxed_clone()),
1830                                                move |window, cx| {
1831                                                    window.focus(&focus_handle, cx);
1832                                                    window.dispatch_action(
1833                                                        ToggleIncludeIgnored.boxed_clone(),
1834                                                        cx,
1835                                                    );
1836                                                },
1837                                            )
1838                                    }
1839                                }))
1840                            }
1841                        }),
1842                )
1843                .child(
1844                    h_flex()
1845                        .gap_0p5()
1846                        .child(
1847                            PopoverMenu::new("split-menu-popover")
1848                                .with_handle(self.split_popover_menu_handle.clone())
1849                                .attach(gpui::Corner::BottomRight)
1850                                .anchor(gpui::Corner::BottomLeft)
1851                                .offset(gpui::Point {
1852                                    x: px(1.0),
1853                                    y: px(1.0),
1854                                })
1855                                .trigger(
1856                                    ButtonLike::new("split-trigger")
1857                                        .child(Label::new("Split…"))
1858                                        .selected_style(ButtonStyle::Tinted(TintColor::Accent))
1859                                        .child(
1860                                            KeyBinding::for_action_in(
1861                                                &ToggleSplitMenu,
1862                                                &focus_handle,
1863                                                cx,
1864                                            )
1865                                            .size(rems_from_px(12.)),
1866                                        ),
1867                                )
1868                                .menu({
1869                                    let focus_handle = focus_handle.clone();
1870
1871                                    move |window, cx| {
1872                                        Some(ContextMenu::build(window, cx, {
1873                                            let focus_handle = focus_handle.clone();
1874                                            move |menu, _, _| {
1875                                                menu.context(focus_handle)
1876                                                    .action(
1877                                                        "Split Left",
1878                                                        pane::SplitLeft::default().boxed_clone(),
1879                                                    )
1880                                                    .action(
1881                                                        "Split Right",
1882                                                        pane::SplitRight::default().boxed_clone(),
1883                                                    )
1884                                                    .action(
1885                                                        "Split Up",
1886                                                        pane::SplitUp::default().boxed_clone(),
1887                                                    )
1888                                                    .action(
1889                                                        "Split Down",
1890                                                        pane::SplitDown::default().boxed_clone(),
1891                                                    )
1892                                            }
1893                                        }))
1894                                    }
1895                                }),
1896                        )
1897                        .child(
1898                            Button::new("open-selection", "Open")
1899                                .key_binding(
1900                                    KeyBinding::for_action_in(&menu::Confirm, &focus_handle, cx)
1901                                        .map(|kb| kb.size(rems_from_px(12.))),
1902                                )
1903                                .on_click(|_, window, cx| {
1904                                    window.dispatch_action(menu::Confirm.boxed_clone(), cx)
1905                                }),
1906                        ),
1907                )
1908                .into_any(),
1909        )
1910    }
1911}
1912
1913#[derive(Clone, Debug, PartialEq, Eq)]
1914struct PathComponentSlice<'a> {
1915    path: Cow<'a, Path>,
1916    path_str: Cow<'a, str>,
1917    component_ranges: Vec<(Component<'a>, Range<usize>)>,
1918}
1919
1920impl<'a> PathComponentSlice<'a> {
1921    fn new(path: &'a str) -> Self {
1922        let trimmed_path = Path::new(path).components().as_path().as_os_str();
1923        let mut component_ranges = Vec::new();
1924        let mut components = Path::new(trimmed_path).components();
1925        let len = trimmed_path.as_encoded_bytes().len();
1926        let mut pos = 0;
1927        while let Some(component) = components.next() {
1928            component_ranges.push((component, pos..0));
1929            pos = len - components.as_path().as_os_str().as_encoded_bytes().len();
1930        }
1931        for ((_, range), ancestor) in component_ranges
1932            .iter_mut()
1933            .rev()
1934            .zip(Path::new(trimmed_path).ancestors())
1935        {
1936            range.end = ancestor.as_os_str().as_encoded_bytes().len();
1937        }
1938        Self {
1939            path: Cow::Borrowed(Path::new(path)),
1940            path_str: Cow::Borrowed(path),
1941            component_ranges,
1942        }
1943    }
1944
1945    fn elision_range(&self, budget: usize, matches: &[usize]) -> Option<Range<usize>> {
1946        let eligible_range = {
1947            assert!(matches.windows(2).all(|w| w[0] <= w[1]));
1948            let mut matches = matches.iter().copied().peekable();
1949            let mut longest: Option<Range<usize>> = None;
1950            let mut cur = 0..0;
1951            let mut seen_normal = false;
1952            for (i, (component, range)) in self.component_ranges.iter().enumerate() {
1953                let is_normal = matches!(component, Component::Normal(_));
1954                let is_first_normal = is_normal && !seen_normal;
1955                seen_normal |= is_normal;
1956                let is_last = i == self.component_ranges.len() - 1;
1957                let contains_match = matches.peek().is_some_and(|mat| range.contains(mat));
1958                if contains_match {
1959                    matches.next();
1960                }
1961                if is_first_normal || is_last || !is_normal || contains_match {
1962                    if longest
1963                        .as_ref()
1964                        .is_none_or(|old| old.end - old.start <= cur.end - cur.start)
1965                    {
1966                        longest = Some(cur);
1967                    }
1968                    cur = i + 1..i + 1;
1969                } else {
1970                    cur.end = i + 1;
1971                }
1972            }
1973            if longest
1974                .as_ref()
1975                .is_none_or(|old| old.end - old.start <= cur.end - cur.start)
1976            {
1977                longest = Some(cur);
1978            }
1979            longest
1980        };
1981
1982        let eligible_range = eligible_range?;
1983        assert!(eligible_range.start <= eligible_range.end);
1984        if eligible_range.is_empty() {
1985            return None;
1986        }
1987
1988        let elided_range: Range<usize> = {
1989            let byte_range = self.component_ranges[eligible_range.start].1.start
1990                ..self.component_ranges[eligible_range.end - 1].1.end;
1991            let midpoint = self.path_str.len() / 2;
1992            let distance_from_start = byte_range.start.abs_diff(midpoint);
1993            let distance_from_end = byte_range.end.abs_diff(midpoint);
1994            let pick_from_end = distance_from_start > distance_from_end;
1995            let mut len_with_elision = self.path_str.len();
1996            let mut i = eligible_range.start;
1997            while i < eligible_range.end {
1998                let x = if pick_from_end {
1999                    eligible_range.end - i + eligible_range.start - 1
2000                } else {
2001                    i
2002                };
2003                len_with_elision -= self.component_ranges[x]
2004                    .0
2005                    .as_os_str()
2006                    .as_encoded_bytes()
2007                    .len()
2008                    + 1;
2009                if len_with_elision <= budget {
2010                    break;
2011                }
2012                i += 1;
2013            }
2014            if len_with_elision > budget {
2015                return None;
2016            } else if pick_from_end {
2017                let x = eligible_range.end - i + eligible_range.start - 1;
2018                x..eligible_range.end
2019            } else {
2020                let x = i;
2021                eligible_range.start..x + 1
2022            }
2023        };
2024
2025        let byte_range = self.component_ranges[elided_range.start].1.start
2026            ..self.component_ranges[elided_range.end - 1].1.end;
2027        Some(byte_range)
2028    }
2029}