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