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