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