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