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