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