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