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