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