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