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