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