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