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::{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 if raw_query.is_empty() {
556 let project = self.project.read(cx);
557 self.latest_search_id = post_inc(&mut self.search_count);
558 self.matches = Matches {
559 history: self
560 .history_items
561 .iter()
562 .filter(|history_item| {
563 project
564 .worktree_for_id(history_item.project.worktree_id, cx)
565 .is_some()
566 || (project.is_local() && history_item.absolute.is_some())
567 })
568 .cloned()
569 .map(|p| (p, None))
570 .collect(),
571 search: Vec::new(),
572 };
573 cx.notify();
574 Task::ready(())
575 } else {
576 let raw_query = &raw_query;
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
691 .update(&mut cx, |_, cx| cx.emit(DismissEvent::Dismiss))
692 .ok()?;
693
694 Some(())
695 })
696 .detach();
697 }
698 }
699 }
700
701 fn dismissed(&mut self, cx: &mut ViewContext<Picker<FileFinderDelegate>>) {
702 self.file_finder
703 .update(cx, |_, cx| cx.emit(DismissEvent::Dismiss))
704 .log_err();
705 }
706
707 fn render_match(
708 &self,
709 ix: usize,
710 selected: bool,
711 cx: &mut ViewContext<Picker<Self>>,
712 ) -> Option<Self::ListItem> {
713 let path_match = self
714 .matches
715 .get(ix)
716 .expect("Invalid matches state: no element for index {ix}");
717
718 let (file_name, file_name_positions, full_path, full_path_positions) =
719 self.labels_for_match(path_match, cx, ix);
720
721 Some(
722 ListItem::new(ix).inset(true).selected(selected).child(
723 v_stack()
724 .child(HighlightedLabel::new(file_name, file_name_positions))
725 .child(HighlightedLabel::new(full_path, full_path_positions)),
726 ),
727 )
728 }
729}
730
731#[cfg(test)]
732mod tests {
733 use std::{assert_eq, path::Path, time::Duration};
734
735 use super::*;
736 use editor::Editor;
737 use gpui::{Entity, TestAppContext, VisualTestContext};
738 use menu::{Confirm, SelectNext};
739 use serde_json::json;
740 use workspace::{AppState, Workspace};
741
742 #[ctor::ctor]
743 fn init_logger() {
744 if std::env::var("RUST_LOG").is_ok() {
745 env_logger::init();
746 }
747 }
748
749 #[gpui::test]
750 async fn test_matching_paths(cx: &mut TestAppContext) {
751 let app_state = init_test(cx);
752 app_state
753 .fs
754 .as_fake()
755 .insert_tree(
756 "/root",
757 json!({
758 "a": {
759 "banana": "",
760 "bandana": "",
761 }
762 }),
763 )
764 .await;
765
766 let project = Project::test(app_state.fs.clone(), ["/root".as_ref()], cx).await;
767
768 let (picker, workspace, cx) = build_find_picker(project, cx);
769
770 cx.simulate_input("bna");
771
772 picker.update(cx, |picker, _| {
773 assert_eq!(picker.delegate.matches.len(), 2);
774 });
775
776 cx.dispatch_action(SelectNext);
777 cx.dispatch_action(Confirm);
778
779 cx.read(|cx| {
780 let active_editor = workspace.read(cx).active_item_as::<Editor>(cx).unwrap();
781 assert_eq!(active_editor.read(cx).title(cx), "bandana");
782 });
783 }
784
785 #[gpui::test]
786 async fn test_row_column_numbers_query_inside_file(cx: &mut TestAppContext) {
787 let app_state = init_test(cx);
788
789 let first_file_name = "first.rs";
790 let first_file_contents = "// First Rust file";
791 app_state
792 .fs
793 .as_fake()
794 .insert_tree(
795 "/src",
796 json!({
797 "test": {
798 first_file_name: first_file_contents,
799 "second.rs": "// Second Rust file",
800 }
801 }),
802 )
803 .await;
804
805 let project = Project::test(app_state.fs.clone(), ["/src".as_ref()], cx).await;
806
807 let (picker, workspace, cx) = build_find_picker(project, cx);
808
809 let file_query = &first_file_name[..3];
810 let file_row = 1;
811 let file_column = 3;
812 assert!(file_column <= first_file_contents.len());
813 let query_inside_file = format!("{file_query}:{file_row}:{file_column}");
814 picker
815 .update(cx, |finder, cx| {
816 finder
817 .delegate
818 .update_matches(query_inside_file.to_string(), cx)
819 })
820 .await;
821 picker.update(cx, |finder, _| {
822 let finder = &finder.delegate;
823 assert_eq!(finder.matches.len(), 1);
824 let latest_search_query = finder
825 .latest_search_query
826 .as_ref()
827 .expect("Finder should have a query after the update_matches call");
828 assert_eq!(latest_search_query.path_like.raw_query, query_inside_file);
829 assert_eq!(
830 latest_search_query.path_like.file_query_end,
831 Some(file_query.len())
832 );
833 assert_eq!(latest_search_query.row, Some(file_row));
834 assert_eq!(latest_search_query.column, Some(file_column as u32));
835 });
836
837 cx.dispatch_action(SelectNext);
838 cx.dispatch_action(Confirm);
839
840 let editor = cx.update(|cx| workspace.read(cx).active_item_as::<Editor>(cx).unwrap());
841 cx.executor().advance_clock(Duration::from_secs(2));
842
843 editor.update(cx, |editor, cx| {
844 let all_selections = editor.selections.all_adjusted(cx);
845 assert_eq!(
846 all_selections.len(),
847 1,
848 "Expected to have 1 selection (caret) after file finder confirm, but got: {all_selections:?}"
849 );
850 let caret_selection = all_selections.into_iter().next().unwrap();
851 assert_eq!(caret_selection.start, caret_selection.end,
852 "Caret selection should have its start and end at the same position");
853 assert_eq!(file_row, caret_selection.start.row + 1,
854 "Query inside file should get caret with the same focus row");
855 assert_eq!(file_column, caret_selection.start.column as usize + 1,
856 "Query inside file should get caret with the same focus column");
857 });
858 }
859
860 #[gpui::test]
861 async fn test_row_column_numbers_query_outside_file(cx: &mut TestAppContext) {
862 let app_state = init_test(cx);
863
864 let first_file_name = "first.rs";
865 let first_file_contents = "// First Rust file";
866 app_state
867 .fs
868 .as_fake()
869 .insert_tree(
870 "/src",
871 json!({
872 "test": {
873 first_file_name: first_file_contents,
874 "second.rs": "// Second Rust file",
875 }
876 }),
877 )
878 .await;
879
880 let project = Project::test(app_state.fs.clone(), ["/src".as_ref()], cx).await;
881
882 let (picker, workspace, cx) = build_find_picker(project, cx);
883
884 let file_query = &first_file_name[..3];
885 let file_row = 200;
886 let file_column = 300;
887 assert!(file_column > first_file_contents.len());
888 let query_outside_file = format!("{file_query}:{file_row}:{file_column}");
889 picker
890 .update(cx, |picker, cx| {
891 picker
892 .delegate
893 .update_matches(query_outside_file.to_string(), cx)
894 })
895 .await;
896 picker.update(cx, |finder, _| {
897 let delegate = &finder.delegate;
898 assert_eq!(delegate.matches.len(), 1);
899 let latest_search_query = delegate
900 .latest_search_query
901 .as_ref()
902 .expect("Finder should have a query after the update_matches call");
903 assert_eq!(latest_search_query.path_like.raw_query, query_outside_file);
904 assert_eq!(
905 latest_search_query.path_like.file_query_end,
906 Some(file_query.len())
907 );
908 assert_eq!(latest_search_query.row, Some(file_row));
909 assert_eq!(latest_search_query.column, Some(file_column as u32));
910 });
911
912 cx.dispatch_action(SelectNext);
913 cx.dispatch_action(Confirm);
914
915 let editor = cx.update(|cx| workspace.read(cx).active_item_as::<Editor>(cx).unwrap());
916 cx.executor().advance_clock(Duration::from_secs(2));
917
918 editor.update(cx, |editor, cx| {
919 let all_selections = editor.selections.all_adjusted(cx);
920 assert_eq!(
921 all_selections.len(),
922 1,
923 "Expected to have 1 selection (caret) after file finder confirm, but got: {all_selections:?}"
924 );
925 let caret_selection = all_selections.into_iter().next().unwrap();
926 assert_eq!(caret_selection.start, caret_selection.end,
927 "Caret selection should have its start and end at the same position");
928 assert_eq!(0, caret_selection.start.row,
929 "Excessive rows (as in query outside file borders) should get trimmed to last file row");
930 assert_eq!(first_file_contents.len(), caret_selection.start.column as usize,
931 "Excessive columns (as in query outside file borders) should get trimmed to selected row's last column");
932 });
933 }
934
935 #[gpui::test]
936 async fn test_matching_cancellation(cx: &mut TestAppContext) {
937 let app_state = init_test(cx);
938 app_state
939 .fs
940 .as_fake()
941 .insert_tree(
942 "/dir",
943 json!({
944 "hello": "",
945 "goodbye": "",
946 "halogen-light": "",
947 "happiness": "",
948 "height": "",
949 "hi": "",
950 "hiccup": "",
951 }),
952 )
953 .await;
954
955 let project = Project::test(app_state.fs.clone(), ["/dir".as_ref()], cx).await;
956
957 let (picker, _, cx) = build_find_picker(project, cx);
958
959 let query = test_path_like("hi");
960 picker
961 .update(cx, |picker, cx| {
962 picker.delegate.spawn_search(query.clone(), cx)
963 })
964 .await;
965
966 picker.update(cx, |picker, _cx| {
967 assert_eq!(picker.delegate.matches.len(), 5)
968 });
969
970 picker.update(cx, |picker, cx| {
971 let delegate = &mut picker.delegate;
972 assert!(
973 delegate.matches.history.is_empty(),
974 "Search matches expected"
975 );
976 let matches = delegate.matches.search.clone();
977
978 // Simulate a search being cancelled after the time limit,
979 // returning only a subset of the matches that would have been found.
980 drop(delegate.spawn_search(query.clone(), cx));
981 delegate.set_search_matches(
982 delegate.latest_search_id,
983 true, // did-cancel
984 query.clone(),
985 vec![matches[1].clone(), matches[3].clone()],
986 cx,
987 );
988
989 // Simulate another cancellation.
990 drop(delegate.spawn_search(query.clone(), cx));
991 delegate.set_search_matches(
992 delegate.latest_search_id,
993 true, // did-cancel
994 query.clone(),
995 vec![matches[0].clone(), matches[2].clone(), matches[3].clone()],
996 cx,
997 );
998
999 assert!(
1000 delegate.matches.history.is_empty(),
1001 "Search matches expected"
1002 );
1003 assert_eq!(delegate.matches.search.as_slice(), &matches[0..4]);
1004 });
1005 }
1006
1007 #[gpui::test]
1008 async fn test_ignored_files(cx: &mut TestAppContext) {
1009 let app_state = init_test(cx);
1010 app_state
1011 .fs
1012 .as_fake()
1013 .insert_tree(
1014 "/ancestor",
1015 json!({
1016 ".gitignore": "ignored-root",
1017 "ignored-root": {
1018 "happiness": "",
1019 "height": "",
1020 "hi": "",
1021 "hiccup": "",
1022 },
1023 "tracked-root": {
1024 ".gitignore": "height",
1025 "happiness": "",
1026 "height": "",
1027 "hi": "",
1028 "hiccup": "",
1029 },
1030 }),
1031 )
1032 .await;
1033
1034 let project = Project::test(
1035 app_state.fs.clone(),
1036 [
1037 "/ancestor/tracked-root".as_ref(),
1038 "/ancestor/ignored-root".as_ref(),
1039 ],
1040 cx,
1041 )
1042 .await;
1043
1044 let (picker, _, cx) = build_find_picker(project, cx);
1045
1046 picker
1047 .update(cx, |picker, cx| {
1048 picker.delegate.spawn_search(test_path_like("hi"), cx)
1049 })
1050 .await;
1051 picker.update(cx, |picker, _| assert_eq!(picker.delegate.matches.len(), 7));
1052 }
1053
1054 #[gpui::test]
1055 async fn test_single_file_worktrees(cx: &mut TestAppContext) {
1056 let app_state = init_test(cx);
1057 app_state
1058 .fs
1059 .as_fake()
1060 .insert_tree("/root", json!({ "the-parent-dir": { "the-file": "" } }))
1061 .await;
1062
1063 let project = Project::test(
1064 app_state.fs.clone(),
1065 ["/root/the-parent-dir/the-file".as_ref()],
1066 cx,
1067 )
1068 .await;
1069
1070 let (picker, _, cx) = build_find_picker(project, cx);
1071
1072 // Even though there is only one worktree, that worktree's filename
1073 // is included in the matching, because the worktree is a single file.
1074 picker
1075 .update(cx, |picker, cx| {
1076 picker.delegate.spawn_search(test_path_like("thf"), cx)
1077 })
1078 .await;
1079 cx.read(|cx| {
1080 let picker = picker.read(cx);
1081 let delegate = &picker.delegate;
1082 assert!(
1083 delegate.matches.history.is_empty(),
1084 "Search matches expected"
1085 );
1086 let matches = delegate.matches.search.clone();
1087 assert_eq!(matches.len(), 1);
1088
1089 let (file_name, file_name_positions, full_path, full_path_positions) =
1090 delegate.labels_for_path_match(&matches[0]);
1091 assert_eq!(file_name, "the-file");
1092 assert_eq!(file_name_positions, &[0, 1, 4]);
1093 assert_eq!(full_path, "the-file");
1094 assert_eq!(full_path_positions, &[0, 1, 4]);
1095 });
1096
1097 // Since the worktree root is a file, searching for its name followed by a slash does
1098 // not match anything.
1099 picker
1100 .update(cx, |f, cx| {
1101 f.delegate.spawn_search(test_path_like("thf/"), cx)
1102 })
1103 .await;
1104 picker.update(cx, |f, _| assert_eq!(f.delegate.matches.len(), 0));
1105 }
1106
1107 #[gpui::test]
1108 async fn test_path_distance_ordering(cx: &mut TestAppContext) {
1109 let app_state = init_test(cx);
1110 app_state
1111 .fs
1112 .as_fake()
1113 .insert_tree(
1114 "/root",
1115 json!({
1116 "dir1": { "a.txt": "" },
1117 "dir2": {
1118 "a.txt": "",
1119 "b.txt": ""
1120 }
1121 }),
1122 )
1123 .await;
1124
1125 let project = Project::test(app_state.fs.clone(), ["/root".as_ref()], cx).await;
1126 let (workspace, cx) = cx.add_window_view(|cx| Workspace::test_new(project, cx));
1127
1128 let worktree_id = cx.read(|cx| {
1129 let worktrees = workspace.read(cx).worktrees(cx).collect::<Vec<_>>();
1130 assert_eq!(worktrees.len(), 1);
1131 WorktreeId::from_usize(worktrees[0].entity_id().as_u64() as usize)
1132 });
1133
1134 // When workspace has an active item, sort items which are closer to that item
1135 // first when they have the same name. In this case, b.txt is closer to dir2's a.txt
1136 // so that one should be sorted earlier
1137 let b_path = ProjectPath {
1138 worktree_id,
1139 path: Arc::from(Path::new("/root/dir2/b.txt")),
1140 };
1141 workspace
1142 .update(cx, |workspace, cx| {
1143 workspace.open_path(b_path, None, true, cx)
1144 })
1145 .await
1146 .unwrap();
1147 let finder = open_file_picker(&workspace, cx);
1148 finder
1149 .update(cx, |f, cx| {
1150 f.delegate.spawn_search(test_path_like("a.txt"), cx)
1151 })
1152 .await;
1153
1154 finder.update(cx, |f, _| {
1155 let delegate = &f.delegate;
1156 assert!(
1157 delegate.matches.history.is_empty(),
1158 "Search matches expected"
1159 );
1160 let matches = delegate.matches.search.clone();
1161 assert_eq!(matches[0].path.as_ref(), Path::new("dir2/a.txt"));
1162 assert_eq!(matches[1].path.as_ref(), Path::new("dir1/a.txt"));
1163 });
1164 }
1165
1166 #[gpui::test]
1167 async fn test_search_worktree_without_files(cx: &mut TestAppContext) {
1168 let app_state = init_test(cx);
1169 app_state
1170 .fs
1171 .as_fake()
1172 .insert_tree(
1173 "/root",
1174 json!({
1175 "dir1": {},
1176 "dir2": {
1177 "dir3": {}
1178 }
1179 }),
1180 )
1181 .await;
1182
1183 let project = Project::test(app_state.fs.clone(), ["/root".as_ref()], cx).await;
1184 let (picker, _workspace, cx) = build_find_picker(project, cx);
1185
1186 picker
1187 .update(cx, |f, cx| {
1188 f.delegate.spawn_search(test_path_like("dir"), cx)
1189 })
1190 .await;
1191 cx.read(|cx| {
1192 let finder = picker.read(cx);
1193 assert_eq!(finder.delegate.matches.len(), 0);
1194 });
1195 }
1196
1197 #[gpui::test]
1198 async fn test_query_history(cx: &mut gpui::TestAppContext) {
1199 let app_state = init_test(cx);
1200
1201 app_state
1202 .fs
1203 .as_fake()
1204 .insert_tree(
1205 "/src",
1206 json!({
1207 "test": {
1208 "first.rs": "// First Rust file",
1209 "second.rs": "// Second Rust file",
1210 "third.rs": "// Third Rust file",
1211 }
1212 }),
1213 )
1214 .await;
1215
1216 let project = Project::test(app_state.fs.clone(), ["/src".as_ref()], cx).await;
1217 let (workspace, cx) = cx.add_window_view(|cx| Workspace::test_new(project, cx));
1218 let worktree_id = cx.read(|cx| {
1219 let worktrees = workspace.read(cx).worktrees(cx).collect::<Vec<_>>();
1220 assert_eq!(worktrees.len(), 1);
1221 WorktreeId::from_usize(worktrees[0].entity_id().as_u64() as usize)
1222 });
1223
1224 // Open and close panels, getting their history items afterwards.
1225 // Ensure history items get populated with opened items, and items are kept in a certain order.
1226 // The history lags one opened buffer behind, since it's updated in the search panel only on its reopen.
1227 //
1228 // TODO: without closing, the opened items do not propagate their history changes for some reason
1229 // it does work in real app though, only tests do not propagate.
1230 workspace.update(cx, |_, cx| dbg!(cx.focused()));
1231
1232 let initial_history = open_close_queried_buffer("fir", 1, "first.rs", &workspace, cx).await;
1233 assert!(
1234 initial_history.is_empty(),
1235 "Should have no history before opening any files"
1236 );
1237
1238 let history_after_first =
1239 open_close_queried_buffer("sec", 1, "second.rs", &workspace, cx).await;
1240 assert_eq!(
1241 history_after_first,
1242 vec![FoundPath::new(
1243 ProjectPath {
1244 worktree_id,
1245 path: Arc::from(Path::new("test/first.rs")),
1246 },
1247 Some(PathBuf::from("/src/test/first.rs"))
1248 )],
1249 "Should show 1st opened item in the history when opening the 2nd item"
1250 );
1251
1252 let history_after_second =
1253 open_close_queried_buffer("thi", 1, "third.rs", &workspace, cx).await;
1254 assert_eq!(
1255 history_after_second,
1256 vec![
1257 FoundPath::new(
1258 ProjectPath {
1259 worktree_id,
1260 path: Arc::from(Path::new("test/second.rs")),
1261 },
1262 Some(PathBuf::from("/src/test/second.rs"))
1263 ),
1264 FoundPath::new(
1265 ProjectPath {
1266 worktree_id,
1267 path: Arc::from(Path::new("test/first.rs")),
1268 },
1269 Some(PathBuf::from("/src/test/first.rs"))
1270 ),
1271 ],
1272 "Should show 1st and 2nd opened items in the history when opening the 3rd item. \
1273 2nd item should be the first in the history, as the last opened."
1274 );
1275
1276 let history_after_third =
1277 open_close_queried_buffer("sec", 1, "second.rs", &workspace, cx).await;
1278 assert_eq!(
1279 history_after_third,
1280 vec![
1281 FoundPath::new(
1282 ProjectPath {
1283 worktree_id,
1284 path: Arc::from(Path::new("test/third.rs")),
1285 },
1286 Some(PathBuf::from("/src/test/third.rs"))
1287 ),
1288 FoundPath::new(
1289 ProjectPath {
1290 worktree_id,
1291 path: Arc::from(Path::new("test/second.rs")),
1292 },
1293 Some(PathBuf::from("/src/test/second.rs"))
1294 ),
1295 FoundPath::new(
1296 ProjectPath {
1297 worktree_id,
1298 path: Arc::from(Path::new("test/first.rs")),
1299 },
1300 Some(PathBuf::from("/src/test/first.rs"))
1301 ),
1302 ],
1303 "Should show 1st, 2nd and 3rd opened items in the history when opening the 2nd item again. \
1304 3rd item should be the first in the history, as the last opened."
1305 );
1306
1307 let history_after_second_again =
1308 open_close_queried_buffer("thi", 1, "third.rs", &workspace, cx).await;
1309 assert_eq!(
1310 history_after_second_again,
1311 vec![
1312 FoundPath::new(
1313 ProjectPath {
1314 worktree_id,
1315 path: Arc::from(Path::new("test/second.rs")),
1316 },
1317 Some(PathBuf::from("/src/test/second.rs"))
1318 ),
1319 FoundPath::new(
1320 ProjectPath {
1321 worktree_id,
1322 path: Arc::from(Path::new("test/third.rs")),
1323 },
1324 Some(PathBuf::from("/src/test/third.rs"))
1325 ),
1326 FoundPath::new(
1327 ProjectPath {
1328 worktree_id,
1329 path: Arc::from(Path::new("test/first.rs")),
1330 },
1331 Some(PathBuf::from("/src/test/first.rs"))
1332 ),
1333 ],
1334 "Should show 1st, 2nd and 3rd opened items in the history when opening the 3rd item again. \
1335 2nd item, as the last opened, 3rd item should go next as it was opened right before."
1336 );
1337 }
1338
1339 #[gpui::test]
1340 async fn test_external_files_history(cx: &mut gpui::TestAppContext) {
1341 let app_state = init_test(cx);
1342
1343 app_state
1344 .fs
1345 .as_fake()
1346 .insert_tree(
1347 "/src",
1348 json!({
1349 "test": {
1350 "first.rs": "// First Rust file",
1351 "second.rs": "// Second Rust file",
1352 }
1353 }),
1354 )
1355 .await;
1356
1357 app_state
1358 .fs
1359 .as_fake()
1360 .insert_tree(
1361 "/external-src",
1362 json!({
1363 "test": {
1364 "third.rs": "// Third Rust file",
1365 "fourth.rs": "// Fourth Rust file",
1366 }
1367 }),
1368 )
1369 .await;
1370
1371 let project = Project::test(app_state.fs.clone(), ["/src".as_ref()], cx).await;
1372 cx.update(|cx| {
1373 project.update(cx, |project, cx| {
1374 project.find_or_create_local_worktree("/external-src", false, cx)
1375 })
1376 })
1377 .detach();
1378 cx.background_executor.run_until_parked();
1379
1380 let (workspace, cx) = cx.add_window_view(|cx| Workspace::test_new(project, cx));
1381 let worktree_id = cx.read(|cx| {
1382 let worktrees = workspace.read(cx).worktrees(cx).collect::<Vec<_>>();
1383 assert_eq!(worktrees.len(), 1,);
1384
1385 WorktreeId::from_usize(worktrees[0].entity_id().as_u64() as usize)
1386 });
1387 workspace
1388 .update(cx, |workspace, cx| {
1389 workspace.open_abs_path(PathBuf::from("/external-src/test/third.rs"), false, cx)
1390 })
1391 .detach();
1392 cx.background_executor.run_until_parked();
1393 let external_worktree_id = cx.read(|cx| {
1394 let worktrees = workspace.read(cx).worktrees(cx).collect::<Vec<_>>();
1395 assert_eq!(
1396 worktrees.len(),
1397 2,
1398 "External file should get opened in a new worktree"
1399 );
1400
1401 WorktreeId::from_usize(
1402 worktrees
1403 .into_iter()
1404 .find(|worktree| {
1405 worktree.entity_id().as_u64() as usize != worktree_id.to_usize()
1406 })
1407 .expect("New worktree should have a different id")
1408 .entity_id()
1409 .as_u64() as usize,
1410 )
1411 });
1412 cx.dispatch_action(workspace::CloseActiveItem { save_intent: None });
1413
1414 let initial_history_items =
1415 open_close_queried_buffer("sec", 1, "second.rs", &workspace, cx).await;
1416 assert_eq!(
1417 initial_history_items,
1418 vec![FoundPath::new(
1419 ProjectPath {
1420 worktree_id: external_worktree_id,
1421 path: Arc::from(Path::new("")),
1422 },
1423 Some(PathBuf::from("/external-src/test/third.rs"))
1424 )],
1425 "Should show external file with its full path in the history after it was open"
1426 );
1427
1428 let updated_history_items =
1429 open_close_queried_buffer("fir", 1, "first.rs", &workspace, cx).await;
1430 assert_eq!(
1431 updated_history_items,
1432 vec![
1433 FoundPath::new(
1434 ProjectPath {
1435 worktree_id,
1436 path: Arc::from(Path::new("test/second.rs")),
1437 },
1438 Some(PathBuf::from("/src/test/second.rs"))
1439 ),
1440 FoundPath::new(
1441 ProjectPath {
1442 worktree_id: external_worktree_id,
1443 path: Arc::from(Path::new("")),
1444 },
1445 Some(PathBuf::from("/external-src/test/third.rs"))
1446 ),
1447 ],
1448 "Should keep external file with history updates",
1449 );
1450 }
1451
1452 #[gpui::test]
1453 async fn test_toggle_panel_new_selections(cx: &mut gpui::TestAppContext) {
1454 let app_state = init_test(cx);
1455
1456 app_state
1457 .fs
1458 .as_fake()
1459 .insert_tree(
1460 "/src",
1461 json!({
1462 "test": {
1463 "first.rs": "// First Rust file",
1464 "second.rs": "// Second Rust file",
1465 "third.rs": "// Third Rust file",
1466 }
1467 }),
1468 )
1469 .await;
1470
1471 let project = Project::test(app_state.fs.clone(), ["/src".as_ref()], cx).await;
1472 let (workspace, cx) = cx.add_window_view(|cx| Workspace::test_new(project, cx));
1473
1474 // generate some history to select from
1475 open_close_queried_buffer("fir", 1, "first.rs", &workspace, cx).await;
1476 cx.executor().run_until_parked();
1477 open_close_queried_buffer("sec", 1, "second.rs", &workspace, cx).await;
1478 open_close_queried_buffer("thi", 1, "third.rs", &workspace, cx).await;
1479 let current_history =
1480 open_close_queried_buffer("sec", 1, "second.rs", &workspace, cx).await;
1481
1482 for expected_selected_index in 0..current_history.len() {
1483 cx.dispatch_action(Toggle);
1484 let picker = active_file_picker(&workspace, cx);
1485 let selected_index = picker.update(cx, |picker, _| picker.delegate.selected_index());
1486 assert_eq!(
1487 selected_index, expected_selected_index,
1488 "Should select the next item in the history"
1489 );
1490 }
1491
1492 cx.dispatch_action(Toggle);
1493 let selected_index = workspace.update(cx, |workspace, cx| {
1494 workspace
1495 .active_modal::<FileFinder>(cx)
1496 .unwrap()
1497 .read(cx)
1498 .picker
1499 .read(cx)
1500 .delegate
1501 .selected_index()
1502 });
1503 assert_eq!(
1504 selected_index, 0,
1505 "Should wrap around the history and start all over"
1506 );
1507 }
1508
1509 #[gpui::test]
1510 async fn test_search_preserves_history_items(cx: &mut gpui::TestAppContext) {
1511 let app_state = init_test(cx);
1512
1513 app_state
1514 .fs
1515 .as_fake()
1516 .insert_tree(
1517 "/src",
1518 json!({
1519 "test": {
1520 "first.rs": "// First Rust file",
1521 "second.rs": "// Second Rust file",
1522 "third.rs": "// Third Rust file",
1523 "fourth.rs": "// Fourth Rust file",
1524 }
1525 }),
1526 )
1527 .await;
1528
1529 let project = Project::test(app_state.fs.clone(), ["/src".as_ref()], cx).await;
1530 let (workspace, cx) = cx.add_window_view(|cx| Workspace::test_new(project, cx));
1531 let worktree_id = cx.read(|cx| {
1532 let worktrees = workspace.read(cx).worktrees(cx).collect::<Vec<_>>();
1533 assert_eq!(worktrees.len(), 1,);
1534
1535 WorktreeId::from_usize(worktrees[0].entity_id().as_u64() as usize)
1536 });
1537
1538 // generate some history to select from
1539 open_close_queried_buffer("fir", 1, "first.rs", &workspace, cx).await;
1540 open_close_queried_buffer("sec", 1, "second.rs", &workspace, cx).await;
1541 open_close_queried_buffer("thi", 1, "third.rs", &workspace, cx).await;
1542 open_close_queried_buffer("sec", 1, "second.rs", &workspace, cx).await;
1543
1544 let finder = open_file_picker(&workspace, cx);
1545 let first_query = "f";
1546 finder
1547 .update(cx, |finder, cx| {
1548 finder.delegate.update_matches(first_query.to_string(), cx)
1549 })
1550 .await;
1551 finder.update(cx, |finder, _| {
1552 let delegate = &finder.delegate;
1553 assert_eq!(delegate.matches.history.len(), 1, "Only one history item contains {first_query}, it should be present and others should be filtered out");
1554 let history_match = delegate.matches.history.first().unwrap();
1555 assert!(history_match.1.is_some(), "Should have path matches for history items after querying");
1556 assert_eq!(history_match.0, FoundPath::new(
1557 ProjectPath {
1558 worktree_id,
1559 path: Arc::from(Path::new("test/first.rs")),
1560 },
1561 Some(PathBuf::from("/src/test/first.rs"))
1562 ));
1563 assert_eq!(delegate.matches.search.len(), 1, "Only one non-history item contains {first_query}, it should be present");
1564 assert_eq!(delegate.matches.search.first().unwrap().path.as_ref(), Path::new("test/fourth.rs"));
1565 });
1566
1567 let second_query = "fsdasdsa";
1568 let finder = active_file_picker(&workspace, cx);
1569 finder
1570 .update(cx, |finder, cx| {
1571 finder.delegate.update_matches(second_query.to_string(), cx)
1572 })
1573 .await;
1574 finder.update(cx, |finder, _| {
1575 let delegate = &finder.delegate;
1576 assert!(
1577 delegate.matches.history.is_empty(),
1578 "No history entries should match {second_query}"
1579 );
1580 assert!(
1581 delegate.matches.search.is_empty(),
1582 "No search entries should match {second_query}"
1583 );
1584 });
1585
1586 let first_query_again = first_query;
1587
1588 let finder = active_file_picker(&workspace, cx);
1589 finder
1590 .update(cx, |finder, cx| {
1591 finder
1592 .delegate
1593 .update_matches(first_query_again.to_string(), cx)
1594 })
1595 .await;
1596 finder.update(cx, |finder, _| {
1597 let delegate = &finder.delegate;
1598 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");
1599 let history_match = delegate.matches.history.first().unwrap();
1600 assert!(history_match.1.is_some(), "Should have path matches for history items after querying");
1601 assert_eq!(history_match.0, FoundPath::new(
1602 ProjectPath {
1603 worktree_id,
1604 path: Arc::from(Path::new("test/first.rs")),
1605 },
1606 Some(PathBuf::from("/src/test/first.rs"))
1607 ));
1608 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");
1609 assert_eq!(delegate.matches.search.first().unwrap().path.as_ref(), Path::new("test/fourth.rs"));
1610 });
1611 }
1612
1613 #[gpui::test]
1614 async fn test_history_items_vs_very_good_external_match(cx: &mut gpui::TestAppContext) {
1615 let app_state = init_test(cx);
1616
1617 app_state
1618 .fs
1619 .as_fake()
1620 .insert_tree(
1621 "/src",
1622 json!({
1623 "collab_ui": {
1624 "first.rs": "// First Rust file",
1625 "second.rs": "// Second Rust file",
1626 "third.rs": "// Third Rust file",
1627 "collab_ui.rs": "// Fourth Rust file",
1628 }
1629 }),
1630 )
1631 .await;
1632
1633 let project = Project::test(app_state.fs.clone(), ["/src".as_ref()], cx).await;
1634 let (workspace, cx) = cx.add_window_view(|cx| Workspace::test_new(project, cx));
1635 // generate some history to select from
1636 open_close_queried_buffer("fir", 1, "first.rs", &workspace, cx).await;
1637 open_close_queried_buffer("sec", 1, "second.rs", &workspace, cx).await;
1638 open_close_queried_buffer("thi", 1, "third.rs", &workspace, cx).await;
1639 open_close_queried_buffer("sec", 1, "second.rs", &workspace, cx).await;
1640
1641 let finder = open_file_picker(&workspace, cx);
1642 let query = "collab_ui";
1643 cx.simulate_input(query);
1644 finder.update(cx, |finder, _| {
1645 let delegate = &finder.delegate;
1646 assert!(
1647 delegate.matches.history.is_empty(),
1648 "History items should not math query {query}, they should be matched by name only"
1649 );
1650
1651 let search_entries = delegate
1652 .matches
1653 .search
1654 .iter()
1655 .map(|path_match| path_match.path.to_path_buf())
1656 .collect::<Vec<_>>();
1657 assert_eq!(
1658 search_entries,
1659 vec![
1660 PathBuf::from("collab_ui/collab_ui.rs"),
1661 PathBuf::from("collab_ui/third.rs"),
1662 PathBuf::from("collab_ui/first.rs"),
1663 PathBuf::from("collab_ui/second.rs"),
1664 ],
1665 "Despite all search results having the same directory name, the most matching one should be on top"
1666 );
1667 });
1668 }
1669
1670 #[gpui::test]
1671 async fn test_nonexistent_history_items_not_shown(cx: &mut gpui::TestAppContext) {
1672 let app_state = init_test(cx);
1673
1674 app_state
1675 .fs
1676 .as_fake()
1677 .insert_tree(
1678 "/src",
1679 json!({
1680 "test": {
1681 "first.rs": "// First Rust file",
1682 "nonexistent.rs": "// Second Rust file",
1683 "third.rs": "// Third Rust file",
1684 }
1685 }),
1686 )
1687 .await;
1688
1689 let project = Project::test(app_state.fs.clone(), ["/src".as_ref()], cx).await;
1690 let (workspace, cx) = cx.add_window_view(|cx| Workspace::test_new(project, cx)); // generate some history to select from
1691 open_close_queried_buffer("fir", 1, "first.rs", &workspace, cx).await;
1692 open_close_queried_buffer("non", 1, "nonexistent.rs", &workspace, cx).await;
1693 open_close_queried_buffer("thi", 1, "third.rs", &workspace, cx).await;
1694 open_close_queried_buffer("fir", 1, "first.rs", &workspace, cx).await;
1695
1696 let picker = open_file_picker(&workspace, cx);
1697 cx.simulate_input("rs");
1698
1699 picker.update(cx, |finder, _| {
1700 let history_entries = finder.delegate
1701 .matches
1702 .history
1703 .iter()
1704 .map(|(_, path_match)| path_match.as_ref().expect("should have a path match").path.to_path_buf())
1705 .collect::<Vec<_>>();
1706 assert_eq!(
1707 history_entries,
1708 vec![
1709 PathBuf::from("test/first.rs"),
1710 PathBuf::from("test/third.rs"),
1711 ],
1712 "Should have all opened files in the history, except the ones that do not exist on disk"
1713 );
1714 });
1715 }
1716
1717 async fn open_close_queried_buffer(
1718 input: &str,
1719 expected_matches: usize,
1720 expected_editor_title: &str,
1721 workspace: &View<Workspace>,
1722 cx: &mut gpui::VisualTestContext<'_>,
1723 ) -> Vec<FoundPath> {
1724 let picker = open_file_picker(&workspace, cx);
1725 cx.simulate_input(input);
1726
1727 let history_items = picker.update(cx, |finder, _| {
1728 assert_eq!(
1729 finder.delegate.matches.len(),
1730 expected_matches,
1731 "Unexpected number of matches found for query {input}"
1732 );
1733 finder.delegate.history_items.clone()
1734 });
1735
1736 cx.dispatch_action(SelectNext);
1737 cx.dispatch_action(Confirm);
1738
1739 cx.read(|cx| {
1740 let active_editor = workspace.read(cx).active_item_as::<Editor>(cx).unwrap();
1741 let active_editor_title = active_editor.read(cx).title(cx);
1742 assert_eq!(
1743 expected_editor_title, active_editor_title,
1744 "Unexpected editor title for query {input}"
1745 );
1746 });
1747
1748 cx.dispatch_action(workspace::CloseActiveItem { save_intent: None });
1749
1750 history_items
1751 }
1752
1753 fn init_test(cx: &mut TestAppContext) -> Arc<AppState> {
1754 cx.update(|cx| {
1755 let state = AppState::test(cx);
1756 theme::init(theme::LoadThemes::JustBase, cx);
1757 language::init(cx);
1758 super::init(cx);
1759 editor::init(cx);
1760 workspace::init_settings(cx);
1761 Project::init_settings(cx);
1762 state
1763 })
1764 }
1765
1766 fn test_path_like(test_str: &str) -> PathLikeWithPosition<FileSearchQuery> {
1767 PathLikeWithPosition::parse_str(test_str, |path_like_str| {
1768 Ok::<_, std::convert::Infallible>(FileSearchQuery {
1769 raw_query: test_str.to_owned(),
1770 file_query_end: if path_like_str == test_str {
1771 None
1772 } else {
1773 Some(path_like_str.len())
1774 },
1775 })
1776 })
1777 .unwrap()
1778 }
1779
1780 fn build_find_picker(
1781 project: Model<Project>,
1782 cx: &mut TestAppContext,
1783 ) -> (
1784 View<Picker<FileFinderDelegate>>,
1785 View<Workspace>,
1786 &mut VisualTestContext,
1787 ) {
1788 let (workspace, cx) = cx.add_window_view(|cx| Workspace::test_new(project, cx));
1789 let picker = open_file_picker(&workspace, cx);
1790 (picker, workspace, cx)
1791 }
1792
1793 #[track_caller]
1794 fn open_file_picker(
1795 workspace: &View<Workspace>,
1796 cx: &mut VisualTestContext,
1797 ) -> View<Picker<FileFinderDelegate>> {
1798 cx.dispatch_action(Toggle);
1799 active_file_picker(workspace, cx)
1800 }
1801
1802 #[track_caller]
1803 fn active_file_picker(
1804 workspace: &View<Workspace>,
1805 cx: &mut VisualTestContext,
1806 ) -> View<Picker<FileFinderDelegate>> {
1807 workspace.update(cx, |workspace, cx| {
1808 workspace
1809 .active_modal::<FileFinder>(cx)
1810 .unwrap()
1811 .read(cx)
1812 .picker
1813 .clone()
1814 })
1815 }
1816}