file_finder_tests.rs

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