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