file_finder.rs

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