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    actions, Action, AnyElement, App, Context, DismissEvent, Entity, EventEmitter, FocusHandle,
  20    Focusable, KeyContext, Modifiers, ModifiersChangedEvent, ParentElement, Render, Styled, Task,
  21    WeakEntity, Window,
  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        atomic::{self, AtomicBool},
  35        Arc,
  36    },
  37};
  38use text::Point;
  39use ui::{
  40    prelude::*, ContextMenu, HighlightedLabel, ListItem, ListItemSpacing, PopoverMenu,
  41    PopoverMenuHandle,
  42};
  43use util::{maybe, paths::PathWithPosition, post_inc, ResultExt};
  44use workspace::{
  45    item::PreviewTabsSettings, notifications::NotifyResultExt, pane, ModalView, OpenOptions,
  46    OpenVisible, SplitDirection, Workspace,
  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, move |workspace, mut cx| async move {
 149            let history_items = join_all(history_items).await.into_iter().flatten();
 150
 151            workspace
 152                .update_in(&mut 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                cmp::Ordering::Greater
 534            }
 535            (_, Match::History { path, .. }) if Some(path) == currently_opened => {
 536                cmp::Ordering::Less
 537            }
 538
 539            (Match::History { .. }, Match::Search(_)) if separate_history => cmp::Ordering::Greater,
 540            (Match::Search(_), Match::History { .. }) if separate_history => cmp::Ordering::Less,
 541
 542            _ => a.panel_match().cmp(&b.panel_match()),
 543        }
 544    }
 545}
 546
 547fn matching_history_items<'a>(
 548    history_items: impl IntoIterator<Item = &'a FoundPath>,
 549    currently_opened: Option<&'a FoundPath>,
 550    query: &FileSearchQuery,
 551) -> HashMap<Arc<Path>, Match> {
 552    let mut candidates_paths = HashMap::default();
 553
 554    let history_items_by_worktrees = history_items
 555        .into_iter()
 556        .chain(currently_opened)
 557        .filter_map(|found_path| {
 558            let candidate = PathMatchCandidate {
 559                is_dir: false, // You can't open directories as project items
 560                path: &found_path.project.path,
 561                // Only match history items names, otherwise their paths may match too many queries, producing false positives.
 562                // E.g. `foo` would match both `something/foo/bar.rs` and `something/foo/foo.rs` and if the former is a history item,
 563                // it would be shown first always, despite the latter being a better match.
 564                char_bag: CharBag::from_iter(
 565                    found_path
 566                        .project
 567                        .path
 568                        .file_name()?
 569                        .to_string_lossy()
 570                        .to_lowercase()
 571                        .chars(),
 572                ),
 573            };
 574            candidates_paths.insert(&found_path.project, found_path);
 575            Some((found_path.project.worktree_id, candidate))
 576        })
 577        .fold(
 578            HashMap::default(),
 579            |mut candidates, (worktree_id, new_candidate)| {
 580                candidates
 581                    .entry(worktree_id)
 582                    .or_insert_with(Vec::new)
 583                    .push(new_candidate);
 584                candidates
 585            },
 586        );
 587    let mut matching_history_paths = HashMap::default();
 588    for (worktree, candidates) in history_items_by_worktrees {
 589        let max_results = candidates.len() + 1;
 590        matching_history_paths.extend(
 591            fuzzy::match_fixed_path_set(
 592                candidates,
 593                worktree.to_usize(),
 594                query.path_query(),
 595                false,
 596                max_results,
 597            )
 598            .into_iter()
 599            .filter_map(|path_match| {
 600                candidates_paths
 601                    .remove_entry(&ProjectPath {
 602                        worktree_id: WorktreeId::from_usize(path_match.worktree_id),
 603                        path: Arc::clone(&path_match.path),
 604                    })
 605                    .map(|(_, found_path)| {
 606                        (
 607                            Arc::clone(&path_match.path),
 608                            Match::History {
 609                                path: found_path.clone(),
 610                                panel_match: Some(ProjectPanelOrdMatch(path_match)),
 611                            },
 612                        )
 613                    })
 614            }),
 615        );
 616    }
 617    matching_history_paths
 618}
 619
 620#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
 621struct FoundPath {
 622    project: ProjectPath,
 623    absolute: Option<PathBuf>,
 624}
 625
 626impl FoundPath {
 627    fn new(project: ProjectPath, absolute: Option<PathBuf>) -> Self {
 628        Self { project, absolute }
 629    }
 630}
 631
 632const MAX_RECENT_SELECTIONS: usize = 20;
 633
 634pub enum Event {
 635    Selected(ProjectPath),
 636    Dismissed,
 637}
 638
 639#[derive(Debug, Clone)]
 640struct FileSearchQuery {
 641    raw_query: String,
 642    file_query_end: Option<usize>,
 643    path_position: PathWithPosition,
 644}
 645
 646impl FileSearchQuery {
 647    fn path_query(&self) -> &str {
 648        match self.file_query_end {
 649            Some(file_path_end) => &self.raw_query[..file_path_end],
 650            None => &self.raw_query,
 651        }
 652    }
 653}
 654
 655impl FileFinderDelegate {
 656    #[allow(clippy::too_many_arguments)]
 657    fn new(
 658        file_finder: WeakEntity<FileFinder>,
 659        workspace: WeakEntity<Workspace>,
 660        project: Entity<Project>,
 661        currently_opened_path: Option<FoundPath>,
 662        history_items: Vec<FoundPath>,
 663        separate_history: bool,
 664        window: &mut Window,
 665        cx: &mut Context<FileFinder>,
 666    ) -> Self {
 667        Self::subscribe_to_updates(&project, window, cx);
 668        Self {
 669            file_finder,
 670            workspace,
 671            project,
 672            search_count: 0,
 673            latest_search_id: 0,
 674            latest_search_did_cancel: false,
 675            latest_search_query: None,
 676            currently_opened_path,
 677            matches: Matches::default(),
 678            has_changed_selected_index: false,
 679            selected_index: 0,
 680            cancel_flag: Arc::new(AtomicBool::new(false)),
 681            history_items,
 682            separate_history,
 683            first_update: true,
 684            popover_menu_handle: PopoverMenuHandle::default(),
 685            focus_handle: cx.focus_handle(),
 686        }
 687    }
 688
 689    fn subscribe_to_updates(
 690        project: &Entity<Project>,
 691        window: &mut Window,
 692        cx: &mut Context<FileFinder>,
 693    ) {
 694        cx.subscribe_in(project, window, |file_finder, _, event, window, cx| {
 695            match event {
 696                project::Event::WorktreeUpdatedEntries(_, _)
 697                | project::Event::WorktreeAdded(_)
 698                | project::Event::WorktreeRemoved(_) => file_finder
 699                    .picker
 700                    .update(cx, |picker, cx| picker.refresh(window, cx)),
 701                _ => {}
 702            };
 703        })
 704        .detach();
 705    }
 706
 707    fn spawn_search(
 708        &mut self,
 709        query: FileSearchQuery,
 710        window: &mut Window,
 711        cx: &mut Context<Picker<Self>>,
 712    ) -> Task<()> {
 713        let relative_to = self
 714            .currently_opened_path
 715            .as_ref()
 716            .map(|found_path| Arc::clone(&found_path.project.path));
 717        let worktrees = self
 718            .project
 719            .read(cx)
 720            .visible_worktrees(cx)
 721            .collect::<Vec<_>>();
 722        let include_root_name = worktrees.len() > 1;
 723        let candidate_sets = worktrees
 724            .into_iter()
 725            .map(|worktree| {
 726                let worktree = worktree.read(cx);
 727                PathMatchCandidateSet {
 728                    snapshot: worktree.snapshot(),
 729                    include_ignored: worktree
 730                        .root_entry()
 731                        .map_or(false, |entry| entry.is_ignored),
 732                    include_root_name,
 733                    candidates: project::Candidates::Files,
 734                }
 735            })
 736            .collect::<Vec<_>>();
 737
 738        let search_id = util::post_inc(&mut self.search_count);
 739        self.cancel_flag.store(true, atomic::Ordering::Relaxed);
 740        self.cancel_flag = Arc::new(AtomicBool::new(false));
 741        let cancel_flag = self.cancel_flag.clone();
 742        cx.spawn_in(window, |picker, mut cx| async move {
 743            let matches = fuzzy::match_path_sets(
 744                candidate_sets.as_slice(),
 745                query.path_query(),
 746                relative_to,
 747                false,
 748                100,
 749                &cancel_flag,
 750                cx.background_executor().clone(),
 751            )
 752            .await
 753            .into_iter()
 754            .map(ProjectPanelOrdMatch);
 755            let did_cancel = cancel_flag.load(atomic::Ordering::Relaxed);
 756            picker
 757                .update(&mut cx, |picker, cx| {
 758                    picker
 759                        .delegate
 760                        .set_search_matches(search_id, did_cancel, query, matches, cx)
 761                })
 762                .log_err();
 763        })
 764    }
 765
 766    fn set_search_matches(
 767        &mut self,
 768        search_id: usize,
 769        did_cancel: bool,
 770        query: FileSearchQuery,
 771        matches: impl IntoIterator<Item = ProjectPanelOrdMatch>,
 772
 773        cx: &mut Context<Picker<Self>>,
 774    ) {
 775        if search_id >= self.latest_search_id {
 776            self.latest_search_id = search_id;
 777            let query_changed = Some(query.path_query())
 778                != self
 779                    .latest_search_query
 780                    .as_ref()
 781                    .map(|query| query.path_query());
 782            let extend_old_matches = self.latest_search_did_cancel && !query_changed;
 783
 784            let selected_match = if query_changed {
 785                None
 786            } else {
 787                self.matches.get(self.selected_index).cloned()
 788            };
 789
 790            self.matches.push_new_matches(
 791                &self.history_items,
 792                self.currently_opened_path.as_ref(),
 793                Some(&query),
 794                matches.into_iter(),
 795                extend_old_matches,
 796            );
 797
 798            self.selected_index = selected_match.map_or_else(
 799                || self.calculate_selected_index(),
 800                |m| {
 801                    self.matches
 802                        .position(&m, self.currently_opened_path.as_ref())
 803                        .unwrap_or(0)
 804                },
 805            );
 806
 807            self.latest_search_query = Some(query);
 808            self.latest_search_did_cancel = did_cancel;
 809
 810            cx.notify();
 811        }
 812    }
 813
 814    fn labels_for_match(
 815        &self,
 816        path_match: &Match,
 817        window: &mut Window,
 818        cx: &App,
 819        ix: usize,
 820    ) -> (HighlightedLabel, HighlightedLabel) {
 821        let (file_name, file_name_positions, mut full_path, mut full_path_positions) =
 822            match &path_match {
 823                Match::History {
 824                    path: entry_path,
 825                    panel_match,
 826                } => {
 827                    let worktree_id = entry_path.project.worktree_id;
 828                    let project_relative_path = &entry_path.project.path;
 829                    let has_worktree = self
 830                        .project
 831                        .read(cx)
 832                        .worktree_for_id(worktree_id, cx)
 833                        .is_some();
 834
 835                    if let Some(absolute_path) =
 836                        entry_path.absolute.as_ref().filter(|_| !has_worktree)
 837                    {
 838                        (
 839                            absolute_path
 840                                .file_name()
 841                                .map_or_else(
 842                                    || project_relative_path.to_string_lossy(),
 843                                    |file_name| file_name.to_string_lossy(),
 844                                )
 845                                .to_string(),
 846                            Vec::new(),
 847                            absolute_path.to_string_lossy().to_string(),
 848                            Vec::new(),
 849                        )
 850                    } else {
 851                        let mut path = Arc::clone(project_relative_path);
 852                        if project_relative_path.as_ref() == Path::new("") {
 853                            if let Some(absolute_path) = &entry_path.absolute {
 854                                path = Arc::from(absolute_path.as_path());
 855                            }
 856                        }
 857
 858                        let mut path_match = PathMatch {
 859                            score: ix as f64,
 860                            positions: Vec::new(),
 861                            worktree_id: worktree_id.to_usize(),
 862                            path,
 863                            is_dir: false, // File finder doesn't support directories
 864                            path_prefix: "".into(),
 865                            distance_to_relative_ancestor: usize::MAX,
 866                        };
 867                        if let Some(found_path_match) = &panel_match {
 868                            path_match
 869                                .positions
 870                                .extend(found_path_match.0.positions.iter())
 871                        }
 872
 873                        self.labels_for_path_match(&path_match)
 874                    }
 875                }
 876                Match::Search(path_match) => self.labels_for_path_match(&path_match.0),
 877            };
 878
 879        if file_name_positions.is_empty() {
 880            if let Some(user_home_path) = std::env::var("HOME").ok() {
 881                let user_home_path = user_home_path.trim();
 882                if !user_home_path.is_empty() {
 883                    if (&full_path).starts_with(user_home_path) {
 884                        full_path.replace_range(0..user_home_path.len(), "~");
 885                        full_path_positions.retain_mut(|pos| {
 886                            if *pos >= user_home_path.len() {
 887                                *pos -= user_home_path.len();
 888                                *pos += 1;
 889                                true
 890                            } else {
 891                                false
 892                            }
 893                        })
 894                    }
 895                }
 896            }
 897        }
 898
 899        if full_path.is_ascii() {
 900            let file_finder_settings = FileFinderSettings::get_global(cx);
 901            let max_width =
 902                FileFinder::modal_max_width(file_finder_settings.modal_max_width, window);
 903            let (normal_em, small_em) = {
 904                let style = window.text_style();
 905                let font_id = window.text_system().resolve_font(&style.font());
 906                let font_size = TextSize::Default.rems(cx).to_pixels(window.rem_size());
 907                let normal = cx
 908                    .text_system()
 909                    .em_width(font_id, font_size)
 910                    .unwrap_or(px(16.));
 911                let font_size = TextSize::Small.rems(cx).to_pixels(window.rem_size());
 912                let small = cx
 913                    .text_system()
 914                    .em_width(font_id, font_size)
 915                    .unwrap_or(px(10.));
 916                (normal, small)
 917            };
 918            let budget = full_path_budget(&file_name, normal_em, small_em, max_width);
 919            // If the computed budget is zero, we certainly won't be able to achieve it,
 920            // so no point trying to elide the path.
 921            if budget > 0 && full_path.len() > budget {
 922                let components = PathComponentSlice::new(&full_path);
 923                if let Some(elided_range) =
 924                    components.elision_range(budget - 1, &full_path_positions)
 925                {
 926                    let elided_len = elided_range.end - elided_range.start;
 927                    let placeholder = "";
 928                    full_path_positions.retain_mut(|mat| {
 929                        if *mat >= elided_range.end {
 930                            *mat -= elided_len;
 931                            *mat += placeholder.len();
 932                        } else if *mat >= elided_range.start {
 933                            return false;
 934                        }
 935                        true
 936                    });
 937                    full_path.replace_range(elided_range, placeholder);
 938                }
 939            }
 940        }
 941
 942        (
 943            HighlightedLabel::new(file_name, file_name_positions),
 944            HighlightedLabel::new(full_path, full_path_positions)
 945                .size(LabelSize::Small)
 946                .color(Color::Muted),
 947        )
 948    }
 949
 950    fn labels_for_path_match(
 951        &self,
 952        path_match: &PathMatch,
 953    ) -> (String, Vec<usize>, String, Vec<usize>) {
 954        let path = &path_match.path;
 955        let path_string = path.to_string_lossy();
 956        let full_path = [path_match.path_prefix.as_ref(), path_string.as_ref()].join("");
 957        let mut path_positions = path_match.positions.clone();
 958
 959        let file_name = path.file_name().map_or_else(
 960            || path_match.path_prefix.to_string(),
 961            |file_name| file_name.to_string_lossy().to_string(),
 962        );
 963        let file_name_start = path_match.path_prefix.len() + path_string.len() - file_name.len();
 964        let file_name_positions = path_positions
 965            .iter()
 966            .filter_map(|pos| {
 967                if pos >= &file_name_start {
 968                    Some(pos - file_name_start)
 969                } else {
 970                    None
 971                }
 972            })
 973            .collect();
 974
 975        let full_path = full_path.trim_end_matches(&file_name).to_string();
 976        path_positions.retain(|idx| *idx < full_path.len());
 977
 978        (file_name, file_name_positions, full_path, path_positions)
 979    }
 980
 981    fn lookup_absolute_path(
 982        &self,
 983        query: FileSearchQuery,
 984        window: &mut Window,
 985        cx: &mut Context<Picker<Self>>,
 986    ) -> Task<()> {
 987        cx.spawn_in(window, |picker, mut cx| async move {
 988            let Some(project) = picker
 989                .update(&mut cx, |picker, _| picker.delegate.project.clone())
 990                .log_err()
 991            else {
 992                return;
 993            };
 994
 995            let query_path = Path::new(query.path_query());
 996            let mut path_matches = Vec::new();
 997
 998            let abs_file_exists = if let Ok(task) = project.update(&mut cx, |this, cx| {
 999                this.resolve_abs_file_path(query.path_query(), cx)
1000            }) {
1001                task.await.is_some()
1002            } else {
1003                false
1004            };
1005
1006            if abs_file_exists {
1007                let update_result = project
1008                    .update(&mut cx, |project, cx| {
1009                        if let Some((worktree, relative_path)) =
1010                            project.find_worktree(query_path, cx)
1011                        {
1012                            path_matches.push(ProjectPanelOrdMatch(PathMatch {
1013                                score: 1.0,
1014                                positions: Vec::new(),
1015                                worktree_id: worktree.read(cx).id().to_usize(),
1016                                path: Arc::from(relative_path),
1017                                path_prefix: "".into(),
1018                                is_dir: false, // File finder doesn't support directories
1019                                distance_to_relative_ancestor: usize::MAX,
1020                            }));
1021                        }
1022                    })
1023                    .log_err();
1024                if update_result.is_none() {
1025                    return;
1026                }
1027            }
1028
1029            picker
1030                .update_in(&mut cx, |picker, _, cx| {
1031                    let picker_delegate = &mut picker.delegate;
1032                    let search_id = util::post_inc(&mut picker_delegate.search_count);
1033                    picker_delegate.set_search_matches(search_id, false, query, path_matches, cx);
1034
1035                    anyhow::Ok(())
1036                })
1037                .log_err();
1038        })
1039    }
1040
1041    /// Skips first history match (that is displayed topmost) if it's currently opened.
1042    fn calculate_selected_index(&self) -> usize {
1043        if let Some(Match::History { path, .. }) = self.matches.get(0) {
1044            if Some(path) == self.currently_opened_path.as_ref() {
1045                let elements_after_first = self.matches.len() - 1;
1046                if elements_after_first > 0 {
1047                    return 1;
1048                }
1049            }
1050        }
1051
1052        0
1053    }
1054
1055    fn key_context(&self, window: &Window, cx: &App) -> KeyContext {
1056        let mut key_context = KeyContext::new_with_defaults();
1057        key_context.add("FileFinder");
1058        if self.popover_menu_handle.is_focused(window, cx) {
1059            key_context.add("menu_open");
1060        }
1061        key_context
1062    }
1063}
1064
1065fn full_path_budget(
1066    file_name: &str,
1067    normal_em: Pixels,
1068    small_em: Pixels,
1069    max_width: Pixels,
1070) -> usize {
1071    ((px(max_width / px(0.8)) - px(file_name.len() as f32) * normal_em) / small_em) as usize
1072}
1073
1074impl PickerDelegate for FileFinderDelegate {
1075    type ListItem = ListItem;
1076
1077    fn placeholder_text(&self, _window: &mut Window, _cx: &mut App) -> Arc<str> {
1078        "Search project files...".into()
1079    }
1080
1081    fn match_count(&self) -> usize {
1082        self.matches.len()
1083    }
1084
1085    fn selected_index(&self) -> usize {
1086        self.selected_index
1087    }
1088
1089    fn set_selected_index(&mut self, ix: usize, _: &mut Window, cx: &mut Context<Picker<Self>>) {
1090        self.has_changed_selected_index = true;
1091        self.selected_index = ix;
1092        cx.notify();
1093    }
1094
1095    fn separators_after_indices(&self) -> Vec<usize> {
1096        if self.separate_history {
1097            let first_non_history_index = self
1098                .matches
1099                .matches
1100                .iter()
1101                .enumerate()
1102                .find(|(_, m)| !matches!(m, Match::History { .. }))
1103                .map(|(i, _)| i);
1104            if let Some(first_non_history_index) = first_non_history_index {
1105                if first_non_history_index > 0 {
1106                    return vec![first_non_history_index - 1];
1107                }
1108            }
1109        }
1110        Vec::new()
1111    }
1112
1113    fn update_matches(
1114        &mut self,
1115        raw_query: String,
1116        window: &mut Window,
1117        cx: &mut Context<Picker<Self>>,
1118    ) -> Task<()> {
1119        let raw_query = raw_query.replace(' ', "");
1120        let raw_query = raw_query.trim();
1121        if raw_query.is_empty() {
1122            // if there was no query before, and we already have some (history) matches
1123            // there's no need to update anything, since nothing has changed.
1124            // We also want to populate matches set from history entries on the first update.
1125            if self.latest_search_query.is_some() || self.first_update {
1126                let project = self.project.read(cx);
1127
1128                self.latest_search_id = post_inc(&mut self.search_count);
1129                self.latest_search_query = None;
1130                self.matches = Matches {
1131                    separate_history: self.separate_history,
1132                    ..Matches::default()
1133                };
1134                self.matches.push_new_matches(
1135                    self.history_items.iter().filter(|history_item| {
1136                        project
1137                            .worktree_for_id(history_item.project.worktree_id, cx)
1138                            .is_some()
1139                            || ((project.is_local() || project.is_via_ssh())
1140                                && history_item.absolute.is_some())
1141                    }),
1142                    self.currently_opened_path.as_ref(),
1143                    None,
1144                    None.into_iter(),
1145                    false,
1146                );
1147
1148                self.first_update = false;
1149                self.selected_index = 0;
1150            }
1151            cx.notify();
1152            Task::ready(())
1153        } else {
1154            let path_position = PathWithPosition::parse_str(&raw_query);
1155
1156            let query = FileSearchQuery {
1157                raw_query: raw_query.trim().to_owned(),
1158                file_query_end: if path_position.path.to_str().unwrap_or(raw_query) == raw_query {
1159                    None
1160                } else {
1161                    // Safe to unwrap as we won't get here when the unwrap in if fails
1162                    Some(path_position.path.to_str().unwrap().len())
1163                },
1164                path_position,
1165            };
1166
1167            if Path::new(query.path_query()).is_absolute() {
1168                self.lookup_absolute_path(query, window, cx)
1169            } else {
1170                self.spawn_search(query, window, cx)
1171            }
1172        }
1173    }
1174
1175    fn confirm(
1176        &mut self,
1177        secondary: bool,
1178        window: &mut Window,
1179        cx: &mut Context<Picker<FileFinderDelegate>>,
1180    ) {
1181        if let Some(m) = self.matches.get(self.selected_index()) {
1182            if let Some(workspace) = self.workspace.upgrade() {
1183                let open_task = workspace.update(cx, |workspace, cx| {
1184                    let split_or_open =
1185                        |workspace: &mut Workspace,
1186                         project_path,
1187                         window: &mut Window,
1188                         cx: &mut Context<Workspace>| {
1189                            let allow_preview =
1190                                PreviewTabsSettings::get_global(cx).enable_preview_from_file_finder;
1191                            if secondary {
1192                                workspace.split_path_preview(
1193                                    project_path,
1194                                    allow_preview,
1195                                    None,
1196                                    window,
1197                                    cx,
1198                                )
1199                            } else {
1200                                workspace.open_path_preview(
1201                                    project_path,
1202                                    None,
1203                                    true,
1204                                    allow_preview,
1205                                    true,
1206                                    window,
1207                                    cx,
1208                                )
1209                            }
1210                        };
1211                    match &m {
1212                        Match::History { path, .. } => {
1213                            let worktree_id = path.project.worktree_id;
1214                            if workspace
1215                                .project()
1216                                .read(cx)
1217                                .worktree_for_id(worktree_id, cx)
1218                                .is_some()
1219                            {
1220                                split_or_open(
1221                                    workspace,
1222                                    ProjectPath {
1223                                        worktree_id,
1224                                        path: Arc::clone(&path.project.path),
1225                                    },
1226                                    window,
1227                                    cx,
1228                                )
1229                            } else {
1230                                match path.absolute.as_ref() {
1231                                    Some(abs_path) => {
1232                                        if secondary {
1233                                            workspace.split_abs_path(
1234                                                abs_path.to_path_buf(),
1235                                                false,
1236                                                window,
1237                                                cx,
1238                                            )
1239                                        } else {
1240                                            workspace.open_abs_path(
1241                                                abs_path.to_path_buf(),
1242                                                OpenOptions {
1243                                                    visible: Some(OpenVisible::None),
1244                                                    ..Default::default()
1245                                                },
1246                                                window,
1247                                                cx,
1248                                            )
1249                                        }
1250                                    }
1251                                    None => split_or_open(
1252                                        workspace,
1253                                        ProjectPath {
1254                                            worktree_id,
1255                                            path: Arc::clone(&path.project.path),
1256                                        },
1257                                        window,
1258                                        cx,
1259                                    ),
1260                                }
1261                            }
1262                        }
1263                        Match::Search(m) => split_or_open(
1264                            workspace,
1265                            ProjectPath {
1266                                worktree_id: WorktreeId::from_usize(m.0.worktree_id),
1267                                path: m.0.path.clone(),
1268                            },
1269                            window,
1270                            cx,
1271                        ),
1272                    }
1273                });
1274
1275                let row = self
1276                    .latest_search_query
1277                    .as_ref()
1278                    .and_then(|query| query.path_position.row)
1279                    .map(|row| row.saturating_sub(1));
1280                let col = self
1281                    .latest_search_query
1282                    .as_ref()
1283                    .and_then(|query| query.path_position.column)
1284                    .unwrap_or(0)
1285                    .saturating_sub(1);
1286                let finder = self.file_finder.clone();
1287
1288                cx.spawn_in(window, |_, mut cx| async move {
1289                    let item = open_task.await.notify_async_err(&mut cx)?;
1290                    if let Some(row) = row {
1291                        if let Some(active_editor) = item.downcast::<Editor>() {
1292                            active_editor
1293                                .downgrade()
1294                                .update_in(&mut cx, |editor, window, cx| {
1295                                    editor.go_to_singleton_buffer_point(
1296                                        Point::new(row, col),
1297                                        window,
1298                                        cx,
1299                                    );
1300                                })
1301                                .log_err();
1302                        }
1303                    }
1304                    finder.update(&mut cx, |_, cx| cx.emit(DismissEvent)).ok()?;
1305
1306                    Some(())
1307                })
1308                .detach();
1309            }
1310        }
1311    }
1312
1313    fn dismissed(&mut self, _: &mut Window, cx: &mut Context<Picker<FileFinderDelegate>>) {
1314        self.file_finder
1315            .update(cx, |_, cx| cx.emit(DismissEvent))
1316            .log_err();
1317    }
1318
1319    fn render_match(
1320        &self,
1321        ix: usize,
1322        selected: bool,
1323        window: &mut Window,
1324        cx: &mut Context<Picker<Self>>,
1325    ) -> Option<Self::ListItem> {
1326        let settings = FileFinderSettings::get_global(cx);
1327
1328        let path_match = self
1329            .matches
1330            .get(ix)
1331            .expect("Invalid matches state: no element for index {ix}");
1332
1333        let history_icon = match &path_match {
1334            Match::History { .. } => Icon::new(IconName::HistoryRerun)
1335                .color(Color::Muted)
1336                .size(IconSize::Small)
1337                .into_any_element(),
1338            Match::Search(_) => v_flex()
1339                .flex_none()
1340                .size(IconSize::Small.rems())
1341                .into_any_element(),
1342        };
1343        let (file_name_label, full_path_label) = self.labels_for_match(path_match, window, cx, ix);
1344
1345        let file_icon = maybe!({
1346            if !settings.file_icons {
1347                return None;
1348            }
1349            let file_name = path_match.path().file_name()?;
1350            let icon = FileIcons::get_icon(file_name.as_ref(), cx)?;
1351            Some(Icon::from_path(icon).color(Color::Muted))
1352        });
1353
1354        Some(
1355            ListItem::new(ix)
1356                .spacing(ListItemSpacing::Sparse)
1357                .start_slot::<Icon>(file_icon)
1358                .end_slot::<AnyElement>(history_icon)
1359                .inset(true)
1360                .toggle_state(selected)
1361                .child(
1362                    h_flex()
1363                        .gap_2()
1364                        .py_px()
1365                        .child(file_name_label)
1366                        .child(full_path_label),
1367                ),
1368        )
1369    }
1370
1371    fn render_footer(&self, _: &mut Window, cx: &mut Context<Picker<Self>>) -> Option<AnyElement> {
1372        let context = self.focus_handle.clone();
1373        Some(
1374            h_flex()
1375                .w_full()
1376                .p_2()
1377                .gap_2()
1378                .justify_end()
1379                .border_t_1()
1380                .border_color(cx.theme().colors().border_variant)
1381                .child(
1382                    Button::new("open-selection", "Open").on_click(|_, window, cx| {
1383                        window.dispatch_action(menu::Confirm.boxed_clone(), cx)
1384                    }),
1385                )
1386                .child(
1387                    PopoverMenu::new("menu-popover")
1388                        .with_handle(self.popover_menu_handle.clone())
1389                        .attach(gpui::Corner::TopRight)
1390                        .anchor(gpui::Corner::BottomRight)
1391                        .trigger(
1392                            Button::new("actions-trigger", "Split…")
1393                                .selected_label_color(Color::Accent),
1394                        )
1395                        .menu({
1396                            move |window, cx| {
1397                                Some(ContextMenu::build(window, cx, {
1398                                    let context = context.clone();
1399                                    move |menu, _, _| {
1400                                        menu.context(context)
1401                                            .action("Split Left", pane::SplitLeft.boxed_clone())
1402                                            .action("Split Right", pane::SplitRight.boxed_clone())
1403                                            .action("Split Up", pane::SplitUp.boxed_clone())
1404                                            .action("Split Down", pane::SplitDown.boxed_clone())
1405                                    }
1406                                }))
1407                            }
1408                        }),
1409                )
1410                .into_any(),
1411        )
1412    }
1413}
1414
1415#[derive(Clone, Debug, PartialEq, Eq)]
1416struct PathComponentSlice<'a> {
1417    path: Cow<'a, Path>,
1418    path_str: Cow<'a, str>,
1419    component_ranges: Vec<(Component<'a>, Range<usize>)>,
1420}
1421
1422impl<'a> PathComponentSlice<'a> {
1423    fn new(path: &'a str) -> Self {
1424        let trimmed_path = Path::new(path).components().as_path().as_os_str();
1425        let mut component_ranges = Vec::new();
1426        let mut components = Path::new(trimmed_path).components();
1427        let len = trimmed_path.as_encoded_bytes().len();
1428        let mut pos = 0;
1429        while let Some(component) = components.next() {
1430            component_ranges.push((component, pos..0));
1431            pos = len - components.as_path().as_os_str().as_encoded_bytes().len();
1432        }
1433        for ((_, range), ancestor) in component_ranges
1434            .iter_mut()
1435            .rev()
1436            .zip(Path::new(trimmed_path).ancestors())
1437        {
1438            range.end = ancestor.as_os_str().as_encoded_bytes().len();
1439        }
1440        Self {
1441            path: Cow::Borrowed(Path::new(path)),
1442            path_str: Cow::Borrowed(path),
1443            component_ranges,
1444        }
1445    }
1446
1447    fn elision_range(&self, budget: usize, matches: &[usize]) -> Option<Range<usize>> {
1448        let eligible_range = {
1449            assert!(matches.windows(2).all(|w| w[0] <= w[1]));
1450            let mut matches = matches.iter().copied().peekable();
1451            let mut longest: Option<Range<usize>> = None;
1452            let mut cur = 0..0;
1453            let mut seen_normal = false;
1454            for (i, (component, range)) in self.component_ranges.iter().enumerate() {
1455                let is_normal = matches!(component, Component::Normal(_));
1456                let is_first_normal = is_normal && !seen_normal;
1457                seen_normal |= is_normal;
1458                let is_last = i == self.component_ranges.len() - 1;
1459                let contains_match = matches.peek().is_some_and(|mat| range.contains(mat));
1460                if contains_match {
1461                    matches.next();
1462                }
1463                if is_first_normal || is_last || !is_normal || contains_match {
1464                    if longest
1465                        .as_ref()
1466                        .is_none_or(|old| old.end - old.start <= cur.end - cur.start)
1467                    {
1468                        longest = Some(cur);
1469                    }
1470                    cur = i + 1..i + 1;
1471                } else {
1472                    cur.end = i + 1;
1473                }
1474            }
1475            if longest
1476                .as_ref()
1477                .is_none_or(|old| old.end - old.start <= cur.end - cur.start)
1478            {
1479                longest = Some(cur);
1480            }
1481            longest
1482        };
1483
1484        let eligible_range = eligible_range?;
1485        assert!(eligible_range.start <= eligible_range.end);
1486        if eligible_range.is_empty() {
1487            return None;
1488        }
1489
1490        let elided_range: Range<usize> = {
1491            let byte_range = self.component_ranges[eligible_range.start].1.start
1492                ..self.component_ranges[eligible_range.end - 1].1.end;
1493            let midpoint = self.path_str.len() / 2;
1494            let distance_from_start = byte_range.start.abs_diff(midpoint);
1495            let distance_from_end = byte_range.end.abs_diff(midpoint);
1496            let pick_from_end = distance_from_start > distance_from_end;
1497            let mut len_with_elision = self.path_str.len();
1498            let mut i = eligible_range.start;
1499            while i < eligible_range.end {
1500                let x = if pick_from_end {
1501                    eligible_range.end - i + eligible_range.start - 1
1502                } else {
1503                    i
1504                };
1505                len_with_elision -= self.component_ranges[x]
1506                    .0
1507                    .as_os_str()
1508                    .as_encoded_bytes()
1509                    .len()
1510                    + 1;
1511                if len_with_elision <= budget {
1512                    break;
1513                }
1514                i += 1;
1515            }
1516            if len_with_elision > budget {
1517                return None;
1518            } else if pick_from_end {
1519                let x = eligible_range.end - i + eligible_range.start - 1;
1520                x..eligible_range.end
1521            } else {
1522                let x = i;
1523                eligible_range.start..x + 1
1524            }
1525        };
1526
1527        let byte_range = self.component_ranges[elided_range.start].1.start
1528            ..self.component_ranges[elided_range.end - 1].1.end;
1529        Some(byte_range)
1530    }
1531}