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_unix_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::new(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 = Cow::Owned(suffix.to_owned());
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.into_arc(),
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_unix_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(".\\" | "./") => &raw_query[2..],
1319 Some(prefix @ ("a\\" | "a/" | "b\\" | "b/")) => {
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::unix(prefix.split_at(1).0).unwrap())
1329 .is_none_or(|entry| !entry.is_dir())
1330 })
1331 {
1332 &raw_query[2..]
1333 } else {
1334 raw_query
1335 }
1336 }
1337 _ => raw_query,
1338 };
1339
1340 if raw_query.is_empty() {
1341 // if there was no query before, and we already have some (history) matches
1342 // there's no need to update anything, since nothing has changed.
1343 // We also want to populate matches set from history entries on the first update.
1344 if self.latest_search_query.is_some() || self.first_update {
1345 let project = self.project.read(cx);
1346
1347 self.latest_search_id = post_inc(&mut self.search_count);
1348 self.latest_search_query = None;
1349 self.matches = Matches {
1350 separate_history: self.separate_history,
1351 ..Matches::default()
1352 };
1353 self.matches.push_new_matches(
1354 self.history_items.iter().filter(|history_item| {
1355 project
1356 .worktree_for_id(history_item.project.worktree_id, cx)
1357 .is_some()
1358 || project.is_local()
1359 || project.is_via_remote_server()
1360 }),
1361 self.currently_opened_path.as_ref(),
1362 None,
1363 None.into_iter(),
1364 false,
1365 );
1366
1367 self.first_update = false;
1368 self.selected_index = 0;
1369 }
1370 cx.notify();
1371 Task::ready(())
1372 } else {
1373 let path_position = PathWithPosition::parse_str(raw_query);
1374 let raw_query = raw_query.trim().trim_end_matches(':').to_owned();
1375 let path = path_position.path.to_str();
1376 let path_trimmed = path.unwrap_or(&raw_query).trim_end_matches(':');
1377 let file_query_end = if path_trimmed == raw_query {
1378 None
1379 } else {
1380 // Safe to unwrap as we won't get here when the unwrap in if fails
1381 Some(path.unwrap().len())
1382 };
1383
1384 let query = FileSearchQuery {
1385 raw_query,
1386 file_query_end,
1387 path_position,
1388 };
1389
1390 if Path::new(query.path_query()).is_absolute() {
1391 self.lookup_absolute_path(query, window, cx)
1392 } else {
1393 self.spawn_search(query, window, cx)
1394 }
1395 }
1396 }
1397
1398 fn confirm(
1399 &mut self,
1400 secondary: bool,
1401 window: &mut Window,
1402 cx: &mut Context<Picker<FileFinderDelegate>>,
1403 ) {
1404 if let Some(m) = self.matches.get(self.selected_index())
1405 && let Some(workspace) = self.workspace.upgrade()
1406 {
1407 let open_task = workspace.update(cx, |workspace, cx| {
1408 let split_or_open =
1409 |workspace: &mut Workspace,
1410 project_path,
1411 window: &mut Window,
1412 cx: &mut Context<Workspace>| {
1413 let allow_preview =
1414 PreviewTabsSettings::get_global(cx).enable_preview_from_file_finder;
1415 if secondary {
1416 workspace.split_path_preview(
1417 project_path,
1418 allow_preview,
1419 None,
1420 window,
1421 cx,
1422 )
1423 } else {
1424 workspace.open_path_preview(
1425 project_path,
1426 None,
1427 true,
1428 allow_preview,
1429 true,
1430 window,
1431 cx,
1432 )
1433 }
1434 };
1435 match &m {
1436 Match::CreateNew(project_path) => {
1437 // Create a new file with the given filename
1438 if secondary {
1439 workspace.split_path_preview(
1440 project_path.clone(),
1441 false,
1442 None,
1443 window,
1444 cx,
1445 )
1446 } else {
1447 workspace.open_path_preview(
1448 project_path.clone(),
1449 None,
1450 true,
1451 false,
1452 true,
1453 window,
1454 cx,
1455 )
1456 }
1457 }
1458
1459 Match::History { path, .. } => {
1460 let worktree_id = path.project.worktree_id;
1461 if workspace
1462 .project()
1463 .read(cx)
1464 .worktree_for_id(worktree_id, cx)
1465 .is_some()
1466 {
1467 split_or_open(
1468 workspace,
1469 ProjectPath {
1470 worktree_id,
1471 path: Arc::clone(&path.project.path),
1472 },
1473 window,
1474 cx,
1475 )
1476 } else if secondary {
1477 workspace.split_abs_path(path.absolute.clone(), false, window, cx)
1478 } else {
1479 workspace.open_abs_path(
1480 path.absolute.clone(),
1481 OpenOptions {
1482 visible: Some(OpenVisible::None),
1483 ..Default::default()
1484 },
1485 window,
1486 cx,
1487 )
1488 }
1489 }
1490 Match::Search(m) => split_or_open(
1491 workspace,
1492 ProjectPath {
1493 worktree_id: WorktreeId::from_usize(m.0.worktree_id),
1494 path: m.0.path.clone(),
1495 },
1496 window,
1497 cx,
1498 ),
1499 }
1500 });
1501
1502 let row = self
1503 .latest_search_query
1504 .as_ref()
1505 .and_then(|query| query.path_position.row)
1506 .map(|row| row.saturating_sub(1));
1507 let col = self
1508 .latest_search_query
1509 .as_ref()
1510 .and_then(|query| query.path_position.column)
1511 .unwrap_or(0)
1512 .saturating_sub(1);
1513 let finder = self.file_finder.clone();
1514
1515 cx.spawn_in(window, async move |_, cx| {
1516 let item = open_task.await.notify_async_err(cx)?;
1517 if let Some(row) = row
1518 && let Some(active_editor) = item.downcast::<Editor>()
1519 {
1520 active_editor
1521 .downgrade()
1522 .update_in(cx, |editor, window, cx| {
1523 editor.go_to_singleton_buffer_point(Point::new(row, col), window, cx);
1524 })
1525 .log_err();
1526 }
1527 finder.update(cx, |_, cx| cx.emit(DismissEvent)).ok()?;
1528
1529 Some(())
1530 })
1531 .detach();
1532 }
1533 }
1534
1535 fn dismissed(&mut self, _: &mut Window, cx: &mut Context<Picker<FileFinderDelegate>>) {
1536 self.file_finder
1537 .update(cx, |_, cx| cx.emit(DismissEvent))
1538 .log_err();
1539 }
1540
1541 fn render_match(
1542 &self,
1543 ix: usize,
1544 selected: bool,
1545 window: &mut Window,
1546 cx: &mut Context<Picker<Self>>,
1547 ) -> Option<Self::ListItem> {
1548 let settings = FileFinderSettings::get_global(cx);
1549
1550 let path_match = self.matches.get(ix)?;
1551
1552 let history_icon = match &path_match {
1553 Match::History { .. } => Icon::new(IconName::HistoryRerun)
1554 .color(Color::Muted)
1555 .size(IconSize::Small)
1556 .into_any_element(),
1557 Match::Search(_) => v_flex()
1558 .flex_none()
1559 .size(IconSize::Small.rems())
1560 .into_any_element(),
1561 Match::CreateNew(_) => Icon::new(IconName::Plus)
1562 .color(Color::Muted)
1563 .size(IconSize::Small)
1564 .into_any_element(),
1565 };
1566 let (file_name_label, full_path_label) = self.labels_for_match(path_match, window, cx);
1567
1568 let file_icon = maybe!({
1569 if !settings.file_icons {
1570 return None;
1571 }
1572 let abs_path = path_match.abs_path(&self.project, cx)?;
1573 let file_name = abs_path.file_name()?;
1574 let icon = FileIcons::get_icon(file_name.as_ref(), cx)?;
1575 Some(Icon::from_path(icon).color(Color::Muted))
1576 });
1577
1578 Some(
1579 ListItem::new(ix)
1580 .spacing(ListItemSpacing::Sparse)
1581 .start_slot::<Icon>(file_icon)
1582 .end_slot::<AnyElement>(history_icon)
1583 .inset(true)
1584 .toggle_state(selected)
1585 .child(
1586 h_flex()
1587 .gap_2()
1588 .py_px()
1589 .child(file_name_label)
1590 .child(full_path_label),
1591 ),
1592 )
1593 }
1594
1595 fn render_footer(
1596 &self,
1597 window: &mut Window,
1598 cx: &mut Context<Picker<Self>>,
1599 ) -> Option<AnyElement> {
1600 let focus_handle = self.focus_handle.clone();
1601
1602 Some(
1603 h_flex()
1604 .w_full()
1605 .p_1p5()
1606 .justify_between()
1607 .border_t_1()
1608 .border_color(cx.theme().colors().border_variant)
1609 .child(
1610 PopoverMenu::new("filter-menu-popover")
1611 .with_handle(self.filter_popover_menu_handle.clone())
1612 .attach(gpui::Corner::BottomRight)
1613 .anchor(gpui::Corner::BottomLeft)
1614 .offset(gpui::Point {
1615 x: px(1.0),
1616 y: px(1.0),
1617 })
1618 .trigger_with_tooltip(
1619 IconButton::new("filter-trigger", IconName::Sliders)
1620 .icon_size(IconSize::Small)
1621 .icon_size(IconSize::Small)
1622 .toggle_state(self.include_ignored.unwrap_or(false))
1623 .when(self.include_ignored.is_some(), |this| {
1624 this.indicator(Indicator::dot().color(Color::Info))
1625 }),
1626 {
1627 let focus_handle = focus_handle.clone();
1628 move |window, cx| {
1629 Tooltip::for_action_in(
1630 "Filter Options",
1631 &ToggleFilterMenu,
1632 &focus_handle,
1633 window,
1634 cx,
1635 )
1636 }
1637 },
1638 )
1639 .menu({
1640 let focus_handle = focus_handle.clone();
1641 let include_ignored = self.include_ignored;
1642
1643 move |window, cx| {
1644 Some(ContextMenu::build(window, cx, {
1645 let focus_handle = focus_handle.clone();
1646 move |menu, _, _| {
1647 menu.context(focus_handle.clone())
1648 .header("Filter Options")
1649 .toggleable_entry(
1650 "Include Ignored Files",
1651 include_ignored.unwrap_or(false),
1652 ui::IconPosition::End,
1653 Some(ToggleIncludeIgnored.boxed_clone()),
1654 move |window, cx| {
1655 window.focus(&focus_handle);
1656 window.dispatch_action(
1657 ToggleIncludeIgnored.boxed_clone(),
1658 cx,
1659 );
1660 },
1661 )
1662 }
1663 }))
1664 }
1665 }),
1666 )
1667 .child(
1668 h_flex()
1669 .gap_0p5()
1670 .child(
1671 PopoverMenu::new("split-menu-popover")
1672 .with_handle(self.split_popover_menu_handle.clone())
1673 .attach(gpui::Corner::BottomRight)
1674 .anchor(gpui::Corner::BottomLeft)
1675 .offset(gpui::Point {
1676 x: px(1.0),
1677 y: px(1.0),
1678 })
1679 .trigger(
1680 ButtonLike::new("split-trigger")
1681 .child(Label::new("Split…"))
1682 .selected_style(ButtonStyle::Tinted(TintColor::Accent))
1683 .children(
1684 KeyBinding::for_action_in(
1685 &ToggleSplitMenu,
1686 &focus_handle,
1687 window,
1688 cx,
1689 )
1690 .map(|kb| kb.size(rems_from_px(12.))),
1691 ),
1692 )
1693 .menu({
1694 let focus_handle = focus_handle.clone();
1695
1696 move |window, cx| {
1697 Some(ContextMenu::build(window, cx, {
1698 let focus_handle = focus_handle.clone();
1699 move |menu, _, _| {
1700 menu.context(focus_handle)
1701 .action(
1702 "Split Left",
1703 pane::SplitLeft.boxed_clone(),
1704 )
1705 .action(
1706 "Split Right",
1707 pane::SplitRight.boxed_clone(),
1708 )
1709 .action("Split Up", pane::SplitUp.boxed_clone())
1710 .action(
1711 "Split Down",
1712 pane::SplitDown.boxed_clone(),
1713 )
1714 }
1715 }))
1716 }
1717 }),
1718 )
1719 .child(
1720 Button::new("open-selection", "Open")
1721 .key_binding(
1722 KeyBinding::for_action_in(
1723 &menu::Confirm,
1724 &focus_handle,
1725 window,
1726 cx,
1727 )
1728 .map(|kb| kb.size(rems_from_px(12.))),
1729 )
1730 .on_click(|_, window, cx| {
1731 window.dispatch_action(menu::Confirm.boxed_clone(), cx)
1732 }),
1733 ),
1734 )
1735 .into_any(),
1736 )
1737 }
1738}
1739
1740#[derive(Clone, Debug, PartialEq, Eq)]
1741struct PathComponentSlice<'a> {
1742 path: Cow<'a, Path>,
1743 path_str: Cow<'a, str>,
1744 component_ranges: Vec<(Component<'a>, Range<usize>)>,
1745}
1746
1747impl<'a> PathComponentSlice<'a> {
1748 fn new(path: &'a str) -> Self {
1749 let trimmed_path = Path::new(path).components().as_path().as_os_str();
1750 let mut component_ranges = Vec::new();
1751 let mut components = Path::new(trimmed_path).components();
1752 let len = trimmed_path.as_encoded_bytes().len();
1753 let mut pos = 0;
1754 while let Some(component) = components.next() {
1755 component_ranges.push((component, pos..0));
1756 pos = len - components.as_path().as_os_str().as_encoded_bytes().len();
1757 }
1758 for ((_, range), ancestor) in component_ranges
1759 .iter_mut()
1760 .rev()
1761 .zip(Path::new(trimmed_path).ancestors())
1762 {
1763 range.end = ancestor.as_os_str().as_encoded_bytes().len();
1764 }
1765 Self {
1766 path: Cow::Borrowed(Path::new(path)),
1767 path_str: Cow::Borrowed(path),
1768 component_ranges,
1769 }
1770 }
1771
1772 fn elision_range(&self, budget: usize, matches: &[usize]) -> Option<Range<usize>> {
1773 let eligible_range = {
1774 assert!(matches.windows(2).all(|w| w[0] <= w[1]));
1775 let mut matches = matches.iter().copied().peekable();
1776 let mut longest: Option<Range<usize>> = None;
1777 let mut cur = 0..0;
1778 let mut seen_normal = false;
1779 for (i, (component, range)) in self.component_ranges.iter().enumerate() {
1780 let is_normal = matches!(component, Component::Normal(_));
1781 let is_first_normal = is_normal && !seen_normal;
1782 seen_normal |= is_normal;
1783 let is_last = i == self.component_ranges.len() - 1;
1784 let contains_match = matches.peek().is_some_and(|mat| range.contains(mat));
1785 if contains_match {
1786 matches.next();
1787 }
1788 if is_first_normal || is_last || !is_normal || contains_match {
1789 if longest
1790 .as_ref()
1791 .is_none_or(|old| old.end - old.start <= cur.end - cur.start)
1792 {
1793 longest = Some(cur);
1794 }
1795 cur = i + 1..i + 1;
1796 } else {
1797 cur.end = i + 1;
1798 }
1799 }
1800 if longest
1801 .as_ref()
1802 .is_none_or(|old| old.end - old.start <= cur.end - cur.start)
1803 {
1804 longest = Some(cur);
1805 }
1806 longest
1807 };
1808
1809 let eligible_range = eligible_range?;
1810 assert!(eligible_range.start <= eligible_range.end);
1811 if eligible_range.is_empty() {
1812 return None;
1813 }
1814
1815 let elided_range: Range<usize> = {
1816 let byte_range = self.component_ranges[eligible_range.start].1.start
1817 ..self.component_ranges[eligible_range.end - 1].1.end;
1818 let midpoint = self.path_str.len() / 2;
1819 let distance_from_start = byte_range.start.abs_diff(midpoint);
1820 let distance_from_end = byte_range.end.abs_diff(midpoint);
1821 let pick_from_end = distance_from_start > distance_from_end;
1822 let mut len_with_elision = self.path_str.len();
1823 let mut i = eligible_range.start;
1824 while i < eligible_range.end {
1825 let x = if pick_from_end {
1826 eligible_range.end - i + eligible_range.start - 1
1827 } else {
1828 i
1829 };
1830 len_with_elision -= self.component_ranges[x]
1831 .0
1832 .as_os_str()
1833 .as_encoded_bytes()
1834 .len()
1835 + 1;
1836 if len_with_elision <= budget {
1837 break;
1838 }
1839 i += 1;
1840 }
1841 if len_with_elision > budget {
1842 return None;
1843 } else if pick_from_end {
1844 let x = eligible_range.end - i + eligible_range.start - 1;
1845 x..eligible_range.end
1846 } else {
1847 let x = i;
1848 eligible_range.start..x + 1
1849 }
1850 };
1851
1852 let byte_range = self.component_ranges[elided_range.start].1.start
1853 ..self.component_ranges[elided_range.end - 1].1.end;
1854 Some(byte_range)
1855 }
1856}