file_finder.rs

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