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