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 - Pixels(512.)).max(small_width),
359 FileFinderWidth::Large => (window_width - Pixels(768.)).max(small_width),
360 FileFinderWidth::Medium => (window_width - Pixels(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| !new_history_matches.contains_key(&path_match.0.path))
563 .map(Match::Search)
564 .collect();
565
566 if extend_old_matches {
567 // since we take history matches instead of new search matches
568 // and history matches has not changed(since the query has not changed and we do not extend old matches otherwise),
569 // old matches can't contain paths present in history_matches as well.
570 self.matches.retain(|m| matches!(m, Match::Search(_)));
571 } else {
572 self.matches.clear();
573 }
574
575 // At this point we have an unsorted set of new history matches, an unsorted set of new search matches
576 // and a sorted set of old search matches.
577 // It is possible that the new search matches' paths contain some of the old search matches' paths.
578 // History matches' paths are unique, since store in a HashMap by path.
579 // We build a sorted Vec<Match>, eliminating duplicate search matches.
580 // Search matches with the same paths should have equal `ProjectPanelOrdMatch`, so we should
581 // not have any duplicates after building the final list.
582 for new_match in new_history_matches
583 .into_values()
584 .chain(new_search_matches.into_iter())
585 {
586 match self.position(&new_match, currently_opened) {
587 Ok(_duplicate) => continue,
588 Err(i) => {
589 self.matches.insert(i, new_match);
590 if self.matches.len() == 100 {
591 break;
592 }
593 }
594 }
595 }
596 }
597
598 /// If a < b, then a is a worse match, aligning with the `ProjectPanelOrdMatch` ordering.
599 fn cmp_matches(
600 separate_history: bool,
601 currently_opened: Option<&FoundPath>,
602 a: &Match,
603 b: &Match,
604 ) -> cmp::Ordering {
605 // Handle CreateNew variant - always put it at the end
606 match (a, b) {
607 (Match::CreateNew(_), _) => return cmp::Ordering::Less,
608 (_, Match::CreateNew(_)) => return cmp::Ordering::Greater,
609 _ => {}
610 }
611 debug_assert!(a.panel_match().is_some() && b.panel_match().is_some());
612
613 match (&a, &b) {
614 // bubble currently opened files to the top
615 (Match::History { path, .. }, _) if Some(path) == currently_opened => {
616 return cmp::Ordering::Greater;
617 }
618 (_, Match::History { path, .. }) if Some(path) == currently_opened => {
619 return cmp::Ordering::Less;
620 }
621
622 _ => {}
623 }
624
625 if separate_history {
626 match (a, b) {
627 (Match::History { .. }, Match::Search(_)) => return cmp::Ordering::Greater,
628 (Match::Search(_), Match::History { .. }) => return cmp::Ordering::Less,
629
630 _ => {}
631 }
632 }
633
634 let a_panel_match = match a.panel_match() {
635 Some(pm) => pm,
636 None => {
637 return if b.panel_match().is_some() {
638 cmp::Ordering::Less
639 } else {
640 cmp::Ordering::Equal
641 };
642 }
643 };
644
645 let b_panel_match = match b.panel_match() {
646 Some(pm) => pm,
647 None => return cmp::Ordering::Greater,
648 };
649
650 let a_in_filename = Self::is_filename_match(a_panel_match);
651 let b_in_filename = Self::is_filename_match(b_panel_match);
652
653 match (a_in_filename, b_in_filename) {
654 (true, false) => return cmp::Ordering::Greater,
655 (false, true) => return cmp::Ordering::Less,
656 _ => {} // Both are filename matches or both are path matches
657 }
658
659 a_panel_match.cmp(b_panel_match)
660 }
661
662 /// Determines if the match occurred within the filename rather than in the path
663 fn is_filename_match(panel_match: &ProjectPanelOrdMatch) -> bool {
664 if panel_match.0.positions.is_empty() {
665 return false;
666 }
667
668 if let Some(filename) = panel_match.0.path.file_name() {
669 let path_str = panel_match.0.path.as_str();
670
671 if let Some(filename_pos) = path_str.rfind(filename)
672 && panel_match.0.positions[0] >= filename_pos
673 {
674 let mut prev_position = panel_match.0.positions[0];
675 for p in &panel_match.0.positions[1..] {
676 if *p != prev_position + 1 {
677 return false;
678 }
679 prev_position = *p;
680 }
681 return true;
682 }
683 }
684
685 false
686 }
687}
688
689fn matching_history_items<'a>(
690 history_items: impl IntoIterator<Item = &'a FoundPath>,
691 currently_opened: Option<&'a FoundPath>,
692 query: &FileSearchQuery,
693) -> HashMap<Arc<RelPath>, Match> {
694 let mut candidates_paths = HashMap::default();
695
696 let history_items_by_worktrees = history_items
697 .into_iter()
698 .chain(currently_opened)
699 .filter_map(|found_path| {
700 let candidate = PathMatchCandidate {
701 is_dir: false, // You can't open directories as project items
702 path: &found_path.project.path,
703 // Only match history items names, otherwise their paths may match too many queries, producing false positives.
704 // E.g. `foo` would match both `something/foo/bar.rs` and `something/foo/foo.rs` and if the former is a history item,
705 // it would be shown first always, despite the latter being a better match.
706 char_bag: CharBag::from_iter(
707 found_path
708 .project
709 .path
710 .file_name()?
711 .to_string()
712 .to_lowercase()
713 .chars(),
714 ),
715 };
716 candidates_paths.insert(&found_path.project, found_path);
717 Some((found_path.project.worktree_id, candidate))
718 })
719 .fold(
720 HashMap::default(),
721 |mut candidates, (worktree_id, new_candidate)| {
722 candidates
723 .entry(worktree_id)
724 .or_insert_with(Vec::new)
725 .push(new_candidate);
726 candidates
727 },
728 );
729 let mut matching_history_paths = HashMap::default();
730 for (worktree, candidates) in history_items_by_worktrees {
731 let max_results = candidates.len() + 1;
732 matching_history_paths.extend(
733 fuzzy::match_fixed_path_set(
734 candidates,
735 worktree.to_usize(),
736 query.path_query(),
737 false,
738 max_results,
739 )
740 .into_iter()
741 .filter_map(|path_match| {
742 candidates_paths
743 .remove_entry(&ProjectPath {
744 worktree_id: WorktreeId::from_usize(path_match.worktree_id),
745 path: Arc::clone(&path_match.path),
746 })
747 .map(|(_, found_path)| {
748 (
749 Arc::clone(&path_match.path),
750 Match::History {
751 path: found_path.clone(),
752 panel_match: Some(ProjectPanelOrdMatch(path_match)),
753 },
754 )
755 })
756 }),
757 );
758 }
759 matching_history_paths
760}
761
762#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
763struct FoundPath {
764 project: ProjectPath,
765 absolute: PathBuf,
766}
767
768impl FoundPath {
769 fn new(project: ProjectPath, absolute: PathBuf) -> Self {
770 Self { project, absolute }
771 }
772}
773
774const MAX_RECENT_SELECTIONS: usize = 20;
775
776pub enum Event {
777 Selected(ProjectPath),
778 Dismissed,
779}
780
781#[derive(Debug, Clone)]
782struct FileSearchQuery {
783 raw_query: String,
784 file_query_end: Option<usize>,
785 path_position: PathWithPosition,
786}
787
788impl FileSearchQuery {
789 fn path_query(&self) -> &str {
790 match self.file_query_end {
791 Some(file_path_end) => &self.raw_query[..file_path_end],
792 None => &self.raw_query,
793 }
794 }
795}
796
797impl FileFinderDelegate {
798 fn new(
799 file_finder: WeakEntity<FileFinder>,
800 workspace: WeakEntity<Workspace>,
801 project: Entity<Project>,
802 currently_opened_path: Option<FoundPath>,
803 history_items: Vec<FoundPath>,
804 separate_history: bool,
805 window: &mut Window,
806 cx: &mut Context<FileFinder>,
807 ) -> Self {
808 Self::subscribe_to_updates(&project, window, cx);
809 Self {
810 file_finder,
811 workspace,
812 project,
813 search_count: 0,
814 latest_search_id: 0,
815 latest_search_did_cancel: false,
816 latest_search_query: None,
817 currently_opened_path,
818 matches: Matches::default(),
819 has_changed_selected_index: false,
820 selected_index: 0,
821 cancel_flag: Arc::new(AtomicBool::new(false)),
822 history_items,
823 separate_history,
824 first_update: true,
825 filter_popover_menu_handle: PopoverMenuHandle::default(),
826 split_popover_menu_handle: PopoverMenuHandle::default(),
827 focus_handle: cx.focus_handle(),
828 include_ignored: FileFinderSettings::get_global(cx).include_ignored,
829 include_ignored_refresh: Task::ready(()),
830 }
831 }
832
833 fn subscribe_to_updates(
834 project: &Entity<Project>,
835 window: &mut Window,
836 cx: &mut Context<FileFinder>,
837 ) {
838 cx.subscribe_in(project, window, |file_finder, _, event, window, cx| {
839 match event {
840 project::Event::WorktreeUpdatedEntries(_, _)
841 | project::Event::WorktreeAdded(_)
842 | project::Event::WorktreeRemoved(_) => file_finder
843 .picker
844 .update(cx, |picker, cx| picker.refresh(window, cx)),
845 _ => {}
846 };
847 })
848 .detach();
849 }
850
851 fn spawn_search(
852 &mut self,
853 query: FileSearchQuery,
854 window: &mut Window,
855 cx: &mut Context<Picker<Self>>,
856 ) -> Task<()> {
857 let relative_to = self
858 .currently_opened_path
859 .as_ref()
860 .map(|found_path| Arc::clone(&found_path.project.path));
861 let worktrees = self
862 .project
863 .read(cx)
864 .visible_worktrees(cx)
865 .collect::<Vec<_>>();
866 let include_root_name = worktrees.len() > 1;
867 let candidate_sets = worktrees
868 .into_iter()
869 .map(|worktree| {
870 let worktree = worktree.read(cx);
871 PathMatchCandidateSet {
872 snapshot: worktree.snapshot(),
873 include_ignored: self.include_ignored.unwrap_or_else(|| {
874 worktree.root_entry().is_some_and(|entry| entry.is_ignored)
875 }),
876 include_root_name,
877 candidates: project::Candidates::Files,
878 }
879 })
880 .collect::<Vec<_>>();
881
882 let search_id = util::post_inc(&mut self.search_count);
883 self.cancel_flag.store(true, atomic::Ordering::Release);
884 self.cancel_flag = Arc::new(AtomicBool::new(false));
885 let cancel_flag = self.cancel_flag.clone();
886 cx.spawn_in(window, async move |picker, cx| {
887 let matches = fuzzy::match_path_sets(
888 candidate_sets.as_slice(),
889 query.path_query(),
890 &relative_to,
891 false,
892 100,
893 &cancel_flag,
894 cx.background_executor().clone(),
895 )
896 .await
897 .into_iter()
898 .map(ProjectPanelOrdMatch);
899 let did_cancel = cancel_flag.load(atomic::Ordering::Acquire);
900 picker
901 .update(cx, |picker, cx| {
902 picker
903 .delegate
904 .set_search_matches(search_id, did_cancel, query, matches, cx)
905 })
906 .log_err();
907 })
908 }
909
910 fn set_search_matches(
911 &mut self,
912 search_id: usize,
913 did_cancel: bool,
914 query: FileSearchQuery,
915 matches: impl IntoIterator<Item = ProjectPanelOrdMatch>,
916 cx: &mut Context<Picker<Self>>,
917 ) {
918 if search_id >= self.latest_search_id {
919 self.latest_search_id = search_id;
920 let query_changed = Some(query.path_query())
921 != self
922 .latest_search_query
923 .as_ref()
924 .map(|query| query.path_query());
925 let extend_old_matches = self.latest_search_did_cancel && !query_changed;
926
927 let selected_match = if query_changed {
928 None
929 } else {
930 self.matches.get(self.selected_index).cloned()
931 };
932
933 self.matches.push_new_matches(
934 &self.history_items,
935 self.currently_opened_path.as_ref(),
936 Some(&query),
937 matches.into_iter(),
938 extend_old_matches,
939 );
940
941 let path_style = self.project.read(cx).path_style(cx);
942 let query_path = query.raw_query.as_str();
943 if let Ok(mut query_path) = RelPath::from_std_path(Path::new(query_path), path_style) {
944 let available_worktree = self
945 .project
946 .read(cx)
947 .visible_worktrees(cx)
948 .filter(|worktree| !worktree.read(cx).is_single_file())
949 .collect::<Vec<_>>();
950 let worktree_count = available_worktree.len();
951 let mut expect_worktree = available_worktree.first().cloned();
952 for worktree in available_worktree {
953 let worktree_root = worktree.read(cx).root_name();
954 if worktree_count > 1 {
955 if let Ok(suffix) = query_path.strip_prefix(worktree_root) {
956 query_path = suffix.into();
957 expect_worktree = Some(worktree);
958 break;
959 }
960 }
961 }
962
963 if let Some(FoundPath { ref project, .. }) = self.currently_opened_path {
964 let worktree_id = project.worktree_id;
965 expect_worktree = self.project.read(cx).worktree_for_id(worktree_id, cx);
966 }
967
968 if let Some(worktree) = expect_worktree {
969 let worktree = worktree.read(cx);
970 if worktree.entry_for_path(&query_path).is_none()
971 && !query.raw_query.ends_with("/")
972 && !(path_style.is_windows() && query.raw_query.ends_with("\\"))
973 {
974 self.matches.matches.push(Match::CreateNew(ProjectPath {
975 worktree_id: worktree.id(),
976 path: query_path,
977 }));
978 }
979 }
980 }
981
982 self.selected_index = selected_match.map_or_else(
983 || self.calculate_selected_index(cx),
984 |m| {
985 self.matches
986 .position(&m, self.currently_opened_path.as_ref())
987 .unwrap_or(0)
988 },
989 );
990
991 self.latest_search_query = Some(query);
992 self.latest_search_did_cancel = did_cancel;
993
994 cx.notify();
995 }
996 }
997
998 fn labels_for_match(
999 &self,
1000 path_match: &Match,
1001 window: &mut Window,
1002 cx: &App,
1003 ) -> (HighlightedLabel, HighlightedLabel) {
1004 let path_style = self.project.read(cx).path_style(cx);
1005 let (file_name, file_name_positions, mut full_path, mut full_path_positions) =
1006 match &path_match {
1007 Match::History {
1008 path: entry_path,
1009 panel_match,
1010 } => {
1011 let worktree_id = entry_path.project.worktree_id;
1012 let worktree = self
1013 .project
1014 .read(cx)
1015 .worktree_for_id(worktree_id, cx)
1016 .filter(|worktree| worktree.read(cx).is_visible());
1017
1018 if let Some(panel_match) = panel_match {
1019 self.labels_for_path_match(&panel_match.0, path_style)
1020 } else if let Some(worktree) = worktree {
1021 let full_path =
1022 worktree.read(cx).root_name().join(&entry_path.project.path);
1023 let mut components = full_path.components();
1024 let filename = components.next_back().unwrap_or("");
1025 let prefix = components.rest();
1026 (
1027 filename.to_string(),
1028 Vec::new(),
1029 prefix.display(path_style).to_string() + path_style.separator(),
1030 Vec::new(),
1031 )
1032 } else {
1033 (
1034 entry_path
1035 .absolute
1036 .file_name()
1037 .map_or(String::new(), |f| f.to_string_lossy().into_owned()),
1038 Vec::new(),
1039 entry_path.absolute.parent().map_or(String::new(), |path| {
1040 path.to_string_lossy().into_owned() + path_style.separator()
1041 }),
1042 Vec::new(),
1043 )
1044 }
1045 }
1046 Match::Search(path_match) => self.labels_for_path_match(&path_match.0, path_style),
1047 Match::CreateNew(project_path) => (
1048 format!("Create file: {}", project_path.path.display(path_style)),
1049 vec![],
1050 String::from(""),
1051 vec![],
1052 ),
1053 };
1054
1055 if file_name_positions.is_empty() {
1056 let user_home_path = util::paths::home_dir().to_string_lossy();
1057 if !user_home_path.is_empty() && full_path.starts_with(&*user_home_path) {
1058 full_path.replace_range(0..user_home_path.len(), "~");
1059 full_path_positions.retain_mut(|pos| {
1060 if *pos >= user_home_path.len() {
1061 *pos -= user_home_path.len();
1062 *pos += 1;
1063 true
1064 } else {
1065 false
1066 }
1067 })
1068 }
1069 }
1070
1071 if full_path.is_ascii() {
1072 let file_finder_settings = FileFinderSettings::get_global(cx);
1073 let max_width =
1074 FileFinder::modal_max_width(file_finder_settings.modal_max_width, window);
1075 let (normal_em, small_em) = {
1076 let style = window.text_style();
1077 let font_id = window.text_system().resolve_font(&style.font());
1078 let font_size = TextSize::Default.rems(cx).to_pixels(window.rem_size());
1079 let normal = cx
1080 .text_system()
1081 .em_width(font_id, font_size)
1082 .unwrap_or(px(16.));
1083 let font_size = TextSize::Small.rems(cx).to_pixels(window.rem_size());
1084 let small = cx
1085 .text_system()
1086 .em_width(font_id, font_size)
1087 .unwrap_or(px(10.));
1088 (normal, small)
1089 };
1090 let budget = full_path_budget(&file_name, normal_em, small_em, max_width);
1091 // If the computed budget is zero, we certainly won't be able to achieve it,
1092 // so no point trying to elide the path.
1093 if budget > 0 && full_path.len() > budget {
1094 let components = PathComponentSlice::new(&full_path);
1095 if let Some(elided_range) =
1096 components.elision_range(budget - 1, &full_path_positions)
1097 {
1098 let elided_len = elided_range.end - elided_range.start;
1099 let placeholder = "…";
1100 full_path_positions.retain_mut(|mat| {
1101 if *mat >= elided_range.end {
1102 *mat -= elided_len;
1103 *mat += placeholder.len();
1104 } else if *mat >= elided_range.start {
1105 return false;
1106 }
1107 true
1108 });
1109 full_path.replace_range(elided_range, placeholder);
1110 }
1111 }
1112 }
1113
1114 (
1115 HighlightedLabel::new(file_name, file_name_positions),
1116 HighlightedLabel::new(full_path, full_path_positions)
1117 .size(LabelSize::Small)
1118 .color(Color::Muted),
1119 )
1120 }
1121
1122 fn labels_for_path_match(
1123 &self,
1124 path_match: &PathMatch,
1125 path_style: PathStyle,
1126 ) -> (String, Vec<usize>, String, Vec<usize>) {
1127 let full_path = path_match.path_prefix.join(&path_match.path);
1128 let mut path_positions = path_match.positions.clone();
1129
1130 let file_name = full_path.file_name().unwrap_or("");
1131 let file_name_start = full_path.as_str().len() - file_name.len();
1132 let file_name_positions = path_positions
1133 .iter()
1134 .filter_map(|pos| {
1135 if pos >= &file_name_start {
1136 Some(pos - file_name_start)
1137 } else {
1138 None
1139 }
1140 })
1141 .collect::<Vec<_>>();
1142
1143 let full_path = full_path
1144 .display(path_style)
1145 .trim_end_matches(&file_name)
1146 .to_string();
1147 path_positions.retain(|idx| *idx < full_path.len());
1148
1149 debug_assert!(
1150 file_name_positions
1151 .iter()
1152 .all(|ix| file_name[*ix..].chars().next().is_some()),
1153 "invalid file name positions {file_name:?} {file_name_positions:?}"
1154 );
1155 debug_assert!(
1156 path_positions
1157 .iter()
1158 .all(|ix| full_path[*ix..].chars().next().is_some()),
1159 "invalid path positions {full_path:?} {path_positions:?}"
1160 );
1161
1162 (
1163 file_name.to_string(),
1164 file_name_positions,
1165 full_path,
1166 path_positions,
1167 )
1168 }
1169
1170 fn lookup_absolute_path(
1171 &self,
1172 query: FileSearchQuery,
1173 window: &mut Window,
1174 cx: &mut Context<Picker<Self>>,
1175 ) -> Task<()> {
1176 cx.spawn_in(window, async move |picker, cx| {
1177 let Some(project) = picker
1178 .read_with(cx, |picker, _| picker.delegate.project.clone())
1179 .log_err()
1180 else {
1181 return;
1182 };
1183
1184 let query_path = Path::new(query.path_query());
1185 let mut path_matches = Vec::new();
1186
1187 let abs_file_exists = if let Ok(task) = project.update(cx, |this, cx| {
1188 this.resolve_abs_file_path(query.path_query(), cx)
1189 }) {
1190 task.await.is_some()
1191 } else {
1192 false
1193 };
1194
1195 if abs_file_exists {
1196 let update_result = project
1197 .update(cx, |project, cx| {
1198 if let Some((worktree, relative_path)) =
1199 project.find_worktree(query_path, cx)
1200 {
1201 path_matches.push(ProjectPanelOrdMatch(PathMatch {
1202 score: 1.0,
1203 positions: Vec::new(),
1204 worktree_id: worktree.read(cx).id().to_usize(),
1205 path: relative_path,
1206 path_prefix: RelPath::empty().into(),
1207 is_dir: false, // File finder doesn't support directories
1208 distance_to_relative_ancestor: usize::MAX,
1209 }));
1210 }
1211 })
1212 .log_err();
1213 if update_result.is_none() {
1214 return;
1215 }
1216 }
1217
1218 picker
1219 .update_in(cx, |picker, _, cx| {
1220 let picker_delegate = &mut picker.delegate;
1221 let search_id = util::post_inc(&mut picker_delegate.search_count);
1222 picker_delegate.set_search_matches(search_id, false, query, path_matches, cx);
1223
1224 anyhow::Ok(())
1225 })
1226 .log_err();
1227 })
1228 }
1229
1230 /// Skips first history match (that is displayed topmost) if it's currently opened.
1231 fn calculate_selected_index(&self, cx: &mut Context<Picker<Self>>) -> usize {
1232 if FileFinderSettings::get_global(cx).skip_focus_for_active_in_search
1233 && let Some(Match::History { path, .. }) = self.matches.get(0)
1234 && Some(path) == self.currently_opened_path.as_ref()
1235 {
1236 let elements_after_first = self.matches.len() - 1;
1237 if elements_after_first > 0 {
1238 return 1;
1239 }
1240 }
1241
1242 0
1243 }
1244
1245 fn key_context(&self, window: &Window, cx: &App) -> KeyContext {
1246 let mut key_context = KeyContext::new_with_defaults();
1247 key_context.add("FileFinder");
1248
1249 if self.filter_popover_menu_handle.is_focused(window, cx) {
1250 key_context.add("filter_menu_open");
1251 }
1252
1253 if self.split_popover_menu_handle.is_focused(window, cx) {
1254 key_context.add("split_menu_open");
1255 }
1256 key_context
1257 }
1258}
1259
1260fn full_path_budget(
1261 file_name: &str,
1262 normal_em: Pixels,
1263 small_em: Pixels,
1264 max_width: Pixels,
1265) -> usize {
1266 (((max_width / 0.8) - file_name.len() * normal_em) / small_em) as usize
1267}
1268
1269impl PickerDelegate for FileFinderDelegate {
1270 type ListItem = ListItem;
1271
1272 fn placeholder_text(&self, _window: &mut Window, _cx: &mut App) -> Arc<str> {
1273 "Search project files...".into()
1274 }
1275
1276 fn match_count(&self) -> usize {
1277 self.matches.len()
1278 }
1279
1280 fn selected_index(&self) -> usize {
1281 self.selected_index
1282 }
1283
1284 fn set_selected_index(&mut self, ix: usize, _: &mut Window, cx: &mut Context<Picker<Self>>) {
1285 self.has_changed_selected_index = true;
1286 self.selected_index = ix;
1287 cx.notify();
1288 }
1289
1290 fn separators_after_indices(&self) -> Vec<usize> {
1291 if self.separate_history {
1292 let first_non_history_index = self
1293 .matches
1294 .matches
1295 .iter()
1296 .enumerate()
1297 .find(|(_, m)| !matches!(m, Match::History { .. }))
1298 .map(|(i, _)| i);
1299 if let Some(first_non_history_index) = first_non_history_index
1300 && first_non_history_index > 0
1301 {
1302 return vec![first_non_history_index - 1];
1303 }
1304 }
1305 Vec::new()
1306 }
1307
1308 fn update_matches(
1309 &mut self,
1310 raw_query: String,
1311 window: &mut Window,
1312 cx: &mut Context<Picker<Self>>,
1313 ) -> Task<()> {
1314 let raw_query = raw_query.replace(' ', "");
1315 let raw_query = raw_query.trim();
1316
1317 let raw_query = match &raw_query.get(0..2) {
1318 Some(".\\") | Some("./") => &raw_query[2..],
1319 Some("a\\") | Some("a/") => {
1320 if self
1321 .workspace
1322 .upgrade()
1323 .into_iter()
1324 .flat_map(|workspace| workspace.read(cx).worktrees(cx))
1325 .all(|worktree| {
1326 worktree
1327 .read(cx)
1328 .entry_for_path(RelPath::new("a").unwrap())
1329 .is_none_or(|entry| !entry.is_dir())
1330 })
1331 {
1332 &raw_query[2..]
1333 } else {
1334 raw_query
1335 }
1336 }
1337 Some("b\\") | Some("b/") => {
1338 if self
1339 .workspace
1340 .upgrade()
1341 .into_iter()
1342 .flat_map(|workspace| workspace.read(cx).worktrees(cx))
1343 .all(|worktree| {
1344 worktree
1345 .read(cx)
1346 .entry_for_path(RelPath::new("b").unwrap())
1347 .is_none_or(|entry| !entry.is_dir())
1348 })
1349 {
1350 &raw_query[2..]
1351 } else {
1352 raw_query
1353 }
1354 }
1355 _ => raw_query,
1356 };
1357
1358 if raw_query.is_empty() {
1359 // if there was no query before, and we already have some (history) matches
1360 // there's no need to update anything, since nothing has changed.
1361 // We also want to populate matches set from history entries on the first update.
1362 if self.latest_search_query.is_some() || self.first_update {
1363 let project = self.project.read(cx);
1364
1365 self.latest_search_id = post_inc(&mut self.search_count);
1366 self.latest_search_query = None;
1367 self.matches = Matches {
1368 separate_history: self.separate_history,
1369 ..Matches::default()
1370 };
1371 self.matches.push_new_matches(
1372 self.history_items.iter().filter(|history_item| {
1373 project
1374 .worktree_for_id(history_item.project.worktree_id, cx)
1375 .is_some()
1376 || project.is_local()
1377 || project.is_via_remote_server()
1378 }),
1379 self.currently_opened_path.as_ref(),
1380 None,
1381 None.into_iter(),
1382 false,
1383 );
1384
1385 self.first_update = false;
1386 self.selected_index = 0;
1387 }
1388 cx.notify();
1389 Task::ready(())
1390 } else {
1391 let path_position = PathWithPosition::parse_str(raw_query);
1392 let raw_query = raw_query.trim().trim_end_matches(':').to_owned();
1393 let path = path_position.path.to_str();
1394 let path_trimmed = path.unwrap_or(&raw_query).trim_end_matches(':');
1395 let file_query_end = if path_trimmed == raw_query {
1396 None
1397 } else {
1398 // Safe to unwrap as we won't get here when the unwrap in if fails
1399 Some(path.unwrap().len())
1400 };
1401
1402 let query = FileSearchQuery {
1403 raw_query,
1404 file_query_end,
1405 path_position,
1406 };
1407
1408 if Path::new(query.path_query()).is_absolute() {
1409 self.lookup_absolute_path(query, window, cx)
1410 } else {
1411 self.spawn_search(query, window, cx)
1412 }
1413 }
1414 }
1415
1416 fn confirm(
1417 &mut self,
1418 secondary: bool,
1419 window: &mut Window,
1420 cx: &mut Context<Picker<FileFinderDelegate>>,
1421 ) {
1422 if let Some(m) = self.matches.get(self.selected_index())
1423 && let Some(workspace) = self.workspace.upgrade()
1424 {
1425 let open_task = workspace.update(cx, |workspace, cx| {
1426 let split_or_open =
1427 |workspace: &mut Workspace,
1428 project_path,
1429 window: &mut Window,
1430 cx: &mut Context<Workspace>| {
1431 let allow_preview =
1432 PreviewTabsSettings::get_global(cx).enable_preview_from_file_finder;
1433 if secondary {
1434 workspace.split_path_preview(
1435 project_path,
1436 allow_preview,
1437 None,
1438 window,
1439 cx,
1440 )
1441 } else {
1442 workspace.open_path_preview(
1443 project_path,
1444 None,
1445 true,
1446 allow_preview,
1447 true,
1448 window,
1449 cx,
1450 )
1451 }
1452 };
1453 match &m {
1454 Match::CreateNew(project_path) => {
1455 // Create a new file with the given filename
1456 if secondary {
1457 workspace.split_path_preview(
1458 project_path.clone(),
1459 false,
1460 None,
1461 window,
1462 cx,
1463 )
1464 } else {
1465 workspace.open_path_preview(
1466 project_path.clone(),
1467 None,
1468 true,
1469 false,
1470 true,
1471 window,
1472 cx,
1473 )
1474 }
1475 }
1476
1477 Match::History { path, .. } => {
1478 let worktree_id = path.project.worktree_id;
1479 if workspace
1480 .project()
1481 .read(cx)
1482 .worktree_for_id(worktree_id, cx)
1483 .is_some()
1484 {
1485 split_or_open(
1486 workspace,
1487 ProjectPath {
1488 worktree_id,
1489 path: Arc::clone(&path.project.path),
1490 },
1491 window,
1492 cx,
1493 )
1494 } else if secondary {
1495 workspace.split_abs_path(path.absolute.clone(), false, window, cx)
1496 } else {
1497 workspace.open_abs_path(
1498 path.absolute.clone(),
1499 OpenOptions {
1500 visible: Some(OpenVisible::None),
1501 ..Default::default()
1502 },
1503 window,
1504 cx,
1505 )
1506 }
1507 }
1508 Match::Search(m) => split_or_open(
1509 workspace,
1510 ProjectPath {
1511 worktree_id: WorktreeId::from_usize(m.0.worktree_id),
1512 path: m.0.path.clone(),
1513 },
1514 window,
1515 cx,
1516 ),
1517 }
1518 });
1519
1520 let row = self
1521 .latest_search_query
1522 .as_ref()
1523 .and_then(|query| query.path_position.row)
1524 .map(|row| row.saturating_sub(1));
1525 let col = self
1526 .latest_search_query
1527 .as_ref()
1528 .and_then(|query| query.path_position.column)
1529 .unwrap_or(0)
1530 .saturating_sub(1);
1531 let finder = self.file_finder.clone();
1532
1533 cx.spawn_in(window, async move |_, cx| {
1534 let item = open_task.await.notify_async_err(cx)?;
1535 if let Some(row) = row
1536 && let Some(active_editor) = item.downcast::<Editor>()
1537 {
1538 active_editor
1539 .downgrade()
1540 .update_in(cx, |editor, window, cx| {
1541 editor.go_to_singleton_buffer_point(Point::new(row, col), window, cx);
1542 })
1543 .log_err();
1544 }
1545 finder.update(cx, |_, cx| cx.emit(DismissEvent)).ok()?;
1546
1547 Some(())
1548 })
1549 .detach();
1550 }
1551 }
1552
1553 fn dismissed(&mut self, _: &mut Window, cx: &mut Context<Picker<FileFinderDelegate>>) {
1554 self.file_finder
1555 .update(cx, |_, cx| cx.emit(DismissEvent))
1556 .log_err();
1557 }
1558
1559 fn render_match(
1560 &self,
1561 ix: usize,
1562 selected: bool,
1563 window: &mut Window,
1564 cx: &mut Context<Picker<Self>>,
1565 ) -> Option<Self::ListItem> {
1566 let settings = FileFinderSettings::get_global(cx);
1567
1568 let path_match = self.matches.get(ix)?;
1569
1570 let history_icon = match &path_match {
1571 Match::History { .. } => Icon::new(IconName::HistoryRerun)
1572 .color(Color::Muted)
1573 .size(IconSize::Small)
1574 .into_any_element(),
1575 Match::Search(_) => v_flex()
1576 .flex_none()
1577 .size(IconSize::Small.rems())
1578 .into_any_element(),
1579 Match::CreateNew(_) => Icon::new(IconName::Plus)
1580 .color(Color::Muted)
1581 .size(IconSize::Small)
1582 .into_any_element(),
1583 };
1584 let (file_name_label, full_path_label) = self.labels_for_match(path_match, window, cx);
1585
1586 let file_icon = maybe!({
1587 if !settings.file_icons {
1588 return None;
1589 }
1590 let abs_path = path_match.abs_path(&self.project, cx)?;
1591 let file_name = abs_path.file_name()?;
1592 let icon = FileIcons::get_icon(file_name.as_ref(), cx)?;
1593 Some(Icon::from_path(icon).color(Color::Muted))
1594 });
1595
1596 Some(
1597 ListItem::new(ix)
1598 .spacing(ListItemSpacing::Sparse)
1599 .start_slot::<Icon>(file_icon)
1600 .end_slot::<AnyElement>(history_icon)
1601 .inset(true)
1602 .toggle_state(selected)
1603 .child(
1604 h_flex()
1605 .gap_2()
1606 .py_px()
1607 .child(file_name_label)
1608 .child(full_path_label),
1609 ),
1610 )
1611 }
1612
1613 fn render_footer(
1614 &self,
1615 window: &mut Window,
1616 cx: &mut Context<Picker<Self>>,
1617 ) -> Option<AnyElement> {
1618 let focus_handle = self.focus_handle.clone();
1619
1620 Some(
1621 h_flex()
1622 .w_full()
1623 .p_1p5()
1624 .justify_between()
1625 .border_t_1()
1626 .border_color(cx.theme().colors().border_variant)
1627 .child(
1628 PopoverMenu::new("filter-menu-popover")
1629 .with_handle(self.filter_popover_menu_handle.clone())
1630 .attach(gpui::Corner::BottomRight)
1631 .anchor(gpui::Corner::BottomLeft)
1632 .offset(gpui::Point {
1633 x: px(1.0),
1634 y: px(1.0),
1635 })
1636 .trigger_with_tooltip(
1637 IconButton::new("filter-trigger", IconName::Sliders)
1638 .icon_size(IconSize::Small)
1639 .icon_size(IconSize::Small)
1640 .toggle_state(self.include_ignored.unwrap_or(false))
1641 .when(self.include_ignored.is_some(), |this| {
1642 this.indicator(Indicator::dot().color(Color::Info))
1643 }),
1644 {
1645 let focus_handle = focus_handle.clone();
1646 move |window, cx| {
1647 Tooltip::for_action_in(
1648 "Filter Options",
1649 &ToggleFilterMenu,
1650 &focus_handle,
1651 window,
1652 cx,
1653 )
1654 }
1655 },
1656 )
1657 .menu({
1658 let focus_handle = focus_handle.clone();
1659 let include_ignored = self.include_ignored;
1660
1661 move |window, cx| {
1662 Some(ContextMenu::build(window, cx, {
1663 let focus_handle = focus_handle.clone();
1664 move |menu, _, _| {
1665 menu.context(focus_handle.clone())
1666 .header("Filter Options")
1667 .toggleable_entry(
1668 "Include Ignored Files",
1669 include_ignored.unwrap_or(false),
1670 ui::IconPosition::End,
1671 Some(ToggleIncludeIgnored.boxed_clone()),
1672 move |window, cx| {
1673 window.focus(&focus_handle);
1674 window.dispatch_action(
1675 ToggleIncludeIgnored.boxed_clone(),
1676 cx,
1677 );
1678 },
1679 )
1680 }
1681 }))
1682 }
1683 }),
1684 )
1685 .child(
1686 h_flex()
1687 .gap_0p5()
1688 .child(
1689 PopoverMenu::new("split-menu-popover")
1690 .with_handle(self.split_popover_menu_handle.clone())
1691 .attach(gpui::Corner::BottomRight)
1692 .anchor(gpui::Corner::BottomLeft)
1693 .offset(gpui::Point {
1694 x: px(1.0),
1695 y: px(1.0),
1696 })
1697 .trigger(
1698 ButtonLike::new("split-trigger")
1699 .child(Label::new("Split…"))
1700 .selected_style(ButtonStyle::Tinted(TintColor::Accent))
1701 .children(
1702 KeyBinding::for_action_in(
1703 &ToggleSplitMenu,
1704 &focus_handle,
1705 window,
1706 cx,
1707 )
1708 .map(|kb| kb.size(rems_from_px(12.))),
1709 ),
1710 )
1711 .menu({
1712 let focus_handle = focus_handle.clone();
1713
1714 move |window, cx| {
1715 Some(ContextMenu::build(window, cx, {
1716 let focus_handle = focus_handle.clone();
1717 move |menu, _, _| {
1718 menu.context(focus_handle)
1719 .action(
1720 "Split Left",
1721 pane::SplitLeft.boxed_clone(),
1722 )
1723 .action(
1724 "Split Right",
1725 pane::SplitRight.boxed_clone(),
1726 )
1727 .action("Split Up", pane::SplitUp.boxed_clone())
1728 .action(
1729 "Split Down",
1730 pane::SplitDown.boxed_clone(),
1731 )
1732 }
1733 }))
1734 }
1735 }),
1736 )
1737 .child(
1738 Button::new("open-selection", "Open")
1739 .key_binding(
1740 KeyBinding::for_action_in(
1741 &menu::Confirm,
1742 &focus_handle,
1743 window,
1744 cx,
1745 )
1746 .map(|kb| kb.size(rems_from_px(12.))),
1747 )
1748 .on_click(|_, window, cx| {
1749 window.dispatch_action(menu::Confirm.boxed_clone(), cx)
1750 }),
1751 ),
1752 )
1753 .into_any(),
1754 )
1755 }
1756}
1757
1758#[derive(Clone, Debug, PartialEq, Eq)]
1759struct PathComponentSlice<'a> {
1760 path: Cow<'a, Path>,
1761 path_str: Cow<'a, str>,
1762 component_ranges: Vec<(Component<'a>, Range<usize>)>,
1763}
1764
1765impl<'a> PathComponentSlice<'a> {
1766 fn new(path: &'a str) -> Self {
1767 let trimmed_path = Path::new(path).components().as_path().as_os_str();
1768 let mut component_ranges = Vec::new();
1769 let mut components = Path::new(trimmed_path).components();
1770 let len = trimmed_path.as_encoded_bytes().len();
1771 let mut pos = 0;
1772 while let Some(component) = components.next() {
1773 component_ranges.push((component, pos..0));
1774 pos = len - components.as_path().as_os_str().as_encoded_bytes().len();
1775 }
1776 for ((_, range), ancestor) in component_ranges
1777 .iter_mut()
1778 .rev()
1779 .zip(Path::new(trimmed_path).ancestors())
1780 {
1781 range.end = ancestor.as_os_str().as_encoded_bytes().len();
1782 }
1783 Self {
1784 path: Cow::Borrowed(Path::new(path)),
1785 path_str: Cow::Borrowed(path),
1786 component_ranges,
1787 }
1788 }
1789
1790 fn elision_range(&self, budget: usize, matches: &[usize]) -> Option<Range<usize>> {
1791 let eligible_range = {
1792 assert!(matches.windows(2).all(|w| w[0] <= w[1]));
1793 let mut matches = matches.iter().copied().peekable();
1794 let mut longest: Option<Range<usize>> = None;
1795 let mut cur = 0..0;
1796 let mut seen_normal = false;
1797 for (i, (component, range)) in self.component_ranges.iter().enumerate() {
1798 let is_normal = matches!(component, Component::Normal(_));
1799 let is_first_normal = is_normal && !seen_normal;
1800 seen_normal |= is_normal;
1801 let is_last = i == self.component_ranges.len() - 1;
1802 let contains_match = matches.peek().is_some_and(|mat| range.contains(mat));
1803 if contains_match {
1804 matches.next();
1805 }
1806 if is_first_normal || is_last || !is_normal || contains_match {
1807 if longest
1808 .as_ref()
1809 .is_none_or(|old| old.end - old.start <= cur.end - cur.start)
1810 {
1811 longest = Some(cur);
1812 }
1813 cur = i + 1..i + 1;
1814 } else {
1815 cur.end = i + 1;
1816 }
1817 }
1818 if longest
1819 .as_ref()
1820 .is_none_or(|old| old.end - old.start <= cur.end - cur.start)
1821 {
1822 longest = Some(cur);
1823 }
1824 longest
1825 };
1826
1827 let eligible_range = eligible_range?;
1828 assert!(eligible_range.start <= eligible_range.end);
1829 if eligible_range.is_empty() {
1830 return None;
1831 }
1832
1833 let elided_range: Range<usize> = {
1834 let byte_range = self.component_ranges[eligible_range.start].1.start
1835 ..self.component_ranges[eligible_range.end - 1].1.end;
1836 let midpoint = self.path_str.len() / 2;
1837 let distance_from_start = byte_range.start.abs_diff(midpoint);
1838 let distance_from_end = byte_range.end.abs_diff(midpoint);
1839 let pick_from_end = distance_from_start > distance_from_end;
1840 let mut len_with_elision = self.path_str.len();
1841 let mut i = eligible_range.start;
1842 while i < eligible_range.end {
1843 let x = if pick_from_end {
1844 eligible_range.end - i + eligible_range.start - 1
1845 } else {
1846 i
1847 };
1848 len_with_elision -= self.component_ranges[x]
1849 .0
1850 .as_os_str()
1851 .as_encoded_bytes()
1852 .len()
1853 + 1;
1854 if len_with_elision <= budget {
1855 break;
1856 }
1857 i += 1;
1858 }
1859 if len_with_elision > budget {
1860 return None;
1861 } else if pick_from_end {
1862 let x = eligible_range.end - i + eligible_range.start - 1;
1863 x..eligible_range.end
1864 } else {
1865 let x = i;
1866 eligible_range.start..x + 1
1867 }
1868 };
1869
1870 let byte_range = self.component_ranges[elided_range.start].1.start
1871 ..self.component_ranges[elided_range.end - 1].1.end;
1872 Some(byte_range)
1873 }
1874}