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(&found_path.project, 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 .filter_map(|path_match| {
415 candidates_paths
416 .remove_entry(&ProjectPath {
417 worktree_id: WorktreeId::from_usize(path_match.worktree_id),
418 path: Arc::clone(&path_match.path),
419 })
420 .map(|(_, found_path)| {
421 (
422 Arc::clone(&path_match.path),
423 Match::History {
424 path: found_path.clone(),
425 panel_match: Some(ProjectPanelOrdMatch(path_match)),
426 },
427 )
428 })
429 }),
430 );
431 }
432 matching_history_paths
433}
434
435#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
436struct FoundPath {
437 project: ProjectPath,
438 absolute: Option<PathBuf>,
439}
440
441impl FoundPath {
442 fn new(project: ProjectPath, absolute: Option<PathBuf>) -> Self {
443 Self { project, absolute }
444 }
445}
446
447const MAX_RECENT_SELECTIONS: usize = 20;
448
449#[cfg(not(test))]
450fn history_file_exists(abs_path: &PathBuf) -> bool {
451 abs_path.exists()
452}
453
454#[cfg(test)]
455fn history_file_exists(abs_path: &Path) -> bool {
456 !abs_path.ends_with("nonexistent.rs")
457}
458
459pub enum Event {
460 Selected(ProjectPath),
461 Dismissed,
462}
463
464#[derive(Debug, Clone)]
465struct FileSearchQuery {
466 raw_query: String,
467 file_query_end: Option<usize>,
468 path_position: PathWithPosition,
469}
470
471impl FileSearchQuery {
472 fn path_query(&self) -> &str {
473 match self.file_query_end {
474 Some(file_path_end) => &self.raw_query[..file_path_end],
475 None => &self.raw_query,
476 }
477 }
478}
479
480impl FileFinderDelegate {
481 fn new(
482 file_finder: WeakView<FileFinder>,
483 workspace: WeakView<Workspace>,
484 project: Model<Project>,
485 currently_opened_path: Option<FoundPath>,
486 history_items: Vec<FoundPath>,
487 separate_history: bool,
488 cx: &mut ViewContext<FileFinder>,
489 ) -> Self {
490 Self::subscribe_to_updates(&project, cx);
491 Self {
492 file_finder,
493 workspace,
494 project,
495 search_count: 0,
496 latest_search_id: 0,
497 latest_search_did_cancel: false,
498 latest_search_query: None,
499 currently_opened_path,
500 matches: Matches::default(),
501 has_changed_selected_index: false,
502 selected_index: 0,
503 cancel_flag: Arc::new(AtomicBool::new(false)),
504 history_items,
505 separate_history,
506 first_update: true,
507 }
508 }
509
510 fn subscribe_to_updates(project: &Model<Project>, cx: &mut ViewContext<FileFinder>) {
511 cx.subscribe(project, |file_finder, _, event, cx| {
512 match event {
513 project::Event::WorktreeUpdatedEntries(_, _)
514 | project::Event::WorktreeAdded
515 | project::Event::WorktreeRemoved(_) => file_finder
516 .picker
517 .update(cx, |picker, cx| picker.refresh(cx)),
518 _ => {}
519 };
520 })
521 .detach();
522 }
523
524 fn spawn_search(
525 &mut self,
526 query: FileSearchQuery,
527 cx: &mut ViewContext<Picker<Self>>,
528 ) -> Task<()> {
529 let relative_to = self
530 .currently_opened_path
531 .as_ref()
532 .map(|found_path| Arc::clone(&found_path.project.path));
533 let worktrees = self
534 .project
535 .read(cx)
536 .visible_worktrees(cx)
537 .collect::<Vec<_>>();
538 let include_root_name = worktrees.len() > 1;
539 let candidate_sets = worktrees
540 .into_iter()
541 .map(|worktree| {
542 let worktree = worktree.read(cx);
543 PathMatchCandidateSet {
544 snapshot: worktree.snapshot(),
545 include_ignored: worktree
546 .root_entry()
547 .map_or(false, |entry| entry.is_ignored),
548 include_root_name,
549 candidates: project::Candidates::Files,
550 }
551 })
552 .collect::<Vec<_>>();
553
554 let search_id = util::post_inc(&mut self.search_count);
555 self.cancel_flag.store(true, atomic::Ordering::Relaxed);
556 self.cancel_flag = Arc::new(AtomicBool::new(false));
557 let cancel_flag = self.cancel_flag.clone();
558 cx.spawn(|picker, mut cx| async move {
559 let matches = fuzzy::match_path_sets(
560 candidate_sets.as_slice(),
561 query.path_query(),
562 relative_to,
563 false,
564 100,
565 &cancel_flag,
566 cx.background_executor().clone(),
567 )
568 .await
569 .into_iter()
570 .map(ProjectPanelOrdMatch);
571 let did_cancel = cancel_flag.load(atomic::Ordering::Relaxed);
572 picker
573 .update(&mut cx, |picker, cx| {
574 picker
575 .delegate
576 .set_search_matches(search_id, did_cancel, query, matches, cx)
577 })
578 .log_err();
579 })
580 }
581
582 fn set_search_matches(
583 &mut self,
584 search_id: usize,
585 did_cancel: bool,
586 query: FileSearchQuery,
587 matches: impl IntoIterator<Item = ProjectPanelOrdMatch>,
588 cx: &mut ViewContext<Picker<Self>>,
589 ) {
590 if search_id >= self.latest_search_id {
591 self.latest_search_id = search_id;
592 let query_changed = Some(query.path_query())
593 != self
594 .latest_search_query
595 .as_ref()
596 .map(|query| query.path_query());
597 let extend_old_matches = self.latest_search_did_cancel && !query_changed;
598
599 let selected_match = if query_changed {
600 None
601 } else {
602 self.matches.get(self.selected_index).cloned()
603 };
604
605 self.matches.push_new_matches(
606 &self.history_items,
607 self.currently_opened_path.as_ref(),
608 Some(&query),
609 matches.into_iter(),
610 extend_old_matches,
611 );
612
613 self.selected_index = selected_match.map_or_else(
614 || self.calculate_selected_index(),
615 |m| {
616 self.matches
617 .position(&m, self.currently_opened_path.as_ref())
618 .unwrap_or(0)
619 },
620 );
621
622 self.latest_search_query = Some(query);
623 self.latest_search_did_cancel = did_cancel;
624
625 cx.notify();
626 }
627 }
628
629 fn labels_for_match(
630 &self,
631 path_match: &Match,
632 cx: &AppContext,
633 ix: usize,
634 ) -> (String, Vec<usize>, String, Vec<usize>) {
635 let (file_name, file_name_positions, full_path, full_path_positions) = match &path_match {
636 Match::History {
637 path: entry_path,
638 panel_match,
639 } => {
640 let worktree_id = entry_path.project.worktree_id;
641 let project_relative_path = &entry_path.project.path;
642 let has_worktree = self
643 .project
644 .read(cx)
645 .worktree_for_id(worktree_id, cx)
646 .is_some();
647
648 if !has_worktree {
649 if let Some(absolute_path) = &entry_path.absolute {
650 return (
651 absolute_path
652 .file_name()
653 .map_or_else(
654 || project_relative_path.to_string_lossy(),
655 |file_name| file_name.to_string_lossy(),
656 )
657 .to_string(),
658 Vec::new(),
659 absolute_path.to_string_lossy().to_string(),
660 Vec::new(),
661 );
662 }
663 }
664
665 let mut path = Arc::clone(project_relative_path);
666 if project_relative_path.as_ref() == Path::new("") {
667 if let Some(absolute_path) = &entry_path.absolute {
668 path = Arc::from(absolute_path.as_path());
669 }
670 }
671
672 let mut path_match = PathMatch {
673 score: ix as f64,
674 positions: Vec::new(),
675 worktree_id: worktree_id.to_usize(),
676 path,
677 is_dir: false, // File finder doesn't support directories
678 path_prefix: "".into(),
679 distance_to_relative_ancestor: usize::MAX,
680 };
681 if let Some(found_path_match) = &panel_match {
682 path_match
683 .positions
684 .extend(found_path_match.0.positions.iter())
685 }
686
687 self.labels_for_path_match(&path_match)
688 }
689 Match::Search(path_match) => self.labels_for_path_match(&path_match.0),
690 };
691
692 if file_name_positions.is_empty() {
693 if let Some(user_home_path) = std::env::var("HOME").ok() {
694 let user_home_path = user_home_path.trim();
695 if !user_home_path.is_empty() {
696 if (&full_path).starts_with(user_home_path) {
697 return (
698 file_name,
699 file_name_positions,
700 full_path.replace(user_home_path, "~"),
701 full_path_positions,
702 );
703 }
704 }
705 }
706 }
707
708 (
709 file_name,
710 file_name_positions,
711 full_path,
712 full_path_positions,
713 )
714 }
715
716 fn labels_for_path_match(
717 &self,
718 path_match: &PathMatch,
719 ) -> (String, Vec<usize>, String, Vec<usize>) {
720 let path = &path_match.path;
721 let path_string = path.to_string_lossy();
722 let full_path = [path_match.path_prefix.as_ref(), path_string.as_ref()].join("");
723 let mut path_positions = path_match.positions.clone();
724
725 let file_name = path.file_name().map_or_else(
726 || path_match.path_prefix.to_string(),
727 |file_name| file_name.to_string_lossy().to_string(),
728 );
729 let file_name_start = path_match.path_prefix.len() + path_string.len() - file_name.len();
730 let file_name_positions = path_positions
731 .iter()
732 .filter_map(|pos| {
733 if pos >= &file_name_start {
734 Some(pos - file_name_start)
735 } else {
736 None
737 }
738 })
739 .collect();
740
741 let full_path = full_path.trim_end_matches(&file_name).to_string();
742 path_positions.retain(|idx| *idx < full_path.len());
743
744 (file_name, file_name_positions, full_path, path_positions)
745 }
746
747 fn lookup_absolute_path(
748 &self,
749 query: FileSearchQuery,
750 cx: &mut ViewContext<'_, Picker<Self>>,
751 ) -> Task<()> {
752 cx.spawn(|picker, mut cx| async move {
753 let Some((project, fs)) = picker
754 .update(&mut cx, |picker, cx| {
755 let fs = Arc::clone(&picker.delegate.project.read(cx).fs());
756 (picker.delegate.project.clone(), fs)
757 })
758 .log_err()
759 else {
760 return;
761 };
762
763 let query_path = Path::new(query.path_query());
764 let mut path_matches = Vec::new();
765 match fs.metadata(query_path).await.log_err() {
766 Some(Some(_metadata)) => {
767 let update_result = project
768 .update(&mut cx, |project, cx| {
769 if let Some((worktree, relative_path)) =
770 project.find_worktree(query_path, cx)
771 {
772 path_matches.push(ProjectPanelOrdMatch(PathMatch {
773 score: 1.0,
774 positions: Vec::new(),
775 worktree_id: worktree.read(cx).id().to_usize(),
776 path: Arc::from(relative_path),
777 path_prefix: "".into(),
778 is_dir: false, // File finder doesn't support directories
779 distance_to_relative_ancestor: usize::MAX,
780 }));
781 }
782 })
783 .log_err();
784 if update_result.is_none() {
785 return;
786 }
787 }
788 Some(None) => {}
789 None => return,
790 }
791
792 picker
793 .update(&mut cx, |picker, cx| {
794 let picker_delegate = &mut picker.delegate;
795 let search_id = util::post_inc(&mut picker_delegate.search_count);
796 picker_delegate.set_search_matches(search_id, false, query, path_matches, cx);
797
798 anyhow::Ok(())
799 })
800 .log_err();
801 })
802 }
803
804 /// Skips first history match (that is displayed topmost) if it's currently opened.
805 fn calculate_selected_index(&self) -> usize {
806 if let Some(Match::History { path, .. }) = self.matches.get(0) {
807 if Some(path) == self.currently_opened_path.as_ref() {
808 let elements_after_first = self.matches.len() - 1;
809 if elements_after_first > 0 {
810 return 1;
811 }
812 }
813 }
814
815 0
816 }
817}
818
819impl PickerDelegate for FileFinderDelegate {
820 type ListItem = ListItem;
821
822 fn placeholder_text(&self, _cx: &mut WindowContext) -> Arc<str> {
823 "Search project files...".into()
824 }
825
826 fn match_count(&self) -> usize {
827 self.matches.len()
828 }
829
830 fn selected_index(&self) -> usize {
831 self.selected_index
832 }
833
834 fn set_selected_index(&mut self, ix: usize, cx: &mut ViewContext<Picker<Self>>) {
835 self.has_changed_selected_index = true;
836 self.selected_index = ix;
837 cx.notify();
838 }
839
840 fn separators_after_indices(&self) -> Vec<usize> {
841 if self.separate_history {
842 let first_non_history_index = self
843 .matches
844 .matches
845 .iter()
846 .enumerate()
847 .find(|(_, m)| !matches!(m, Match::History { .. }))
848 .map(|(i, _)| i);
849 if let Some(first_non_history_index) = first_non_history_index {
850 if first_non_history_index > 0 {
851 return vec![first_non_history_index - 1];
852 }
853 }
854 }
855 Vec::new()
856 }
857
858 fn update_matches(
859 &mut self,
860 raw_query: String,
861 cx: &mut ViewContext<Picker<Self>>,
862 ) -> Task<()> {
863 let raw_query = raw_query.replace(' ', "");
864 let raw_query = raw_query.trim();
865 if raw_query.is_empty() {
866 // if there was no query before, and we already have some (history) matches
867 // there's no need to update anything, since nothing has changed.
868 // We also want to populate matches set from history entries on the first update.
869 if self.latest_search_query.is_some() || self.first_update {
870 let project = self.project.read(cx);
871
872 self.latest_search_id = post_inc(&mut self.search_count);
873 self.latest_search_query = None;
874 self.matches = Matches {
875 separate_history: self.separate_history,
876 ..Matches::default()
877 };
878 self.matches.push_new_matches(
879 self.history_items.iter().filter(|history_item| {
880 project
881 .worktree_for_id(history_item.project.worktree_id, cx)
882 .is_some()
883 || (project.is_local_or_ssh() && history_item.absolute.is_some())
884 }),
885 self.currently_opened_path.as_ref(),
886 None,
887 None.into_iter(),
888 false,
889 );
890
891 self.first_update = false;
892 self.selected_index = 0;
893 }
894 cx.notify();
895 Task::ready(())
896 } else {
897 let path_position = PathWithPosition::parse_str(&raw_query);
898
899 let query = FileSearchQuery {
900 raw_query: raw_query.trim().to_owned(),
901 file_query_end: if path_position.path.to_str().unwrap_or(raw_query) == raw_query {
902 None
903 } else {
904 // Safe to unwrap as we won't get here when the unwrap in if fails
905 Some(path_position.path.to_str().unwrap().len())
906 },
907 path_position,
908 };
909
910 if Path::new(query.path_query()).is_absolute() {
911 self.lookup_absolute_path(query, cx)
912 } else {
913 self.spawn_search(query, cx)
914 }
915 }
916 }
917
918 fn confirm(&mut self, secondary: bool, cx: &mut ViewContext<Picker<FileFinderDelegate>>) {
919 if let Some(m) = self.matches.get(self.selected_index()) {
920 if let Some(workspace) = self.workspace.upgrade() {
921 let open_task = workspace.update(cx, move |workspace, cx| {
922 let split_or_open =
923 |workspace: &mut Workspace,
924 project_path,
925 cx: &mut ViewContext<Workspace>| {
926 let allow_preview =
927 PreviewTabsSettings::get_global(cx).enable_preview_from_file_finder;
928 if secondary {
929 workspace.split_path_preview(project_path, allow_preview, cx)
930 } else {
931 workspace.open_path_preview(
932 project_path,
933 None,
934 true,
935 allow_preview,
936 cx,
937 )
938 }
939 };
940 match &m {
941 Match::History { path, .. } => {
942 let worktree_id = path.project.worktree_id;
943 if workspace
944 .project()
945 .read(cx)
946 .worktree_for_id(worktree_id, cx)
947 .is_some()
948 {
949 split_or_open(
950 workspace,
951 ProjectPath {
952 worktree_id,
953 path: Arc::clone(&path.project.path),
954 },
955 cx,
956 )
957 } else {
958 match path.absolute.as_ref() {
959 Some(abs_path) => {
960 if secondary {
961 workspace.split_abs_path(
962 abs_path.to_path_buf(),
963 false,
964 cx,
965 )
966 } else {
967 workspace.open_abs_path(
968 abs_path.to_path_buf(),
969 false,
970 cx,
971 )
972 }
973 }
974 None => split_or_open(
975 workspace,
976 ProjectPath {
977 worktree_id,
978 path: Arc::clone(&path.project.path),
979 },
980 cx,
981 ),
982 }
983 }
984 }
985 Match::Search(m) => split_or_open(
986 workspace,
987 ProjectPath {
988 worktree_id: WorktreeId::from_usize(m.0.worktree_id),
989 path: m.0.path.clone(),
990 },
991 cx,
992 ),
993 }
994 });
995
996 let row = self
997 .latest_search_query
998 .as_ref()
999 .and_then(|query| query.path_position.row)
1000 .map(|row| row.saturating_sub(1));
1001 let col = self
1002 .latest_search_query
1003 .as_ref()
1004 .and_then(|query| query.path_position.column)
1005 .unwrap_or(0)
1006 .saturating_sub(1);
1007 let finder = self.file_finder.clone();
1008
1009 cx.spawn(|_, mut cx| async move {
1010 let item = open_task.await.log_err()?;
1011 if let Some(row) = row {
1012 if let Some(active_editor) = item.downcast::<Editor>() {
1013 active_editor
1014 .downgrade()
1015 .update(&mut cx, |editor, cx| {
1016 let snapshot = editor.snapshot(cx).display_snapshot;
1017 let point = snapshot
1018 .buffer_snapshot
1019 .clip_point(Point::new(row, col), Bias::Left);
1020 editor.change_selections(Some(Autoscroll::center()), cx, |s| {
1021 s.select_ranges([point..point])
1022 });
1023 })
1024 .log_err();
1025 }
1026 }
1027 finder.update(&mut cx, |_, cx| cx.emit(DismissEvent)).ok()?;
1028
1029 Some(())
1030 })
1031 .detach();
1032 }
1033 }
1034 }
1035
1036 fn dismissed(&mut self, cx: &mut ViewContext<Picker<FileFinderDelegate>>) {
1037 self.file_finder
1038 .update(cx, |_, cx| cx.emit(DismissEvent))
1039 .log_err();
1040 }
1041
1042 fn render_match(
1043 &self,
1044 ix: usize,
1045 selected: bool,
1046 cx: &mut ViewContext<Picker<Self>>,
1047 ) -> Option<Self::ListItem> {
1048 let path_match = self
1049 .matches
1050 .get(ix)
1051 .expect("Invalid matches state: no element for index {ix}");
1052
1053 let icon = match &path_match {
1054 Match::History { .. } => Icon::new(IconName::HistoryRerun)
1055 .color(Color::Muted)
1056 .size(IconSize::Small)
1057 .into_any_element(),
1058 Match::Search(_) => v_flex()
1059 .flex_none()
1060 .size(IconSize::Small.rems())
1061 .into_any_element(),
1062 };
1063 let (file_name, file_name_positions, full_path, full_path_positions) =
1064 self.labels_for_match(path_match, cx, ix);
1065
1066 Some(
1067 ListItem::new(ix)
1068 .spacing(ListItemSpacing::Sparse)
1069 .end_slot::<AnyElement>(Some(icon))
1070 .inset(true)
1071 .selected(selected)
1072 .child(
1073 h_flex()
1074 .gap_2()
1075 .py_px()
1076 .child(HighlightedLabel::new(file_name, file_name_positions))
1077 .child(
1078 HighlightedLabel::new(full_path, full_path_positions)
1079 .size(LabelSize::Small)
1080 .color(Color::Muted),
1081 ),
1082 ),
1083 )
1084 }
1085}
1086
1087#[cfg(test)]
1088mod tests {
1089 use super::*;
1090
1091 #[test]
1092 fn test_custom_project_search_ordering_in_file_finder() {
1093 let mut file_finder_sorted_output = vec![
1094 ProjectPanelOrdMatch(PathMatch {
1095 score: 0.5,
1096 positions: Vec::new(),
1097 worktree_id: 0,
1098 path: Arc::from(Path::new("b0.5")),
1099 path_prefix: Arc::default(),
1100 distance_to_relative_ancestor: 0,
1101 is_dir: false,
1102 }),
1103 ProjectPanelOrdMatch(PathMatch {
1104 score: 1.0,
1105 positions: Vec::new(),
1106 worktree_id: 0,
1107 path: Arc::from(Path::new("c1.0")),
1108 path_prefix: Arc::default(),
1109 distance_to_relative_ancestor: 0,
1110 is_dir: false,
1111 }),
1112 ProjectPanelOrdMatch(PathMatch {
1113 score: 1.0,
1114 positions: Vec::new(),
1115 worktree_id: 0,
1116 path: Arc::from(Path::new("a1.0")),
1117 path_prefix: Arc::default(),
1118 distance_to_relative_ancestor: 0,
1119 is_dir: false,
1120 }),
1121 ProjectPanelOrdMatch(PathMatch {
1122 score: 0.5,
1123 positions: Vec::new(),
1124 worktree_id: 0,
1125 path: Arc::from(Path::new("a0.5")),
1126 path_prefix: Arc::default(),
1127 distance_to_relative_ancestor: 0,
1128 is_dir: false,
1129 }),
1130 ProjectPanelOrdMatch(PathMatch {
1131 score: 1.0,
1132 positions: Vec::new(),
1133 worktree_id: 0,
1134 path: Arc::from(Path::new("b1.0")),
1135 path_prefix: Arc::default(),
1136 distance_to_relative_ancestor: 0,
1137 is_dir: false,
1138 }),
1139 ];
1140 file_finder_sorted_output.sort_by(|a, b| b.cmp(a));
1141
1142 assert_eq!(
1143 file_finder_sorted_output,
1144 vec![
1145 ProjectPanelOrdMatch(PathMatch {
1146 score: 1.0,
1147 positions: Vec::new(),
1148 worktree_id: 0,
1149 path: Arc::from(Path::new("a1.0")),
1150 path_prefix: Arc::default(),
1151 distance_to_relative_ancestor: 0,
1152 is_dir: false,
1153 }),
1154 ProjectPanelOrdMatch(PathMatch {
1155 score: 1.0,
1156 positions: Vec::new(),
1157 worktree_id: 0,
1158 path: Arc::from(Path::new("b1.0")),
1159 path_prefix: Arc::default(),
1160 distance_to_relative_ancestor: 0,
1161 is_dir: false,
1162 }),
1163 ProjectPanelOrdMatch(PathMatch {
1164 score: 1.0,
1165 positions: Vec::new(),
1166 worktree_id: 0,
1167 path: Arc::from(Path::new("c1.0")),
1168 path_prefix: Arc::default(),
1169 distance_to_relative_ancestor: 0,
1170 is_dir: false,
1171 }),
1172 ProjectPanelOrdMatch(PathMatch {
1173 score: 0.5,
1174 positions: Vec::new(),
1175 worktree_id: 0,
1176 path: Arc::from(Path::new("a0.5")),
1177 path_prefix: Arc::default(),
1178 distance_to_relative_ancestor: 0,
1179 is_dir: false,
1180 }),
1181 ProjectPanelOrdMatch(PathMatch {
1182 score: 0.5,
1183 positions: Vec::new(),
1184 worktree_id: 0,
1185 path: Arc::from(Path::new("b0.5")),
1186 path_prefix: Arc::default(),
1187 distance_to_relative_ancestor: 0,
1188 is_dir: false,
1189 }),
1190 ]
1191 );
1192 }
1193}