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