1#[cfg(test)]
2mod file_finder_tests;
3
4mod new_path_prompt;
5mod open_path_prompt;
6
7use collections::HashMap;
8use editor::{scroll::Autoscroll, Bias, Editor};
9use fuzzy::{CharBag, PathMatch, PathMatchCandidate};
10use gpui::{
11 actions, rems, Action, AnyElement, AppContext, DismissEvent, EventEmitter, FocusHandle,
12 FocusableView, Model, Modifiers, ModifiersChangedEvent, ParentElement, Render, Styled, Task,
13 View, ViewContext, VisualContext, WeakView,
14};
15use new_path_prompt::NewPathPrompt;
16use open_path_prompt::OpenPathPrompt;
17use picker::{Picker, PickerDelegate};
18use project::{PathMatchCandidateSet, Project, ProjectPath, WorktreeId};
19use settings::Settings;
20use std::{
21 cmp,
22 path::{Path, PathBuf},
23 sync::{
24 atomic::{self, AtomicBool},
25 Arc,
26 },
27};
28use text::Point;
29use ui::{prelude::*, HighlightedLabel, ListItem, ListItemSpacing};
30use util::{paths::PathWithPosition, post_inc, ResultExt};
31use workspace::{item::PreviewTabsSettings, ModalView, Workspace};
32
33actions!(file_finder, [SelectPrev]);
34
35impl ModalView for FileFinder {}
36
37pub struct FileFinder {
38 picker: View<Picker<FileFinderDelegate>>,
39 init_modifiers: Option<Modifiers>,
40}
41
42pub fn init(cx: &mut AppContext) {
43 cx.observe_new_views(FileFinder::register).detach();
44 cx.observe_new_views(NewPathPrompt::register).detach();
45 cx.observe_new_views(OpenPathPrompt::register).detach();
46}
47
48impl FileFinder {
49 fn register(workspace: &mut Workspace, _: &mut ViewContext<Workspace>) {
50 workspace.register_action(|workspace, action: &workspace::ToggleFileFinder, cx| {
51 let Some(file_finder) = workspace.active_modal::<Self>(cx) else {
52 Self::open(workspace, action.separate_history, cx);
53 return;
54 };
55
56 file_finder.update(cx, |file_finder, cx| {
57 file_finder.init_modifiers = Some(cx.modifiers());
58 file_finder.picker.update(cx, |picker, cx| {
59 picker.cycle_selection(cx);
60 });
61 });
62 });
63 }
64
65 fn open(workspace: &mut Workspace, separate_history: bool, cx: &mut ViewContext<Workspace>) {
66 let project = workspace.project().read(cx);
67
68 let currently_opened_path = workspace
69 .active_item(cx)
70 .and_then(|item| item.project_path(cx))
71 .map(|project_path| {
72 let abs_path = project
73 .worktree_for_id(project_path.worktree_id, cx)
74 .map(|worktree| worktree.read(cx).abs_path().join(&project_path.path));
75 FoundPath::new(project_path, abs_path)
76 });
77
78 let history_items = workspace
79 .recent_navigation_history(Some(MAX_RECENT_SELECTIONS), cx)
80 .into_iter()
81 .filter(|(_, history_abs_path)| match history_abs_path {
82 Some(abs_path) => history_file_exists(abs_path),
83 None => true,
84 })
85 .map(|(history_path, abs_path)| FoundPath::new(history_path, abs_path))
86 .collect::<Vec<_>>();
87
88 let project = workspace.project().clone();
89 let weak_workspace = cx.view().downgrade();
90 workspace.toggle_modal(cx, |cx| {
91 let delegate = FileFinderDelegate::new(
92 cx.view().downgrade(),
93 weak_workspace,
94 project,
95 currently_opened_path,
96 history_items,
97 separate_history,
98 cx,
99 );
100
101 FileFinder::new(delegate, cx)
102 });
103 }
104
105 fn new(delegate: FileFinderDelegate, cx: &mut ViewContext<Self>) -> Self {
106 Self {
107 picker: cx.new_view(|cx| Picker::uniform_list(delegate, cx)),
108 init_modifiers: cx.modifiers().modified().then_some(cx.modifiers()),
109 }
110 }
111
112 fn handle_modifiers_changed(
113 &mut self,
114 event: &ModifiersChangedEvent,
115 cx: &mut ViewContext<Self>,
116 ) {
117 let Some(init_modifiers) = self.init_modifiers.take() else {
118 return;
119 };
120 if self.picker.read(cx).delegate.has_changed_selected_index {
121 if !event.modified() || !init_modifiers.is_subset_of(&event) {
122 self.init_modifiers = None;
123 cx.dispatch_action(menu::Confirm.boxed_clone());
124 }
125 }
126 }
127
128 fn handle_select_prev(&mut self, _: &SelectPrev, cx: &mut ViewContext<Self>) {
129 self.init_modifiers = Some(cx.modifiers());
130 cx.dispatch_action(Box::new(menu::SelectPrev));
131 }
132}
133
134impl EventEmitter<DismissEvent> for FileFinder {}
135
136impl FocusableView for FileFinder {
137 fn focus_handle(&self, cx: &AppContext) -> FocusHandle {
138 self.picker.focus_handle(cx)
139 }
140}
141
142impl Render for FileFinder {
143 fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
144 v_flex()
145 .key_context("FileFinder")
146 .w(rems(34.))
147 .on_modifiers_changed(cx.listener(Self::handle_modifiers_changed))
148 .on_action(cx.listener(Self::handle_select_prev))
149 .child(self.picker.clone())
150 }
151}
152
153pub struct FileFinderDelegate {
154 file_finder: WeakView<FileFinder>,
155 workspace: WeakView<Workspace>,
156 project: Model<Project>,
157 search_count: usize,
158 latest_search_id: usize,
159 latest_search_did_cancel: bool,
160 latest_search_query: Option<FileSearchQuery>,
161 currently_opened_path: Option<FoundPath>,
162 matches: Matches,
163 selected_index: usize,
164 has_changed_selected_index: bool,
165 cancel_flag: Arc<AtomicBool>,
166 history_items: Vec<FoundPath>,
167 separate_history: bool,
168 first_update: bool,
169}
170
171/// Use a custom ordering for file finder: the regular one
172/// defines max element with the highest score and the latest alphanumerical path (in case of a tie on other params), e.g:
173/// `[{score: 0.5, path = "c/d" }, { score: 0.5, path = "/a/b" }]`
174///
175/// In the file finder, we would prefer to have the max element with the highest score and the earliest alphanumerical path, e.g:
176/// `[{ score: 0.5, path = "/a/b" }, {score: 0.5, path = "c/d" }]`
177/// as the files are shown in the project panel lists.
178#[derive(Debug, Clone, PartialEq, Eq)]
179struct ProjectPanelOrdMatch(PathMatch);
180
181impl Ord for ProjectPanelOrdMatch {
182 fn cmp(&self, other: &Self) -> cmp::Ordering {
183 self.0
184 .score
185 .partial_cmp(&other.0.score)
186 .unwrap_or(cmp::Ordering::Equal)
187 .then_with(|| self.0.worktree_id.cmp(&other.0.worktree_id))
188 .then_with(|| {
189 other
190 .0
191 .distance_to_relative_ancestor
192 .cmp(&self.0.distance_to_relative_ancestor)
193 })
194 .then_with(|| self.0.path.cmp(&other.0.path).reverse())
195 }
196}
197
198impl PartialOrd for ProjectPanelOrdMatch {
199 fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> {
200 Some(self.cmp(other))
201 }
202}
203
204#[derive(Debug, Default)]
205struct Matches {
206 separate_history: bool,
207 matches: Vec<Match>,
208}
209
210#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone)]
211enum Match {
212 History {
213 path: FoundPath,
214 panel_match: Option<ProjectPanelOrdMatch>,
215 },
216 Search(ProjectPanelOrdMatch),
217}
218
219impl Match {
220 fn path(&self) -> &Arc<Path> {
221 match self {
222 Match::History { path, .. } => &path.project.path,
223 Match::Search(panel_match) => &panel_match.0.path,
224 }
225 }
226
227 fn panel_match(&self) -> Option<&ProjectPanelOrdMatch> {
228 match self {
229 Match::History { panel_match, .. } => panel_match.as_ref(),
230 Match::Search(panel_match) => Some(&panel_match),
231 }
232 }
233}
234
235impl Matches {
236 fn len(&self) -> usize {
237 self.matches.len()
238 }
239
240 fn get(&self, index: usize) -> Option<&Match> {
241 self.matches.get(index)
242 }
243
244 fn position(
245 &self,
246 entry: &Match,
247 currently_opened: Option<&FoundPath>,
248 ) -> Result<usize, usize> {
249 if let Match::History {
250 path,
251 panel_match: None,
252 } = entry
253 {
254 // Slow case: linear search by path. Should not happen actually,
255 // since we call `position` only if matches set changed, but the query has not changed.
256 // And History entries do not have panel_match if query is empty, so there's no
257 // reason for the matches set to change.
258 self.matches
259 .iter()
260 .position(|m| path.project.path == *m.path())
261 .ok_or(0)
262 } else {
263 self.matches.binary_search_by(|m| {
264 // `reverse()` since if cmp_matches(a, b) == Ordering::Greater, then a is better than b.
265 // And we want the better entries go first.
266 Self::cmp_matches(self.separate_history, currently_opened, &m, &entry).reverse()
267 })
268 }
269 }
270
271 fn push_new_matches<'a>(
272 &'a mut self,
273 history_items: impl IntoIterator<Item = &'a FoundPath> + Clone,
274 currently_opened: Option<&'a FoundPath>,
275 query: Option<&FileSearchQuery>,
276 new_search_matches: impl Iterator<Item = ProjectPanelOrdMatch>,
277 extend_old_matches: bool,
278 ) {
279 let Some(query) = query else {
280 // assuming that if there's no query, then there's no search matches.
281 self.matches.clear();
282 let path_to_entry = |found_path: &FoundPath| Match::History {
283 path: found_path.clone(),
284 panel_match: None,
285 };
286 self.matches
287 .extend(currently_opened.into_iter().map(path_to_entry));
288
289 self.matches.extend(
290 history_items
291 .into_iter()
292 .filter(|found_path| Some(*found_path) != currently_opened)
293 .map(path_to_entry),
294 );
295 return;
296 };
297
298 let new_history_matches = matching_history_items(history_items, currently_opened, query);
299 let new_search_matches: Vec<Match> = new_search_matches
300 .filter(|path_match| !new_history_matches.contains_key(&path_match.0.path))
301 .map(Match::Search)
302 .collect();
303
304 if extend_old_matches {
305 // since we take history matches instead of new search matches
306 // and history matches has not changed(since the query has not changed and we do not extend old matches otherwise),
307 // old matches can't contain paths present in history_matches as well.
308 self.matches.retain(|m| matches!(m, Match::Search(_)));
309 } else {
310 self.matches.clear();
311 }
312
313 // At this point we have an unsorted set of new history matches, an unsorted set of new search matches
314 // and a sorted set of old search matches.
315 // It is possible that the new search matches' paths contain some of the old search matches' paths.
316 // History matches' paths are unique, since store in a HashMap by path.
317 // We build a sorted Vec<Match>, eliminating duplicate search matches.
318 // Search matches with the same paths should have equal `ProjectPanelOrdMatch`, so we should
319 // not have any duplicates after building the final list.
320 for new_match in new_history_matches
321 .into_values()
322 .chain(new_search_matches.into_iter())
323 {
324 match self.position(&new_match, currently_opened) {
325 Ok(_duplicate) => continue,
326 Err(i) => {
327 self.matches.insert(i, new_match);
328 if self.matches.len() == 100 {
329 break;
330 }
331 }
332 }
333 }
334 }
335
336 /// If a < b, then a is a worse match, aligning with the `ProjectPanelOrdMatch` ordering.
337 fn cmp_matches(
338 separate_history: bool,
339 currently_opened: Option<&FoundPath>,
340 a: &Match,
341 b: &Match,
342 ) -> cmp::Ordering {
343 debug_assert!(a.panel_match().is_some() && b.panel_match().is_some());
344
345 match (&a, &b) {
346 // bubble currently opened files to the top
347 (Match::History { path, .. }, _) if Some(path) == currently_opened => {
348 cmp::Ordering::Greater
349 }
350 (_, Match::History { path, .. }) if Some(path) == currently_opened => {
351 cmp::Ordering::Less
352 }
353
354 (Match::History { .. }, Match::Search(_)) if separate_history => cmp::Ordering::Greater,
355 (Match::Search(_), Match::History { .. }) if separate_history => cmp::Ordering::Less,
356
357 _ => a.panel_match().cmp(&b.panel_match()),
358 }
359 }
360}
361
362fn matching_history_items<'a>(
363 history_items: impl IntoIterator<Item = &'a FoundPath>,
364 currently_opened: Option<&'a FoundPath>,
365 query: &FileSearchQuery,
366) -> HashMap<Arc<Path>, Match> {
367 let mut candidates_paths = HashMap::default();
368
369 let history_items_by_worktrees = history_items
370 .into_iter()
371 .chain(currently_opened)
372 .filter_map(|found_path| {
373 let candidate = PathMatchCandidate {
374 is_dir: false, // You can't open directories as project items
375 path: &found_path.project.path,
376 // Only match history items names, otherwise their paths may match too many queries, producing false positives.
377 // E.g. `foo` would match both `something/foo/bar.rs` and `something/foo/foo.rs` and if the former is a history item,
378 // it would be shown first always, despite the latter being a better match.
379 char_bag: CharBag::from_iter(
380 found_path
381 .project
382 .path
383 .file_name()?
384 .to_string_lossy()
385 .to_lowercase()
386 .chars(),
387 ),
388 };
389 candidates_paths.insert(Arc::clone(&found_path.project.path), found_path);
390 Some((found_path.project.worktree_id, candidate))
391 })
392 .fold(
393 HashMap::default(),
394 |mut candidates, (worktree_id, new_candidate)| {
395 candidates
396 .entry(worktree_id)
397 .or_insert_with(Vec::new)
398 .push(new_candidate);
399 candidates
400 },
401 );
402 let mut matching_history_paths = HashMap::default();
403 for (worktree, candidates) in history_items_by_worktrees {
404 let max_results = candidates.len() + 1;
405 matching_history_paths.extend(
406 fuzzy::match_fixed_path_set(
407 candidates,
408 worktree.to_usize(),
409 query.path_query(),
410 false,
411 max_results,
412 )
413 .into_iter()
414 .map(|path_match| {
415 let (_, found_path) = candidates_paths
416 .remove_entry(&path_match.path)
417 .expect("candidate info not found");
418 (
419 Arc::clone(&path_match.path),
420 Match::History {
421 path: found_path.clone(),
422 panel_match: Some(ProjectPanelOrdMatch(path_match)),
423 },
424 )
425 }),
426 );
427 }
428 matching_history_paths
429}
430
431#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
432struct FoundPath {
433 project: ProjectPath,
434 absolute: Option<PathBuf>,
435}
436
437impl FoundPath {
438 fn new(project: ProjectPath, absolute: Option<PathBuf>) -> Self {
439 Self { project, absolute }
440 }
441}
442
443const MAX_RECENT_SELECTIONS: usize = 20;
444
445#[cfg(not(test))]
446fn history_file_exists(abs_path: &PathBuf) -> bool {
447 abs_path.exists()
448}
449
450#[cfg(test)]
451fn history_file_exists(abs_path: &PathBuf) -> bool {
452 !abs_path.ends_with("nonexistent.rs")
453}
454
455pub enum Event {
456 Selected(ProjectPath),
457 Dismissed,
458}
459
460#[derive(Debug, Clone)]
461struct FileSearchQuery {
462 raw_query: String,
463 file_query_end: Option<usize>,
464 path_position: PathWithPosition,
465}
466
467impl FileSearchQuery {
468 fn path_query(&self) -> &str {
469 match self.file_query_end {
470 Some(file_path_end) => &self.raw_query[..file_path_end],
471 None => &self.raw_query,
472 }
473 }
474}
475
476impl FileFinderDelegate {
477 fn new(
478 file_finder: WeakView<FileFinder>,
479 workspace: WeakView<Workspace>,
480 project: Model<Project>,
481 currently_opened_path: Option<FoundPath>,
482 history_items: Vec<FoundPath>,
483 separate_history: bool,
484 cx: &mut ViewContext<FileFinder>,
485 ) -> Self {
486 Self::subscribe_to_updates(&project, cx);
487 Self {
488 file_finder,
489 workspace,
490 project,
491 search_count: 0,
492 latest_search_id: 0,
493 latest_search_did_cancel: false,
494 latest_search_query: None,
495 currently_opened_path,
496 matches: Matches::default(),
497 has_changed_selected_index: false,
498 selected_index: 0,
499 cancel_flag: Arc::new(AtomicBool::new(false)),
500 history_items,
501 separate_history,
502 first_update: true,
503 }
504 }
505
506 fn subscribe_to_updates(project: &Model<Project>, cx: &mut ViewContext<FileFinder>) {
507 cx.subscribe(project, |file_finder, _, event, cx| {
508 match event {
509 project::Event::WorktreeUpdatedEntries(_, _)
510 | project::Event::WorktreeAdded
511 | project::Event::WorktreeRemoved(_) => file_finder
512 .picker
513 .update(cx, |picker, cx| picker.refresh(cx)),
514 _ => {}
515 };
516 })
517 .detach();
518 }
519
520 fn spawn_search(
521 &mut self,
522 query: FileSearchQuery,
523 cx: &mut ViewContext<Picker<Self>>,
524 ) -> Task<()> {
525 let relative_to = self
526 .currently_opened_path
527 .as_ref()
528 .map(|found_path| Arc::clone(&found_path.project.path));
529 let worktrees = self
530 .project
531 .read(cx)
532 .visible_worktrees(cx)
533 .collect::<Vec<_>>();
534 let include_root_name = worktrees.len() > 1;
535 let candidate_sets = worktrees
536 .into_iter()
537 .map(|worktree| {
538 let worktree = worktree.read(cx);
539 PathMatchCandidateSet {
540 snapshot: worktree.snapshot(),
541 include_ignored: worktree
542 .root_entry()
543 .map_or(false, |entry| entry.is_ignored),
544 include_root_name,
545 candidates: project::Candidates::Files,
546 }
547 })
548 .collect::<Vec<_>>();
549
550 let search_id = util::post_inc(&mut self.search_count);
551 self.cancel_flag.store(true, atomic::Ordering::Relaxed);
552 self.cancel_flag = Arc::new(AtomicBool::new(false));
553 let cancel_flag = self.cancel_flag.clone();
554 cx.spawn(|picker, mut cx| async move {
555 let matches = fuzzy::match_path_sets(
556 candidate_sets.as_slice(),
557 query.path_query(),
558 relative_to,
559 false,
560 100,
561 &cancel_flag,
562 cx.background_executor().clone(),
563 )
564 .await
565 .into_iter()
566 .map(ProjectPanelOrdMatch);
567 let did_cancel = cancel_flag.load(atomic::Ordering::Relaxed);
568 picker
569 .update(&mut cx, |picker, cx| {
570 picker
571 .delegate
572 .set_search_matches(search_id, did_cancel, query, matches, cx)
573 })
574 .log_err();
575 })
576 }
577
578 fn set_search_matches(
579 &mut self,
580 search_id: usize,
581 did_cancel: bool,
582 query: FileSearchQuery,
583 matches: impl IntoIterator<Item = ProjectPanelOrdMatch>,
584 cx: &mut ViewContext<Picker<Self>>,
585 ) {
586 if search_id >= self.latest_search_id {
587 self.latest_search_id = search_id;
588 let query_changed = Some(query.path_query())
589 != self
590 .latest_search_query
591 .as_ref()
592 .map(|query| query.path_query());
593 let extend_old_matches = self.latest_search_did_cancel && !query_changed;
594
595 let selected_match = if query_changed {
596 None
597 } else {
598 self.matches.get(self.selected_index).cloned()
599 };
600
601 self.matches.push_new_matches(
602 &self.history_items,
603 self.currently_opened_path.as_ref(),
604 Some(&query),
605 matches.into_iter(),
606 extend_old_matches,
607 );
608
609 self.selected_index = selected_match.map_or_else(
610 || self.calculate_selected_index(),
611 |m| {
612 self.matches
613 .position(&m, self.currently_opened_path.as_ref())
614 .unwrap_or(0)
615 },
616 );
617
618 self.latest_search_query = Some(query);
619 self.latest_search_did_cancel = did_cancel;
620
621 cx.notify();
622 }
623 }
624
625 fn labels_for_match(
626 &self,
627 path_match: &Match,
628 cx: &AppContext,
629 ix: usize,
630 ) -> (String, Vec<usize>, String, Vec<usize>) {
631 let (file_name, file_name_positions, full_path, full_path_positions) = match &path_match {
632 Match::History {
633 path: entry_path,
634 panel_match,
635 } => {
636 let worktree_id = entry_path.project.worktree_id;
637 let project_relative_path = &entry_path.project.path;
638 let has_worktree = self
639 .project
640 .read(cx)
641 .worktree_for_id(worktree_id, cx)
642 .is_some();
643
644 if !has_worktree {
645 if let Some(absolute_path) = &entry_path.absolute {
646 return (
647 absolute_path
648 .file_name()
649 .map_or_else(
650 || project_relative_path.to_string_lossy(),
651 |file_name| file_name.to_string_lossy(),
652 )
653 .to_string(),
654 Vec::new(),
655 absolute_path.to_string_lossy().to_string(),
656 Vec::new(),
657 );
658 }
659 }
660
661 let mut path = Arc::clone(project_relative_path);
662 if project_relative_path.as_ref() == Path::new("") {
663 if let Some(absolute_path) = &entry_path.absolute {
664 path = Arc::from(absolute_path.as_path());
665 }
666 }
667
668 let mut path_match = PathMatch {
669 score: ix as f64,
670 positions: Vec::new(),
671 worktree_id: worktree_id.to_usize(),
672 path,
673 is_dir: false, // File finder doesn't support directories
674 path_prefix: "".into(),
675 distance_to_relative_ancestor: usize::MAX,
676 };
677 if let Some(found_path_match) = &panel_match {
678 path_match
679 .positions
680 .extend(found_path_match.0.positions.iter())
681 }
682
683 self.labels_for_path_match(&path_match)
684 }
685 Match::Search(path_match) => self.labels_for_path_match(&path_match.0),
686 };
687
688 if file_name_positions.is_empty() {
689 if let Some(user_home_path) = std::env::var("HOME").ok() {
690 let user_home_path = user_home_path.trim();
691 if !user_home_path.is_empty() {
692 if (&full_path).starts_with(user_home_path) {
693 return (
694 file_name,
695 file_name_positions,
696 full_path.replace(user_home_path, "~"),
697 full_path_positions,
698 );
699 }
700 }
701 }
702 }
703
704 (
705 file_name,
706 file_name_positions,
707 full_path,
708 full_path_positions,
709 )
710 }
711
712 fn labels_for_path_match(
713 &self,
714 path_match: &PathMatch,
715 ) -> (String, Vec<usize>, String, Vec<usize>) {
716 let path = &path_match.path;
717 let path_string = path.to_string_lossy();
718 let full_path = [path_match.path_prefix.as_ref(), path_string.as_ref()].join("");
719 let mut path_positions = path_match.positions.clone();
720
721 let file_name = path.file_name().map_or_else(
722 || path_match.path_prefix.to_string(),
723 |file_name| file_name.to_string_lossy().to_string(),
724 );
725 let file_name_start = path_match.path_prefix.len() + path_string.len() - file_name.len();
726 let file_name_positions = path_positions
727 .iter()
728 .filter_map(|pos| {
729 if pos >= &file_name_start {
730 Some(pos - file_name_start)
731 } else {
732 None
733 }
734 })
735 .collect();
736
737 let full_path = full_path.trim_end_matches(&file_name).to_string();
738 path_positions.retain(|idx| *idx < full_path.len());
739
740 (file_name, file_name_positions, full_path, path_positions)
741 }
742
743 fn lookup_absolute_path(
744 &self,
745 query: FileSearchQuery,
746 cx: &mut ViewContext<'_, Picker<Self>>,
747 ) -> Task<()> {
748 cx.spawn(|picker, mut cx| async move {
749 let Some((project, fs)) = picker
750 .update(&mut cx, |picker, cx| {
751 let fs = Arc::clone(&picker.delegate.project.read(cx).fs());
752 (picker.delegate.project.clone(), fs)
753 })
754 .log_err()
755 else {
756 return;
757 };
758
759 let query_path = Path::new(query.path_query());
760 let mut path_matches = Vec::new();
761 match fs.metadata(query_path).await.log_err() {
762 Some(Some(_metadata)) => {
763 let update_result = project
764 .update(&mut cx, |project, cx| {
765 if let Some((worktree, relative_path)) =
766 project.find_worktree(query_path, cx)
767 {
768 path_matches.push(ProjectPanelOrdMatch(PathMatch {
769 score: 1.0,
770 positions: Vec::new(),
771 worktree_id: worktree.read(cx).id().to_usize(),
772 path: Arc::from(relative_path),
773 path_prefix: "".into(),
774 is_dir: false, // File finder doesn't support directories
775 distance_to_relative_ancestor: usize::MAX,
776 }));
777 }
778 })
779 .log_err();
780 if update_result.is_none() {
781 return;
782 }
783 }
784 Some(None) => {}
785 None => return,
786 }
787
788 picker
789 .update(&mut cx, |picker, cx| {
790 let picker_delegate = &mut picker.delegate;
791 let search_id = util::post_inc(&mut picker_delegate.search_count);
792 picker_delegate.set_search_matches(search_id, false, query, path_matches, cx);
793
794 anyhow::Ok(())
795 })
796 .log_err();
797 })
798 }
799
800 /// Skips first history match (that is displayed topmost) if it's currently opened.
801 fn calculate_selected_index(&self) -> usize {
802 if let Some(Match::History { path, .. }) = self.matches.get(0) {
803 if Some(path) == self.currently_opened_path.as_ref() {
804 let elements_after_first = self.matches.len() - 1;
805 if elements_after_first > 0 {
806 return 1;
807 }
808 }
809 }
810
811 0
812 }
813}
814
815impl PickerDelegate for FileFinderDelegate {
816 type ListItem = ListItem;
817
818 fn placeholder_text(&self, _cx: &mut WindowContext) -> Arc<str> {
819 "Search project files...".into()
820 }
821
822 fn match_count(&self) -> usize {
823 self.matches.len()
824 }
825
826 fn selected_index(&self) -> usize {
827 self.selected_index
828 }
829
830 fn set_selected_index(&mut self, ix: usize, cx: &mut ViewContext<Picker<Self>>) {
831 self.has_changed_selected_index = true;
832 self.selected_index = ix;
833 cx.notify();
834 }
835
836 fn separators_after_indices(&self) -> Vec<usize> {
837 if self.separate_history {
838 let first_non_history_index = self
839 .matches
840 .matches
841 .iter()
842 .enumerate()
843 .find(|(_, m)| !matches!(m, Match::History { .. }))
844 .map(|(i, _)| i);
845 if let Some(first_non_history_index) = first_non_history_index {
846 if first_non_history_index > 0 {
847 return vec![first_non_history_index - 1];
848 }
849 }
850 }
851 Vec::new()
852 }
853
854 fn update_matches(
855 &mut self,
856 raw_query: String,
857 cx: &mut ViewContext<Picker<Self>>,
858 ) -> Task<()> {
859 let raw_query = raw_query.replace(' ', "");
860 let raw_query = raw_query.trim();
861 if raw_query.is_empty() {
862 // if there was no query before, and we already have some (history) matches
863 // there's no need to update anything, since nothing has changed.
864 // We also want to populate matches set from history entries on the first update.
865 if self.latest_search_query.is_some() || self.first_update {
866 let project = self.project.read(cx);
867
868 self.latest_search_id = post_inc(&mut self.search_count);
869 self.latest_search_query = None;
870 self.matches = Matches {
871 separate_history: self.separate_history,
872 ..Matches::default()
873 };
874 self.matches.push_new_matches(
875 self.history_items.iter().filter(|history_item| {
876 project
877 .worktree_for_id(history_item.project.worktree_id, cx)
878 .is_some()
879 || (project.is_local_or_ssh() && history_item.absolute.is_some())
880 }),
881 self.currently_opened_path.as_ref(),
882 None,
883 None.into_iter(),
884 false,
885 );
886
887 self.first_update = false;
888 self.selected_index = 0;
889 }
890 cx.notify();
891 Task::ready(())
892 } else {
893 let path_position = PathWithPosition::parse_str(&raw_query);
894
895 let query = FileSearchQuery {
896 raw_query: raw_query.trim().to_owned(),
897 file_query_end: if path_position.path.to_str().unwrap_or(raw_query) == raw_query {
898 None
899 } else {
900 // Safe to unwrap as we won't get here when the unwrap in if fails
901 Some(path_position.path.to_str().unwrap().len())
902 },
903 path_position,
904 };
905
906 if Path::new(query.path_query()).is_absolute() {
907 self.lookup_absolute_path(query, cx)
908 } else {
909 self.spawn_search(query, cx)
910 }
911 }
912 }
913
914 fn confirm(&mut self, secondary: bool, cx: &mut ViewContext<Picker<FileFinderDelegate>>) {
915 if let Some(m) = self.matches.get(self.selected_index()) {
916 if let Some(workspace) = self.workspace.upgrade() {
917 let open_task = workspace.update(cx, move |workspace, cx| {
918 let split_or_open =
919 |workspace: &mut Workspace,
920 project_path,
921 cx: &mut ViewContext<Workspace>| {
922 let allow_preview =
923 PreviewTabsSettings::get_global(cx).enable_preview_from_file_finder;
924 if secondary {
925 workspace.split_path_preview(project_path, allow_preview, cx)
926 } else {
927 workspace.open_path_preview(
928 project_path,
929 None,
930 true,
931 allow_preview,
932 cx,
933 )
934 }
935 };
936 match &m {
937 Match::History { path, .. } => {
938 let worktree_id = path.project.worktree_id;
939 if workspace
940 .project()
941 .read(cx)
942 .worktree_for_id(worktree_id, cx)
943 .is_some()
944 {
945 split_or_open(
946 workspace,
947 ProjectPath {
948 worktree_id,
949 path: Arc::clone(&path.project.path),
950 },
951 cx,
952 )
953 } else {
954 match path.absolute.as_ref() {
955 Some(abs_path) => {
956 if secondary {
957 workspace.split_abs_path(
958 abs_path.to_path_buf(),
959 false,
960 cx,
961 )
962 } else {
963 workspace.open_abs_path(
964 abs_path.to_path_buf(),
965 false,
966 cx,
967 )
968 }
969 }
970 None => split_or_open(
971 workspace,
972 ProjectPath {
973 worktree_id,
974 path: Arc::clone(&path.project.path),
975 },
976 cx,
977 ),
978 }
979 }
980 }
981 Match::Search(m) => split_or_open(
982 workspace,
983 ProjectPath {
984 worktree_id: WorktreeId::from_usize(m.0.worktree_id),
985 path: m.0.path.clone(),
986 },
987 cx,
988 ),
989 }
990 });
991
992 let row = self
993 .latest_search_query
994 .as_ref()
995 .and_then(|query| query.path_position.row)
996 .map(|row| row.saturating_sub(1));
997 let col = self
998 .latest_search_query
999 .as_ref()
1000 .and_then(|query| query.path_position.column)
1001 .unwrap_or(0)
1002 .saturating_sub(1);
1003 let finder = self.file_finder.clone();
1004
1005 cx.spawn(|_, mut cx| async move {
1006 let item = open_task.await.log_err()?;
1007 if let Some(row) = row {
1008 if let Some(active_editor) = item.downcast::<Editor>() {
1009 active_editor
1010 .downgrade()
1011 .update(&mut cx, |editor, cx| {
1012 let snapshot = editor.snapshot(cx).display_snapshot;
1013 let point = snapshot
1014 .buffer_snapshot
1015 .clip_point(Point::new(row, col), Bias::Left);
1016 editor.change_selections(Some(Autoscroll::center()), cx, |s| {
1017 s.select_ranges([point..point])
1018 });
1019 })
1020 .log_err();
1021 }
1022 }
1023 finder.update(&mut cx, |_, cx| cx.emit(DismissEvent)).ok()?;
1024
1025 Some(())
1026 })
1027 .detach();
1028 }
1029 }
1030 }
1031
1032 fn dismissed(&mut self, cx: &mut ViewContext<Picker<FileFinderDelegate>>) {
1033 self.file_finder
1034 .update(cx, |_, cx| cx.emit(DismissEvent))
1035 .log_err();
1036 }
1037
1038 fn render_match(
1039 &self,
1040 ix: usize,
1041 selected: bool,
1042 cx: &mut ViewContext<Picker<Self>>,
1043 ) -> Option<Self::ListItem> {
1044 let path_match = self
1045 .matches
1046 .get(ix)
1047 .expect("Invalid matches state: no element for index {ix}");
1048
1049 let icon = match &path_match {
1050 Match::History { .. } => Icon::new(IconName::HistoryRerun)
1051 .color(Color::Muted)
1052 .size(IconSize::Small)
1053 .into_any_element(),
1054 Match::Search(_) => v_flex()
1055 .flex_none()
1056 .size(IconSize::Small.rems())
1057 .into_any_element(),
1058 };
1059 let (file_name, file_name_positions, full_path, full_path_positions) =
1060 self.labels_for_match(path_match, cx, ix);
1061
1062 Some(
1063 ListItem::new(ix)
1064 .spacing(ListItemSpacing::Sparse)
1065 .end_slot::<AnyElement>(Some(icon))
1066 .inset(true)
1067 .selected(selected)
1068 .child(
1069 h_flex()
1070 .gap_2()
1071 .py_px()
1072 .child(HighlightedLabel::new(file_name, file_name_positions))
1073 .child(
1074 HighlightedLabel::new(full_path, full_path_positions)
1075 .size(LabelSize::Small)
1076 .color(Color::Muted),
1077 ),
1078 ),
1079 )
1080 }
1081}
1082
1083#[cfg(test)]
1084mod tests {
1085 use super::*;
1086
1087 #[test]
1088 fn test_custom_project_search_ordering_in_file_finder() {
1089 let mut file_finder_sorted_output = vec![
1090 ProjectPanelOrdMatch(PathMatch {
1091 score: 0.5,
1092 positions: Vec::new(),
1093 worktree_id: 0,
1094 path: Arc::from(Path::new("b0.5")),
1095 path_prefix: Arc::default(),
1096 distance_to_relative_ancestor: 0,
1097 is_dir: false,
1098 }),
1099 ProjectPanelOrdMatch(PathMatch {
1100 score: 1.0,
1101 positions: Vec::new(),
1102 worktree_id: 0,
1103 path: Arc::from(Path::new("c1.0")),
1104 path_prefix: Arc::default(),
1105 distance_to_relative_ancestor: 0,
1106 is_dir: false,
1107 }),
1108 ProjectPanelOrdMatch(PathMatch {
1109 score: 1.0,
1110 positions: Vec::new(),
1111 worktree_id: 0,
1112 path: Arc::from(Path::new("a1.0")),
1113 path_prefix: Arc::default(),
1114 distance_to_relative_ancestor: 0,
1115 is_dir: false,
1116 }),
1117 ProjectPanelOrdMatch(PathMatch {
1118 score: 0.5,
1119 positions: Vec::new(),
1120 worktree_id: 0,
1121 path: Arc::from(Path::new("a0.5")),
1122 path_prefix: Arc::default(),
1123 distance_to_relative_ancestor: 0,
1124 is_dir: false,
1125 }),
1126 ProjectPanelOrdMatch(PathMatch {
1127 score: 1.0,
1128 positions: Vec::new(),
1129 worktree_id: 0,
1130 path: Arc::from(Path::new("b1.0")),
1131 path_prefix: Arc::default(),
1132 distance_to_relative_ancestor: 0,
1133 is_dir: false,
1134 }),
1135 ];
1136 file_finder_sorted_output.sort_by(|a, b| b.cmp(a));
1137
1138 assert_eq!(
1139 file_finder_sorted_output,
1140 vec![
1141 ProjectPanelOrdMatch(PathMatch {
1142 score: 1.0,
1143 positions: Vec::new(),
1144 worktree_id: 0,
1145 path: Arc::from(Path::new("a1.0")),
1146 path_prefix: Arc::default(),
1147 distance_to_relative_ancestor: 0,
1148 is_dir: false,
1149 }),
1150 ProjectPanelOrdMatch(PathMatch {
1151 score: 1.0,
1152 positions: Vec::new(),
1153 worktree_id: 0,
1154 path: Arc::from(Path::new("b1.0")),
1155 path_prefix: Arc::default(),
1156 distance_to_relative_ancestor: 0,
1157 is_dir: false,
1158 }),
1159 ProjectPanelOrdMatch(PathMatch {
1160 score: 1.0,
1161 positions: Vec::new(),
1162 worktree_id: 0,
1163 path: Arc::from(Path::new("c1.0")),
1164 path_prefix: Arc::default(),
1165 distance_to_relative_ancestor: 0,
1166 is_dir: false,
1167 }),
1168 ProjectPanelOrdMatch(PathMatch {
1169 score: 0.5,
1170 positions: Vec::new(),
1171 worktree_id: 0,
1172 path: Arc::from(Path::new("a0.5")),
1173 path_prefix: Arc::default(),
1174 distance_to_relative_ancestor: 0,
1175 is_dir: false,
1176 }),
1177 ProjectPanelOrdMatch(PathMatch {
1178 score: 0.5,
1179 positions: Vec::new(),
1180 worktree_id: 0,
1181 path: Arc::from(Path::new("b0.5")),
1182 path_prefix: Arc::default(),
1183 distance_to_relative_ancestor: 0,
1184 is_dir: false,
1185 }),
1186 ]
1187 );
1188 }
1189}