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