1use collections::HashMap;
2use editor::{scroll::autoscroll::Autoscroll, Bias, Editor};
3use fuzzy::{CharBag, PathMatch, PathMatchCandidate};
4use gpui::{
5 actions, AppContext, DismissEvent, Div, EventEmitter, FocusHandle, FocusableView, Model,
6 ParentElement, Render, Styled, Task, View, ViewContext, VisualContext, WeakView,
7};
8use picker::{Picker, PickerDelegate};
9use project::{PathMatchCandidateSet, Project, ProjectPath, WorktreeId};
10use std::{
11 path::{Path, PathBuf},
12 sync::{
13 atomic::{self, AtomicBool},
14 Arc,
15 },
16};
17use text::Point;
18use ui::{prelude::*, v_stack, HighlightedLabel, ListItem};
19use util::{paths::PathLikeWithPosition, post_inc, ResultExt};
20use workspace::Workspace;
21
22actions!(Toggle);
23
24pub struct FileFinder {
25 picker: View<Picker<FileFinderDelegate>>,
26}
27
28pub fn init(cx: &mut AppContext) {
29 cx.observe_new_views(FileFinder::register).detach();
30}
31
32impl FileFinder {
33 fn register(workspace: &mut Workspace, _: &mut ViewContext<Workspace>) {
34 workspace.register_action(|workspace, _: &Toggle, cx| {
35 let Some(file_finder) = workspace.active_modal::<Self>(cx) else {
36 Self::open(workspace, cx);
37 return;
38 };
39
40 file_finder.update(cx, |file_finder, cx| {
41 file_finder
42 .picker
43 .update(cx, |picker, cx| picker.cycle_selection(cx))
44 });
45 });
46 }
47
48 fn open(workspace: &mut Workspace, cx: &mut ViewContext<Workspace>) {
49 let project = workspace.project().read(cx);
50
51 let currently_opened_path = workspace
52 .active_item(cx)
53 .and_then(|item| item.project_path(cx))
54 .map(|project_path| {
55 let abs_path = project
56 .worktree_for_id(project_path.worktree_id, cx)
57 .map(|worktree| worktree.read(cx).abs_path().join(&project_path.path));
58 FoundPath::new(project_path, abs_path)
59 });
60
61 // if exists, bubble the currently opened path to the top
62 let history_items = currently_opened_path
63 .clone()
64 .into_iter()
65 .chain(
66 workspace
67 .recent_navigation_history(Some(MAX_RECENT_SELECTIONS), cx)
68 .into_iter()
69 .filter(|(history_path, _)| {
70 Some(history_path)
71 != currently_opened_path
72 .as_ref()
73 .map(|found_path| &found_path.project)
74 })
75 .filter(|(_, history_abs_path)| {
76 history_abs_path.as_ref()
77 != currently_opened_path
78 .as_ref()
79 .and_then(|found_path| found_path.absolute.as_ref())
80 })
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 )
87 .collect();
88
89 let project = workspace.project().clone();
90 let weak_workspace = cx.view().downgrade();
91 workspace.toggle_modal(cx, |cx| {
92 let delegate = FileFinderDelegate::new(
93 cx.view().downgrade(),
94 weak_workspace,
95 project,
96 currently_opened_path,
97 history_items,
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.build_view(|cx| Picker::new(delegate, cx)),
108 }
109 }
110}
111
112impl EventEmitter<DismissEvent> for FileFinder {}
113impl FocusableView for FileFinder {
114 fn focus_handle(&self, cx: &AppContext) -> FocusHandle {
115 self.picker.focus_handle(cx)
116 }
117}
118impl Render for FileFinder {
119 type Element = Div;
120
121 fn render(&mut self, _cx: &mut ViewContext<Self>) -> Self::Element {
122 v_stack().w_96().child(self.picker.clone())
123 }
124}
125
126pub struct FileFinderDelegate {
127 file_finder: WeakView<FileFinder>,
128 workspace: WeakView<Workspace>,
129 project: Model<Project>,
130 search_count: usize,
131 latest_search_id: usize,
132 latest_search_did_cancel: bool,
133 latest_search_query: Option<PathLikeWithPosition<FileSearchQuery>>,
134 currently_opened_path: Option<FoundPath>,
135 matches: Matches,
136 selected_index: Option<usize>,
137 cancel_flag: Arc<AtomicBool>,
138 history_items: Vec<FoundPath>,
139}
140
141#[derive(Debug, Default)]
142struct Matches {
143 history: Vec<(FoundPath, Option<PathMatch>)>,
144 search: Vec<PathMatch>,
145}
146
147#[derive(Debug)]
148enum Match<'a> {
149 History(&'a FoundPath, Option<&'a PathMatch>),
150 Search(&'a PathMatch),
151}
152
153impl Matches {
154 fn len(&self) -> usize {
155 self.history.len() + self.search.len()
156 }
157
158 fn get(&self, index: usize) -> Option<Match<'_>> {
159 if index < self.history.len() {
160 self.history
161 .get(index)
162 .map(|(path, path_match)| Match::History(path, path_match.as_ref()))
163 } else {
164 self.search
165 .get(index - self.history.len())
166 .map(Match::Search)
167 }
168 }
169
170 fn push_new_matches(
171 &mut self,
172 history_items: &Vec<FoundPath>,
173 query: &PathLikeWithPosition<FileSearchQuery>,
174 mut new_search_matches: Vec<PathMatch>,
175 extend_old_matches: bool,
176 ) {
177 let matching_history_paths = matching_history_item_paths(history_items, query);
178 new_search_matches
179 .retain(|path_match| !matching_history_paths.contains_key(&path_match.path));
180 let history_items_to_show = history_items
181 .iter()
182 .filter_map(|history_item| {
183 Some((
184 history_item.clone(),
185 Some(
186 matching_history_paths
187 .get(&history_item.project.path)?
188 .clone(),
189 ),
190 ))
191 })
192 .collect::<Vec<_>>();
193 self.history = history_items_to_show;
194 if extend_old_matches {
195 self.search
196 .retain(|path_match| !matching_history_paths.contains_key(&path_match.path));
197 util::extend_sorted(
198 &mut self.search,
199 new_search_matches.into_iter(),
200 100,
201 |a, b| b.cmp(a),
202 )
203 } else {
204 self.search = new_search_matches;
205 }
206 }
207}
208
209fn matching_history_item_paths(
210 history_items: &Vec<FoundPath>,
211 query: &PathLikeWithPosition<FileSearchQuery>,
212) -> HashMap<Arc<Path>, PathMatch> {
213 let history_items_by_worktrees = history_items
214 .iter()
215 .filter_map(|found_path| {
216 let candidate = PathMatchCandidate {
217 path: &found_path.project.path,
218 // Only match history items names, otherwise their paths may match too many queries, producing false positives.
219 // E.g. `foo` would match both `something/foo/bar.rs` and `something/foo/foo.rs` and if the former is a history item,
220 // it would be shown first always, despite the latter being a better match.
221 char_bag: CharBag::from_iter(
222 found_path
223 .project
224 .path
225 .file_name()?
226 .to_string_lossy()
227 .to_lowercase()
228 .chars(),
229 ),
230 };
231 Some((found_path.project.worktree_id, candidate))
232 })
233 .fold(
234 HashMap::default(),
235 |mut candidates, (worktree_id, new_candidate)| {
236 candidates
237 .entry(worktree_id)
238 .or_insert_with(Vec::new)
239 .push(new_candidate);
240 candidates
241 },
242 );
243 let mut matching_history_paths = HashMap::default();
244 for (worktree, candidates) in history_items_by_worktrees {
245 let max_results = candidates.len() + 1;
246 matching_history_paths.extend(
247 fuzzy::match_fixed_path_set(
248 candidates,
249 worktree.to_usize(),
250 query.path_like.path_query(),
251 false,
252 max_results,
253 )
254 .into_iter()
255 .map(|path_match| (Arc::clone(&path_match.path), path_match)),
256 );
257 }
258 matching_history_paths
259}
260
261#[derive(Debug, Clone, PartialEq, Eq)]
262struct FoundPath {
263 project: ProjectPath,
264 absolute: Option<PathBuf>,
265}
266
267impl FoundPath {
268 fn new(project: ProjectPath, absolute: Option<PathBuf>) -> Self {
269 Self { project, absolute }
270 }
271}
272
273const MAX_RECENT_SELECTIONS: usize = 20;
274
275#[cfg(not(test))]
276fn history_file_exists(abs_path: &PathBuf) -> bool {
277 abs_path.exists()
278}
279
280#[cfg(test)]
281fn history_file_exists(abs_path: &PathBuf) -> bool {
282 !abs_path.ends_with("nonexistent.rs")
283}
284
285pub enum Event {
286 Selected(ProjectPath),
287 Dismissed,
288}
289
290#[derive(Debug, Clone)]
291struct FileSearchQuery {
292 raw_query: String,
293 file_query_end: Option<usize>,
294}
295
296impl FileSearchQuery {
297 fn path_query(&self) -> &str {
298 match self.file_query_end {
299 Some(file_path_end) => &self.raw_query[..file_path_end],
300 None => &self.raw_query,
301 }
302 }
303}
304
305impl FileFinderDelegate {
306 fn new(
307 file_finder: WeakView<FileFinder>,
308 workspace: WeakView<Workspace>,
309 project: Model<Project>,
310 currently_opened_path: Option<FoundPath>,
311 history_items: Vec<FoundPath>,
312 cx: &mut ViewContext<FileFinder>,
313 ) -> Self {
314 cx.observe(&project, |file_finder, _, cx| {
315 //todo!() We should probably not re-render on every project anything
316 file_finder
317 .picker
318 .update(cx, |picker, cx| picker.refresh(cx))
319 })
320 .detach();
321
322 Self {
323 file_finder,
324 workspace,
325 project,
326 search_count: 0,
327 latest_search_id: 0,
328 latest_search_did_cancel: false,
329 latest_search_query: None,
330 currently_opened_path,
331 matches: Matches::default(),
332 selected_index: None,
333 cancel_flag: Arc::new(AtomicBool::new(false)),
334 history_items,
335 }
336 }
337
338 fn spawn_search(
339 &mut self,
340 query: PathLikeWithPosition<FileSearchQuery>,
341 cx: &mut ViewContext<Picker<Self>>,
342 ) -> Task<()> {
343 let relative_to = self
344 .currently_opened_path
345 .as_ref()
346 .map(|found_path| Arc::clone(&found_path.project.path));
347 let worktrees = self
348 .project
349 .read(cx)
350 .visible_worktrees(cx)
351 .collect::<Vec<_>>();
352 let include_root_name = worktrees.len() > 1;
353 let candidate_sets = worktrees
354 .into_iter()
355 .map(|worktree| {
356 let worktree = worktree.read(cx);
357 PathMatchCandidateSet {
358 snapshot: worktree.snapshot(),
359 include_ignored: worktree
360 .root_entry()
361 .map_or(false, |entry| entry.is_ignored),
362 include_root_name,
363 }
364 })
365 .collect::<Vec<_>>();
366
367 let search_id = util::post_inc(&mut self.search_count);
368 self.cancel_flag.store(true, atomic::Ordering::Relaxed);
369 self.cancel_flag = Arc::new(AtomicBool::new(false));
370 let cancel_flag = self.cancel_flag.clone();
371 cx.spawn(|picker, mut cx| async move {
372 let matches = fuzzy::match_path_sets(
373 candidate_sets.as_slice(),
374 query.path_like.path_query(),
375 relative_to,
376 false,
377 100,
378 &cancel_flag,
379 cx.background_executor().clone(),
380 )
381 .await;
382 let did_cancel = cancel_flag.load(atomic::Ordering::Relaxed);
383 picker
384 .update(&mut cx, |picker, cx| {
385 picker
386 .delegate
387 .set_search_matches(search_id, did_cancel, query, matches, cx)
388 })
389 .log_err();
390 })
391 }
392
393 fn set_search_matches(
394 &mut self,
395 search_id: usize,
396 did_cancel: bool,
397 query: PathLikeWithPosition<FileSearchQuery>,
398 matches: Vec<PathMatch>,
399 cx: &mut ViewContext<Picker<Self>>,
400 ) {
401 if search_id >= self.latest_search_id {
402 self.latest_search_id = search_id;
403 let extend_old_matches = self.latest_search_did_cancel
404 && Some(query.path_like.path_query())
405 == self
406 .latest_search_query
407 .as_ref()
408 .map(|query| query.path_like.path_query());
409 self.matches
410 .push_new_matches(&self.history_items, &query, matches, extend_old_matches);
411 self.latest_search_query = Some(query);
412 self.latest_search_did_cancel = did_cancel;
413 cx.notify();
414 }
415 }
416
417 fn labels_for_match(
418 &self,
419 path_match: Match,
420 cx: &AppContext,
421 ix: usize,
422 ) -> (String, Vec<usize>, String, Vec<usize>) {
423 let (file_name, file_name_positions, full_path, full_path_positions) = match path_match {
424 Match::History(found_path, found_path_match) => {
425 let worktree_id = found_path.project.worktree_id;
426 let project_relative_path = &found_path.project.path;
427 let has_worktree = self
428 .project
429 .read(cx)
430 .worktree_for_id(worktree_id, cx)
431 .is_some();
432
433 if !has_worktree {
434 if let Some(absolute_path) = &found_path.absolute {
435 return (
436 absolute_path
437 .file_name()
438 .map_or_else(
439 || project_relative_path.to_string_lossy(),
440 |file_name| file_name.to_string_lossy(),
441 )
442 .to_string(),
443 Vec::new(),
444 absolute_path.to_string_lossy().to_string(),
445 Vec::new(),
446 );
447 }
448 }
449
450 let mut path = Arc::clone(project_relative_path);
451 if project_relative_path.as_ref() == Path::new("") {
452 if let Some(absolute_path) = &found_path.absolute {
453 path = Arc::from(absolute_path.as_path());
454 }
455 }
456
457 let mut path_match = PathMatch {
458 score: ix as f64,
459 positions: Vec::new(),
460 worktree_id: worktree_id.to_usize(),
461 path,
462 path_prefix: "".into(),
463 distance_to_relative_ancestor: usize::MAX,
464 };
465 if let Some(found_path_match) = found_path_match {
466 path_match
467 .positions
468 .extend(found_path_match.positions.iter())
469 }
470
471 self.labels_for_path_match(&path_match)
472 }
473 Match::Search(path_match) => self.labels_for_path_match(path_match),
474 };
475
476 if file_name_positions.is_empty() {
477 if let Some(user_home_path) = std::env::var("HOME").ok() {
478 let user_home_path = user_home_path.trim();
479 if !user_home_path.is_empty() {
480 if (&full_path).starts_with(user_home_path) {
481 return (
482 file_name,
483 file_name_positions,
484 full_path.replace(user_home_path, "~"),
485 full_path_positions,
486 );
487 }
488 }
489 }
490 }
491
492 (
493 file_name,
494 file_name_positions,
495 full_path,
496 full_path_positions,
497 )
498 }
499
500 fn labels_for_path_match(
501 &self,
502 path_match: &PathMatch,
503 ) -> (String, Vec<usize>, String, Vec<usize>) {
504 let path = &path_match.path;
505 let path_string = path.to_string_lossy();
506 let full_path = [path_match.path_prefix.as_ref(), path_string.as_ref()].join("");
507 let path_positions = path_match.positions.clone();
508
509 let file_name = path.file_name().map_or_else(
510 || path_match.path_prefix.to_string(),
511 |file_name| file_name.to_string_lossy().to_string(),
512 );
513 let file_name_start = path_match.path_prefix.chars().count() + path_string.chars().count()
514 - file_name.chars().count();
515 let file_name_positions = path_positions
516 .iter()
517 .filter_map(|pos| {
518 if pos >= &file_name_start {
519 Some(pos - file_name_start)
520 } else {
521 None
522 }
523 })
524 .collect();
525
526 (file_name, file_name_positions, full_path, path_positions)
527 }
528}
529
530impl PickerDelegate for FileFinderDelegate {
531 type ListItem = ListItem;
532
533 fn placeholder_text(&self) -> Arc<str> {
534 "Search project files...".into()
535 }
536
537 fn match_count(&self) -> usize {
538 self.matches.len()
539 }
540
541 fn selected_index(&self) -> usize {
542 self.selected_index.unwrap_or(0)
543 }
544
545 fn set_selected_index(&mut self, ix: usize, cx: &mut ViewContext<Picker<Self>>) {
546 self.selected_index = Some(ix);
547 cx.notify();
548 }
549
550 fn update_matches(
551 &mut self,
552 raw_query: String,
553 cx: &mut ViewContext<Picker<Self>>,
554 ) -> Task<()> {
555 let raw_query = raw_query.trim();
556 if raw_query.is_empty() {
557 let project = self.project.read(cx);
558 self.latest_search_id = post_inc(&mut self.search_count);
559 self.matches = Matches {
560 history: self
561 .history_items
562 .iter()
563 .filter(|history_item| {
564 project
565 .worktree_for_id(history_item.project.worktree_id, cx)
566 .is_some()
567 || (project.is_local() && history_item.absolute.is_some())
568 })
569 .cloned()
570 .map(|p| (p, None))
571 .collect(),
572 search: Vec::new(),
573 };
574 cx.notify();
575 Task::ready(())
576 } else {
577 let query = PathLikeWithPosition::parse_str(raw_query, |path_like_str| {
578 Ok::<_, std::convert::Infallible>(FileSearchQuery {
579 raw_query: raw_query.to_owned(),
580 file_query_end: if path_like_str == raw_query {
581 None
582 } else {
583 Some(path_like_str.len())
584 },
585 })
586 })
587 .expect("infallible");
588 self.spawn_search(query, cx)
589 }
590 }
591
592 fn confirm(&mut self, secondary: bool, cx: &mut ViewContext<Picker<FileFinderDelegate>>) {
593 if let Some(m) = self.matches.get(self.selected_index()) {
594 if let Some(workspace) = self.workspace.upgrade() {
595 let open_task = workspace.update(cx, move |workspace, cx| {
596 let split_or_open = |workspace: &mut Workspace, project_path, cx| {
597 if secondary {
598 workspace.split_path(project_path, cx)
599 } else {
600 workspace.open_path(project_path, None, true, cx)
601 }
602 };
603 match m {
604 Match::History(history_match, _) => {
605 let worktree_id = history_match.project.worktree_id;
606 if workspace
607 .project()
608 .read(cx)
609 .worktree_for_id(worktree_id, cx)
610 .is_some()
611 {
612 split_or_open(
613 workspace,
614 ProjectPath {
615 worktree_id,
616 path: Arc::clone(&history_match.project.path),
617 },
618 cx,
619 )
620 } else {
621 match history_match.absolute.as_ref() {
622 Some(abs_path) => {
623 if secondary {
624 workspace.split_abs_path(
625 abs_path.to_path_buf(),
626 false,
627 cx,
628 )
629 } else {
630 workspace.open_abs_path(
631 abs_path.to_path_buf(),
632 false,
633 cx,
634 )
635 }
636 }
637 None => split_or_open(
638 workspace,
639 ProjectPath {
640 worktree_id,
641 path: Arc::clone(&history_match.project.path),
642 },
643 cx,
644 ),
645 }
646 }
647 }
648 Match::Search(m) => split_or_open(
649 workspace,
650 ProjectPath {
651 worktree_id: WorktreeId::from_usize(m.worktree_id),
652 path: m.path.clone(),
653 },
654 cx,
655 ),
656 }
657 });
658
659 let row = self
660 .latest_search_query
661 .as_ref()
662 .and_then(|query| query.row)
663 .map(|row| row.saturating_sub(1));
664 let col = self
665 .latest_search_query
666 .as_ref()
667 .and_then(|query| query.column)
668 .unwrap_or(0)
669 .saturating_sub(1);
670 let finder = self.file_finder.clone();
671
672 cx.spawn(|_, mut cx| async move {
673 let item = open_task.await.log_err()?;
674 if let Some(row) = row {
675 if let Some(active_editor) = item.downcast::<Editor>() {
676 active_editor
677 .downgrade()
678 .update(&mut cx, |editor, cx| {
679 let snapshot = editor.snapshot(cx).display_snapshot;
680 let point = snapshot
681 .buffer_snapshot
682 .clip_point(Point::new(row, col), Bias::Left);
683 editor.change_selections(Some(Autoscroll::center()), cx, |s| {
684 s.select_ranges([point..point])
685 });
686 })
687 .log_err();
688 }
689 }
690 finder.update(&mut cx, |_, cx| cx.emit(DismissEvent)).ok()?;
691
692 Some(())
693 })
694 .detach();
695 }
696 }
697 }
698
699 fn dismissed(&mut self, cx: &mut ViewContext<Picker<FileFinderDelegate>>) {
700 self.file_finder
701 .update(cx, |_, cx| cx.emit(DismissEvent))
702 .log_err();
703 }
704
705 fn render_match(
706 &self,
707 ix: usize,
708 selected: bool,
709 cx: &mut ViewContext<Picker<Self>>,
710 ) -> Option<Self::ListItem> {
711 let path_match = self
712 .matches
713 .get(ix)
714 .expect("Invalid matches state: no element for index {ix}");
715
716 let (file_name, file_name_positions, full_path, full_path_positions) =
717 self.labels_for_match(path_match, cx, ix);
718
719 Some(
720 ListItem::new(ix).inset(true).selected(selected).child(
721 v_stack()
722 .child(HighlightedLabel::new(file_name, file_name_positions))
723 .child(HighlightedLabel::new(full_path, full_path_positions)),
724 ),
725 )
726 }
727}
728
729#[cfg(test)]
730mod tests {
731 use std::{assert_eq, path::Path, time::Duration};
732
733 use super::*;
734 use editor::Editor;
735 use gpui::{Entity, TestAppContext, VisualTestContext};
736 use menu::{Confirm, SelectNext};
737 use serde_json::json;
738 use workspace::{AppState, Workspace};
739
740 #[ctor::ctor]
741 fn init_logger() {
742 if std::env::var("RUST_LOG").is_ok() {
743 env_logger::init();
744 }
745 }
746
747 #[gpui::test]
748 async fn test_matching_paths(cx: &mut TestAppContext) {
749 let app_state = init_test(cx);
750 app_state
751 .fs
752 .as_fake()
753 .insert_tree(
754 "/root",
755 json!({
756 "a": {
757 "banana": "",
758 "bandana": "",
759 }
760 }),
761 )
762 .await;
763
764 let project = Project::test(app_state.fs.clone(), ["/root".as_ref()], cx).await;
765
766 let (picker, workspace, cx) = build_find_picker(project, cx);
767
768 cx.simulate_input("bna");
769 picker.update(cx, |picker, _| {
770 assert_eq!(picker.delegate.matches.len(), 2);
771 });
772 cx.dispatch_action(SelectNext);
773 cx.dispatch_action(Confirm);
774 cx.read(|cx| {
775 let active_editor = workspace.read(cx).active_item_as::<Editor>(cx).unwrap();
776 assert_eq!(active_editor.read(cx).title(cx), "bandana");
777 });
778
779 for bandana_query in [
780 "bandana",
781 " bandana",
782 "bandana ",
783 " bandana ",
784 " ndan ",
785 " band ",
786 ] {
787 picker
788 .update(cx, |picker, cx| {
789 picker
790 .delegate
791 .update_matches(bandana_query.to_string(), cx)
792 })
793 .await;
794 picker.update(cx, |picker, _| {
795 assert_eq!(
796 picker.delegate.matches.len(),
797 1,
798 "Wrong number of matches for bandana query '{bandana_query}'"
799 );
800 });
801 cx.dispatch_action(SelectNext);
802 cx.dispatch_action(Confirm);
803 cx.read(|cx| {
804 let active_editor = workspace.read(cx).active_item_as::<Editor>(cx).unwrap();
805 assert_eq!(
806 active_editor.read(cx).title(cx),
807 "bandana",
808 "Wrong match for bandana query '{bandana_query}'"
809 );
810 });
811 }
812 }
813
814 #[gpui::test]
815 async fn test_row_column_numbers_query_inside_file(cx: &mut TestAppContext) {
816 let app_state = init_test(cx);
817
818 let first_file_name = "first.rs";
819 let first_file_contents = "// First Rust file";
820 app_state
821 .fs
822 .as_fake()
823 .insert_tree(
824 "/src",
825 json!({
826 "test": {
827 first_file_name: first_file_contents,
828 "second.rs": "// Second Rust file",
829 }
830 }),
831 )
832 .await;
833
834 let project = Project::test(app_state.fs.clone(), ["/src".as_ref()], cx).await;
835
836 let (picker, workspace, cx) = build_find_picker(project, cx);
837
838 let file_query = &first_file_name[..3];
839 let file_row = 1;
840 let file_column = 3;
841 assert!(file_column <= first_file_contents.len());
842 let query_inside_file = format!("{file_query}:{file_row}:{file_column}");
843 picker
844 .update(cx, |finder, cx| {
845 finder
846 .delegate
847 .update_matches(query_inside_file.to_string(), cx)
848 })
849 .await;
850 picker.update(cx, |finder, _| {
851 let finder = &finder.delegate;
852 assert_eq!(finder.matches.len(), 1);
853 let latest_search_query = finder
854 .latest_search_query
855 .as_ref()
856 .expect("Finder should have a query after the update_matches call");
857 assert_eq!(latest_search_query.path_like.raw_query, query_inside_file);
858 assert_eq!(
859 latest_search_query.path_like.file_query_end,
860 Some(file_query.len())
861 );
862 assert_eq!(latest_search_query.row, Some(file_row));
863 assert_eq!(latest_search_query.column, Some(file_column as u32));
864 });
865
866 cx.dispatch_action(SelectNext);
867 cx.dispatch_action(Confirm);
868
869 let editor = cx.update(|cx| workspace.read(cx).active_item_as::<Editor>(cx).unwrap());
870 cx.executor().advance_clock(Duration::from_secs(2));
871
872 editor.update(cx, |editor, cx| {
873 let all_selections = editor.selections.all_adjusted(cx);
874 assert_eq!(
875 all_selections.len(),
876 1,
877 "Expected to have 1 selection (caret) after file finder confirm, but got: {all_selections:?}"
878 );
879 let caret_selection = all_selections.into_iter().next().unwrap();
880 assert_eq!(caret_selection.start, caret_selection.end,
881 "Caret selection should have its start and end at the same position");
882 assert_eq!(file_row, caret_selection.start.row + 1,
883 "Query inside file should get caret with the same focus row");
884 assert_eq!(file_column, caret_selection.start.column as usize + 1,
885 "Query inside file should get caret with the same focus column");
886 });
887 }
888
889 #[gpui::test]
890 async fn test_row_column_numbers_query_outside_file(cx: &mut TestAppContext) {
891 let app_state = init_test(cx);
892
893 let first_file_name = "first.rs";
894 let first_file_contents = "// First Rust file";
895 app_state
896 .fs
897 .as_fake()
898 .insert_tree(
899 "/src",
900 json!({
901 "test": {
902 first_file_name: first_file_contents,
903 "second.rs": "// Second Rust file",
904 }
905 }),
906 )
907 .await;
908
909 let project = Project::test(app_state.fs.clone(), ["/src".as_ref()], cx).await;
910
911 let (picker, workspace, cx) = build_find_picker(project, cx);
912
913 let file_query = &first_file_name[..3];
914 let file_row = 200;
915 let file_column = 300;
916 assert!(file_column > first_file_contents.len());
917 let query_outside_file = format!("{file_query}:{file_row}:{file_column}");
918 picker
919 .update(cx, |picker, cx| {
920 picker
921 .delegate
922 .update_matches(query_outside_file.to_string(), cx)
923 })
924 .await;
925 picker.update(cx, |finder, _| {
926 let delegate = &finder.delegate;
927 assert_eq!(delegate.matches.len(), 1);
928 let latest_search_query = delegate
929 .latest_search_query
930 .as_ref()
931 .expect("Finder should have a query after the update_matches call");
932 assert_eq!(latest_search_query.path_like.raw_query, query_outside_file);
933 assert_eq!(
934 latest_search_query.path_like.file_query_end,
935 Some(file_query.len())
936 );
937 assert_eq!(latest_search_query.row, Some(file_row));
938 assert_eq!(latest_search_query.column, Some(file_column as u32));
939 });
940
941 cx.dispatch_action(SelectNext);
942 cx.dispatch_action(Confirm);
943
944 let editor = cx.update(|cx| workspace.read(cx).active_item_as::<Editor>(cx).unwrap());
945 cx.executor().advance_clock(Duration::from_secs(2));
946
947 editor.update(cx, |editor, cx| {
948 let all_selections = editor.selections.all_adjusted(cx);
949 assert_eq!(
950 all_selections.len(),
951 1,
952 "Expected to have 1 selection (caret) after file finder confirm, but got: {all_selections:?}"
953 );
954 let caret_selection = all_selections.into_iter().next().unwrap();
955 assert_eq!(caret_selection.start, caret_selection.end,
956 "Caret selection should have its start and end at the same position");
957 assert_eq!(0, caret_selection.start.row,
958 "Excessive rows (as in query outside file borders) should get trimmed to last file row");
959 assert_eq!(first_file_contents.len(), caret_selection.start.column as usize,
960 "Excessive columns (as in query outside file borders) should get trimmed to selected row's last column");
961 });
962 }
963
964 #[gpui::test]
965 async fn test_matching_cancellation(cx: &mut TestAppContext) {
966 let app_state = init_test(cx);
967 app_state
968 .fs
969 .as_fake()
970 .insert_tree(
971 "/dir",
972 json!({
973 "hello": "",
974 "goodbye": "",
975 "halogen-light": "",
976 "happiness": "",
977 "height": "",
978 "hi": "",
979 "hiccup": "",
980 }),
981 )
982 .await;
983
984 let project = Project::test(app_state.fs.clone(), ["/dir".as_ref()], cx).await;
985
986 let (picker, _, cx) = build_find_picker(project, cx);
987
988 let query = test_path_like("hi");
989 picker
990 .update(cx, |picker, cx| {
991 picker.delegate.spawn_search(query.clone(), cx)
992 })
993 .await;
994
995 picker.update(cx, |picker, _cx| {
996 assert_eq!(picker.delegate.matches.len(), 5)
997 });
998
999 picker.update(cx, |picker, cx| {
1000 let delegate = &mut picker.delegate;
1001 assert!(
1002 delegate.matches.history.is_empty(),
1003 "Search matches expected"
1004 );
1005 let matches = delegate.matches.search.clone();
1006
1007 // Simulate a search being cancelled after the time limit,
1008 // returning only a subset of the matches that would have been found.
1009 drop(delegate.spawn_search(query.clone(), cx));
1010 delegate.set_search_matches(
1011 delegate.latest_search_id,
1012 true, // did-cancel
1013 query.clone(),
1014 vec![matches[1].clone(), matches[3].clone()],
1015 cx,
1016 );
1017
1018 // Simulate another cancellation.
1019 drop(delegate.spawn_search(query.clone(), cx));
1020 delegate.set_search_matches(
1021 delegate.latest_search_id,
1022 true, // did-cancel
1023 query.clone(),
1024 vec![matches[0].clone(), matches[2].clone(), matches[3].clone()],
1025 cx,
1026 );
1027
1028 assert!(
1029 delegate.matches.history.is_empty(),
1030 "Search matches expected"
1031 );
1032 assert_eq!(delegate.matches.search.as_slice(), &matches[0..4]);
1033 });
1034 }
1035
1036 #[gpui::test]
1037 async fn test_ignored_files(cx: &mut TestAppContext) {
1038 let app_state = init_test(cx);
1039 app_state
1040 .fs
1041 .as_fake()
1042 .insert_tree(
1043 "/ancestor",
1044 json!({
1045 ".gitignore": "ignored-root",
1046 "ignored-root": {
1047 "happiness": "",
1048 "height": "",
1049 "hi": "",
1050 "hiccup": "",
1051 },
1052 "tracked-root": {
1053 ".gitignore": "height",
1054 "happiness": "",
1055 "height": "",
1056 "hi": "",
1057 "hiccup": "",
1058 },
1059 }),
1060 )
1061 .await;
1062
1063 let project = Project::test(
1064 app_state.fs.clone(),
1065 [
1066 "/ancestor/tracked-root".as_ref(),
1067 "/ancestor/ignored-root".as_ref(),
1068 ],
1069 cx,
1070 )
1071 .await;
1072
1073 let (picker, _, cx) = build_find_picker(project, cx);
1074
1075 picker
1076 .update(cx, |picker, cx| {
1077 picker.delegate.spawn_search(test_path_like("hi"), cx)
1078 })
1079 .await;
1080 picker.update(cx, |picker, _| assert_eq!(picker.delegate.matches.len(), 7));
1081 }
1082
1083 #[gpui::test]
1084 async fn test_single_file_worktrees(cx: &mut TestAppContext) {
1085 let app_state = init_test(cx);
1086 app_state
1087 .fs
1088 .as_fake()
1089 .insert_tree("/root", json!({ "the-parent-dir": { "the-file": "" } }))
1090 .await;
1091
1092 let project = Project::test(
1093 app_state.fs.clone(),
1094 ["/root/the-parent-dir/the-file".as_ref()],
1095 cx,
1096 )
1097 .await;
1098
1099 let (picker, _, cx) = build_find_picker(project, cx);
1100
1101 // Even though there is only one worktree, that worktree's filename
1102 // is included in the matching, because the worktree is a single file.
1103 picker
1104 .update(cx, |picker, cx| {
1105 picker.delegate.spawn_search(test_path_like("thf"), cx)
1106 })
1107 .await;
1108 cx.read(|cx| {
1109 let picker = picker.read(cx);
1110 let delegate = &picker.delegate;
1111 assert!(
1112 delegate.matches.history.is_empty(),
1113 "Search matches expected"
1114 );
1115 let matches = delegate.matches.search.clone();
1116 assert_eq!(matches.len(), 1);
1117
1118 let (file_name, file_name_positions, full_path, full_path_positions) =
1119 delegate.labels_for_path_match(&matches[0]);
1120 assert_eq!(file_name, "the-file");
1121 assert_eq!(file_name_positions, &[0, 1, 4]);
1122 assert_eq!(full_path, "the-file");
1123 assert_eq!(full_path_positions, &[0, 1, 4]);
1124 });
1125
1126 // Since the worktree root is a file, searching for its name followed by a slash does
1127 // not match anything.
1128 picker
1129 .update(cx, |f, cx| {
1130 f.delegate.spawn_search(test_path_like("thf/"), cx)
1131 })
1132 .await;
1133 picker.update(cx, |f, _| assert_eq!(f.delegate.matches.len(), 0));
1134 }
1135
1136 #[gpui::test]
1137 async fn test_path_distance_ordering(cx: &mut TestAppContext) {
1138 let app_state = init_test(cx);
1139 app_state
1140 .fs
1141 .as_fake()
1142 .insert_tree(
1143 "/root",
1144 json!({
1145 "dir1": { "a.txt": "" },
1146 "dir2": {
1147 "a.txt": "",
1148 "b.txt": ""
1149 }
1150 }),
1151 )
1152 .await;
1153
1154 let project = Project::test(app_state.fs.clone(), ["/root".as_ref()], cx).await;
1155 let (workspace, cx) = cx.add_window_view(|cx| Workspace::test_new(project, cx));
1156
1157 let worktree_id = cx.read(|cx| {
1158 let worktrees = workspace.read(cx).worktrees(cx).collect::<Vec<_>>();
1159 assert_eq!(worktrees.len(), 1);
1160 WorktreeId::from_usize(worktrees[0].entity_id().as_u64() as usize)
1161 });
1162
1163 // When workspace has an active item, sort items which are closer to that item
1164 // first when they have the same name. In this case, b.txt is closer to dir2's a.txt
1165 // so that one should be sorted earlier
1166 let b_path = ProjectPath {
1167 worktree_id,
1168 path: Arc::from(Path::new("/root/dir2/b.txt")),
1169 };
1170 workspace
1171 .update(cx, |workspace, cx| {
1172 workspace.open_path(b_path, None, true, cx)
1173 })
1174 .await
1175 .unwrap();
1176 let finder = open_file_picker(&workspace, cx);
1177 finder
1178 .update(cx, |f, cx| {
1179 f.delegate.spawn_search(test_path_like("a.txt"), cx)
1180 })
1181 .await;
1182
1183 finder.update(cx, |f, _| {
1184 let delegate = &f.delegate;
1185 assert!(
1186 delegate.matches.history.is_empty(),
1187 "Search matches expected"
1188 );
1189 let matches = delegate.matches.search.clone();
1190 assert_eq!(matches[0].path.as_ref(), Path::new("dir2/a.txt"));
1191 assert_eq!(matches[1].path.as_ref(), Path::new("dir1/a.txt"));
1192 });
1193 }
1194
1195 #[gpui::test]
1196 async fn test_search_worktree_without_files(cx: &mut TestAppContext) {
1197 let app_state = init_test(cx);
1198 app_state
1199 .fs
1200 .as_fake()
1201 .insert_tree(
1202 "/root",
1203 json!({
1204 "dir1": {},
1205 "dir2": {
1206 "dir3": {}
1207 }
1208 }),
1209 )
1210 .await;
1211
1212 let project = Project::test(app_state.fs.clone(), ["/root".as_ref()], cx).await;
1213 let (picker, _workspace, cx) = build_find_picker(project, cx);
1214
1215 picker
1216 .update(cx, |f, cx| {
1217 f.delegate.spawn_search(test_path_like("dir"), cx)
1218 })
1219 .await;
1220 cx.read(|cx| {
1221 let finder = picker.read(cx);
1222 assert_eq!(finder.delegate.matches.len(), 0);
1223 });
1224 }
1225
1226 #[gpui::test]
1227 async fn test_query_history(cx: &mut gpui::TestAppContext) {
1228 let app_state = init_test(cx);
1229
1230 app_state
1231 .fs
1232 .as_fake()
1233 .insert_tree(
1234 "/src",
1235 json!({
1236 "test": {
1237 "first.rs": "// First Rust file",
1238 "second.rs": "// Second Rust file",
1239 "third.rs": "// Third Rust file",
1240 }
1241 }),
1242 )
1243 .await;
1244
1245 let project = Project::test(app_state.fs.clone(), ["/src".as_ref()], cx).await;
1246 let (workspace, cx) = cx.add_window_view(|cx| Workspace::test_new(project, cx));
1247 let worktree_id = cx.read(|cx| {
1248 let worktrees = workspace.read(cx).worktrees(cx).collect::<Vec<_>>();
1249 assert_eq!(worktrees.len(), 1);
1250 WorktreeId::from_usize(worktrees[0].entity_id().as_u64() as usize)
1251 });
1252
1253 // Open and close panels, getting their history items afterwards.
1254 // Ensure history items get populated with opened items, and items are kept in a certain order.
1255 // The history lags one opened buffer behind, since it's updated in the search panel only on its reopen.
1256 //
1257 // TODO: without closing, the opened items do not propagate their history changes for some reason
1258 // it does work in real app though, only tests do not propagate.
1259 workspace.update(cx, |_, cx| cx.focused());
1260
1261 let initial_history = open_close_queried_buffer("fir", 1, "first.rs", &workspace, cx).await;
1262 assert!(
1263 initial_history.is_empty(),
1264 "Should have no history before opening any files"
1265 );
1266
1267 let history_after_first =
1268 open_close_queried_buffer("sec", 1, "second.rs", &workspace, cx).await;
1269 assert_eq!(
1270 history_after_first,
1271 vec![FoundPath::new(
1272 ProjectPath {
1273 worktree_id,
1274 path: Arc::from(Path::new("test/first.rs")),
1275 },
1276 Some(PathBuf::from("/src/test/first.rs"))
1277 )],
1278 "Should show 1st opened item in the history when opening the 2nd item"
1279 );
1280
1281 let history_after_second =
1282 open_close_queried_buffer("thi", 1, "third.rs", &workspace, cx).await;
1283 assert_eq!(
1284 history_after_second,
1285 vec![
1286 FoundPath::new(
1287 ProjectPath {
1288 worktree_id,
1289 path: Arc::from(Path::new("test/second.rs")),
1290 },
1291 Some(PathBuf::from("/src/test/second.rs"))
1292 ),
1293 FoundPath::new(
1294 ProjectPath {
1295 worktree_id,
1296 path: Arc::from(Path::new("test/first.rs")),
1297 },
1298 Some(PathBuf::from("/src/test/first.rs"))
1299 ),
1300 ],
1301 "Should show 1st and 2nd opened items in the history when opening the 3rd item. \
1302 2nd item should be the first in the history, as the last opened."
1303 );
1304
1305 let history_after_third =
1306 open_close_queried_buffer("sec", 1, "second.rs", &workspace, cx).await;
1307 assert_eq!(
1308 history_after_third,
1309 vec![
1310 FoundPath::new(
1311 ProjectPath {
1312 worktree_id,
1313 path: Arc::from(Path::new("test/third.rs")),
1314 },
1315 Some(PathBuf::from("/src/test/third.rs"))
1316 ),
1317 FoundPath::new(
1318 ProjectPath {
1319 worktree_id,
1320 path: Arc::from(Path::new("test/second.rs")),
1321 },
1322 Some(PathBuf::from("/src/test/second.rs"))
1323 ),
1324 FoundPath::new(
1325 ProjectPath {
1326 worktree_id,
1327 path: Arc::from(Path::new("test/first.rs")),
1328 },
1329 Some(PathBuf::from("/src/test/first.rs"))
1330 ),
1331 ],
1332 "Should show 1st, 2nd and 3rd opened items in the history when opening the 2nd item again. \
1333 3rd item should be the first in the history, as the last opened."
1334 );
1335
1336 let history_after_second_again =
1337 open_close_queried_buffer("thi", 1, "third.rs", &workspace, cx).await;
1338 assert_eq!(
1339 history_after_second_again,
1340 vec![
1341 FoundPath::new(
1342 ProjectPath {
1343 worktree_id,
1344 path: Arc::from(Path::new("test/second.rs")),
1345 },
1346 Some(PathBuf::from("/src/test/second.rs"))
1347 ),
1348 FoundPath::new(
1349 ProjectPath {
1350 worktree_id,
1351 path: Arc::from(Path::new("test/third.rs")),
1352 },
1353 Some(PathBuf::from("/src/test/third.rs"))
1354 ),
1355 FoundPath::new(
1356 ProjectPath {
1357 worktree_id,
1358 path: Arc::from(Path::new("test/first.rs")),
1359 },
1360 Some(PathBuf::from("/src/test/first.rs"))
1361 ),
1362 ],
1363 "Should show 1st, 2nd and 3rd opened items in the history when opening the 3rd item again. \
1364 2nd item, as the last opened, 3rd item should go next as it was opened right before."
1365 );
1366 }
1367
1368 #[gpui::test]
1369 async fn test_external_files_history(cx: &mut gpui::TestAppContext) {
1370 let app_state = init_test(cx);
1371
1372 app_state
1373 .fs
1374 .as_fake()
1375 .insert_tree(
1376 "/src",
1377 json!({
1378 "test": {
1379 "first.rs": "// First Rust file",
1380 "second.rs": "// Second Rust file",
1381 }
1382 }),
1383 )
1384 .await;
1385
1386 app_state
1387 .fs
1388 .as_fake()
1389 .insert_tree(
1390 "/external-src",
1391 json!({
1392 "test": {
1393 "third.rs": "// Third Rust file",
1394 "fourth.rs": "// Fourth Rust file",
1395 }
1396 }),
1397 )
1398 .await;
1399
1400 let project = Project::test(app_state.fs.clone(), ["/src".as_ref()], cx).await;
1401 cx.update(|cx| {
1402 project.update(cx, |project, cx| {
1403 project.find_or_create_local_worktree("/external-src", false, cx)
1404 })
1405 })
1406 .detach();
1407 cx.background_executor.run_until_parked();
1408
1409 let (workspace, cx) = cx.add_window_view(|cx| Workspace::test_new(project, cx));
1410 let worktree_id = cx.read(|cx| {
1411 let worktrees = workspace.read(cx).worktrees(cx).collect::<Vec<_>>();
1412 assert_eq!(worktrees.len(), 1,);
1413
1414 WorktreeId::from_usize(worktrees[0].entity_id().as_u64() as usize)
1415 });
1416 workspace
1417 .update(cx, |workspace, cx| {
1418 workspace.open_abs_path(PathBuf::from("/external-src/test/third.rs"), false, cx)
1419 })
1420 .detach();
1421 cx.background_executor.run_until_parked();
1422 let external_worktree_id = cx.read(|cx| {
1423 let worktrees = workspace.read(cx).worktrees(cx).collect::<Vec<_>>();
1424 assert_eq!(
1425 worktrees.len(),
1426 2,
1427 "External file should get opened in a new worktree"
1428 );
1429
1430 WorktreeId::from_usize(
1431 worktrees
1432 .into_iter()
1433 .find(|worktree| {
1434 worktree.entity_id().as_u64() as usize != worktree_id.to_usize()
1435 })
1436 .expect("New worktree should have a different id")
1437 .entity_id()
1438 .as_u64() as usize,
1439 )
1440 });
1441 cx.dispatch_action(workspace::CloseActiveItem { save_intent: None });
1442
1443 let initial_history_items =
1444 open_close_queried_buffer("sec", 1, "second.rs", &workspace, cx).await;
1445 assert_eq!(
1446 initial_history_items,
1447 vec![FoundPath::new(
1448 ProjectPath {
1449 worktree_id: external_worktree_id,
1450 path: Arc::from(Path::new("")),
1451 },
1452 Some(PathBuf::from("/external-src/test/third.rs"))
1453 )],
1454 "Should show external file with its full path in the history after it was open"
1455 );
1456
1457 let updated_history_items =
1458 open_close_queried_buffer("fir", 1, "first.rs", &workspace, cx).await;
1459 assert_eq!(
1460 updated_history_items,
1461 vec![
1462 FoundPath::new(
1463 ProjectPath {
1464 worktree_id,
1465 path: Arc::from(Path::new("test/second.rs")),
1466 },
1467 Some(PathBuf::from("/src/test/second.rs"))
1468 ),
1469 FoundPath::new(
1470 ProjectPath {
1471 worktree_id: external_worktree_id,
1472 path: Arc::from(Path::new("")),
1473 },
1474 Some(PathBuf::from("/external-src/test/third.rs"))
1475 ),
1476 ],
1477 "Should keep external file with history updates",
1478 );
1479 }
1480
1481 #[gpui::test]
1482 async fn test_toggle_panel_new_selections(cx: &mut gpui::TestAppContext) {
1483 let app_state = init_test(cx);
1484
1485 app_state
1486 .fs
1487 .as_fake()
1488 .insert_tree(
1489 "/src",
1490 json!({
1491 "test": {
1492 "first.rs": "// First Rust file",
1493 "second.rs": "// Second Rust file",
1494 "third.rs": "// Third Rust file",
1495 }
1496 }),
1497 )
1498 .await;
1499
1500 let project = Project::test(app_state.fs.clone(), ["/src".as_ref()], cx).await;
1501 let (workspace, cx) = cx.add_window_view(|cx| Workspace::test_new(project, cx));
1502
1503 // generate some history to select from
1504 open_close_queried_buffer("fir", 1, "first.rs", &workspace, cx).await;
1505 cx.executor().run_until_parked();
1506 open_close_queried_buffer("sec", 1, "second.rs", &workspace, cx).await;
1507 open_close_queried_buffer("thi", 1, "third.rs", &workspace, cx).await;
1508 let current_history =
1509 open_close_queried_buffer("sec", 1, "second.rs", &workspace, cx).await;
1510
1511 for expected_selected_index in 0..current_history.len() {
1512 cx.dispatch_action(Toggle);
1513 let picker = active_file_picker(&workspace, cx);
1514 let selected_index = picker.update(cx, |picker, _| picker.delegate.selected_index());
1515 assert_eq!(
1516 selected_index, expected_selected_index,
1517 "Should select the next item in the history"
1518 );
1519 }
1520
1521 cx.dispatch_action(Toggle);
1522 let selected_index = workspace.update(cx, |workspace, cx| {
1523 workspace
1524 .active_modal::<FileFinder>(cx)
1525 .unwrap()
1526 .read(cx)
1527 .picker
1528 .read(cx)
1529 .delegate
1530 .selected_index()
1531 });
1532 assert_eq!(
1533 selected_index, 0,
1534 "Should wrap around the history and start all over"
1535 );
1536 }
1537
1538 #[gpui::test]
1539 async fn test_search_preserves_history_items(cx: &mut gpui::TestAppContext) {
1540 let app_state = init_test(cx);
1541
1542 app_state
1543 .fs
1544 .as_fake()
1545 .insert_tree(
1546 "/src",
1547 json!({
1548 "test": {
1549 "first.rs": "// First Rust file",
1550 "second.rs": "// Second Rust file",
1551 "third.rs": "// Third Rust file",
1552 "fourth.rs": "// Fourth Rust file",
1553 }
1554 }),
1555 )
1556 .await;
1557
1558 let project = Project::test(app_state.fs.clone(), ["/src".as_ref()], cx).await;
1559 let (workspace, cx) = cx.add_window_view(|cx| Workspace::test_new(project, cx));
1560 let worktree_id = cx.read(|cx| {
1561 let worktrees = workspace.read(cx).worktrees(cx).collect::<Vec<_>>();
1562 assert_eq!(worktrees.len(), 1,);
1563
1564 WorktreeId::from_usize(worktrees[0].entity_id().as_u64() as usize)
1565 });
1566
1567 // generate some history to select from
1568 open_close_queried_buffer("fir", 1, "first.rs", &workspace, cx).await;
1569 open_close_queried_buffer("sec", 1, "second.rs", &workspace, cx).await;
1570 open_close_queried_buffer("thi", 1, "third.rs", &workspace, cx).await;
1571 open_close_queried_buffer("sec", 1, "second.rs", &workspace, cx).await;
1572
1573 let finder = open_file_picker(&workspace, cx);
1574 let first_query = "f";
1575 finder
1576 .update(cx, |finder, cx| {
1577 finder.delegate.update_matches(first_query.to_string(), cx)
1578 })
1579 .await;
1580 finder.update(cx, |finder, _| {
1581 let delegate = &finder.delegate;
1582 assert_eq!(delegate.matches.history.len(), 1, "Only one history item contains {first_query}, it should be present and others should be filtered out");
1583 let history_match = delegate.matches.history.first().unwrap();
1584 assert!(history_match.1.is_some(), "Should have path matches for history items after querying");
1585 assert_eq!(history_match.0, FoundPath::new(
1586 ProjectPath {
1587 worktree_id,
1588 path: Arc::from(Path::new("test/first.rs")),
1589 },
1590 Some(PathBuf::from("/src/test/first.rs"))
1591 ));
1592 assert_eq!(delegate.matches.search.len(), 1, "Only one non-history item contains {first_query}, it should be present");
1593 assert_eq!(delegate.matches.search.first().unwrap().path.as_ref(), Path::new("test/fourth.rs"));
1594 });
1595
1596 let second_query = "fsdasdsa";
1597 let finder = active_file_picker(&workspace, cx);
1598 finder
1599 .update(cx, |finder, cx| {
1600 finder.delegate.update_matches(second_query.to_string(), cx)
1601 })
1602 .await;
1603 finder.update(cx, |finder, _| {
1604 let delegate = &finder.delegate;
1605 assert!(
1606 delegate.matches.history.is_empty(),
1607 "No history entries should match {second_query}"
1608 );
1609 assert!(
1610 delegate.matches.search.is_empty(),
1611 "No search entries should match {second_query}"
1612 );
1613 });
1614
1615 let first_query_again = first_query;
1616
1617 let finder = active_file_picker(&workspace, cx);
1618 finder
1619 .update(cx, |finder, cx| {
1620 finder
1621 .delegate
1622 .update_matches(first_query_again.to_string(), cx)
1623 })
1624 .await;
1625 finder.update(cx, |finder, _| {
1626 let delegate = &finder.delegate;
1627 assert_eq!(delegate.matches.history.len(), 1, "Only one history item contains {first_query_again}, it should be present and others should be filtered out, even after non-matching query");
1628 let history_match = delegate.matches.history.first().unwrap();
1629 assert!(history_match.1.is_some(), "Should have path matches for history items after querying");
1630 assert_eq!(history_match.0, FoundPath::new(
1631 ProjectPath {
1632 worktree_id,
1633 path: Arc::from(Path::new("test/first.rs")),
1634 },
1635 Some(PathBuf::from("/src/test/first.rs"))
1636 ));
1637 assert_eq!(delegate.matches.search.len(), 1, "Only one non-history item contains {first_query_again}, it should be present, even after non-matching query");
1638 assert_eq!(delegate.matches.search.first().unwrap().path.as_ref(), Path::new("test/fourth.rs"));
1639 });
1640 }
1641
1642 #[gpui::test]
1643 async fn test_history_items_vs_very_good_external_match(cx: &mut gpui::TestAppContext) {
1644 let app_state = init_test(cx);
1645
1646 app_state
1647 .fs
1648 .as_fake()
1649 .insert_tree(
1650 "/src",
1651 json!({
1652 "collab_ui": {
1653 "first.rs": "// First Rust file",
1654 "second.rs": "// Second Rust file",
1655 "third.rs": "// Third Rust file",
1656 "collab_ui.rs": "// Fourth Rust file",
1657 }
1658 }),
1659 )
1660 .await;
1661
1662 let project = Project::test(app_state.fs.clone(), ["/src".as_ref()], cx).await;
1663 let (workspace, cx) = cx.add_window_view(|cx| Workspace::test_new(project, cx));
1664 // generate some history to select from
1665 open_close_queried_buffer("fir", 1, "first.rs", &workspace, cx).await;
1666 open_close_queried_buffer("sec", 1, "second.rs", &workspace, cx).await;
1667 open_close_queried_buffer("thi", 1, "third.rs", &workspace, cx).await;
1668 open_close_queried_buffer("sec", 1, "second.rs", &workspace, cx).await;
1669
1670 let finder = open_file_picker(&workspace, cx);
1671 let query = "collab_ui";
1672 cx.simulate_input(query);
1673 finder.update(cx, |finder, _| {
1674 let delegate = &finder.delegate;
1675 assert!(
1676 delegate.matches.history.is_empty(),
1677 "History items should not math query {query}, they should be matched by name only"
1678 );
1679
1680 let search_entries = delegate
1681 .matches
1682 .search
1683 .iter()
1684 .map(|path_match| path_match.path.to_path_buf())
1685 .collect::<Vec<_>>();
1686 assert_eq!(
1687 search_entries,
1688 vec![
1689 PathBuf::from("collab_ui/collab_ui.rs"),
1690 PathBuf::from("collab_ui/third.rs"),
1691 PathBuf::from("collab_ui/first.rs"),
1692 PathBuf::from("collab_ui/second.rs"),
1693 ],
1694 "Despite all search results having the same directory name, the most matching one should be on top"
1695 );
1696 });
1697 }
1698
1699 #[gpui::test]
1700 async fn test_nonexistent_history_items_not_shown(cx: &mut gpui::TestAppContext) {
1701 let app_state = init_test(cx);
1702
1703 app_state
1704 .fs
1705 .as_fake()
1706 .insert_tree(
1707 "/src",
1708 json!({
1709 "test": {
1710 "first.rs": "// First Rust file",
1711 "nonexistent.rs": "// Second Rust file",
1712 "third.rs": "// Third Rust file",
1713 }
1714 }),
1715 )
1716 .await;
1717
1718 let project = Project::test(app_state.fs.clone(), ["/src".as_ref()], cx).await;
1719 let (workspace, cx) = cx.add_window_view(|cx| Workspace::test_new(project, cx)); // generate some history to select from
1720 open_close_queried_buffer("fir", 1, "first.rs", &workspace, cx).await;
1721 open_close_queried_buffer("non", 1, "nonexistent.rs", &workspace, cx).await;
1722 open_close_queried_buffer("thi", 1, "third.rs", &workspace, cx).await;
1723 open_close_queried_buffer("fir", 1, "first.rs", &workspace, cx).await;
1724
1725 let picker = open_file_picker(&workspace, cx);
1726 cx.simulate_input("rs");
1727
1728 picker.update(cx, |finder, _| {
1729 let history_entries = finder.delegate
1730 .matches
1731 .history
1732 .iter()
1733 .map(|(_, path_match)| path_match.as_ref().expect("should have a path match").path.to_path_buf())
1734 .collect::<Vec<_>>();
1735 assert_eq!(
1736 history_entries,
1737 vec![
1738 PathBuf::from("test/first.rs"),
1739 PathBuf::from("test/third.rs"),
1740 ],
1741 "Should have all opened files in the history, except the ones that do not exist on disk"
1742 );
1743 });
1744 }
1745
1746 async fn open_close_queried_buffer(
1747 input: &str,
1748 expected_matches: usize,
1749 expected_editor_title: &str,
1750 workspace: &View<Workspace>,
1751 cx: &mut gpui::VisualTestContext<'_>,
1752 ) -> Vec<FoundPath> {
1753 let picker = open_file_picker(&workspace, cx);
1754 cx.simulate_input(input);
1755
1756 let history_items = picker.update(cx, |finder, _| {
1757 assert_eq!(
1758 finder.delegate.matches.len(),
1759 expected_matches,
1760 "Unexpected number of matches found for query {input}"
1761 );
1762 finder.delegate.history_items.clone()
1763 });
1764
1765 cx.dispatch_action(SelectNext);
1766 cx.dispatch_action(Confirm);
1767
1768 cx.read(|cx| {
1769 let active_editor = workspace.read(cx).active_item_as::<Editor>(cx).unwrap();
1770 let active_editor_title = active_editor.read(cx).title(cx);
1771 assert_eq!(
1772 expected_editor_title, active_editor_title,
1773 "Unexpected editor title for query {input}"
1774 );
1775 });
1776
1777 cx.dispatch_action(workspace::CloseActiveItem { save_intent: None });
1778
1779 history_items
1780 }
1781
1782 fn init_test(cx: &mut TestAppContext) -> Arc<AppState> {
1783 cx.update(|cx| {
1784 let state = AppState::test(cx);
1785 theme::init(theme::LoadThemes::JustBase, cx);
1786 language::init(cx);
1787 super::init(cx);
1788 editor::init(cx);
1789 workspace::init_settings(cx);
1790 Project::init_settings(cx);
1791 state
1792 })
1793 }
1794
1795 fn test_path_like(test_str: &str) -> PathLikeWithPosition<FileSearchQuery> {
1796 PathLikeWithPosition::parse_str(test_str, |path_like_str| {
1797 Ok::<_, std::convert::Infallible>(FileSearchQuery {
1798 raw_query: test_str.to_owned(),
1799 file_query_end: if path_like_str == test_str {
1800 None
1801 } else {
1802 Some(path_like_str.len())
1803 },
1804 })
1805 })
1806 .unwrap()
1807 }
1808
1809 fn build_find_picker(
1810 project: Model<Project>,
1811 cx: &mut TestAppContext,
1812 ) -> (
1813 View<Picker<FileFinderDelegate>>,
1814 View<Workspace>,
1815 &mut VisualTestContext,
1816 ) {
1817 let (workspace, cx) = cx.add_window_view(|cx| Workspace::test_new(project, cx));
1818 let picker = open_file_picker(&workspace, cx);
1819 (picker, workspace, cx)
1820 }
1821
1822 #[track_caller]
1823 fn open_file_picker(
1824 workspace: &View<Workspace>,
1825 cx: &mut VisualTestContext,
1826 ) -> View<Picker<FileFinderDelegate>> {
1827 cx.dispatch_action(Toggle);
1828 active_file_picker(workspace, cx)
1829 }
1830
1831 #[track_caller]
1832 fn active_file_picker(
1833 workspace: &View<Workspace>,
1834 cx: &mut VisualTestContext,
1835 ) -> View<Picker<FileFinderDelegate>> {
1836 workspace.update(cx, |workspace, cx| {
1837 workspace
1838 .active_modal::<FileFinder>(cx)
1839 .unwrap()
1840 .read(cx)
1841 .picker
1842 .clone()
1843 })
1844 }
1845}