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